debian_analyzer/
changelog.rs

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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Functions for working with debian/changelog files.
use crate::release_info;
use breezyshim::error::Error;
use breezyshim::tree::{Tree, TreeChange, WorkingTree};
use debian_changelog::ChangeLog;

/// Check whether the only change in a tree is to the last changelog entry.
///
/// # Arguments
/// * `tree`: Tree to analyze
/// * `changelog_path`: Path to the changelog file
/// * `changes`: Changes in the tree
pub fn only_changes_last_changelog_block<'a>(
    tree: &WorkingTree,
    basis_tree: &dyn Tree,
    changelog_path: &std::path::Path,
    changes: impl Iterator<Item = &'a TreeChange>,
) -> Result<bool, debian_changelog::Error> {
    let read_lock = tree.lock_read();
    let basis_lock = basis_tree.lock_read();
    let mut changes_seen = false;
    for change in changes {
        if let Some(path) = change.path.1.as_ref() {
            if path == std::path::Path::new("") {
                continue;
            }
            if path == changelog_path {
                changes_seen = true;
                continue;
            }
            if !tree.has_versioned_directories() && changelog_path.starts_with(path) {
                // Directory leading up to changelog
                continue;
            }
        }
        // If the change is not in the changelog, it's not just a changelog change
        return Ok(false);
    }

    if !changes_seen {
        // Doesn't change the changelog at all
        return Ok(false);
    }
    let mut new_cl = match tree.get_file(changelog_path) {
        Ok(f) => ChangeLog::read(f)?,
        Err(Error::NoSuchFile(_)) => {
            return Ok(false);
        }
        Err(e) => {
            panic!("Error reading changelog: {}", e);
        }
    };
    let mut old_cl = match basis_tree.get_file(changelog_path) {
        Ok(f) => ChangeLog::read(f)?,
        Err(Error::NoSuchFile(_)) => {
            return Ok(true);
        }
        Err(e) => {
            panic!("Error reading changelog: {}", e);
        }
    };
    let first_entry = if let Some(e) = new_cl.pop_first() {
        e
    } else {
        // No entries
        return Ok(false);
    };
    if first_entry.distributions().as_deref() != Some(&["UNRELEASED".into()]) {
        // Not unreleased
        return Ok(false);
    }
    old_cl.pop_first();
    std::mem::drop(read_lock);
    std::mem::drop(basis_lock);
    Ok(new_cl.to_string() == old_cl.to_string())
}

/// Find the last distribution the package was uploaded to.
pub fn find_last_distribution(cl: &ChangeLog) -> Option<String> {
    for block in cl.iter() {
        if block.is_unreleased() != Some(true) {
            if let Some(distributions) = block.distributions() {
                if distributions.len() == 1 {
                    return Some(distributions[0].clone());
                }
            }
        }
    }
    None
}

/// Given a tree, find the previous upload to the distribution.
///
/// When e.g. Ubuntu merges from Debian they want to build with
/// -vPREV_VERSION. Here's where we find that previous version.
///
/// We look at the last changelog entry and find the upload target.
/// We then search backwards until we find the same target. That's
/// the previous version that we return.
///
/// We require there to be a previous version, otherwise we throw
/// an error.
///
/// It's not a simple string comparison to find the same target in
/// a previous version, as we should consider old series in e.g.
/// Ubuntu.
pub fn find_previous_upload(changelog: &ChangeLog) -> Option<debversion::Version> {
    let current_target = find_last_distribution(changelog)?;
    // multiple debian pockets with all debian releases
    let all_debian = crate::release_info::debian_releases()
        .iter()
        .flat_map(|r| {
            release_info::DEBIAN_POCKETS
                .iter()
                .map(move |t| format!("{}{}", r, t))
        })
        .collect::<Vec<_>>();
    let all_ubuntu = crate::release_info::ubuntu_releases()
        .iter()
        .flat_map(|r| {
            release_info::UBUNTU_POCKETS
                .iter()
                .map(move |t| format!("{}{}", r, t))
        })
        .collect::<Vec<_>>();
    let match_targets = if all_debian.contains(&current_target) {
        vec![current_target]
    } else if all_ubuntu.contains(&current_target) {
        let mut match_targets = crate::release_info::ubuntu_releases();
        if current_target.contains('-') {
            let distro = current_target.split('-').next().unwrap();
            match_targets.extend(
                release_info::DEBIAN_POCKETS
                    .iter()
                    .map(|r| format!("{}{}", r, distro)),
            );
        }
        match_targets
    } else {
        // If we do not recognize the current target in order to apply special
        // rules to it, then just assume that only previous uploads to exactly
        // the same target count.
        vec![current_target]
    };
    for block in changelog.iter().skip(1) {
        if match_targets.contains(&block.distributions().unwrap()[0]) {
            return block.version().clone();
        }
    }

    None
}

#[derive(Debug)]
/// Error type for find_changelog
pub enum FindChangelogError {
    /// No changelog found in the given files
    MissingChangelog(Vec<std::path::PathBuf>),

