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
use breezyshim::branch::Branch;
use breezyshim::dirty_tracker::DirtyTracker;
use breezyshim::error::Error;
use breezyshim::tree::{MutableTree, Tree, TreeChange, WorkingTree};
use breezyshim::workspace::reset_tree;
use debian_changelog::ChangeLog;
use pyo3::prelude::*;
#[cfg(feature = "python")]
use std::str::FromStr;

pub mod changelog;
pub mod config;
pub mod debmutateshim;
pub mod detect_gbp_dch;
pub mod patches;
pub mod publish;
pub mod release_info;
pub mod salsa;
pub mod svp;
pub mod vcs;

// TODO(jelmer): Import this from ognibuild
pub const DEFAULT_BUILDER: &str = "sbuild --no-clean-source";

#[derive(Debug)]
pub enum ApplyError<R, E> {
    /// Error from the callback
    CallbackError(E),
    /// Error from the tree
    BrzError(Error),
    /// No changes made
    NoChanges(R),
}

impl<R, E> From<Error> for ApplyError<R, E> {
    fn from(e: Error) -> Self {
        ApplyError::BrzError(e)
    }
}

/// Apply a change in a clean tree.
///
/// This will either run a callback in a tree, or if the callback fails,
/// revert the tree to the original state.
///
/// The original tree should be clean; you can run check_clean_tree() to
/// verify this.
///
/// # Arguments
/// * `local_tree` - Local tree
/// * `subpath` - Subpath to apply changes to
/// * `basis_tree` - Basis tree to reset to
/// * `dirty_tracker` - Dirty tracker
/// * `applier` - Callback to apply changes
///
/// # Returns
/// * `Result<(R, Vec<TreeChange>, Option<Vec<std::path::PathBuf>>), E>` - Result of the callback,
///   the changes made, and the files that were changed
pub fn apply_or_revert<R, E>(
    local_tree: &WorkingTree,
    subpath: &std::path::Path,
    basis_tree: &dyn Tree,
    dirty_tracker: Option<&DirtyTracker>,
    applier: impl FnOnce(&std::path::Path) -> Result<R, E>,
) -> Result<(R, Vec<TreeChange>, Option<Vec<std::path::PathBuf>>), ApplyError<R, E>> {
    let r = match applier(local_tree.abspath(subpath).unwrap().as_path()) {
        Ok(r) => r,
        Err(e) => {
            reset_tree(local_tree, Some(basis_tree), Some(subpath), dirty_tracker).unwrap();
            return Err(ApplyError::CallbackError(e));
        }
    };

    let specific_files = if let Some(dirty_tracker) = dirty_tracker {
        let mut relpaths: Vec<_> = dirty_tracker.relpaths().into_iter().collect();
        relpaths.sort();
        // Sort paths so that directories get added before the files they
        // contain (on VCSes where it matters)
        local_tree.add(
            relpaths
                .iter()
                .filter_map(|p| {
                    if local_tree.has_filename(p) && local_tree.is_ignored(p).is_some() {
                        Some(p.as_path())
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>()
                .as_slice(),
        )?;
        let specific_files = relpaths
            .into_iter()
            .filter(|p| local_tree.is_versioned(p))
            .collect::<Vec<_>>();
        if specific_files.is_empty() {
            return Err(ApplyError::NoChanges(r));
        }
        Some(specific_files)
    } else {
        local_tree.smart_add(&[local_tree.abspath(subpath).unwrap().as_path()])?;
        if subpath.as_os_str().is_empty() {
            None
        } else {
            Some(vec![subpath.to_path_buf()])
        }
    };

    if local_tree.supports_setting_file_ids() {
        breezyshim::rename_map::guess_renames(basis_tree, local_tree).unwrap();
    }

    let specific_files_ref = specific_files
        .as_ref()
        .map(|fs| fs.iter().map(|p| p.as_path()).collect::<Vec<_>>());

    let changes = local_tree
        .iter_changes(
            basis_tree,
            specific_files_ref.as_deref(),
            Some(false),
            Some(true),
        )?
        .collect::<Result<Vec<_>, _>>()?;

    if local_tree.get_parent_ids()?.len() <= 1 && changes.is_empty() {
        return Err(ApplyError::NoChanges(r));
    }

    Ok((r, changes, specific_files))
}

pub enum ChangelogError {
    NotDebianPackage(std::path::PathBuf),
    Python(pyo3::PyErr),
}

impl std::fmt::Display for ChangelogError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ChangelogError::NotDebianPackage(path) => {
                write!(f, "Not a Debian package: {}", path.display())
            }
            ChangelogError::Python(e) => write!(f, "{}", e),
        }
    }
}

