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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use std::fmt;
use std::env;

use std::fs::File;
use std::io;
use std::io::{Write, BufRead};
use std::path::Path;

use chrono::prelude::*;

use super::Version;

/// represents a single entry in a debian/changelog file
pub struct ChangelogEntry {
    /// source package name
    pkg: String,
    /// debian revision
    version: String,
    /// distribution(s) where this version should be installed when it
    /// is uploaded
    distributions: Vec<String>,
    // urgency of the upload
    urgency: String,
    // changelog description
    detail: String,
    // name of the uploader of the package
    maintainer_name: String,
    // email of the uploader of the package
	maintainer_email: String,
    // date of the upload
    ts: DateTime<Local>
}

/// simply a collection of `ChangeLogEntry`
pub struct Changelog {
    entries: Vec<ChangelogEntry>
}

impl ChangelogEntry {
    pub fn new(pkg: String, version: String, detail: String)
               -> ChangelogEntry {
        ChangelogEntry {
            pkg: pkg,
            version: version,
            distributions: vec!["UNRELEASED".to_string()],
            urgency: "medium".to_string(),
            detail: detail,
            maintainer_name: get_default_maintainer_name(),
			maintainer_email: get_default_maintainer_email(),
            ts: Local::now()
        }
    }

    fn serialize(&self) -> String {
        format!("{} ({}) {}; urgency={}\n\n{}\n -- {} <{}>  {}\n\n",
                self.pkg,
                self.version,
                self.distributions.join(" "),
                self.urgency,
                self.detail,
                self.maintainer_name,
				self.maintainer_email,
				self.ts.to_rfc2822()
                ).to_string()
    }
}

impl Changelog {
    pub fn new(single_entry: ChangelogEntry) -> Changelog {
        Changelog {
            entries: vec![single_entry]
        }
    }

    pub fn to_file(&self, out_file_path: &Path) -> io::Result<()> {
        let mut file = match File::create(out_file_path, ) {
            Ok(f) => f,
            Err(f) => return Err(f)
        };
        for entry in self.entries.iter() {
            match file.write(entry.serialize().as_bytes()) {
                Ok(_) => {},
                Err(f) => return Err(f)
            }
        }
        Ok(())
    }

    pub fn from_file(in_file: &Path) -> io::Result<Changelog> {
		let file = try!(File::open(in_file));
        let mut buf = io::BufReader::new(file);
        let entries = vec![];
        loop {
			let mut line = String::new();
			try!(buf.read_line(&mut line));
			let is_eof = line.len() == 0;

            // Loop termination condition
            if is_eof { break; }
        }

        Ok(Changelog { entries: entries })
    }
}

/// A helper routine to determine the default Debian maintainer name
/// from the environment.
pub fn get_default_maintainer_name() -> String {
    match env::var("DEBFULLNAME") {
        Ok(name) => name,
        Err(_) => match env::var("NAME") {
            Ok(name) => name,
            Err(_) => "Mickey Mouse".to_string()
        }
    }
}

/// A helper routine to determine the default Debian email address
/// from the environment.
pub fn get_default_maintainer_email() -> String {
    match env::var("DEBEMAIL") {
        Ok(email) => email,
        Err(_) => match env::var("EMAIL") {
            Ok(email) => email,
            Err(_) => "mmouse@disney.com".to_string()
        }
    }
}

#[derive(Debug, Clone)]
pub enum ControlValue {
    Simple(String),
    Folded(String),
    MultiLine(String)
}

/// A single field or entry in a control file
#[derive(Debug, Clone)]
pub struct ControlEntry {
    key: String,
    value: ControlValue
}

/// A paragraph consisting of multiple entries of type `ControlEntry`.
#[derive(Debug, Clone)]
pub struct ControlParagraph {
    entries: Vec<ControlEntry>
}

#[derive(Debug)]
pub struct ControlFile {
    paragraphs: Vec<ControlParagraph>
}

impl ControlValue {
    /// Creates a `ControlValue` from a `String` choosing its type
    /// from the key.
    pub fn new(key: &str, val: String) -> ControlValue {
        match key {
            // Fields appearing in both types of source paragraphs
            "Maintainer" => ControlValue::Simple(val),
            "Section" => ControlValue::Simple(val),
            "Priority" => ControlValue::Simple(val),

            "Pre-Depends" => ControlValue::Folded(val),
            "Depends" => ControlValue::Folded(val),
            "Build-Depends" => ControlValue::Folded(val),
            "Build-Depends-Indep" => ControlValue::Folded(val),

            "Homepage" => ControlValue::Simple(val),

            // Fields appearing in the general paragraph, only
            "Source" => ControlValue::Simple(val),
            "Uploaders" => ControlValue::Folded(val),
            "Standards-Version" => ControlValue::Simple(val),
            "Vcs-Browser" => ControlValue::Simple(val),
            "Vcs-Git" => ControlValue::Simple(val),
            "Recommends" => ControlValue::Folded(val),
            "Suggests" => ControlValue::Folded(val),
            "Breaks" => ControlValue::Folded(val),
            "Replaces" => ControlValue::Folded(val),

            // Fields appearing in binary paragraph, only
            "Package" => ControlValue::Simple(val),
            "Changed-By" => ControlValue::Simple(val),
            "Architecture" => ControlValue::Simple(val),
            "Essential" => ControlValue::Simple(val),
            "Description" => ControlValue::MultiLine(val),
            "Built-Using" => ControlValue::Simple(val),
            "Binaries" => ControlValue::Folded(val),
            "Package-Type" => ControlValue::Simple(val),
            "Dgit" => ControlValue::Folded(val),

            // Fields appearing in binary packages' control files
            "Version" => ControlValue::Simple(val),
            "Installed-Size" => ControlValue::Simple(val),

            _ => {
                debug!("Unknown key: {}", key);
                ControlValue::Simple(val)
            }
        }
    }
}

