ognibuild 0.2.12

Detect and run any build system
Documentation
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
use crate::debian::apt::AptManager;
use crate::debian::context::{DebianPackagingContext, Error};
use crate::debian::fix_build::DebianBuildFixer;
use crate::dependencies::debian::{DebianDependency, TieBreaker};
use crate::session::Session;
use breezyshim::tree::Tree;
use breezyshim::workingtree::WorkingTree;
use buildlog_consultant::problems::common::NeedPgBuildExtUpdateControl;
use buildlog_consultant::sbuild::Phase;
use buildlog_consultant::Problem;
use debian_analyzer::editor::Editor;
use std::path::Path;

/// Extract targeted Python versions from a package's build dependencies.
///
/// This function parses the debian/control file to determine which Python
/// versions (python3, pypy, etc.) are targeted by the package's build dependencies.
///
/// # Arguments
/// * `tree` - The working tree containing the package
/// * `subpath` - Path to the package within the tree
///
/// # Returns
/// A list of Python version strings that the package targets
fn targeted_python_versions(tree: &dyn Tree, subpath: &Path) -> Vec<String> {
    let f = tree.get_file(&subpath.join("debian/control")).unwrap();
    let control = debian_control::Control::read(f).unwrap();
    let source = control.source().unwrap();
    let all = if let Some(build_depends) = source.build_depends() {
        build_depends
    } else {
        return vec![];
    };

    let targeted = vec![];
    for entry in all.entries() {
        for relation in entry.relations() {
            let mut targeted = vec![];
            if relation.name().starts_with("python3-") {
                targeted.push("python3".to_owned());
            }
            if relation.name().starts_with("pypy") {
                targeted.push("pypy".to_owned());
            }
            if relation.name().starts_with("python-") {
                targeted.push("python".to_owned());
            }
        }
    }
    targeted
}

/// Tie-breaker for Python dependencies based on targeted Python versions.
///
/// This tie-breaker helps select appropriate Python dependencies based on
/// the Python versions targeted by the package as specified in its build
/// dependencies.
pub struct PythonTieBreaker {
    /// List of targeted Python versions (e.g., "python3", "pypy")
    targeted: Vec<String>,
}

impl PythonTieBreaker {
    fn from_tree(tree: &dyn Tree, subpath: &Path) -> Self {
        let targeted = targeted_python_versions(tree, subpath);
        Self { targeted }
    }
}

impl TieBreaker for PythonTieBreaker {
    fn break_tie<'a>(&self, reqs: &[&'a DebianDependency]) -> Option<&'a DebianDependency> {
        if self.targeted.is_empty() {
            return None;
        }

        fn same(pkg: &str, python_version: &str) -> bool {
            if pkg.starts_with(&format!("{}-", python_version)) {
                return true;
            }
            if pkg.starts_with(&format!("lib{}-", python_version)) {
                return true;
            }
            pkg == format!("lib{}-dev", python_version)
        }

        for python_version in &self.targeted {
            for req in reqs {
                if req
                    .package_names()
                    .iter()
                    .any(|name| same(name, &python_version))
                {
                    log::info!(
                        "Breaking tie between {:?} to {:?}, since package already has {} build-dependencies",
                        reqs,
                        req,
                        python_version,
                    );
                    return Some(req);
                }
            }
        }

        None
    }
}

/// Handle APT fetch failures by simply retrying.
///
/// This fixer deals with transient APT fetch failures by indicating that
/// the build should be retried.
///
/// # Arguments
/// * `_error` - The APT fetch failure problem
/// * `_phase` - The build phase in which the error occurred
/// * `_context` - The Debian packaging context
///
/// # Returns
/// Always returns Ok(true) to indicate the build should be retried
fn retry_apt_failure(
    _error: &dyn Problem,
    _phase: &Phase,
    _context: &DebianPackagingContext,
) -> Result<bool, Error> {
    Ok(true)
}

/// Enable dh-autoreconf in debian/rules.
///
/// This function adds dh-autoreconf to debian/rules to handle autoconf-related
/// build issues.
///
/// # Arguments
/// * `context` - The Debian packaging context
/// * `phase` - The build phase in which autoreconf is needed
///
/// # Returns
/// Ok(true) if successful, Error otherwise
fn enable_dh_autoreconf(context: &DebianPackagingContext, phase: &Phase) -> Result<bool, Error> {
    // Debhelper >= 10 depends on dh-autoreconf and enables autoreconf by default.
    let debhelper_compat_version =
        debian_analyzer::debhelper::get_debhelper_compat_level(&context.abspath(Path::new(".")))
            .unwrap();

    if !debhelper_compat_version
        .map(|dcv| dcv < 10)
        .unwrap_or(false)
    {
        return Ok(false);
    }

    let mut modified = false;

    let rules = context.edit_rules()?;
    for mut rule in rules.rules_by_target("%") {
        for (i, line) in rule.recipes().enumerate() {
            if !line.starts_with("dh ") {
                continue;
            }
            let new_line = debian_analyzer::rules::dh_invoke_add_with(&line, "autoreconf");
            if line != new_line {
                rule.replace_command(i, &new_line);
                modified = true;
            }
        }
    }

    if modified {
        context.add_dependency(phase, &DebianDependency::simple("dh-autoreconf"))
    } else {
        Ok(false)
    }
}