#[cfg(feature = "python")]
impl From<pyo3::PyErr> for ChangelogError {
    fn from(e: pyo3::PyErr) -> Self {
        use pyo3::import_exception;

        import_exception!(breezy.transport, NoSuchFile);

        pyo3::Python::with_gil(|py| {
            if e.is_instance_of::<NoSuchFile>(py) {
                return ChangelogError::NotDebianPackage(
                    e.into_value(py)
                        .bind(py)
                        .getattr("path")
                        .unwrap()
                        .extract()
                        .unwrap(),
                );
            } else {
                ChangelogError::Python(e)
            }
        })
    }
}

pub fn add_changelog_entry(
    working_tree: &WorkingTree,
    changelog_path: &std::path::Path,
    entry: &[&str],
) -> Result<(), ChangelogError> {
    let f = match working_tree.get_file(changelog_path) {
        Ok(f) => f,
        Err(Error::NoSuchFile(_)) => {
            return Err(ChangelogError::NotDebianPackage(
                working_tree.abspath(changelog_path).unwrap(),
            ))
        }
        Err(e) => panic!("Unexpected error: {}", e),
    };
    let mut cl = ChangeLog::read(f).unwrap();

    cl.auto_add_change(
        entry,
        debian_changelog::get_maintainer().unwrap(),
        None,
        None,
    );

    working_tree
        .put_file_bytes_non_atomic(changelog_path, cl.to_string().as_bytes())
        .unwrap();

    Ok(())
}

#[derive(
    Clone,
    Copy,
    PartialEq,
    Eq,
    Debug,
    Default,
    PartialOrd,
    Ord,
    serde::Serialize,
    serde::Deserialize,
)]
pub enum Certainty {
    #[serde(rename = "possible")]
    Possible,
    #[serde(rename = "likely")]
    Likely,
    #[serde(rename = "confident")]
    Confident,
    #[default]
    #[serde(rename = "certain")]
    Certain,
}

impl std::str::FromStr for Certainty {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "certain" => Ok(Certainty::Certain),
            "confident" => Ok(Certainty::Confident),
            "likely" => Ok(Certainty::Likely),
            "possible" => Ok(Certainty::Possible),
            _ => Err(format!("Invalid certainty: {}", value)),
        }
    }
}

impl std::fmt::Display for Certainty {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Certainty::Certain => write!(f, "certain"),
            Certainty::Confident => write!(f, "confident"),
            Certainty::Likely => write!(f, "likely"),
            Certainty::Possible => write!(f, "possible"),
        }
    }
}

#[cfg(feature = "python")]
impl pyo3::FromPyObject<'_> for Certainty {
    fn extract_bound(ob: &pyo3::Bound<pyo3::PyAny>) -> pyo3::PyResult<Self> {
        let s = ob.extract::<String>()?;
        Certainty::from_str(&s).map_err(pyo3::exceptions::PyValueError::new_err)
    }
}

#[cfg(feature = "python")]
impl pyo3::ToPyObject for Certainty {
    fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject {
        self.to_string().to_object(py)
    }
}