    /// Add a changelog at the given file
    AddChangelog(std::path::PathBuf),

    /// Error parsing the changelog
    ChangelogParseError(String),

    /// Error from breezyshim
    BrzError(breezyshim::error::Error),
}

impl std::fmt::Display for FindChangelogError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            FindChangelogError::MissingChangelog(files) => {
                write!(f, "No changelog found in {:?}", files)
            }
            FindChangelogError::AddChangelog(file) => {
                write!(f, "Add a changelog at {:?}", file)
            }
            FindChangelogError::ChangelogParseError(e) => write!(f, "{}", e),
            FindChangelogError::BrzError(e) => write!(f, "{}", e),
        }
    }
}

impl std::error::Error for FindChangelogError {}

impl From<breezyshim::error::Error> for FindChangelogError {
    fn from(e: breezyshim::error::Error) -> Self {
        FindChangelogError::BrzError(e)
    }
}

/// Find the changelog in the given tree.
///
/// First looks for 'debian/changelog'. If "merge" is true will also
/// look for 'changelog'.
///
/// The returned changelog is created with 'allow_empty_author=True'
/// as some people do this but still want to build.
/// 'max_blocks' defaults to 1 to try and prevent old broken
/// changelog entries from causing the command to fail.
///
/// "top_level" is a subset of "merge" mode. It indicates that the
/// '.bzr' dir is at the same level as 'changelog' etc., rather
/// than being at the same level as 'debian/'.
///
/// # Arguments
/// * `tree`: Tree to look in
/// * `subpath`: Path to the changelog file
/// * `merge`: Whether this is a "merge" package
///
/// # Returns
/// * (changelog, top_level) where changelog is the Changelog,
///   and top_level is a boolean indicating whether the file is
///   located at 'changelog' (rather than 'debian/changelog') if
///   merge was given, False otherwise.
pub fn find_changelog(
    tree: &dyn Tree,
    subpath: &std::path::Path,
    merge: Option<bool>,
) -> Result<(ChangeLog, bool), FindChangelogError> {
    let mut top_level = false;
    let lock = tree.lock_read();

    let mut changelog_file = subpath.join("debian/changelog");
    if !tree.has_filename(&changelog_file) {
        let mut checked_files = vec![changelog_file.clone()];
        let changelog_file = if merge.unwrap_or(false) {
            // Assume LarstiQ's layout (.bzr in debian/)
            let changelog_file = subpath.join("changelog");
            top_level = true;
            if !tree.has_filename(&changelog_file) {
                checked_files.push(changelog_file);
                None
            } else {
                Some(changelog_file)
            }
        } else {
            None
        };
        if changelog_file.is_none() {
            return Err(FindChangelogError::MissingChangelog(checked_files));
        }
    } else if merge.unwrap_or(true) && tree.has_filename(&subpath.join("changelog")) {
        // If it is a "top_level" package and debian is a symlink to
        // "." then it will have found debian/changelog. Try and detect
        // this.
        let debian_file = subpath.join("debian");
        if tree.is_versioned(&debian_file)
            && tree.kind(&debian_file)? == breezyshim::tree::Kind::Symlink
            && tree.get_symlink_target(&debian_file)?.as_path() == std::path::Path::new(".")
        {
            changelog_file = "changelog".into();
            top_level = true;
        }
    }
    log::debug!(
        "Using '{}' to get package information",
        changelog_file.display()
    );
    if !tree.is_versioned(&changelog_file) {
        return Err(FindChangelogError::AddChangelog(changelog_file));
    }
    let contents = tree.get_file_text(&changelog_file)?;
    std::mem::drop(lock);
    let changelog = ChangeLog::read_relaxed(contents.as_slice()).unwrap();
    Ok((changelog, top_level))
}

#[cfg(test)]
mod tests {
    use super::*;
    pub const COMMITTER: &str = "Test User <example@example.com>";
    #[test]
    fn test_find_previous_upload() {
        let cl = r#"test (1.0-1) unstable; urgency=medium

  * Initial release.

 -- Test User <test@user.example.com>  Fri, 01 Jan 2021 00:00:00 +0000
"#
        .parse()
        .unwrap();
        assert_eq!(super::find_previous_upload(&cl), None);

        let cl = r#"test (1.0-1) unstable; urgency=medium

  * More change.

 -- Test User <test@user.example.com>  Fri, 01 Jan 2021 00:00:00 +0000

test (1.0-0) unstable; urgency=medium

  * Initial release.

 -- Test User <test@example.com>  Fri, 01 Jan 2021 00:00:00 +0000
"#
        .parse()
        .unwrap();
        assert_eq!(
            super::find_previous_upload(&cl),
            Some("1.0-0".parse().unwrap())
        );
    }

