1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! # dpkg-query-json
//!
//!
//! A crate for parsing "dpkg-query" in json.
//!
//! # Examples
//!
//!
//! Minimum length of fields 2. Default fields `Package` `Version`. List available below.
//!
//! if the list of packages is empty, all are returned
//!
//!
//! #### Map<String, Value>
//! ```
//! use dpkg_query_json::QueryFieldPackage;
//! let fields = vec![String::from("Package"),
//! String::from("Version"),
//! String::from("Architecture")];
//! let packages = vec![String::from("dpkg")];
//! QueryFieldPackage::new(fields, packages).json(); //Map<String, Value>
//!
//! ```
//!
//!
//! ```{"dpkg": Object({"Architecture": String("amd64"), "Version": String("1.19.7ubuntu3")})}```
//!
//!
//!
//!------------------------------------
//!
//!
//!#### String
//! ```
//! use dpkg_query_json::QueryFieldPackage;
//! let fields = vec![String::from("Package"),
//! String::from("Version"),
//! String::from("Architecture")];
//! let packages = vec![String::from("dpkg")];
//! QueryFieldPackage::new(fields, packages).json_string(); //String
//!
//! ```
//!
//! ```"{\"dpkg\":{\"Architecture\":\"amd64\",\"Version\":\"1.19.7ubuntu3\"}}"```
//!


//! # Package information fields
//!
//! Architecture
//!
//! Bugs
//!
//! Conffiles
//!
//! Config-Version
//!
//! Conflicts
//!
//! Breaks
//!
//! Depends
//!
//! Description
//!
//! Enhances
//!
//! Essential
//!
//! Filename
//!
//! Installed-Size
//!
//! MD5sum
//!
//! MSDOS-Filename
//!
//! Maintainer
//!
//! Origin
//!
//! Package
//!
//! Pre-Depends
//!
//! Priority
//!
//! Provides
//!
//! Recommends
//!
//! Replaces
//!
//! Revision
//!
//! Section
//!
//! Size
//!
//! Source
//!
//! Status
//!
//! Suggests
//!
//! Version
//!


use std::process::{Command};
use std::io::{Error};
use serde_json::{Value, Map, json};

//#[derive(Debug)]
pub struct QueryFieldPackage{
    fields: Vec<String>,
    packages: Vec<String>
}

impl QueryFieldPackage{
    pub fn new(fields: Vec<String>, packages: Vec<String>) -> Self{
        QueryFieldPackage{
            fields,
            packages
        }
    }

    fn exec(&mut self) -> Result<String, Error> {

        if self.fields.len() <= 1{
            self.fields.clear();
            self.fields = vec![String::from("Package"), String::from("Version")];
        }

        let mut command = String::from("dpkg-query -W");
        if self.fields.len() > 0{
            let mut modified_fields = Vec::with_capacity(29);
            for str in self.fields.iter(){
                modified_fields.push("${".to_owned() + &str + "}");
            }
            command.push_str(&format!(" -f '{}\t\n'", modified_fields.join("<==>")))
        }

        if self.packages.len() > 0{
            command.push_str(&format!(" {}", self.packages.join(" ")))
        }

        match Command::new("sh")
            .args(&["-c", command.as_str()])
            .output(){
            Ok(data) => {Ok(String::from_utf8_lossy(&data.stdout).to_string())}
            Err(e) => Err(e)
        }

    }

    fn parse_to_json(&mut self) -> Result<Map<String, Value>, Error> {
        let mut data_json = Map::new();

        for line in self.exec()?.split("\t\n"){
            let mut d = Map::new();
            let split_line = line.split("<==>").collect::<Vec<&str>>();
            for (i,line) in split_line[1..].iter().enumerate(){
                d.insert((self.fields[i + 1]).to_string(), json!(line));
            }
            &data_json.insert(split_line[0].to_string(), Value::from(d));
        }

        Ok(data_json)
    }

    pub fn json(mut self) -> Map<String, Value> {
        self.parse_to_json().unwrap_or_else(|err|{
            let mut x = Map::new();
            x.insert(String::from("error"), Value::from(err.to_string()));
            x
        })
    }


    /// Adds one to the number given.
    ///
    /// # Examples
    ///
    /// ```
    /// let arg = 5;
    /// let answer = my_crate::add_one(arg);
    ///
    /// assert_eq!(6, answer);
    /// ```
    pub fn json_string(mut self) -> String {
        serde_json::to_string(&self.parse_to_json().unwrap_or_else(|err|{
            let mut x = Map::new();
            x.insert(String::from("error"), Value::from(err.to_string()));
            x
        })).unwrap()
    }

}