/// Check if the actual certainty is sufficient.
///
/// # Arguments
///
/// * `actual_certainty` - Actual certainty with which changes were made
/// * `minimum_certainty` - Minimum certainty to keep changes
///
/// # Returns
///
/// * `bool` - Whether the actual certainty is sufficient
pub fn certainty_sufficient(
    actual_certainty: Certainty,
    minimum_certainty: Option<Certainty>,
) -> bool {
    if let Some(minimum_certainty) = minimum_certainty {
        actual_certainty >= minimum_certainty
    } else {
        true
    }
}

/// Return the minimum certainty from a list of certainties.
pub fn min_certainty(certainties: &[Certainty]) -> Option<Certainty> {
    certainties.iter().min().cloned()
}

/// Get the committer string for a tree
pub fn get_committer(working_tree: &WorkingTree) -> String {
    pyo3::prepare_freethreaded_python();
    pyo3::Python::with_gil(|py| {
        let m = py.import_bound("lintian_brush")?;
        let get_committer = m.getattr("get_committer")?;
        get_committer.call1((&working_tree.0,))?.extract()
    })
    .unwrap()
}

/// Check whether there are any control files present in a tree.
///
/// # Arguments
///
///   * `tree`: tree to check
///   * `subpath`: subpath to check
///
/// # Returns
///
/// whether control file is present
pub fn control_file_present(tree: &dyn Tree, subpath: &std::path::Path) -> bool {
    for name in [
        "debian/control",
        "debian/control.in",
        "control",
        "control.in",
        "debian/debcargo.toml",
    ] {
        let name = subpath.join(name);
        if tree.has_filename(name.as_path()) {
            return true;
        }
    }
    false
}

pub fn is_debcargo_package(tree: &dyn Tree, subpath: &std::path::Path) -> bool {
    tree.has_filename(subpath.join("debian/debcargo.toml").as_path())
}

pub fn control_files_in_root(tree: &dyn Tree, subpath: &std::path::Path) -> bool {
    let debian_path = subpath.join("debian");
    if tree.has_filename(debian_path.as_path()) {
        return false;
    }

    let control_path = subpath.join("control");
    if tree.has_filename(control_path.as_path()) {
        return true;
    }

    tree.has_filename(subpath.join("control.in").as_path())
}

pub fn branch_vcs_type(branch: &dyn Branch) -> String {
    pyo3::prepare_freethreaded_python();
    pyo3::Python::with_gil(|py| {
        let repo = branch.to_object(py).getattr(py, "repository").unwrap();
        if repo.bind(py).hasattr("_git").unwrap() {
            Ok::<String, pyo3::PyErr>("git".to_string())
        } else {
            Ok::<String, pyo3::PyErr>("bzr".to_string())
        }
    })
    .unwrap()
}

pub fn parseaddr(input: &str) -> Option<(Option<String>, Option<String>)> {
    if let Some((_whole, name, addr)) =
        lazy_regex::regex_captures!(r"(?:(?P<name>[^<]*)\s*<)?(?P<addr>[^<>]*)>?", input)
    {
        let name = Some(name.trim().to_string());
        let addr = Some(addr.trim().to_string());

        return Some((name, addr));
    } else if let Some((_whole, addr)) = lazy_regex::regex_captures!(r"(?P<addr>[^<>]*)", input) {
        let addr = Some(addr.trim().to_string());

        return Some((None, addr));
    } else if input.is_empty() {
        return None;
    } else if !input.contains('<') {
        return Some((None, Some(input.to_string())));
    }
    None
}

pub fn gbp_dch(path: &std::path::Path) -> Result<(), std::io::Error> {
    let mut cmd = std::process::Command::new("gbp");
    cmd.arg("dch").arg("--ignore-branch");
    cmd.current_dir(path);
    let status = cmd.status()?;
    if !status.success() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::Other,
            format!("gbp dch failed: {}", status),
        ));
    }
    Ok(())
}