    mod test_only_changes_last_changelog_block {
        use super::*;
        use breezyshim::controldir::{create_standalone_workingtree, ControlDirFormat};
        use breezyshim::tree::Path;
        use breezyshim::tree::Tree;
        fn make_package_tree(p: &std::path::Path) -> breezyshim::tree::WorkingTree {
            let tree = create_standalone_workingtree(p, &ControlDirFormat::default()).unwrap();
            std::fs::create_dir_all(p.join("debian")).unwrap();

            std::fs::write(
                p.join("debian/control"),
                r###"Source: blah
Vcs-Git: https://example.com/blah
Testsuite: autopkgtest

Binary: blah
Arch: all

"###,
            )
            .unwrap();
            std::fs::write(
                p.join("debian/changelog"),
                r###"blah (0.2) UNRELEASED; urgency=medium

  * And a change.

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100

blah (0.1) unstable; urgency=medium

  * Initial release. (Closes: #911016)

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            tree.add(&[
                Path::new("debian"),
                Path::new("debian/changelog"),
                Path::new("debian/control"),
            ])
            .unwrap();
            tree.build_commit()
                .message("Initial thingy.")
                .committer(COMMITTER)
                .commit()
                .unwrap();
            tree
        }

        #[test]
        fn test_no_changes() {
            let td = tempfile::tempdir().unwrap();
            let tree = make_package_tree(td.path());
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            assert!(!only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
        }

        #[test]
        fn test_other_change() {
            let td = tempfile::tempdir().unwrap();
            let tree = make_package_tree(td.path());
            std::fs::write(
                td.path().join("debian/control"),
                r###"Source: blah
Vcs-Bzr: https://example.com/blah
Testsuite: autopkgtest

Binary: blah
Arch: all
"###,
            )
            .unwrap();
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            assert!(!only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
        }

        #[test]
        fn test_other_changes() {
            let td = tempfile::tempdir().unwrap();
            let tree = make_package_tree(td.path());
            std::fs::write(
                td.path().join("debian/control"),
                r###"Source: blah
Vcs-Bzr: https://example.com/blah
Testsuite: autopkgtest

Binary: blah
Arch: all

"###,
            )
            .unwrap();
            std::fs::write(
                td.path().join("debian/changelog"),
                r###"blah (0.1) UNRELEASED; urgency=medium

  * Initial release. (Closes: #911016)
  * Some other change.

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            assert!(!only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
        }

        #[test]
        fn test_changes_to_other_changelog_entries() {
            let td = tempfile::tempdir().unwrap();
            let tree = make_package_tree(td.path());
            std::fs::write(
                td.path().join("debian/changelog"),
                r###"blah (0.2) UNRELEASED; urgency=medium

  * debian/changelog: And a change.

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100

blah (0.1) unstable; urgency=medium

  * debian/changelog: Initial release. (Closes: #911016)

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            assert!(!only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
        }

        #[test]
        fn test_changes_to_last_only() {
            let td = tempfile::tempdir().unwrap();
            let tree = make_package_tree(td.path());
            std::fs::write(
                td.path().join("debian/changelog"),
                r###"blah (0.2) UNRELEASED; urgency=medium

  * And a change.
  * Not a team upload.

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100

blah (0.1) unstable; urgency=medium

  * Initial release. (Closes: #911016)

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            assert!(only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
        }

        #[test]
        fn test_only_new_changelog() {
            use breezyshim::tree::MutableTree;
            let td = tempfile::tempdir().unwrap();
            let tree = create_standalone_workingtree(td.path(), "git").unwrap();
            let lock_write = tree.lock_write();
            std::fs::create_dir_all(td.path().join("debian")).unwrap();
            std::fs::write(
                td.path().join("debian/changelog"),
                r###"blah (0.1) unstable; urgency=medium

  * Initial release. (Closes: #911016)

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            tree.add(&[Path::new("debian"), Path::new("debian/changelog")])
                .unwrap();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            assert!(only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
            std::mem::drop(lock_write);
        }

        #[test]
        fn test_changes_to_last_only_but_released() {
            let td = tempfile::tempdir().unwrap();
            let tree = make_package_tree(td.path());
            std::fs::write(
                td.path().join("debian/changelog"),
                r###"blah (0.2) unstable; urgency=medium

  * And a change.

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100

blah (0.1) unstable; urgency=medium

  * Initial release. (Closes: #911016)

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            tree.build_commit()
                .message("release")
                .committer(COMMITTER)
                .commit()
                .unwrap();
            std::fs::write(
                td.path().join("debian/changelog"),
                r###"blah (0.2) unstable; urgency=medium

  * And a change.
  * Team Upload.

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100

blah (0.1) unstable; urgency=medium

  * Initial release. (Closes: #911016)

 -- Blah <example@debian.org>  Sat, 13 Oct 2018 11:21:39 +0100
"###,
            )
            .unwrap();
            let basis_tree = tree.basis_tree().unwrap();
            let lock_read = tree.lock_read();
            let basis_lock_read = basis_tree.lock_read();
            let changes = tree
                .iter_changes(&basis_tree, None, None, None)
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();

            assert!(!only_changes_last_changelog_block(
                &tree,
                &tree.basis_tree().unwrap(),
                Path::new("debian/changelog"),
                changes.iter()
            )
            .unwrap());
            std::mem::drop(basis_lock_read);
            std::mem::drop(lock_read);
        }
    }
}