debian_analyzer/
lib.rs

1//! Library for manipulating Debian packages.
2#![deny(missing_docs)]
3use breezyshim::branch::Branch;
4use breezyshim::dirty_tracker::DirtyTreeTracker;
5use breezyshim::error::Error;
6#[cfg(feature = "python")]
7use breezyshim::repository::PyRepository;
8use breezyshim::tree::{PyTree, Tree, TreeChange, WorkingTree};
9use breezyshim::workingtree::PyWorkingTree;
10use breezyshim::workspace::reset_tree_with_dirty_tracker;
11#[cfg(feature = "python")]
12use pyo3::prelude::*;
13
14pub mod abstract_control;
15pub mod benfile;
16pub mod changelog;
17pub mod config;
18pub mod control;
19pub mod debcargo;
20pub mod debcommit;
21pub mod debhelper;
22pub mod detect_gbp_dch;
23pub mod editor;
24pub mod lintian;
25pub mod maintscripts;
26pub mod patches;
27pub mod publish;
28pub mod relations;
29pub mod release_info;
30pub mod rules;
31pub mod salsa;
32pub mod snapshot;
33pub mod transition;
34#[cfg(feature = "udd")]
35pub mod udd;
36pub mod vcs;
37pub mod vendor;
38pub mod versions;
39#[cfg(feature = "udd")]
40pub mod wnpp;
41
42// TODO(jelmer): Import this from ognibuild
43/// Default builder
44pub const DEFAULT_BUILDER: &str = "sbuild --no-clean-source";
45
46#[derive(Debug)]
47/// Error applying a change
48pub enum ApplyError<R, E> {
49    /// Error from the callback
50    CallbackError(E),
51    /// Error from the tree
52    BrzError(Error),
53    /// No changes made
54    NoChanges(R),
55}
56
57impl<R, E> From<Error> for ApplyError<R, E> {
58    fn from(e: Error) -> Self {
59        ApplyError::BrzError(e)
60    }
61}
62
63/// Apply a change in a clean tree.
64///
65/// This will either run a callback in a tree, or if the callback fails,
66/// revert the tree to the original state.
67///
68/// The original tree should be clean; you can run check_clean_tree() to
69/// verify this.
70///
71/// # Arguments
72/// * `local_tree` - Local tree
73/// * `subpath` - Subpath to apply changes to
74/// * `basis_tree` - Basis tree to reset to
75/// * `dirty_tracker` - Dirty tracker
76/// * `applier` - Callback to apply changes
77///
78/// # Returns
79/// * `Result<(R, Vec<TreeChange>, Option<Vec<std::path::PathBuf>>), E>` - Result of the callback,
80///   the changes made, and the files that were changed
81pub fn apply_or_revert<R, E, T, U>(
82    local_tree: &T,
83    subpath: &std::path::Path,
84    basis_tree: &U,
85    dirty_tracker: Option<&mut DirtyTreeTracker>,
86    applier: impl FnOnce(&std::path::Path) -> Result<R, E>,
87) -> Result<(R, Vec<TreeChange>, Option<Vec<std::path::PathBuf>>), ApplyError<R, E>>
88where
89    T: PyWorkingTree + breezyshim::tree::PyMutableTree,
90    U: PyTree,
91{
92    let r = match applier(local_tree.abspath(subpath).unwrap().as_path()) {
93        Ok(r) => r,
94        Err(e) => {
95            reset_tree_with_dirty_tracker(
96                local_tree,
97                Some(basis_tree),
98                Some(subpath),
99                dirty_tracker,
100            )
101            .unwrap();
102            return Err(ApplyError::CallbackError(e));
103        }
104    };
105
106    let specific_files = if let Some(relpaths) = dirty_tracker.and_then(|x| x.relpaths()) {
107        let mut relpaths: Vec<_> = relpaths.into_iter().collect();
108        relpaths.sort();
109        // Sort paths so that directories get added before the files they
110        // contain (on VCSes where it matters)
111        local_tree.add(
112            relpaths
113                .iter()
114                .filter_map(|p| {
115                    if local_tree.has_filename(p) && local_tree.is_ignored(p).is_some() {
116                        Some(p.as_path())
117                    } else {
118                        None
119                    }
120                })
121                .collect::<Vec<_>>()
122                .as_slice(),
123        )?;
124        let specific_files = relpaths
125            .into_iter()
126            .filter(|p| local_tree.is_versioned(p))
127            .collect::<Vec<_>>();
128        if specific_files.is_empty() {
129            return Err(ApplyError::NoChanges(r));
130        }
131        Some(specific_files)
132    } else {
133        local_tree.smart_add(&[local_tree.abspath(subpath).unwrap().as_path()])?;
134        if subpath.as_os_str().is_empty() {
135            None
136        } else {
137            Some(vec![subpath.to_path_buf()])
138        }
139    };
140
141    if local_tree.supports_setting_file_ids() {
142        let local_lock = local_tree.lock_read().unwrap();
143        let basis_lock = basis_tree.lock_read().unwrap();
144        breezyshim::rename_map::guess_renames(basis_tree, local_tree).unwrap();
145        std::mem::drop(basis_lock);
146        std::mem::drop(local_lock);
147    }
148
149    let specific_files_ref = specific_files
150        .as_ref()
151        .map(|fs| fs.iter().map(|p| p.as_path()).collect::<Vec<_>>());
152
153    let changes = local_tree
154        .iter_changes(
155            basis_tree,
156            specific_files_ref.as_deref(),
157            Some(false),
158            Some(true),
159        )?
160        .collect::<Result<Vec<_>, _>>()?;
161
162    if local_tree.get_parent_ids()?.len() <= 1 && changes.is_empty() {
163        return Err(ApplyError::NoChanges(r));
164    }
165
166    Ok((r, changes, specific_files))
167}
168
169/// A changelog error
170pub enum ChangelogError {
171    /// Not a Debian package
172    NotDebianPackage(std::path::PathBuf),
173    #[cfg(feature = "python")]
174    /// Python error
175    Python(pyo3::PyErr),
176}
177
178impl std::fmt::Display for ChangelogError {
179    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
180        match self {
181            ChangelogError::NotDebianPackage(path) => {
182                write!(f, "Not a Debian package: {}", path.display())
183            }
184            #[cfg(feature = "python")]
185            ChangelogError::Python(e) => write!(f, "{}", e),
186        }
187    }
188}
189
190#[cfg(feature = "python")]
191// This is needed because import_exception! checks the gil-refs
192// feature which we don't provide.
193#[allow(unexpected_cfgs)]
194impl From<pyo3::PyErr> for ChangelogError {
195    fn from(e: pyo3::PyErr) -> Self {
196        use pyo3::import_exception;
197
198        import_exception!(breezy.transport, NoSuchFile);
199
200        pyo3::Python::attach(|py| {
201            if e.is_instance_of::<NoSuchFile>(py) {
202                return ChangelogError::NotDebianPackage(
203                    e.into_value(py)
204                        .bind(py)
205                        .getattr("path")
206                        .unwrap()
207                        .extract()
208                        .unwrap(),
209                );
210            } else {
211                ChangelogError::Python(e)
212            }
213        })
214    }
215}
216
217/// Add an entry to a changelog.
218///
219/// # Arguments
220/// * `working_tree` - Working tree
221/// * `changelog_path` - Path to the changelog
222/// * `entry` - Changelog entry
223pub fn add_changelog_entry<T: WorkingTree>(
224    working_tree: &T,
225    changelog_path: &std::path::Path,
226    entry: &[&str],
227) -> Result<(), crate::editor::EditorError> {
228    use crate::editor::{Editor, MutableTreeEdit};
229    let mut cl =
230        working_tree.edit_file::<debian_changelog::ChangeLog>(changelog_path, false, true)?;
231
232    cl.auto_add_change(
233        entry,
234        debian_changelog::get_maintainer().unwrap(),
235        None,
236        None,
237    );
238
239    cl.commit()?;
240
241    Ok(())
242}
243
244#[derive(
245    Clone,
246    Copy,
247    PartialEq,
248    Eq,
249    Debug,
250    Default,
251    PartialOrd,
252    Ord,
253    serde::Serialize,
254    serde::Deserialize,
255)]
256/// Certainty of a change.
257pub enum Certainty {
258    #[serde(rename = "possible")]
259    /// Possible change, basically a guess
260    Possible,
261    #[serde(rename = "likely")]
262    /// Likely to be correct, but not certain
263    Likely,
264    #[serde(rename = "confident")]
265    /// Confident change, but not absolutely certain
266    Confident,
267    #[default]
268    #[serde(rename = "certain")]
269    /// Absolutely certain change
270    Certain,
271}
272
273impl std::str::FromStr for Certainty {
274    type Err = String;
275
276    fn from_str(value: &str) -> Result<Self, Self::Err> {
277        match value {
278            "certain" => Ok(Certainty::Certain),
279            "confident" => Ok(Certainty::Confident),
280            "likely" => Ok(Certainty::Likely),
281            "possible" => Ok(Certainty::Possible),
282            _ => Err(format!("Invalid certainty: {}", value)),
283        }
284    }
285}
286
287impl std::fmt::Display for Certainty {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        match self {
290            Certainty::Certain => write!(f, "certain"),
291            Certainty::Confident => write!(f, "confident"),
292            Certainty::Likely => write!(f, "likely"),
293            Certainty::Possible => write!(f, "possible"),
294        }
295    }
296}
297
298#[cfg(feature = "python")]
299impl pyo3::FromPyObject<'_, '_> for Certainty {
300    type Error = pyo3::PyErr;
301
302    fn extract(ob: pyo3::Borrowed<'_, '_, pyo3::PyAny>) -> Result<Self, Self::Error> {
303        use std::str::FromStr;
304        let s = ob.extract::<String>()?;
305        Certainty::from_str(&s).map_err(pyo3::exceptions::PyValueError::new_err)
306    }
307}
308
309#[cfg(feature = "python")]
310impl<'py> pyo3::IntoPyObject<'py> for Certainty {
311    type Target = pyo3::types::PyString;
312
313    type Output = pyo3::Bound<'py, Self::Target>;
314
315    type Error = pyo3::PyErr;
316
317    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
318        let s = self.to_string();
319        Ok(pyo3::types::PyString::new(py, &s))
320    }
321}
322
323/// Check if the actual certainty is sufficient.
324///
325/// # Arguments
326///
327/// * `actual_certainty` - Actual certainty with which changes were made
328/// * `minimum_certainty` - Minimum certainty to keep changes
329///
330/// # Returns
331///
332/// * `bool` - Whether the actual certainty is sufficient
333pub fn certainty_sufficient(
334    actual_certainty: Certainty,
335    minimum_certainty: Option<Certainty>,
336) -> bool {
337    if let Some(minimum_certainty) = minimum_certainty {
338        actual_certainty >= minimum_certainty
339    } else {
340        true
341    }
342}
343
344/// Return the minimum certainty from a list of certainties.
345pub fn min_certainty(certainties: &[Certainty]) -> Option<Certainty> {
346    certainties.iter().min().cloned()
347}
348
349#[cfg(feature = "python")]
350fn get_git_committer(working_tree: &dyn PyWorkingTree) -> Option<String> {
351    pyo3::Python::attach(|py| {
352        let repo = working_tree.branch().repository();
353        let git = match repo.to_object(py).getattr(py, "_git") {
354            Ok(x) => Some(x),
355            Err(e) if e.is_instance_of::<pyo3::exceptions::PyAttributeError>(py) => None,
356            Err(e) => {
357                return Err(e);
358            }
359        };
360
361        if let Some(git) = git {
362            let cs = git.call_method0(py, "get_config_stack")?;
363
364            let mut user = std::env::var("GIT_COMMITTER_NAME").ok();
365            let mut email = std::env::var("GIT_COMMITTER_EMAIL").ok();
366            if user.is_none() {
367                match cs.call_method1(py, "get", (("user",), "name")) {
368                    Ok(x) => {
369                        user = Some(
370                            std::str::from_utf8(x.extract::<&[u8]>(py)?)
371                                .unwrap()
372                                .to_string(),
373                        );
374                    }
375                    Err(e) if e.is_instance_of::<pyo3::exceptions::PyKeyError>(py) => {
376                        // Ignore
377                    }
378                    Err(e) => {
379                        return Err(e);
380                    }
381                };
382            }
383            if email.is_none() {
384                match cs.call_method1(py, "get", (("user",), "email")) {
385                    Ok(x) => {
386                        email = Some(
387                            std::str::from_utf8(x.extract::<&[u8]>(py)?)
388                                .unwrap()
389                                .to_string(),
390                        );
391                    }
392                    Err(e) if e.is_instance_of::<pyo3::exceptions::PyKeyError>(py) => {
393                        // Ignore
394                    }
395                    Err(e) => {
396                        return Err(e);
397                    }
398                };
399            }
400
401            if let (Some(user), Some(email)) = (user, email) {
402                return Ok(Some(format!("{} <{}>", user, email)));
403            }
404
405            let gs = breezyshim::config::global_stack().unwrap();
406
407            Ok(gs
408                .get("email")?
409                .map(|email| email.extract::<String>(py).unwrap()))
410        } else {
411            Ok(None)
412        }
413    })
414    .unwrap()
415}
416
417/// Get the committer string for a tree
418pub fn get_committer(working_tree: &dyn PyWorkingTree) -> String {
419    #[cfg(feature = "python")]
420    if let Some(committer) = get_git_committer(working_tree) {
421        return committer;
422    }
423
424    let config = working_tree.branch().get_config_stack();
425
426    config
427        .get("email")
428        .unwrap()
429        .map(|x| x.to_string())
430        .unwrap_or_default()
431}
432
433/// Check whether there are any control files present in a tree.
434///
435/// # Arguments
436///
437///   * `tree`: tree to check
438///   * `subpath`: subpath to check
439///
440/// # Returns
441///
442/// whether control file is present
443pub fn control_file_present(tree: &dyn Tree, subpath: &std::path::Path) -> bool {
444    for name in [
445        "debian/control",
446        "debian/control.in",
447        "control",
448        "control.in",
449        "debian/debcargo.toml",
450    ] {
451        let name = subpath.join(name);
452        if tree.has_filename(name.as_path()) {
453            return true;
454        }
455    }
456    false
457}
458
459/// Check whether the package in a tree uses debcargo.
460pub fn is_debcargo_package(tree: &dyn Tree, subpath: &std::path::Path) -> bool {
461    tree.has_filename(subpath.join("debian/debcargo.toml").as_path())
462}
463
464/// Check whether the package in a tree has control files in the root, rather than in debian/.
465pub fn control_files_in_root(tree: &dyn Tree, subpath: &std::path::Path) -> bool {
466    let debian_path = subpath.join("debian");
467    if tree.has_filename(debian_path.as_path()) {
468        return false;
469    }
470
471    let control_path = subpath.join("control");
472    if tree.has_filename(control_path.as_path()) {
473        return true;
474    }
475
476    tree.has_filename(subpath.join("control.in").as_path())
477}
478
479/// Parse a Debian name and email address from a string.
480pub fn parseaddr(input: &str) -> Option<(Option<String>, Option<String>)> {
481    if let Some((_whole, name, addr)) =
482        lazy_regex::regex_captures!(r"(?:(?P<name>[^<]*)\s*<)?(?P<addr>[^<>]*)>?", input)
483    {
484        let name = match name.trim() {
485            "" => None,
486            x => Some(x.to_string()),
487        };
488        let addr = match addr.trim() {
489            "" => None,
490            x => Some(x.to_string()),
491        };
492
493        return Some((name, addr));
494    } else if let Some((_whole, addr)) = lazy_regex::regex_captures!(r"(?P<addr>[^<>]*)", input) {
495        let addr = Some(addr.trim().to_string());
496
497        return Some((None, addr));
498    } else if input.is_empty() {
499        return None;
500    } else if !input.contains('<') {
501        return Some((None, Some(input.to_string())));
502    }
503    None
504}
505
506/// Run gbp dch
507pub fn gbp_dch(path: &std::path::Path) -> Result<(), std::io::Error> {
508    let mut cmd = std::process::Command::new("gbp");
509    cmd.arg("dch").arg("--ignore-branch");
510    cmd.current_dir(path);
511    let status = cmd.status()?;
512    if !status.success() {
513        return Err(std::io::Error::new(
514            std::io::ErrorKind::Other,
515            format!("gbp dch failed: {}", status),
516        ));
517    }
518    Ok(())
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524    use serial_test::serial;
525
526    #[test]
527    fn test_parseaddr() {
528        assert_eq!(
529            parseaddr("foo <bar@example.com>").unwrap(),
530            (Some("foo".to_string()), Some("bar@example.com".to_string()))
531        );
532        assert_eq!(parseaddr("foo").unwrap(), (None, Some("foo".to_string())));
533    }
534
535    #[cfg(feature = "python")]
536    #[serial]
537    #[test]
538    fn test_git_env() {
539        let td = tempfile::tempdir().unwrap();
540        let cd = breezyshim::controldir::create_standalone_workingtree(td.path(), "git").unwrap();
541
542        let old_name = std::env::var("GIT_COMMITTER_NAME").ok();
543        let old_email = std::env::var("GIT_COMMITTER_EMAIL").ok();
544
545        std::env::set_var("GIT_COMMITTER_NAME", "Some Git Committer");
546        std::env::set_var("GIT_COMMITTER_EMAIL", "committer@example.com");
547
548        let committer = get_committer(&cd);
549
550        if let Some(old_name) = old_name {
551            std::env::set_var("GIT_COMMITTER_NAME", old_name);
552        } else {
553            std::env::remove_var("GIT_COMMITTER_NAME");
554        }
555
556        if let Some(old_email) = old_email {
557            std::env::set_var("GIT_COMMITTER_EMAIL", old_email);
558        } else {
559            std::env::remove_var("GIT_COMMITTER_EMAIL");
560        }
561
562        assert_eq!("Some Git Committer <committer@example.com>", committer);
563    }
564
565    #[serial]
566    #[test]
567    fn test_git_config() {
568        let td = tempfile::tempdir().unwrap();
569        let cd = breezyshim::controldir::create_standalone_workingtree(td.path(), "git").unwrap();
570
571        std::fs::write(
572            td.path().join(".git/config"),
573            b"[user]\nname = Some Git Committer\nemail = other@example.com",
574        )
575        .unwrap();
576
577        assert_eq!(get_committer(&cd), "Some Git Committer <other@example.com>");
578    }
579
580    #[test]
581    fn test_min_certainty() {
582        assert_eq!(None, min_certainty(&[]));
583        assert_eq!(
584            Some(Certainty::Certain),
585            min_certainty(&[Certainty::Certain])
586        );
587        assert_eq!(
588            Some(Certainty::Possible),
589            min_certainty(&[Certainty::Possible])
590        );
591        assert_eq!(
592            Some(Certainty::Possible),
593            min_certainty(&[Certainty::Possible, Certainty::Certain])
594        );
595        assert_eq!(
596            Some(Certainty::Likely),
597            min_certainty(&[Certainty::Likely, Certainty::Certain])
598        );
599        assert_eq!(
600            Some(Certainty::Possible),
601            min_certainty(&[Certainty::Likely, Certainty::Certain, Certainty::Possible])
602        );
603    }
604}