fn fix_missing_configure(
    _error: &dyn Problem,
    phase: &Phase,
    context: &DebianPackagingContext,
) -> Result<bool, Error> {
    if !context.has_filename(Path::new("configure.ac"))
        && !context.has_filename(Path::new("configure.in"))
    {
        return Ok(false);
    }

    enable_dh_autoreconf(context, phase)
}

fn fix_missing_automake_input(
    _error: &dyn Problem,
    phase: &Phase,
    context: &DebianPackagingContext,
) -> Result<bool, Error> {
    // TODO(jelmer): If it's ./NEWS, ./AUTHORS or ./README that's missing, then
    // try to set 'export AUTOMAKE = automake --foreign' in debian/rules.
    // https://salsa.debian.org/jelmer/debian-janitor/issues/88
    enable_dh_autoreconf(context, phase)
}

fn fix_missing_config_status_input(
    _error: &dyn Problem,
    _phase: &Phase,
    context: &DebianPackagingContext,
) -> Result<bool, Error> {
    let autogen_path = "autogen.sh";
    if !context.has_filename(Path::new(autogen_path)) {
        return Ok(false);
    }

    let mut rules = context.edit_rules()?;

    let rule_exists = rules
        .rules_by_target("override_dh_autoreconf")
        .next()
        .is_some();
    if rule_exists {
        return Ok(false);
    }

    let mut rule = rules.add_rule("override_dh_autoreconf");
    rule.push_command("dh_autoreconf ./autogen.sh");

    rules.commit()?;

    context.commit("Run autogen.sh during build.", None)
}

/// Fixer that resolves missing package dependencies.
///
/// This fixer identifies missing dependencies in build errors and adds them
/// to the package's build dependencies in debian/control.
pub struct PackageDependencyFixer<'a, 'b, 'c>
where
    'c: 'a,
{
    /// APT package manager for dependency resolution
    apt: &'a AptManager<'c>,
    /// Debian packaging context for making changes to the package
    context: &'b DebianPackagingContext,
    /// List of tie-breakers for selecting between alternative dependencies
    tie_breakers: Vec<Box<dyn TieBreaker>>,
}

impl<'a, 'b, 'c> std::fmt::Display for PackageDependencyFixer<'a, 'b, 'c> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PackageDependencyFixer")
    }
}

impl<'a, 'b, 'c> std::fmt::Debug for PackageDependencyFixer<'a, 'b, 'c> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PackageDependencyFixer")
    }
}

impl<'a, 'b, 'c> DebianBuildFixer for PackageDependencyFixer<'a, 'b, 'c> {
    fn can_fix(&self, problem: &dyn Problem) -> bool {
        crate::buildlog::problem_to_dependency(problem).is_some()
    }

    fn fix(
        &self,
        problem: &dyn Problem,
        phase: &Phase,
    ) -> Result<bool, crate::fix_build::InterimError<Error>> {
        let dep = crate::buildlog::problem_to_dependency(problem).unwrap();

        let deb_dep = crate::debian::apt::dependency_to_deb_dependency(
            &self.apt,
            dep.as_ref(),
            self.tie_breakers.as_slice(),
        )
        .unwrap();

        let deb_dep = if let Some(deb_dep) = deb_dep {
            deb_dep
        } else {
            return Ok(false);
        };

        Ok(self.context.add_dependency(phase, &deb_dep).unwrap())
    }
}

/// Fixer that updates PostgreSQL build extension control files.
///
/// This fixer handles the case where pg_buildext detects that control files
/// are out of date and need to be updated.
pub struct PgBuildExtOutOfDateControlFixer<'a, 'b, 'c, 'd>
where
    'a: 'c,
{
    /// Session for executing commands
    session: &'a dyn Session,
    /// Debian packaging context for making changes to the package
    context: &'b DebianPackagingContext,
    /// APT package manager for dependency resolution
    apt: &'c AptManager<'d>,
}