impl ControlEntry {
    pub fn new(key: &str, val: String) -> ControlEntry {
        ControlEntry {
            key: key.to_string(),
            value: ControlValue::new(key, val)
        }
    }
}

impl ControlParagraph {
    pub fn new() -> ControlParagraph {
        ControlParagraph {
            entries: vec![]
        }
    }

    /// Append an entry at the end of the paragraph.
    pub fn add_entry(&mut self, key: &str, val: String) {
        let e = ControlEntry::new(key, val);
        self.entries.push(e);
    }

    /// Update or append an entry in the paragraph, returning true if
    /// the entry was found and replaced, false if appended.
    pub fn update_entry(&mut self, key: &str, val: String) -> bool {
        for entry in self.entries.iter_mut() {
            if entry.key == key {
                entry.value = ControlValue::new(key, val);
                return true;
            }
        }

        // append entry
        self.add_entry(key, val);
        return false;
    }

    /// Check if an entry exists in the paragraph
    pub fn has_entry(&self, key: &str) -> bool {
        for entry in self.entries.iter() {
            if entry.key == key {
                return true;
            }
        }
        return false;
    }

    /// Get the value of an entry in the paragraph
    pub fn get_entry(&self, key: &str) -> Option<&str> {
        for entry in self.entries.iter() {
            if entry.key == key {
                return Some(match entry.value {
                    ControlValue::Simple(ref v) => &v,
                    ControlValue::Folded(ref v) => &v,
                    ControlValue::MultiLine(ref v) => &v
                });
            }
        }
        return None;
    }
}

impl ControlFile {
    pub fn new() -> ControlFile {
        ControlFile { paragraphs: vec![] }
    }

    pub fn add_paragraph(&mut self, p: ControlParagraph) {
        self.paragraphs.push(p);
    }

    pub fn from_file(in_file: &Path) -> io::Result<ControlFile> {
		let file = try!(File::open(in_file));
        let mut buf = io::BufReader::new(file);
        let mut paragraphs = Vec::new();
        let mut cur_entry: Option<String> = None;
        let mut cur_para = ControlParagraph::new();
        loop {
			let mut line = "".to_string();

			try!(buf.read_line(&mut line));
			let is_eof = line.len() == 0;

			let (is_end_of_para, is_indented) = {
				let trimmed_line = line.trim();
				(trimmed_line.len() == 0,
				 line.starts_with(" ") && line.len() > 1)
			};

            // Possibly terminate the current entry and append to the
            // current paragraph.
            cur_entry = match (cur_entry, is_indented, is_end_of_para) {
                (Some(v), false, _) => {
                    // terminate the last entry
                    let mut v2 = v.splitn(2, ':');
                    let key = v2.next().unwrap();
                    match v2.next() {
                        Some(value) => {
                            let value = value.trim().to_string();
                            cur_para.add_entry(key, value);
                        },
                        None => {
                            // FIXME: handle this parser error!
                            debug!("Parser error in line before: '{}', with value '{}'", line, v);
                        }
                    };

                    // begin new entry
                    if is_end_of_para { None } else { Some(line) }
                },
                (Some(v), true, false) => Some(v + &line),
                (None, _, false) => Some(line),
                (_, _, true) => None,
            };

            // Possibly terminate the current paragraph and append it
            // to the main structure.
            if is_end_of_para && cur_para.entries.len() > 0 {
                paragraphs.push(cur_para);
                cur_para = ControlParagraph::new();
            }

            // Loop termination condition
            if is_eof { break; }
        }

        Ok(ControlFile { paragraphs: paragraphs })
    }

    pub fn serialize(&self, out_file: &Path) -> io::Result<()> {
        let mut file = match File::create(out_file) {
            Ok(f) => f,
            Err(e) => return Err(e)
        };

        for para in self.paragraphs.iter() {
            for entry in para.entries.iter() {
                let v = match entry.value.clone() {
                    ControlValue::Simple(v) => v,
                    ControlValue::Folded(v) => v,
                    ControlValue::MultiLine(v) => v,
                };
                let s = entry.key.clone() + ": " + &v + "\n";
                try!(file.write(s.as_bytes()));
            }
            try!(file.write("\n".as_bytes()));
        }

        Ok(())
    }