impl<'a, 'b, 'c, 'd> std::fmt::Debug for PgBuildExtOutOfDateControlFixer<'a, 'b, 'c, 'd> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PgBuildExtOutOfDateControlFixer")
    }
}

impl<'a, 'b, 'c, 'd> std::fmt::Display for PgBuildExtOutOfDateControlFixer<'a, 'b, 'c, 'd> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PgBuildExtOutOfDateControlFixer")
    }
}

impl<'a, 'b, 'c, 'd> DebianBuildFixer for PgBuildExtOutOfDateControlFixer<'a, 'b, 'c, 'd> {
    fn can_fix(&self, problem: &dyn Problem) -> bool {
        problem
            .as_any()
            .downcast_ref::<NeedPgBuildExtUpdateControl>()
            .is_some()
    }

    fn fix(
        &self,
        error: &dyn Problem,
        _phase: &Phase,
    ) -> std::result::Result<bool, crate::fix_build::InterimError<crate::debian::context::Error>>
    {
        let error = error
            .as_any()
            .downcast_ref::<NeedPgBuildExtUpdateControl>()
            .unwrap();
        log::info!("Running 'pg_buildext updatecontrol'");
        self.apt
            .satisfy(vec![crate::debian::apt::SatisfyEntry::Required(
                "postgresql-common".to_string(),
            )])
            .unwrap();
        let project = self
            .session
            .project_from_directory(&self.context.tree.abspath(Path::new(".")).unwrap(), None)
            .unwrap();
        self.session
            .command(vec!["pg_buildext", "updatecontrol"])
            .cwd(&project.internal_path())
            .check_call()
            .unwrap();
        std::fs::copy(
            project.internal_path().join(&error.generated_path),
            self.context.abspath(Path::new(&error.generated_path)),
        )
        .unwrap();
        self.context
            .commit("Run 'pgbuildext updatecontrol'.", Some(false))?;
        Ok(true)
    }
}

fn fix_missing_makefile_pl(
    error: &buildlog_consultant::problems::common::MissingPerlFile,
    _phase: &Phase,
    context: &DebianPackagingContext,
) -> Result<bool, Error> {
    if error.filename == "Makefile.PL"
        && !context.has_filename(Path::new("Makefile.PL"))
        && context.has_filename(Path::new("dist.ini"))
    {
        // TODO(jelmer): add dist-zilla add-on to debhelper
        unimplemented!()
    }
    return Ok(false);
}

fn debcargo_coerce_unacceptable_prerelease(
    _error: &dyn Problem,
    _phase: &Phase,
    context: &DebianPackagingContext,
) -> Result<bool, Error> {
    let path = context.abspath(Path::new("debian/debcargo.toml"));
    let text = std::fs::read_to_string(&path)?;
    let mut doc: toml_edit::DocumentMut = text.parse().unwrap();
    doc.as_table_mut()["allow_prerelease_deps"] = toml_edit::value(true);
    std::fs::write(&path, doc.to_string())?;
    context.commit("Enable allow_prerelease_deps.", None)?;
    Ok(true)
}

/// Macro to generate simple build fixers.
///
/// This macro creates structs that implement the DebianBuildFixer trait
/// for specific problem types, delegating the actual fixing to the provided
/// function.
macro_rules! simple_build_fixer {
    ($name:ident, $problem_cls:ty, $fn:expr) => {
        #[doc = concat!("Fixer for ", stringify!($problem_cls), " problems.")]
        ///
        /// This fixer detects and attempts to resolve specific build problems
        /// by delegating to an appropriate fixing function.
        pub struct $name<'a>(&'a DebianPackagingContext);

        impl<'a> std::fmt::Display for $name<'a> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", stringify!($name))
            }
        }

        impl<'a> std::fmt::Debug for $name<'a> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", stringify!($name))
            }
        }

        impl<'a> DebianBuildFixer for $name<'a> {
            fn can_fix(&self, problem: &dyn Problem) -> bool {
                problem.as_any().downcast_ref::<$problem_cls>().is_some()
            }

            fn fix(
                &self,
                error: &dyn Problem,
                phase: &Phase,
            ) -> std::result::Result<
                bool,
                crate::fix_build::InterimError<crate::debian::context::Error>,
            > {
                let error = error.as_any().downcast_ref::<$problem_cls>().unwrap();
                $fn(error, phase, self.0).map_err(|e| crate::fix_build::InterimError::Other(e))
            }
        }
    };
}