    pub fn get_paragraphs(&self) -> &Vec<ControlParagraph> {
        &self.paragraphs
    }
}

/// Version relations
#[derive(Debug, PartialEq, Clone)]
pub enum VRel {
    GreaterOrEqual,
    Greater,
    LesserOrEqual,
    Lesser,
    Equal,
}

impl fmt::Display for VRel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &VRel::GreaterOrEqual => write!(f, ">="),
            &VRel::Greater => write!(f, ">>"),
            &VRel::LesserOrEqual => write!(f, "<="),
            &VRel::Lesser => write!(f, "<<"),
            &VRel::Equal => write!(f, "=")
        }
    }
}

/// A dependency on another package
#[derive(Debug, PartialEq, Clone)]
pub struct SingleDependency {
    pub package: String,
    pub version: Option<(VRel, Version)>,
    pub arch: Option<String>
}

impl fmt::Display for SingleDependency {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match (&self.version, &self.arch) {
            (&None, &None) => write!(f, "{}", self.package),
            (&Some((ref vrel, ref ver)), &None) =>
                write!(f, "{} ({} {})", self.package, vrel, ver),
            (&None, &Some(ref a)) => write!(f, "{} [{}]", self.package, a),
            (&Some((ref vrel, ref ver)), &Some(ref a)) =>
                write!(f, "{} ({} {}) [{}]", self.package,
                                        vrel, ver, a)
        }
    }
}

/// Multiple variants that may statisfy a dependency
#[derive(Debug, PartialEq, Clone)]
pub struct Dependency {
    pub alternatives: Vec<SingleDependency>
}

impl fmt::Display for Dependency {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let alts = self.alternatives.iter().map(|x| format!("{}", x))
            .collect::<Vec<String>>()
            .join(" | ");
        write!(f, "{}", alts)
    }
}


/// Parse a single dependency
fn parse_single_dep(s: &str) -> Result<SingleDependency, &'static str> {
    enum ST {
        PackageName,
        PreVersion,
        InVersionRel,
        InVersionDef,
        PreArch,
        InArch,
        Done
    }
    let mut st = ST::PackageName;
    let mut result = SingleDependency {
        package: "".to_string(),
        version: None,
        arch: None
    };
    let mut vrel = "".to_string();
    let mut vdef = "".to_string();
    let mut arch = "".to_string();
    for ch in s.chars() {
        match st {
            ST::PackageName => {
                if ch.is_whitespace() { st = ST::PreVersion; }
                else if ch == '(' { st = ST::InVersionRel; }
                else { result.package.push(ch); }
            },
            ST::PreVersion => {
                if ch.is_whitespace() { }
                else if ch == '(' { st = ST::InVersionRel; }
                else { return Err("garbage after package name"); }
            },
            ST::InVersionRel => {
                if ch == '>' || ch == '<' || ch == '=' { vrel.push(ch); }
                else if ch == ')' { return Err("no version given"); }
                else {
                    st = ST::InVersionDef;
                    vdef.push(ch);
                }
            },
            ST::InVersionDef => {
                if ch == ')' {
                    let version = match Version::parse(vdef.trim()) {
                        Ok(v) => v,
                        Err(_) => return Err("error parsing version")
                    };
                    result.version = match &vrel[..] {
                        ">=" | ">" => Some((VRel::GreaterOrEqual, version)),
                        ">>" => Some((VRel::Greater, version)),
                        "<=" | "<" => Some((VRel::LesserOrEqual, version)),
                        "<<" => Some((VRel::Lesser, version)),
                        "=" => Some((VRel::Equal, version)),
                        _ => return Err("invalid relation")
                    };
                    st = ST::PreArch;
                } else { vdef.push(ch); }
            },
            ST::PreArch => {
                if ch.is_whitespace() { }
                else if ch == '[' { st = ST::InArch; }
                else { return Err("garbage after version"); }
            },
            ST::InArch => {
                if ch == ']' {
                    let arch = arch.trim().to_string();
                    if arch.len() > 0 { result.arch = Some(arch); }
                    else { return Err("empty arch given"); }
                    st = ST::Done;
                }
                else { arch.push(ch); }
            },
            ST::Done => {
                if ch.is_whitespace() { }
                else { return Err("garbage after arch"); }
            }
        }
    }
    return Ok(result);
}

/// Parse a dependency list, comma separated, with pipes separating
/// variants
pub fn parse_dep_list(s: &str) -> Result<Vec<Dependency>, &'static str> {
    let mut result = vec![];
    for s in s.split(',').map(|x| x.trim()) {
        let mut a = vec![];
        for sd in s.split('|').map(|x| x.trim()) {
            a.push(match parse_single_dep(sd) {
                Ok(v) => v,
                Err(e) => return Err(e)
            });
        }
        result.push(Dependency { alternatives: a });
    }
    return Ok(result);
}