simple_build_fixer!(
    MissingConfigureFixer,
    buildlog_consultant::problems::common::MissingConfigure,
    fix_missing_configure
);
simple_build_fixer!(
    MissingAutomakeInputFixer,
    buildlog_consultant::problems::common::MissingAutomakeInput,
    fix_missing_automake_input
);
simple_build_fixer!(
    MissingConfigStatusInputFixer,
    buildlog_consultant::problems::common::MissingConfigStatusInput,
    fix_missing_config_status_input
);
simple_build_fixer!(
    MissingPerlFileFixer,
    buildlog_consultant::problems::common::MissingPerlFile,
    fix_missing_makefile_pl
);
simple_build_fixer!(
    DebcargoUnacceptablePredicateFixer,
    buildlog_consultant::problems::debian::DebcargoUnacceptablePredicate,
    debcargo_coerce_unacceptable_prerelease
);
simple_build_fixer!(
    DebcargoUnacceptableComparatorFixer,
    buildlog_consultant::problems::debian::DebcargoUnacceptableComparator,
    debcargo_coerce_unacceptable_prerelease
);
simple_build_fixer!(
    RetryAptFetchFailure,
    buildlog_consultant::problems::debian::AptFetchFailure,
    retry_apt_failure
);

/// Create a collection of all available Debian build fixers.
///
/// This function creates and returns all the build fixers available for
/// fixing Debian package build problems.
///
/// # Arguments
/// * `session` - Session for running commands
/// * `packaging_context` - Packaging context for making changes to the package
/// * `apt` - APT manager for package installation and queries
///
/// # Returns
/// A vector of boxed build fixers
pub fn versioned_package_fixers<'a, 'b, 'c, 'd, 'e>(
    session: &'c dyn Session,
    packaging_context: &'b DebianPackagingContext,
    apt: &'a AptManager<'e>,
) -> Vec<Box<dyn DebianBuildFixer + 'd>>
where
    'a: 'd,
    'b: 'd,
    'c: 'd,
    'c: 'a,
{
    vec![
        Box::new(PgBuildExtOutOfDateControlFixer {
            context: packaging_context,
            session,
            apt,
        }),
        Box::new(MissingConfigureFixer(packaging_context)),
        Box::new(MissingAutomakeInputFixer(packaging_context)),
        Box::new(MissingConfigStatusInputFixer(packaging_context)),
        Box::new(MissingPerlFileFixer(packaging_context)),
        Box::new(DebcargoUnacceptablePredicateFixer(packaging_context)),
        Box::new(DebcargoUnacceptableComparatorFixer(packaging_context)),
    ]
}

/// Create APT-specific Debian build fixers.
///
/// This function creates fixers that handle APT-related build issues.
///
/// # Arguments
/// * `apt` - APT manager for package installation and queries
/// * `packaging_context` - Packaging context for making changes to the package
///
/// # Returns
/// A vector of boxed build fixers for APT-related issues
pub fn apt_fixers<'a, 'b, 'c, 'd>(
    apt: &'a AptManager<'d>,
    packaging_context: &'b DebianPackagingContext,
) -> Vec<Box<dyn DebianBuildFixer + 'c>>
where
    'a: 'c,
    'b: 'c,
{
    let apt_tie_breakers: Vec<Box<dyn TieBreaker>> = vec![
        Box::new(PythonTieBreaker::from_tree(
            &packaging_context.tree,
            &packaging_context.subpath,
        )),
        Box::new(crate::debian::build_deps::BuildDependencyTieBreaker::from_session(apt.session())),
        #[cfg(feature = "udd")]
        Box::new(crate::debian::udd::PopconTieBreaker),
    ];
    vec![
        Box::new(RetryAptFetchFailure(packaging_context)) as Box<dyn DebianBuildFixer>,
        Box::new(PackageDependencyFixer {
            context: packaging_context,
            apt,
            tie_breakers: apt_tie_breakers,
        }) as Box<dyn DebianBuildFixer + 'c>,
    ]
}

/// Create a set of default Debian build fixers.
///
/// This function creates a standard set of build fixers that can handle
/// common build problems.
///
/// # Arguments
/// * `packaging_context` - Packaging context for making changes to the package
/// * `apt` - APT manager for package installation and queries
///
/// # Returns
/// A vector of boxed build fixers for common build issues
pub fn default_fixers<'a, 'b, 'c, 'd>(
    packaging_context: &'a DebianPackagingContext,
    apt: &'b AptManager<'d>,
) -> Vec<Box<dyn DebianBuildFixer + 'c>>
where
    'a: 'c,
    'b: 'c,
{
    let mut ret = Vec::new();
    ret.extend(versioned_package_fixers(
        apt.session(),
        packaging_context,
        apt,
    ));
    ret.extend(apt_fixers(apt, packaging_context));
    ret
}