Compare commits
124
Commits
c0b7e341fc
..
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6df490cf9a | ||
|
|
f5b7704647 | ||
|
|
4c1edc7dcd
|
||
|
|
9a66f8f7df | ||
|
|
7a6337e1cb | ||
|
|
9186bbbe51 | ||
|
|
681fa3d687 | ||
|
|
cc5bbd2297 | ||
|
|
5a1c1672cd | ||
|
|
adde0ee977 | ||
|
|
84405a6762 | ||
|
|
8250a0e3b1 | ||
|
|
edfd7ed5ed | ||
|
|
6545d327e4
|
||
|
|
b118a54bff | ||
|
|
43f8a9e275
|
||
|
|
ff41edbd47 | ||
|
|
9e0b6a37a6 | ||
|
|
ac19fd9d65 | ||
|
|
02e1f739c3 | ||
|
|
8c6f6f4028 | ||
|
|
37e0b5c978 | ||
|
|
6c0b200241 | ||
|
|
4edf331444 | ||
|
|
fa121f08ec | ||
|
|
ac83a939e3 | ||
|
|
1145ca55eb | ||
|
|
b99f945b98 | ||
|
|
ae5b0042e4 | ||
|
|
5b0cc08d8f | ||
|
|
ff1f8c7ccd | ||
|
|
31fe6dc524 | ||
|
|
5592d5a6e4 | ||
|
|
bb719e7c80 | ||
|
|
af9845c480 | ||
|
|
02cb5306f3 | ||
|
|
5c026a7050 | ||
|
|
9238aa961f | ||
|
|
d1056fbbbf | ||
|
|
a0e74073bf
|
||
|
|
4f5246ccd3 | ||
|
|
dd2438a72c | ||
|
|
012df20961 | ||
|
|
47bb7c608e | ||
|
|
6caedce61a | ||
|
|
bd8f814a53 | ||
|
|
4fae02bc85 | ||
|
|
c2dae4f3f9 | ||
|
|
0421a91e01 | ||
|
|
54cb04ba27 | ||
|
|
bb76e41908 | ||
|
|
d64e472845 | ||
|
|
052c02cdc3 | ||
|
|
27b1083b15 | ||
|
|
a7d2cfdc6e | ||
|
|
ff635b305b | ||
|
|
781ed204c2 | ||
|
|
0235ec6457 | ||
|
|
fa399f64b2 | ||
|
|
e6f2012835 | ||
|
|
ffac4d6b57 | ||
|
|
04a572cd77 | ||
|
|
fc0d2f247e | ||
|
|
ccd2e37385 | ||
|
|
52d5ad064f | ||
|
|
b8b2be5acf | ||
|
|
dd1c70c91a | ||
|
|
12407c8eac | ||
|
|
7601524b7c | ||
|
|
7af767898e | ||
|
|
ead97e1213 | ||
|
|
6e5ecd2f45 | ||
|
|
69f3c3954e | ||
|
|
c106ebe315 | ||
|
|
941f91decf | ||
|
|
b489db2728 | ||
|
|
c1f8893576 | ||
|
|
e640b153bd | ||
|
|
231c478d0b | ||
|
|
1aa0ca3d2f | ||
|
|
b20acf3199 | ||
|
|
3feca504fc | ||
|
|
85f0d7d92f | ||
|
|
c45edcee76 | ||
|
|
1fc1d1aa77 | ||
|
|
af870cb7cb | ||
|
|
2b017dcf43 | ||
|
|
4ab41e691a | ||
|
|
c18f1fe9c2 | ||
|
|
e7b35f5c37 | ||
|
|
54274e9079 | ||
|
|
93296c26c1 | ||
|
|
d6bad9fbbe | ||
|
|
607711a6b5 | ||
|
|
47b462ad61 | ||
|
|
fa39851783 | ||
|
|
22e43741f3 | ||
|
|
36875513ee | ||
|
|
06e591c665 | ||
|
|
12828f8498 | ||
|
|
eaf1b40369 | ||
|
|
27ab4cb9ad | ||
|
|
3501096107 | ||
|
|
174a13df39 | ||
|
|
dd006f7b80 | ||
|
|
d5b76ec8d8 | ||
|
|
70e375a34d | ||
|
|
8ad50aaf83 | ||
|
|
efb18bfa37 | ||
|
|
57db98d776 | ||
|
|
775e3d3b8a | ||
|
|
a7cd4244b2 | ||
|
|
d2bb311f74 | ||
|
|
4c26122357 | ||
|
|
3ed95725e4 | ||
|
|
afedde1f2b | ||
|
|
bc3d07abaa | ||
|
|
bac82f0afe | ||
|
|
05e7c55d32 | ||
|
|
f055b70281 | ||
|
|
77420e723a | ||
|
|
8e06b2074d | ||
|
|
84824f61c6 | ||
|
|
9cb3e29a3e |
Binary file not shown.
|
After Width: | Height: | Size: 799 KiB |
@@ -3,6 +3,7 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [ "main", "ci-test" ]
|
||||
tags: [ "v*" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
@@ -102,7 +103,7 @@ jobs:
|
||||
- name: Install build prerequisites
|
||||
run: |
|
||||
apt-get update -q
|
||||
apt-get install -y -q --no-install-recommends git curl
|
||||
apt-get install -y -q --no-install-recommends git curl nodejs
|
||||
- uses: actions/checkout@v6
|
||||
- name: Build snap
|
||||
run: |
|
||||
@@ -114,8 +115,48 @@ jobs:
|
||||
export PATH="/usr/libexec/snapcraft:$HOME/.cargo/bin:$PATH"
|
||||
snapcraft pack --destructive-mode
|
||||
- name: Upload snap artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
# v4 refuses to run outside github.com (GHESNotSupportedError); Gitea
|
||||
# implements the artifact API used by v3, so v3 is the supported choice.
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: snap
|
||||
path: ./*.snap
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
# Publishes the crate to crates.io on a v* tag. Trusted publishing
|
||||
# (OIDC) is GitHub-Actions-only, so authentication goes through a
|
||||
# crates.io API token stored as the CARGO_REGISTRY_TOKEN secret,
|
||||
# scoped to the pkh crate.
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ubuntu:26.04
|
||||
options: --privileged --cap-add SYS_ADMIN --security-opt apparmor:unconfined
|
||||
steps:
|
||||
- name: Set up container image
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y nodejs sudo curl wget ca-certificates build-essential
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install build dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y pkg-config libssl-dev libgpg-error-dev libgpgme-dev
|
||||
- name: Check the tag matches the crate version
|
||||
# cargo publish ships whatever version Cargo.toml declares,
|
||||
# regardless of the tag: a mismatch must fail loudly instead of
|
||||
# publishing the wrong version under the release tag.
|
||||
run: |
|
||||
crate_version="$(awk -F'"' '/^version =/{print $2; exit}' Cargo.toml)"
|
||||
tag_version="${GITHUB_REF_NAME#v}"
|
||||
if [ "$crate_version" != "$tag_version" ]; then
|
||||
echo "tag $GITHUB_REF_NAME does not match crate version $crate_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
- name: Publish
|
||||
run: cargo publish
|
||||
env:
|
||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
|
||||
+7
-1
@@ -1,2 +1,8 @@
|
||||
*.lock
|
||||
target
|
||||
|
||||
# Local snapcraft builds
|
||||
.craft
|
||||
parts
|
||||
prim
|
||||
stage
|
||||
*.snap
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# AGENTS.md
|
||||
|
||||
Conventions for working in this tree. They apply to every commit; the
|
||||
whole history follows them.
|
||||
|
||||
## Before every commit
|
||||
|
||||
Run, in order, and make sure they are clean before committing:
|
||||
|
||||
```sh
|
||||
cargo fmt --all
|
||||
cargo clippy --all-targets --all-features # zero warnings
|
||||
```
|
||||
|
||||
CI builds and lints with `RUSTFLAGS: -Dwarnings`, so a `cargo build`
|
||||
warning fails the gate too. `cargo fmt` may amend files you did not
|
||||
touch — include those changes in the commit (or in a separate `fmt:`
|
||||
commit) rather than leaving the tree dirty.
|
||||
|
||||
The test suite is heavy (chroots, ssh, network): always run the
|
||||
`#[cfg(test)]` modules of what you touch, and the full suite when
|
||||
changing shared plumbing (`report`, `logfmt`, `test_support`,
|
||||
`debian/`). Tests marked `#[ignore]` shell out or hit the network and
|
||||
are for deliberate ad-hoc runs (`cargo test -- --ignored`), not for the
|
||||
pre-commit pass. Building needs the gpgme/openssl system packages
|
||||
(`pkg-config libssl-dev libgpg-error-dev libgpgme-dev`).
|
||||
|
||||
## Commit messages
|
||||
|
||||
There are no conventional-commit types; the format is a component scope
|
||||
and a summary:
|
||||
|
||||
```
|
||||
<scope>: <short summary>
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- The scope is the component touched — the module under `src/` (file or
|
||||
directory), named after the user-facing subcommand when that differs:
|
||||
- `pull` — source package download (`src/pull.rs`)
|
||||
- `chlog` — changelog entry generation (`src/changelog.rs`)
|
||||
- `build` — source package builds, .dsc (`src/build/`)
|
||||
- `deb` — binary package builds, .deb (`src/deb/`)
|
||||
- `put` — PPA/archive upload (`src/put/`)
|
||||
- `new` — package scaffolding (`src/new/`)
|
||||
- `lint` — tree linting (`src/lint/`)
|
||||
- `prune`, `package_info` — remaining subcommand modules
|
||||
- `context` — build contexts: local, ssh, chroot/schroot, unshare
|
||||
(`src/context/`)
|
||||
- `interrupt` — Ctrl+C interception and interrupt-time cleanup
|
||||
(`src/interrupt.rs`)
|
||||
- `debian` — Debian format primitives: control, versions, checksums,
|
||||
arch (`src/debian/`)
|
||||
- `apt`, `launchpad`, `distro_info`, `quirks` — archive/distro
|
||||
integration
|
||||
- `report` — BuildView/Prompter ports and the views implementing them
|
||||
- `ui`, `logfmt` — terminal rendering and output classification
|
||||
- `data` — the `data/*.yml` embed convention itself; content changes
|
||||
to a data file belong to the commit of the module consuming it
|
||||
- `cli` — the binary, argument wiring (`src/main.rs`)
|
||||
- `test` — test-only changes (shared plumbing: `src/test_support.rs`)
|
||||
- `deps` — dependency additions/bumps (manifests, lockfile)
|
||||
- `fmt`, `clippy` — rustfmt/clippy fixups
|
||||
- `ci`, `snap`, `docs` — workflows, snap packaging, README
|
||||
- Use the submodule path when the change is confined to one
|
||||
(`apt/keyring`, `debian/version`).
|
||||
- A commit touching several components should be split into one commit
|
||||
per component when practical; otherwise comma-join the scopes without
|
||||
spaces (`pull,deb`).
|
||||
- Summary: imperative mood, lowercase first letter (proper nouns keep
|
||||
theirs: Ubuntu, SRU, lintian), no trailing period, max ~72 characters.
|
||||
- Body (expected for anything nontrivial): separated by a blank line,
|
||||
wrapped at 72 columns; explain why, and the design when the approach
|
||||
was a choice among alternatives. Reference issues as `#123`.
|
||||
- Reverts use git's default `Revert "<original subject>"`.
|
||||
|
||||
### Examples
|
||||
|
||||
```
|
||||
chlog: fall back to the changelog history when no version tag exists
|
||||
ui: ellipsize fake-terminal pane lines wider than the terminal
|
||||
lint: add pkh lint, wrapping lintian for parity plus pkh-native checks
|
||||
chlog: number Ubuntu backports with the per-release SRU scheme
|
||||
deb: resolve cross pkg-config against the target multiarch
|
||||
pull,deb: add top-level --pocket option
|
||||
debian/version: dpkg-compatible version comparison
|
||||
deps: bump git2 to 0.21
|
||||
fmt: apply rustfmt
|
||||
docs: refresh the README roadmap for 1.0
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
- The crate denies missing docs (`#![deny(missing_docs)]` in
|
||||
`src/lib.rs`): every public item carries a doc comment, and the module
|
||||
list there is the layout map — keep it in sync when adding a module.
|
||||
- Subcommand business logic lives in the library and reports through the
|
||||
`report` ports (`BuildView`, `Prompter`) instead of printing;
|
||||
`src/main.rs` is argument wiring only. Subprocess output
|
||||
classification is pure logic in `logfmt`, testable without a pty.
|
||||
- Static reference data (series tables, keyserver URLs, licenses,
|
||||
forges, templates) lives in `data/*.yml`, embedded with the
|
||||
`embed_data!` macro — not in hardcoded tables.
|
||||
- Comments state constraints the code cannot show; no narration.
|
||||
- Anything user-facing (subcommands, flags, option defaults) is
|
||||
reflected in `README.md` — including its roadmap checklists — before
|
||||
commit.
|
||||
Generated
+3068
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,10 @@ name = "pkh"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
authors = ["vhaudiquet"]
|
||||
description = "pkh is a packaging helper for Debian/Ubuntu packages"
|
||||
license = "MIT OR GPL-2.0-only"
|
||||
repository = "https://git.vhaudiquet.fr/vhaudiquet/pkh"
|
||||
readme = "README.md"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5.51", features = ["cargo"] }
|
||||
@@ -34,6 +38,9 @@ ssh2 = "0.9.5"
|
||||
gpgme = "0.11"
|
||||
serde_yaml = "0.9"
|
||||
lazy_static = "1.4.0"
|
||||
unicode-width = "0.2"
|
||||
parking_lot = "0.12"
|
||||
suppaftp = "12"
|
||||
|
||||
[dev-dependencies]
|
||||
test-log = "0.2.19"
|
||||
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1989
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025-2026 Valentin Haudiquet
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -2,6 +2,24 @@
|
||||
|
||||
`pkh` is a packaging helper for Debian/Ubuntu packages.
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
No distribution channel is published yet; build from source:
|
||||
|
||||
```
|
||||
sudo apt install pkg-config libssl-dev libgpg-error-dev libgpgme-dev
|
||||
git clone https://git.vhaudiquet.fr/vhaudiquet/pkh.git
|
||||
cd pkh
|
||||
cargo install --path .
|
||||
```
|
||||
|
||||
At runtime pkh shells out to the Debian packaging toolchain (git,
|
||||
dpkg-dev, quilt, mmdebstrap, lintian, pristine-tar, ...): install the
|
||||
ones your workflows use, or build the classic snap from
|
||||
`snap/snapcraft.yaml` (`snapcraft pack`), which carries them.
|
||||
|
||||
## Usage and features
|
||||
|
||||
### Basic concepts
|
||||
@@ -25,12 +43,19 @@ Options:
|
||||
Commands and workflows include:
|
||||
```
|
||||
Commands:
|
||||
new Scaffold a new Debian source package (buildable right away)
|
||||
pull Pull a source package from the archive or git
|
||||
chlog Auto-generate changelog entry, editing it, committing it afterwards
|
||||
build Build the source package (into a .dsc)
|
||||
deb Build the source package into binary package (.deb)
|
||||
put Upload the built source package to a PPA
|
||||
deb Build the source package into binary package (.deb)
|
||||
lint Lint the package (lintian wrapper + pkh-native checks)
|
||||
prune Prune residual pkh build artifacts and caches
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
Options:
|
||||
-h, --help Print help
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
### Examples
|
||||
@@ -66,68 +91,25 @@ That is a lot of different tools and operations. With pkh, the same workflow:
|
||||
pkh pull hello # needs -d ubuntu if you are not running Ubuntu
|
||||
# Apply the patch to the package
|
||||
...
|
||||
pkh commit -m "Applied patch xxx"
|
||||
git add debian/patches/xxx.patch
|
||||
git commit -m "Applied patch xxx"
|
||||
pkh chlog
|
||||
git add debian/changelog
|
||||
git commit -m "d/changelog"
|
||||
# Test that the package builds
|
||||
pkh build
|
||||
pkh deb
|
||||
# Upload the package to a ppa
|
||||
pkh put --ppa user/hello_xxx
|
||||
# Push previously commited changes
|
||||
# Push the commits to your fork
|
||||
git push xxx user-fork
|
||||
```
|
||||
|
||||
## Roadmap: features needed for 1.0
|
||||
|
||||
Basically, wrapping the basic debian workflows.
|
||||
Missing features:
|
||||
- [ ] `pkh pull`
|
||||
- [x] Obtain package sources from git
|
||||
- [x] Obtain package sources from the archive (fallback)
|
||||
- [x] Obtain package source from PPA (--ppa)
|
||||
- [ ] Obtain a specific version of the package
|
||||
- [x] Fetch the correct git branch for series on Ubuntu
|
||||
- [ ] Try to fetch the correct git branch for series on Debian, or fallback to the archive
|
||||
- [ ] `pkh chlog`
|
||||
- [x] Auto-generate changelog entry
|
||||
- [ ] Extra flags: backport, non-maintainer upload, no change rebuild, ...
|
||||
- [ ] Commit changelog entry
|
||||
- [ ] `pkh build`
|
||||
- [x] Build the source package
|
||||
- [ ] `pkh deb`
|
||||
- [x] Build the binary package
|
||||
- [x] Build for a specific architecture
|
||||
- [ ] Three build modes:
|
||||
- [ ] Build locally (discouraged)
|
||||
- [x] Build using unshare chroot, with binary emulation (default)
|
||||
- [x] Cross-compilation
|
||||
- [ ] Async build
|
||||
- [ ] `pkh status`
|
||||
- [ ] Show build status
|
||||
- [ ] `pkh put`
|
||||
- [x] Upload the source package to a PPA (native SFTP, no `dput` dependency)
|
||||
- [ ] Upload the source package to the archive
|
||||
- [ ] `pkh commit`
|
||||
- [ ] Commit the changes to git
|
||||
- [ ] `pkh lint`
|
||||
- [ ] Lint the package
|
||||
- [ ] `pkh test`
|
||||
- [ ] Run autopkgtest
|
||||
- [ ] Provide options: local (discouraged), chroot, VM?, ppa
|
||||
- [ ] Async test
|
||||
|
||||
## Nice-to-have features
|
||||
|
||||
- [ ] 'pkh pull'
|
||||
- [ ] Cache the Sources.gz files, to improve speed
|
||||
- [ ] Work in an already downloaded package, to git pull and re-fetch orig tar gz
|
||||
- [ ] 'pkh context'
|
||||
- [x] Select, add, remove, list contexts
|
||||
- [x] Context-scoped command execution
|
||||
- [ ] Context-scoped deb and test commands
|
||||
- [ ] Per-architecture contexts
|
||||
- [ ] Per-series contexts
|
||||
- [x] ssh contexts
|
||||
- [ ] docker, lxc contexts?
|
||||
- [ ] context push, context pop: context stack
|
||||
## Future improvement ideas
|
||||
|
||||
- pull: try to fetch the correct git branch for series on Debian
|
||||
- deb: asynchronous build, detachable and monitorable
|
||||
- put: allow uploads to Debian or Ubuntu archives
|
||||
- test: add 'pkh test' to run autopkgtests
|
||||
- pull: cache Sources.gz files to improve speed
|
||||
- pull: 'pkh pull' in a package tree should git pull and re-fetch orig tgz
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
## Static data needed for pkh operations
|
||||
## Instead of hardcoding the data in code, data files allow to quickly
|
||||
## update and maintain such data in one unique place
|
||||
## The goal is to have the minimal possible set of data necessary
|
||||
## to grab the actual data. For example we don't want to store every Ubuntu
|
||||
## or Debian series, but rather pointers to where that data lives: each dist
|
||||
## entry below carries its series sources (the local distro-info CSV, with
|
||||
## the network URL as fallback).
|
||||
##
|
||||
## Per-dist keys beyond the series pointers:
|
||||
## mirrors: the archive mirrors, each a URL serving a set of
|
||||
## architectures: `primary` (the main archive, whose url
|
||||
## doubles as the dist's base URL) and, where they exist,
|
||||
## the others (`ports`). `security_url` is the sibling
|
||||
## host serving the -security pocket for the same arches
|
||||
## (ports mirrors serve their own security); `archs` is
|
||||
## an explicit list, or the `all` sentinel when one
|
||||
## mirror serves every architecture (Debian's case — an
|
||||
## exhaustive list would rot each time an arch is added).
|
||||
## Host matching treats a URI as official when its host
|
||||
## equals a mirror host or is a subdomain of it, so the
|
||||
## country mirrors (fr.archive.ubuntu.com) count too.
|
||||
## components: the archive components (main, universe, contrib, ...)
|
||||
## a cross-build environment enables on official sources.
|
||||
## Live archive operations keep resolving components from
|
||||
## Release files; this is the offline default.
|
||||
## cross_pockets: the pockets a cross-build environment enables for a
|
||||
## series (`<series>-updates`, ...). Deliberately not the
|
||||
## `pockets` key: that one is the *search order* of pull,
|
||||
## where backports must not fold in.
|
||||
## suite_aliases: the changelog suite names that alias a series
|
||||
## codename: Debian packages conventionally target
|
||||
## 'unstable' where the series data carries 'sid'.
|
||||
## Mapped suite name -> series codename; the two
|
||||
## names identify the same series, and the selector
|
||||
## offers the aliased entry as '<suite> (<series>)'.
|
||||
## build_profiles: the vendor's default DEB_BUILD_PROFILES (Ubuntu
|
||||
## activates derivative.ubuntu noudeb, Debian none),
|
||||
## mirroring what Dpkg::BuildProfiles resolves when the
|
||||
## variable is unset.
|
||||
dist:
|
||||
debian:
|
||||
mirrors:
|
||||
primary:
|
||||
url: https://deb.debian.org/debian
|
||||
# One mirror serves every architecture.
|
||||
archs: all
|
||||
components: [main, contrib, non-free, non-free-firmware]
|
||||
cross_pockets: [updates, backports, security]
|
||||
build_profiles: []
|
||||
archive_keyring: https://ftp-master.debian.org/keys/archive-key-{series_num}.asc
|
||||
pockets:
|
||||
- updates
|
||||
- security
|
||||
- proposed-updates
|
||||
# Debian changelogs conventionally target 'unstable'; the series data
|
||||
# knows the same series as 'sid'.
|
||||
suite_aliases:
|
||||
unstable: sid
|
||||
sections:
|
||||
# Valid Section values for debian/control: the Debian policy section
|
||||
# list unioned with the sections observed in the live Ubuntu archive.
|
||||
# Archives reject uploads carrying an unknown section; only the part
|
||||
# before a '/' (the subsection) is validated.
|
||||
- admin
|
||||
- cli-mono
|
||||
- comm
|
||||
- database
|
||||
- debian-installer
|
||||
- debug
|
||||
- devel
|
||||
- doc
|
||||
- editors
|
||||
- education
|
||||
- electronics
|
||||
- embedded
|
||||
- fonts
|
||||
- games
|
||||
- gnome
|
||||
- gnu-r
|
||||
- golang
|
||||
- graphics
|
||||
- hamradio
|
||||
- haskell
|
||||
- httpd
|
||||
- interpreters
|
||||
- introspection
|
||||
- java
|
||||
- javascript
|
||||
- kde
|
||||
- kernel
|
||||
- libdevel
|
||||
- libs
|
||||
- lisp
|
||||
- localization
|
||||
- mail
|
||||
- math
|
||||
- metapackages
|
||||
- misc
|
||||
- net
|
||||
- news
|
||||
- ocaml
|
||||
- oldlibs
|
||||
- otherosfs
|
||||
- perl
|
||||
- php
|
||||
- python
|
||||
- ruby
|
||||
- rust
|
||||
- science
|
||||
- shells
|
||||
- sound
|
||||
- tasks
|
||||
- tex
|
||||
- text
|
||||
- translations
|
||||
- utils
|
||||
- vcs
|
||||
- video
|
||||
- web
|
||||
- x11
|
||||
- xfce
|
||||
- zope
|
||||
series:
|
||||
local: /usr/share/distro-info/debian.csv
|
||||
network: https://salsa.debian.org/debian/distro-info-data/-/raw/main/debian.csv
|
||||
ubuntu:
|
||||
mirrors:
|
||||
primary:
|
||||
url: https://archive.ubuntu.com/ubuntu
|
||||
# Sibling host serving the -security pocket for the same arches.
|
||||
security_url: http://security.ubuntu.com/ubuntu
|
||||
archs: [amd64, i386]
|
||||
ports:
|
||||
# Everything else lives on the ports archive, which also serves
|
||||
# its own -security pocket (no security_url needed).
|
||||
url: http://ports.ubuntu.com/ubuntu-ports
|
||||
archs: [armhf, arm64, ppc64el, riscv64, s390x]
|
||||
components: [main, restricted, universe, multiverse]
|
||||
cross_pockets: [updates, backports, security]
|
||||
build_profiles: [derivative.ubuntu, noudeb]
|
||||
archive_keyring: https://archive.ubuntu.com/ubuntu/project/ubuntu-archive-keyring.gpg
|
||||
pockets:
|
||||
- updates
|
||||
- security
|
||||
- proposed
|
||||
sections:
|
||||
# Same list as debian (see the comment there)
|
||||
- admin
|
||||
- cli-mono
|
||||
- comm
|
||||
- database
|
||||
- debian-installer
|
||||
- debug
|
||||
- devel
|
||||
- doc
|
||||
- editors
|
||||
- education
|
||||
- electronics
|
||||
- embedded
|
||||
- fonts
|
||||
- games
|
||||
- gnome
|
||||
- gnu-r
|
||||
- golang
|
||||
- graphics
|
||||
- hamradio
|
||||
- haskell
|
||||
- httpd
|
||||
- interpreters
|
||||
- introspection
|
||||
- java
|
||||
- javascript
|
||||
- kde
|
||||
- kernel
|
||||
- libdevel
|
||||
- libs
|
||||
- lisp
|
||||
- localization
|
||||
- mail
|
||||
- math
|
||||
- metapackages
|
||||
- misc
|
||||
- net
|
||||
- news
|
||||
- ocaml
|
||||
- oldlibs
|
||||
- otherosfs
|
||||
- perl
|
||||
- php
|
||||
- python
|
||||
- ruby
|
||||
- rust
|
||||
- science
|
||||
- shells
|
||||
- sound
|
||||
- tasks
|
||||
- tex
|
||||
- text
|
||||
- translations
|
||||
- utils
|
||||
- vcs
|
||||
- video
|
||||
- web
|
||||
- x11
|
||||
- xfce
|
||||
- zope
|
||||
series:
|
||||
local: /usr/share/distro-info/ubuntu.csv
|
||||
network: https://salsa.debian.org/debian/distro-info-data/-/raw/main/ubuntu.csv
|
||||
@@ -0,0 +1,31 @@
|
||||
## Forge hosts recognized by `pkh new` origin detection, with the
|
||||
## release-tarball URL templates of each: `Forge::parse`
|
||||
## (src/new/origin.rs) matches a git remote's host against the map keys,
|
||||
## and the tarball download substitutes {owner}, {repo} and {tag} into the
|
||||
## templates. Like host_keys.yml, this file exists so that static
|
||||
## endpoints are data: adding a forge is a YAML entry, not a code change
|
||||
## (self-hosted instances are deliberately absent — the download URL
|
||||
## shapes differ per instance).
|
||||
##
|
||||
## tarball_templates are tried sequentially in file order, best candidate
|
||||
## first (GitHub prefers the codeload direct link: no redirect).
|
||||
## `kind` documents the forge family the URL shapes belong to; the
|
||||
## templates fully describe the URLs, so nothing branches on it (yet) —
|
||||
## but it must be one of the known kinds, enforced at load time.
|
||||
##
|
||||
## Where the values come from: each forge's release-archive download URL
|
||||
## shapes, verified against the live forges —
|
||||
## github: codeload.github.com/<owner>/<repo>/tar.gz/refs/tags/<tag>
|
||||
## and github.com/<owner>/<repo>/archive/refs/tags/<tag>.tar.gz
|
||||
## gitlab: gitlab.com/<owner>/<repo>/-/archive/<tag>/<repo>-<tag>.tar.gz
|
||||
|
||||
forges:
|
||||
github.com:
|
||||
kind: github
|
||||
tarball_templates:
|
||||
- https://codeload.github.com/{owner}/{repo}/tar.gz/refs/tags/{tag}
|
||||
- https://github.com/{owner}/{repo}/archive/refs/tags/{tag}.tar.gz
|
||||
gitlab.com:
|
||||
kind: gitlab
|
||||
tarball_templates:
|
||||
- https://gitlab.com/{owner}/{repo}/-/archive/{tag}/{repo}-{tag}.tar.gz
|
||||
@@ -0,0 +1,17 @@
|
||||
## Keyserver lookup endpoint used to fetch PPA signing keys.
|
||||
## Like host_keys.yml, this file exists so that a static endpoint is data,
|
||||
## updatable in one reviewable place, instead of hardcoded in the source —
|
||||
## the URL was previously duplicated in the apt keyring and release
|
||||
## modules. Sparse on purpose: it grows if keyserver pools or alternates
|
||||
## ever need to be tried.
|
||||
##
|
||||
## The template carries its variable part as a {fingerprint} placeholder,
|
||||
## substituted by the accessor of src/apt/keyring.rs with plain string
|
||||
## replacement.
|
||||
##
|
||||
## Where the value comes from: keyserver.ubuntu.com, Ubuntu's OpenPKS
|
||||
## (formerly SKS) keyserver; op=get with search=0x<fingerprint> is the
|
||||
## documented machine interface fetching one key by fingerprint
|
||||
## (https://keyserver.ubuntu.com).
|
||||
|
||||
lookup_template: "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{fingerprint}"
|
||||
@@ -0,0 +1,33 @@
|
||||
## Launchpad service endpoints: the REST API, the PPA SFTP upload queue,
|
||||
## the PPA package-content host and the Ubuntu source-package git web UI.
|
||||
## Like host_keys.yml, this file exists so that static endpoints are data,
|
||||
## updatable in one reviewable place, instead of hardcoded in the source —
|
||||
## the API and content URLs were previously triplicated across modules.
|
||||
##
|
||||
## Templates carry their variable parts as {name} placeholders ({owner},
|
||||
## {ppa}, {package}), substituted by the accessors of src/launchpad.rs
|
||||
## with plain string replacement.
|
||||
##
|
||||
## Where the values come from:
|
||||
## api_base: the Launchpad REST API root (https://launchpad.net/docs/api/)
|
||||
## ssh_*: the PPA upload queue, as expanded by dput-ng's
|
||||
## ppa:user/ppa profile (ppa.launchpad.net:22, incoming
|
||||
## ~<user>/<ppa>)
|
||||
## ftp_*: the same upload queue over anonymous FTP, dput-ng's
|
||||
## plain ppa: profile: the transport pkh degrades to
|
||||
## when the SSH connection itself never comes up
|
||||
## content_host_template: ppa.launchpadcontent.net serves PPA apt
|
||||
## repositories since the 2022 move off ppa.launchpad.net
|
||||
## git_web_template: Launchpad's CGit mirrors of Ubuntu source packages
|
||||
## (git.launchpad.net/ubuntu/+source/<package>)
|
||||
|
||||
api_base: https://api.launchpad.net/1.0
|
||||
ssh_host: ppa.launchpad.net
|
||||
ssh_port: 22
|
||||
## The anonymous FTP upload queue dput-ng's plain ppa: profile uses:
|
||||
## pkh degrades to it when the SSH connection itself never comes up.
|
||||
ftp_host: ppa.launchpad.net
|
||||
ftp_port: 21
|
||||
incoming_template: "~{owner}/{ppa}"
|
||||
content_host_template: https://ppa.launchpadcontent.net/{owner}/{ppa}/ubuntu
|
||||
git_web_template: https://git.launchpad.net/ubuntu/+source/{package}
|
||||
@@ -0,0 +1,139 @@
|
||||
## License knowledge of `pkh new`, in one place: the wizard menu labels
|
||||
## (src/new/questions.rs), the spellings accepted by License::parse and the
|
||||
## SPDX URL template (src/new/options.rs), and the license-file sniffing
|
||||
## inputs (src/new/detect.rs) all read this table, so the three lists —
|
||||
## previously kept in sync by comments only — cannot drift apart anymore.
|
||||
## Adding or changing a curated license is one entry below.
|
||||
##
|
||||
## Keys:
|
||||
## id: SPDX identifier: written to debian/copyright, returned
|
||||
## by the license sniff and substituted into
|
||||
## license_url_template (minus a trailing '+' of the
|
||||
## "or later" spellings)
|
||||
## menu: label offered by the wizard license question (the
|
||||
## free-text "Other (enter a SPDX identifier)" entry
|
||||
## stays in Rust — it is UX, not data)
|
||||
## spellings: inputs accepted by License::parse, matched
|
||||
## case-insensitively; each entry must accept its own id
|
||||
## (a consistency test in options.rs locks ids, spellings
|
||||
## and the License enum together)
|
||||
## detect_markers: marker sets driving the LICENSE/COPYING text sniff of
|
||||
## detect.rs. A set matches when every marker of `all`
|
||||
## occurs in the lowercased license text and none of
|
||||
## `unless` does; an entry matches when any of its sets
|
||||
## does. The sets are written to be mutually exclusive:
|
||||
## the `unless` markers keep multi-license texts on the
|
||||
## entry carrying the stronger reference (a MIT-named
|
||||
## file also quoting the GPL or the Apache license is a
|
||||
## GPL/Apache file) and keep GPL sets off LGPL texts,
|
||||
## whose name contains theirs. The entry order below
|
||||
## (menu order) therefore only breaks ties.
|
||||
##
|
||||
## detect_files (top level): the candidate license file names the sniff
|
||||
## reads, in preference order, shared by every license (the case-variant
|
||||
## directory scan around them stays in Rust).
|
||||
##
|
||||
## license_url_template: the SPDX license page URL, with {id} substituted
|
||||
## for the debian/copyright reference paragraph.
|
||||
##
|
||||
## The behavioral lock for the markers is the LICENSE_TEXTS test table in
|
||||
## src/new/detect.rs: a bad marker edit fails those tests, not packages.
|
||||
|
||||
license_url_template: https://spdx.org/licenses/{id}.html
|
||||
|
||||
detect_files:
|
||||
- LICENSE
|
||||
- LICENSE.md
|
||||
- LICENSE.txt
|
||||
- COPYING
|
||||
- COPYING.txt
|
||||
|
||||
# Entries in wizard-menu order.
|
||||
licenses:
|
||||
- id: MIT
|
||||
menu: MIT
|
||||
spellings: [MIT]
|
||||
detect_markers:
|
||||
- all:
|
||||
- mit license
|
||||
unless:
|
||||
- apache license
|
||||
- general public license
|
||||
- all:
|
||||
- permission is hereby granted, free of charge
|
||||
unless:
|
||||
- apache license
|
||||
- general public license
|
||||
- id: Apache-2.0
|
||||
menu: Apache-2.0
|
||||
spellings: [Apache-2.0]
|
||||
detect_markers:
|
||||
- all:
|
||||
- apache license
|
||||
- version 2
|
||||
- id: GPL-2.0+
|
||||
menu: GPL-2.0+
|
||||
spellings: [GPL-2.0+]
|
||||
detect_markers:
|
||||
- all:
|
||||
- general public license
|
||||
unless:
|
||||
- version 3
|
||||
- lesser general public license
|
||||
- id: GPL-3.0+
|
||||
menu: GPL-3.0+
|
||||
spellings: [GPL-3.0+]
|
||||
detect_markers:
|
||||
- all:
|
||||
- general public license
|
||||
- version 3
|
||||
unless:
|
||||
- lesser general public license
|
||||
- id: LGPL-2.1+
|
||||
menu: LGPL-2.1+
|
||||
spellings: [LGPL-2.1+]
|
||||
detect_markers:
|
||||
- all:
|
||||
- lesser general public license
|
||||
unless:
|
||||
- version 3
|
||||
- all:
|
||||
- lesser general public license
|
||||
- version 2.1
|
||||
- id: LGPL-3.0+
|
||||
menu: LGPL-3.0+
|
||||
spellings: [LGPL-3.0+]
|
||||
detect_markers:
|
||||
- all:
|
||||
- lesser general public license
|
||||
- version 3
|
||||
unless:
|
||||
- version 2.1
|
||||
- id: BSD-2-Clause
|
||||
menu: BSD-2-Clause
|
||||
spellings: [BSD-2-Clause]
|
||||
detect_markers:
|
||||
- all:
|
||||
- redistribution and use in source and binary forms
|
||||
unless:
|
||||
- endorse or promote
|
||||
- isc license
|
||||
- permission to use, copy, modify, and/or distribute this software
|
||||
- id: BSD-3-Clause
|
||||
menu: BSD-3-Clause
|
||||
spellings: [BSD-3-Clause]
|
||||
detect_markers:
|
||||
- all:
|
||||
- redistribution and use in source and binary forms
|
||||
- endorse or promote
|
||||
unless:
|
||||
- isc license
|
||||
- permission to use, copy, modify, and/or distribute this software
|
||||
- id: ISC
|
||||
menu: ISC
|
||||
spellings: [ISC]
|
||||
detect_markers:
|
||||
- all:
|
||||
- isc license
|
||||
- all:
|
||||
- permission to use, copy, modify, and/or distribute this software
|
||||
@@ -0,0 +1,47 @@
|
||||
# Quirks configuration for package-specific workarounds
|
||||
# This file defines package-specific quirks that are applied during pull and deb operations
|
||||
#
|
||||
# `pull` and `deb` hold one entry per scope: several entries can carry
|
||||
# different `series` lists, and every matching entry applies in file
|
||||
# order. Entries can be scoped with `series`: an empty list applies to
|
||||
# every series, otherwise only the listed ones. Packaging workarounds
|
||||
# should carry the series they were verified against so they can be
|
||||
# dropped once the upstream packaging catches up.
|
||||
|
||||
quirks:
|
||||
|
||||
# The resolute kernels declare `llvm-21-dev` unqualified while their
|
||||
# other llvm pieces are `:native`; the dpkg cross rules then resolve it
|
||||
# against the host architecture, whose dependency closure conflicts with
|
||||
# the `:native` python3. Resolve it against the build architecture
|
||||
# until the control is fixed upstream.
|
||||
linux:
|
||||
deb:
|
||||
- series: [resolute]
|
||||
dependencies:
|
||||
replace:
|
||||
llvm-21-dev: llvm-21-dev:native <!stage1>
|
||||
linux-riscv:
|
||||
deb:
|
||||
- series: [resolute]
|
||||
dependencies:
|
||||
replace:
|
||||
llvm-21-dev: llvm-21-dev:native <!stage1>
|
||||
|
||||
# Add more packages and their quirks as needed
|
||||
# example-package:
|
||||
# pull:
|
||||
# - series: [noble]
|
||||
# package_directory:
|
||||
# - linux-main
|
||||
# deb:
|
||||
# - series: [resolute]
|
||||
# dependencies:
|
||||
# replace:
|
||||
# llvm-21-dev: llvm-21-dev:native <!stage1>
|
||||
# - series: [stonking]
|
||||
# dependencies:
|
||||
# replace:
|
||||
# llvm-22-dev: llvm-22-dev:native <!stage1>
|
||||
# parameters:
|
||||
# key: value
|
||||
@@ -0,0 +1,130 @@
|
||||
---
|
||||
name: pkh
|
||||
description: 'Drive pkh, a Debian/Ubuntu packaging helper: pull source packages, generate changelog entries, build .dsc/.deb, lint, and upload to a PPA. Use it whenever the task touches Debian or Ubuntu packaging: patching an existing package, preparing an SRU, backport or NMU, scaffolding a new .deb, rebuilding for a PPA, or uploading a source package. Trigger on "update the changelog", "package this", or a bare package name, even when the user never mentions Debian.'
|
||||
---
|
||||
|
||||
# pkh
|
||||
|
||||
`pkh` wraps the Debian packaging toolchain (`dch`, `dpkg-buildpackage`,
|
||||
`sbuild`, `dpkg-source`, `quilt`, `lintian`, PPA uploads) in one CLI.
|
||||
The subcommands share one set of option names, so `-s` always targets
|
||||
the series and `--ppa` always names the PPA. Each step also does more
|
||||
than the raw tool it replaces: `pull` fetches the orig tarball with the
|
||||
source, `chlog` commits the entry it writes, `deb` sets up a chroot and
|
||||
installs the build dependencies.
|
||||
|
||||
Check the install with `pkh --version`. Each command lists its flags
|
||||
with `pkh <command> --help`, so check there instead of guessing. pkh
|
||||
shells out to host tools (git, dpkg-dev, quilt, mmdebstrap, lintian,
|
||||
pristine-tar, schroot, ...). Install the ones your workflow uses, or
|
||||
use the classic snap, which carries them.
|
||||
|
||||
## Shared options
|
||||
|
||||
| Option | Meaning |
|
||||
|---|---|
|
||||
| `-d, --dist <dist>` | Target distribution, `debian` or `ubuntu` |
|
||||
| `-s, --series <series>` | Target series, for example `resolute` or `noble` |
|
||||
| `-v, --version <version>` | Target package version |
|
||||
| `-a, --arch <arch>` | Target architecture, for example `amd64` or `riscv64` |
|
||||
| `-p, --pocket <pocket>` | Distribution pocket: `updates`, `security`, `proposed` |
|
||||
| `--ppa <user/ppa>` | Act on the named PPA |
|
||||
|
||||
Defaults come from the host vendor, its development series, and its
|
||||
architecture. When the target differs, pass the flags: packaging for
|
||||
Ubuntu on a Debian host needs `-d ubuntu`, and a series or architecture
|
||||
that differs from the host needs `-s` or `-a`.
|
||||
|
||||
## Patch an Ubuntu package
|
||||
|
||||
```
|
||||
pkh pull hello # source and orig tarball; add -d ubuntu off an Ubuntu host
|
||||
# edit the package, committing each patch to git
|
||||
pkh chlog # generates the entry, opens it for editing, commits it
|
||||
git add debian/changelog && git commit -m "d/changelog"
|
||||
pkh build # source package, written next to the tree
|
||||
pkh deb # binary build in a chroot with build deps installed
|
||||
pkh lint # lintian plus pkh-native checks
|
||||
pkh put --ppa user/hello_xxx # uploads the .changes file from the build
|
||||
git push xxx user-fork # push the branch to your fork
|
||||
```
|
||||
|
||||
Run `pkh chlog` and `pkh build` from the root of the source tree; they
|
||||
act on the package in the current directory.
|
||||
|
||||
## Command reference
|
||||
|
||||
- `pkh new [name]` scaffolds a buildable source package. `--lang`
|
||||
picks the build system (`rust`, `python`, `meson`, `cmake`,
|
||||
`autotools`, `go`, `shell`, `makefile`); `--source <PATH>` packages
|
||||
existing sources instead. `--upstream-version` and `--revision` set
|
||||
the version. `--description`, `--homepage`, `--license <SPDX>`,
|
||||
`--command`, `--maintainer "Name <email>"`, and `--depends` fill in
|
||||
the package metadata, with the maintainer defaulting to
|
||||
`DEBFULLNAME`/`DEBEMAIL` and then git config. `--quilt` and
|
||||
`--native` choose the source format; `--orig-from
|
||||
release|git|path|snapshot` and `--orig-path` control the orig
|
||||
tarball. The changelog starts as `UNRELEASED`; `--release` targets
|
||||
`--series` instead. `--defaults` answers every remaining question
|
||||
with its default, which keeps the run non-interactive.
|
||||
|
||||
- `pkh pull <package>` fetches a source package from the archive or
|
||||
git. `--archive` skips git. `--ppa user/ppa` and `--repository
|
||||
<suite-url>` pull from a PPA or an external flat repository instead.
|
||||
`-d`, `-s`, `-v`, and `-p` target an exact source.
|
||||
|
||||
- `pkh chlog` generates the changelog entry from the commits since the
|
||||
last version tag, opens it for editing, and commits it. `--backport`,
|
||||
`--nmu`, and `--rebuild` apply the matching numbering scheme
|
||||
(`3.1-1ubuntu2~24.04.1`, `1.0-1.1`, `1.0-1build1`); `-v` sets an
|
||||
explicit version instead.
|
||||
|
||||
- `pkh build` produces the .dsc. `--orig auto|always|never` controls
|
||||
whether the upload includes the orig tarball; the default, `auto`,
|
||||
includes it only when the upstream version changed.
|
||||
|
||||
- `pkh deb` builds the binary packages in an isolated context with the
|
||||
build dependencies installed. `--ppa` (repeatable) adds dependency
|
||||
sources, `--inject <package|.deb>` preinstalls a package, and `-j`
|
||||
caps parallel jobs. `--cross` cross-compiles instead of using
|
||||
qemu-binfmt, but most packages cannot cross-compile, so prefer qemu.
|
||||
Leave `--mode` unset unless you need a specific build context.
|
||||
|
||||
- `pkh lint [path]` runs lintian plus the pkh-native checks. `--json`
|
||||
emits a machine-readable report and `--list-tags` prints the native
|
||||
tag catalog. `--fail-on` sets the severities that fail the run
|
||||
(errors by default), `--suppress-tags` ignores tags, `--check` runs a
|
||||
single native check, and `--info`, `--pedantic`, and
|
||||
`--experimental` add detail. `--repack` packs the tree fresh instead
|
||||
of reusing the existing build output.
|
||||
|
||||
- `pkh put [changes]` uploads a .changes file to `--ppa user/ppa`.
|
||||
With no argument it uploads the .changes from this package's last
|
||||
build, found next to the source tree. `--force` re-uploads a file
|
||||
that was already uploaded.
|
||||
|
||||
- `pkh prune` removes build artifacts and caches. Run it with
|
||||
`--dry-run` first to list them. `--all` also deletes the cached
|
||||
chroot tarballs, which take long to download again, so use it when
|
||||
you need the disk space.
|
||||
|
||||
## Notes for agent runs
|
||||
|
||||
- Pass `-d`, `-s`, and `-a` whenever the target differs from the host,
|
||||
so runs are reproducible.
|
||||
- Keep runs non-interactive. Pass explicit flags, use `pkh new
|
||||
--defaults`, and set `EDITOR` before `pkh chlog` (`EDITOR=true` keeps
|
||||
the generated text). Commands may ask short questions on the
|
||||
terminal; flags avoid most prompts.
|
||||
- Pass `RUST_LOG=debug` for pkh's own logs. `--verbose` on `pkh build`
|
||||
and `pkh deb` prints raw tool output instead of the live view.
|
||||
- pkh writes the build artifacts (.dsc, .changes, logs) next to the
|
||||
source tree. `pkh put` finds them without arguments, and `pkh prune`
|
||||
removes them again.
|
||||
- Run `pkh lint` before `pkh put`. It exits nonzero when findings reach
|
||||
the `--fail-on` level, which defaults to errors.
|
||||
- pkh intercepts Ctrl+C, runs its cleanup hooks, and exits with status
|
||||
130. `pkh prune` removes anything left over.
|
||||
|
||||
The upstream repository is https://git.vhaudiquet.fr/vhaudiquet/pkh.
|
||||
Its README has longer workflow examples.
|
||||
@@ -0,0 +1,2 @@
|
||||
bin_PROGRAMS = {command}
|
||||
{command}_SOURCES = hello.c
|
||||
@@ -0,0 +1,5 @@
|
||||
AC_INIT([{name}], [{upstream_version}])
|
||||
AM_INIT_AUTOMAKE([foreign])
|
||||
AC_PROG_CC
|
||||
AC_CONFIG_FILES([Makefile])
|
||||
AC_OUTPUT
|
||||
@@ -0,0 +1,8 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* Placeholder for {name}, generated by `pkh new`. */
|
||||
int main(void)
|
||||
{
|
||||
printf("Hello from {command}!\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
## The `autotools` template: a C project with a configure.ac built through
|
||||
## debhelper's auto-detection (dh runs autoreconf itself when it finds
|
||||
## configure.ac, debhelper >= 10 — no override needed). The skeleton bodies
|
||||
## below are static data (the first source build runs `autoreconf`,
|
||||
## integrated in the dh sequence, so no generated configure script is
|
||||
## committed); the logic half — the AC_INIT probe and the GNU-gettext
|
||||
## detection (appended to Build-Depends) — lives in
|
||||
## src/new/templates/autotools.rs. hello.c.tpl duplicates the shared C
|
||||
## skeleton of the other C/C++ template directories (see
|
||||
## meson/manifest.yml for why).
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: autotools
|
||||
label: C/C++ (Autotools)
|
||||
detect:
|
||||
files: [configure.ac]
|
||||
build_depends:
|
||||
- autoconf
|
||||
- automake
|
||||
- libtool
|
||||
architecture: any
|
||||
rules_dh_line: "dh $@"
|
||||
files:
|
||||
- path: configure.ac
|
||||
template: configure.ac.tpl
|
||||
- path: Makefile.am
|
||||
template: Makefile.am.tpl
|
||||
- path: hello.c
|
||||
template: hello.c.tpl
|
||||
@@ -0,0 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project({name} VERSION {upstream_version})
|
||||
|
||||
add_executable({command} hello.c)
|
||||
install(TARGETS {command} RUNTIME DESTINATION bin)
|
||||
@@ -0,0 +1,8 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* Placeholder for {name}, generated by `pkh new`. */
|
||||
int main(void)
|
||||
{
|
||||
printf("Hello from {command}!\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
## The `cmake` template: a C/C++ project built with CMake through the
|
||||
## debhelper cmake buildsystem. The skeleton bodies below are static data;
|
||||
## the logic half — the project() probe and the wizard's pkg-config
|
||||
## opt-in (appended to Build-Depends) — lives in src/new/templates/cmake.rs.
|
||||
## hello.c.tpl duplicates the shared C skeleton of the other C/C++
|
||||
## template directories (see meson/manifest.yml for why).
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: cmake
|
||||
label: C/C++ (CMake)
|
||||
detect:
|
||||
files: [CMakeLists.txt]
|
||||
build_depends:
|
||||
- cmake
|
||||
architecture: any
|
||||
rules_dh_line: "dh $@ --buildsystem=cmake"
|
||||
files:
|
||||
- path: CMakeLists.txt
|
||||
template: CMakeLists.txt.tpl
|
||||
- path: hello.c
|
||||
template: hello.c.tpl
|
||||
@@ -0,0 +1 @@
|
||||
{name} - empty base tree scaffolded by `pkh new`; there is intentionally no upstream build system here.
|
||||
@@ -0,0 +1,19 @@
|
||||
## The `empty` template: a metapackage (non-empty Depends list) or an
|
||||
## empty base package with no build system at all — pure `dh $@` plumbing
|
||||
## as a starting point for hand-written rules. Pure data: no hooks, the
|
||||
## metapackage Depends payload travels in the wizard answers, and the
|
||||
## only upstream file is the stub README marking the tree as
|
||||
## intentionally empty.
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: empty
|
||||
label: Metapackage / empty base (no build system)
|
||||
detect:
|
||||
files: []
|
||||
build_depends: []
|
||||
architecture: all
|
||||
rules_dh_line: "dh $@"
|
||||
files:
|
||||
- path: README
|
||||
template: README.tpl
|
||||
@@ -0,0 +1,3 @@
|
||||
module {name}
|
||||
|
||||
go 1.21
|
||||
@@ -0,0 +1,8 @@
|
||||
// Placeholder for {name}, generated by `pkh new`.
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello from {command}!")
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
## The `go` template: a Go module built through dh-golang. The logic half
|
||||
## — the go.mod module-line probe and the `{go_import_path}` value below —
|
||||
## lives in src/new/templates/go.rs; the skeleton bodies are static data
|
||||
## (the `go` directive of go.mod stays a literal: nothing about it is
|
||||
## answer-derived, so it has no {placeholder}).
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: go
|
||||
label: Go module
|
||||
detect:
|
||||
files: [go.mod]
|
||||
build_depends:
|
||||
- golang-any
|
||||
- dh-golang
|
||||
architecture: any
|
||||
rules_dh_line: "dh $@ --buildsystem=golang"
|
||||
source_fields:
|
||||
XS-Go-Import-Path: "{go_import_path}"
|
||||
files:
|
||||
- path: go.mod
|
||||
template: go.mod.tpl
|
||||
- path: main.go
|
||||
template: main.go.tpl
|
||||
@@ -0,0 +1,16 @@
|
||||
CC ?= cc
|
||||
CFLAGS ?= -O2 -Wall -Wextra
|
||||
PREFIX ?= /usr
|
||||
|
||||
all: {command}
|
||||
|
||||
{command}: hello.c
|
||||
$(CC) $(CFLAGS) -o $@ hello.c
|
||||
|
||||
install: {command}
|
||||
install -Dm755 {command} $(DESTDIR)$(PREFIX)/bin/{command}
|
||||
|
||||
clean:
|
||||
rm -f {command}
|
||||
|
||||
.PHONY: all install clean
|
||||
@@ -0,0 +1,8 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* Placeholder for {name}, generated by `pkh new`. */
|
||||
int main(void)
|
||||
{
|
||||
printf("Hello from {command}!\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{command} usr/bin/{command}
|
||||
@@ -0,0 +1,28 @@
|
||||
## The `makefile` template: a generic project driven by a plain Makefile.
|
||||
## debhelper's makefile buildsystem runs `make` for the build and
|
||||
## `make install DESTDIR=...` when the Makefile carries an `install:`
|
||||
## target (missing targets are skipped gracefully), so plain `dh $@`
|
||||
## plumbing is enough here. The phony-install hint of
|
||||
## src/new/templates/makefile.rs (whether dh_auto_install will run
|
||||
## `make install` for an existing tree) is the only logic; the skeleton
|
||||
## bodies below are static data (the install mapping is rendered for
|
||||
## skeletons only, whose phony install target is known by construction).
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: makefile
|
||||
label: Generic (Makefile)
|
||||
detect:
|
||||
files: [Makefile]
|
||||
build_depends:
|
||||
- build-essential
|
||||
architecture: any
|
||||
rules_dh_line: "dh $@"
|
||||
files:
|
||||
- path: hello.c
|
||||
template: hello.c.tpl
|
||||
- path: Makefile
|
||||
template: Makefile.tpl
|
||||
- path: debian/install
|
||||
template: install.tpl
|
||||
skeleton_only: true
|
||||
@@ -0,0 +1,8 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* Placeholder for {name}, generated by `pkh new`. */
|
||||
int main(void)
|
||||
{
|
||||
printf("Hello from {command}!\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
## The `meson` template: a C/C++ project built with Meson through the
|
||||
## debhelper meson buildsystem. The skeleton bodies below are static data;
|
||||
## the logic half — the project() probe and the wizard's pkg-config
|
||||
## opt-in (appended to Build-Depends) — lives in src/new/templates/meson.rs.
|
||||
##
|
||||
## hello.c.tpl is deliberately duplicated (byte-identical) across the
|
||||
## makefile, cmake and autotools template directories: every template
|
||||
## directory is self-contained — the registry embeds each directory's
|
||||
## bodies under its own entry — so a shared body would need
|
||||
## cross-directory references the manifest schema has no machinery for.
|
||||
## The duplication replaces the Rust hello_c() helper meson.rs used to
|
||||
## lend cmake.rs and autotools.rs.
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: meson
|
||||
label: C/C++ (Meson)
|
||||
detect:
|
||||
files: [meson.build]
|
||||
build_depends:
|
||||
- meson
|
||||
architecture: any
|
||||
rules_dh_line: "dh $@ --buildsystem=meson"
|
||||
files:
|
||||
- path: meson.build
|
||||
template: meson.build.tpl
|
||||
- path: hello.c
|
||||
template: hello.c.tpl
|
||||
@@ -0,0 +1,3 @@
|
||||
project('{name}', version: '{upstream_version}', license: '{license}', default_options: ['c_std=c11'])
|
||||
|
||||
executable('{command}', 'hello.c', install: true)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Placeholder for {name}, generated by `pkh new`."""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print("Hello from {command}!")
|
||||
@@ -0,0 +1,29 @@
|
||||
## The `python` template: a PEP 517 project built with pybuild. The
|
||||
## skeleton bodies below are static data on the fresh-skeleton baseline
|
||||
## (the setuptools backend): the module directory and the console-script
|
||||
## entry point are named by the `{module_name}` placeholder python.rs
|
||||
## derives from the package name — dpkg names may carry `+`/`.` and may
|
||||
## start with a digit, none of which a Python module name may. The logic
|
||||
## half — the pyproject.toml/setup.py probe and the Build-Depends /
|
||||
## architecture resolution for existing projects (backend package,
|
||||
## pyproject presence, C-extension hints) — lives in
|
||||
## src/new/templates/python.rs.
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: python
|
||||
label: Python (pyproject.toml / setup.py)
|
||||
detect:
|
||||
files: [pyproject.toml, setup.py, setup.cfg]
|
||||
build_depends:
|
||||
- dh-python
|
||||
- python3-all
|
||||
- pybuild-plugin-pyproject
|
||||
- python3-setuptools
|
||||
architecture: all
|
||||
rules_dh_line: "dh $@ --with python3 --buildsystem=pybuild"
|
||||
files:
|
||||
- path: pyproject.toml
|
||||
template: pyproject.toml.tpl
|
||||
- path: "{module_name}/__init__.py"
|
||||
template: __init__.py.tpl
|
||||
@@ -0,0 +1,12 @@
|
||||
[build-system]
|
||||
requires = ["setuptools"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "{name}"
|
||||
version = "{upstream_version}"
|
||||
description = "{summary}"
|
||||
requires-python = ">=3.8"
|
||||
|
||||
[project.scripts]
|
||||
{command} = "{module_name}:main"
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "{crate_name}"
|
||||
version = "{upstream_version}"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,4 @@
|
||||
// Placeholder for {name}, generated by `pkh new`.
|
||||
fn main() {
|
||||
println!("Hello from {command}!");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
## The `rust` template: a vendored Cargo build (see the module docs of
|
||||
## src/new/templates/rust.rs for the vendoring strategy). The skeleton
|
||||
## bodies and the vendored-build rules overrides below are static data; the
|
||||
## logic half — the cargo vendor post-write hook, the project probe, and
|
||||
## the `{crate_name}` / `{locked}` / `{artifact}` values of the bodies —
|
||||
## lives in that module (dpkg package names may carry `+`/`.`, which cargo
|
||||
## rejects in crate names, so the skeleton crate name is a derived
|
||||
## placeholder, not the raw `{name}`).
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: rust
|
||||
label: Rust (Cargo.toml)
|
||||
detect:
|
||||
files: [Cargo.toml]
|
||||
build_depends:
|
||||
- cargo:native
|
||||
- rustc:native
|
||||
architecture: any
|
||||
rules_dh_line: "dh $@"
|
||||
# The vendored-build overrides appended to debian/rules; `--locked` is only
|
||||
# used when the packaged tree already carries a Cargo.lock (the vendoring
|
||||
# hook patches it in once it creates the lockfile), and the built artifact
|
||||
# of a fresh skeleton is named after its crate.
|
||||
rules_extra_file: rules.extra.tpl
|
||||
gitignore_entries:
|
||||
- vendor/
|
||||
- .cargo/config.toml
|
||||
files:
|
||||
- path: Cargo.toml
|
||||
template: Cargo.toml.tpl
|
||||
- path: src/main.rs
|
||||
template: main.rs.tpl
|
||||
@@ -0,0 +1,19 @@
|
||||
override_dh_auto_build:
|
||||
cargo build --release --offline{locked}
|
||||
|
||||
override_dh_auto_install:
|
||||
install -Dm755 target/release/{artifact} debian/{name}/usr/bin/{command}
|
||||
|
||||
override_dh_auto_test:
|
||||
cargo test --release --offline{locked}
|
||||
|
||||
override_dh_update_autotools_config:
|
||||
|
||||
override_dh_clean:
|
||||
# dh_clean unlinks `*.orig` patch backups, but vendored crates
|
||||
# ship files like `Cargo.toml.orig` that cargo's per-file
|
||||
# checksums require on cold builds (chroots, Launchpad).
|
||||
dh_clean -X .orig
|
||||
|
||||
override_dh_auto_clean:
|
||||
cargo clean
|
||||
@@ -0,0 +1 @@
|
||||
{command}.sh usr/bin/{command}
|
||||
@@ -0,0 +1,25 @@
|
||||
## The `shell` template: a single interpreted script installed to
|
||||
## /usr/bin with plain `dh $@` plumbing. Detection is not marker-based: the
|
||||
## single-script heuristic of src/new/detect.rs (a lone *.sh or shebang
|
||||
## file) maps here. The probe pre-filling the wizard answers from the
|
||||
## script file name lives in src/new/templates/shell.rs; everything else
|
||||
## is the data below (the skeleton script is executable, the install
|
||||
## mapping exists for skeletons only — packaging an existing tree leaves
|
||||
## the mapping to the user).
|
||||
##
|
||||
## Schema: see src/new/templates/mod.rs.
|
||||
|
||||
id: shell
|
||||
label: Shell script / single interpreted file
|
||||
detect:
|
||||
files: []
|
||||
build_depends: []
|
||||
architecture: all
|
||||
rules_dh_line: "dh $@"
|
||||
files:
|
||||
- path: "{command}.sh"
|
||||
template: script.tpl
|
||||
executable: true
|
||||
- path: debian/install
|
||||
template: install.tpl
|
||||
skeleton_only: true
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
# Placeholder for {name}, generated by `pkh new`.
|
||||
echo "Hello from {command}!"
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
## Static data needed for pkh operations
|
||||
## Instead of hardcoding the data in code, data files allow to quickly
|
||||
## update and maintain such data in one unique place
|
||||
## The goal is to have the minimal possible set of data necessary
|
||||
## to grab the actual data. For example we don't want to store every Ubuntu
|
||||
## or Debian series, but rather an URL where we can properly access that data.
|
||||
dist_info:
|
||||
local: /usr/share/distro-info/{dist}
|
||||
network: https://salsa.debian.org/debian/distro-info-data/-/raw/main/
|
||||
dist:
|
||||
debian:
|
||||
base_url: https://deb.debian.org/debian
|
||||
archive_keyring: https://ftp-master.debian.org/keys/archive-key-{series_num}.asc
|
||||
pockets:
|
||||
- updates
|
||||
- security
|
||||
- proposed-updates
|
||||
sections:
|
||||
# Valid Section values for debian/control: the Debian policy section
|
||||
# list unioned with the sections observed in the live Ubuntu archive.
|
||||
# Archives reject uploads carrying an unknown section; only the part
|
||||
# before a '/' (the subsection) is validated.
|
||||
- admin
|
||||
- cli-mono
|
||||
- comm
|
||||
- database
|
||||
- debian-installer
|
||||
- debug
|
||||
- devel
|
||||
- doc
|
||||
- editors
|
||||
- education
|
||||
- electronics
|
||||
- embedded
|
||||
- fonts
|
||||
- games
|
||||
- gnome
|
||||
- gnu-r
|
||||
- golang
|
||||
- graphics
|
||||
- hamradio
|
||||
- haskell
|
||||
- httpd
|
||||
- interpreters
|
||||
- introspection
|
||||
- java
|
||||
- javascript
|
||||
- kde
|
||||
- kernel
|
||||
- libdevel
|
||||
- libs
|
||||
- lisp
|
||||
- localization
|
||||
- mail
|
||||
- math
|
||||
- metapackages
|
||||
- misc
|
||||
- net
|
||||
- news
|
||||
- ocaml
|
||||
- oldlibs
|
||||
- otherosfs
|
||||
- perl
|
||||
- php
|
||||
- python
|
||||
- ruby
|
||||
- rust
|
||||
- science
|
||||
- shells
|
||||
- sound
|
||||
- tasks
|
||||
- tex
|
||||
- text
|
||||
- translations
|
||||
- utils
|
||||
- vcs
|
||||
- video
|
||||
- web
|
||||
- x11
|
||||
- xfce
|
||||
- zope
|
||||
series:
|
||||
local: /usr/share/distro-info/debian.csv
|
||||
network: https://salsa.debian.org/debian/distro-info-data/-/raw/main/debian.csv
|
||||
ubuntu:
|
||||
base_url: https://archive.ubuntu.com/ubuntu
|
||||
archive_keyring: https://archive.ubuntu.com/ubuntu/project/ubuntu-archive-keyring.gpg
|
||||
pockets:
|
||||
- updates
|
||||
- security
|
||||
- proposed
|
||||
sections:
|
||||
# Same list as debian (see the comment there)
|
||||
- admin
|
||||
- cli-mono
|
||||
- comm
|
||||
- database
|
||||
- debian-installer
|
||||
- debug
|
||||
- devel
|
||||
- doc
|
||||
- editors
|
||||
- education
|
||||
- electronics
|
||||
- embedded
|
||||
- fonts
|
||||
- games
|
||||
- gnome
|
||||
- gnu-r
|
||||
- golang
|
||||
- graphics
|
||||
- hamradio
|
||||
- haskell
|
||||
- httpd
|
||||
- interpreters
|
||||
- introspection
|
||||
- java
|
||||
- javascript
|
||||
- kde
|
||||
- kernel
|
||||
- libdevel
|
||||
- libs
|
||||
- lisp
|
||||
- localization
|
||||
- mail
|
||||
- math
|
||||
- metapackages
|
||||
- misc
|
||||
- net
|
||||
- news
|
||||
- ocaml
|
||||
- oldlibs
|
||||
- otherosfs
|
||||
- perl
|
||||
- php
|
||||
- python
|
||||
- ruby
|
||||
- rust
|
||||
- science
|
||||
- shells
|
||||
- sound
|
||||
- tasks
|
||||
- tex
|
||||
- text
|
||||
- translations
|
||||
- utils
|
||||
- vcs
|
||||
- video
|
||||
- web
|
||||
- x11
|
||||
- xfce
|
||||
- zope
|
||||
series:
|
||||
local: /usr/share/distro-info/ubuntu.csv
|
||||
network: https://salsa.debian.org/debian/distro-info-data/-/raw/main/ubuntu.csv
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
# Quirks configuration for package-specific workarounds
|
||||
# This file defines package-specific quirks that are applied during pull and deb operations
|
||||
|
||||
quirks:
|
||||
|
||||
# Add more packages and their quirks as needed
|
||||
# example-package:
|
||||
# pull:
|
||||
# method: archive
|
||||
# deb:
|
||||
# extra_dependencies:
|
||||
# - another-dependency
|
||||
# parameters:
|
||||
# key: value
|
||||
|
||||
+83
-10
@@ -2,12 +2,17 @@ name: pkh
|
||||
base: core24
|
||||
summary: pkh is a packaging helper for Debian/Ubuntu packages
|
||||
description: |
|
||||
pkh aims at wrapping the different debian tools and workflows
|
||||
into one tool, that would have the same interface for everything,
|
||||
pkh aims at wrapping the different debian tools and workflows
|
||||
into one tool, that would have the same interface for everything,
|
||||
while being smarter at integrating all workflows.
|
||||
|
||||
This snap uses classic confinement and carries the packaging
|
||||
toolchain it drives (dpkg-dev, git, mmdebstrap, lintian, quilt, ...)
|
||||
so it behaves the same on any Debian/Ubuntu host.
|
||||
license: MIT OR GPL-2.0-only
|
||||
adopt-info: pkh-part
|
||||
|
||||
confinement: devmode
|
||||
confinement: classic
|
||||
|
||||
apps:
|
||||
pkh:
|
||||
@@ -19,24 +24,92 @@ parts:
|
||||
source: .
|
||||
override-pull: |
|
||||
craftctl default
|
||||
craftctl set version=$(git rev-parse --short=11 HEAD)
|
||||
craftctl set grade="devel"
|
||||
# Release metadata comes from the crate, not the git state: a build
|
||||
# of any commit must produce the version the crate declares.
|
||||
craftctl set version="$(awk -F'"' '/^version =/{print $2; exit}' Cargo.toml)"
|
||||
craftctl set grade="stable"
|
||||
build-packages:
|
||||
- build-essential
|
||||
- file
|
||||
- patchelf
|
||||
- pkg-config
|
||||
- libssl-dev
|
||||
- libgpg-error-dev
|
||||
- libgpgme-dev
|
||||
# Host-side tools pkh execs directly. Tools that only run *inside*
|
||||
# the build chroot (dose-builddebcheck, dpkg-cross) are provisioned
|
||||
# there by pkh itself and must not be staged; likewise qemu-user-static
|
||||
# is host binfmt configuration, not a bundled file.
|
||||
#
|
||||
# The apt and dpkg state-owning tools are deliberately excluded below:
|
||||
# they must be the host's (classic mode makes them visible), since a
|
||||
# core24 apt/dpkg managing a newer host's package database is exactly
|
||||
# the version skew classic snaps must avoid. The source-package tools
|
||||
# (dpkg-buildpackage, dpkg-source, ...) are bundled instead.
|
||||
stage-packages:
|
||||
- libgpgme11t64
|
||||
- git
|
||||
- curl
|
||||
- gnupg
|
||||
- gpgv
|
||||
- dpkg-dev
|
||||
- quilt
|
||||
- pristine-tar
|
||||
- mmdebstrap
|
||||
- lintian
|
||||
- fakeroot
|
||||
- util-linux
|
||||
- dpkg-dev
|
||||
# mount/umount moved to their own package (split from util-linux)
|
||||
- mount
|
||||
- schroot
|
||||
- openssh-client
|
||||
- tar
|
||||
- xz-utils
|
||||
- bzip2
|
||||
stage:
|
||||
- -usr/lib/x86_64-linux-gnu/libicuio.so.74.2
|
||||
- -usr/lib/x86_64-linux-gnu/libicutest.so.74.2
|
||||
- -usr/lib/x86_64-linux-gnu/libicutu.so.74.2
|
||||
- -usr/lib/x86_64-linux-gnu/libicui18n.so.74.2
|
||||
- -usr/bin/apt
|
||||
- -usr/bin/apt-cache
|
||||
- -usr/bin/apt-cdrom
|
||||
- -usr/bin/apt-config
|
||||
- -usr/bin/apt-get
|
||||
- -usr/bin/apt-key
|
||||
- -usr/bin/apt-mark
|
||||
- -usr/lib/*/libapt-*
|
||||
- -usr/lib/*/libicuio*
|
||||
- -usr/lib/*/libicutest*
|
||||
- -usr/lib/*/libicutu*
|
||||
- -usr/lib/*/libicui18n*
|
||||
# update-alternatives does not run at staging time: expose the sysv
|
||||
# fakeroot under the plain name dpkg-buildpackage and pkh exec.
|
||||
override-prime: |
|
||||
craftctl default
|
||||
ln -sfn fakeroot-sysv "${CRAFT_PRIME}/usr/bin/fakeroot"
|
||||
# Ship the license texts with the binary: the MIT grant requires
|
||||
# the notice to accompany copies, and GPL-2 requires the license
|
||||
# text alongside distribution.
|
||||
mkdir -p "${CRAFT_PRIME}/usr/share/doc/pkh"
|
||||
cp "${CRAFT_PART_SRC}/LICENSE-MIT" "${CRAFT_PART_SRC}/LICENSE-GPL" \
|
||||
"${CRAFT_PRIME}/usr/share/doc/pkh/"
|
||||
# Classic-confined ELFs default to the host loader, which pins the
|
||||
# snap to hosts shipping at least the build environment's glibc,
|
||||
# and cannot see the libraries deduplicated against the base.
|
||||
# Point every bundled ELF at the core24 loader and give it an
|
||||
# rpath resolving base libraries from the mounted base and
|
||||
# snap-local libraries from $ORIGIN — the classic linter's
|
||||
# guidance, and what Canonical's own classic snaps do. DT_RPATH
|
||||
# (--force-rpath) is required over the default DT_RUNPATH: the
|
||||
# host ld.so.cache would otherwise resolve sonames to host
|
||||
# libraries first, mixing host libm/libresolv with base libc.
|
||||
# DT_RPATH also propagates transitively, covering dependencies of
|
||||
# dependencies (libgpgme -> libassuan). Host tools spawned later
|
||||
# (host apt-get, ...) run with a pristine environment since no
|
||||
# LD_LIBRARY_PATH is exported.
|
||||
find "${CRAFT_PRIME}" -type f -exec sh -c '
|
||||
for f do
|
||||
[ "$(od -An -N4 -tx1 "$f" | tr -d " \n")" = "7f454c46" ] || continue
|
||||
patchelf --set-interpreter \
|
||||
/snap/core24/current/lib64/ld-linux-x86-64.so.2 "$f" 2>/dev/null || true
|
||||
patchelf --force-rpath --set-rpath \
|
||||
"/snap/core24/current/lib/x86_64-linux-gnu:/snap/core24/current/usr/lib/x86_64-linux-gnu:\$ORIGIN:\$ORIGIN/../lib/x86_64-linux-gnu:\$ORIGIN/../usr/lib/x86_64-linux-gnu" \
|
||||
"$f" 2>/dev/null || true
|
||||
done' sh {} +
|
||||
|
||||
+81
-33
@@ -4,6 +4,7 @@
|
||||
//! for mmdebstrap operations and for PPA packages by downloading them.
|
||||
|
||||
use crate::context;
|
||||
use crate::data::embed_data;
|
||||
use crate::distro_info;
|
||||
use serde::Deserialize;
|
||||
use std::error::Error;
|
||||
@@ -11,6 +12,26 @@ use std::os::unix::fs::MetadataExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Keyserver endpoint, loaded from the bundled `keyserver.yml` data file
|
||||
/// (same pattern as `distro_info.yml`): the lookup URL is a static
|
||||
/// endpoint that was previously hardcoded in two modules.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct KeyserverData {
|
||||
/// OpenPGP key lookup URL template (`{fingerprint}`)
|
||||
lookup_template: String,
|
||||
}
|
||||
|
||||
embed_data! {
|
||||
static ref KEYSERVER_DATA: KeyserverData = "../../data/keyserver.yml"
|
||||
}
|
||||
|
||||
/// URL fetching the OpenPGP key of `fingerprint` from the keyserver
|
||||
pub(crate) fn keyserver_lookup_url(fingerprint: &str) -> String {
|
||||
KEYSERVER_DATA
|
||||
.lookup_template
|
||||
.replace("{fingerprint}", fingerprint)
|
||||
}
|
||||
|
||||
/// Launchpad API response structure for PPA information
|
||||
#[derive(Deserialize)]
|
||||
struct LaunchpadPpaResponse {
|
||||
@@ -68,24 +89,27 @@ pub async fn download_cache_keyrings(
|
||||
keyring_dir.display()
|
||||
)
|
||||
})?;
|
||||
// Upgrade cache directories created by versions that made them
|
||||
// private: mmdebstrap's unshare-mode hooks cannot read them.
|
||||
} else {
|
||||
// Remote contexts (e.g. ssh) have no stat/metadata access through
|
||||
// the context API, so the ownership guard cannot be performed;
|
||||
// keep the previous best-effort behavior of tightening the
|
||||
// directory permissions instead (0700 instead of the former
|
||||
// world-writable a+rwx).
|
||||
ctx.command("chmod").arg("700").arg(&keyring_dir).status()?;
|
||||
// directory permissions instead (no group/others write).
|
||||
}
|
||||
ctx.command("chmod").arg("755").arg(&keyring_dir).status()?;
|
||||
} else {
|
||||
// Create the directory private to the invoking user (0700). This is
|
||||
// sufficient for mmdebstrap in unshare mode: it runs with the same
|
||||
// real uid (the user namespace only maps that uid to root, file
|
||||
// access still happens as the real uid), so no world-accessible
|
||||
// permissions are needed.
|
||||
// Create the directory readable but not writable by group/others.
|
||||
// mmdebstrap's unshare-mode hooks run under an identity that cannot
|
||||
// read the invoking user's private directories, so 0700 breaks the
|
||||
// keyring copy into the chroot; the planting guard stays on the
|
||||
// ownership and no-write checks of validate_keyring_dir (the
|
||||
// skip-if-exists logic below trusts pre-existing keyrings, so the
|
||||
// directory must never be writable by anyone else).
|
||||
ctx.command("mkdir")
|
||||
.arg("-p")
|
||||
.arg("-m")
|
||||
.arg("700")
|
||||
.arg("755")
|
||||
.arg(&keyring_dir)
|
||||
.status()?;
|
||||
}
|
||||
@@ -157,6 +181,11 @@ pub async fn download_cache_keyrings(
|
||||
binary_path.display()
|
||||
);
|
||||
}
|
||||
|
||||
// Readable like the directory: mmdebstrap's hooks copy these into
|
||||
// the chroot. Applies to legacy files too, which a restrictive
|
||||
// umask may have left private, and a permissive one group-writable.
|
||||
let _ = ctx.command("chmod").arg("644").arg(&binary_path).status();
|
||||
}
|
||||
|
||||
log::info!(
|
||||
@@ -198,7 +227,12 @@ fn validate_keyring_dir(dir_uid: u32, mode: u32, euid: u32) -> Result<(), String
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download and import a PPA key using Launchpad API
|
||||
/// Download and import a PPA key using the Launchpad API
|
||||
///
|
||||
/// The signing key fingerprint is looked up through the shared HTTP client;
|
||||
/// the key itself is fetched from the keyserver with curl through the
|
||||
/// context, because the key file must land in the context's filesystem
|
||||
/// (which may be remote).
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `ctx` - Optional context to use
|
||||
@@ -229,33 +263,36 @@ pub async fn download_trust_ppa_key(
|
||||
ppa_name
|
||||
);
|
||||
|
||||
// Get PPA information from Launchpad API to get signing key fingerprint
|
||||
// Use the correct devel API endpoint
|
||||
let api_url = format!(
|
||||
"https://api.launchpad.net/1.0/~{}/+archive/ubuntu/{}",
|
||||
ppa_owner, ppa_name
|
||||
);
|
||||
// Get PPA information from the Launchpad API to get the signing key
|
||||
// fingerprint. The query is context-independent metadata, so it goes
|
||||
// through the shared HTTP client (timeouts, retries) rather than
|
||||
// shelling out to curl.
|
||||
let api_url = crate::launchpad::archive_url(ppa_owner, ppa_name);
|
||||
log::debug!("Querying Launchpad API: {}", api_url);
|
||||
|
||||
let api_response = ctx
|
||||
.command("curl")
|
||||
.arg("-s")
|
||||
.arg("-f")
|
||||
.arg("-H")
|
||||
.arg("Accept: application/json")
|
||||
.arg(&api_url)
|
||||
.output()?;
|
||||
|
||||
if !api_response.status.success() {
|
||||
let response = distro_info::http_get_retried(&api_url).await.map_err(|e| {
|
||||
format!(
|
||||
"Failed to query Launchpad API for PPA {}/{}: {}",
|
||||
ppa_owner, ppa_name, e
|
||||
)
|
||||
})?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"Failed to query Launchpad API for PPA {}/{}",
|
||||
ppa_owner, ppa_name
|
||||
"Failed to query Launchpad API for PPA {}/{}: HTTP {}",
|
||||
ppa_owner,
|
||||
ppa_name,
|
||||
response.status()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
// Parse the JSON response to extract the signing key fingerprint
|
||||
let api_response_str = String::from_utf8_lossy(&api_response.stdout);
|
||||
let api_response_str = response.text().await.map_err(|e| {
|
||||
format!(
|
||||
"Failed to read the Launchpad API response for PPA {}/{}: {}",
|
||||
ppa_owner, ppa_name, e
|
||||
)
|
||||
})?;
|
||||
let ppa_response: LaunchpadPpaResponse =
|
||||
serde_json::from_str(&api_response_str).map_err(|e| {
|
||||
format!(
|
||||
@@ -268,10 +305,7 @@ pub async fn download_trust_ppa_key(
|
||||
log::debug!("Found PPA signing key fingerprint: {}", fingerprint);
|
||||
|
||||
// Download the actual key from the keyserver using the fingerprint
|
||||
let keyserver_url = format!(
|
||||
"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{}",
|
||||
fingerprint
|
||||
);
|
||||
let keyserver_url = keyserver_lookup_url(&fingerprint);
|
||||
log::debug!("Downloading key from keyserver: {}", keyserver_url);
|
||||
|
||||
let mut curl_cmd = ctx.command("curl");
|
||||
@@ -306,12 +340,26 @@ pub async fn download_trust_ppa_key(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The data-driven template renders the lookup URL the hardcoded
|
||||
/// format! used to build (verified against the live keyserver)
|
||||
#[test]
|
||||
fn keyserver_lookup_url_substitutes_the_fingerprint() {
|
||||
assert_eq!(
|
||||
keyserver_lookup_url("0123456789ABCDEF"),
|
||||
"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x0123456789ABCDEF"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_keyring_dir_accepts_private_dir_owned_by_current_user() {
|
||||
assert!(validate_keyring_dir(1000, 0o700, 1000).is_ok());
|
||||
assert!(validate_keyring_dir(1000, 0o750, 1000).is_ok());
|
||||
assert!(validate_keyring_dir(1000, 0o1744, 1000).is_ok());
|
||||
assert!(validate_keyring_dir(0, 0o700, 0).is_ok());
|
||||
// The world-readable modes the cache now uses: readable so that
|
||||
// mmdebstrap's unshare-mode hooks can copy the keyrings, while the
|
||||
// ownership and no-write checks keep the planting guard.
|
||||
assert!(validate_keyring_dir(1000, 0o755, 1000).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+7
-7
@@ -137,7 +137,7 @@ impl ChecksumKind {
|
||||
}
|
||||
|
||||
/// Human-readable algorithm name, for error messages
|
||||
fn name(self) -> &'static str {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ChecksumKind::Md5 => "MD5",
|
||||
ChecksumKind::Sha1 => "SHA-1",
|
||||
@@ -782,7 +782,7 @@ pub async fn verify_suite(
|
||||
/// GET a URL, returning None on any HTTP error, non-success status, or body
|
||||
/// read failure (Release files are probed, so absence is a normal outcome)
|
||||
async fn fetch_optional(url: &str) -> Option<Vec<u8>> {
|
||||
match reqwest::get(url).await {
|
||||
match crate::distro_info::http_get_retried(url).await {
|
||||
Ok(response) if response.status().is_success() => match response.bytes().await {
|
||||
Ok(bytes) => return Some(bytes.to_vec()),
|
||||
Err(e) => debug!("Reading the body of '{url}' failed: {e}"),
|
||||
@@ -811,7 +811,7 @@ async fn fetch_keyring_cached(url: &str) -> Result<Vec<u8>, Box<dyn Error + Send
|
||||
return Ok(cached.clone());
|
||||
}
|
||||
|
||||
let response = reqwest::get(url).await?;
|
||||
let response = crate::distro_info::http_get_retried(url).await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"downloading keyring from '{url}' failed with HTTP {}",
|
||||
@@ -851,7 +851,7 @@ fn parse_ppa_url(ppa_base_url: &str) -> Option<(String, String)> {
|
||||
.strip_prefix("https://")
|
||||
.or_else(|| ppa_base_url.strip_prefix("http://"))?;
|
||||
let (host, path) = rest.split_once('/')?;
|
||||
if host != "ppa.launchpadcontent.net" {
|
||||
if host != crate::launchpad::ppa_content_host() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -886,8 +886,8 @@ pub async fn ppa_keyring_bytes(
|
||||
return Ok(cached.clone());
|
||||
}
|
||||
|
||||
let api_url = format!("https://api.launchpad.net/1.0/~{owner}/+archive/ubuntu/{name}");
|
||||
let response = reqwest::get(&api_url).await?;
|
||||
let api_url = crate::launchpad::archive_url(&owner, &name);
|
||||
let response = crate::distro_info::http_get_retried(&api_url).await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"querying the Launchpad API for the signing key of PPA \
|
||||
@@ -905,7 +905,7 @@ pub async fn ppa_keyring_bytes(
|
||||
.into());
|
||||
}
|
||||
|
||||
let key_url = format!("https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{fingerprint}");
|
||||
let key_url = crate::apt::keyring::keyserver_lookup_url(&fingerprint);
|
||||
let armored = fetch_keyring_cached(&key_url).await?;
|
||||
let keyring = dearmor(&armored)
|
||||
.map_err(|e| format!("invalid PGP armor in the key of PPA '{owner}/{name}': {e}"))?;
|
||||
|
||||
+254
-182
@@ -14,11 +14,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::context::Context;
|
||||
use crate::debian::{
|
||||
ChecksumEntry, ControlInfo, FileChecksums, FilesList, parse_changelog_entry_from_str,
|
||||
};
|
||||
|
||||
use super::parse_checksum_field;
|
||||
use crate::debian::{ChecksumEntry, ControlInfo, FileChecksums, FilesList};
|
||||
|
||||
/// Digests of one artifact.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -59,7 +55,7 @@ pub struct BinaryMetadataOptions {
|
||||
/// `dpkg-genchanges -b`: sorted `Binary` list, encounter-order `Architecture`
|
||||
/// accumulation, sorted `Description` lines formatted like dpkg, `.buildinfo`
|
||||
/// registration in `debian/files`, and binary-NMU handling (`Source:
|
||||
/// pkg (prev)` + previous `.dsc` redistribution when present).
|
||||
/// pkg (prev)` + `Binary-Only-Changes`, with no source files distributed).
|
||||
pub fn generate_binary_metadata(
|
||||
ctx: &Arc<Context>,
|
||||
package_dir: &Path,
|
||||
@@ -70,14 +66,25 @@ pub fn generate_binary_metadata(
|
||||
// Metadata sources inside the context
|
||||
// ------------------------------------------------------------------
|
||||
let changelog_content = ctx.read_file(&package_dir.join("debian/changelog"))?;
|
||||
let entry = parse_changelog_entry_from_str(&changelog_content)?;
|
||||
let mut entries =
|
||||
crate::debian::changelog::parse_changelog_entries_from_str(&changelog_content, Some(2))?;
|
||||
let entry = entries.remove(0);
|
||||
let previous_entry = entries.into_iter().next();
|
||||
|
||||
let control_content = ctx.read_file(&package_dir.join("debian/control"))?;
|
||||
let control = ControlInfo::parse_content(&control_content)?;
|
||||
|
||||
let files_content = ctx
|
||||
.read_file(&package_dir.join("debian/files"))
|
||||
.unwrap_or_default();
|
||||
// A missing `debian/files` is tolerated (first binary build in a fresh
|
||||
// tree has nothing registered yet; that surfaces below as the "no binary
|
||||
// artifacts" error), like `FilesList::load`. Any other read failure must
|
||||
// not be silently mistaken for an empty registry.
|
||||
let files_path = package_dir.join("debian/files");
|
||||
let files_content = if ctx.exists(&files_path)? {
|
||||
ctx.read_file(&files_path)
|
||||
.map_err(|e| format!("cannot read '{}': {}", files_path.display(), e))?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let mut files_list = FilesList::parse(&files_content)?;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -102,6 +109,9 @@ pub fn generate_binary_metadata(
|
||||
let entry_hashes = hashes
|
||||
.remove(name)
|
||||
.ok_or_else(|| format!("artifact '{name}' listed in debian/files but not found"))?;
|
||||
// SHA-512 stays unknown here: like dpkg-genbuildinfo, no SHA-512
|
||||
// digest is computed for the artifacts, and an empty digest keeps
|
||||
// the `Checksums-Sha512` field of the `.buildinfo` omitted.
|
||||
checksums.insert_entry(
|
||||
name,
|
||||
ChecksumEntry {
|
||||
@@ -109,6 +119,7 @@ pub fn generate_binary_metadata(
|
||||
md5: entry_hashes.md5,
|
||||
sha1: entry_hashes.sha1,
|
||||
sha256: entry_hashes.sha256,
|
||||
sha512: String::new(),
|
||||
},
|
||||
);
|
||||
// Architecture accumulation in encounter order (dpkg-genchanges).
|
||||
@@ -124,28 +135,24 @@ pub fn generate_binary_metadata(
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Binary-NMU: redistribute the previous source when present
|
||||
// Binary-NMU: reference the previous source version, textually only
|
||||
// ------------------------------------------------------------------
|
||||
let sversion = entry.version.no_epoch();
|
||||
let mut source_display = entry.source.clone();
|
||||
let mut binary_only_changes = None;
|
||||
|
||||
if entry.binary_only
|
||||
&& let Ok(prev_entry) = crate::debian::changelog::parse_previous_version_from_str(
|
||||
&ctx.read_file(&package_dir.join("debian/changelog"))?,
|
||||
)
|
||||
&& let Some(prev) = prev_entry
|
||||
{
|
||||
source_display = format!("{} ({})", entry.source, prev);
|
||||
binary_only_changes = Some(format!(
|
||||
"{}\n\n -- {} <{}> {}",
|
||||
entry.changes_field, entry.maintainer_name, entry.maintainer_email, entry.date_raw
|
||||
));
|
||||
let prev_version = crate::debian::DebianVersion::parse(&prev)?;
|
||||
let dsc_name = format!("{}_{}.dsc", entry.source, prev_version.no_epoch());
|
||||
let dsc_path = upload_dir.join(&dsc_name);
|
||||
if ctx.exists(&dsc_path)? {
|
||||
include_dsc_artifacts(ctx, upload_dir, &dsc_name, &mut checksums)?;
|
||||
if entry.binary_only {
|
||||
// Like dpkg-genchanges/genbuildinfo, a binary-only upload references
|
||||
// the previous source version in the `Source` field and records the
|
||||
// entry in `Binary-Only-Changes`, but distributes NO source files:
|
||||
// the previous `.dsc` and its tarballs already sit in the archive,
|
||||
// and are not re-uploaded even when present next to the tree.
|
||||
if let Some(prev) = &previous_entry {
|
||||
source_display = format!("{} ({})", entry.source, prev.version.full());
|
||||
binary_only_changes = Some(format!(
|
||||
"{}\n\n -- {} <{}> {}",
|
||||
entry.changes_field, entry.maintainer_name, entry.maintainer_email, entry.date_raw
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,9 +206,13 @@ pub fn generate_binary_metadata(
|
||||
// ------------------------------------------------------------------
|
||||
// Installed-Build-Depends closure over the context status database
|
||||
// ------------------------------------------------------------------
|
||||
// Like the source-build path, a status database that cannot be read is
|
||||
// a hard error: silently treating it as empty would drop (or gut) the
|
||||
// `Installed-Build-Depends` field of the produced metadata.
|
||||
let status_path = Path::new("/var/lib/dpkg/status");
|
||||
let status_content = ctx
|
||||
.read_file(Path::new("/var/lib/dpkg/status"))
|
||||
.unwrap_or_default();
|
||||
.read_file(status_path)
|
||||
.map_err(|e| format!("cannot read status file '{}': {}", status_path.display(), e))?;
|
||||
let bd_fields = [
|
||||
control.source.get("Build-Depends").unwrap_or(""),
|
||||
control.source.get("Build-Depends-Arch").unwrap_or(""),
|
||||
@@ -264,6 +275,9 @@ pub fn generate_binary_metadata(
|
||||
md5: h.md5.clone(),
|
||||
sha1: h.sha1.clone(),
|
||||
sha256: h.sha256.clone(),
|
||||
// No SHA-512 digest available (see above); keeps the
|
||||
// `Checksums-Sha512` `.buildinfo` field omitted.
|
||||
sha512: String::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -277,6 +291,7 @@ pub fn generate_binary_metadata(
|
||||
date: entry.date_raw.clone(),
|
||||
source: source_display,
|
||||
binaries,
|
||||
binary_only: entry.binary_only,
|
||||
built_for_profiles: opts.profiles.clone(),
|
||||
architecture: arch_values.join(" "),
|
||||
version: entry.version.full(),
|
||||
@@ -311,21 +326,34 @@ fn hashes_in_context(
|
||||
.map(|n| (n.clone(), ArtifactHashes::default()))
|
||||
.collect();
|
||||
|
||||
// Sizes.
|
||||
// Sizes. A failed `stat` must fail the metadata generation: an unchecked
|
||||
// exit status would leave the default size 0 in the produced
|
||||
// `.changes`/`.buildinfo` checksum entries.
|
||||
let output = ctx
|
||||
.command("stat")
|
||||
.current_dir(dir)
|
||||
.arg("-c")
|
||||
.arg("%s %n")
|
||||
.args(names)
|
||||
.output()?;
|
||||
.output()
|
||||
.map_err(|e| format!("failed to run 'stat' inside the build context: {e}"))?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"'stat' failed inside the build context: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
for line in stdout.lines() {
|
||||
let Some((size, name)) = line.trim().split_once(' ') else {
|
||||
continue;
|
||||
};
|
||||
let size = size
|
||||
.parse::<u64>()
|
||||
.map_err(|_| format!("'stat' reported an invalid size '{size}' for '{name}'"))?;
|
||||
if let Some(slot) = out.get_mut(name) {
|
||||
slot.size = size.parse().unwrap_or(0);
|
||||
slot.size = size;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,85 +395,6 @@ fn hashes_in_context(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Pull the `.dsc` checksums (and its referenced tarballs) into the
|
||||
/// checksum registry, mirroring how binary-NMU uploads redistribute the
|
||||
/// previous source.
|
||||
fn include_dsc_artifacts(
|
||||
ctx: &Arc<Context>,
|
||||
upload_dir: &Path,
|
||||
dsc_name: &str,
|
||||
checksums: &mut FileChecksums,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let dsc_content = ctx.read_file(&upload_dir.join(dsc_name))?;
|
||||
let para = crate::debian::control::parse_paragraphs(
|
||||
crate::debian::control::strip_clearsigned_armour(&dsc_content),
|
||||
)
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| format!("'{dsc_name}' is empty"))?;
|
||||
|
||||
// Names and partial checksums are filled from the very same validated
|
||||
// lines, so a listed name can never miss its checksum entry.
|
||||
// Distribution order follows the Checksums fields (Checksums-Sha1 then
|
||||
// Checksums-Sha256), like dpkg-genchanges; the `Files` field only
|
||||
// supplements the md5 digests.
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
let mut partials: BTreeMap<String, super::PartialChecksum> = BTreeMap::new();
|
||||
for field in ["Checksums-Sha1", "Checksums-Sha256", "Files"] {
|
||||
let Some(value) = para.get(field) else {
|
||||
continue;
|
||||
};
|
||||
for cl in parse_checksum_field(field, value)
|
||||
.map_err(|e| format!("cannot parse '{dsc_name}': {e}"))?
|
||||
{
|
||||
let slot = partials.entry(cl.name.clone()).or_default();
|
||||
match field {
|
||||
"Checksums-Sha1" => slot.sha1 = Some(cl.digest),
|
||||
"Checksums-Sha256" => slot.sha256 = Some(cl.digest),
|
||||
_ => slot.md5 = Some(cl.digest),
|
||||
}
|
||||
slot.size = Some(cl.size);
|
||||
if field != "Files" && !names.contains(&cl.name) {
|
||||
names.push(cl.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The .dsc itself is hashed fresh (it may be signed/rewritten); the
|
||||
// tarballs reuse the .dsc-recorded digests, like dpkg-genchanges does.
|
||||
let dsc_hashes =
|
||||
hashes_in_context(ctx, upload_dir, std::slice::from_ref(&dsc_name.to_string()))?;
|
||||
if let Some(h) = dsc_hashes.get(dsc_name) {
|
||||
checksums.insert_entry(
|
||||
dsc_name,
|
||||
ChecksumEntry {
|
||||
size: h.size,
|
||||
md5: h.md5.clone(),
|
||||
sha1: h.sha1.clone(),
|
||||
sha256: h.sha256.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
for name in &names {
|
||||
if name == dsc_name {
|
||||
continue;
|
||||
}
|
||||
let p = partials
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("file '{name}' listed in '{dsc_name}' has no checksum entry"))?;
|
||||
checksums.insert_entry(
|
||||
name,
|
||||
ChecksumEntry {
|
||||
size: p.size.unwrap_or(0),
|
||||
md5: p.md5.clone().unwrap_or_default(),
|
||||
sha1: p.sha1.clone().unwrap_or_default(),
|
||||
sha256: p.sha256.clone().unwrap_or_default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -483,101 +432,224 @@ mod tests {
|
||||
assert!(!environment.contains("DEBIAN_FRONTEND"), "{environment}");
|
||||
}
|
||||
|
||||
/// A minimal previous-version `.dsc` with a 3-column Checksums-Sha1
|
||||
/// field, a 4-column Checksums-Sha256 line and a 3-column `Files`.
|
||||
/// Regression: the old code filled `names` from any line with a third
|
||||
/// column but `partials` only from exactly-3-column lines, so the
|
||||
/// "bogus" name landed in `names` alone and `&partials["bogus"]`
|
||||
/// panicked. It must produce a build error instead.
|
||||
/// A binary-only (binNMU) build whose changelog cannot yield the
|
||||
/// previous entry (malformed second header, unbalanced parenthesis) must
|
||||
/// fail the metadata generation with a diagnostic naming the problem,
|
||||
/// instead of silently emitting a plain `Source:` `.changes` with no
|
||||
/// `Binary-Only-Changes` and no previous-version reference.
|
||||
#[test]
|
||||
fn dsc_four_column_checksum_line_errors_instead_of_panicking() {
|
||||
let dsc_name = "hello_1.0-1.dsc";
|
||||
let dsc = "\
|
||||
Format: 3.0 (native)
|
||||
fn binary_only_prev_version_parse_failure_errors_instead_of_wrong_metadata() {
|
||||
let changelog = "\
|
||||
hello (1.0-1+b1) unstable; urgency=medium, binary-only=yes
|
||||
|
||||
* Binary-only rebuild.
|
||||
|
||||
-- A B <a@b.c> Mon, 01 Jan 2024 00:00:00 +0000
|
||||
|
||||
hello (1.0-1 unstable; urgency=medium
|
||||
|
||||
* Previous entry with an unbalanced parenthesis.
|
||||
|
||||
-- A B <a@b.c> Sun, 31 Dec 2023 00:00:00 +0000
|
||||
";
|
||||
let control = "\
|
||||
Source: hello
|
||||
Binary: hello
|
||||
Architecture: any
|
||||
Version: 1.0-1
|
||||
Section: devel
|
||||
Priority: optional
|
||||
Maintainer: A B <a@b.c>
|
||||
Checksums-Sha1:
|
||||
aaa111 12 hello_1.0.orig.tar.xz
|
||||
Checksums-Sha256:
|
||||
bbb222 12 bogus hello_1.0-1.debian.tar.xz
|
||||
Files:
|
||||
ddd333 12 hello_1.0.orig.tar.xz
|
||||
|
||||
Package: hello
|
||||
Architecture: all
|
||||
Description: test package
|
||||
";
|
||||
let base = tempfile::tempdir().expect("tempdir");
|
||||
std::fs::write(base.path().join(dsc_name), dsc).expect("write dsc");
|
||||
let tree = base.path().join("hello-1.0");
|
||||
std::fs::create_dir_all(tree.join("debian")).expect("mkdir tree");
|
||||
std::fs::write(tree.join("debian/changelog"), changelog).expect("write changelog");
|
||||
std::fs::write(tree.join("debian/control"), control).expect("write control");
|
||||
std::fs::write(
|
||||
tree.join("debian/files"),
|
||||
"hello_1.0-1+b1_all.deb devel optional\n",
|
||||
)
|
||||
.expect("write files");
|
||||
std::fs::write(base.path().join("hello_1.0-1+b1_all.deb"), "deb payload")
|
||||
.expect("write deb");
|
||||
|
||||
let ctx = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"),
|
||||
);
|
||||
let mut checksums = FileChecksums::new();
|
||||
let err = include_dsc_artifacts(&ctx, base.path(), dsc_name, &mut checksums)
|
||||
.expect_err("malformed Checksums-Sha256 line must fail the build");
|
||||
let opts = BinaryMetadataOptions {
|
||||
profiles: Vec::new(),
|
||||
vendor: "debian".to_string(),
|
||||
exported_env: BTreeMap::new(),
|
||||
build_arch: "amd64".to_string(),
|
||||
host_arch: "amd64".to_string(),
|
||||
};
|
||||
let err = generate_binary_metadata(&ctx, &tree, base.path(), &opts)
|
||||
.expect_err("binary-only build with an unparseable changelog must fail");
|
||||
let err = err.to_string();
|
||||
assert!(err.contains("Checksums-Sha256"), "{err}");
|
||||
assert!(err.contains("hello_1.0-1.debian.tar.xz"), "{err}");
|
||||
assert!(err.contains("unbalanced parenthesis"), "{err}");
|
||||
assert!(err.contains("1.0-1 unstable"), "{err}");
|
||||
}
|
||||
|
||||
/// Happy path: tarball entries are assembled from the Checksums fields
|
||||
/// (sha1/sha256) and merged with the legacy 5-column `Files` md5, in
|
||||
/// Checksums-Sha1 order, with the `.dsc` itself hashed fresh first.
|
||||
/// An unreadable `debian/files` (e.g. permissions) must fail the
|
||||
/// metadata generation with an error naming the read failure, instead of
|
||||
/// being silently treated as an empty registry and reported as "no
|
||||
/// binary artifacts found". A *missing* file stays tolerated (first
|
||||
/// build in a fresh tree); the distinction matters.
|
||||
#[test]
|
||||
fn include_dsc_artifacts_merges_legacy_files_layout() {
|
||||
let dsc_name = "hello_1.0-1.dsc";
|
||||
let tarball = "hello_1.0.orig.tar.xz";
|
||||
let dsc = "\
|
||||
Format: 3.0 (quilt)
|
||||
fn unreadable_debian_files_errors_instead_of_empty_registry() {
|
||||
if crate::utils::root::is_root().unwrap_or(false) {
|
||||
// Root can read files regardless of permissions.
|
||||
return;
|
||||
}
|
||||
let changelog = "\
|
||||
hello (1.0-1) unstable; urgency=medium
|
||||
|
||||
* Regular build.
|
||||
|
||||
-- A B <a@b.c> Mon, 01 Jan 2024 00:00:00 +0000
|
||||
";
|
||||
let control = "\
|
||||
Source: hello
|
||||
Binary: hello
|
||||
Architecture: any
|
||||
Version: 1.0-1
|
||||
Section: devel
|
||||
Priority: optional
|
||||
Maintainer: A B <a@b.c>
|
||||
Checksums-Sha1:
|
||||
aaa111 12 hello_1.0.orig.tar.xz
|
||||
Checksums-Sha256:
|
||||
bbb222 12 hello_1.0.orig.tar.xz
|
||||
Files:
|
||||
ddd333 12 devel optional hello_1.0.orig.tar.xz
|
||||
|
||||
Package: hello
|
||||
Architecture: all
|
||||
Description: test package
|
||||
";
|
||||
let base = tempfile::tempdir().expect("tempdir");
|
||||
std::fs::write(base.path().join(dsc_name), dsc).expect("write dsc");
|
||||
std::fs::write(base.path().join(tarball), "tarball bytes").expect("write tarball");
|
||||
let tree = base.path().join("hello-1.0");
|
||||
std::fs::create_dir_all(tree.join("debian")).expect("mkdir tree");
|
||||
std::fs::write(tree.join("debian/changelog"), changelog).expect("write changelog");
|
||||
std::fs::write(tree.join("debian/control"), control).expect("write control");
|
||||
let files_path = tree.join("debian/files");
|
||||
std::fs::write(&files_path, "hello_1.0-1_all.deb devel optional\n").expect("write files");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&files_path, std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod files");
|
||||
}
|
||||
|
||||
let ctx = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"),
|
||||
);
|
||||
let mut checksums = FileChecksums::new();
|
||||
include_dsc_artifacts(&ctx, base.path(), dsc_name, &mut checksums)
|
||||
.expect("valid dsc must parse");
|
||||
let opts = BinaryMetadataOptions {
|
||||
profiles: Vec::new(),
|
||||
vendor: "debian".to_string(),
|
||||
exported_env: BTreeMap::new(),
|
||||
build_arch: "amd64".to_string(),
|
||||
host_arch: "amd64".to_string(),
|
||||
};
|
||||
let err = generate_binary_metadata(&ctx, &tree, base.path(), &opts)
|
||||
.expect_err("unreadable debian/files must fail with a read error");
|
||||
let err = err.to_string();
|
||||
assert!(err.contains("cannot read"), "{err}");
|
||||
assert!(err.contains("debian/files"), "{err}");
|
||||
#[cfg(unix)]
|
||||
assert!(err.contains("Permission denied"), "{err}");
|
||||
}
|
||||
|
||||
let collected: Vec<(String, crate::debian::ChecksumEntry)> = checksums
|
||||
.iter()
|
||||
.map(|(k, e)| (k.clone(), e.clone()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
collected
|
||||
.iter()
|
||||
.map(|(k, _)| k.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![dsc_name, tarball],
|
||||
".dsc first, then Checksums-Sha1 order"
|
||||
/// A binary-only (binNMU) build references the previous source version
|
||||
/// (`Source: pkg (prev)`, `Binary-Only-Changes`) but must NOT
|
||||
/// redistribute any source file: like dpkg-genchanges/genbuildinfo, the
|
||||
/// previous `.dsc` and its tarballs stay out of both documents even when
|
||||
/// they exist next to the artifacts.
|
||||
#[test]
|
||||
fn binary_only_metadata_references_previous_source_without_redistributing_it() {
|
||||
let changelog = "\
|
||||
hello (1.0-1+b1) unstable; urgency=medium, binary-only=yes
|
||||
|
||||
* Binary-only rebuild.
|
||||
|
||||
-- A B <a@b.c> Mon, 01 Jan 2024 00:00:00 +0000
|
||||
|
||||
hello (1.0-1) unstable; urgency=medium
|
||||
|
||||
* Initial release.
|
||||
|
||||
-- A B <a@b.c> Sun, 31 Dec 2023 00:00:00 +0000
|
||||
";
|
||||
let control = "\
|
||||
Source: hello
|
||||
Section: devel
|
||||
Priority: optional
|
||||
Maintainer: A B <a@b.c>
|
||||
|
||||
Package: hello
|
||||
Architecture: all
|
||||
Description: test package
|
||||
";
|
||||
let base = tempfile::tempdir().expect("tempdir");
|
||||
let tree = base.path().join("hello-1.0");
|
||||
std::fs::create_dir_all(tree.join("debian")).expect("mkdir tree");
|
||||
std::fs::write(tree.join("debian/changelog"), changelog).expect("write changelog");
|
||||
std::fs::write(tree.join("debian/control"), control).expect("write control");
|
||||
std::fs::write(
|
||||
tree.join("debian/files"),
|
||||
"hello_1.0-1+b1_all.deb devel optional\n",
|
||||
)
|
||||
.expect("write files");
|
||||
std::fs::write(base.path().join("hello_1.0-1+b1_all.deb"), "deb payload")
|
||||
.expect("write deb");
|
||||
|
||||
// The trap: the previous source artifacts sit right next to the
|
||||
// binaries, as they would after a source build. dpkg does not
|
||||
// redistribute them for a binary-only upload, and neither must we.
|
||||
std::fs::write(
|
||||
base.path().join("hello_1.0-1.dsc"),
|
||||
"Format: 3.0 (quilt)\nSource: hello\nBinary: hello\nArchitecture: any\nVersion: \
|
||||
1.0-1\nMaintainer: A B <a@b.c>\nChecksums-Sha1:\n aaa111 12 \
|
||||
hello_1.0.orig.tar.xz\n",
|
||||
)
|
||||
.expect("write previous dsc");
|
||||
std::fs::write(base.path().join("hello_1.0.orig.tar.xz"), "tarball bytes")
|
||||
.expect("write previous tarball");
|
||||
|
||||
let ctx = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"),
|
||||
);
|
||||
let opts = BinaryMetadataOptions {
|
||||
profiles: Vec::new(),
|
||||
vendor: "debian".to_string(),
|
||||
exported_env: BTreeMap::new(),
|
||||
build_arch: "amd64".to_string(),
|
||||
host_arch: "amd64".to_string(),
|
||||
};
|
||||
let (buildinfo_path, changes_path) =
|
||||
generate_binary_metadata(&ctx, &tree, base.path(), &opts)
|
||||
.expect("binNMU metadata generation must succeed");
|
||||
|
||||
// The .dsc is hashed fresh from disk.
|
||||
let dsc_entry = &collected[0].1;
|
||||
assert_eq!(dsc_entry.size, dsc.len() as u64);
|
||||
assert_eq!(dsc_entry.md5.len(), 32);
|
||||
assert_eq!(dsc_entry.sha1.len(), 40);
|
||||
assert_eq!(dsc_entry.sha256.len(), 64);
|
||||
let changes = std::fs::read_to_string(&changes_path).expect("read changes");
|
||||
let buildinfo = std::fs::read_to_string(&buildinfo_path).expect("read buildinfo");
|
||||
|
||||
// The tarball reuses the .dsc-recorded digests, including the
|
||||
// legacy 5-column `Files` md5 (section/priority skipped).
|
||||
let tar_entry = &collected[1].1;
|
||||
assert_eq!(tar_entry.size, 12);
|
||||
assert_eq!(tar_entry.md5, "ddd333");
|
||||
assert_eq!(tar_entry.sha1, "aaa111");
|
||||
assert_eq!(tar_entry.sha256, "bbb222");
|
||||
// The previous version is referenced textually.
|
||||
assert!(
|
||||
changes.contains("Source: hello (1.0-1)"),
|
||||
"changes must reference the previous version: {changes}"
|
||||
);
|
||||
assert!(
|
||||
buildinfo.contains("Binary-Only-Changes"),
|
||||
"buildinfo must record the binary-only entry: {buildinfo}"
|
||||
);
|
||||
// ... but no source file is distributed, on either side.
|
||||
for (doc, text) in [("changes", &changes), ("buildinfo", &buildinfo)] {
|
||||
assert!(
|
||||
!text.contains("hello_1.0-1.dsc"),
|
||||
"{doc} must not redistribute the previous .dsc: {text}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains("hello_1.0.orig.tar.xz"),
|
||||
"{doc} must not redistribute the previous tarball: {text}"
|
||||
);
|
||||
}
|
||||
// The distributed set is exactly the binary artifacts + buildinfo.
|
||||
assert!(
|
||||
changes.contains("hello_1.0-1+b1_all.deb") && changes.contains(".buildinfo"),
|
||||
"changes must distribute the deb and the buildinfo: {changes}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,6 +207,13 @@ pub fn installed_build_depends_from_content(
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
entries.dedup_by(|a, b| a.0 == b.0);
|
||||
|
||||
// With no reachable entries, return an empty value so `render_buildinfo`
|
||||
// omits the field entirely; a leading `\n` alone would render a
|
||||
// malformed `Installed-Build-Depends:` with only a blank continuation.
|
||||
if entries.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
|
||||
// Leading `\n`: pre-wrapped multiline field, dpkg-style.
|
||||
let mut out = String::from("\n");
|
||||
out.push_str(
|
||||
@@ -289,6 +296,12 @@ pub fn render_buildinfo(input: &BuildInfoInput) -> Paragraph {
|
||||
p.set("Checksums-Md5", &input.checksums.field_md5());
|
||||
p.set("Checksums-Sha1", &input.checksums.field_sha1());
|
||||
p.set("Checksums-Sha256", &input.checksums.field_sha256());
|
||||
// Only-if-populated: entries merged from a `.dsc` carry no SHA-512
|
||||
// (dpkg only records sha1/sha256 there), and an incomplete checksum
|
||||
// list must never be rendered.
|
||||
if let Some(sha512) = input.checksums.field_sha512() {
|
||||
p.set("Checksums-Sha512", &sha512);
|
||||
}
|
||||
}
|
||||
p.set("Build-Origin", &input.build_origin);
|
||||
p.set("Build-Architecture", &input.build_architecture);
|
||||
@@ -378,6 +391,68 @@ Architecture: amd64
|
||||
assert!(!ibd.contains("not-installed"));
|
||||
}
|
||||
|
||||
/// With no installed entries reachable (empty status database), the
|
||||
/// computed value must be EMPTY so `render_buildinfo` omits the
|
||||
/// `Installed-Build-Depends` field entirely, instead of emitting a
|
||||
/// malformed field with only a blank continuation line.
|
||||
#[test]
|
||||
fn installed_build_depends_without_entries_is_empty_and_omitted() {
|
||||
let ibd = installed_build_depends_from_content("", &["libc6"]).unwrap();
|
||||
assert_eq!(
|
||||
ibd, "",
|
||||
"zero entries must yield an empty value, not \"\\n\""
|
||||
);
|
||||
|
||||
let input = BuildInfoInput {
|
||||
source: "hello".to_string(),
|
||||
binaries: vec!["hello".to_string()],
|
||||
architecture: "amd64".to_string(),
|
||||
version: "1.0".to_string(),
|
||||
binary_only_changes: None,
|
||||
build_origin: "debian".to_string(),
|
||||
build_architecture: "amd64".to_string(),
|
||||
build_date: "Sat, 22 Aug 2026 23:08:42 +0200".to_string(),
|
||||
checksums: FileChecksums::new(),
|
||||
installed_build_depends: ibd,
|
||||
environment: String::new(),
|
||||
};
|
||||
let p = render_buildinfo(&input);
|
||||
assert!(
|
||||
p.get("Installed-Build-Depends").is_none(),
|
||||
"empty value must omit the field entirely"
|
||||
);
|
||||
}
|
||||
|
||||
/// With installed entries, the value keeps the dpkg-style leading `\n`
|
||||
/// (pre-wrapped multiline field) and the field is rendered.
|
||||
#[test]
|
||||
fn installed_build_depends_with_entries_renders_field() {
|
||||
let status = "\
|
||||
Package: gcc
|
||||
Status: install ok installed
|
||||
Version: 13.2
|
||||
Architecture: amd64
|
||||
";
|
||||
let ibd = installed_build_depends_from_content(status, &["gcc"]).unwrap();
|
||||
assert_eq!(ibd, "\ngcc (= 13.2)");
|
||||
|
||||
let input = BuildInfoInput {
|
||||
source: "hello".to_string(),
|
||||
binaries: vec!["hello".to_string()],
|
||||
architecture: "amd64".to_string(),
|
||||
version: "1.0".to_string(),
|
||||
binary_only_changes: None,
|
||||
build_origin: "debian".to_string(),
|
||||
build_architecture: "amd64".to_string(),
|
||||
build_date: "Sat, 22 Aug 2026 23:08:42 +0200".to_string(),
|
||||
checksums: FileChecksums::new(),
|
||||
installed_build_depends: ibd,
|
||||
environment: String::new(),
|
||||
};
|
||||
let p = render_buildinfo(&input);
|
||||
assert_eq!(p.get("Installed-Build-Depends"), Some("\ngcc (= 13.2)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_binary_field() {
|
||||
assert_eq!(wrap_long("abc"), "abc");
|
||||
@@ -425,4 +500,78 @@ Architecture: amd64
|
||||
);
|
||||
assert_eq!(p.get("Format"), Some("1.0"));
|
||||
}
|
||||
|
||||
/// `Checksums-Sha512` is emitted (after `Checksums-Sha256`) only when
|
||||
/// every distributed file has a SHA-512 digest; entries merged without
|
||||
/// one (e.g. taken from a `.dsc`) omit the field entirely instead of
|
||||
/// rendering an incomplete checksum list.
|
||||
#[test]
|
||||
fn checksums_sha512_emitted_only_when_populated() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let artifact = dir.path().join("hello_1.0_all.deb");
|
||||
std::fs::write(&artifact, b"deb payload").unwrap();
|
||||
|
||||
let mut checksums = FileChecksums::new();
|
||||
checksums.add_file(&artifact).unwrap();
|
||||
|
||||
let mk_input = |checksums: FileChecksums| BuildInfoInput {
|
||||
source: "hello".to_string(),
|
||||
binaries: vec![],
|
||||
architecture: "all".to_string(),
|
||||
version: "1.0".to_string(),
|
||||
binary_only_changes: None,
|
||||
build_origin: "debian".to_string(),
|
||||
build_architecture: "amd64".to_string(),
|
||||
build_date: "Sat, 22 Aug 2026 23:08:42 +0200".to_string(),
|
||||
checksums,
|
||||
installed_build_depends: String::new(),
|
||||
environment: String::new(),
|
||||
};
|
||||
|
||||
// All digests computed: the field is present and parses back.
|
||||
let p = render_buildinfo(&mk_input(checksums.clone()));
|
||||
let keys: Vec<&str> = p.iter().map(|(k, _)| k).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
vec![
|
||||
"Format",
|
||||
"Source",
|
||||
"Architecture",
|
||||
"Version",
|
||||
"Checksums-Md5",
|
||||
"Checksums-Sha1",
|
||||
"Checksums-Sha256",
|
||||
"Checksums-Sha512",
|
||||
"Build-Origin",
|
||||
"Build-Architecture",
|
||||
"Build-Date",
|
||||
]
|
||||
);
|
||||
let sha512_field = p.get("Checksums-Sha512").unwrap();
|
||||
let parsed =
|
||||
FileChecksums::parse_field(crate::debian::ChecksumKind::Sha512, sha512_field).unwrap();
|
||||
assert_eq!(parsed.len(), 1);
|
||||
assert_eq!(parsed[0].0, "hello_1.0_all.deb");
|
||||
assert_eq!(
|
||||
parsed[0].1.sha512,
|
||||
checksums.get("hello_1.0_all.deb").unwrap().sha512
|
||||
);
|
||||
|
||||
// An entry without SHA-512 (as merged from a `.dsc`) suppresses the
|
||||
// field; the other Checksums fields keep listing every file.
|
||||
checksums.insert_entry(
|
||||
"hello_1.0.orig.tar.xz",
|
||||
crate::debian::ChecksumEntry {
|
||||
size: 3,
|
||||
md5: checksums.get("hello_1.0_all.deb").unwrap().md5.clone(),
|
||||
sha1: String::new(),
|
||||
sha256: String::new(),
|
||||
sha512: String::new(),
|
||||
},
|
||||
);
|
||||
let p = render_buildinfo(&mk_input(checksums));
|
||||
assert!(p.get("Checksums-Sha512").is_none());
|
||||
let sha256_lines = p.get("Checksums-Sha256").unwrap().lines();
|
||||
assert_eq!(sha256_lines.filter(|l| !l.is_empty()).count(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,58 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::OrigSourceMode;
|
||||
use crate::debian::changelog::ChangelogEntry;
|
||||
use crate::debian::checksums::FileChecksums;
|
||||
use crate::debian::control::{Paragraph, write_paragraph};
|
||||
use crate::debian::files::FilesList;
|
||||
|
||||
/// Compression suffixes dpkg recognizes on source tarballs.
|
||||
const TARBALL_COMPRESSIONS: &[&str] = &[".gz", ".bz2", ".xz", ".lzma", ".zst"];
|
||||
|
||||
/// Whether this `.dsc`-listed file is an upstream orig tarball
|
||||
/// (`*.orig.tar.<ext>` or a component tarball `*.orig-<c>.tar.<ext>`),
|
||||
/// mirroring dpkg-genchanges' strip pattern `\.orig(-.+)?\.tar\.$ext`.
|
||||
pub fn is_orig_tarball(name: &str) -> bool {
|
||||
TARBALL_COMPRESSIONS.iter().any(|ext| {
|
||||
name.strip_suffix(ext)
|
||||
.and_then(|s| s.strip_suffix(".tar"))
|
||||
.is_some_and(|stem| stem.ends_with(".orig") || stem.contains(".orig-"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this `.dsc`-listed file is the Debian part of the source package
|
||||
/// (`*.debian.tar.<ext>` for the 3.0 formats, `*.diff.<ext>` for 1.0).
|
||||
pub fn is_debian_tarball_or_diff(name: &str) -> bool {
|
||||
TARBALL_COMPRESSIONS.iter().any(|ext| {
|
||||
name.ends_with(&format!(".debian.tar{ext}")) || name.ends_with(&format!(".diff{ext}"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the upload redistributes the upstream tarballs, mirroring the
|
||||
/// dpkg-genchanges source styles: `Always`/`Never` are the forced
|
||||
/// `-sa`/`-sd`, while `Auto` is the default `-si` — include them only when
|
||||
/// there is no previous changelog entry (first upload) or the source name or
|
||||
/// upstream version changed since it. Like dpkg, the comparison uses the
|
||||
/// epoch-less upstream version: a plain revision bump reuses the tarball
|
||||
/// already in the archive.
|
||||
pub fn include_orig_tarball(
|
||||
mode: OrigSourceMode,
|
||||
current: &ChangelogEntry,
|
||||
previous: Option<&ChangelogEntry>,
|
||||
) -> bool {
|
||||
match mode {
|
||||
OrigSourceMode::Always => true,
|
||||
OrigSourceMode::Never => false,
|
||||
OrigSourceMode::Auto => match previous {
|
||||
None => true,
|
||||
Some(prev) => {
|
||||
prev.source != current.source || prev.version.upstream != current.version.upstream
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything needed to render a `.changes` file.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChangesInput {
|
||||
@@ -17,6 +65,9 @@ pub struct ChangesInput {
|
||||
pub source: String,
|
||||
/// Sorted binary package names with artifacts (empty for source-only).
|
||||
pub binaries: Vec<String>,
|
||||
/// Whether the changelog entry is a binary-only (binNMU) upload
|
||||
/// (`Binary-Only: yes` field).
|
||||
pub binary_only: bool,
|
||||
/// Active build profiles (`Built-For-Profiles`); omitted when empty.
|
||||
pub built_for_profiles: Vec<String>,
|
||||
/// `Architecture` field value in encounter order (e.g. `source`,
|
||||
@@ -94,6 +145,9 @@ pub fn render_changes(input: &ChangesInput) -> Paragraph {
|
||||
let joined = input.binaries.join(" ");
|
||||
p.set("Binary", &wrap_long(&joined));
|
||||
}
|
||||
if input.binary_only {
|
||||
p.set("Binary-Only", "yes");
|
||||
}
|
||||
if !input.built_for_profiles.is_empty() {
|
||||
p.set("Built-For-Profiles", &input.built_for_profiles.join(" "));
|
||||
}
|
||||
@@ -159,6 +213,91 @@ pub fn save_changes(path: &Path, paragraph: &Paragraph) -> Result<(), Box<dyn st
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn orig_tarball_detection() {
|
||||
assert!(is_orig_tarball("pkg_1.0.orig.tar.gz"));
|
||||
assert!(is_orig_tarball("pkg_1.0.orig.tar.xz"));
|
||||
assert!(is_orig_tarball("pkg_1.0.orig.tar.zst"));
|
||||
assert!(is_orig_tarball("pkg_1.0~rc1.orig.tar.bz2"));
|
||||
// Component tarballs.
|
||||
assert!(is_orig_tarball("pkg_1.0.orig-docs.tar.xz"));
|
||||
assert!(is_orig_tarball("pkg_1.0.orig-vendor.tar.gz"));
|
||||
// Not orig tarballs.
|
||||
assert!(!is_orig_tarball("pkg_1.0.debian.tar.xz"));
|
||||
assert!(!is_debian_tarball_or_diff("pkg_1.0.orig.tar.xz"));
|
||||
assert!(!is_orig_tarball("pkg_1.0.tar.xz")); // native tarball
|
||||
assert!(!is_orig_tarball("pkg_1.0.dsc"));
|
||||
assert!(!is_orig_tarball("pkg_1.0.orig.tar")); // no compression suffix
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debian_tarball_detection() {
|
||||
assert!(is_debian_tarball_or_diff("pkg_1.0.debian.tar.xz"));
|
||||
assert!(is_debian_tarball_or_diff("pkg_1.0.diff.gz"));
|
||||
assert!(!is_debian_tarball_or_diff("pkg_1.0.orig.tar.xz"));
|
||||
assert!(!is_debian_tarball_or_diff("pkg_1.0.tar.xz"));
|
||||
}
|
||||
|
||||
/// Build a minimal changelog entry for one source/version pair.
|
||||
fn entry(src: &str, ver: &str) -> ChangelogEntry {
|
||||
crate::debian::changelog::parse_changelog_entries_from_str(
|
||||
&format!(
|
||||
"{src} ({ver}) unstable; urgency=medium\n\n * x\n\n \
|
||||
-- A B <a@b.c> Thu, 01 Jan 2026 00:00:00 +0000\n"
|
||||
),
|
||||
Some(1),
|
||||
)
|
||||
.unwrap()
|
||||
.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orig_inclusion_matrix() {
|
||||
let cur = entry("pkg", "1.4-2");
|
||||
let prev_same_upstream = entry("pkg", "1.4-1");
|
||||
let prev_new_upstream = entry("pkg", "2.0-1");
|
||||
let prev_renamed = entry("renamed", "1.4-1");
|
||||
|
||||
// -sa / -sd force the outcome.
|
||||
assert!(include_orig_tarball(
|
||||
OrigSourceMode::Always,
|
||||
&cur,
|
||||
Some(&prev_same_upstream)
|
||||
));
|
||||
assert!(!include_orig_tarball(
|
||||
OrigSourceMode::Never,
|
||||
&cur,
|
||||
Some(&prev_new_upstream)
|
||||
));
|
||||
|
||||
// -si: first upload includes; a revision bump excludes; a new
|
||||
// upstream version or a renamed source includes.
|
||||
assert!(include_orig_tarball(OrigSourceMode::Auto, &cur, None));
|
||||
assert!(!include_orig_tarball(
|
||||
OrigSourceMode::Auto,
|
||||
&cur,
|
||||
Some(&prev_same_upstream)
|
||||
));
|
||||
assert!(include_orig_tarball(
|
||||
OrigSourceMode::Auto,
|
||||
&cur,
|
||||
Some(&prev_new_upstream)
|
||||
));
|
||||
assert!(include_orig_tarball(
|
||||
OrigSourceMode::Auto,
|
||||
&cur,
|
||||
Some(&prev_renamed)
|
||||
));
|
||||
|
||||
// The epoch is not part of the comparison, like dpkg's version().
|
||||
let cur_epoch = entry("pkg", "2:1.4-2");
|
||||
assert!(!include_orig_tarball(
|
||||
OrigSourceMode::Auto,
|
||||
&cur_epoch,
|
||||
Some(&prev_same_upstream)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn description_formatting() {
|
||||
assert_eq!(
|
||||
@@ -196,6 +335,7 @@ mod tests {
|
||||
date: "Sat, 22 Aug 2026 10:00:00 +0000".to_string(),
|
||||
source: "pkg".to_string(),
|
||||
binaries: vec![],
|
||||
binary_only: false,
|
||||
built_for_profiles: vec![],
|
||||
architecture: "source".to_string(),
|
||||
version: "1.0".to_string(),
|
||||
|
||||
+136
-15
@@ -3,7 +3,7 @@
|
||||
//! sanitized environment recorded in `.buildinfo` files.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Number of parallel jobs to advertise in `DEB_BUILD_OPTIONS`.
|
||||
pub fn num_parallel() -> usize {
|
||||
@@ -12,12 +12,36 @@ pub fn num_parallel() -> usize {
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
/// Merge an inherited `DEB_BUILD_OPTIONS` value with options pkh computes
|
||||
/// itself.
|
||||
///
|
||||
/// `dpkg-buildpackage` prepends the environment's `DEB_BUILD_OPTIONS` to the
|
||||
/// options it derives (`parallel=N`, ...), so caller-set options such as
|
||||
/// `terse` or `nocheck` survive alongside pkh's own. The result is therefore
|
||||
/// the inherited options followed by `computed`, space-separated; each side is
|
||||
/// trimmed and its internal whitespace runs collapsed. An unset or blank
|
||||
/// inherited value yields just `computed`.
|
||||
pub fn merge_deb_build_options(inherited: Option<&str>, computed: &str) -> String {
|
||||
let computed = normalize_build_options(computed);
|
||||
match inherited.map(normalize_build_options) {
|
||||
Some(inherited) if !inherited.is_empty() => format!("{} {}", inherited, computed),
|
||||
_ => computed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Trim and collapse internal whitespace in a `DEB_BUILD_OPTIONS` fragment.
|
||||
fn normalize_build_options(options: &str) -> String {
|
||||
options.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Compute the environment variables exported before running any build step.
|
||||
///
|
||||
/// Mirrors dpkg behavior:
|
||||
/// - `SOURCE_DATE_EPOCH` from the changelog entry timestamp
|
||||
/// (<https://reproducible-builds.org/specs/source-date-epoch/>),
|
||||
/// - `DEB_BUILD_OPTIONS=parallel=N` (auto-detected job count),
|
||||
/// - `DEB_BUILD_OPTIONS`: any value inherited from the invoking environment
|
||||
/// (dpkg-buildpackage prepends it) followed by `parallel=N` (auto-detected
|
||||
/// job count),
|
||||
/// - `DEB_BUILD_PROFILES` when non-default profiles are requested.
|
||||
///
|
||||
/// The locale is pinned to `C` (`LC_ALL`, which takes precedence over any
|
||||
@@ -38,7 +62,10 @@ pub fn build_env(
|
||||
);
|
||||
env.insert(
|
||||
"DEB_BUILD_OPTIONS".to_string(),
|
||||
format!("parallel={}", parallel),
|
||||
merge_deb_build_options(
|
||||
std::env::var("DEB_BUILD_OPTIONS").ok().as_deref(),
|
||||
&format!("parallel={}", parallel),
|
||||
),
|
||||
);
|
||||
if !build_profiles.is_empty() {
|
||||
env.insert("DEB_BUILD_PROFILES".to_string(), build_profiles.join(","));
|
||||
@@ -57,15 +84,31 @@ pub fn arch_env(host_arch: Option<&str>) -> Result<BTreeMap<String, String>, Str
|
||||
crate::debian::arch::arch_env(host_arch)
|
||||
}
|
||||
|
||||
/// Read the current vendor name from `/etc/dpkg/origins/default`
|
||||
/// (its `Vendor:` or `Origin:` field), defaulting to `"debian"`.
|
||||
/// Read the current vendor name from the active dpkg origins `default` file
|
||||
/// (`$DPKG_ORIGINS_DIR/default`, falling back to `/etc/dpkg/origins/default`;
|
||||
/// its `Vendor:` or `Origin:` field), defaulting to `"debian"`.
|
||||
pub fn current_vendor() -> String {
|
||||
std::fs::read_to_string(Path::new("/etc/dpkg/origins/default"))
|
||||
let path = resolve_origins_default(
|
||||
std::env::var("DPKG_ORIGINS_DIR").ok().as_deref(),
|
||||
"/etc/dpkg/origins",
|
||||
);
|
||||
std::fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|content| vendor_from_origins_content(&content))
|
||||
.unwrap_or_else(|| "debian".to_string())
|
||||
}
|
||||
|
||||
/// Resolve the path of the active dpkg origins file from the
|
||||
/// `DPKG_ORIGINS_DIR` value (the directory holding the origin files, where
|
||||
/// `default` selects the active one) and the fallback directory
|
||||
/// (`/etc/dpkg/origins`). An unset or empty directory value falls back.
|
||||
fn resolve_origins_default(origins_dir: Option<&str>, fallback_dir: &str) -> PathBuf {
|
||||
let dir = origins_dir
|
||||
.filter(|d| !d.is_empty())
|
||||
.unwrap_or(fallback_dir);
|
||||
Path::new(dir).join("default")
|
||||
}
|
||||
|
||||
/// Extract the vendor name from the content of a dpkg origins file: its
|
||||
/// `Vendor:` field, falling back to `Origin:` when absent. `None` when
|
||||
/// neither field carries a non-empty value.
|
||||
@@ -92,15 +135,15 @@ pub fn vendor_from_origins_content(content: &str) -> Option<String> {
|
||||
|
||||
/// Default build profiles applied by vendor hooks.
|
||||
///
|
||||
/// The Ubuntu vendor module activates `derivative.ubuntu noudeb` by default;
|
||||
/// Debian applies none. This mirrors what `Dpkg::BuildProfiles` resolves when
|
||||
/// `DEB_BUILD_PROFILES` is unset.
|
||||
/// The distro data carries them (`build_profiles` of the vendor's
|
||||
/// distribution in `data/distro_info.yml` — the Ubuntu vendor activates
|
||||
/// `derivative.ubuntu noudeb`, Debian applies none), mirroring what
|
||||
/// `Dpkg::BuildProfiles` resolves when `DEB_BUILD_PROFILES` is unset. The
|
||||
/// vendor is matched case-insensitively against the distro data keys
|
||||
/// (dpkg's `Vendor:` field keeps its original casing); a vendor with no
|
||||
/// distro entry gets no profiles.
|
||||
pub fn default_build_profiles(vendor: &str) -> Vec<String> {
|
||||
if vendor.eq_ignore_ascii_case("ubuntu") {
|
||||
vec!["derivative.ubuntu".to_string(), "noudeb".to_string()]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
crate::distro_info::get_build_profiles(&vendor.to_lowercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolve the active build profiles: explicit `-P` profiles take precedence,
|
||||
@@ -271,13 +314,63 @@ mod tests {
|
||||
assert_eq!(env.get("LANG").unwrap(), "C");
|
||||
assert_eq!(env.get("LC_ALL").unwrap(), "C");
|
||||
assert_eq!(env.get("SOURCE_DATE_EPOCH").unwrap(), "1787392800");
|
||||
assert_eq!(env.get("DEB_BUILD_OPTIONS").unwrap(), "parallel=16");
|
||||
// Reading the var is race-free; the expected value goes through the
|
||||
// same merge so the assertion holds whatever the ambient environment
|
||||
// carries.
|
||||
let expected = merge_deb_build_options(
|
||||
std::env::var("DEB_BUILD_OPTIONS").ok().as_deref(),
|
||||
"parallel=16",
|
||||
);
|
||||
assert_eq!(env.get("DEB_BUILD_OPTIONS").unwrap(), &expected);
|
||||
assert!(!env.contains_key("DEB_BUILD_PROFILES"));
|
||||
|
||||
let env = build_env(1, 4, &["nodoc".to_string(), "cross".to_string()]);
|
||||
assert_eq!(env.get("DEB_BUILD_PROFILES").unwrap(), "nodoc,cross");
|
||||
}
|
||||
|
||||
/// dpkg-buildpackage prepends the inherited `DEB_BUILD_OPTIONS`, so
|
||||
/// user-set options survive alongside the computed ones.
|
||||
#[test]
|
||||
fn merge_prepends_inherited_options() {
|
||||
assert_eq!(
|
||||
merge_deb_build_options(Some("terse"), "parallel=16"),
|
||||
"terse parallel=16"
|
||||
);
|
||||
assert_eq!(
|
||||
merge_deb_build_options(Some("nocheck terse"), "parallel=4"),
|
||||
"nocheck terse parallel=4"
|
||||
);
|
||||
}
|
||||
|
||||
/// An unset, empty or blank inherited value yields just the computed
|
||||
/// options.
|
||||
#[test]
|
||||
fn merge_skips_empty_inherited() {
|
||||
assert_eq!(merge_deb_build_options(None, "parallel=8"), "parallel=8");
|
||||
assert_eq!(
|
||||
merge_deb_build_options(Some(""), "parallel=8"),
|
||||
"parallel=8"
|
||||
);
|
||||
assert_eq!(
|
||||
merge_deb_build_options(Some(" "), "parallel=8"),
|
||||
"parallel=8"
|
||||
);
|
||||
}
|
||||
|
||||
/// Both sides are trimmed and internal whitespace runs collapsed: no
|
||||
/// leading/trailing space, no double spaces in the merged result.
|
||||
#[test]
|
||||
fn merge_normalizes_whitespace() {
|
||||
assert_eq!(
|
||||
merge_deb_build_options(Some(" terse "), "parallel=2"),
|
||||
"terse parallel=2"
|
||||
);
|
||||
assert_eq!(
|
||||
merge_deb_build_options(Some("nocheck\t terse"), "parallel=2"),
|
||||
"nocheck terse parallel=2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vendor_defaults() {
|
||||
assert!(default_build_profiles("debian").is_empty());
|
||||
@@ -285,6 +378,14 @@ mod tests {
|
||||
default_build_profiles("ubuntu"),
|
||||
vec!["derivative.ubuntu".to_string(), "noudeb".to_string()]
|
||||
);
|
||||
// dpkg's Vendor field keeps its original casing; the distro data
|
||||
// keys are lowercase.
|
||||
assert_eq!(
|
||||
default_build_profiles("Ubuntu"),
|
||||
vec!["derivative.ubuntu".to_string(), "noudeb".to_string()]
|
||||
);
|
||||
// A vendor without a distro entry gets no profiles.
|
||||
assert!(default_build_profiles("some-derivative").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -306,6 +407,26 @@ mod tests {
|
||||
assert_eq!(vendor_from_origins_content("Suite: stable\n"), None);
|
||||
}
|
||||
|
||||
/// `current_vendor` must honor `DPKG_ORIGINS_DIR` (already on the
|
||||
/// `.buildinfo` allow-list) when locating the `default` origins file,
|
||||
/// falling back to `/etc/dpkg/origins/default` when unset or empty.
|
||||
#[test]
|
||||
fn origins_default_path_honors_dpkg_origins_dir() {
|
||||
assert_eq!(
|
||||
resolve_origins_default(Some("/custom/origins"), "/etc/dpkg/origins"),
|
||||
PathBuf::from("/custom/origins/default")
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_origins_default(None, "/etc/dpkg/origins"),
|
||||
PathBuf::from("/etc/dpkg/origins/default")
|
||||
);
|
||||
// An empty value behaves as unset, like dpkg's `$dir || $default`.
|
||||
assert_eq!(
|
||||
resolve_origins_default(Some(""), "/etc/dpkg/origins"),
|
||||
PathBuf::from("/etc/dpkg/origins/default")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_escaping() {
|
||||
// The function reads the process env; just verify formatting helpers
|
||||
|
||||
+889
-225
File diff suppressed because it is too large
Load Diff
+1050
-87
File diff suppressed because it is too large
Load Diff
+132
-2
@@ -70,6 +70,12 @@ pub trait ContextDriver {
|
||||
fn read_file(&self, path: &Path) -> io::Result<String>;
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()>;
|
||||
fn exists(&self, path: &Path) -> io::Result<bool>;
|
||||
/// Check if a path is a directory inside the context
|
||||
///
|
||||
/// Distinct from [`ContextDriver::exists`] because paths returned by
|
||||
/// [`ContextDriver::list_files`] are context-relative and can only be
|
||||
/// classified through the context, never with a host-side stat.
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool>;
|
||||
|
||||
/// Clean up any resources held by the driver (e.g. unmount overlay filesystems).
|
||||
/// Called before the chroot directory is removed.
|
||||
@@ -117,6 +123,28 @@ pub enum ContextConfig {
|
||||
},
|
||||
}
|
||||
|
||||
impl ContextConfig {
|
||||
/// Build an SSH context configuration from an endpoint of the form
|
||||
/// `[ssh://][user@]host[:port]`.
|
||||
pub fn from_endpoint(endpoint: &str) -> Result<Self, String> {
|
||||
let re = regex::Regex::new(
|
||||
r"^(?:ssh://)?(?:(?P<user>[^@]+)@)?(?P<host>[^:/]+)(?::(?P<port>\d+))?$",
|
||||
)
|
||||
.expect("valid endpoint regex");
|
||||
let cap = re.captures(endpoint).ok_or_else(|| {
|
||||
format!("Invalid endpoint format: '{endpoint}'. Expected [ssh://][user@]host[:port]")
|
||||
})?;
|
||||
let host = cap.name("host").unwrap().as_str().to_string();
|
||||
let user = cap.name("user").map(|m| m.as_str().to_string());
|
||||
let port = cap
|
||||
.name("port")
|
||||
.map(|m| m.as_str().parse::<u16>())
|
||||
.transpose()
|
||||
.map_err(|_| "Invalid port number".to_string())?;
|
||||
Ok(ContextConfig::Ssh { host, user, port })
|
||||
}
|
||||
}
|
||||
|
||||
/// A context, allowing to run commands, read and write files, etc
|
||||
pub struct Context {
|
||||
/// Configuration for the context
|
||||
@@ -221,12 +249,22 @@ impl Context {
|
||||
}
|
||||
|
||||
/// Make a command inside context
|
||||
///
|
||||
/// Build tooling must not inherit the session's locale: dpkg-family
|
||||
/// tools and perl-based packaging scripts change their output (and
|
||||
/// dpkg-buildpackage treats some of it as data) with the environment,
|
||||
/// and a translated or mixed locale leaks host state into builds. The
|
||||
/// C locale is the default; a caller can still override it by setting
|
||||
/// LANG/LC_ALL through [`ContextCommand::envs`] afterwards.
|
||||
pub fn command<S: AsRef<OsStr>>(&self, program: S) -> ContextCommand<'_> {
|
||||
ContextCommand {
|
||||
context: self,
|
||||
program: program.as_ref().to_string_lossy().to_string(),
|
||||
args: Vec::new(),
|
||||
env: Vec::new(),
|
||||
env: vec![
|
||||
("LANG".to_string(), "C".to_string()),
|
||||
("LC_ALL".to_string(), "C".to_string()),
|
||||
],
|
||||
cwd: None,
|
||||
sink: None,
|
||||
}
|
||||
@@ -281,6 +319,15 @@ impl Context {
|
||||
self.driver().as_ref().unwrap().exists(path)
|
||||
}
|
||||
|
||||
/// Check if a path is a directory inside context
|
||||
///
|
||||
/// Paths returned by [`Context::list_files`] are context-relative
|
||||
/// (e.g. rooted inside the chroot for an unshare context): whether they
|
||||
/// are directories can only be decided through the context.
|
||||
pub fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
self.driver().as_ref().unwrap().is_dir(path)
|
||||
}
|
||||
|
||||
/// Clean up any resources held by the driver (e.g. unmount overlay filesystems).
|
||||
/// Called before the chroot directory is removed.
|
||||
pub fn cleanup(&self) -> io::Result<()> {
|
||||
@@ -311,7 +358,9 @@ impl Context {
|
||||
overlay_mounts: std::sync::Mutex::new(Vec::new()),
|
||||
}),
|
||||
};
|
||||
*driver_lock = Some(driver);
|
||||
// In test runs, commands whose output would inherit the terminal
|
||||
// are captured into the per-test log file instead
|
||||
*driver_lock = Some(crate::test_support::wrap_driver(driver));
|
||||
}
|
||||
driver_lock
|
||||
}
|
||||
@@ -453,3 +502,84 @@ fn contextualize_spawn_error(program: &str, e: io::Error) -> io::Error {
|
||||
io::Error::new(e.kind(), format!("Could not run '{program}': {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod endpoint_tests {
|
||||
use super::*;
|
||||
|
||||
/// Every accepted endpoint spelling maps to the expected config.
|
||||
#[test]
|
||||
fn from_endpoint_parses_all_spellings() {
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("myhost"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: None,
|
||||
port: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("admin@myhost"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: Some("admin".into()),
|
||||
port: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("myhost:2222"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: None,
|
||||
port: Some(2222),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("ssh://admin@myhost:22"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: Some("admin".into()),
|
||||
port: Some(22),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// Non-numeric ports and extra segments are format errors; a
|
||||
/// non-u16 numeric port is a port error.
|
||||
#[test]
|
||||
fn from_endpoint_rejects_malformed_endpoints() {
|
||||
for bad in ["", "a/b/c", "host:notaport"] {
|
||||
let err = ContextConfig::from_endpoint(bad).unwrap_err();
|
||||
assert!(err.contains("Invalid endpoint format"), "{err}");
|
||||
}
|
||||
let err = ContextConfig::from_endpoint("host:99999").unwrap_err();
|
||||
assert_eq!(err, "Invalid port number");
|
||||
}
|
||||
|
||||
/// Commands run in the C locale whatever the session environment
|
||||
/// carries: host locale variables must not leak into builds. An
|
||||
/// explicit caller override still wins.
|
||||
#[test]
|
||||
fn commands_default_to_the_c_locale() {
|
||||
let ctx = Context::new(ContextConfig::Local).unwrap();
|
||||
|
||||
let locale = ctx
|
||||
.command("sh")
|
||||
.arg("-c")
|
||||
.arg("printf '%s' \"${LC_ALL:-unset}:${LANG:-unset}\"")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout;
|
||||
assert_eq!(String::from_utf8_lossy(&locale), "C:C");
|
||||
|
||||
let locale = ctx
|
||||
.command("sh")
|
||||
.arg("-c")
|
||||
.arg("printf '%s' \"$LC_ALL\"")
|
||||
.env("LC_ALL", "C.UTF-8")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout;
|
||||
assert_eq!(String::from_utf8_lossy(&locale), "C.UTF-8");
|
||||
}
|
||||
}
|
||||
|
||||
+52
-14
@@ -24,33 +24,31 @@ impl ContextDriver for LocalDriver {
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
// Generate a unique temporary directory name with random string
|
||||
// Sub-second precision and an atomic create: two concurrent
|
||||
// contexts racing on the same name must never share a directory,
|
||||
// so the loser of a create falls through to the next attempt
|
||||
// instead of probing for existence first (a probe-then-create
|
||||
// window loses exactly when two callers arrive together).
|
||||
let base_timestamp = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
.as_millis();
|
||||
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
let work_dir_name = if attempt == 0 {
|
||||
format!("pkh-{}", base_timestamp)
|
||||
format!("pkh-{base_timestamp}")
|
||||
} else {
|
||||
format!("pkh-{}-{}", base_timestamp, attempt)
|
||||
format!("pkh-{base_timestamp}-{attempt}")
|
||||
};
|
||||
|
||||
let temp_dir_path = std::env::temp_dir().join(&work_dir_name);
|
||||
|
||||
// Check if directory already exists
|
||||
if temp_dir_path.exists() {
|
||||
attempt += 1;
|
||||
continue;
|
||||
match std::fs::create_dir(&temp_dir_path) {
|
||||
Ok(()) => return Ok(temp_dir_path.to_string_lossy().to_string()),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => attempt += 1,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
// Create the directory
|
||||
std::fs::create_dir_all(&temp_dir_path)?;
|
||||
|
||||
// Return the path as a string
|
||||
return Ok(temp_dir_path.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +155,10 @@ impl ContextDriver for LocalDriver {
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(path.exists())
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(path.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
@@ -190,3 +192,39 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Concurrent callers must never share a temporary directory: the
|
||||
/// create is atomic, so a lost race falls through to the next name
|
||||
/// instead of both callers probing the same free name and unpacking
|
||||
/// into the same directory.
|
||||
#[test]
|
||||
fn create_temp_dir_is_unique_under_concurrency() {
|
||||
const CALLERS: usize = 8;
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let handles: Vec<_> = (0..CALLERS)
|
||||
.map(|_| {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let dir = LocalDriver.create_temp_dir().unwrap();
|
||||
tx.send(dir).unwrap();
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
let mut names: Vec<String> = rx.iter().collect();
|
||||
names.sort();
|
||||
let unique: std::collections::BTreeSet<&String> = names.iter().collect();
|
||||
assert_eq!(names.len(), unique.len(), "duplicate temp dirs: {names:?}");
|
||||
for name in &unique {
|
||||
std::fs::remove_dir(name).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ mod ssh;
|
||||
mod unshare;
|
||||
|
||||
pub use api::{Context, ContextCommand, ContextConfig, LineSink, Stream};
|
||||
// The driver trait is implementation detail of the context API; it is only
|
||||
// needed crate-internally (test-run capture wrapper), so keep it out of the
|
||||
// public surface (and its documentation requirement).
|
||||
pub(crate) use api::ContextDriver;
|
||||
pub use manager::ContextManager;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -381,6 +385,40 @@ mod tests {
|
||||
assert!(!dest.join("src/.svn").exists());
|
||||
}
|
||||
|
||||
/// The unshare driver maps context-relative paths onto the chroot root
|
||||
/// on the host: `is_dir` must answer through that mapping (a host-side
|
||||
/// stat of the unmapped path sees nothing), which is what lets the deb
|
||||
/// package-directory search classify staged entries.
|
||||
#[test]
|
||||
fn test_unshare_is_dir_maps_through_the_chroot_root() {
|
||||
let chroot = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(chroot.path().join("tmp/work/tree/debian")).unwrap();
|
||||
fs::write(chroot.path().join("tmp/work/orig.tar.xz"), "tar").unwrap();
|
||||
|
||||
let base = Context::new(ContextConfig::Local).unwrap();
|
||||
let ctx = Context::with_parent(
|
||||
ContextConfig::Unshare {
|
||||
path: chroot.path().to_string_lossy().to_string(),
|
||||
parent: None,
|
||||
},
|
||||
Arc::new(base),
|
||||
);
|
||||
|
||||
assert!(ctx.is_dir(std::path::Path::new("/tmp/work/tree")).unwrap());
|
||||
assert!(
|
||||
ctx.exists(std::path::Path::new("/tmp/work/tree/debian"))
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!ctx.is_dir(std::path::Path::new("/tmp/work/orig.tar.xz"))
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!ctx.exists(std::path::Path::new("/tmp/work/missing"))
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
/// The overlay-mount path exposes the tree verbatim, so pruning happens
|
||||
/// after the fact: nested VCS metadata must be removed recursively.
|
||||
#[test]
|
||||
|
||||
@@ -296,6 +296,16 @@ impl ContextDriver for SchrootDriver {
|
||||
)?;
|
||||
Ok(status.success())
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
let status = self.run(
|
||||
"test",
|
||||
&["-d".to_string(), path.to_string_lossy().to_string()],
|
||||
&[],
|
||||
None,
|
||||
)?;
|
||||
Ok(status.success())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -288,6 +288,13 @@ impl ContextDriver for SshDriver {
|
||||
}
|
||||
let mut remote_file = sftp.create(path).map_err(io::Error::other)?;
|
||||
remote_file.write_all(content.as_bytes())?;
|
||||
// Close explicitly: the `Drop` impl of `ssh2::File` discards a
|
||||
// close-time error ("too late to recover"), silently truncating the
|
||||
// remote file. Writes are unbuffered (`Write::flush` is a no-op), so
|
||||
// no flush is needed before closing.
|
||||
remote_file.close().map_err(|e| {
|
||||
io::Error::other(format!("Failed to close remote file {:?}: {}", path, e))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -299,6 +306,14 @@ impl ContextDriver for SshDriver {
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
// Same error tolerance as `exists`: an unreachable path is not a
|
||||
// directory, and the caller decides what absence means.
|
||||
Ok(sftp.stat(path).map(|stat| stat.is_dir()).unwrap_or(false))
|
||||
}
|
||||
}
|
||||
|
||||
impl SshDriver {
|
||||
@@ -327,6 +342,18 @@ impl SshDriver {
|
||||
io::Error::other(format!("Failed to create remote file {:?}: {}", dest, e))
|
||||
})?;
|
||||
io::copy(&mut file, &mut remote_file)?;
|
||||
// Close explicitly: quota-exceeded and similar failures only
|
||||
// surface in the final ACKs and the close handshake, and the
|
||||
// `Drop` impl of `ssh2::File` discards that error ("too late to
|
||||
// recover"), leaving a truncated remote file behind. Writes are
|
||||
// unbuffered (`ssh2::File`'s `Write::flush` is a no-op), so no
|
||||
// flush is needed before closing.
|
||||
remote_file.close().map_err(|e| {
|
||||
io::Error::other(format!(
|
||||
"Failed to close remote file {:?} after upload: {}",
|
||||
dest, e
|
||||
))
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+26
-17
@@ -296,37 +296,41 @@ impl ContextDriver for UnshareDriver {
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
// Create a temporary directory inside the chroot with unique naming
|
||||
// Sub-second precision and an atomic create, like the local
|
||||
// driver: concurrent callers racing on the same name must not
|
||||
// share a directory, so an existing target falls through to the
|
||||
// next attempt instead of a probe-then-create window.
|
||||
let base_timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
.as_millis();
|
||||
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
let work_dir_name = if attempt == 0 {
|
||||
format!("pkh-build-{}", base_timestamp)
|
||||
format!("pkh-build-{base_timestamp}")
|
||||
} else {
|
||||
format!("pkh-build-{}-{}", base_timestamp, attempt)
|
||||
format!("pkh-build-{base_timestamp}-{attempt}")
|
||||
};
|
||||
|
||||
let work_dir_inside_chroot = format!("/tmp/{}", work_dir_name);
|
||||
let work_dir_inside_chroot = format!("/tmp/{work_dir_name}");
|
||||
let host_path = Path::new(&self.path).join("tmp").join(&work_dir_name);
|
||||
|
||||
// Check if directory already exists
|
||||
if host_path.exists() {
|
||||
attempt += 1;
|
||||
continue;
|
||||
match std::fs::create_dir(&host_path) {
|
||||
Ok(()) => {
|
||||
debug!(
|
||||
"Created work directory: {} (host: {})",
|
||||
work_dir_inside_chroot,
|
||||
host_path.display()
|
||||
);
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
// Create the directory on the host filesystem
|
||||
std::fs::create_dir_all(&host_path)?;
|
||||
|
||||
debug!(
|
||||
"Created work directory: {} (host: {})",
|
||||
work_dir_inside_chroot,
|
||||
host_path.display()
|
||||
);
|
||||
|
||||
// Return the path as it appears inside the chroot
|
||||
return Ok(work_dir_inside_chroot);
|
||||
}
|
||||
@@ -352,6 +356,11 @@ impl ContextDriver for UnshareDriver {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
self.parent().exists(&host_path)
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
Ok(host_path.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
impl UnshareDriver {
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
//! Embedding convention for the static reference data files (`data/*.yml`)
|
||||
//!
|
||||
//! Reference data that changes independently of the code — distro series
|
||||
//! pointers, pinned SSH host keys, package quirks — lives in YAML files
|
||||
//! under `data/` at the repo root instead of hardcoded in the source, so
|
||||
//! it is updatable in one reviewable place.
|
||||
//!
|
||||
//! This module is deliberately not a central registry: each file is
|
||||
//! embedded by the module that owns it (distro_info.rs owns
|
||||
//! data/distro_info.yml, launchpad.rs owns data/launchpad.yml,
|
||||
//! apt/keyring.rs owns data/keyserver.yml, new/origin.rs owns
|
||||
//! data/forges.yml, put/ssh.rs owns data/host_keys.yml, quirks.rs owns
|
||||
//! data/quirks.yml) through the [`embed_data!`] macro below, so data
|
||||
//! and its accessors stay together and a diff touching one domain cannot
|
||||
//! half-touch another. The macro embeds the file at compile time and
|
||||
//! parses it once into a `lazy_static` on first use; since the data ships
|
||||
//! inside the binary, a parse failure is a build-time bug that cannot be
|
||||
//! recovered from at runtime, and the macro panics on it.
|
||||
//!
|
||||
//! Paths and URLs in the data files carry their variable parts as `{name}`
|
||||
//! placeholders, substituted with `str::replace` at the use site — no
|
||||
//! template engine.
|
||||
|
||||
/// Embed one YAML data file as a lazily-parsed static, following the
|
||||
/// convention documented at the module level.
|
||||
///
|
||||
/// Takes the visibility of the generated static (none for private, `pub` or
|
||||
/// `pub(crate)`-style), its name, its struct type (which stays defined in
|
||||
/// the owning module, next to its accessors) and the file path relative to
|
||||
/// the invoking source file (`"../data/distro_info.yml"` from
|
||||
/// `src/distro_info.rs`, `"../../data/host_keys.yml"` from
|
||||
/// `src/put/ssh.rs`, ...), and expands to the house `include_str!` →
|
||||
/// `lazy_static` → parse pattern — only the embed+parse boilerplate is
|
||||
/// generated.
|
||||
///
|
||||
/// ```ignore
|
||||
/// embed_data! {
|
||||
/// static ref MY_DATA: MyData = "../data/my_data.yml"
|
||||
/// }
|
||||
/// ```
|
||||
macro_rules! embed_data {
|
||||
// Internal arm: the visibility arrives wrapped in parentheses (empty for
|
||||
// private statics) because `lazy_static!` only re-matches literal
|
||||
// `pub`/`pub(...)` token sequences, not an opaque forwarded `vis`.
|
||||
(@expand ($($vis:tt)*) static ref $name:ident : $ty:ty = $path:literal) => {
|
||||
lazy_static::lazy_static! {
|
||||
// The YAML is include_str!'d at compile time and statically
|
||||
// valid; if it ever failed to parse it would be a build-time bug
|
||||
// that cannot be recovered from at runtime, so panicking here is
|
||||
// acceptable.
|
||||
$($vis)* static ref $name: $ty = serde_yaml::from_str(include_str!($path))
|
||||
.expect(concat!(
|
||||
"built-in ",
|
||||
$path,
|
||||
" data is statically valid and must parse"
|
||||
));
|
||||
}
|
||||
};
|
||||
(static ref $name:ident : $ty:ty = $path:literal) => {
|
||||
$crate::data::embed_data!(@expand () static ref $name : $ty = $path);
|
||||
};
|
||||
(pub static ref $name:ident : $ty:ty = $path:literal) => {
|
||||
$crate::data::embed_data!(@expand (pub) static ref $name : $ty = $path);
|
||||
};
|
||||
(pub ($($vis:tt)+) static ref $name:ident : $ty:ty = $path:literal) => {
|
||||
$crate::data::embed_data!(@expand (pub ($($vis)+)) static ref $name : $ty = $path);
|
||||
};
|
||||
}
|
||||
|
||||
/// Makes the macro available through the module path
|
||||
/// (`use crate::data::embed_data;`)
|
||||
pub(crate) use embed_data;
|
||||
+149
-59
@@ -62,13 +62,60 @@ pub fn setup_environment(
|
||||
.map_err(|e| format!("Invalid UTF-8 in dpkg-architecture output: {e}"))?;
|
||||
parse_dpkg_architecture_output(&dpkg_architecture, env);
|
||||
|
||||
// In-tree tools locate their libraries with the *host* pkg-config during
|
||||
// cross builds (the kernel's tools/build feature checks derive their
|
||||
// cflags/ldflags from `pkg-config --cflags/--libs`), whose search path
|
||||
// only covers the build architecture's pkgconfig dirs. Point it at the
|
||||
// target's so `libtraceevent` & co resolve to target-arch libraries:
|
||||
// linux-riscv cross builds die in rtla's Makefile.config otherwise, even
|
||||
// with the target -dev packages installed.
|
||||
if let Some(multiarch) = env.get("DEB_HOST_MULTIARCH").cloned() {
|
||||
env.insert(
|
||||
"PKG_CONFIG_LIBDIR".to_string(),
|
||||
format!("/usr/lib/{multiarch}/pkgconfig:/usr/share/pkgconfig"),
|
||||
);
|
||||
}
|
||||
|
||||
env.insert("DEB_BUILD_PROFILES".to_string(), "cross".to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The suites a cross-build environment enables for `series`: the series
|
||||
/// itself plus the distro data's cross pockets (`<series>-updates`,
|
||||
/// `<series>-backports`, `<series>-security`), plus the explicitly
|
||||
/// requested `pocket` when one is given ('proposed' stays opt-in exactly
|
||||
/// this way — it is not a cross pocket). Shared by the source-adjusting
|
||||
/// pass and the added mirror entry, which used to duplicate the list.
|
||||
fn cross_suites(
|
||||
series: &str,
|
||||
pocket: Option<&str>,
|
||||
dist: &str,
|
||||
) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let mut suites = vec![series.to_string()];
|
||||
for p in crate::distro_info::get_cross_pockets(dist)? {
|
||||
suites.push(format!("{series}-{p}"));
|
||||
}
|
||||
if let Some(p) = pocket {
|
||||
let pocket_suite = format!("{series}-{p}");
|
||||
if !suites.contains(&pocket_suite) {
|
||||
suites.push(pocket_suite);
|
||||
}
|
||||
}
|
||||
Ok(suites)
|
||||
}
|
||||
|
||||
/// Ensure that repositories for target architecture are available
|
||||
/// This also handles the 'ports.ubuntu.com' vs 'archive.ubuntu.com' on Ubuntu
|
||||
///
|
||||
/// On Ubuntu hosts, driven by the bundled distro data
|
||||
/// (`data/distro_info.yml`): the official sources served by the mirror of
|
||||
/// the local architecture (the primary archive and its security sibling)
|
||||
/// are scoped to it and carry every component and cross-build suite, and
|
||||
/// the mirror serving the target architecture (ports, for the non-local
|
||||
/// ones) is added when no existing source serves the arch from it yet.
|
||||
/// Debian hosts are left alone: one mirror serves every architecture, so
|
||||
/// the host's own sources already cover the target — the os-release gate
|
||||
/// below is what makes that a data conclusion instead of hardcoding.
|
||||
pub fn ensure_repositories(
|
||||
arch: &str,
|
||||
series: &str,
|
||||
@@ -97,90 +144,78 @@ pub fn ensure_repositories(
|
||||
if !os_release.contains("ID=ubuntu") {
|
||||
return Ok(());
|
||||
}
|
||||
let dist = "ubuntu";
|
||||
|
||||
// Load existing sources
|
||||
let mut sources = crate::apt::sources::load(Some(ctx.clone()))?;
|
||||
|
||||
// The mirrors serving each side of the cross build (primary for the
|
||||
// local architectures, ports for the others) and the distro data's
|
||||
// components and suites
|
||||
let local_mirror = crate::distro_info::mirror_for_arch(dist, &local_arch)?;
|
||||
let target_mirror = crate::distro_info::mirror_for_arch(dist, arch)?;
|
||||
let components = crate::distro_info::get_dist_components(dist)?;
|
||||
let required_suites = cross_suites(series, pocket, dist)?;
|
||||
|
||||
// Ensure all components are enabled for the primary architecture
|
||||
for source in &mut sources {
|
||||
if source.uri.contains("archive.ubuntu.com") || source.uri.contains("security.ubuntu.com") {
|
||||
// Scope to local_arch if not already scoped
|
||||
if source.architectures.is_empty() {
|
||||
source.architectures.push(local_arch.clone());
|
||||
}
|
||||
// Official sources served by the local mirror (the primary archive
|
||||
// and its security sibling); ports serves the other architectures
|
||||
// and is configured below instead
|
||||
if !crate::distro_info::is_mirror_source(local_mirror, &source.uri) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure all components are present
|
||||
let required_components = ["main", "restricted", "universe", "multiverse"];
|
||||
for &comp in &required_components {
|
||||
if !source.components.contains(&comp.to_string()) {
|
||||
source.components.push(comp.to_string());
|
||||
}
|
||||
}
|
||||
// Scope to local_arch if not already scoped
|
||||
if source.architectures.is_empty() {
|
||||
source.architectures.push(local_arch.clone());
|
||||
}
|
||||
|
||||
// Ensure all suites (pockets) are enabled, excluding 'proposed'
|
||||
// unless explicitly requested through the 'pocket' option
|
||||
let mut required_suites = vec![
|
||||
series.to_string(),
|
||||
format!("{}-updates", series),
|
||||
format!("{}-backports", series),
|
||||
format!("{}-security", series),
|
||||
];
|
||||
if let Some(p) = pocket {
|
||||
let pocket_suite = format!("{series}-{p}");
|
||||
if !required_suites.contains(&pocket_suite) {
|
||||
required_suites.push(pocket_suite);
|
||||
}
|
||||
// Ensure all components are present
|
||||
for comp in &components {
|
||||
if !source.components.contains(comp) {
|
||||
source.components.push(comp.clone());
|
||||
}
|
||||
for suite in required_suites {
|
||||
if !source.suite.contains(&suite) {
|
||||
source.suite.push(suite);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure all suites (pockets) are enabled
|
||||
for suite in &required_suites {
|
||||
if !source.suite.contains(suite) {
|
||||
source.suite.push(suite.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if ports repository already exists for the target architecture
|
||||
let has_ports = sources
|
||||
.iter()
|
||||
.any(|s| s.uri.contains("ports.ubuntu.com") && s.architectures.contains(&arch.to_string()));
|
||||
// Check whether an existing source already serves the target
|
||||
// architecture from its mirror (e.g. the ports mirror for a
|
||||
// non-local arch); when cross-building for the local architecture,
|
||||
// the primary sources above already do
|
||||
let has_target = sources.iter().any(|s| {
|
||||
crate::distro_info::is_mirror_source(target_mirror, &s.uri)
|
||||
&& s.architectures.contains(&arch.to_string())
|
||||
});
|
||||
|
||||
if !has_ports {
|
||||
// Add ports repository for the target architecture
|
||||
let mut ports_suites = vec![
|
||||
series.to_string(),
|
||||
format!("{series}-updates"),
|
||||
format!("{series}-backports"),
|
||||
format!("{series}-security"),
|
||||
];
|
||||
if let Some(p) = pocket {
|
||||
let pocket_suite = format!("{series}-{p}");
|
||||
if !ports_suites.contains(&pocket_suite) {
|
||||
ports_suites.push(pocket_suite);
|
||||
}
|
||||
}
|
||||
let ports_entry = crate::apt::sources::SourceEntry {
|
||||
if !has_target {
|
||||
// Add the target architecture's mirror (ports for the non-local
|
||||
// architectures on Ubuntu)
|
||||
let mirror_entry = crate::apt::sources::SourceEntry {
|
||||
enabled: true,
|
||||
kind: crate::apt::sources::SourceKind::Deb,
|
||||
components: vec![
|
||||
"main".to_string(),
|
||||
"restricted".to_string(),
|
||||
"universe".to_string(),
|
||||
"multiverse".to_string(),
|
||||
],
|
||||
components: components.clone(),
|
||||
architectures: vec![arch.to_string()],
|
||||
uri: "http://ports.ubuntu.com/ubuntu-ports".to_string(),
|
||||
uri: target_mirror.url.clone(),
|
||||
signed_by: None,
|
||||
trusted: None,
|
||||
suite: ports_suites,
|
||||
suite: required_suites.clone(),
|
||||
// No origin: saved to the pkh-owned added-sources file
|
||||
origin: None,
|
||||
};
|
||||
sources.push(ports_entry);
|
||||
sources.push(mirror_entry);
|
||||
}
|
||||
|
||||
// Save the updated sources: each entry is written back to its origin
|
||||
// file in its own format (keeping its own Signed-By and Enabled state),
|
||||
// and the new ports entry goes to the pkh-owned added-sources file
|
||||
// and the new mirror entry goes to the pkh-owned added-sources file
|
||||
crate::apt::sources::save(Some(ctx.clone()), sources)?;
|
||||
|
||||
Ok(())
|
||||
@@ -234,4 +269,59 @@ mod tests {
|
||||
);
|
||||
assert_eq!(env.len(), 2);
|
||||
}
|
||||
|
||||
/// The suite list a cross-build environment enables: the series, its
|
||||
/// cross pockets from the distro data (updates, backports, security),
|
||||
/// and the explicitly requested pocket — which is the only way
|
||||
/// 'proposed' gets in.
|
||||
#[test]
|
||||
fn test_cross_suites_from_distro_data() {
|
||||
assert_eq!(
|
||||
cross_suites("noble", None, "ubuntu").unwrap(),
|
||||
vec![
|
||||
"noble".to_string(),
|
||||
"noble-updates".to_string(),
|
||||
"noble-backports".to_string(),
|
||||
"noble-security".to_string()
|
||||
]
|
||||
);
|
||||
// An explicitly requested pocket is added (not duplicated when it
|
||||
// is already a cross pocket).
|
||||
assert_eq!(
|
||||
cross_suites("noble", Some("proposed"), "ubuntu").unwrap(),
|
||||
vec![
|
||||
"noble".to_string(),
|
||||
"noble-updates".to_string(),
|
||||
"noble-backports".to_string(),
|
||||
"noble-security".to_string(),
|
||||
"noble-proposed".to_string()
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
cross_suites("noble", Some("updates"), "ubuntu").unwrap(),
|
||||
cross_suites("noble", None, "ubuntu").unwrap()
|
||||
);
|
||||
assert!(cross_suites("noble", None, "not-a-distro").is_err());
|
||||
}
|
||||
|
||||
/// setup_environment exports the target multiarch pkg-config libdir:
|
||||
/// tools' feature checks run the *host* pkg-config, which must find the
|
||||
/// target's .pc files (rtla hard-errors on libtraceevent otherwise,
|
||||
/// failing linux-riscv cross builds despite the target -dev packages
|
||||
/// being installed).
|
||||
#[test]
|
||||
fn test_setup_environment_exports_cross_pkg_config_libdir() {
|
||||
let mut env = HashMap::new();
|
||||
let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
setup_environment(&mut env, "riscv64", ctx).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
env.get("PKG_CONFIG_LIBDIR").map(String::as_str),
|
||||
Some("/usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig")
|
||||
);
|
||||
assert_eq!(
|
||||
env.get("DEB_BUILD_PROFILES").map(String::as_str),
|
||||
Some("cross")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+97
-294
@@ -1,138 +1,24 @@
|
||||
use crate::context::{self, Context, ContextConfig};
|
||||
use crate::ui::deb::{DebUi, Phase};
|
||||
use crate::deb::{Phase, enter_phase};
|
||||
use crate::interrupt::CleanupHookGuard;
|
||||
use crate::report::BuildView;
|
||||
use directories::ProjectDirs;
|
||||
use std::any::Any;
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use tar::Archive;
|
||||
use xz2::read::XzDecoder;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Process-global cleanup hooks
|
||||
//
|
||||
// On Ctrl-C, the SIGINT handler in `ui::deb` restores the terminal and then
|
||||
// `libc::_exit(130)`s, skipping all destructors — including
|
||||
// [`EphemeralContextGuard::drop`] — which leaks the freshly bootstrapped
|
||||
// chroot under /tmp together with its bind-mounted /proc and any overlayfs
|
||||
// mounts. To make interrupt-time cleanup possible anyway, resources register
|
||||
// a self-contained cleanup hook here; the SIGINT handler drains and runs the
|
||||
// registry right before exiting.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A boxed, send-safe cleanup hook body
|
||||
type CleanupFn = Box<dyn Fn() + Send>;
|
||||
|
||||
/// A pending cleanup hook together with its registry id
|
||||
struct CleanupHook {
|
||||
id: u64,
|
||||
f: CleanupFn,
|
||||
}
|
||||
|
||||
/// Registry of cleanup hooks waiting to run at interrupt time
|
||||
static CLEANUP_HOOKS: Mutex<Vec<CleanupHook>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Source of the registry ids used to deregister a specific hook
|
||||
static NEXT_CLEANUP_HOOK_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Register a hook to be run by [`run_cleanup_hooks`] (i.e. when the process
|
||||
/// is interrupted), returning a guard whose drop deregisters the hook again
|
||||
fn register_cleanup_hook(f: CleanupFn) -> CleanupHookGuard {
|
||||
let id = NEXT_CLEANUP_HOOK_ID.fetch_add(1, Ordering::Relaxed);
|
||||
CLEANUP_HOOKS.lock().unwrap().push(CleanupHook { id, f });
|
||||
CleanupHookGuard(id)
|
||||
}
|
||||
|
||||
/// RAII handle to a registered cleanup hook: dropping it (or an explicit
|
||||
/// [`CleanupHookGuard::deregister`]) removes the hook from the registry so
|
||||
/// the interrupt path can no longer run it
|
||||
struct CleanupHookGuard(u64);
|
||||
|
||||
impl CleanupHookGuard {
|
||||
/// Registry id of the hook (used to filter the registry in tests)
|
||||
#[cfg(test)]
|
||||
fn id(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Remove the hook from the registry; returns whether it was still pending
|
||||
fn deregister(&mut self) -> bool {
|
||||
deregister_cleanup_hook(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CleanupHookGuard {
|
||||
fn drop(&mut self) {
|
||||
deregister_cleanup_hook(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a hook from the registry; returns whether it was still pending
|
||||
fn deregister_cleanup_hook(id: u64) -> bool {
|
||||
let mut hooks = CLEANUP_HOOKS.lock().unwrap();
|
||||
let len_before = hooks.len();
|
||||
hooks.retain(|hook| hook.id != id);
|
||||
hooks.len() != len_before
|
||||
}
|
||||
|
||||
/// Drain and run every registered cleanup hook exactly once
|
||||
///
|
||||
/// Called from the SIGINT handler right before the process exits. Draining
|
||||
/// uses `try_lock` with a bounded retry instead of a blocking lock: if the
|
||||
/// signal interrupted the main thread while it held [`CLEANUP_HOOKS`] (inside
|
||||
/// register/deregister), blocking on the same non-recursive mutex from the
|
||||
/// handler would deadlock the process. Timing out therefore skips cleanup
|
||||
/// (leaking, as before this registry existed) rather than hanging.
|
||||
pub(crate) fn run_cleanup_hooks() {
|
||||
run_drained_hooks(drain_cleanup_hooks());
|
||||
}
|
||||
|
||||
/// Take every pending hook out of the registry, waiting at most ~1s for the
|
||||
/// registry lock (see [`run_cleanup_hooks`] for why this must not block forever)
|
||||
fn drain_cleanup_hooks() -> Vec<CleanupHook> {
|
||||
const RETRIES: usize = 200;
|
||||
const RETRY_DELAY: Duration = Duration::from_millis(5);
|
||||
|
||||
for _ in 0..RETRIES {
|
||||
if let Ok(mut hooks) = CLEANUP_HOOKS.try_lock() {
|
||||
return std::mem::take(&mut *hooks);
|
||||
}
|
||||
std::thread::sleep(RETRY_DELAY);
|
||||
}
|
||||
log::error!("Timed out waiting for the cleanup hook registry; skipping interrupt cleanup");
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Run drained hooks one by one, isolating panics so that one failing hook
|
||||
/// cannot skip the remaining ones
|
||||
fn run_drained_hooks(hooks: Vec<CleanupHook>) {
|
||||
for CleanupHook { id, f } in hooks {
|
||||
// Hooks are arbitrary user code; assert unwind safety so they can be
|
||||
// run inside a catching context
|
||||
if let Err(panic) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
|
||||
log::error!("Cleanup hook {id} panicked: {}", panic_message(&panic));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort message extraction from a panic payload
|
||||
fn panic_message(panic: &(dyn Any + Send)) -> String {
|
||||
if let Some(s) = panic.downcast_ref::<&str>() {
|
||||
(*s).to_string()
|
||||
} else if let Some(s) = panic.downcast_ref::<String>() {
|
||||
s.clone()
|
||||
} else {
|
||||
"non-string panic payload".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Interrupt-time chroot cleanup
|
||||
//
|
||||
// On Ctrl-C, the watchdog in `crate::interrupt` runs the hook registered in
|
||||
// [`EphemeralContextGuard::new_with_context`] right before exiting — the
|
||||
// interrupt sequence skips all destructors, which would otherwise leak the
|
||||
// freshly bootstrapped chroot under /tmp together with its bind-mounted
|
||||
// /proc and any overlayfs mounts.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Interrupt-time cleanup of an ephemeral chroot: unmount every host-side
|
||||
@@ -142,9 +28,9 @@ fn panic_message(panic: &(dyn Any + Send)) -> String {
|
||||
/// Unlike [`EphemeralContextGuard::drop`], this deliberately does NOT go
|
||||
/// through the context manager, the ephemeral context's driver (whose
|
||||
/// `cleanup()` unmounts the tracked overlays) or the base context's command
|
||||
/// builder: the signal may arrive while the interrupted thread holds any of
|
||||
/// those mutexes, and re-locking them from the signal handler would deadlock.
|
||||
/// Instead it only reads /proc/mounts and spawns umount/rm directly.
|
||||
/// builder: interrupt-time hooks must be self-contained, and those
|
||||
/// machineries may be mid-mutation on the interrupted thread. Instead it
|
||||
/// only reads /proc/mounts and spawns umount/rm directly.
|
||||
///
|
||||
/// It also differs from `drop` in that it removes the chroot regardless of
|
||||
/// the build result: the build was aborted, and leaving a still-mounted
|
||||
@@ -174,31 +60,48 @@ fn sigint_cleanup_chroot(chroot_path: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the chroot tree itself (tolerates a missing directory)
|
||||
let status = privileged_command("rm", is_root)
|
||||
.arg("-rf")
|
||||
.arg(chroot_path)
|
||||
.status();
|
||||
match status {
|
||||
Ok(status) if status.success() => {
|
||||
// Remove the chroot tree itself (tolerates a missing directory). A
|
||||
// child the Ctrl+C interrupted may still be finishing its writeout —
|
||||
// dpkg defers SIGINT until it reaches a safe state — so retry while rm
|
||||
// reports the tree non-empty instead of leaving it half-removed.
|
||||
const RETRIES: usize = 10;
|
||||
const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(300);
|
||||
let mut last = None;
|
||||
for attempt in 0..=RETRIES {
|
||||
if attempt > 0 {
|
||||
std::thread::sleep(RETRY_DELAY);
|
||||
}
|
||||
last = Some(
|
||||
privileged_command("rm", is_root)
|
||||
.arg("-rf")
|
||||
.arg(chroot_path)
|
||||
.status(),
|
||||
);
|
||||
if matches!(&last, Some(Ok(status)) if status.success()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match last {
|
||||
Some(Ok(status)) if status.success() => {
|
||||
log::debug!(
|
||||
"Removed chroot {} during interrupt cleanup",
|
||||
chroot_path.display()
|
||||
);
|
||||
}
|
||||
Ok(status) => {
|
||||
Some(Ok(status)) => {
|
||||
log::error!(
|
||||
"Failed to remove chroot {} during interrupt cleanup \
|
||||
(rm exited with {status}); run `pkh prune`",
|
||||
chroot_path.display()
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
Some(Err(e)) => {
|
||||
log::error!(
|
||||
"Failed to run rm for chroot {} during interrupt cleanup: {e}; run `pkh prune`",
|
||||
chroot_path.display()
|
||||
);
|
||||
}
|
||||
None => unreachable!("at least one rm attempt ran"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,7 +215,7 @@ impl EphemeralContextGuard {
|
||||
series: &str,
|
||||
arch: Option<&str>,
|
||||
base_ctx: Arc<Context>,
|
||||
ui: Option<Arc<DebUi>>,
|
||||
view: &dyn BuildView,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
// Save the globally-installed context so Drop can restore exactly
|
||||
// this handle: concurrent builds install their own ephemeral
|
||||
@@ -333,15 +236,14 @@ impl EphemeralContextGuard {
|
||||
|
||||
// Register the interrupt-time cleanup hook before any heavy work: if
|
||||
// the user hits Ctrl-C during bootstrap or the build itself, the
|
||||
// SIGINT handler unmounts and removes the chroot through this hook
|
||||
// (see `sigint_cleanup_chroot`). This only works for a local base
|
||||
// context: the hook must be self-contained (stored path + direct
|
||||
// umount/rm subprocesses) and cannot go through `base_ctx`, whose
|
||||
// driver mutex may be held by the interrupted thread. For remote or
|
||||
// nested bases the chroot lives elsewhere, and leftovers stay
|
||||
// handled by `pkh prune` as before.
|
||||
// interrupt watchdog unmounts and removes the chroot through this
|
||||
// hook (see `sigint_cleanup_chroot`). This only works for a local
|
||||
// base context: the hook must be self-contained (stored path +
|
||||
// direct umount/rm subprocesses) and cannot go through `base_ctx`.
|
||||
// For remote or nested bases the chroot lives elsewhere, and
|
||||
// leftovers stay handled by `pkh prune` as before.
|
||||
let cleanup_hook = if matches!(base_ctx.config, ContextConfig::Local) {
|
||||
Some(register_cleanup_hook(Box::new({
|
||||
Some(crate::interrupt::register_cleanup_hook(Box::new({
|
||||
let chroot_path = chroot_path.clone();
|
||||
move || sigint_cleanup_chroot(&chroot_path)
|
||||
})))
|
||||
@@ -355,13 +257,21 @@ impl EphemeralContextGuard {
|
||||
|
||||
// Download and extract the chroot tarball
|
||||
if let Err(e) =
|
||||
Self::download_and_extract_chroot(series, arch, &chroot_path, base_ctx.clone(), &ui)
|
||||
Self::download_and_extract_chroot(series, arch, &chroot_path, base_ctx.clone(), view)
|
||||
.await
|
||||
{
|
||||
// The guard (and its Drop) never materializes on this path, so
|
||||
// stop tracking the chroot for interrupt cleanup; as before, a
|
||||
// failed bootstrap leaves its partial directory in place.
|
||||
drop(cleanup_hook);
|
||||
// On a Ctrl+C the interrupt watchdog owns the tree: keep the
|
||||
// hook registered (forgetting the guard) so it removes the
|
||||
// partial directory, instead of the historical behavior of
|
||||
// leaving it in place. Without an interrupt this is a plain
|
||||
// bootstrap failure and the partial directory stays, as before.
|
||||
if crate::interrupt::interrupted()
|
||||
&& let Some(hook) = cleanup_hook
|
||||
{
|
||||
std::mem::forget(hook);
|
||||
} else {
|
||||
drop(cleanup_hook);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
@@ -408,7 +318,7 @@ impl EphemeralContextGuard {
|
||||
arch: Option<&str>,
|
||||
chroot_path: &PathBuf,
|
||||
ctx: Arc<context::Context>,
|
||||
ui: &Option<Arc<DebUi>>,
|
||||
view: &dyn BuildView,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Clone ctx for use in create_device_nodes after download_chroot_tarball consumes it
|
||||
let ctx_for_devices = ctx.clone();
|
||||
@@ -436,6 +346,11 @@ impl EphemeralContextGuard {
|
||||
let poll_interval = 5; // Check every 5 seconds
|
||||
|
||||
while ctx.exists(&lockfile_path)? {
|
||||
// Stop waiting on a Ctrl+C: the interrupt watchdog removes the
|
||||
// (yet empty) chroot and exits without waiting for the poll
|
||||
if crate::interrupt::interrupted() {
|
||||
return Err("Interrupted while waiting for the chroot tarball".into());
|
||||
}
|
||||
if wait_time >= timeout {
|
||||
log::warn!(
|
||||
"Lockfile {} exists and has been present for more than {} seconds. \
|
||||
@@ -464,10 +379,8 @@ impl EphemeralContextGuard {
|
||||
series,
|
||||
arch
|
||||
);
|
||||
if let Some(u) = ui {
|
||||
u.phase(Phase::PreparingChroot);
|
||||
}
|
||||
Self::download_chroot_tarball(series, arch, &tarball_path, ctx, ui).await?;
|
||||
enter_phase(view, Phase::PreparingChroot);
|
||||
Self::download_chroot_tarball(series, arch, &tarball_path, ctx, view).await?;
|
||||
} else {
|
||||
log::debug!(
|
||||
"Using cached chroot tarball for {} (arch: {:?})",
|
||||
@@ -478,16 +391,12 @@ impl EphemeralContextGuard {
|
||||
|
||||
// Extract tarball to chroot directory
|
||||
log::debug!("Extracting chroot tarball to {}...", chroot_path.display());
|
||||
if let Some(u) = ui {
|
||||
u.phase(Phase::ExtractingChroot);
|
||||
}
|
||||
Self::extract_tarball(&tarball_path, chroot_path, ui.as_deref())?;
|
||||
enter_phase(view, Phase::ExtractingChroot);
|
||||
Self::extract_tarball(&tarball_path, chroot_path, view)?;
|
||||
|
||||
// Create device nodes in the chroot
|
||||
log::debug!("Creating device nodes in chroot...");
|
||||
if let Some(u) = ui {
|
||||
u.phase(Phase::FinalizingChroot);
|
||||
}
|
||||
enter_phase(view, Phase::FinalizingChroot);
|
||||
Self::create_device_nodes(chroot_path, ctx_for_devices.clone())?;
|
||||
|
||||
// Bind mount /proc from host into chroot (before entering unshare namespace)
|
||||
@@ -503,7 +412,7 @@ impl EphemeralContextGuard {
|
||||
arch: Option<&str>,
|
||||
tarball_path: &Path,
|
||||
ctx: Arc<context::Context>,
|
||||
ui: &Option<Arc<DebUi>>,
|
||||
view: &dyn BuildView,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Create a lock file to make sure that noone tries to use the file while it's not fully downloaded
|
||||
let lockfile_path = tarball_path.with_extension("lock");
|
||||
@@ -537,8 +446,8 @@ impl EphemeralContextGuard {
|
||||
cmd.arg(series)
|
||||
.arg(tarball_path.to_string_lossy().to_string());
|
||||
|
||||
if let Some(u) = ui {
|
||||
cmd.capture(u.sink());
|
||||
if let Some(s) = view.sink() {
|
||||
cmd.capture(s);
|
||||
}
|
||||
|
||||
let status = cmd.status()?;
|
||||
@@ -575,7 +484,7 @@ impl EphemeralContextGuard {
|
||||
fn extract_tarball(
|
||||
tarball_path: &PathBuf,
|
||||
chroot_path: &PathBuf,
|
||||
ui: Option<&DebUi>,
|
||||
view: &dyn BuildView,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Create the chroot directory
|
||||
fs::create_dir_all(chroot_path)?;
|
||||
@@ -590,18 +499,19 @@ impl EphemeralContextGuard {
|
||||
// too expensive for multi-hundred-MB chroot tarballs)
|
||||
let mut count = 0usize;
|
||||
for entry in archive.entries()? {
|
||||
// Bail on a Ctrl+C before the interrupt watchdog's rm -rf races
|
||||
// this loop writing entries into the tree being removed
|
||||
if crate::interrupt::interrupted() {
|
||||
return Err("Interrupted while extracting the chroot".into());
|
||||
}
|
||||
let mut entry = entry?;
|
||||
entry.unpack_in(chroot_path)?;
|
||||
count += 1;
|
||||
if count.is_multiple_of(100)
|
||||
&& let Some(u) = ui
|
||||
{
|
||||
u.progress_message(&format!("Extracting chroot… ({count} files)"));
|
||||
if count.is_multiple_of(100) {
|
||||
view.message(&format!("Extracting chroot… ({count} files)"));
|
||||
}
|
||||
}
|
||||
if let Some(u) = ui {
|
||||
u.progress_message(&format!("Extracting chroot… ({count} files)"));
|
||||
}
|
||||
view.message(&format!("Extracting chroot… ({count} files)"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -711,6 +621,20 @@ impl EphemeralContextGuard {
|
||||
|
||||
impl Drop for EphemeralContextGuard {
|
||||
fn drop(&mut self) {
|
||||
// On Ctrl+C the interrupt watchdog owns the chroot teardown through
|
||||
// the registered hook: duplicating it here would race the hook's
|
||||
// umount/rm (mounts vanish under each other). Dropping this guard
|
||||
// would normally deregister the hook, so while the watchdog runs it
|
||||
// must be leaked instead to keep it registered (if it was already
|
||||
// drained, forgetting is a harmless no-op).
|
||||
if crate::interrupt::interrupted() {
|
||||
context::manager().set_current_ephemeral(self.previous_context.clone());
|
||||
if let Some(hook) = self.cleanup_hook.take() {
|
||||
std::mem::forget(hook);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Deregister the interrupt-time cleanup hook first: the normal
|
||||
// cleanup below takes care of the chroot, so the hook must not fire
|
||||
// afterwards. (If a SIGINT arrived mid-drop and the hook is already
|
||||
@@ -808,129 +732,8 @@ impl Drop for EphemeralContextGuard {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cleanup_registry_tests {
|
||||
mod chroot_cleanup_tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
/// Serializes these tests: they drain the process-global registry, and
|
||||
/// unrelated tests (e.g. live end-to-end builds) may hold registrations
|
||||
/// concurrently that must be neither run nor lost. Poison-proof: a test
|
||||
/// failing while holding the lock must not cascade into the others.
|
||||
static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Drain the registry and take out only the hooks with the given ids,
|
||||
/// putting everything else back so unrelated registrations (e.g. hooks of
|
||||
/// live end-to-end builds running concurrently) stay pending
|
||||
fn take_hooks(ids: &[u64]) -> Vec<CleanupHook> {
|
||||
let drained = drain_cleanup_hooks();
|
||||
let mut mine = Vec::new();
|
||||
let mut others = Vec::new();
|
||||
for hook in drained {
|
||||
if ids.contains(&hook.id) {
|
||||
mine.push(hook);
|
||||
} else {
|
||||
others.push(hook);
|
||||
}
|
||||
}
|
||||
CLEANUP_HOOKS.lock().unwrap().extend(others);
|
||||
mine
|
||||
}
|
||||
|
||||
/// Register a hook that counts its invocations
|
||||
fn counting_hook() -> (CleanupHookGuard, Arc<AtomicUsize>) {
|
||||
let counter = Arc::new(AtomicUsize::new(0));
|
||||
let seen = counter.clone();
|
||||
let guard = register_cleanup_hook(Box::new(move || {
|
||||
seen.fetch_add(1, Ordering::SeqCst);
|
||||
}));
|
||||
(guard, counter)
|
||||
}
|
||||
|
||||
/// Hooks run in registration order, and draining means each hook runs
|
||||
/// exactly once even across repeated cleanup passes.
|
||||
#[test]
|
||||
fn hooks_run_once_in_registration_order() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut guards = Vec::new();
|
||||
let mut ids = Vec::new();
|
||||
for name in ["hook-a", "hook-b", "hook-c"] {
|
||||
let log = log.clone();
|
||||
// The returned guard must stay alive: dropping it deregisters
|
||||
let guard = register_cleanup_hook(Box::new(move || log.lock().unwrap().push(name)));
|
||||
ids.push(guard.id());
|
||||
guards.push(guard);
|
||||
}
|
||||
|
||||
// Only our own hooks are extracted; they run in registration order
|
||||
let mine = take_hooks(&ids);
|
||||
assert_eq!(mine.len(), ids.len());
|
||||
run_drained_hooks(mine);
|
||||
assert_eq!(*log.lock().unwrap(), vec!["hook-a", "hook-b", "hook-c"]);
|
||||
|
||||
// Draining removed them: a second pass runs nothing again
|
||||
assert!(take_hooks(&ids).is_empty());
|
||||
assert_eq!(*log.lock().unwrap(), vec!["hook-a", "hook-b", "hook-c"]);
|
||||
|
||||
drop(guards);
|
||||
}
|
||||
|
||||
/// A panicking hook is contained by the runner: it neither aborts the
|
||||
/// process nor skips the hooks registered around it.
|
||||
#[test]
|
||||
fn panicking_hook_does_not_skip_the_others() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let (before, ran_before) = counting_hook();
|
||||
let boom = register_cleanup_hook(Box::new(|| panic!("cleanup exploded")));
|
||||
let (after, ran_after) = counting_hook();
|
||||
|
||||
let ids = [before.id(), boom.id(), after.id()];
|
||||
run_drained_hooks(take_hooks(&ids));
|
||||
|
||||
assert_eq!(ran_before.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(ran_after.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// Explicit deregistration removes the hook: it is no longer drained and
|
||||
/// never runs; a second deregistration reports it as already gone.
|
||||
#[test]
|
||||
fn deregistered_hook_never_runs() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let (mut guard, ran) = counting_hook();
|
||||
|
||||
assert!(guard.deregister());
|
||||
assert!(!guard.deregister());
|
||||
|
||||
assert!(take_hooks(&[guard.id()]).is_empty());
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
/// Dropping the registration guard deregisters the hook implicitly.
|
||||
#[test]
|
||||
fn dropping_the_guard_deregisters_the_hook() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let id;
|
||||
let ran;
|
||||
{
|
||||
let (guard, counter) = counting_hook();
|
||||
id = guard.id();
|
||||
ran = counter;
|
||||
drop(guard);
|
||||
}
|
||||
|
||||
assert!(take_hooks(&[id]).is_empty());
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
/// /proc/mounts path fields use octal escapes for whitespace and
|
||||
/// backslashes; anything else must be kept verbatim.
|
||||
|
||||
+830
-149
File diff suppressed because it is too large
Load Diff
+545
-117
@@ -5,7 +5,11 @@ pub(crate) mod ephemeral;
|
||||
mod local;
|
||||
|
||||
use crate::context::{self, Context};
|
||||
use crate::ui::deb::{DebUi, Phase};
|
||||
use crate::logfmt::{
|
||||
AptInstallClassifier, AptUpdateClassifier, Classifier, GenericClassifier, MakeClassifier,
|
||||
MmdebstrapClassifier, QuiltClassifier,
|
||||
};
|
||||
use crate::report::{BuildTarget, BuildView};
|
||||
use std::error::Error;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -17,67 +21,163 @@ pub enum BuildMode {
|
||||
Local,
|
||||
}
|
||||
|
||||
/// Phases of a binary build, announced to the [`BuildView`]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
/// Downloading the chroot tarball (mmdebstrap)
|
||||
PreparingChroot,
|
||||
/// Extracting the chroot tarball
|
||||
ExtractingChroot,
|
||||
/// Device nodes, /proc bind mount, etc.
|
||||
FinalizingChroot,
|
||||
/// apt-get update
|
||||
UpdatingPackageLists,
|
||||
/// Installing build-essential & co
|
||||
InstallingEssentials,
|
||||
/// quilt push -a
|
||||
ApplyingPatches,
|
||||
/// --inject packages
|
||||
InjectingPackages,
|
||||
/// apt-get build-dep
|
||||
InstallingBuildDeps,
|
||||
/// debian/rules build
|
||||
Building,
|
||||
/// fakeroot debian/rules binary
|
||||
ProducingBinaries,
|
||||
/// Retrieving produced .deb files
|
||||
RetrievingArtifacts,
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
/// Human-readable label displayed in the status bar
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Phase::PreparingChroot => "Preparing chroot",
|
||||
Phase::ExtractingChroot => "Extracting chroot",
|
||||
Phase::FinalizingChroot => "Finalizing chroot",
|
||||
Phase::UpdatingPackageLists => "Updating package lists",
|
||||
Phase::InstallingEssentials => "Installing essential packages",
|
||||
Phase::ApplyingPatches => "Applying patches",
|
||||
Phase::InjectingPackages => "Injecting packages",
|
||||
Phase::InstallingBuildDeps => "Installing build dependencies",
|
||||
Phase::Building => "Building package",
|
||||
Phase::ProducingBinaries => "Producing binary packages",
|
||||
Phase::RetrievingArtifacts => "Retrieving artifacts",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Default line classifier rewriting a phase's subprocess output
|
||||
fn default_classifier(phase: Phase) -> Box<dyn Classifier> {
|
||||
match phase {
|
||||
Phase::PreparingChroot => Box::new(MmdebstrapClassifier::new()),
|
||||
Phase::ExtractingChroot | Phase::FinalizingChroot => Box::new(GenericClassifier::new()),
|
||||
Phase::UpdatingPackageLists => Box::new(AptUpdateClassifier::new()),
|
||||
Phase::InstallingEssentials => Box::new(AptInstallClassifier::new("Installing essentials")),
|
||||
Phase::ApplyingPatches => Box::new(QuiltClassifier::new(0)),
|
||||
Phase::InjectingPackages => Box::new(AptInstallClassifier::new("Injecting packages")),
|
||||
Phase::InstallingBuildDeps => {
|
||||
Box::new(AptInstallClassifier::new("Installing build dependencies"))
|
||||
}
|
||||
Phase::Building | Phase::ProducingBinaries => Box::new(MakeClassifier::new()),
|
||||
Phase::RetrievingArtifacts => Box::new(GenericClassifier::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter `phase` on the view with its default line classifier
|
||||
pub(crate) fn enter_phase(view: &dyn BuildView, phase: Phase) {
|
||||
view.phase(phase.label(), default_classifier(phase));
|
||||
}
|
||||
|
||||
/// Parameters of one [`build_binary_package`] call.
|
||||
pub struct DebBuildOptions<'a> {
|
||||
/// Target architecture; defaults to the host architecture.
|
||||
pub arch: Option<String>,
|
||||
/// Target distribution series; defaults to the changelog series
|
||||
/// (UNRELEASED resolves to the vendor's development series).
|
||||
pub series: Option<String>,
|
||||
/// Distribution pocket to resolve build-dependencies from.
|
||||
pub pocket: Option<String>,
|
||||
/// Source tree to build; defaults to the process working directory.
|
||||
pub cwd: Option<PathBuf>,
|
||||
/// Cross-compile for the target architecture instead of using
|
||||
/// qemu-binfmt.
|
||||
pub cross: bool,
|
||||
/// Build mode; defaults to [`BuildMode::Local`].
|
||||
pub mode: Option<BuildMode>,
|
||||
/// PPAs to add for build-dependencies (`user/ppa_name`).
|
||||
pub ppa: Vec<String>,
|
||||
/// Packages to inject into the build environment before build-dep
|
||||
/// (.deb paths, archive names or PPA packages).
|
||||
pub inject: Vec<String>,
|
||||
/// Parallel build jobs; defaults to the core count available in the
|
||||
/// build context.
|
||||
pub jobs: Option<usize>,
|
||||
/// Explicit build context; defaults to the current context.
|
||||
pub ctx: Option<Arc<Context>>,
|
||||
/// Where build events (phases, progress, outcome) are reported.
|
||||
pub view: &'a dyn BuildView,
|
||||
}
|
||||
|
||||
impl Default for DebBuildOptions<'_> {
|
||||
fn default() -> Self {
|
||||
static QUIET: crate::report::Quiet = crate::report::Quiet;
|
||||
DebBuildOptions {
|
||||
arch: None,
|
||||
series: None,
|
||||
pocket: None,
|
||||
cwd: None,
|
||||
cross: false,
|
||||
mode: None,
|
||||
ppa: Vec::new(),
|
||||
inject: Vec::new(),
|
||||
jobs: None,
|
||||
ctx: None,
|
||||
view: &QUIET,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build package in 'cwd' to a .deb
|
||||
///
|
||||
/// Returns the list of produced artifacts (.deb files plus the upload
|
||||
/// metadata `.buildinfo`/`.changes`) retrieved locally, identified from
|
||||
/// `debian/files` and the native metadata generation rather than by
|
||||
/// globbing the build root (which would surface stale files). When `ui` is
|
||||
/// set, a live view (status bar + rolling log pane) is displayed and all
|
||||
/// subprocess output is captured through it; on failure the widget is
|
||||
/// cleared and a summary of captured errors is printed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// globbing the build root (which would surface stale files). Subprocess
|
||||
/// output is captured through the view's sink (live view + tee log for the
|
||||
/// terminal adapter); on failure the view is cleared and prints a summary
|
||||
/// of captured errors.
|
||||
pub async fn build_binary_package(
|
||||
arch: Option<&str>,
|
||||
series: Option<&str>,
|
||||
pocket: Option<&str>,
|
||||
cwd: Option<&Path>,
|
||||
cross: bool,
|
||||
mode: Option<BuildMode>,
|
||||
ppa: Option<&[&str]>,
|
||||
inject_packages: Option<&[&str]>,
|
||||
ctx: Option<Arc<Context>>,
|
||||
ui: Option<Arc<DebUi>>,
|
||||
jobs: Option<usize>,
|
||||
opts: DebBuildOptions<'_>,
|
||||
) -> Result<Vec<PathBuf>, Box<dyn Error>> {
|
||||
let result = build_binary_package_impl(
|
||||
arch,
|
||||
series,
|
||||
pocket,
|
||||
cwd,
|
||||
cross,
|
||||
mode,
|
||||
ppa,
|
||||
inject_packages,
|
||||
ctx,
|
||||
&ui,
|
||||
jobs,
|
||||
)
|
||||
.await;
|
||||
let view = opts.view;
|
||||
let result = build_binary_package_impl(opts).await;
|
||||
|
||||
if let (Some(u), Err(_)) = (&ui, &result) {
|
||||
u.finish_failure();
|
||||
if result.is_err() {
|
||||
view.finish_failure();
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Implementation of [`build_binary_package`], without failure handling
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn build_binary_package_impl(
|
||||
arch: Option<&str>,
|
||||
series: Option<&str>,
|
||||
pocket: Option<&str>,
|
||||
cwd: Option<&Path>,
|
||||
cross: bool,
|
||||
mode: Option<BuildMode>,
|
||||
ppa: Option<&[&str]>,
|
||||
inject_packages: Option<&[&str]>,
|
||||
ctx: Option<Arc<Context>>,
|
||||
ui: &Option<Arc<DebUi>>,
|
||||
jobs: Option<usize>,
|
||||
opts: DebBuildOptions<'_>,
|
||||
) -> Result<Vec<PathBuf>, Box<dyn Error>> {
|
||||
let cwd = cwd.unwrap_or_else(|| Path::new("."));
|
||||
let DebBuildOptions {
|
||||
ref arch,
|
||||
ref series,
|
||||
ref pocket,
|
||||
ref cwd,
|
||||
cross,
|
||||
ref mode,
|
||||
ref ppa,
|
||||
ref inject,
|
||||
ref jobs,
|
||||
ref ctx,
|
||||
view,
|
||||
} = opts;
|
||||
let cwd = cwd.as_deref().unwrap_or_else(|| Path::new("."));
|
||||
|
||||
// Parse changelog to get package name, version and series
|
||||
let changelog_path = cwd.join("debian/changelog");
|
||||
@@ -101,44 +201,45 @@ async fn build_binary_package_impl(
|
||||
&package_series
|
||||
};
|
||||
let current_arch = crate::get_current_arch();
|
||||
let arch = arch.unwrap_or(¤t_arch);
|
||||
let arch = arch.as_deref().unwrap_or(¤t_arch);
|
||||
|
||||
// Make sure we select a specific mode, either using user-requested
|
||||
// or by using default for user-supplied parameters
|
||||
let mode = if let Some(m) = mode {
|
||||
m
|
||||
} else {
|
||||
// By default, we use local build
|
||||
BuildMode::Local
|
||||
};
|
||||
let default_mode = BuildMode::Local;
|
||||
let mode = mode.as_ref().unwrap_or(&default_mode);
|
||||
|
||||
// Create an ephemeral unshare context for all Local builds
|
||||
// Use qemu_binfmt when target architecture differs from host and cross is not requested
|
||||
let chroot_arch = if mode == BuildMode::Local && arch != current_arch && !cross {
|
||||
let chroot_arch = if mode == &BuildMode::Local && arch != current_arch && !cross {
|
||||
Some(arch)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Use provided context or get current
|
||||
let base_ctx = ctx.unwrap_or_else(context::current);
|
||||
let base_ctx = ctx.clone().unwrap_or_else(context::current);
|
||||
|
||||
// Identify the target in the live UI once the changelog is parsed, so
|
||||
// Identify the target in the live view once the changelog is parsed, so
|
||||
// even the chroot download output is attributed and tee'd
|
||||
if let Some(u) = ui {
|
||||
u.set_target(&package, &version, series, arch);
|
||||
}
|
||||
view.target(BuildTarget {
|
||||
package: &package,
|
||||
version: &version,
|
||||
target: &format!("{series}/{arch}"),
|
||||
display: format!("Building {package} ({version}) for {series}/{arch}"),
|
||||
source_only: false,
|
||||
tee_log: true,
|
||||
});
|
||||
|
||||
// Create an ephemeral unshare context for all Local builds. It is kept in
|
||||
// this scope so it outlives the guarded section below and is only dropped
|
||||
// once the live view has been cleared.
|
||||
let mut guard = if mode == BuildMode::Local {
|
||||
let mut guard = if *mode == BuildMode::Local {
|
||||
Some(
|
||||
ephemeral::EphemeralContextGuard::new_with_context(
|
||||
series,
|
||||
chroot_arch,
|
||||
base_ctx.clone(),
|
||||
ui.clone(),
|
||||
view,
|
||||
)
|
||||
.await?,
|
||||
)
|
||||
@@ -168,6 +269,19 @@ async fn build_binary_package_impl(
|
||||
.ok_or("Cannot find parent directory name")?;
|
||||
let build_root = format!("{}/{}", build_root, parent_dir_name.to_str().unwrap());
|
||||
|
||||
// Resolve the package directory inside the staging area. The tree
|
||||
// the caller pointed at is authoritative (its changelog defined the
|
||||
// package/version/series above), so its staged copy wins; the
|
||||
// name-pattern search only runs as a fallback.
|
||||
let package_dir = resolve_package_directory(
|
||||
Path::new(&build_root),
|
||||
cwd,
|
||||
&package,
|
||||
&version,
|
||||
series,
|
||||
&build_ctx,
|
||||
)?;
|
||||
|
||||
// Run the build using target build mode. It returns the exact set of
|
||||
// artifacts produced by this build (binary packages registered in
|
||||
// debian/files plus the generated .buildinfo/.changes), as paths
|
||||
@@ -179,14 +293,15 @@ async fn build_binary_package_impl(
|
||||
&version,
|
||||
arch,
|
||||
series,
|
||||
pocket,
|
||||
pocket.as_deref(),
|
||||
&build_root,
|
||||
&package_dir,
|
||||
cross,
|
||||
ppa,
|
||||
inject_packages,
|
||||
inject,
|
||||
build_ctx.clone(),
|
||||
ui.clone(),
|
||||
jobs,
|
||||
view,
|
||||
*jobs,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
@@ -194,9 +309,7 @@ async fn build_binary_package_impl(
|
||||
|
||||
// Retrieve the produced artifacts (binary packages plus the upload
|
||||
// metadata) to the parent directory.
|
||||
if let Some(u) = ui {
|
||||
u.phase(Phase::RetrievingArtifacts);
|
||||
}
|
||||
enter_phase(view, Phase::RetrievingArtifacts);
|
||||
let total_debs = remote_files.len();
|
||||
|
||||
let mut artifacts = Vec::with_capacity(total_debs);
|
||||
@@ -206,14 +319,10 @@ async fn build_binary_package_impl(
|
||||
build_ctx.retrieve_path(remote_file, &local_dest)?;
|
||||
artifacts.push(local_dest);
|
||||
|
||||
if let Some(u) = ui {
|
||||
u.count_progress("Retrieving artifacts", idx + 1, total_debs);
|
||||
}
|
||||
view.progress("Retrieving artifacts", idx + 1, total_debs);
|
||||
}
|
||||
|
||||
if let Some(u) = ui {
|
||||
u.finish_success(&artifacts, u.elapsed());
|
||||
}
|
||||
view.finish_success(&artifacts);
|
||||
|
||||
Ok(artifacts)
|
||||
}
|
||||
@@ -222,9 +331,7 @@ async fn build_binary_package_impl(
|
||||
// Clear the live view before returning: the ephemeral guard is dropped at
|
||||
// the end of this function and its cleanup commands (umount, rm -rf of
|
||||
// the chroot) inherit the terminal, so they must not fight the widget.
|
||||
if let Some(u) = ui {
|
||||
u.suspend();
|
||||
}
|
||||
view.suspend();
|
||||
|
||||
// Mark build as successful to trigger chroot cleanup
|
||||
if result.is_ok()
|
||||
@@ -236,6 +343,38 @@ async fn build_binary_package_impl(
|
||||
result
|
||||
}
|
||||
|
||||
/// Resolve the package directory for a build inside the staged build root.
|
||||
///
|
||||
/// The tree the caller pointed at is authoritative: `cwd`'s changelog
|
||||
/// already defined the package, version and series for this build, so its
|
||||
/// staged copy is used outright when it carries a `debian/` tree. The
|
||||
/// name-pattern search ([`find_package_directory`], including the quirks
|
||||
/// overrides) only runs when that copy cannot be resolved — a default `.`
|
||||
/// cwd has no basename, and the pointed-at tree may live outside the staged
|
||||
/// parent. Embedded callers are the motivation: their working directory
|
||||
/// names (`tree`, `checkout`, ...) match none of the search patterns.
|
||||
pub(crate) fn resolve_package_directory(
|
||||
build_root: &Path,
|
||||
cwd: &Path,
|
||||
package: &str,
|
||||
version: &str,
|
||||
series: &str,
|
||||
ctx: &context::Context,
|
||||
) -> Result<PathBuf, Box<dyn Error>> {
|
||||
if let Some(tree_name) = cwd.file_name() {
|
||||
let staged_tree = build_root.join(tree_name);
|
||||
if ctx.is_dir(&staged_tree)? && ctx.exists(&staged_tree.join("debian"))? {
|
||||
log::debug!(
|
||||
"Using the staged copy of {} at {}",
|
||||
cwd.display(),
|
||||
staged_tree.display()
|
||||
);
|
||||
return Ok(staged_tree);
|
||||
}
|
||||
}
|
||||
find_package_directory(build_root, package, version, series, ctx)
|
||||
}
|
||||
|
||||
/// Find the current package directory by trying both patterns:
|
||||
/// - package/package
|
||||
/// - package/package-origversion
|
||||
@@ -244,10 +383,11 @@ pub(crate) fn find_package_directory(
|
||||
parent_dir: &Path,
|
||||
package: &str,
|
||||
version: &str,
|
||||
series: &str,
|
||||
ctx: &context::Context,
|
||||
) -> Result<PathBuf, Box<dyn Error>> {
|
||||
// Check quirks first for custom package directories
|
||||
let custom_dirs = crate::quirks::get_package_directories(package);
|
||||
let custom_dirs = crate::quirks::get_package_directories(package, series);
|
||||
for custom_dir in custom_dirs {
|
||||
let package_dir = parent_dir.join(&custom_dir);
|
||||
if ctx.exists(&package_dir)? && ctx.exists(&package_dir.join("debian"))? {
|
||||
@@ -319,11 +459,13 @@ pub(crate) fn find_package_directory(
|
||||
let entries = ctx.list_files(package_parent)?;
|
||||
let mut found_dirs = Vec::new();
|
||||
for entry in entries {
|
||||
if entry.is_dir() {
|
||||
if let Some(file_name) = entry.file_name() {
|
||||
found_dirs.push(file_name.to_string_lossy().into_owned());
|
||||
}
|
||||
log::debug!(" - {}", entry.display());
|
||||
// list_files yields context-relative paths (e.g. rooted inside
|
||||
// the chroot for an unshare context): classify through the
|
||||
// context, a host-side stat would miss every entry.
|
||||
let is_dir = ctx.is_dir(&entry)?;
|
||||
log::debug!(" - {}", entry.display());
|
||||
if is_dir && let Some(file_name) = entry.file_name() {
|
||||
found_dirs.push(file_name.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,12 +508,15 @@ fn find_dsc_file(
|
||||
}
|
||||
|
||||
/// Check whether an apt source URI points to a distribution archive
|
||||
/// (as opposed to a PPA or another third-party repository)
|
||||
/// (as opposed to a PPA or another third-party repository): a thin,
|
||||
/// dist-agnostic wrapper over [`crate::distro_info::is_official_source`],
|
||||
/// unioned across every known distro. Where the distribution is known,
|
||||
/// the dist-scoped check is preferred (it cannot misfire on another
|
||||
/// distro's mirror); this fallback stays for the sites that cannot know.
|
||||
pub(crate) fn is_archive_source(uri: &str) -> bool {
|
||||
uri.contains("archive.ubuntu.com")
|
||||
|| uri.contains("security.ubuntu.com")
|
||||
|| uri.contains("ports.ubuntu.com")
|
||||
|| uri.contains("deb.debian.org")
|
||||
crate::distro_info::supported_dists()
|
||||
.iter()
|
||||
.any(|dist| crate::distro_info::is_official_source(dist, uri))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -379,6 +524,126 @@ mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The archive check is dist-agnostic (any distro's official mirror
|
||||
/// counts) and host-based: the country mirrors the old substring
|
||||
/// checks matched (`fr.archive.ubuntu.com`) still count, look-alike
|
||||
/// hosts and PPAs do not.
|
||||
#[test]
|
||||
fn archive_sources_are_official_mirrors_of_any_distro() {
|
||||
for uri in [
|
||||
"https://archive.ubuntu.com/ubuntu",
|
||||
// Country mirrors front the Ubuntu archive.
|
||||
"http://fr.archive.ubuntu.com/ubuntu",
|
||||
"http://security.ubuntu.com/ubuntu",
|
||||
"http://ports.ubuntu.com/ubuntu-ports",
|
||||
"https://deb.debian.org/debian",
|
||||
] {
|
||||
assert!(is_archive_source(uri), "{uri}");
|
||||
}
|
||||
for uri in [
|
||||
"https://ppa.launchpadcontent.net/user/ppa/ubuntu",
|
||||
"http://notarchive.ubuntu.com/ubuntu",
|
||||
"https://example.com/debian",
|
||||
] {
|
||||
assert!(!is_archive_source(uri), "{uri}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An unshare context mapped over `chroot_root`, parented on a local
|
||||
/// context like the ephemeral build contexts are: exists/list_files/
|
||||
/// is_dir answer through the path mapping, no namespace privileges
|
||||
/// needed.
|
||||
fn unshare_test_context(chroot_root: &Path) -> Context {
|
||||
let base = Context::new(crate::context::ContextConfig::Local).unwrap();
|
||||
Context::with_parent(
|
||||
crate::context::ContextConfig::Unshare {
|
||||
path: chroot_root.to_string_lossy().to_string(),
|
||||
parent: None,
|
||||
},
|
||||
Arc::new(base),
|
||||
)
|
||||
}
|
||||
|
||||
/// The staging-area listing must classify entries through the context:
|
||||
/// an unshare context returns build-root-relative paths that a host-side
|
||||
/// stat never sees (they live under the chroot root on the host), which
|
||||
/// used to silently empty the 'Found directories' list of the search
|
||||
/// failure message — and with it every hint about the actual layout.
|
||||
#[test]
|
||||
fn find_package_directory_lists_staged_directories_through_the_context() {
|
||||
let chroot = tempfile::tempdir().unwrap();
|
||||
// Staged parent holding a single tree whose name matches none of
|
||||
// the search patterns (the embedded-caller layout: <job>/tree)
|
||||
let staged_parent = chroot.path().join("tmp/pkh-build-1/j-42");
|
||||
std::fs::create_dir_all(staged_parent.join("tree/debian")).unwrap();
|
||||
|
||||
let ctx = unshare_test_context(chroot.path());
|
||||
let err = find_package_directory(
|
||||
Path::new("/tmp/pkh-build-1/j-42"),
|
||||
"bc",
|
||||
"1.07.1-1ubuntu1",
|
||||
"questing",
|
||||
&ctx,
|
||||
)
|
||||
.expect_err("no candidate matches a tree named 'tree'");
|
||||
|
||||
let message = err.to_string();
|
||||
assert!(
|
||||
message.contains("Found directories: tree"),
|
||||
"error should list the staged directories through the context: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An explicit cwd must resolve to its staged copy even when its name
|
||||
/// matches none of the search patterns: the pointed-at tree is what the
|
||||
/// parsed changelog came from.
|
||||
#[test]
|
||||
fn resolve_package_directory_prefers_the_pointed_tree() {
|
||||
let chroot = tempfile::tempdir().unwrap();
|
||||
let staged_parent = chroot.path().join("tmp/pkh-build-1/j-42");
|
||||
std::fs::create_dir_all(staged_parent.join("tree/debian/source")).unwrap();
|
||||
|
||||
let ctx = unshare_test_context(chroot.path());
|
||||
let resolved = resolve_package_directory(
|
||||
Path::new("/tmp/pkh-build-1/j-42"),
|
||||
Path::new("/work/jobs/j-42/tree"),
|
||||
"bc",
|
||||
"1.07.1-1ubuntu1",
|
||||
"questing",
|
||||
&ctx,
|
||||
)
|
||||
.expect("the staged copy of the pointed-at tree must resolve");
|
||||
|
||||
assert_eq!(resolved, PathBuf::from("/tmp/pkh-build-1/j-42/tree"));
|
||||
}
|
||||
|
||||
/// When the pointed-at tree is not in the staging area under its own
|
||||
/// name, resolution falls back to the name-pattern search.
|
||||
#[test]
|
||||
fn resolve_package_directory_falls_back_to_the_name_search() {
|
||||
let chroot = tempfile::tempdir().unwrap();
|
||||
let staged_parent = chroot.path().join("tmp/pkh-build-1/j-42");
|
||||
// Staged copy of a pulled tree: <pkg>/<pkg>-<origversion>
|
||||
std::fs::create_dir_all(staged_parent.join("bc/bc-1.07.1/debian")).unwrap();
|
||||
|
||||
let ctx = unshare_test_context(chroot.path());
|
||||
let resolved = resolve_package_directory(
|
||||
Path::new("/tmp/pkh-build-1/j-42"),
|
||||
// A tree never staged under that name
|
||||
Path::new("/work/other/checkout"),
|
||||
"bc",
|
||||
"1.07.1-1ubuntu1",
|
||||
"questing",
|
||||
&ctx,
|
||||
)
|
||||
.expect("the pulled-tree layout must resolve via the name search");
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
PathBuf::from("/tmp/pkh-build-1/j-42/bc/bc-1.07.1")
|
||||
);
|
||||
}
|
||||
|
||||
async fn test_build_end_to_end(
|
||||
package: &str,
|
||||
series: &str,
|
||||
@@ -412,25 +677,25 @@ mod tests {
|
||||
let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
|
||||
// Change directory to the package directory
|
||||
let cwd =
|
||||
crate::deb::find_package_directory(cwd, package, &package_info.stanza.version, &ctx)
|
||||
.expect("Cannot find package directory");
|
||||
let cwd = crate::deb::find_package_directory(
|
||||
cwd,
|
||||
package,
|
||||
&package_info.stanza.version,
|
||||
series,
|
||||
&ctx,
|
||||
)
|
||||
.expect("Cannot find package directory");
|
||||
log::debug!("Package directory: {}", cwd.display());
|
||||
|
||||
log::info!("Starting binary package build...");
|
||||
crate::deb::build_binary_package(
|
||||
arch,
|
||||
Some(series),
|
||||
None,
|
||||
Some(&cwd),
|
||||
crate::deb::build_binary_package(DebBuildOptions {
|
||||
arch: arch.map(str::to_string),
|
||||
series: Some(series.to_string()),
|
||||
cross,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(ctx),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
cwd: Some(cwd.to_path_buf()),
|
||||
ctx: Some(ctx),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("Cannot build binary package (deb)");
|
||||
log::info!("Successfully built binary package");
|
||||
@@ -487,12 +752,34 @@ mod tests {
|
||||
/// NOTE: Ideally, we want to run this in CI, but it takes more than 1h
|
||||
/// to fully build the linux-riscv package on an amd64 builder, which is too
|
||||
/// much time
|
||||
/// The series is the current LTS (26.04) rather than an interim one:
|
||||
/// interim series vanish from the mirrors a few months after their EOL
|
||||
/// (questing is already unreachable), an LTS stays pullable for years.
|
||||
#[ignore]
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
async fn test_deb_linux_riscv_ubuntu_cross_end_to_end() {
|
||||
test_build_end_to_end("linux-riscv", "questing", None, Some("riscv64"), true).await;
|
||||
test_build_end_to_end("linux-riscv", "resolute", None, Some("riscv64"), true).await;
|
||||
}
|
||||
|
||||
/// KNOWN-BROKEN cross build of the noble-era kernel, kept as an
|
||||
/// ignored fixture to work from. Noble controls declare their build
|
||||
/// tools unqualified (the `:native` idiom landed later), so exact dpkg
|
||||
/// semantics demand host-architecture instances of them
|
||||
/// (python3:riscv64, gcc-13:riscv64, clang-17:riscv64, ...) and the
|
||||
/// resulting two-architecture install set is unsolvable: t64
|
||||
/// libraries (libclang1-17t64) conflict with their own foreign-arch
|
||||
/// variant, and the riscv64 toolchain instances drag depends chains
|
||||
/// (gcc:riscv64) that do not resolve from the chroot sources. A real
|
||||
/// run fails at the apt transaction with 'Unable to correct problems'.
|
||||
/// Resolute-era controls declare :native properly; see the test above.
|
||||
#[ignore]
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
async fn test_deb_linux_riscv_noble_cross_end_to_end() {
|
||||
test_build_end_to_end("linux-riscv", "noble", None, Some("riscv64"), true).await;
|
||||
}
|
||||
|
||||
/// This is a specific test case for the latest gcc package on Debian
|
||||
@@ -592,19 +879,14 @@ mod tests {
|
||||
|
||||
let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
|
||||
crate::deb::build_binary_package(
|
||||
Some("arm64"),
|
||||
Some("noble"),
|
||||
None,
|
||||
Some(&pkg_dir),
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(ctx),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
crate::deb::build_binary_package(DebBuildOptions {
|
||||
arch: Some("arm64".to_string()),
|
||||
series: Some("noble".to_string()),
|
||||
cwd: Some(pkg_dir),
|
||||
cross: true,
|
||||
ctx: Some(ctx),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("Cannot cross-build package declaring Build-Depends-Indep");
|
||||
|
||||
@@ -628,4 +910,150 @@ mod tests {
|
||||
"arch-independant .deb not produced, got: {deb_files:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A cross build whose build-dependencies cannot be satisfied under
|
||||
/// dpkg's cross semantics must abort at the install step, naming the
|
||||
/// unsatisfied dependency: the expected-failure counterpart of the
|
||||
/// cross builds above.
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
async fn test_deb_cross_unsatisfiable_build_dep_fails_end_to_end() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let pkg_dir = temp_dir.path().join("pkh-crosstest");
|
||||
std::fs::create_dir_all(pkg_dir.join("debian/source")).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
pkg_dir.join("debian/changelog"),
|
||||
"pkh-crosstest (1.0) noble; urgency=medium\n\n \
|
||||
* Synthetic package declaring an unsatisfiable build-dependency.\n\n \
|
||||
-- pkh tests <pkh@example.com> Tue, 15 Sep 2026 08:00:00 +0000\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
pkg_dir.join("debian/control"),
|
||||
"Source: pkh-crosstest\n\
|
||||
Section: devel\n\
|
||||
Priority: optional\n\
|
||||
Maintainer: pkh tests <pkh@example.com>\n\
|
||||
Standards-Version: 4.7.4\n\
|
||||
Build-Depends: pkh-no-such-package-xyz\n\
|
||||
Architecture: any\n\
|
||||
\n\
|
||||
Package: pkh-crosstest\n\
|
||||
Architecture: any\n\
|
||||
Depends: ${misc:Depends}, ${shlibs:Depends}\n\
|
||||
Description: Cross-build negative regression package\n \
|
||||
Declares a build-dependency absent from the archive.\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
pkg_dir.join("debian/rules"),
|
||||
"#!/usr/bin/make -f\n%:\n\tdh $@\n",
|
||||
)
|
||||
.unwrap();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let rules = pkg_dir.join("debian/rules");
|
||||
let mut perms = std::fs::metadata(&rules).unwrap().permissions();
|
||||
perms.set_mode(0o755);
|
||||
std::fs::set_permissions(&rules, perms).unwrap();
|
||||
|
||||
std::fs::write(pkg_dir.join("debian/source/format"), "3.0 (native)\n").unwrap();
|
||||
|
||||
let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
|
||||
let err = crate::deb::build_binary_package(DebBuildOptions {
|
||||
arch: Some("arm64".to_string()),
|
||||
series: Some("noble".to_string()),
|
||||
cwd: Some(pkg_dir),
|
||||
cross: true,
|
||||
ctx: Some(ctx),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect_err("an unsatisfiable build-dependency must fail the cross build");
|
||||
|
||||
assert!(
|
||||
err.to_string().contains("pkh-no-such-package-xyz"),
|
||||
"error should name the unsatisfied dependency: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An embedded-caller layout — the tree checked out at <job>/tree, a
|
||||
/// name matching none of the search patterns — must build: the staged
|
||||
/// copy of the tree the caller pointed at is resolved directly instead
|
||||
/// of being re-derived from package/version names (which used to fail
|
||||
/// with 'Could not find package directory').
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_deb_builds_a_tree_named_directory_end_to_end() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let pkg_dir = temp_dir.path().join("j-42/tree");
|
||||
std::fs::create_dir_all(pkg_dir.join("debian/source")).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
pkg_dir.join("debian/changelog"),
|
||||
"pkh-treetest (1.0) noble; urgency=medium\n\n \
|
||||
* Synthetic package built from a directory named 'tree'.\n\n \
|
||||
-- pkh tests <pkh@example.com> Tue, 15 Sep 2026 08:00:00 +0000\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
pkg_dir.join("debian/control"),
|
||||
"Source: pkh-treetest\n\
|
||||
Section: devel\n\
|
||||
Priority: optional\n\
|
||||
Maintainer: pkh tests <pkh@example.com>\n\
|
||||
Standards-Version: 4.7.4\n\
|
||||
Build-Depends: debhelper-compat (= 13)\n\
|
||||
Architecture: any\n\
|
||||
\n\
|
||||
Package: pkh-treetest\n\
|
||||
Architecture: any\n\
|
||||
Depends: ${misc:Depends}, ${shlibs:Depends}\n\
|
||||
Description: Package-directory resolution regression package\n \
|
||||
Its tree lives in a directory whose name matches none of the\n \
|
||||
package-directory search patterns.\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
pkg_dir.join("debian/rules"),
|
||||
"#!/usr/bin/make -f\n%:\n\tdh $@\n",
|
||||
)
|
||||
.unwrap();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let rules = pkg_dir.join("debian/rules");
|
||||
let mut perms = std::fs::metadata(&rules).unwrap().permissions();
|
||||
perms.set_mode(0o755);
|
||||
std::fs::set_permissions(&rules, perms).unwrap();
|
||||
|
||||
std::fs::write(pkg_dir.join("debian/source/format"), "3.0 (native)\n").unwrap();
|
||||
|
||||
let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
|
||||
crate::deb::build_binary_package(DebBuildOptions {
|
||||
series: Some("noble".to_string()),
|
||||
cwd: Some(pkg_dir),
|
||||
ctx: Some(ctx),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("a tree named 'tree' must build");
|
||||
|
||||
let deb_files: Vec<String> = std::fs::read_dir(temp_dir.path().join("j-42"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert!(
|
||||
deb_files
|
||||
.iter()
|
||||
.any(|f| f.starts_with("pkh-treetest_1.0_") && f.ends_with(".deb")),
|
||||
".deb not produced for the 'tree'-named directory, got: {deb_files:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+167
-41
@@ -36,8 +36,12 @@ pub struct ChangelogEntry {
|
||||
pub closes: Option<String>,
|
||||
}
|
||||
|
||||
/// Parse the most recent entry of a Debian changelog file.
|
||||
pub fn parse_changelog_entry(path: &Path) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
|
||||
/// Parse up to `limit` entries of a Debian changelog file, newest first
|
||||
/// (`None` parses the whole file).
|
||||
pub fn parse_changelog_entries(
|
||||
path: &Path,
|
||||
limit: Option<usize>,
|
||||
) -> Result<Vec<ChangelogEntry>, Box<dyn std::error::Error>> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| {
|
||||
format!(
|
||||
"failed to read changelog '{}': {}. Make sure you are running \
|
||||
@@ -46,17 +50,60 @@ pub fn parse_changelog_entry(path: &Path) -> Result<ChangelogEntry, Box<dyn std:
|
||||
e
|
||||
)
|
||||
})?;
|
||||
parse_changelog_entry_from_str(&content)
|
||||
parse_changelog_entries_from_str(&content, limit)
|
||||
}
|
||||
|
||||
/// Parse the most recent changelog entry from its textual content. `origin`
|
||||
/// is used in error messages only.
|
||||
/// Parse the most recent entry of a Debian changelog file.
|
||||
pub fn parse_changelog_entry(path: &Path) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
|
||||
parse_changelog_entries(path, Some(1)).map(|mut entries| entries.remove(0))
|
||||
}
|
||||
|
||||
/// Parse the most recent changelog entry from its textual content.
|
||||
pub fn parse_changelog_entry_from_str(
|
||||
content: &str,
|
||||
) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
|
||||
parse_changelog_entries_from_str(content, Some(1)).map(|mut entries| entries.remove(0))
|
||||
}
|
||||
|
||||
/// Parse changelog entries from their textual content, newest first.
|
||||
///
|
||||
/// `limit` bounds the number of parsed entries (`None` parses the whole
|
||||
/// file). Content below the last entry that is not another entry header
|
||||
/// (e.g. an older changelog kept in a non-Debian format) is ignored.
|
||||
pub fn parse_changelog_entries_from_str(
|
||||
content: &str,
|
||||
limit: Option<usize>,
|
||||
) -> Result<Vec<ChangelogEntry>, Box<dyn std::error::Error>> {
|
||||
let origin = "changelog";
|
||||
let mut lines = content.lines().peekable();
|
||||
let mut entries = Vec::new();
|
||||
loop {
|
||||
if limit.is_some_and(|n| entries.len() >= n) {
|
||||
break;
|
||||
}
|
||||
// Blank separators between entries.
|
||||
while lines.peek().is_some_and(|l| l.trim().is_empty()) {
|
||||
lines.next();
|
||||
}
|
||||
let Some(next) = lines.peek() else {
|
||||
break;
|
||||
};
|
||||
if !entries.is_empty() && !looks_like_header(next.trim_end()) {
|
||||
break;
|
||||
}
|
||||
entries.push(parse_one_entry(&mut lines, origin)?);
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Parse one entry: header line, body, maintainer trailer. Parsing stops
|
||||
/// without consuming the first line that is a trailer terminator, an emacs
|
||||
/// local-variables block, or the next entry's header — the stream can then
|
||||
/// be resumed for the following entry.
|
||||
fn parse_one_entry(
|
||||
lines: &mut std::iter::Peekable<std::str::Lines<'_>>,
|
||||
origin: &str,
|
||||
) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
|
||||
// --- Header line: `package (version) distributions; urgency=medium[, key=value]`
|
||||
let header = loop {
|
||||
match lines.next() {
|
||||
@@ -104,19 +151,21 @@ pub fn parse_changelog_entry_from_str(
|
||||
// --- Body until trailer line ` -- Name <email> Date`
|
||||
let mut body_lines: Vec<String> = Vec::new();
|
||||
let mut trailer: Option<String> = None;
|
||||
for line in lines {
|
||||
while let Some(line) = lines.peek().copied() {
|
||||
let line = line.trim_end();
|
||||
if line.starts_with(" -- ") {
|
||||
trailer = Some(line.to_string());
|
||||
trailer = lines.next().map(|l| l.trim_end().to_string());
|
||||
break;
|
||||
}
|
||||
// Stop at an emacs local-variables block or a new entry header.
|
||||
// Stop at an emacs local-variables block or a new entry header
|
||||
// (both peeked, not consumed).
|
||||
if line.starts_with("Local variables:") {
|
||||
break;
|
||||
}
|
||||
if !line.trim().is_empty() && looks_like_header(line) && !body_lines.is_empty() {
|
||||
break;
|
||||
}
|
||||
lines.next();
|
||||
// Blank lines become "." like dpkg does for the Changes field.
|
||||
if line.trim().is_empty() {
|
||||
body_lines.push(".".to_string());
|
||||
@@ -211,39 +260,6 @@ fn find_closes(body_lines: &[String]) -> Option<String> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Return the version of the *previous* changelog entry (the second header
|
||||
/// in the file), or `None` when only one entry exists.
|
||||
pub fn parse_previous_version(path: &Path) -> Result<Option<String>, Box<dyn std::error::Error>> {
|
||||
let content = std::fs::read_to_string(path)
|
||||
.map_err(|e| format!("failed to read changelog '{}': {}", path.display(), e))?;
|
||||
parse_previous_version_from_str(&content)
|
||||
}
|
||||
|
||||
/// Return the version of the *previous* changelog entry from the textual
|
||||
/// content of a changelog file.
|
||||
pub fn parse_previous_version_from_str(
|
||||
content: &str,
|
||||
) -> Result<Option<String>, Box<dyn std::error::Error>> {
|
||||
let mut seen_first = false;
|
||||
for line in content.lines() {
|
||||
let line = line.trim_end();
|
||||
if looks_like_header(line) {
|
||||
if !seen_first {
|
||||
seen_first = true;
|
||||
continue;
|
||||
}
|
||||
let open = line
|
||||
.find('(')
|
||||
.ok_or_else(|| format!("invalid changelog header: {line}"))?;
|
||||
let close = line[open..]
|
||||
.find(')')
|
||||
.ok_or_else(|| format!("unbalanced parenthesis in changelog header '{line}'"))?;
|
||||
return Ok(Some(line[open + 1..open + close].to_string()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Heuristic check for a changelog entry header line
|
||||
/// (`name (version) dist; urgency=...`).
|
||||
fn looks_like_header(line: &str) -> bool {
|
||||
@@ -309,4 +325,114 @@ pkg (1.0-1+b1) unstable; urgency=medium, binary-only=yes
|
||||
assert!(entry.binary_only);
|
||||
assert_eq!(entry.version.full(), "1.0-1+b1");
|
||||
}
|
||||
|
||||
const THREE_ENTRIES: &str = "\
|
||||
pkg (2.0-1) unstable; urgency=low
|
||||
|
||||
* New upstream release.
|
||||
|
||||
-- Pkh Tester <pkh@example.com> Thu, 01 Jan 2026 00:00:00 +0000
|
||||
|
||||
pkg (1.4-2) unstable; urgency=medium
|
||||
|
||||
* Revision bump.
|
||||
|
||||
-- Pkh Tester <pkh@example.com> Wed, 01 Jan 2025 00:00:00 +0000
|
||||
|
||||
pkg (1.4-1) unstable; urgency=medium
|
||||
|
||||
* Initial release.
|
||||
|
||||
-- Pkh Tester <pkh@example.com> Sat, 01 Mar 2025 00:00:00 +0000
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn entries_parse_newest_first_with_limits() {
|
||||
// Whole file.
|
||||
let all = parse_changelog_entries_from_str(THREE_ENTRIES, None).unwrap();
|
||||
assert_eq!(all.len(), 3);
|
||||
assert_eq!(all[0].version.full(), "2.0-1");
|
||||
assert_eq!(all[1].version.full(), "1.4-2");
|
||||
assert_eq!(all[2].version.full(), "1.4-1");
|
||||
|
||||
// Bounded limits.
|
||||
assert_eq!(
|
||||
parse_changelog_entries_from_str(THREE_ENTRIES, Some(1))
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
let two = parse_changelog_entries_from_str(THREE_ENTRIES, Some(2)).unwrap();
|
||||
assert_eq!(two.len(), 2);
|
||||
assert_eq!(two[0].version.full(), "2.0-1");
|
||||
assert_eq!(two[1].version.full(), "1.4-2");
|
||||
|
||||
// A limit beyond the entry count yields everything.
|
||||
assert_eq!(
|
||||
parse_changelog_entries_from_str(THREE_ENTRIES, Some(10))
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
|
||||
// The single-entry helpers agree with a limit of 1.
|
||||
let one = parse_changelog_entries_from_str(THREE_ENTRIES, Some(1)).unwrap();
|
||||
let via_helper = parse_changelog_entry_from_str(THREE_ENTRIES).unwrap();
|
||||
assert_eq!(one[0].version.full(), via_helper.version.full());
|
||||
assert_eq!(one[0].source, via_helper.source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_ignore_trailing_foreign_content() {
|
||||
let content = "\
|
||||
pkg (1.0) unstable; urgency=medium
|
||||
|
||||
* Something.
|
||||
|
||||
-- Pkh Tester <pkh@example.com> Thu, 01 Jan 2026 00:00:00 +0000
|
||||
|
||||
older changelog kept in an ad-hoc format:
|
||||
version 0.9 - some text, not a Debian entry
|
||||
version 0.8 - more text
|
||||
";
|
||||
let entries = parse_changelog_entries_from_str(content, None).unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].version.full(), "1.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_parse_body_of_later_entries() {
|
||||
let entries = parse_changelog_entries_from_str(THREE_ENTRIES, Some(2)).unwrap();
|
||||
// The second entry's body and trailer are fully parsed, not merely
|
||||
// its header line.
|
||||
assert_eq!(
|
||||
entries[1].changes_field,
|
||||
"\npkg (1.4-2) unstable; urgency=medium\n.\n * Revision bump."
|
||||
);
|
||||
assert_eq!(entries[1].maintainer_email, "pkh@example.com");
|
||||
assert_eq!(entries[1].urgency, "medium");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_reject_malformed_later_entry() {
|
||||
let content = "\
|
||||
pkg (1.0) unstable; urgency=medium
|
||||
|
||||
* Something.
|
||||
|
||||
-- Pkh Tester <pkh@example.com> Thu, 01 Jan 2026 00:00:00 +0000
|
||||
|
||||
pkg (0.9) unstable; urgency=medium
|
||||
|
||||
* No trailer below.
|
||||
";
|
||||
assert!(parse_changelog_entries_from_str(content, None).is_err());
|
||||
// Not parsed when not requested.
|
||||
assert_eq!(
|
||||
parse_changelog_entries_from_str(content, Some(1))
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+267
-3
@@ -1,5 +1,5 @@
|
||||
//! File checksum computation and formatting for `.changes` / `.buildinfo`
|
||||
//! fields (MD5, SHA-1, SHA-256 + size), mirroring `Dpkg::Checksums`.
|
||||
//! fields (MD5, SHA-1, SHA-256, SHA-512 + size), mirroring `Dpkg::Checksums`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
@@ -7,7 +7,7 @@ use std::path::Path;
|
||||
|
||||
use md5::Md5;
|
||||
use sha1::Sha1;
|
||||
use sha2::{Digest, Sha256};
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
|
||||
/// Checksums and size of a single file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -20,6 +20,40 @@ pub struct Entry {
|
||||
pub sha1: String,
|
||||
/// Lowercase hexadecimal SHA-256 digest.
|
||||
pub sha256: String,
|
||||
/// Lowercase hexadecimal SHA-512 digest.
|
||||
pub sha512: String,
|
||||
}
|
||||
|
||||
/// The checksum algorithm carried by a `Checksums-*` field body, as handled
|
||||
/// by [`FileChecksums::parse_field`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ChecksumKind {
|
||||
/// SHA-1 (`Checksums-Sha1` field).
|
||||
Sha1,
|
||||
/// SHA-256 (`Checksums-Sha256` field).
|
||||
Sha256,
|
||||
/// SHA-512 (`Checksums-Sha512` field).
|
||||
Sha512,
|
||||
}
|
||||
|
||||
impl ChecksumKind {
|
||||
/// The `Checksums-*` field name carrying this digest.
|
||||
pub fn field_name(self) -> &'static str {
|
||||
match self {
|
||||
ChecksumKind::Sha1 => "Checksums-Sha1",
|
||||
ChecksumKind::Sha256 => "Checksums-Sha256",
|
||||
ChecksumKind::Sha512 => "Checksums-Sha512",
|
||||
}
|
||||
}
|
||||
|
||||
/// Length in lowercase hex characters of one digest of this kind.
|
||||
fn digest_len(self) -> usize {
|
||||
match self {
|
||||
ChecksumKind::Sha1 => 40,
|
||||
ChecksumKind::Sha256 => 64,
|
||||
ChecksumKind::Sha512 => 128,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute all supported checksums of a file.
|
||||
@@ -30,6 +64,7 @@ fn compute(path: &Path) -> Result<Entry, Box<dyn std::error::Error>> {
|
||||
let mut md5_hasher = Md5::new();
|
||||
let mut sha1_hasher = Sha1::new();
|
||||
let mut sha256_hasher = Sha256::new();
|
||||
let mut sha512_hasher = Sha512::new();
|
||||
let mut size: u64 = 0;
|
||||
let mut buf = [0u8; 64 * 1024];
|
||||
|
||||
@@ -41,6 +76,7 @@ fn compute(path: &Path) -> Result<Entry, Box<dyn std::error::Error>> {
|
||||
md5_hasher.update(&buf[..n]);
|
||||
sha1_hasher.update(&buf[..n]);
|
||||
sha256_hasher.update(&buf[..n]);
|
||||
sha512_hasher.update(&buf[..n]);
|
||||
size += n as u64;
|
||||
}
|
||||
|
||||
@@ -49,6 +85,7 @@ fn compute(path: &Path) -> Result<Entry, Box<dyn std::error::Error>> {
|
||||
md5: hex::encode(md5_hasher.finalize()),
|
||||
sha1: hex::encode(sha1_hasher.finalize()),
|
||||
sha256: hex::encode(sha256_hasher.finalize()),
|
||||
sha512: hex::encode(sha512_hasher.finalize()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -168,6 +205,84 @@ impl FileChecksums {
|
||||
pub fn field_sha256(&self) -> String {
|
||||
self.format_field(|e| &e.sha256)
|
||||
}
|
||||
|
||||
/// Value for the `Checksums-Sha512` field, or `None` when any registered
|
||||
/// file has no SHA-512 digest (e.g. entries merged from a `.dsc`, which
|
||||
/// dpkg only writes with sha1/sha256 checksums): renderers omit the
|
||||
/// field instead of writing an incomplete checksum list.
|
||||
pub fn field_sha512(&self) -> Option<String> {
|
||||
if self.iter().any(|(_, e)| e.sha512.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
Some(self.format_field(|e| &e.sha512))
|
||||
}
|
||||
|
||||
/// Parse the body of a `Checksums-Sha1` / `Checksums-Sha256` /
|
||||
/// `Checksums-Sha512` field (as rendered by [`FileChecksums::field_sha1`],
|
||||
/// [`FileChecksums::field_sha256`] or [`FileChecksums::field_sha512`])
|
||||
/// into `(name, entry)` pairs, ready to be fed into
|
||||
/// [`FileChecksums::insert_entry`] (e.g. when consuming a `.dsc`).
|
||||
///
|
||||
/// Each non-blank line holds `"<hex digest> <size> <name>"`; blank lines
|
||||
/// are tolerated and anything else is a malformed line, reported as an
|
||||
/// error naming [`ChecksumKind::field_name`] and the offending line. Only
|
||||
/// the digest selected by `kind` is filled in the returned entries: the
|
||||
/// other digest fields are left empty and must be completed from the
|
||||
/// remaining `Checksums-*` fields (or by recomputation) before rendering.
|
||||
///
|
||||
/// Note: this deliberately re-implements the line grammar of the private
|
||||
/// `build::parse_checksum_field` helper (which additionally accepts the
|
||||
/// legacy 5-column `Files` layout); the two are intentionally not unified
|
||||
/// across modules.
|
||||
pub fn parse_field(kind: ChecksumKind, value: &str) -> Result<Vec<(String, Entry)>, String> {
|
||||
let mut entries = Vec::new();
|
||||
for line in value.lines() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tokens: Vec<&str> = line.split_whitespace().collect();
|
||||
let [digest, size, name] = tokens.as_slice() else {
|
||||
return Err(format!(
|
||||
"malformed '{}' line (expected 'checksum size name', got {} \
|
||||
columns): '{line}'",
|
||||
kind.field_name(),
|
||||
tokens.len()
|
||||
));
|
||||
};
|
||||
let size: u64 = size.parse().map_err(|_| {
|
||||
format!(
|
||||
"malformed '{}' line (size '{size}' is not a number): '{line}'",
|
||||
kind.field_name()
|
||||
)
|
||||
})?;
|
||||
let digest_ok = digest.len() == kind.digest_len()
|
||||
&& digest
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
|
||||
if !digest_ok {
|
||||
return Err(format!(
|
||||
"malformed '{}' line (digest '{digest}' is not {} lowercase \
|
||||
hex characters): '{line}'",
|
||||
kind.field_name(),
|
||||
kind.digest_len()
|
||||
));
|
||||
}
|
||||
let mut entry = Entry {
|
||||
size,
|
||||
md5: String::new(),
|
||||
sha1: String::new(),
|
||||
sha256: String::new(),
|
||||
sha512: String::new(),
|
||||
};
|
||||
match kind {
|
||||
ChecksumKind::Sha1 => entry.sha1 = digest.to_string(),
|
||||
ChecksumKind::Sha256 => entry.sha256 = digest.to_string(),
|
||||
ChecksumKind::Sha512 => entry.sha512 = digest.to_string(),
|
||||
}
|
||||
entries.push((name.to_string(), entry));
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -184,16 +299,165 @@ mod tests {
|
||||
cs.add_file(&p).unwrap();
|
||||
|
||||
let e = cs.get("sample.txt").unwrap();
|
||||
// Verified with coreutils: echo "hello world" | md5sum / sha1sum / sha256sum
|
||||
// Verified with coreutils: echo "hello world" | md5sum / sha1sum / sha256sum / sha512sum
|
||||
assert_eq!(e.md5, "6f5902ac237024bdd0c176cb93063dc4");
|
||||
assert_eq!(e.sha1, "22596363b3de40b06f981fb85d82312e8c0ed511");
|
||||
assert_eq!(
|
||||
e.sha256,
|
||||
"a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447"
|
||||
);
|
||||
assert_eq!(
|
||||
e.sha512,
|
||||
"db3974a97f2407b7cae1ae637c0030687a11913274d578492558e39c16c017de\
|
||||
84eacdc8c62fe34ee4e12b4b1428817f09b6a2760c3f8a664ceae94d2434a593"
|
||||
);
|
||||
assert_eq!(e.size, 12);
|
||||
}
|
||||
|
||||
/// SHA-512 of the empty input is a well-known constant: a zero-size file
|
||||
/// must still carry it (never an empty digest string, which is reserved
|
||||
/// for "digest unknown", e.g. entries merged from a `.dsc`).
|
||||
#[test]
|
||||
fn sha512_of_empty_file_is_the_known_constant() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let p = dir.path().join("empty.txt");
|
||||
std::fs::write(&p, b"").unwrap();
|
||||
|
||||
let mut cs = FileChecksums::new();
|
||||
cs.add_file(&p).unwrap();
|
||||
|
||||
let e = cs.get("empty.txt").unwrap();
|
||||
assert_eq!(e.size, 0);
|
||||
assert_eq!(
|
||||
e.sha512,
|
||||
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce\
|
||||
47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
|
||||
);
|
||||
}
|
||||
|
||||
/// All four digests render; the `Checksums-Sha512` field round-trips
|
||||
/// through [`FileChecksums::parse_field`] back into a registry with
|
||||
/// identical names (insertion order), sizes and SHA-512 digests.
|
||||
#[test]
|
||||
fn sha512_field_round_trip() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = dir.path().join("a.txt");
|
||||
let b = dir.path().join("b.txt");
|
||||
std::fs::write(&a, b"aaa").unwrap();
|
||||
std::fs::write(&b, b"bb").unwrap();
|
||||
|
||||
let mut cs = FileChecksums::new();
|
||||
cs.add_file(&b).unwrap();
|
||||
cs.add_file(&a).unwrap();
|
||||
|
||||
// Every digest kind must be populated and render a full field.
|
||||
assert!(!cs.field_md5().is_empty());
|
||||
assert!(!cs.field_sha1().is_empty());
|
||||
assert!(!cs.field_sha256().is_empty());
|
||||
let sha512_field = cs.field_sha512().expect("all entries have sha512");
|
||||
|
||||
// Round-trip the Checksums-Sha512 field through the parser.
|
||||
let mut reparsed = FileChecksums::new();
|
||||
for (key, entry) in FileChecksums::parse_field(ChecksumKind::Sha512, &sha512_field).unwrap()
|
||||
{
|
||||
reparsed.insert_entry(&key, entry);
|
||||
}
|
||||
let keys: Vec<&str> = reparsed.iter().map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(keys, vec!["b.txt", "a.txt"], "insertion order preserved");
|
||||
for (key, e) in cs.iter() {
|
||||
let got = reparsed.get(key).unwrap();
|
||||
assert_eq!(got.size, e.size, "{key}");
|
||||
assert_eq!(got.sha512, e.sha512, "{key}");
|
||||
}
|
||||
// Rendering the re-parsed registry yields the same field value.
|
||||
assert_eq!(reparsed.field_sha512().unwrap(), sha512_field);
|
||||
|
||||
// The parser dispatches on `kind`: a Checksums-Sha256 body fills the
|
||||
// sha256 column, leaving the others (including sha512) unknown.
|
||||
let (key, entry) =
|
||||
&FileChecksums::parse_field(ChecksumKind::Sha256, &cs.field_sha256()).unwrap()[0];
|
||||
assert_eq!(entry.sha256, cs.get(key).unwrap().sha256);
|
||||
assert!(entry.sha512.is_empty());
|
||||
let (_, entry) =
|
||||
&FileChecksums::parse_field(ChecksumKind::Sha512, &sha512_field).unwrap()[0];
|
||||
assert!(entry.md5.is_empty() && entry.sha1.is_empty() && entry.sha256.is_empty());
|
||||
assert!(!entry.sha512.is_empty());
|
||||
}
|
||||
|
||||
/// Malformed `Checksums-Sha512` bodies (wrong column count, non-numeric
|
||||
/// size, wrong digest shape) must be rejected with an error naming the
|
||||
/// field and the offending line; blank lines are tolerated.
|
||||
#[test]
|
||||
fn parse_field_rejects_malformed_lines() {
|
||||
// 128 lowercase hex characters, as rendered by field_sha512.
|
||||
let digest = "ab".repeat(64);
|
||||
|
||||
// Blank lines are skipped.
|
||||
let entries =
|
||||
FileChecksums::parse_field(ChecksumKind::Sha512, &format!("\n {digest} 12 a.txt\n\n"))
|
||||
.unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].0, "a.txt");
|
||||
assert_eq!(entries[0].1.size, 12);
|
||||
|
||||
// 2 columns: missing the name.
|
||||
let err =
|
||||
FileChecksums::parse_field(ChecksumKind::Sha512, &format!("{digest} 12")).unwrap_err();
|
||||
assert!(err.contains("Checksums-Sha512"), "{err}");
|
||||
assert!(err.contains(&format!("{digest} 12")), "{err}");
|
||||
|
||||
// 4 columns.
|
||||
let err =
|
||||
FileChecksums::parse_field(ChecksumKind::Sha512, &format!(" {digest} 12 bogus a.txt"))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("Checksums-Sha512"), "{err}");
|
||||
assert!(err.contains("a.txt"), "{err}");
|
||||
|
||||
// Non-numeric size.
|
||||
let err =
|
||||
FileChecksums::parse_field(ChecksumKind::Sha512, &format!(" {digest} twelve a.txt"))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("not a number"), "{err}");
|
||||
assert!(err.contains("twelve"), "{err}");
|
||||
|
||||
// Digest that is not 128 lowercase hex characters.
|
||||
let err = FileChecksums::parse_field(ChecksumKind::Sha512, " abc123 12 a.txt").unwrap_err();
|
||||
assert!(err.contains("lowercase hex"), "{err}");
|
||||
}
|
||||
|
||||
/// `field_sha512` is only-if-populated: an entry merged without a SHA-512
|
||||
/// digest (e.g. taken from a `.dsc`) suppresses the whole field instead
|
||||
/// of rendering an incomplete checksum list.
|
||||
#[test]
|
||||
fn field_sha512_omitted_when_any_digest_missing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = dir.path().join("a.txt");
|
||||
std::fs::write(&a, b"aaa").unwrap();
|
||||
|
||||
let mut cs = FileChecksums::new();
|
||||
cs.add_file(&a).unwrap();
|
||||
assert!(cs.field_sha512().is_some());
|
||||
|
||||
cs.insert_entry(
|
||||
"from.dsc",
|
||||
Entry {
|
||||
size: 12,
|
||||
md5: "d41d8cd98f00b204e9800998ecf8427e".to_string(),
|
||||
sha1: "da39a3ee5e6b4b0d3255bfef95601890afd80709".to_string(),
|
||||
sha256: format!("e3b0{:0>62}", "0"),
|
||||
sha512: String::new(), // not recorded in .dsc files
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
cs.field_sha512().is_none(),
|
||||
"one incomplete entry must suppress Checksums-Sha512"
|
||||
);
|
||||
// The other kinds are unaffected.
|
||||
assert!(!cs.field_md5().is_empty());
|
||||
assert!(!cs.field_sha1().is_empty());
|
||||
assert!(!cs.field_sha256().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertion_order_preserved() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
+52
-5
@@ -10,6 +10,9 @@ use std::path::Path;
|
||||
|
||||
/// A single deb822 paragraph: an ordered list of `(field, value)` pairs.
|
||||
///
|
||||
/// The parser is lenient: duplicate field names are kept as separate entries
|
||||
/// (accessors see the first one; `set` collapses them back to a single one).
|
||||
///
|
||||
/// Values are stored with continuation-line breaks as `\n` and without the
|
||||
/// leading whitespace of continuation lines. Serialization re-adds a single
|
||||
/// leading space in front of every continuation line, matching dpkg output;
|
||||
@@ -27,6 +30,10 @@ impl Paragraph {
|
||||
}
|
||||
|
||||
/// Look up a field value (case-insensitive field name).
|
||||
///
|
||||
/// Returns the first match. The parser is lenient and keeps duplicate
|
||||
/// field names as-is; use [`Paragraph::iter`] to reach the other
|
||||
/// occurrences. [`Paragraph::set`] collapses them.
|
||||
pub fn get(&self, field: &str) -> Option<&str> {
|
||||
self.fields
|
||||
.iter()
|
||||
@@ -34,16 +41,25 @@ impl Paragraph {
|
||||
.map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// Set a field value, replacing any previous occurrence (case-insensitive).
|
||||
/// Appends the field at the end if it did not exist yet.
|
||||
/// Set a field value, replacing all case-insensitive duplicates: after
|
||||
/// the call at most one entry with this field name remains — the updated
|
||||
/// one, kept at its original position. Appends the field at the end if
|
||||
/// no entry existed yet.
|
||||
pub fn set(&mut self, field: &str, value: &str) {
|
||||
for (k, v) in self.fields.iter_mut() {
|
||||
let mut updated = false;
|
||||
self.fields.retain_mut(|(k, v)| {
|
||||
if k.eq_ignore_ascii_case(field) {
|
||||
if updated {
|
||||
return false;
|
||||
}
|
||||
*v = value.to_string();
|
||||
return;
|
||||
updated = true;
|
||||
}
|
||||
true
|
||||
});
|
||||
if !updated {
|
||||
self.fields.push((field.to_string(), value.to_string()));
|
||||
}
|
||||
self.fields.push((field.to_string(), value.to_string()));
|
||||
}
|
||||
|
||||
/// Remove a field (case-insensitive). Returns true if it was present.
|
||||
@@ -337,6 +353,37 @@ iQEcBAABCgAGBQJabcdAAoJEL abc
|
||||
assert_eq!(p.iter().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lenient_parse_keeps_duplicate_fields() {
|
||||
let paras = parse_paragraphs("Package: hello\nDepends: a\ndepends: b\n");
|
||||
let p = ¶s[0];
|
||||
// deb822 forbids duplicate fields but the parser is lenient and keeps
|
||||
// both entries; `get` returns the first.
|
||||
let depends: Vec<_> = p
|
||||
.iter()
|
||||
.filter(|(k, _)| k.eq_ignore_ascii_case("Depends"))
|
||||
.collect();
|
||||
assert_eq!(depends, [("Depends", "a"), ("depends", "b")]);
|
||||
assert_eq!(p.get("Depends"), Some("a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_removes_case_insensitive_duplicates() {
|
||||
let mut paras = parse_paragraphs("Package: hello\nDepends: a\ndepends: b\n");
|
||||
let mut p = paras.remove(0);
|
||||
p.set("Depends", "c");
|
||||
// Exactly one depends-family entry remains, with the new value.
|
||||
let depends: Vec<_> = p
|
||||
.iter()
|
||||
.filter(|(k, _)| k.eq_ignore_ascii_case("Depends"))
|
||||
.collect();
|
||||
assert_eq!(depends, [("Depends", "c")]);
|
||||
assert_eq!(p.get("depends"), Some("c"));
|
||||
// ...kept at its original position, and a write round-trip no longer
|
||||
// leaks the stale duplicate.
|
||||
assert_eq!(write_paragraph(&p), "Package: hello\nDepends: c\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_field() {
|
||||
let mut p = Paragraph::new();
|
||||
|
||||
+449
-22
@@ -10,7 +10,7 @@
|
||||
//! (<https://manpages.debian.org/libdpkg-perl>) and were validated
|
||||
//! differentially against the real tool.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -583,6 +583,24 @@ pub struct Facts {
|
||||
build_arch: String,
|
||||
installed: HashMap<String, Vec<InstalledPkg>>,
|
||||
provided: HashMap<String, Vec<ProvidedPkg>>,
|
||||
/// Virtual packages whose `Provides` entries had to be rejected as a
|
||||
/// whole (unparseable field, malformed version, or a relation other
|
||||
/// than `=`), mirroring a dpkg rejection of the entry: versioned
|
||||
/// relations on them stay undecidable instead of turning unmet.
|
||||
unreadable_provides: HashSet<String>,
|
||||
}
|
||||
|
||||
/// Best-effort virtual package names mentioned in a raw `Provides` value,
|
||||
/// used to remember rejected entries whose content cannot even be parsed
|
||||
/// (the full dependency grammar is deliberately not re-applied here).
|
||||
fn raw_provides_names(field: &str) -> impl Iterator<Item = &str> {
|
||||
field
|
||||
.split([',', '|'])
|
||||
.filter_map(|alt| alt.split_whitespace().next())
|
||||
.map(|tok| match tok.split_once(':') {
|
||||
Some((name, _qual)) => name,
|
||||
None => tok,
|
||||
})
|
||||
}
|
||||
|
||||
impl Facts {
|
||||
@@ -593,6 +611,7 @@ impl Facts {
|
||||
build_arch: build_arch.to_string(),
|
||||
installed: HashMap::new(),
|
||||
provided: HashMap::new(),
|
||||
unreadable_provides: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,6 +628,11 @@ impl Facts {
|
||||
}
|
||||
|
||||
/// Record that `provider` provides the virtual package `virtual_name`.
|
||||
///
|
||||
/// A `relation` other than [`Relation::Eq`], or a `version` that fails
|
||||
/// to parse, makes the provide unusable: versioned relations on
|
||||
/// `virtual_name` then evaluate to `None` (undecidable) instead of a
|
||||
/// possibly-wrong `Some(false)`.
|
||||
pub fn add_provided(
|
||||
&mut self,
|
||||
virtual_name: &str,
|
||||
@@ -639,7 +663,10 @@ impl Facts {
|
||||
/// Only stanzas whose `Status` ends with `ok installed` participate;
|
||||
/// their `Provides` field registers versioned/unversioned virtual
|
||||
/// packages (architecture-restricted provides are reduced against
|
||||
/// `host_arch`).
|
||||
/// `host_arch`). A `Provides` field that fails to parse, or that
|
||||
/// carries a relation other than `=`, is rejected as a whole (like
|
||||
/// dpkg rejects the entry) and its virtual names are remembered as
|
||||
/// unreadable.
|
||||
pub fn from_status(content: &str, host_arch: &str, build_arch: &str) -> Facts {
|
||||
let mut facts = Facts::new(host_arch, build_arch);
|
||||
for para in crate::debian::control::parse_paragraphs(content) {
|
||||
@@ -664,20 +691,38 @@ impl Facts {
|
||||
union: true,
|
||||
build_dep: false,
|
||||
};
|
||||
// Virtual (Provides) fields only accept '=' relations; a
|
||||
// parse failure skips the whole field, like dpkg does.
|
||||
let Ok(parsed) = Deps::parse_inner(provides, &opts, true) else {
|
||||
// Virtual (Provides) fields only accept versionless or
|
||||
// exactly '='-versioned alternatives; a field that fails
|
||||
// to parse, or that carries any other relation, is
|
||||
// rejected as a whole, like dpkg rejects the entry. The
|
||||
// mentioned virtual names are remembered so versioned
|
||||
// relations on them stay undecidable instead of turning
|
||||
// into a possibly-wrong "unmet" verdict.
|
||||
let mut parsed = None;
|
||||
let mut rejected: Vec<String> = Vec::new();
|
||||
match Deps::parse_inner(provides, &opts, true) {
|
||||
Ok(deps) => {
|
||||
if deps.clauses().flatten().any(|alt| {
|
||||
alt.constraint
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.relation != Relation::Eq)
|
||||
}) {
|
||||
rejected
|
||||
.extend(deps.clauses().flatten().map(|alt| alt.package.clone()));
|
||||
} else {
|
||||
parsed = Some(deps);
|
||||
}
|
||||
}
|
||||
// The field could not even be parsed: recover the raw
|
||||
// names so the rejection is still remembered.
|
||||
Err(_) => rejected.extend(raw_provides_names(provides).map(str::to_string)),
|
||||
}
|
||||
facts.unreadable_provides.extend(rejected);
|
||||
let Some(parsed) = parsed else {
|
||||
continue;
|
||||
};
|
||||
for clause in parsed.clauses() {
|
||||
for alt in clause {
|
||||
if alt
|
||||
.constraint
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.relation != Relation::Eq)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let provided_version = alt
|
||||
.constraint
|
||||
.as_ref()
|
||||
@@ -755,11 +800,21 @@ impl Facts {
|
||||
}
|
||||
}
|
||||
|
||||
// A rejected Provides entry for this virtual package carries
|
||||
// information that could not be read: a versioned relation can
|
||||
// then not be decided (an unversioned one only needs the name,
|
||||
// which the rejection removed).
|
||||
if rel.constraint.is_some() && self.unreadable_provides.contains(&rel.package) {
|
||||
lackinfos = true;
|
||||
}
|
||||
|
||||
if let Some(providers) = self.provided.get(&rel.package) {
|
||||
for vp in providers {
|
||||
// Only unversioned provides and strictly-versioned provides
|
||||
// can satisfy a dependency.
|
||||
// Only unversioned provides and exactly-versioned provides
|
||||
// can satisfy a dependency; anything else is an invalid
|
||||
// provide and leaves the relation undecidable.
|
||||
if vp.relation.is_some_and(|r| r != Relation::Eq) {
|
||||
lackinfos = true;
|
||||
continue;
|
||||
}
|
||||
match &rel.constraint {
|
||||
@@ -767,10 +822,15 @@ impl Facts {
|
||||
let Some(vp_version) = &vp.version else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(vp_v) = DebianVersion::parse(vp_version)
|
||||
&& constraint.relation.eval(&vp_v, &constraint.version)
|
||||
{
|
||||
return Some(true);
|
||||
match DebianVersion::parse(vp_version) {
|
||||
Ok(vp_v) if constraint.relation.eval(&vp_v, &constraint.version) => {
|
||||
return Some(true);
|
||||
}
|
||||
// An unreadable provided version, like an
|
||||
// unreadable installed version, makes the
|
||||
// relation undecidable instead of unmet.
|
||||
Err(_) => lackinfos = true,
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
None => return Some(true),
|
||||
@@ -785,8 +845,15 @@ impl Facts {
|
||||
/// Options for [`check_build_depends`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CheckOpts {
|
||||
/// Host architecture (defaults to the native architecture).
|
||||
/// Host architecture, i.e. `DEB_HOST_ARCH`: the architecture the
|
||||
/// packages are built FOR (defaults to the native architecture).
|
||||
/// Bracketed `foo [arch]` restrictions evaluate against it.
|
||||
pub host_arch: String,
|
||||
/// Build architecture, i.e. `DEB_BUILD_ARCH`: the architecture the
|
||||
/// build runs ON (defaults to the native architecture). `:native`
|
||||
/// dependency qualifiers and the dpkg status attribution of the
|
||||
/// build-side facts resolve against it.
|
||||
pub build_arch: String,
|
||||
/// Active build profiles.
|
||||
pub build_profiles: Vec<String>,
|
||||
/// Ignore `Build-Depends-Arch`/`Build-Conflicts-Arch` (`-A`).
|
||||
@@ -804,6 +871,7 @@ impl Default for CheckOpts {
|
||||
fn default() -> Self {
|
||||
CheckOpts {
|
||||
host_arch: arch::native().unwrap_or_default(),
|
||||
build_arch: arch::native().unwrap_or_default(),
|
||||
build_profiles: Vec::new(),
|
||||
ignore_arch: false,
|
||||
ignore_indep: false,
|
||||
@@ -904,14 +972,14 @@ pub fn check_build_depends(control: &ControlInfo, opts: &CheckOpts) -> Result<Un
|
||||
let bc_value = bc_parts.join(", ");
|
||||
|
||||
let status_path = opts.admindir.join("status");
|
||||
let facts = Facts::load_status(&status_path, &opts.host_arch, &opts.host_arch)?;
|
||||
let facts = Facts::load_status(&status_path, &opts.host_arch, &opts.build_arch)?;
|
||||
|
||||
let mut report = UnmetReport::default();
|
||||
|
||||
if !bd_value.trim().is_empty() {
|
||||
let parse_opts = ParseOpts {
|
||||
host_arch: opts.host_arch.clone(),
|
||||
build_arch: opts.host_arch.clone(),
|
||||
build_arch: opts.build_arch.clone(),
|
||||
build_profiles: opts.build_profiles.clone(),
|
||||
reduce_restrictions: true,
|
||||
union: false,
|
||||
@@ -933,7 +1001,7 @@ pub fn check_build_depends(control: &ControlInfo, opts: &CheckOpts) -> Result<Un
|
||||
if !bc_value.trim().is_empty() {
|
||||
let parse_opts = ParseOpts {
|
||||
host_arch: opts.host_arch.clone(),
|
||||
build_arch: opts.host_arch.clone(),
|
||||
build_arch: opts.build_arch.clone(),
|
||||
build_profiles: opts.build_profiles.clone(),
|
||||
reduce_restrictions: true,
|
||||
union: true,
|
||||
@@ -1243,6 +1311,300 @@ Provides: old-virtual (= 0.5)
|
||||
assert_eq!(facts.evaluate_relation(&o("old-virtual")), Some(true));
|
||||
}
|
||||
|
||||
/// A `Provides` entry that dpkg would reject as a whole (a malformed
|
||||
/// provided version, or a relation other than `=`) must not degrade to
|
||||
/// a bogus "unmet" verdict: versioned relations on the affected virtual
|
||||
/// names stay undecidable.
|
||||
#[test]
|
||||
fn corrupt_provides_are_undecidable_not_unmet() {
|
||||
// `not-a-version!` is rejected by DebianVersion::parse ('!' is not
|
||||
// a legal version character), unlike dpkg-invalid but here-valid
|
||||
// letter-only spellings.
|
||||
let status = "\
|
||||
Package: bad-version-provider
|
||||
Status: install ok installed
|
||||
Version: 1.0
|
||||
Architecture: amd64
|
||||
Provides: virt (= not-a-version!)
|
||||
|
||||
Package: bad-relation-provider
|
||||
Status: install ok installed
|
||||
Version: 1.0
|
||||
Architecture: amd64
|
||||
Provides: virt2 (>= 1.0), plain
|
||||
";
|
||||
let facts = Facts::from_status(status, "amd64", "amd64");
|
||||
let o = |s: &str| parse_simple(s, true).unwrap();
|
||||
|
||||
// The provided version fails to parse: undecidable, not unmet.
|
||||
assert_eq!(facts.evaluate_relation(&o("virt (>= 0.5)")), None);
|
||||
// A non-'=' relation invalidates the whole Provides field, so
|
||||
// neither of its alternatives may produce a verdict.
|
||||
assert_eq!(facts.evaluate_relation(&o("virt2 (>= 0.5)")), None);
|
||||
assert_eq!(facts.evaluate_relation(&o("plain (>= 0.5)")), None);
|
||||
// Unversioned relations only need the name, which the rejected
|
||||
// entries no longer provide: genuinely unmet.
|
||||
assert_eq!(facts.evaluate_relation(&o("virt")), Some(false));
|
||||
assert_eq!(facts.evaluate_relation(&o("virt2")), Some(false));
|
||||
assert_eq!(facts.evaluate_relation(&o("plain")), Some(false));
|
||||
}
|
||||
|
||||
/// Cross-compilation semantics of the package lookup (the `Facts`
|
||||
/// host/build split), mirroring `Dpkg::Deps::KnownFacts::_find_package`:
|
||||
/// an unqualified dependency is satisfied by the HOST architecture
|
||||
/// instance, by any instance of a `Multi-Arch: foreign` package, or by
|
||||
/// an `Architecture: all` instance — never by a foreign-arch instance
|
||||
/// of a `Multi-Arch: no`/`same` package. The build-architecture
|
||||
/// instances only come into play through `:native`.
|
||||
///
|
||||
/// Verdicts marked «live» were probed against `dpkg-checkbuilddeps -a
|
||||
/// <host>` on a real amd64 system carrying the build-arch instances.
|
||||
#[test]
|
||||
fn cross_lookup_matrix() {
|
||||
const O: fn(&str) -> PkgRelation = |s| parse_simple(s, true).unwrap();
|
||||
// host = arm64 (target), build = amd64 (machine): the instances
|
||||
// below simulate what a cross-building amd64 machine has installed.
|
||||
let facts = |ma_build: &str, ma_host: &str| {
|
||||
let mut f = Facts::new("arm64", "amd64");
|
||||
if !ma_build.is_empty() {
|
||||
f.add_installed("t", "1.0", "amd64", ma_build);
|
||||
}
|
||||
if !ma_host.is_empty() {
|
||||
f.add_installed("t", "1.0", "arm64", ma_host);
|
||||
}
|
||||
f
|
||||
};
|
||||
|
||||
// Unqualified: only the host-arch instance satisfies...
|
||||
assert_eq!(
|
||||
facts("no", "").evaluate_relation(&O("t")),
|
||||
Some(false),
|
||||
"M-A:no build-arch instance must not satisfy an unqualified dep"
|
||||
);
|
||||
assert_eq!(
|
||||
facts("same", "").evaluate_relation(&O("t")),
|
||||
Some(false),
|
||||
"M-A:same build-arch instance must not satisfy an unqualified dep"
|
||||
);
|
||||
assert_eq!(facts("", "no").evaluate_relation(&O("t")), Some(true));
|
||||
assert_eq!(facts("", "same").evaluate_relation(&O("t")), Some(true));
|
||||
// ...unless the package is Multi-Arch: foreign («live»: bison,
|
||||
// flex: the natively-installed variant satisfies the cross check).
|
||||
assert_eq!(facts("foreign", "").evaluate_relation(&O("t")), Some(true));
|
||||
assert_eq!(facts("", "foreign").evaluate_relation(&O("t")), Some(true));
|
||||
|
||||
// `Architecture: all` instances satisfy unqualified dependencies
|
||||
// whatever the Multi-Arch attribute.
|
||||
let mut all = Facts::new("arm64", "amd64");
|
||||
all.add_installed("t", "1.0", "all", "foreign");
|
||||
assert_eq!(all.evaluate_relation(&O("t")), Some(true));
|
||||
let mut all2 = Facts::new("arm64", "amd64");
|
||||
all2.add_installed("t", "1.0", "all", "no");
|
||||
assert_eq!(all2.evaluate_relation(&O("t")), Some(true));
|
||||
|
||||
// Versioned relations check the first matching instance only:
|
||||
// insertion order decides which instance a dependency binds to,
|
||||
// and an unsatisfying version does not fall through to later
|
||||
// instances.
|
||||
let mut mixed = Facts::new("arm64", "amd64");
|
||||
mixed.add_installed("t", "0.5", "arm64", "no");
|
||||
mixed.add_installed("t", "3.0", "amd64", "no");
|
||||
assert_eq!(mixed.evaluate_relation(&O("t (>= 1)")), Some(false));
|
||||
assert_eq!(mixed.evaluate_relation(&O("t (<< 1)")), Some(true));
|
||||
|
||||
// `:native`: the build-architecture instance satisfies («live»:
|
||||
// gcc:native on an amd64 machine, whatever the target); an
|
||||
// Architecture: all instance does too — but a Multi-Arch: foreign
|
||||
// instance aborts the whole lookup, even on the build architecture
|
||||
// («live»: flex:native with natively-installed M-A:foreign flex is
|
||||
// unmet).
|
||||
assert_eq!(
|
||||
facts("no", "").evaluate_relation(&O("t:native")),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
facts("same", "").evaluate_relation(&O("t:native")),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
facts("foreign", "").evaluate_relation(&O("t:native")),
|
||||
Some(false)
|
||||
);
|
||||
// An Architecture: all instance satisfies :native — unless it is
|
||||
// Multi-Arch: foreign, which aborts the lookup like any foreign
|
||||
// instance.
|
||||
assert_eq!(all2.evaluate_relation(&O("t:native")), Some(true));
|
||||
assert_eq!(all.evaluate_relation(&O("t:native")), Some(false));
|
||||
assert_eq!(
|
||||
facts("", "no").evaluate_relation(&O("t:native")),
|
||||
Some(false)
|
||||
);
|
||||
|
||||
// `:any`: only a Multi-Arch: allowed instance satisfies, on any
|
||||
// architecture («live»: libssl-dev:any with M-A:same libssl-dev is
|
||||
// unmet).
|
||||
assert_eq!(
|
||||
facts("allowed", "").evaluate_relation(&O("t:any")),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
facts("", "allowed").evaluate_relation(&O("t:any")),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
facts("same", "").evaluate_relation(&O("t:any")),
|
||||
Some(false)
|
||||
);
|
||||
|
||||
// Explicit architecture qualifier: only that exact instance.
|
||||
assert_eq!(facts("no", "").evaluate_relation(&O("t:amd64")), Some(true));
|
||||
assert_eq!(
|
||||
facts("", "no").evaluate_relation(&O("t:amd64")),
|
||||
Some(false)
|
||||
);
|
||||
}
|
||||
|
||||
/// The same cross matrix, validated against the real
|
||||
/// `dpkg-checkbuilddeps`: for each fixture the exit status and the
|
||||
/// reported unmet list must match, with host != build (the machine is
|
||||
/// the native architecture; the host architecture is a foreign one).
|
||||
#[test]
|
||||
fn diff_checkbuilddeps_cross_matrix() {
|
||||
let build_arch = arch::native().unwrap_or_else(|_| "amd64".into());
|
||||
// Any foreign arch the dpkg tables know; the instances only exist
|
||||
// in the synthetic status file.
|
||||
let host_arch = if build_arch == "arm64" {
|
||||
"riscv64".to_string()
|
||||
} else {
|
||||
"arm64".to_string()
|
||||
};
|
||||
|
||||
let mk_status = |entries: &[(&str, &str)]| {
|
||||
let mut s = String::new();
|
||||
for (pkg_arch, ma) in entries {
|
||||
let ma = if ma.is_empty() { "no" } else { ma };
|
||||
s.push_str(&format!(
|
||||
"Package: t\nStatus: install ok installed\nVersion: 1.0\nArchitecture: {pkg_arch}\nMulti-Arch: {ma}\n\n"
|
||||
));
|
||||
}
|
||||
s
|
||||
};
|
||||
|
||||
for (name, entries, dep) in [
|
||||
// Unqualified: build-arch instances never satisfy, host-arch
|
||||
// and Multi-Arch: foreign do.
|
||||
("ma-no-build", &[("amd64", "no")] as &[(&str, &str)], "t"),
|
||||
("ma-same-build", &[("amd64", "same")], "t"),
|
||||
("ma-no-host", &[("arm64", "no")], "t"),
|
||||
("ma-same-host", &[("arm64", "same")], "t"),
|
||||
("ma-foreign-build", &[("amd64", "foreign")], "t"),
|
||||
("all-build", &[("all", "foreign")], "t"),
|
||||
// :native and :any qualifiers.
|
||||
("native-build", &[("amd64", "no")], "t:native"),
|
||||
("native-foreign-build", &[("amd64", "foreign")], "t:native"),
|
||||
("any-allowed-build", &[("amd64", "allowed")], "t:any"),
|
||||
("any-same-build", &[("amd64", "same")], "t:any"),
|
||||
("explicit-build", &[("amd64", "no")], "t:amd64"),
|
||||
("explicit-host", &[("arm64", "no")], "t:amd64"),
|
||||
] {
|
||||
// Substitute the foreign architecture for fixtures that name
|
||||
// the host arch explicitly.
|
||||
let dep = dep.replace("arm64", &host_arch);
|
||||
let entries: Vec<(String, &str)> = entries
|
||||
.iter()
|
||||
.map(|(a, m)| (a.replace("amd64", &build_arch), *m))
|
||||
.collect();
|
||||
let entries: Vec<(&str, &str)> =
|
||||
entries.iter().map(|(a, m)| (a.as_str(), *m)).collect();
|
||||
let status = mk_status(&entries);
|
||||
let verdict = |bd: &str, host: &str| {
|
||||
diff_cross_case(bd, &status, &build_arch, host, |ours, real| {
|
||||
assert_eq!(ours, real, "verdict mismatch for {name}")
|
||||
})
|
||||
};
|
||||
verdict(&dep, &host_arch);
|
||||
}
|
||||
}
|
||||
|
||||
/// One differential cross case: run the real `dpkg-checkbuilddeps`
|
||||
/// with `-a <host>` against a synthetic admindir, and the native
|
||||
/// checker with the equivalent options on the same control, then hand
|
||||
/// both verdicts to `compare`.
|
||||
fn diff_cross_case(
|
||||
bd: &str,
|
||||
status: &str,
|
||||
build_arch: &str,
|
||||
host_arch: &str,
|
||||
compare: impl Fn(bool, bool),
|
||||
) {
|
||||
let control_text = format!(
|
||||
"Source: t\nMaintainer: a <a@b.c>\nBuild-Depends: {bd}\n\nPackage: t\nArchitecture: any\nDescription: x\n y\n"
|
||||
);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("control"), &control_text).unwrap();
|
||||
let admindir = dir.path().join("admin");
|
||||
std::fs::create_dir_all(&admindir).unwrap();
|
||||
std::fs::write(admindir.join("status"), status).unwrap();
|
||||
|
||||
let output = std::process::Command::new("dpkg-checkbuilddeps")
|
||||
.current_dir(dir.path())
|
||||
.env("LC_ALL", "C")
|
||||
.arg("--admindir")
|
||||
.arg(&admindir)
|
||||
.arg("-a")
|
||||
.arg(host_arch)
|
||||
.arg("-I")
|
||||
.arg("control")
|
||||
.output()
|
||||
.expect("run dpkg-checkbuilddeps (is dpkg-dev installed?)");
|
||||
let real_ok = output.status.success();
|
||||
|
||||
let opts = CheckOpts {
|
||||
host_arch: host_arch.to_string(),
|
||||
build_arch: build_arch.to_string(),
|
||||
build_profiles: Vec::new(),
|
||||
ignore_arch: false,
|
||||
ignore_indep: false,
|
||||
ignore_builtin: true,
|
||||
admindir: admindir.to_path_buf(),
|
||||
};
|
||||
let control = ControlInfo::parse_content(&control_text).unwrap();
|
||||
let ours_ok = check_build_depends(&control, &opts)
|
||||
.expect("native check failure")
|
||||
.is_ok();
|
||||
|
||||
compare(ours_ok, real_ok);
|
||||
}
|
||||
|
||||
/// The same undecidable verdicts through the direct facts API: an
|
||||
/// unreadable provided version and an invalid (non-`=`) provide each
|
||||
/// leave a versioned relation undecided, while a readable provider
|
||||
/// elsewhere still satisfies it.
|
||||
#[test]
|
||||
fn unreadable_provided_version_and_relation_are_undecidable() {
|
||||
let o = |s: &str| parse_simple(s, true).unwrap();
|
||||
|
||||
let mut facts = Facts::new("amd64", "amd64");
|
||||
facts.add_installed("provider", "1.0", "amd64", "no");
|
||||
// `virt (= not-a-version!)`: the version string fails to parse.
|
||||
facts.add_provided(
|
||||
"virt",
|
||||
Some(Relation::Eq),
|
||||
Some("not-a-version!"),
|
||||
"provider",
|
||||
);
|
||||
assert_eq!(facts.evaluate_relation(&o("virt (>= 0.5)")), None);
|
||||
// `virt2 (>= 1.0)`: a non-'=' provide is invalid.
|
||||
facts.add_provided("virt2", Some(Relation::Ge), Some("1.0"), "provider");
|
||||
assert_eq!(facts.evaluate_relation(&o("virt2 (>= 0.5)")), None);
|
||||
|
||||
// A readable provider decides the relation when it matches;
|
||||
// otherwise the unreadable entry keeps it undecidable.
|
||||
facts.add_provided("virt", Some(Relation::Eq), Some("2.0"), "better");
|
||||
assert_eq!(facts.evaluate_relation(&o("virt (>= 0.5)")), Some(true));
|
||||
assert_eq!(facts.evaluate_relation(&o("virt (>> 2.0)")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplify_reports_unmet() {
|
||||
let facts = Facts::from_status(STATUS, "amd64", "amd64");
|
||||
@@ -1363,4 +1725,69 @@ Architecture: amd64
|
||||
let report = check_build_depends(&control_conflict, &opts).unwrap();
|
||||
assert_eq!(report.message(), "unmet build conflicts: mypackage");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_build_depends_cross_native_qualifier() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let admindir = dir.path();
|
||||
|
||||
// Cross build: armhf packages built ON an amd64 machine, so
|
||||
// DEB_HOST_ARCH=armhf but DEB_BUILD_ARCH=amd64.
|
||||
let opts = CheckOpts {
|
||||
host_arch: "armhf".to_string(),
|
||||
build_arch: "amd64".to_string(),
|
||||
admindir: admindir.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
let control_for = |bd: &str| {
|
||||
ControlInfo::parse_content(&format!(
|
||||
"Source: t\nMaintainer: a <a@b.c>\nBuild-Depends: {bd}\n\nPackage: t\nArchitecture: any\nDescription: x\n y\n"
|
||||
))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
// foo is only installed for the build architecture, like a native
|
||||
// toolchain package pulled in on the build machine.
|
||||
std::fs::write(
|
||||
admindir.join("status"),
|
||||
"\
|
||||
Package: foo
|
||||
Status: install ok installed
|
||||
Version: 1.0
|
||||
Architecture: amd64
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `:native` resolves against the BUILD architecture: satisfied even
|
||||
// though the host architecture is armhf.
|
||||
let report = check_build_depends(&control_for("foo:native"), &opts).unwrap();
|
||||
assert!(report.is_ok());
|
||||
|
||||
// Bracketed architecture restrictions keep evaluating against the
|
||||
// HOST architecture: the amd64 instance cannot satisfy `foo [armhf]`.
|
||||
// (The applied restriction reduces away, per dpkg's reduce_arch.)
|
||||
let report = check_build_depends(&control_for("foo [armhf]"), &opts).unwrap();
|
||||
assert_eq!(report.message(), "unmet build dependencies: foo");
|
||||
|
||||
// Now foo is only installed for the host architecture.
|
||||
std::fs::write(
|
||||
admindir.join("status"),
|
||||
"\
|
||||
Package: foo
|
||||
Status: install ok installed
|
||||
Version: 1.0
|
||||
Architecture: armhf
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `:native` no longer matches: no amd64 instance is installed.
|
||||
let report = check_build_depends(&control_for("foo:native"), &opts).unwrap();
|
||||
assert_eq!(report.message(), "unmet build dependencies: foo:native");
|
||||
|
||||
// The host-arch restriction matches the armhf instance.
|
||||
let report = check_build_depends(&control_for("foo [armhf]"), &opts).unwrap();
|
||||
assert!(report.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -20,10 +20,10 @@ pub mod files;
|
||||
pub mod version;
|
||||
|
||||
pub use changelog::{
|
||||
ChangelogEntry, parse_changelog_entry, parse_changelog_entry_from_str,
|
||||
parse_previous_version_from_str,
|
||||
ChangelogEntry, parse_changelog_entries, parse_changelog_entries_from_str,
|
||||
parse_changelog_entry, parse_changelog_entry_from_str,
|
||||
};
|
||||
pub use checksums::{Entry as ChecksumEntry, FileChecksums};
|
||||
pub use checksums::{ChecksumKind, Entry as ChecksumEntry, FileChecksums};
|
||||
pub use control::{
|
||||
ControlInfo, Paragraph, parse_paragraphs, strip_clearsigned_armour, write_paragraph,
|
||||
};
|
||||
|
||||
@@ -48,6 +48,12 @@ impl DebianVersion {
|
||||
}
|
||||
}
|
||||
if let Some(rev) = &debian_revision {
|
||||
if rev.is_empty() {
|
||||
// dpkg rejects a trailing hyphen: "bad syntax: revision
|
||||
// number is empty". Native versions (no `-` at all) are
|
||||
// handled above and stay valid.
|
||||
return Err(format!("empty debian revision in '{}'", raw));
|
||||
}
|
||||
for c in rev.chars() {
|
||||
if !(c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '~') || !c.is_ascii()) {
|
||||
return Err(format!(
|
||||
@@ -329,6 +335,27 @@ mod tests {
|
||||
assert!(DebianVersion::parse("1.0~rc1-2").is_ok());
|
||||
}
|
||||
|
||||
/// dpkg rejects a trailing `-` ("bad syntax: revision number is
|
||||
/// empty") but accepts `1.0--1`, where the revision is the text after
|
||||
/// the *last* hyphen (upstream `1.0-` + revision `1`).
|
||||
#[test]
|
||||
fn version_empty_revision() {
|
||||
let err = DebianVersion::parse("1.0-").unwrap_err();
|
||||
assert!(err.contains("empty"), "unexpected message: {err}");
|
||||
|
||||
assert!(DebianVersion::parse("1.0-").is_err());
|
||||
// Epoch variants take the same path.
|
||||
assert!(DebianVersion::parse("3:1.0-").is_err());
|
||||
assert!(DebianVersion::parse("1.0-1").is_ok());
|
||||
// Native versions (no revision at all) are still fine.
|
||||
assert!(DebianVersion::parse("1.0").is_ok());
|
||||
assert!(DebianVersion::parse("3:1.0").is_ok());
|
||||
|
||||
let v = DebianVersion::parse("1.0--1").unwrap();
|
||||
assert_eq!(v.upstream, "1.0-");
|
||||
assert_eq!(v.debian_revision.as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
fn cmp_sign(a: &DebianVersion, b: &DebianVersion) -> i32 {
|
||||
match a.cmp(b) {
|
||||
std::cmp::Ordering::Less => -1,
|
||||
|
||||
+491
-34
@@ -1,6 +1,8 @@
|
||||
use crate::data::embed_data;
|
||||
use chrono::NaiveDate;
|
||||
use lazy_static::lazy_static;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
@@ -28,34 +30,91 @@ struct SeriesInfo {
|
||||
network: String,
|
||||
}
|
||||
|
||||
/// Architectures an archive mirror serves: an explicit list, or the `all`
|
||||
/// sentinel meaning one mirror serves every architecture (Debian's mirror
|
||||
/// setup — an exhaustive list would rot each time an arch is added)
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum MirrorArchs {
|
||||
/// The `all` sentinel
|
||||
All(String),
|
||||
/// An explicit list of dpkg architecture names
|
||||
List(Vec<String>),
|
||||
}
|
||||
|
||||
impl MirrorArchs {
|
||||
/// Whether the mirror serves `arch`. A scalar other than the `all`
|
||||
/// sentinel serves nothing (a test locks that reading of the data).
|
||||
fn serves(&self, arch: &str) -> bool {
|
||||
match self {
|
||||
MirrorArchs::All(sentinel) => sentinel == "all",
|
||||
MirrorArchs::List(archs) => archs.iter().any(|a| a == arch),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One archive mirror of a distribution: a URL serving a set of
|
||||
/// architectures, plus the sibling host serving its `-security` pocket
|
||||
/// for the same architectures (ports mirrors serve their own security)
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Mirror {
|
||||
/// Base URL of the mirror (the primary mirror's URL doubles as the
|
||||
/// dist's base URL, see [`get_base_url`])
|
||||
pub url: String,
|
||||
/// Sibling host serving the `-security` pocket for these
|
||||
/// architectures; `None` when the mirror serves its own security
|
||||
#[serde(default)]
|
||||
security_url: Option<String>,
|
||||
/// Architectures the mirror serves (see [`MirrorArchs`])
|
||||
archs: MirrorArchs,
|
||||
}
|
||||
|
||||
impl Mirror {
|
||||
/// Whether the mirror serves `arch`
|
||||
pub fn serves(&self, arch: &str) -> bool {
|
||||
self.archs.serves(arch)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct DistData {
|
||||
base_url: String,
|
||||
mirrors: HashMap<String, Mirror>,
|
||||
archive_keyring: String,
|
||||
pockets: Vec<String>,
|
||||
#[serde(default)]
|
||||
sections: Vec<String>,
|
||||
components: Vec<String>,
|
||||
cross_pockets: Vec<String>,
|
||||
#[serde(default)]
|
||||
build_profiles: Vec<String>,
|
||||
/// Changelog suite names aliasing a distro-info series codename
|
||||
/// ('unstable' for Debian's 'sid'): the two names identify the same
|
||||
/// series ([`series_suite_alias`], [`resolve_suite_alias`])
|
||||
#[serde(default)]
|
||||
suite_aliases: HashMap<String, String>,
|
||||
series: SeriesInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Data {
|
||||
dist: std::collections::HashMap<String, DistData>,
|
||||
dist: HashMap<String, DistData>,
|
||||
}
|
||||
|
||||
const DATA_YAML: &str = include_str!("../distro_info.yml");
|
||||
lazy_static! {
|
||||
// The YAML is include_str!'d at compile time and statically valid; if it
|
||||
// ever failed to parse it would be a build-time bug that cannot be
|
||||
// recovered from at runtime, so panicking here is acceptable.
|
||||
static ref DATA: Data = serde_yaml::from_str(DATA_YAML)
|
||||
.expect("built-in distro_info.yml data is statically valid and must parse");
|
||||
embed_data! {
|
||||
static ref DATA: Data = "../data/distro_info.yml"
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
// Shared HTTP client used for all outgoing plain requests: timeouts keep
|
||||
// a hanging remote (connect or transfer) from stalling pkh indefinitely.
|
||||
// The short pool idle timeout and TCP keepalive avoid reusing keep-alive
|
||||
// connections that the remote closed in the meantime, which surfaces as
|
||||
// spurious 'error sending request' failures on busy mirrors/CDNs.
|
||||
static ref HTTP_CLIENT: reqwest::Client = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.timeout(Duration::from_secs(30))
|
||||
.pool_idle_timeout(Duration::from_secs(10))
|
||||
.tcp_keepalive(Duration::from_secs(30))
|
||||
.build()
|
||||
.expect("building the shared HTTP client with static options cannot fail");
|
||||
}
|
||||
@@ -66,6 +125,49 @@ pub(crate) fn http_client() -> &'static reqwest::Client {
|
||||
&HTTP_CLIENT
|
||||
}
|
||||
|
||||
/// GET `url` with bounded retries on transient transport errors (a pooled
|
||||
/// keep-alive connection closed by the remote, a momentary network hiccup,
|
||||
/// ...): these always succeed again on a fresh connection, and mirrors are
|
||||
/// busy enough that unguarded single attempts make bulk operations flaky.
|
||||
///
|
||||
/// The response status is not inspected: 404s and the like are meaningful
|
||||
/// answers, not transport failures.
|
||||
pub(crate) async fn http_get_retried(url: &str) -> reqwest::Result<reqwest::Response> {
|
||||
http_get_retried_with_timeout(url, None).await
|
||||
}
|
||||
|
||||
/// [`http_get_retried`] with a per-request timeout override, for large
|
||||
/// streaming downloads that exceed the shared client's total timeout
|
||||
pub(crate) async fn http_get_retried_with_timeout(
|
||||
url: &str,
|
||||
timeout: Option<Duration>,
|
||||
) -> reqwest::Result<reqwest::Response> {
|
||||
const ATTEMPTS: u32 = 3;
|
||||
let mut last_error: Option<reqwest::Error> = None;
|
||||
for attempt in 0..ATTEMPTS {
|
||||
let mut request = http_client().get(url);
|
||||
if let Some(timeout) = timeout {
|
||||
request = request.timeout(timeout);
|
||||
}
|
||||
match request.send().await {
|
||||
Ok(response) => return Ok(response),
|
||||
Err(e) => {
|
||||
if attempt + 1 < ATTEMPTS {
|
||||
log::debug!(
|
||||
"GET '{url}' failed (attempt {}/{}, retrying): {}",
|
||||
attempt + 1,
|
||||
ATTEMPTS,
|
||||
e
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(300 * (u64::from(attempt) + 1))).await;
|
||||
}
|
||||
last_error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_error.expect("at least one attempt was made"))
|
||||
}
|
||||
|
||||
/// Parse an optional '%Y-%m-%d' date from a CSV cell, warning instead of
|
||||
/// panicking on invalid remote data
|
||||
fn parse_optional_date(value: Option<&str>, series: &str, field: &str) -> Option<NaiveDate> {
|
||||
@@ -166,9 +268,30 @@ fn parse_series_csv(content: &str) -> Result<Vec<SeriesInformation>, Box<dyn Err
|
||||
Ok(series_info_list)
|
||||
}
|
||||
|
||||
/// List the distributions known to pkh (e.g. "debian", "ubuntu")
|
||||
/// List the distributions known to pkh (e.g. "debian", "ubuntu"), sorted so
|
||||
/// that menus and error messages derived from it are deterministic
|
||||
pub fn supported_dists() -> Vec<String> {
|
||||
DATA.dist.keys().cloned().collect()
|
||||
let mut dists: Vec<String> = DATA.dist.keys().cloned().collect();
|
||||
dists.sort();
|
||||
dists
|
||||
}
|
||||
|
||||
/// Name of a dist's primary mirror entry: its URL doubles as the dist's
|
||||
/// base URL ([`get_base_url`]) and is the first candidate of
|
||||
/// [`mirror_for_arch`]
|
||||
const PRIMARY_MIRROR: &str = "primary";
|
||||
|
||||
/// The data of a known distribution: the shared "unknown distribution"
|
||||
/// error of the per-dist accessors
|
||||
fn dist_data(dist: &str) -> Result<&'static DistData, Box<dyn Error>> {
|
||||
DATA.dist.get(dist).ok_or_else(|| {
|
||||
format!(
|
||||
"Unknown distribution '{}'. Supported distributions are: {}.",
|
||||
dist,
|
||||
supported_dists().join(", ")
|
||||
)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// Special changelog distribution marking an entry that has not been
|
||||
@@ -192,7 +315,7 @@ pub async fn get_ordered_series(dist: &str) -> Result<Vec<SeriesInformation>, Bo
|
||||
})?;
|
||||
let series_info = &dist_data.series;
|
||||
let content = if Path::new(series_info.local.as_str()).exists() {
|
||||
std::fs::read_to_string(format!("/usr/share/distro-info/{dist}.csv")).map_err(|e| {
|
||||
std::fs::read_to_string(series_info.local.as_str()).map_err(|e| {
|
||||
format!(
|
||||
"Failed to read distribution series data for '{dist}' \
|
||||
from '{}': {}. The 'distro-info' package provides these CSV files.",
|
||||
@@ -295,6 +418,30 @@ pub async fn get_dist_from_series(series: &str) -> Result<String, Box<dyn Error>
|
||||
Err(format!("Unknown series: {}", series).into())
|
||||
}
|
||||
|
||||
/// The changelog suite name that aliases the series codename of `dist`
|
||||
/// (Debian's 'unstable' for 'sid'): the two names identify the same
|
||||
/// series. `None` when the series carries no suite alias.
|
||||
pub fn series_suite_alias(dist: &str, series: &str) -> Option<String> {
|
||||
dist_data(dist)
|
||||
.ok()?
|
||||
.suite_aliases
|
||||
.iter()
|
||||
.find(|(_suite, codename)| codename.as_str() == series)
|
||||
.map(|(suite, _)| suite.clone())
|
||||
}
|
||||
|
||||
/// Identify a changelog suite name with the distro-info series codename
|
||||
/// it aliases (Debian's 'unstable' is 'sid'), and the dist that codename
|
||||
/// belongs to. `None` when `suite` is not a known alias of any dist.
|
||||
pub fn resolve_suite_alias(suite: &str) -> Option<(String, String)> {
|
||||
for (dist, data) in DATA.dist.iter() {
|
||||
if let Some(codename) = data.suite_aliases.get(suite) {
|
||||
return Some((dist.clone(), codename.clone()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Get the package pockets available for a given distribution, in search order
|
||||
///
|
||||
/// The main archive ('') comes first so that a search without an explicit
|
||||
@@ -303,14 +450,7 @@ pub async fn get_dist_from_series(series: &str) -> Result<String, Box<dyn Error>
|
||||
///
|
||||
/// Example: get_dist_pockets(ubuntu) => ["", "updates", "security", "proposed"]
|
||||
pub fn get_dist_pockets(dist: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let dist_data = DATA.dist.get(dist).ok_or_else(|| {
|
||||
format!(
|
||||
"Unknown distribution '{}'. Supported distributions are: {}.",
|
||||
dist,
|
||||
supported_dists().join(", ")
|
||||
)
|
||||
})?;
|
||||
let mut pockets = dist_data.pockets.clone();
|
||||
let mut pockets = dist_data(dist)?.pockets.clone();
|
||||
|
||||
// Explicitely add 'main' pocket, which is just the empty string, first
|
||||
pockets.insert(0, "".to_string());
|
||||
@@ -318,18 +458,38 @@ pub fn get_dist_pockets(dist: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
Ok(pockets)
|
||||
}
|
||||
|
||||
/// Get the archive components of a distribution (ubuntu's main,
|
||||
/// restricted, universe, multiverse; Debian's main, contrib, non-free,
|
||||
/// non-free-firmware): the default set a build environment enables on its
|
||||
/// official sources. Live archive operations keep resolving components
|
||||
/// from Release files ([`get_components`]); this is the offline default.
|
||||
pub fn get_dist_components(dist: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
Ok(dist_data(dist)?.components.clone())
|
||||
}
|
||||
|
||||
/// Get the pockets a cross-build environment enables for a series (the
|
||||
/// `<series>-<pocket>` suite list is built from these): updates,
|
||||
/// backports and security. Deliberately separate from
|
||||
/// [`get_dist_pockets`], which is the *search order* of pull — folding
|
||||
/// backports into it would change pull behavior.
|
||||
pub fn get_cross_pockets(dist: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
Ok(dist_data(dist)?.cross_pockets.clone())
|
||||
}
|
||||
|
||||
/// Get the default build profiles of a distribution's vendor (Ubuntu
|
||||
/// activates `derivative.ubuntu noudeb`, Debian none), mirroring what
|
||||
/// `Dpkg::BuildProfiles` resolves when `DEB_BUILD_PROFILES` is unset.
|
||||
/// Vendors are matched case-insensitively by the caller (dpkg's `Vendor:`
|
||||
/// field keeps its original casing).
|
||||
pub fn get_build_profiles(dist: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
Ok(dist_data(dist)?.build_profiles.clone())
|
||||
}
|
||||
|
||||
/// Get the valid `Section` values of a distribution's packages, as accepted
|
||||
/// by its archives (a `section/subsection` in debian/control validates on
|
||||
/// the part before the '/')
|
||||
pub fn get_sections(dist: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let dist_data = DATA.dist.get(dist).ok_or_else(|| {
|
||||
format!(
|
||||
"Unknown distribution '{}'. Supported distributions are: {}.",
|
||||
dist,
|
||||
supported_dists().join(", ")
|
||||
)
|
||||
})?;
|
||||
Ok(dist_data.sections.clone())
|
||||
Ok(dist_data(dist)?.sections.clone())
|
||||
}
|
||||
|
||||
/// Get the sources URL for a distribution, series, pocket, and component
|
||||
@@ -342,23 +502,105 @@ pub fn get_sources_url(base_url: &str, series: &str, pocket: &str, component: &s
|
||||
format!("{base_url}/dists/{series}{pocket_full}/{component}/source/Sources.gz")
|
||||
}
|
||||
|
||||
/// Get the archive base URL for a distribution
|
||||
/// Get the archive base URL for a distribution: the URL of its primary
|
||||
/// mirror (the former `base_url` key folded into `mirrors.primary.url`
|
||||
/// when the mirrors were modeled — the signature is kept so the pull
|
||||
/// paths do not churn)
|
||||
///
|
||||
/// Example: ubuntu => https://archive.ubuntu.com/ubuntu
|
||||
pub fn get_base_url(dist: &str) -> Result<String, Box<dyn Error>> {
|
||||
DATA.dist
|
||||
.get(dist)
|
||||
.map(|d| d.base_url.clone())
|
||||
let mirror = dist_data(dist)?
|
||||
.mirrors
|
||||
.get(PRIMARY_MIRROR)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"Unknown distribution '{}'. Supported distributions are: {}.",
|
||||
dist,
|
||||
"Distribution '{dist}' has no '{PRIMARY_MIRROR}' mirror in the built-in \
|
||||
configuration. This is a bug; supported distributions are: {}.",
|
||||
supported_dists().join(", ")
|
||||
)
|
||||
})?;
|
||||
Ok(mirror.url.clone())
|
||||
}
|
||||
|
||||
/// The mirror of `dist` serving `arch`: the primary mirror first, then
|
||||
/// the other mirrors by name, so the answer is deterministic. Debian's
|
||||
/// `all` sentinel makes its primary mirror serve every architecture.
|
||||
/// Errors when the dist is unknown or no mirror serves the architecture
|
||||
/// (an architecture the built-in data does not know about).
|
||||
///
|
||||
/// Example: mirror_for_arch(ubuntu, riscv64) => the ports mirror
|
||||
pub fn mirror_for_arch(dist: &str, arch: &str) -> Result<&'static Mirror, Box<dyn Error>> {
|
||||
let data = dist_data(dist)?;
|
||||
if let Some(primary) = data.mirrors.get(PRIMARY_MIRROR)
|
||||
&& primary.serves(arch)
|
||||
{
|
||||
return Ok(primary);
|
||||
}
|
||||
let mut others: Vec<&String> = data
|
||||
.mirrors
|
||||
.keys()
|
||||
.filter(|name| name.as_str() != PRIMARY_MIRROR)
|
||||
.collect();
|
||||
others.sort();
|
||||
others
|
||||
.into_iter()
|
||||
.filter_map(|name| data.mirrors.get(name))
|
||||
.find(|mirror| mirror.serves(arch))
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"No mirror of '{dist}' serves the '{arch}' architecture. Supported \
|
||||
distributions are: {}.",
|
||||
supported_dists().join(", ")
|
||||
)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// Host part of an apt-source URL: everything after the `://` scheme up
|
||||
/// to the first `/` (a `:port` suffix stripped). URLs without a scheme
|
||||
/// yield their leading segment.
|
||||
fn url_host(url: &str) -> &str {
|
||||
let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
|
||||
let authority = after_scheme.split('/').next().unwrap_or(after_scheme);
|
||||
authority
|
||||
.split_once(':')
|
||||
.map_or(authority, |(host, _)| host)
|
||||
}
|
||||
|
||||
/// Whether the host of `uri` is the host of `mirror_url` or a subdomain
|
||||
/// of it: the old substring checks (`uri.contains("archive.ubuntu.com")`)
|
||||
/// intentionally matched the country mirrors fronting each archive host
|
||||
/// (`fr.archive.ubuntu.com`), and an exact host comparison would have
|
||||
/// dropped them. The leading dot of the suffix keeps look-alike hosts
|
||||
/// (`notarchive.ubuntu.com`) out.
|
||||
fn uri_matches_url_host(uri: &str, mirror_url: &str) -> bool {
|
||||
let host = url_host(mirror_url);
|
||||
let uri_host = url_host(uri);
|
||||
uri_host == host || uri_host.ends_with(&format!(".{host}"))
|
||||
}
|
||||
|
||||
/// Whether `uri` points at `mirror` or its security sibling: the URI's
|
||||
/// host is the mirror's (or the sibling's) host or a subdomain of it (see
|
||||
/// [`uri_matches_url_host`])
|
||||
pub fn is_mirror_source(mirror: &Mirror, uri: &str) -> bool {
|
||||
uri_matches_url_host(uri, &mirror.url)
|
||||
|| mirror
|
||||
.security_url
|
||||
.as_deref()
|
||||
.is_some_and(|security| uri_matches_url_host(uri, security))
|
||||
}
|
||||
|
||||
/// Whether `uri` points at an official source of `dist` — one of its
|
||||
/// archive mirrors or their security siblings — as opposed to a PPA or
|
||||
/// another third-party repository. Unknown distributions match nothing.
|
||||
pub fn is_official_source(dist: &str, uri: &str) -> bool {
|
||||
DATA.dist.get(dist).is_some_and(|data| {
|
||||
data.mirrors
|
||||
.values()
|
||||
.any(|mirror| is_mirror_source(mirror, uri))
|
||||
})
|
||||
}
|
||||
|
||||
/// Obtain the URLs for the archive keyrings of a distribution series
|
||||
///
|
||||
/// For 'sid' and 'experimental', returns keyrings from the 3 latest releases
|
||||
@@ -499,6 +741,30 @@ pub async fn get_debian_series_number(series: &str) -> Result<Option<String>, Bo
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The release number of a distribution series, paired with the dist it
|
||||
/// belongs to: the version column of the series data, stripped to its
|
||||
/// leading token ("12" for Debian bookworm, "26.04" out of Ubuntu
|
||||
/// resolute's "26.04 LTS"). `None` when the series carries no version at
|
||||
/// all (Debian's rolling sid/experimental have an empty column;
|
||||
/// pseudo-versions like "unstable" pass through, callers validate per
|
||||
/// vendor). Errors when no known distribution carries the series.
|
||||
pub async fn get_series_release_number(
|
||||
series: &str,
|
||||
) -> Result<Option<(String, String)>, Box<dyn Error>> {
|
||||
let dist = get_dist_from_series(series).await?;
|
||||
for info in get_ordered_series(&dist).await? {
|
||||
if info.series == series {
|
||||
let number = info
|
||||
.version
|
||||
.as_deref()
|
||||
.and_then(|version| version.split_whitespace().next())
|
||||
.map(str::to_string);
|
||||
return Ok(number.map(|number| (dist, number)));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -516,6 +782,143 @@ mod tests {
|
||||
assert!(get_sections("not-a-distro").is_err());
|
||||
}
|
||||
|
||||
/// The primary mirror's URL is the former `base_url`, byte for byte:
|
||||
/// the pull paths build their archive URLs from it.
|
||||
#[test]
|
||||
fn test_primary_mirror_url_is_the_base_url() {
|
||||
assert_eq!(
|
||||
get_base_url("ubuntu").unwrap(),
|
||||
"https://archive.ubuntu.com/ubuntu"
|
||||
);
|
||||
assert_eq!(
|
||||
get_base_url("debian").unwrap(),
|
||||
"https://deb.debian.org/debian"
|
||||
);
|
||||
assert!(get_base_url("not-a-distro").is_err());
|
||||
}
|
||||
|
||||
/// Mirror-per-architecture resolution: the local architectures come
|
||||
/// from Ubuntu's primary mirror, the others from ports; Debian's `all`
|
||||
/// sentinel makes its one mirror serve everything, including
|
||||
/// architectures the data never lists.
|
||||
#[test]
|
||||
fn test_mirror_for_arch() {
|
||||
assert_eq!(
|
||||
mirror_for_arch("ubuntu", "amd64").unwrap().url,
|
||||
"https://archive.ubuntu.com/ubuntu"
|
||||
);
|
||||
assert_eq!(
|
||||
mirror_for_arch("ubuntu", "riscv64").unwrap().url,
|
||||
"http://ports.ubuntu.com/ubuntu-ports"
|
||||
);
|
||||
for arch in ["amd64", "riscv64", "brand-new"] {
|
||||
assert_eq!(
|
||||
mirror_for_arch("debian", arch).unwrap().url,
|
||||
"https://deb.debian.org/debian",
|
||||
"the `all` sentinel serves every architecture, including {arch}"
|
||||
);
|
||||
}
|
||||
// An architecture no Ubuntu mirror serves, and an unknown dist.
|
||||
assert!(mirror_for_arch("ubuntu", "mips64el").is_err());
|
||||
assert!(mirror_for_arch("not-a-distro", "amd64").is_err());
|
||||
}
|
||||
|
||||
/// The `archs` forms and their reading: the `all` sentinel serves
|
||||
/// everything, an explicit list serves exactly its members, and any
|
||||
/// other scalar serves nothing (a data bug a validation would have to
|
||||
/// catch, hence the documented reading).
|
||||
#[test]
|
||||
fn test_mirror_archs_forms() {
|
||||
let all: MirrorArchs = serde_yaml::from_str("all").unwrap();
|
||||
assert!(all.serves("anything"));
|
||||
let list: MirrorArchs = serde_yaml::from_str("[amd64, i386]").unwrap();
|
||||
assert!(list.serves("amd64"));
|
||||
assert!(!list.serves("arm64"));
|
||||
let typo: MirrorArchs = serde_yaml::from_str("every").unwrap();
|
||||
assert!(!typo.serves("amd64"));
|
||||
}
|
||||
|
||||
/// Official-source matching is host-based but keeps matching the
|
||||
/// country mirrors the old substring checks matched (`fr.archive.
|
||||
/// ubuntu.com`): equality or a `.{host}` suffix, never a bare
|
||||
/// substring — `notarchive.ubuntu.com` must not match.
|
||||
#[test]
|
||||
fn test_is_official_source_matches_country_mirrors_only() {
|
||||
for uri in [
|
||||
"https://archive.ubuntu.com/ubuntu",
|
||||
"http://security.ubuntu.com/ubuntu",
|
||||
"http://ports.ubuntu.com/ubuntu-ports",
|
||||
// Country mirrors front the same archives.
|
||||
"http://fr.archive.ubuntu.com/ubuntu",
|
||||
"https://de.security.ubuntu.com/ubuntu",
|
||||
] {
|
||||
assert!(is_official_source("ubuntu", uri), "{uri}");
|
||||
}
|
||||
for uri in [
|
||||
"https://deb.debian.org/debian",
|
||||
"https://ppa.launchpadcontent.net/user/ppa/ubuntu",
|
||||
"http://notarchive.ubuntu.com/ubuntu",
|
||||
"http://archive.ubuntu.com.evil.example/ubuntu",
|
||||
] {
|
||||
assert!(!is_official_source("ubuntu", uri), "{uri}");
|
||||
}
|
||||
// Debian: its own mirror matches, Ubuntu's mirrors do not, and an
|
||||
// unknown dist matches nothing.
|
||||
assert!(is_official_source(
|
||||
"debian",
|
||||
"https://deb.debian.org/debian"
|
||||
));
|
||||
assert!(!is_official_source(
|
||||
"debian",
|
||||
"http://security.ubuntu.com/ubuntu"
|
||||
));
|
||||
assert!(!is_official_source(
|
||||
"not-a-distro",
|
||||
"https://deb.debian.org/debian"
|
||||
));
|
||||
}
|
||||
|
||||
/// The dist-level defaults the build paths read: components,
|
||||
/// cross-build pockets (deliberately not the pull search order) and
|
||||
/// vendor build profiles.
|
||||
#[test]
|
||||
fn test_dist_components_cross_pockets_and_build_profiles() {
|
||||
assert_eq!(
|
||||
get_dist_components("ubuntu").unwrap(),
|
||||
vec!["main", "restricted", "universe", "multiverse"]
|
||||
);
|
||||
assert!(
|
||||
get_dist_components("debian")
|
||||
.unwrap()
|
||||
.contains(&"non-free-firmware".to_string())
|
||||
);
|
||||
|
||||
for dist in ["debian", "ubuntu"] {
|
||||
assert_eq!(
|
||||
get_cross_pockets(dist).unwrap(),
|
||||
vec!["updates", "backports", "security"]
|
||||
);
|
||||
}
|
||||
// Not the pull search order: no 'proposed', no empty main pocket.
|
||||
let cross = get_cross_pockets("ubuntu").unwrap();
|
||||
assert!(!cross.contains(&"proposed".to_string()));
|
||||
assert!(!cross.contains(&"".to_string()));
|
||||
|
||||
assert_eq!(
|
||||
get_build_profiles("ubuntu").unwrap(),
|
||||
vec!["derivative.ubuntu", "noudeb"]
|
||||
);
|
||||
assert!(get_build_profiles("debian").unwrap().is_empty());
|
||||
|
||||
for getter in [
|
||||
get_dist_components as fn(&str) -> Result<Vec<String>, Box<dyn Error>>,
|
||||
get_cross_pockets as fn(&str) -> Result<Vec<String>, Box<dyn Error>>,
|
||||
get_build_profiles as fn(&str) -> Result<Vec<String>, Box<dyn Error>>,
|
||||
] {
|
||||
assert!(getter("not-a-distro").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_series_csv_malformed_rows() {
|
||||
// A short row (missing 'codename') is skipped, a row with an invalid
|
||||
@@ -661,6 +1064,41 @@ mod tests {
|
||||
assert!(series.contains(&"jammy".to_string()));
|
||||
}
|
||||
|
||||
/// Suite aliases identify a changelog suite name with the series
|
||||
/// codename of the same series: Debian's 'unstable' is 'sid'
|
||||
#[test]
|
||||
fn test_suite_aliases() {
|
||||
assert_eq!(
|
||||
resolve_suite_alias("unstable"),
|
||||
Some(("debian".to_string(), "sid".to_string()))
|
||||
);
|
||||
// A series codename or unknown suite is not an alias
|
||||
assert_eq!(resolve_suite_alias("sid"), None);
|
||||
assert_eq!(resolve_suite_alias("noble"), None);
|
||||
assert_eq!(
|
||||
series_suite_alias("debian", "sid"),
|
||||
Some("unstable".to_string())
|
||||
);
|
||||
assert_eq!(series_suite_alias("debian", "trixie"), None);
|
||||
assert_eq!(series_suite_alias("ubuntu", "noble"), None);
|
||||
}
|
||||
|
||||
/// Every suite alias must map to a real series of its dist, or the
|
||||
/// selector would offer a phantom entry
|
||||
#[tokio::test]
|
||||
async fn test_suite_aliases_target_real_series() {
|
||||
for (dist, data) in DATA.dist.iter() {
|
||||
for (suite, codename) in &data.suite_aliases {
|
||||
let series = get_ordered_series_name(dist).await.unwrap_or_default();
|
||||
assert!(
|
||||
series.contains(codename),
|
||||
"suite alias '{suite}' of {dist} maps to '{codename}', \
|
||||
which is not a known series"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_dist_from_series() {
|
||||
assert_eq!(get_dist_from_series("sid").await.unwrap(), "debian");
|
||||
@@ -683,6 +1121,25 @@ mod tests {
|
||||
assert!(unknown_number.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_series_release_number() {
|
||||
let (dist, bookworm) = get_series_release_number("bookworm")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(dist, "debian");
|
||||
assert_eq!(bookworm, "12");
|
||||
|
||||
// Ubuntu LTS rows carry a " LTS" decoration: only the leading
|
||||
// YY.MM token is the release number
|
||||
let (dist, noble) = get_series_release_number("noble").await.unwrap().unwrap();
|
||||
assert_eq!(dist, "ubuntu");
|
||||
assert_eq!(noble, "24.04");
|
||||
|
||||
// No known dist carries the series
|
||||
assert!(get_series_release_number("not-a-series").await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_keyring_urls_sid() {
|
||||
// Test that 'sid' returns keyrings from the 3 latest released versions
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Passive interrupt state shared between the CLI and the library.
|
||||
//!
|
||||
//! Everything active about Ctrl+C lives in the CLI (`main.rs`): it installs
|
||||
//! the SIGINT handler, wakes a watchdog thread, prints the interrupt notice
|
||||
//! and exits with the conventional status 130. This module only holds the
|
||||
//! state the library's own types need:
|
||||
//!
|
||||
//! - the interrupted flag ([`mark_interrupted`] / [`interrupted`]), read by
|
||||
//! flows so they stand down while the watchdog tears everything down;
|
||||
//! - the cleanup hook registry ([`register_cleanup_hook`]) for resources
|
||||
//! that must not outlive the process (e.g. the ephemeral build chroot,
|
||||
//! see [`crate::deb::ephemeral`]), drained and run by the CLI watchdog
|
||||
//! right before exiting ([`run_cleanup_hooks`]);
|
||||
//! - the reporter slot ([`set_reporter`]): the live build view registers
|
||||
//! how to clear the terminal (and where the full log lives); the CLI
|
||||
//! runs it as the first step of the shutdown.
|
||||
//!
|
||||
//! Nothing here installs signal handlers, prints or exits: a library
|
||||
//! consumer embedding these types keeps its own signal disposition.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
/// How the live view reports an interrupt: it clears the terminal and
|
||||
/// returns the log-file hint to print below the notice, if any
|
||||
pub type Reporter = Box<dyn FnOnce() -> Option<String> + Send>;
|
||||
|
||||
/// A boxed, send-safe cleanup hook body
|
||||
type CleanupFn = Box<dyn Fn() + Send>;
|
||||
|
||||
/// The reporter run before the cleanup hooks; taken out when it runs
|
||||
static REPORTER: Mutex<Option<Reporter>> = Mutex::new(None);
|
||||
|
||||
/// Whether a Ctrl+C has been intercepted since the CLI installed the
|
||||
/// handler
|
||||
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Registry of cleanup hooks waiting to run at interrupt time
|
||||
static CLEANUP_HOOKS: Mutex<Vec<CleanupHook>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Source of the registry ids used to deregister a specific hook
|
||||
static NEXT_CLEANUP_HOOK_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// A pending cleanup hook together with its registry id
|
||||
struct CleanupHook {
|
||||
id: u64,
|
||||
f: CleanupFn,
|
||||
}
|
||||
|
||||
/// Record that a Ctrl+C has been intercepted; called by the CLI signal
|
||||
/// handler
|
||||
pub fn mark_interrupted() {
|
||||
INTERRUPTED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Whether a Ctrl+C has been intercepted; flows use this to stay quiet and
|
||||
/// to leave the cleanup to the CLI watchdog
|
||||
pub fn interrupted() -> bool {
|
||||
INTERRUPTED.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Register how the live view reports an interrupt: the CLI watchdog runs
|
||||
/// it as the first step of the shutdown, before the cleanup hooks. At most
|
||||
/// one reporter runs per process: a later call replaces the one set before.
|
||||
/// Without any reporter the watchdog only prints the plain notice.
|
||||
pub fn set_reporter(report: Reporter) {
|
||||
*REPORTER.lock().unwrap_or_else(PoisonError::into_inner) = Some(report);
|
||||
}
|
||||
|
||||
/// Take the registered reporter out of the slot; `None` when no live view
|
||||
/// registered one (`--verbose`, piped output)
|
||||
pub fn take_reporter() -> Option<Reporter> {
|
||||
REPORTER
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.take()
|
||||
}
|
||||
|
||||
/// Register a hook to be run when the process is interrupted (after the
|
||||
/// reporter), returning a guard whose drop deregisters the hook again.
|
||||
///
|
||||
/// Hooks must be self-contained — stored paths plus direct subprocesses —
|
||||
/// and must never block indefinitely: they run in the watchdog while the
|
||||
/// interrupted flow is still unwinding, and a second Ctrl+C during cleanup
|
||||
/// is a no-op.
|
||||
pub fn register_cleanup_hook(f: CleanupFn) -> CleanupHookGuard {
|
||||
let id = NEXT_CLEANUP_HOOK_ID.fetch_add(1, Ordering::Relaxed);
|
||||
CLEANUP_HOOKS
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(CleanupHook { id, f });
|
||||
CleanupHookGuard(id)
|
||||
}
|
||||
|
||||
/// RAII handle to a registered cleanup hook: dropping it (or an explicit
|
||||
/// [`CleanupHookGuard::deregister`]) removes the hook from the registry so
|
||||
/// the interrupt path can no longer run it
|
||||
pub struct CleanupHookGuard(u64);
|
||||
|
||||
impl CleanupHookGuard {
|
||||
/// Registry id of the hook (used to filter the registry in tests)
|
||||
#[cfg(test)]
|
||||
fn id(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Remove the hook from the registry; returns whether it was still
|
||||
/// pending
|
||||
pub fn deregister(&mut self) -> bool {
|
||||
deregister_cleanup_hook(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CleanupHookGuard {
|
||||
fn drop(&mut self) {
|
||||
deregister_cleanup_hook(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a hook from the registry; returns whether it was still pending
|
||||
fn deregister_cleanup_hook(id: u64) -> bool {
|
||||
let mut hooks = CLEANUP_HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let len_before = hooks.len();
|
||||
hooks.retain(|hook| hook.id != id);
|
||||
hooks.len() != len_before
|
||||
}
|
||||
|
||||
/// Drain and run every registered cleanup hook exactly once.
|
||||
///
|
||||
/// Called by the CLI watchdog right before the process exits. Draining uses
|
||||
/// `try_lock` with a bounded retry instead of a blocking lock as a hard
|
||||
/// upper bound on interrupt latency: the sequence must never hang waiting
|
||||
/// for a lock, however unlikely a stalled holder is. Timing out therefore
|
||||
/// skips cleanup (leaking) rather than hanging.
|
||||
pub fn run_cleanup_hooks() {
|
||||
run_drained_hooks(drain_cleanup_hooks());
|
||||
}
|
||||
|
||||
/// Take every pending hook out of the registry, waiting at most ~1s for the
|
||||
/// registry lock (see [`run_cleanup_hooks`] for why this must not block
|
||||
/// forever)
|
||||
fn drain_cleanup_hooks() -> Vec<CleanupHook> {
|
||||
const RETRIES: usize = 200;
|
||||
const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(5);
|
||||
|
||||
for _ in 0..RETRIES {
|
||||
if let Ok(mut hooks) = CLEANUP_HOOKS.try_lock() {
|
||||
return std::mem::take(&mut *hooks);
|
||||
}
|
||||
std::thread::sleep(RETRY_DELAY);
|
||||
}
|
||||
log::error!("Timed out waiting for the cleanup hook registry; skipping interrupt cleanup");
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Run drained hooks one by one, isolating panics so that one failing hook
|
||||
/// cannot skip the remaining ones
|
||||
fn run_drained_hooks(hooks: Vec<CleanupHook>) {
|
||||
for CleanupHook { id, f } in hooks {
|
||||
// Hooks are arbitrary user code; assert unwind safety so they can be
|
||||
// run inside a catching context
|
||||
if let Err(panic) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
|
||||
log::error!("Cleanup hook {id} panicked: {}", panic_message(&panic));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort message extraction from a panic payload
|
||||
fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
|
||||
if let Some(s) = panic.downcast_ref::<&str>() {
|
||||
(*s).to_string()
|
||||
} else if let Some(s) = panic.downcast_ref::<String>() {
|
||||
s.clone()
|
||||
} else {
|
||||
"non-string panic payload".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
/// Serializes these tests: they drain the process-global registry, and
|
||||
/// unrelated tests may hold registrations concurrently that must be
|
||||
/// neither run nor lost. Poison-proof: a test failing while holding the
|
||||
/// lock must not cascade into the others.
|
||||
static TEST_LOCK: StdMutex<()> = StdMutex::new(());
|
||||
|
||||
fn test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
TEST_LOCK.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Drain the registry and take out only the hooks with the given ids,
|
||||
/// putting everything else back so unrelated registrations stay pending
|
||||
fn take_hooks(ids: &[u64]) -> Vec<CleanupHook> {
|
||||
let drained = drain_cleanup_hooks();
|
||||
let mut mine = Vec::new();
|
||||
let mut others = Vec::new();
|
||||
for hook in drained {
|
||||
if ids.contains(&hook.id) {
|
||||
mine.push(hook);
|
||||
} else {
|
||||
others.push(hook);
|
||||
}
|
||||
}
|
||||
CLEANUP_HOOKS
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.extend(others);
|
||||
mine
|
||||
}
|
||||
|
||||
/// Register a hook that counts its invocations
|
||||
fn counting_hook() -> (CleanupHookGuard, Arc<AtomicUsize>) {
|
||||
let counter = Arc::new(AtomicUsize::new(0));
|
||||
let seen = counter.clone();
|
||||
let guard = register_cleanup_hook(Box::new(move || {
|
||||
seen.fetch_add(1, Ordering::SeqCst);
|
||||
}));
|
||||
(guard, counter)
|
||||
}
|
||||
|
||||
/// Hooks run in registration order, and draining means each hook runs
|
||||
/// exactly once even across repeated cleanup passes.
|
||||
#[test]
|
||||
fn hooks_run_once_in_registration_order() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let log = Arc::new(StdMutex::new(Vec::new()));
|
||||
let mut guards = Vec::new();
|
||||
let mut ids = Vec::new();
|
||||
for name in ["hook-a", "hook-b", "hook-c"] {
|
||||
let log = log.clone();
|
||||
// The returned guard must stay alive: dropping it deregisters
|
||||
let guard = register_cleanup_hook(Box::new(move || {
|
||||
log.lock().unwrap().push(name);
|
||||
}));
|
||||
ids.push(guard.id());
|
||||
guards.push(guard);
|
||||
}
|
||||
|
||||
// Only our own hooks are extracted; they run in registration order
|
||||
let mine = take_hooks(&ids);
|
||||
assert_eq!(mine.len(), ids.len());
|
||||
run_drained_hooks(mine);
|
||||
assert_eq!(*log.lock().unwrap(), vec!["hook-a", "hook-b", "hook-c"]);
|
||||
|
||||
// Draining removed them: a second pass runs nothing again
|
||||
assert!(take_hooks(&ids).is_empty());
|
||||
assert_eq!(*log.lock().unwrap(), vec!["hook-a", "hook-b", "hook-c"]);
|
||||
|
||||
drop(guards);
|
||||
}
|
||||
|
||||
/// A panicking hook is contained by the runner: it neither aborts the
|
||||
/// process nor skips the hooks registered around it.
|
||||
#[test]
|
||||
fn panicking_hook_does_not_skip_the_others() {
|
||||
let _serial = test_lock();
|
||||
// The hook below panics on purpose: do not record it as a test
|
||||
// failure in the end-of-run matrix
|
||||
let _quiet = crate::test_support::suppress_failure_recording();
|
||||
|
||||
let (before, ran_before) = counting_hook();
|
||||
let boom = register_cleanup_hook(Box::new(|| panic!("cleanup exploded")));
|
||||
let (after, ran_after) = counting_hook();
|
||||
|
||||
let ids = [before.id(), boom.id(), after.id()];
|
||||
run_drained_hooks(take_hooks(&ids));
|
||||
|
||||
assert_eq!(ran_before.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(ran_after.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// Explicit deregistration removes the hook: it is no longer drained and
|
||||
/// never runs; a second deregistration reports it as already gone.
|
||||
#[test]
|
||||
fn deregistered_hook_never_runs() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let (mut guard, ran) = counting_hook();
|
||||
|
||||
assert!(guard.deregister());
|
||||
assert!(!guard.deregister());
|
||||
|
||||
assert!(take_hooks(&[guard.id()]).is_empty());
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
/// Dropping the registration guard deregisters the hook implicitly.
|
||||
#[test]
|
||||
fn dropping_the_guard_deregisters_the_hook() {
|
||||
let _serial = test_lock();
|
||||
|
||||
let id;
|
||||
let ran;
|
||||
{
|
||||
let (guard, counter) = counting_hook();
|
||||
id = guard.id();
|
||||
ran = counter;
|
||||
drop(guard);
|
||||
}
|
||||
|
||||
assert!(take_hooks(&[id]).is_empty());
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
+367
-53
@@ -23,13 +23,95 @@ use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::data::embed_data;
|
||||
use crate::put::target::UploadTarget;
|
||||
|
||||
/// Git configuration key holding the Launchpad account name
|
||||
const LP_USER_KEY: &str = "lp.user";
|
||||
|
||||
/// Launchpad service endpoints, loaded from the bundled `launchpad.yml`
|
||||
/// data file (same pattern as `distro_info.yml`): static endpoints that
|
||||
/// change with Launchpad, not with the code, are data — several of them
|
||||
/// were previously duplicated across three modules.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct LaunchpadData {
|
||||
/// Base URL of the Launchpad REST API
|
||||
api_base: String,
|
||||
/// Host of the PPA SFTP upload server
|
||||
ssh_host: String,
|
||||
/// Port of the PPA SFTP upload server
|
||||
ssh_port: u16,
|
||||
/// Host of the PPA upload queue over anonymous FTP (the transport
|
||||
/// `pkh put` degrades to when the SSH connection never comes up)
|
||||
ftp_host: String,
|
||||
/// Port of the anonymous FTP upload queue
|
||||
ftp_port: u16,
|
||||
/// Upload queue incoming directory template (`{owner}`/`{ppa}`)
|
||||
incoming_template: String,
|
||||
/// PPA package-content (apt repository) URL template
|
||||
content_host_template: String,
|
||||
/// Ubuntu source-package git web URL template (`{package}`)
|
||||
git_web_template: String,
|
||||
}
|
||||
|
||||
embed_data! {
|
||||
static ref LAUNCHPAD_DATA: LaunchpadData = "../data/launchpad.yml"
|
||||
}
|
||||
|
||||
/// The PPA upload queue over anonymous FTP (host, port): the transport
|
||||
/// dput-ng's plain `ppa:` profile pushes over, and the one `pkh put`
|
||||
/// degrades to when the SSH connection itself never comes up.
|
||||
pub(crate) fn ppa_ftp_queue() -> (String, u16) {
|
||||
(LAUNCHPAD_DATA.ftp_host.clone(), LAUNCHPAD_DATA.ftp_port)
|
||||
}
|
||||
|
||||
/// Base URL of the Launchpad REST API
|
||||
const API_BASE: &str = "https://api.launchpad.net/1.0";
|
||||
fn api_base() -> &'static str {
|
||||
&LAUNCHPAD_DATA.api_base
|
||||
}
|
||||
|
||||
/// Host serving PPA package content, derived from the content-host
|
||||
/// template so the URL builders and the URL parsers of PPA addresses
|
||||
/// cannot drift apart
|
||||
pub(crate) fn ppa_content_host() -> &'static str {
|
||||
let template = LAUNCHPAD_DATA.content_host_template.as_str();
|
||||
let after_scheme = template
|
||||
.split_once("://")
|
||||
.map_or(template, |(_, rest)| rest);
|
||||
after_scheme.split('/').next().unwrap_or(after_scheme)
|
||||
}
|
||||
|
||||
/// Base URL of the apt repository serving a PPA's packages
|
||||
/// (e.g. `https://ppa.launchpadcontent.net/user/ppa/ubuntu`)
|
||||
pub(crate) fn ppa_content_url(owner: &str, ppa: &str) -> String {
|
||||
LAUNCHPAD_DATA
|
||||
.content_host_template
|
||||
.replace("{owner}", owner)
|
||||
.replace("{ppa}", ppa)
|
||||
}
|
||||
|
||||
/// URL of the Launchpad git repository of an Ubuntu source package
|
||||
/// (`git.launchpad.net/ubuntu/+source/<package>`), the preferred VCS of
|
||||
/// Ubuntu packages
|
||||
pub(crate) fn ubuntu_source_git_url(package: &str) -> String {
|
||||
LAUNCHPAD_DATA
|
||||
.git_web_template
|
||||
.replace("{package}", package)
|
||||
}
|
||||
|
||||
/// Page size (`ws.size`) asked from Launchpad collections. Launchpad
|
||||
/// truncates collection answers at 75 entries by default and rejects
|
||||
/// `ws.size` above 300 (both verified against the live API); 100 sits
|
||||
/// comfortably under the cap while keeping multi-page walks rare.
|
||||
const WS_PAGE_SIZE: u32 = 100;
|
||||
|
||||
/// Hard cap on the pages followed while walking a `getPublishedSources`
|
||||
/// collection: 20 pages x 100 entries = 2000 currently published entries
|
||||
/// for one source name. The query only counts `Published` entries of live
|
||||
/// series/pockets, so real histories are a handful of entries; a walk
|
||||
/// reaching the cap means the API is misbehaving (an endless next-link
|
||||
/// chain), not that the history is genuinely huge.
|
||||
const MAX_COLLECTION_PAGES: u32 = 20;
|
||||
|
||||
/// The Launchpad username configured in git: the repository-local
|
||||
/// configuration wins over the global one, like git's own precedence.
|
||||
@@ -74,26 +156,30 @@ fn split_ppa(ppa: &str) -> Result<(String, String), String> {
|
||||
|
||||
/// URL of the Launchpad API resource of a Launchpad account
|
||||
fn person_url(user: &str) -> String {
|
||||
format!("{API_BASE}/~{user}")
|
||||
format!("{}/~{user}", api_base())
|
||||
}
|
||||
|
||||
/// URL of the Launchpad API resource of a PPA (`~user/+archive/ubuntu/name`
|
||||
/// covers the default `ppa` archive and named archives alike)
|
||||
fn archive_url(user: &str, ppa: &str) -> String {
|
||||
format!("{API_BASE}/~{user}/+archive/ubuntu/{ppa}")
|
||||
/// covers the default `ppa` archive and named archives alike); shared by the
|
||||
/// put-side pre-flight checks and the apt keyring's fingerprint lookup
|
||||
pub(crate) fn archive_url(user: &str, ppa: &str) -> String {
|
||||
format!("{}/~{user}/+archive/ubuntu/{ppa}", api_base())
|
||||
}
|
||||
|
||||
/// Resolve a `user/ppa_name` PPA argument into its upload target
|
||||
/// (`ppa.launchpad.net`, incoming `~user/ppa_name`), like dput-ng's
|
||||
/// Resolve a `user/ppa_name` PPA argument into its upload target (the
|
||||
/// SFTP host and incoming template of `launchpad.yml`), like dput-ng's
|
||||
/// `ppa:user/ppa` profile expansion.
|
||||
pub fn ppa_target(ppa: &str) -> Result<UploadTarget, String> {
|
||||
let (user, name) = split_ppa(ppa)?;
|
||||
|
||||
Ok(UploadTarget {
|
||||
fqdn: "ppa.launchpad.net".to_string(),
|
||||
port: 22,
|
||||
fqdn: LAUNCHPAD_DATA.ssh_host.clone(),
|
||||
port: LAUNCHPAD_DATA.ssh_port,
|
||||
login: None,
|
||||
incoming: format!("~{user}/{name}"),
|
||||
incoming: LAUNCHPAD_DATA
|
||||
.incoming_template
|
||||
.replace("{owner}", &user)
|
||||
.replace("{ppa}", &name),
|
||||
label: format!("ppa:{ppa}"),
|
||||
})
|
||||
}
|
||||
@@ -178,20 +264,21 @@ fn percent_encode(value: &str) -> String {
|
||||
encoded
|
||||
}
|
||||
|
||||
/// URL of the `getPublishedSources` API call listing the currently
|
||||
/// `Published` source packages named `source_name` in the PPA `user/name`:
|
||||
/// `exact_match` avoids Launchpad's default case-insensitive substring
|
||||
/// matching, which would return unrelated sources (`data` matching
|
||||
/// `datatables`).
|
||||
/// URL of the first page of the `getPublishedSources` API call listing the
|
||||
/// currently `Published` source packages named `source_name` in the PPA
|
||||
/// `user/name`: `exact_match` avoids Launchpad's default case-insensitive
|
||||
/// substring matching, which would return unrelated sources (`data` matching
|
||||
/// `datatables`). Further pages are reached through the answer's
|
||||
/// `next_collection_link`, not by hand-building URLs.
|
||||
fn published_sources_url(user: &str, ppa: &str, source_name: &str) -> String {
|
||||
format!(
|
||||
"{}?ws.op=getPublishedSources&source_name={}&exact_match=true&status=Published",
|
||||
"{}?ws.op=getPublishedSources&source_name={}&exact_match=true&status=Published&ws.size={WS_PAGE_SIZE}",
|
||||
archive_url(user, ppa),
|
||||
percent_encode(source_name)
|
||||
)
|
||||
}
|
||||
|
||||
/// One entry of a `getPublishedSources` answer: the subset of the source
|
||||
/// One page of a `getPublishedSources` answer: the subset of the source
|
||||
/// package publishing history the superseded-upload check needs (the live
|
||||
/// answer carries many more fields, ignored by serde)
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -200,42 +287,52 @@ struct PublishedSource {
|
||||
source_package_version: String,
|
||||
}
|
||||
|
||||
/// The `getPublishedSources` collection answer
|
||||
/// One page of the `getPublishedSources` collection answer
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PublishedSources {
|
||||
/// The currently published source packages matching the query
|
||||
/// The currently published source packages matching the query, on this
|
||||
/// page only
|
||||
#[serde(default)]
|
||||
entries: Vec<PublishedSource>,
|
||||
/// URL of the next page, present only when the collection was
|
||||
/// truncated (Launchpad answers carry it as a plain JSON string)
|
||||
next_collection_link: Option<String>,
|
||||
}
|
||||
|
||||
/// Every version of `source_name` currently `Published` in the PPA
|
||||
/// `user/name` (same `user/ppa_name` format as `pkh put --ppa`), in API
|
||||
/// order. Empty when the source was never published there — a 200 answer
|
||||
/// with zero entries, the normal first-upload case.
|
||||
pub async fn published_versions(
|
||||
ppa: &str,
|
||||
source_name: &str,
|
||||
) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let (user, name) = split_ppa(ppa)?;
|
||||
let client = crate::distro_info::http_client();
|
||||
/// Parse one page of a `getPublishedSources` collection into the versions
|
||||
/// it carries plus the link to the next page (`None` on the last one): the
|
||||
/// pagination decision, factored out of the HTTP walk so it can be tested
|
||||
/// without a server.
|
||||
fn parse_collection_page(body: &str) -> Result<(Vec<String>, Option<String>), serde_json::Error> {
|
||||
let sources: PublishedSources = serde_json::from_str(body)?;
|
||||
Ok((
|
||||
sources
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|entry| entry.source_package_version)
|
||||
.collect(),
|
||||
sources.next_collection_link,
|
||||
))
|
||||
}
|
||||
|
||||
/// GET one page of a collection, mapping the API statuses to the same
|
||||
/// errors as the other Launchpad calls (404 means the PPA does not exist).
|
||||
/// Returns the response body for [`parse_collection_page`].
|
||||
async fn fetch_collection_page(
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
ppa: &str,
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
let response = client
|
||||
.get(published_sources_url(&user, &name, source_name))
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("cannot reach the Launchpad API: {e}"))?;
|
||||
match response.status() {
|
||||
reqwest::StatusCode::OK => {
|
||||
let sources: PublishedSources = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("cannot parse the Launchpad API response for '{ppa}': {e}"))?;
|
||||
Ok(sources
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|entry| entry.source_package_version)
|
||||
.collect())
|
||||
}
|
||||
reqwest::StatusCode::OK => response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("cannot read the Launchpad API response for '{ppa}': {e}").into()),
|
||||
reqwest::StatusCode::NOT_FOUND => {
|
||||
Err(format!("PPA '{ppa}' does not exist: create it on launchpad.net first").into())
|
||||
}
|
||||
@@ -243,6 +340,66 @@ pub async fn published_versions(
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk a `getPublishedSources` collection page by page: fetch the first
|
||||
/// page, then follow `next_collection_link` (the canonical Launchpad
|
||||
/// pagination) until a page comes without one, accumulating the versions of
|
||||
/// every page in order.
|
||||
///
|
||||
/// Exceeding [`MAX_COLLECTION_PAGES`] errors rather than returning the
|
||||
/// partial list: the result feeds `put`'s superseded-upload check, where a
|
||||
/// silently truncated list is exactly the bug pagination fixes — a
|
||||
/// superseded upload wrongly allowed through, to be rejected (or to
|
||||
/// silently supersede) in Launchpad's queue hours later. Every other
|
||||
/// failure mode of this check (network, HTTP status, parsing) aborts the
|
||||
/// upload too, and `put` fails before anything is written, so erring costs
|
||||
/// only a clear message.
|
||||
async fn walk_collection(
|
||||
client: &reqwest::Client,
|
||||
first_url: &str,
|
||||
ppa: &str,
|
||||
) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let mut versions = Vec::new();
|
||||
let mut url = first_url.to_string();
|
||||
for _page in 1..=MAX_COLLECTION_PAGES {
|
||||
let body = fetch_collection_page(client, &url, ppa).await?;
|
||||
let (mut page_versions, next) = parse_collection_page(&body)
|
||||
.map_err(|e| format!("cannot parse the Launchpad API response for '{ppa}': {e}"))?;
|
||||
versions.append(&mut page_versions);
|
||||
match next {
|
||||
Some(next) => url = next,
|
||||
None => return Ok(versions),
|
||||
}
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"the Launchpad API keeps paginating the published sources of '{ppa}' \
|
||||
after {MAX_COLLECTION_PAGES} pages: cannot run the superseded check \
|
||||
on a partial list"
|
||||
)
|
||||
.into())
|
||||
}
|
||||
|
||||
/// Every version of `source_name` currently `Published` in the PPA
|
||||
/// `user/name` (same `user/ppa_name` format as `pkh put --ppa`), in API
|
||||
/// order. Empty when the source was never published there — a 200 answer
|
||||
/// with zero entries, the normal first-upload case. Launchpad truncates
|
||||
/// collections per page, so the walk follows the API's `next_collection_link`
|
||||
/// until the collection is exhausted: a single page would miss the highest
|
||||
/// version of a source published in many series/pockets over time, and the
|
||||
/// superseded check would wrongly pass.
|
||||
pub async fn published_versions(
|
||||
ppa: &str,
|
||||
source_name: &str,
|
||||
) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let (user, name) = split_ppa(ppa)?;
|
||||
walk_collection(
|
||||
crate::distro_info::http_client(),
|
||||
&published_sources_url(&user, &name, source_name),
|
||||
ppa,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// PPA uploads only target Ubuntu series: fail before uploading when the
|
||||
/// changes' distribution is not a known series (typo) or a non-Ubuntu one —
|
||||
/// both are only rejected during queue processing otherwise
|
||||
@@ -277,6 +434,13 @@ mod tests {
|
||||
assert_eq!(target.login, None);
|
||||
}
|
||||
|
||||
/// The anonymous FTP fallback queue resolves from the same data the
|
||||
/// dput-ng `ppa:` profile uses.
|
||||
#[test]
|
||||
fn ppa_ftp_queue_resolves() {
|
||||
assert_eq!(ppa_ftp_queue(), ("ppa.launchpad.net".to_string(), 21));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ppa_target_rejects_missing_separator() {
|
||||
assert!(ppa_target("just-a-name").is_err());
|
||||
@@ -339,6 +503,23 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The data-driven endpoint accessors build the same addresses the
|
||||
/// former hardcoded constants carried (each verified against the live
|
||||
/// service), and the content host is derived from the same template
|
||||
/// the content URLs are built from
|
||||
#[test]
|
||||
fn data_driven_endpoints_match_the_service() {
|
||||
assert_eq!(
|
||||
ppa_content_url("vhaudiquet", "noctalia"),
|
||||
"https://ppa.launchpadcontent.net/vhaudiquet/noctalia/ubuntu"
|
||||
);
|
||||
assert_eq!(ppa_content_host(), "ppa.launchpadcontent.net");
|
||||
assert_eq!(
|
||||
ubuntu_source_git_url("hello"),
|
||||
"https://git.launchpad.net/ubuntu/+source/hello"
|
||||
);
|
||||
}
|
||||
|
||||
/// The API answer carries many unrelated fields; deserialization must
|
||||
/// pick the relevant ones and tolerate a null `enabled`
|
||||
#[test]
|
||||
@@ -372,16 +553,17 @@ mod tests {
|
||||
}
|
||||
|
||||
/// The query matches the verified live `getPublishedSources` call, with
|
||||
/// the source name percent-encoded
|
||||
/// the source name percent-encoded and an explicit page size (the API
|
||||
/// default of 75 entries would hide part of long publishing histories)
|
||||
#[test]
|
||||
fn published_sources_url_matches_launchpad_call() {
|
||||
assert_eq!(
|
||||
published_sources_url("vhaudiquet", "noctalia", "noctalia"),
|
||||
"https://api.launchpad.net/1.0/~vhaudiquet/+archive/ubuntu/noctalia?ws.op=getPublishedSources&source_name=noctalia&exact_match=true&status=Published"
|
||||
"https://api.launchpad.net/1.0/~vhaudiquet/+archive/ubuntu/noctalia?ws.op=getPublishedSources&source_name=noctalia&exact_match=true&status=Published&ws.size=100"
|
||||
);
|
||||
assert_eq!(
|
||||
published_sources_url("vhaudiquet", "noctalia", "g++"),
|
||||
"https://api.launchpad.net/1.0/~vhaudiquet/+archive/ubuntu/noctalia?ws.op=getPublishedSources&source_name=g%2B%2B&exact_match=true&status=Published"
|
||||
"https://api.launchpad.net/1.0/~vhaudiquet/+archive/ubuntu/noctalia?ws.op=getPublishedSources&source_name=g%2B%2B&exact_match=true&status=Published&ws.size=100"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -411,21 +593,153 @@ mod tests {
|
||||
]
|
||||
}"#;
|
||||
|
||||
let sources: PublishedSources = serde_json::from_str(json).unwrap();
|
||||
let versions: Vec<&str> = sources
|
||||
.entries
|
||||
.iter()
|
||||
.map(|entry| entry.source_package_version.as_str())
|
||||
.collect();
|
||||
let (versions, next) = parse_collection_page(json).unwrap();
|
||||
assert_eq!(versions, vec!["5.1.0-1ubuntu2", "2:1.0-1"]);
|
||||
// A page without a next link is the end of the collection
|
||||
assert_eq!(next, None);
|
||||
}
|
||||
|
||||
/// A 200 answer with zero entries is the normal "nothing published
|
||||
/// there" case, and must deserialize to an empty list
|
||||
#[test]
|
||||
fn published_sources_parses_empty_collection() {
|
||||
let sources: PublishedSources =
|
||||
serde_json::from_str(r#"{"start": 0, "total_size": 0, "entries": []}"#).unwrap();
|
||||
assert!(sources.entries.is_empty());
|
||||
let (versions, next) =
|
||||
parse_collection_page(r#"{"start": 0, "total_size": 0, "entries": []}"#).unwrap();
|
||||
assert!(versions.is_empty());
|
||||
assert_eq!(next, None);
|
||||
}
|
||||
|
||||
/// A truncated page announces the next one through
|
||||
/// `next_collection_link`, carried as a plain JSON string (shape
|
||||
/// verified against the live API)
|
||||
#[test]
|
||||
fn parse_collection_page_reads_next_link() {
|
||||
let json = r#"{
|
||||
"start": 0,
|
||||
"total_size": 150,
|
||||
"entries": [{"source_package_version": "1.0-1"}],
|
||||
"next_collection_link": "https://api.launchpad.net/1.0/~u/+archive/ubuntu/p?ws.op=getPublishedSources&ws.size=100&memo=100&ws.start=100"
|
||||
}"#;
|
||||
|
||||
let (versions, next) = parse_collection_page(json).unwrap();
|
||||
assert_eq!(versions, vec!["1.0-1"]);
|
||||
assert_eq!(
|
||||
next.as_deref(),
|
||||
Some(
|
||||
"https://api.launchpad.net/1.0/~u/+archive/ubuntu/p?ws.op=getPublishedSources&ws.size=100&memo=100&ws.start=100"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// Serve canned byte responses on a local port, one per connection (the
|
||||
/// last response repeats), and return the listener for URL building
|
||||
///
|
||||
/// The canned responses must use 'Connection: close' so the client opens
|
||||
/// a fresh connection (and receives a fresh response) per request.
|
||||
fn serve_responses(listener: std::net::TcpListener, responses: Vec<String>) {
|
||||
use std::io::{Read, Write};
|
||||
std::thread::spawn(move || {
|
||||
for (served, mut stream) in listener.incoming().flatten().enumerate() {
|
||||
let index = served.min(responses.len() - 1);
|
||||
// Drain the request first: closing with unread inbound data
|
||||
// would send a TCP RST and destroy the response in flight
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
match stream.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) if buf[..n].windows(4).any(|w| w == b"\r\n\r\n") => break,
|
||||
Ok(_) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let body = &responses[index];
|
||||
let _ = stream.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
let _ = stream.flush();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One `getPublishedSources` page carrying `versions`, with the
|
||||
/// `next_collection_link` of a truncated page when `next` is given
|
||||
fn collection_body(versions: &[&str], next: Option<&str>) -> String {
|
||||
let entries: Vec<String> = versions
|
||||
.iter()
|
||||
.map(|v| format!(r#"{{"source_package_version": "{v}"}}"#))
|
||||
.collect();
|
||||
let next_field = next
|
||||
.map(|link| format!(r#", "next_collection_link": "{link}""#))
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
r#"{{"start": 0, "total_size": {}, "entries": [{}]{next_field}}}"#,
|
||||
versions.len(),
|
||||
entries.join(", ")
|
||||
)
|
||||
}
|
||||
|
||||
/// Bind a fresh mock server ready to serve `responses` (the caller
|
||||
/// needs the address to build self-referential `next_collection_link`s
|
||||
/// before serving starts)
|
||||
fn bound_collection_server() -> (std::net::TcpListener, String) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
(listener, base)
|
||||
}
|
||||
|
||||
/// The collection walk follows `next_collection_link`: the versions of
|
||||
/// every page are collected in order, and the walk stops on the page
|
||||
/// without a next link (the mock repeats its last response forever, so
|
||||
/// an extra fetch would still pass — but a missing next-link handling
|
||||
/// would drop page two's versions from the result)
|
||||
#[tokio::test]
|
||||
async fn walk_collection_collects_every_page() {
|
||||
let (listener, base) = bound_collection_server();
|
||||
serve_responses(
|
||||
listener,
|
||||
vec![
|
||||
collection_body(&["1.0-1", "1.6-1"], Some(&format!("{base}/next"))),
|
||||
collection_body(&["0.9-1"], None),
|
||||
],
|
||||
);
|
||||
|
||||
let versions = walk_collection(
|
||||
crate::distro_info::http_client(),
|
||||
&format!("{base}/~u/+archive/ubuntu/p?ws.op=getPublishedSources"),
|
||||
"u/p",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(versions, vec!["1.0-1", "1.6-1", "0.9-1"]);
|
||||
}
|
||||
|
||||
/// A next-link chain that never ends must error, not loop forever: the
|
||||
/// partial list would feed the superseded check a false "not superseded"
|
||||
#[tokio::test]
|
||||
async fn walk_collection_errors_when_pagination_never_ends() {
|
||||
// The last (only) response repeats forever, each page linking back
|
||||
// to the server: the walk must stop at the page cap by itself
|
||||
let (listener, base) = bound_collection_server();
|
||||
serve_responses(
|
||||
listener,
|
||||
vec![collection_body(&["1.0-1"], Some(&format!("{base}/loop")))],
|
||||
);
|
||||
|
||||
let err = walk_collection(
|
||||
crate::distro_info::http_client(),
|
||||
&format!("{base}/~u/+archive/ubuntu/p?ws.op=getPublishedSources"),
|
||||
"u/p",
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
err.contains("keeps paginating the published sources of 'u/p'"),
|
||||
"unexpected: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+21
@@ -9,6 +9,9 @@ pub mod apt;
|
||||
pub mod build;
|
||||
/// Parse or edit a Debian changelog of a source package
|
||||
pub mod changelog;
|
||||
/// Embedding convention for static reference data (`data/*.yml`), applied
|
||||
/// by each owning module via the `embed_data!` macro
|
||||
pub(crate) mod data;
|
||||
/// Build a Debian package into a binary (.deb)
|
||||
pub mod deb;
|
||||
/// Reusable Debian format primitives (control/deb822, checksums, versions,
|
||||
@@ -16,8 +19,13 @@ pub mod deb;
|
||||
pub mod debian;
|
||||
/// Obtain general information about distribution, series, etc
|
||||
pub mod distro_info;
|
||||
/// Passive interrupt state: the interrupted flag, the cleanup hook registry
|
||||
/// and the live view's reporter slot (the CLI owns the signal handling)
|
||||
pub mod interrupt;
|
||||
/// Launchpad integration: PPA upload targets and account discovery
|
||||
pub mod launchpad;
|
||||
/// Lint a source tree: lintian wrapper for full parity plus pkh-native checks (`pkh lint`)
|
||||
pub mod lint;
|
||||
/// Scaffold a new Debian source package (`pkh new`)
|
||||
pub mod new;
|
||||
/// Obtain information about one or multiple packages
|
||||
@@ -31,12 +39,25 @@ pub mod put;
|
||||
/// Handle package-specific quirks and workarounds
|
||||
pub mod quirks;
|
||||
|
||||
/// Line classifiers rewriting raw subprocess output into display actions
|
||||
/// and countable progress (pure logic, shared by build views)
|
||||
pub mod logfmt;
|
||||
|
||||
/// Reporting ports: environment-agnostic build observation ([`BuildView`])
|
||||
/// and question answering ([`Prompter`]), implemented by terminal views,
|
||||
/// server bridges or the inert [`Quiet`]
|
||||
pub mod report;
|
||||
|
||||
/// Terminal UI helpers (progress bars, live build views, prompts)
|
||||
pub mod ui;
|
||||
|
||||
/// Handle context for .deb building: locally, over ssh, in a chroot...
|
||||
pub mod context;
|
||||
|
||||
/// Quiet test runs: per-test log files, subprocess capture and failure
|
||||
/// matrix (inert passthrough outside test binaries)
|
||||
pub(crate) mod test_support;
|
||||
|
||||
/// Utility functions
|
||||
pub(crate) mod utils;
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! The check trait and the static check registry.
|
||||
//!
|
||||
//! Checks are zero-sized structs, one module per packaging area, registered
|
||||
//! in one explicit array — reviewable, greppable, and free of proc macros.
|
||||
//! A registry test fails the build on duplicate tag names, undocumented
|
||||
//! tags or casing drift, so the catalog cannot rot silently.
|
||||
|
||||
use crate::lint::collect::LintData;
|
||||
use crate::lint::emit::Emitter;
|
||||
use crate::lint::tag::Tag;
|
||||
|
||||
/// A group of checks over one area of the packaging (control, changelog,
|
||||
/// git workflow, ...). One check instance may emit any of the tags it
|
||||
/// declares; the emitter resolves metadata and applies suppression.
|
||||
pub trait Check: Sync {
|
||||
/// Registry identifier, also the `--check` value (one word, e.g. `pkh-git`).
|
||||
fn id(&self) -> &'static str;
|
||||
|
||||
/// Static metadata of every tag this check may emit.
|
||||
fn tags(&self) -> &'static [Tag];
|
||||
|
||||
/// Run against the collected package information, reporting findings
|
||||
/// through `emit`.
|
||||
fn run(&self, data: &LintData, emit: &mut Emitter);
|
||||
}
|
||||
|
||||
/// Every registered check, in catalog order.
|
||||
pub static CHECKS: &[&dyn Check] = &[&super::checks::pkh::PkhGit as &dyn Check];
|
||||
|
||||
/// Look up a registered check by its id (`--check` value).
|
||||
pub fn find_check(id: &str) -> Option<&'static dyn Check> {
|
||||
CHECKS.iter().copied().find(|check| check.id() == id)
|
||||
}
|
||||
|
||||
/// Look up tag metadata by tag name across the whole registry.
|
||||
pub fn find_tag(name: &str) -> Option<&'static Tag> {
|
||||
CHECKS
|
||||
.iter()
|
||||
.flat_map(|check| check.tags())
|
||||
.find(|tag| tag.name == name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn registry_tag_names_are_unique_and_well_formed() {
|
||||
let mut seen = Vec::new();
|
||||
for tag in CHECKS.iter().flat_map(|check| check.tags()) {
|
||||
assert!(
|
||||
!seen.contains(&tag.name),
|
||||
"duplicate tag name: {}",
|
||||
tag.name
|
||||
);
|
||||
seen.push(tag.name);
|
||||
let valid = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || "+.-".contains(c);
|
||||
assert!(
|
||||
tag.name.starts_with(valid)
|
||||
&& tag.name.chars().all(valid)
|
||||
&& !tag.name.ends_with('-'),
|
||||
"tag name is not kebab-case: {}",
|
||||
tag.name
|
||||
);
|
||||
assert!(
|
||||
!tag.description.trim().is_empty(),
|
||||
"tag without a description: {}",
|
||||
tag.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_ids_are_unique_and_resolvable() {
|
||||
let mut seen = Vec::new();
|
||||
for check in CHECKS {
|
||||
assert!(
|
||||
!seen.contains(&check.id()),
|
||||
"duplicate check id: {}",
|
||||
check.id()
|
||||
);
|
||||
seen.push(check.id());
|
||||
assert!(
|
||||
find_check(check.id()).is_some(),
|
||||
"find_check cannot resolve its own registry: {}",
|
||||
check.id()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkh_native_tags_are_namespaced() {
|
||||
for check in CHECKS {
|
||||
if check.id().starts_with("pkh-") {
|
||||
for tag in check.tags() {
|
||||
assert!(
|
||||
tag.name.starts_with("pkh-"),
|
||||
"pkh-native check '{}' emits non-namespaced tag '{}'",
|
||||
check.id(),
|
||||
tag.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Check areas; one module per area, registered in [`crate::lint::check::CHECKS`].
|
||||
|
||||
/// Pkh-native workflow checks (git-centric trees, PPA uploads).
|
||||
pub mod pkh;
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Pkh-native checks: workflow knowledge lintian cannot have, because it
|
||||
//! lives in pkh's flows (git-centric trees, PPA uploads, scaffolding).
|
||||
|
||||
use crate::lint::check::Check;
|
||||
use crate::lint::collect::LintData;
|
||||
use crate::lint::emit::Emitter;
|
||||
use crate::lint::tag::{Certainty, Severity, Tag};
|
||||
|
||||
/// Metadata of every tag the pkh-native checks emit.
|
||||
pub static TAGS: &[Tag] = &[Tag {
|
||||
name: "pkh-debian-changes-not-committed",
|
||||
severity: Severity::Warning,
|
||||
certainty: Certainty::Certain,
|
||||
experimental: false,
|
||||
description: "The debian/ directory contains changes that are not committed to git. \
|
||||
pkh builds and uploads the tree as-is (pkh deb, pkh put); committing first keeps \
|
||||
the upload and the git history in sync.",
|
||||
references: &[],
|
||||
}];
|
||||
|
||||
/// Flags `debian/` content that exists in the tree but is not committed to
|
||||
/// git. Skips trees outside any git repository: archive-pulled sources
|
||||
/// legitimately have none.
|
||||
pub struct PkhGit;
|
||||
|
||||
impl Check for PkhGit {
|
||||
fn id(&self) -> &'static str {
|
||||
"pkh-git"
|
||||
}
|
||||
|
||||
fn tags(&self) -> &'static [Tag] {
|
||||
TAGS
|
||||
}
|
||||
|
||||
fn run(&self, data: &LintData, emit: &mut Emitter) {
|
||||
let Some(git) = &data.git else {
|
||||
return;
|
||||
};
|
||||
if git.dirty_debian.is_empty() {
|
||||
return;
|
||||
}
|
||||
let examples: Vec<&str> = git
|
||||
.dirty_debian
|
||||
.iter()
|
||||
.take(3)
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
let more = if git.dirty_debian.len() > examples.len() {
|
||||
", ..."
|
||||
} else {
|
||||
""
|
||||
};
|
||||
emit.tag(
|
||||
"pkh-debian-changes-not-committed",
|
||||
format!(
|
||||
"{} uncommitted change(s) under debian/ (e.g. {}{more})",
|
||||
git.dirty_debian.len(),
|
||||
examples.join(", ")
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
fn write(path: &Path, content: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, content).unwrap();
|
||||
}
|
||||
|
||||
fn commit_all(repo: &git2::Repository) {
|
||||
let signature = git2::Signature::now("pkh test", "test@example.com").unwrap();
|
||||
let mut index = repo.index().unwrap();
|
||||
index
|
||||
.add_all(["*"], git2::IndexAddOption::DEFAULT, None)
|
||||
.unwrap();
|
||||
// write_tree alone does not persist the index; without this, a
|
||||
// committed worktree still reads as index-deleted + untracked.
|
||||
index.write().unwrap();
|
||||
let tree_id = index.write_tree().unwrap();
|
||||
let tree = repo.find_tree(tree_id).unwrap();
|
||||
repo.commit(Some("HEAD"), &signature, &signature, "init", &tree, &[])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_git_repository_is_no_finding() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(&dir.path().join("debian/control"), "Source: hello\n");
|
||||
let data = LintData::collect(dir.path(), None, None);
|
||||
assert!(data.git.is_none());
|
||||
|
||||
let mut findings = Vec::new();
|
||||
let mut emitter = Emitter::new(data.source_name.clone(), &mut findings);
|
||||
PkhGit.run(&data, &mut emitter);
|
||||
assert!(findings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_worktree_is_no_finding() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(&dir.path().join("debian/control"), "Source: hello\n");
|
||||
let repo = git2::Repository::init(dir.path()).unwrap();
|
||||
commit_all(&repo);
|
||||
|
||||
let data = LintData::collect(dir.path(), None, None);
|
||||
let mut findings = Vec::new();
|
||||
let mut emitter = Emitter::new(data.source_name.clone(), &mut findings);
|
||||
PkhGit.run(&data, &mut emitter);
|
||||
assert!(findings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirty_debian_tree_is_a_finding() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(&dir.path().join("debian/control"), "Source: hello\n");
|
||||
write(&dir.path().join("hello.txt"), "upstream\n");
|
||||
let repo = git2::Repository::init(dir.path()).unwrap();
|
||||
commit_all(&repo);
|
||||
|
||||
// A modified tracked file and a fresh untracked patch: both count.
|
||||
write(
|
||||
&dir.path().join("debian/control"),
|
||||
"Source: hello\nDepends: x\n",
|
||||
);
|
||||
write(&dir.path().join("debian/patches/new.patch"), "...\n");
|
||||
write(&dir.path().join("hello.txt"), "changed upstream\n");
|
||||
|
||||
let data = LintData::collect(dir.path(), None, None);
|
||||
let mut findings = Vec::new();
|
||||
let mut emitter = Emitter::new(data.source_name.clone(), &mut findings);
|
||||
PkhGit.run(&data, &mut emitter);
|
||||
assert_eq!(findings.len(), 1);
|
||||
let finding = &findings[0];
|
||||
assert_eq!(finding.tag_name, "pkh-debian-changes-not-committed");
|
||||
assert_eq!(finding.letter, 'W');
|
||||
assert!(
|
||||
finding
|
||||
.message
|
||||
.starts_with("2 uncommitted change(s) under debian/")
|
||||
);
|
||||
assert!(finding.message.contains("debian/control"));
|
||||
assert!(finding.message.contains("debian/patches/new.patch"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Collectors: package information gathered once per run and shared by every
|
||||
//! check, mirroring lintian's collection phase without the on-disk lab.
|
||||
//! Source trees are small, so everything is computed eagerly except git
|
||||
//! status, which only exists when the tree is a git worktree.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::debian::control::ControlInfo;
|
||||
|
||||
/// Git worktree state relevant to pkh's git-centric workflow checks.
|
||||
pub struct GitStatus {
|
||||
/// Repo-relative paths under `debian/` with uncommitted content
|
||||
/// (modified, staged or untracked), sorted.
|
||||
pub dirty_debian: Vec<String>,
|
||||
}
|
||||
|
||||
/// Everything the checks and the report renderer know about the linted tree.
|
||||
pub struct LintData {
|
||||
/// Root of the source tree being linted.
|
||||
pub root: PathBuf,
|
||||
/// Source package name, resolved from `debian/control`, else from the
|
||||
/// changelog's first line, else the directory name.
|
||||
pub source_name: String,
|
||||
/// Target distribution (`--dist`); unresolved when None.
|
||||
pub dist: Option<String>,
|
||||
/// Target series (`--series`); unresolved when None.
|
||||
pub series: Option<String>,
|
||||
/// Git worktree state; None when the tree is not inside a git repository.
|
||||
pub git: Option<GitStatus>,
|
||||
}
|
||||
|
||||
impl LintData {
|
||||
/// Collect information about the source tree at `root`.
|
||||
pub fn collect(root: &Path, dist: Option<&str>, series: Option<&str>) -> LintData {
|
||||
LintData {
|
||||
root: root.to_path_buf(),
|
||||
source_name: resolve_source_name(root),
|
||||
dist: dist.map(str::to_string),
|
||||
series: series.map(str::to_string),
|
||||
git: collect_git(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Source package name from `debian/control`, falling back to the changelog
|
||||
/// header and then the directory name; the report needs a display name even
|
||||
/// for broken trees.
|
||||
fn resolve_source_name(root: &Path) -> String {
|
||||
if let Ok(control) = ControlInfo::parse(&root.join("debian/control")) {
|
||||
return control.source_name().to_string();
|
||||
}
|
||||
if let Ok(changelog) = std::fs::read_to_string(root.join("debian/changelog"))
|
||||
&& let Some(first) = changelog.lines().next()
|
||||
&& let Some(name) = first.split(" (").next()
|
||||
&& !name.trim().is_empty()
|
||||
{
|
||||
return name.trim().to_string();
|
||||
}
|
||||
root.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "package".to_string())
|
||||
}
|
||||
|
||||
/// Dirty paths under `debian/` when the tree lives in a git worktree.
|
||||
/// Untracked files count: a fresh patch nobody committed is exactly the
|
||||
/// mistake the workflow checks exist to catch. None when there is no
|
||||
/// repository (or git is somehow unusable here) — never a finding, since
|
||||
/// archive-pulled trees legitimately have none.
|
||||
fn collect_git(root: &Path) -> Option<GitStatus> {
|
||||
let repo = git2::Repository::discover(root).ok()?;
|
||||
let workdir = repo.workdir()?;
|
||||
// Statuses are workdir-relative; trees nested inside a repository only
|
||||
// care about their own slice of it.
|
||||
let prefix = root.strip_prefix(workdir).unwrap_or(Path::new(""));
|
||||
let debian_dir = prefix.join("debian");
|
||||
|
||||
let mut options = git2::StatusOptions::new();
|
||||
options
|
||||
.include_untracked(true)
|
||||
.include_ignored(false)
|
||||
.recurse_untracked_dirs(true);
|
||||
let statuses = repo.statuses(Some(&mut options)).ok()?;
|
||||
|
||||
let mut dirty_debian = Vec::new();
|
||||
for entry in statuses.iter() {
|
||||
// CURRENT is the zero flag in libgit2, so any non-empty status is
|
||||
// some kind of change (worktree or staged).
|
||||
if entry.status().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path()?;
|
||||
if Path::new(path).starts_with(&debian_dir) {
|
||||
dirty_debian.push(path.to_string());
|
||||
}
|
||||
}
|
||||
dirty_debian.sort();
|
||||
Some(GitStatus { dirty_debian })
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Findings, the run report, and the emitter checks report through.
|
||||
//!
|
||||
//! The emitter is deliberately thin: checks name a tag and give a message;
|
||||
//! metadata, output letter and explanations come from the registry, so
|
||||
//! findings from the native engine and findings parsed from the wrapped
|
||||
//! lintian share one shape and one rendering path.
|
||||
|
||||
use crate::lint::check;
|
||||
use crate::lint::tag::Tag;
|
||||
|
||||
/// Where a finding comes from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Origin {
|
||||
/// Emitted by pkh's native Rust checks.
|
||||
Native,
|
||||
/// Parsed from the wrapped lintian's output.
|
||||
Lintian,
|
||||
}
|
||||
|
||||
/// One lint finding, whatever produced it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Finding {
|
||||
/// Output letter (`E`, `W`, `I`, `P`, `X`, `O`, `C`): severity for
|
||||
/// native findings, verbatim from the output line in wrapper mode.
|
||||
pub letter: char,
|
||||
/// Stable tag name (`missing-debian-copyright-file`).
|
||||
pub tag_name: String,
|
||||
/// Free-form details after the tag name; empty when the tag stands alone.
|
||||
pub message: String,
|
||||
/// Package the finding belongs to (`hello`).
|
||||
pub package: String,
|
||||
/// Processable type lintian displays after the package name (`source`,
|
||||
/// `changes`, ...); None for binary findings, which lintian prints
|
||||
/// without a type.
|
||||
pub processable_type: Option<String>,
|
||||
/// Explanation lines shown by `--info`: the `N:` blocks lintian attaches
|
||||
/// to the finding in wrapper mode, or the native tag's description and
|
||||
/// references.
|
||||
pub explanation: Vec<String>,
|
||||
/// Native or parsed-from-lintian.
|
||||
pub origin: Origin,
|
||||
}
|
||||
|
||||
impl Finding {
|
||||
/// Lowercase severity/classification name for this finding's letter, as
|
||||
/// used in `--fail-on` values and JSON output.
|
||||
pub fn severity_name(&self) -> &'static str {
|
||||
match self.letter {
|
||||
'E' => "error",
|
||||
'W' => "warning",
|
||||
'I' => "info",
|
||||
'P' => "pedantic",
|
||||
'X' => "experimental",
|
||||
'O' => "overridden",
|
||||
_ => "classification",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The full result of one lint run: every finding, from every source.
|
||||
pub struct LintReport {
|
||||
/// All findings in emission order: the wrapper's first, then the native
|
||||
/// ones (deduplicated by tag name against the wrapper's).
|
||||
pub findings: Vec<Finding>,
|
||||
/// Display name of the linted source package.
|
||||
pub source_name: String,
|
||||
/// The wrapper was skipped because lintian is not installed; the
|
||||
/// renderer prints a notice and the run is native-only.
|
||||
pub wrapper_unavailable: bool,
|
||||
/// Run-level notes (`N:` lines): how the linted artifact was obtained,
|
||||
/// and similar context that is not a finding.
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Sink checks report findings through. Resolves tag metadata from the
|
||||
/// registry so checks only ever name the tag they mean.
|
||||
pub struct Emitter<'a> {
|
||||
package: String,
|
||||
findings: &'a mut Vec<Finding>,
|
||||
}
|
||||
|
||||
impl<'a> Emitter<'a> {
|
||||
/// Emitter for findings of `package` (e.g. the source package name),
|
||||
/// appending into `findings`.
|
||||
pub fn new(package: String, findings: &'a mut Vec<Finding>) -> Emitter<'a> {
|
||||
Emitter { package, findings }
|
||||
}
|
||||
|
||||
/// Emit `tag_name` with `message` as its detail line. Native findings
|
||||
/// always report on the source package; an unknown tag name (a registry
|
||||
/// bug) still produces a finding rather than panicking — the registry
|
||||
/// test makes that path unreachable in practice.
|
||||
pub fn tag(&mut self, tag_name: &str, message: impl Into<String>) {
|
||||
let (letter, explanation) = match check::find_tag(tag_name) {
|
||||
Some(tag) => (tag.letter(), explanation_of(tag)),
|
||||
None => ('E', Vec::new()),
|
||||
};
|
||||
self.findings.push(Finding {
|
||||
letter,
|
||||
tag_name: tag_name.to_string(),
|
||||
message: message.into(),
|
||||
package: self.package.clone(),
|
||||
processable_type: Some("source".to_string()),
|
||||
explanation,
|
||||
origin: Origin::Native,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The explanation `--info` shows for a native tag: its description plus any
|
||||
/// references, prefixed like lintian's "Please refer to" pointers.
|
||||
fn explanation_of(tag: &Tag) -> Vec<String> {
|
||||
let mut lines = vec![tag.description.to_string()];
|
||||
for reference in tag.references {
|
||||
lines.push(format!("Please refer to {}", reference));
|
||||
}
|
||||
lines
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
//! `pkh lint`: lint a Debian source tree, with lintian feature parity.
|
||||
//!
|
||||
//! The strategy is *wrap first, port second* (see `plans/pkh-lint.md`): the
|
||||
//! [wrapper](wrapper) runs the installed lintian over an ephemeral source
|
||||
//! package for day-one parity with every lintian check, while the native
|
||||
//! engine (check registry, collectors, emitter) hosts pkh-specific workflow
|
||||
//! checks (`pkh-*` tags) and grows ported lintian checks incrementally.
|
||||
//! Both findings merge into one report — deduplicated by tag name, which is
|
||||
//! why native checks mirror lintian's tag names for equivalent checks —
|
||||
//! rendered as lintian-shaped text or JSON, with lintian's exit-code
|
||||
//! contract (0 clean, 1 findings at/above `--fail-on`, 2 runtime error).
|
||||
|
||||
pub mod check;
|
||||
pub mod checks;
|
||||
pub mod collect;
|
||||
pub mod emit;
|
||||
pub mod output;
|
||||
pub mod tag;
|
||||
pub mod wrapper;
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::lint::check::Check;
|
||||
use crate::lint::collect::LintData;
|
||||
use crate::lint::emit::{Finding, LintReport};
|
||||
|
||||
/// Knobs of one `pkh lint` run, built from the CLI in `main.rs`.
|
||||
pub struct LintOptions {
|
||||
/// Source tree to lint.
|
||||
pub path: PathBuf,
|
||||
/// Run the native engine only; never invoke the lintian wrapper.
|
||||
pub native: bool,
|
||||
/// Levels that make the exit code 1 (`--fail-on`, default: error).
|
||||
pub fail_on: Vec<output::Level>,
|
||||
/// Show tag explanations under each finding (`--info`, lintian's `-i`).
|
||||
pub info: bool,
|
||||
/// Also display info-level (`I:`) findings (lintian's `-I`).
|
||||
pub display_info: bool,
|
||||
/// Also display pedantic (`P:`) findings.
|
||||
pub pedantic: bool,
|
||||
/// Also display experimental (`X:`) findings.
|
||||
pub experimental: bool,
|
||||
/// Also display overridden (`O:`) findings.
|
||||
pub show_overrides: bool,
|
||||
/// Tag names to ignore for this run.
|
||||
pub suppress_tags: Vec<String>,
|
||||
/// Run only these native checks (`--check`, repeatable).
|
||||
pub only_checks: Vec<String>,
|
||||
/// Ignore any existing `pkh build` output and pack the tree fresh.
|
||||
pub repack: bool,
|
||||
/// Emit JSON instead of text.
|
||||
pub json: bool,
|
||||
/// Text colorization mode (`--color`, default auto: TTY without NO_COLOR).
|
||||
pub color: output::ColorMode,
|
||||
/// Target distribution (debian/ubuntu), when known.
|
||||
pub dist: Option<String>,
|
||||
/// Target series, when known.
|
||||
pub series: Option<String>,
|
||||
}
|
||||
|
||||
/// Run one lint: collect package information, run the native checks, wrap
|
||||
/// lintian (unless `--native`), and merge everything into one report.
|
||||
pub fn run(options: &LintOptions) -> Result<LintReport, String> {
|
||||
let data = LintData::collect(
|
||||
&options.path,
|
||||
options.dist.as_deref(),
|
||||
options.series.as_deref(),
|
||||
);
|
||||
let mut report = LintReport {
|
||||
findings: Vec::new(),
|
||||
source_name: data.source_name.clone(),
|
||||
wrapper_unavailable: false,
|
||||
notes: Vec::new(),
|
||||
};
|
||||
|
||||
if !options.native {
|
||||
match wrapper::run(&data.root, options)? {
|
||||
Some(outcome) => {
|
||||
report.findings.extend(outcome.findings);
|
||||
report.notes = outcome.notes;
|
||||
}
|
||||
None => report.wrapper_unavailable = true,
|
||||
}
|
||||
}
|
||||
|
||||
let selected: Vec<&'static dyn Check> = if options.only_checks.is_empty() {
|
||||
check::CHECKS.to_vec()
|
||||
} else {
|
||||
options
|
||||
.only_checks
|
||||
.iter()
|
||||
.map(|id| check::find_check(id).ok_or_else(|| format!("Unknown --check '{id}'")))
|
||||
.collect::<Result<_, _>>()?
|
||||
};
|
||||
|
||||
let mut native = Vec::new();
|
||||
{
|
||||
let mut emitter = emit::Emitter::new(report.source_name.clone(), &mut native);
|
||||
for check in selected {
|
||||
check.run(&data, &mut emitter);
|
||||
}
|
||||
}
|
||||
report.findings.extend(merge(&report.findings, native));
|
||||
|
||||
if !options.suppress_tags.is_empty() {
|
||||
report
|
||||
.findings
|
||||
.retain(|finding| !options.suppress_tags.contains(&finding.tag_name));
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Append `native` findings to `lintian`'s, dropping native duplicates by
|
||||
/// tag name (the wrapper's verdict wins for tags both engines produce).
|
||||
fn merge(lintian: &[Finding], native: Vec<Finding>) -> Vec<Finding> {
|
||||
let known: HashSet<&str> = lintian.iter().map(|f| f.tag_name.as_str()).collect();
|
||||
native
|
||||
.into_iter()
|
||||
.filter(|finding| !known.contains(finding.tag_name.as_str()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `--list-tags` catalog: one line per registered native tag.
|
||||
pub fn list_tags() -> String {
|
||||
let mut out = String::new();
|
||||
for check in check::CHECKS {
|
||||
for tag in check.tags() {
|
||||
out.push_str(&format!(
|
||||
"{} [{}] {}\n {}\n",
|
||||
tag.letter(),
|
||||
check.id(),
|
||||
tag.name,
|
||||
tag.description
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lint::emit::Origin;
|
||||
|
||||
fn finding(tag: &str, origin: Origin) -> Finding {
|
||||
Finding {
|
||||
letter: 'W',
|
||||
tag_name: tag.to_string(),
|
||||
message: String::new(),
|
||||
package: "hello".to_string(),
|
||||
processable_type: Some("source".to_string()),
|
||||
explanation: Vec::new(),
|
||||
origin,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_drops_native_duplicates_by_tag_name() {
|
||||
let lintian = vec![finding("no-debian-copyright-in-source", Origin::Lintian)];
|
||||
let native = vec![
|
||||
finding("no-debian-copyright-in-source", Origin::Native),
|
||||
finding("pkh-debian-changes-not-committed", Origin::Native),
|
||||
];
|
||||
let merged = merge(&lintian, native);
|
||||
assert_eq!(merged.len(), 1);
|
||||
assert_eq!(merged[0].tag_name, "pkh-debian-changes-not-committed");
|
||||
assert_eq!(merged[0].origin, Origin::Native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_tags_resolve_from_the_registry() {
|
||||
let tag = check::find_tag("pkh-debian-changes-not-committed")
|
||||
.expect("pkh check tags must resolve");
|
||||
assert_eq!(tag.letter(), 'W');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_native_tags_still_produce_findings() {
|
||||
let mut sink = Vec::new();
|
||||
let mut emitter = emit::Emitter::new("hello".to_string(), &mut sink);
|
||||
emitter.tag("no-such-tag-anywhere", "boom");
|
||||
assert_eq!(sink.len(), 1);
|
||||
assert_eq!(sink[0].tag_name, "no-such-tag-anywhere");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Rendering of a lint report (text and JSON) and the exit-code decision.
|
||||
//!
|
||||
//! Text output keeps lintian's line shape (`<L>: <pkg> <type>: <tag>
|
||||
//! <details>`) so findings read identically in both modes; JSON is the
|
||||
//! schema-stable form for CI. Display filtering (what is shown) and the
|
||||
//! `--fail-on` threshold (what makes the exit code 1) are independent, like
|
||||
//! lintian's. Colorization happens here, at render time — findings are
|
||||
//! captured plain (`--color never` is passed to lintian) and re-painted by
|
||||
//! severity, so colors are a renderer concern that survives the switch from
|
||||
//! wrapped lintian output to native checks.
|
||||
|
||||
use crossterm::style::Stylize;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::lint::LintOptions;
|
||||
use crate::lint::emit::{Finding, LintReport, Origin};
|
||||
|
||||
/// When to colorize the text report.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum ColorMode {
|
||||
/// Colorize when stdout is a terminal and `NO_COLOR` is unset.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Always colorize (piping, CI logs).
|
||||
Always,
|
||||
/// Never colorize.
|
||||
Never,
|
||||
}
|
||||
|
||||
impl ColorMode {
|
||||
/// Parse one `--color` keyword.
|
||||
pub fn parse(word: &str) -> Option<ColorMode> {
|
||||
match word {
|
||||
"auto" => Some(ColorMode::Auto),
|
||||
"always" => Some(ColorMode::Always),
|
||||
"never" => Some(ColorMode::Never),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the text renderer should emit ANSI colors.
|
||||
fn should_color(self) -> bool {
|
||||
match self {
|
||||
ColorMode::Always => true,
|
||||
ColorMode::Never => false,
|
||||
ColorMode::Auto => {
|
||||
std::io::IsTerminal::is_terminal(&std::io::stdout())
|
||||
&& std::env::var_os("NO_COLOR").is_none()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The output letter, painted with its severity color when `color` is set:
|
||||
/// errors red (bold), warnings yellow, info cyan, pedantic/experimental
|
||||
/// magenta, overridden green. Mirrors lintian's tty palette closely enough
|
||||
/// for muscle memory.
|
||||
fn paint_letter(letter: char, color: bool) -> String {
|
||||
if !color {
|
||||
return letter.to_string();
|
||||
}
|
||||
match letter {
|
||||
'E' => "E".red().bold().to_string(),
|
||||
'W' => "W".yellow().to_string(),
|
||||
'I' => "I".cyan().to_string(),
|
||||
'P' => "P".magenta().to_string(),
|
||||
'X' => "X".magenta().to_string(),
|
||||
'O' => "O".green().to_string(),
|
||||
_ => letter.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A named severity class, mirroring the values lintian's `--fail-on`
|
||||
/// accepts. `Experimental` is the `X:` pseudo-level (the letter hides the
|
||||
/// underlying severity) and `Overridden` lets gates count suppressed tags.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Level {
|
||||
/// `E:` findings.
|
||||
Error,
|
||||
/// `W:` findings.
|
||||
Warning,
|
||||
/// `I:` findings.
|
||||
Info,
|
||||
/// `P:` findings.
|
||||
Pedantic,
|
||||
/// `X:` findings.
|
||||
Experimental,
|
||||
/// `O:` findings (only reported when overrides are shown).
|
||||
Overridden,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
/// The output letter the level stands for.
|
||||
pub fn letter(self) -> char {
|
||||
match self {
|
||||
Level::Error => 'E',
|
||||
Level::Warning => 'W',
|
||||
Level::Info => 'I',
|
||||
Level::Pedantic => 'P',
|
||||
Level::Experimental => 'X',
|
||||
Level::Overridden => 'O',
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse one comma-separated `--fail-on` keyword.
|
||||
pub fn parse(word: &str) -> Option<Level> {
|
||||
match word.trim() {
|
||||
"error" => Some(Level::Error),
|
||||
"warning" => Some(Level::Warning),
|
||||
"info" => Some(Level::Info),
|
||||
"pedantic" => Some(Level::Pedantic),
|
||||
"experimental" => Some(Level::Experimental),
|
||||
"override" => Some(Level::Overridden),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the whole `--fail-on` value (comma-separated level names).
|
||||
pub fn parse_fail_on(spec: &str) -> Result<Vec<Level>, String> {
|
||||
let levels: Vec<Level> = spec
|
||||
.split(',')
|
||||
.filter(|word| !word.trim().is_empty())
|
||||
.map(Level::parse)
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"Invalid --fail-on value '{spec}': expected comma-separated \
|
||||
error, warning, info, pedantic, experimental or override"
|
||||
)
|
||||
})?;
|
||||
if levels.is_empty() {
|
||||
return Err("Empty --fail-on value: expected at least one level".to_string());
|
||||
}
|
||||
Ok(levels)
|
||||
}
|
||||
|
||||
/// The letter a finding displays as for display-level purposes: overridden
|
||||
/// findings carry their `O:` letter, classification tags are JSON-only.
|
||||
fn is_displayed(finding: &Finding, options: &LintOptions) -> bool {
|
||||
match finding.letter {
|
||||
'E' | 'W' => true,
|
||||
'I' => options.display_info,
|
||||
'P' => options.pedantic,
|
||||
'X' => options.experimental,
|
||||
'O' => options.show_overrides,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exit code of the run: 1 when any finding (except classification tags) is
|
||||
/// at a level listed in `--fail-on`, 0 otherwise. Runtime failures never
|
||||
/// reach this function — the caller exits 2 directly.
|
||||
pub fn exit_code(report: &LintReport, options: &LintOptions) -> i32 {
|
||||
let failed = report
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| match level_of_letter(finding.letter) {
|
||||
Some(level) => options.fail_on.contains(&level),
|
||||
None => false,
|
||||
});
|
||||
if failed { 1 } else { 0 }
|
||||
}
|
||||
|
||||
/// The level a finding's letter maps to for `--fail-on` purposes; None for
|
||||
/// classification tags, which lintian also never fails on.
|
||||
fn level_of_letter(letter: char) -> Option<Level> {
|
||||
match letter {
|
||||
'E' => Some(Level::Error),
|
||||
'W' => Some(Level::Warning),
|
||||
'I' => Some(Level::Info),
|
||||
'P' => Some(Level::Pedantic),
|
||||
'X' => Some(Level::Experimental),
|
||||
'O' => Some(Level::Overridden),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the report as lintian-shaped text: one `<L>: <pkg> <type>: <tag>
|
||||
/// <details>` line per displayed finding, explanations under `--info`, then
|
||||
/// an `N:` summary line.
|
||||
pub fn render_text(report: &LintReport, options: &LintOptions) -> String {
|
||||
let color = options.color.should_color();
|
||||
let mut out = String::new();
|
||||
if report.wrapper_unavailable {
|
||||
out.push_str(
|
||||
"N: lintian is not installed; showing pkh-native checks only \
|
||||
(install lintian for full check coverage)\n",
|
||||
);
|
||||
}
|
||||
for note in &report.notes {
|
||||
out.push_str(&format!("N: {note}\n"));
|
||||
}
|
||||
|
||||
let mut shown_counts = [('E', 0), ('W', 0), ('I', 0), ('P', 0), ('X', 0), ('O', 0)];
|
||||
let mut shown = 0;
|
||||
for finding in &report.findings {
|
||||
if !is_displayed(finding, options) {
|
||||
continue;
|
||||
}
|
||||
shown += 1;
|
||||
if let Some((_, count)) = shown_counts
|
||||
.iter_mut()
|
||||
.find(|(letter, _)| *letter == finding.letter)
|
||||
{
|
||||
*count += 1;
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"{}: {}\n",
|
||||
paint_letter(finding.letter, color),
|
||||
line_subject(finding)
|
||||
));
|
||||
if options.info {
|
||||
for line in &finding.explanation {
|
||||
if line.is_empty() {
|
||||
out.push_str("N:\n");
|
||||
} else {
|
||||
out.push_str(&format!("N: {}\n", line.trim_end()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut parts = Vec::new();
|
||||
for (letter, count) in shown_counts {
|
||||
if count > 0 {
|
||||
parts.push(format!("{} {}", count, paint_letter(letter, color)));
|
||||
}
|
||||
}
|
||||
let hidden = report.findings.len() - shown;
|
||||
if parts.is_empty() {
|
||||
out.push_str(&format!("N: no displayed tags; {hidden} hidden\n"));
|
||||
} else {
|
||||
out.push_str(&format!(
|
||||
"N: {shown} tag(s) shown ({}); {hidden} hidden\n",
|
||||
parts.join(", ")
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `hello source: tag details` — the part of a lintian line after the
|
||||
/// letter, reproduced identically for both origins.
|
||||
fn line_subject(finding: &Finding) -> String {
|
||||
let mut line = String::from(&finding.package);
|
||||
if let Some(ptype) = &finding.processable_type {
|
||||
line.push(' ');
|
||||
line.push_str(ptype);
|
||||
}
|
||||
line.push_str(": ");
|
||||
line.push_str(&finding.tag_name);
|
||||
if !finding.message.is_empty() {
|
||||
line.push(' ');
|
||||
line.push_str(&finding.message);
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// Render the report as pretty-printed JSON: every finding (displayed or
|
||||
/// not, flagged as such) plus a summary carrying the exit-code verdict.
|
||||
pub fn render_json(report: &LintReport, options: &LintOptions) -> String {
|
||||
let findings: Vec<serde_json::Value> = report
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| {
|
||||
json!({
|
||||
"letter": finding.letter.to_string(),
|
||||
"tag": finding.tag_name,
|
||||
"severity": finding.severity_name(),
|
||||
"package": finding.package,
|
||||
"processable_type": finding.processable_type,
|
||||
"message": finding.message,
|
||||
"origin": match finding.origin {
|
||||
Origin::Native => "native",
|
||||
Origin::Lintian => "lintian",
|
||||
},
|
||||
"overridden": finding.letter == 'O',
|
||||
"displayed": is_displayed(finding, options),
|
||||
"explanation": if finding.explanation.is_empty() {
|
||||
json!(null)
|
||||
} else {
|
||||
json!(finding.explanation)
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let document = json!({
|
||||
"source": report.source_name,
|
||||
"wrapper_unavailable": report.wrapper_unavailable,
|
||||
"notes": report.notes,
|
||||
"findings": findings,
|
||||
"summary": {
|
||||
"failed": exit_code(report, options) == 1,
|
||||
},
|
||||
});
|
||||
serde_json::to_string_pretty(&document).expect("lint report JSON is serializable")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn options(fail_on: &[Level]) -> LintOptions {
|
||||
LintOptions {
|
||||
path: std::path::PathBuf::from("."),
|
||||
native: false,
|
||||
fail_on: fail_on.to_vec(),
|
||||
info: false,
|
||||
display_info: false,
|
||||
pedantic: false,
|
||||
experimental: false,
|
||||
show_overrides: false,
|
||||
suppress_tags: Vec::new(),
|
||||
only_checks: Vec::new(),
|
||||
repack: false,
|
||||
json: false,
|
||||
color: ColorMode::Never,
|
||||
dist: None,
|
||||
series: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn report(findings: &[(&str, char)]) -> LintReport {
|
||||
LintReport {
|
||||
findings: findings
|
||||
.iter()
|
||||
.map(|(tag, letter)| Finding {
|
||||
letter: *letter,
|
||||
tag_name: (*tag).to_string(),
|
||||
message: String::new(),
|
||||
package: "hello".to_string(),
|
||||
processable_type: Some("source".to_string()),
|
||||
explanation: Vec::new(),
|
||||
origin: Origin::Lintian,
|
||||
})
|
||||
.collect(),
|
||||
source_name: "hello".to_string(),
|
||||
wrapper_unavailable: false,
|
||||
notes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fail_on_parses_and_rejects_unknown_levels() {
|
||||
assert_eq!(
|
||||
parse_fail_on("error, warning").unwrap(),
|
||||
vec![Level::Error, Level::Warning]
|
||||
);
|
||||
assert!(parse_fail_on("bogus").is_err());
|
||||
assert!(parse_fail_on(" ").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_code_only_counts_displayed_severity_letters() {
|
||||
let default_opts = options(&[Level::Error]);
|
||||
// Errors fail, warnings alone do not (the default threshold).
|
||||
assert_eq!(exit_code(&report(&[("t", 'E')]), &default_opts), 1);
|
||||
assert_eq!(
|
||||
exit_code(&report(&[("t", 'W'), ("u", 'I')]), &default_opts),
|
||||
0
|
||||
);
|
||||
// Overridden findings never fail unless explicitly requested.
|
||||
assert_eq!(exit_code(&report(&[("t", 'O')]), &default_opts), 0);
|
||||
assert_eq!(
|
||||
exit_code(
|
||||
&report(&[("t", 'O')]),
|
||||
&options(&[Level::Error, Level::Overridden])
|
||||
),
|
||||
1
|
||||
);
|
||||
// Classification tags never fail.
|
||||
assert_eq!(exit_code(&report(&[("t", 'C')]), &default_opts), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rendering_respects_display_levels() {
|
||||
let base = report(&[("e", 'E'), ("i", 'I'), ("o", 'O'), ("x", 'X')]);
|
||||
let default = render_text(&base, &options(&[Level::Error]));
|
||||
assert!(default.contains("E: hello source: e"));
|
||||
assert!(!default.contains("I: "));
|
||||
assert!(!default.contains("O: "));
|
||||
assert!(!default.contains("X: "));
|
||||
assert!(default.ends_with("N: 1 tag(s) shown (1 E); 3 hidden\n"));
|
||||
|
||||
let everything = LintOptions {
|
||||
display_info: true,
|
||||
experimental: true,
|
||||
show_overrides: true,
|
||||
..options(&[Level::Error])
|
||||
};
|
||||
let full = render_text(&base, &everything);
|
||||
for prefix in ["E:", "I:", "O:", "X:"] {
|
||||
assert!(
|
||||
full.contains(&format!("{prefix} hello source:")),
|
||||
"{prefix}"
|
||||
);
|
||||
}
|
||||
assert!(full.ends_with("N: 4 tag(s) shown (1 E, 1 I, 1 X, 1 O); 0 hidden\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colorization_is_render_only_and_mode_switchable() {
|
||||
let run_report = report(&[("e", 'E'), ("w", 'W'), ("o", 'O')]);
|
||||
|
||||
let plain = options(&[Level::Error]);
|
||||
let mut forced = options(&[Level::Error]);
|
||||
forced.color = ColorMode::Always;
|
||||
|
||||
let plain = render_text(&run_report, &plain);
|
||||
let colored = render_text(&run_report, &forced);
|
||||
assert!(
|
||||
!plain.contains('\u{1b}'),
|
||||
"never/auto-on-pipe must stay plain"
|
||||
);
|
||||
assert!(colored.contains('\u{1b}'), "always must colorize");
|
||||
// Colors wrap the letters only; the lintian line shape is intact.
|
||||
assert!(colored.contains("hello source: e"));
|
||||
// Mode parsing round-trips.
|
||||
assert_eq!(ColorMode::parse("always"), Some(ColorMode::Always));
|
||||
assert_eq!(ColorMode::parse("bogus"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trips_with_verdicts() {
|
||||
let run_report = report(&[("e", 'E'), ("w", 'W')]);
|
||||
let default_opts = options(&[Level::Error]);
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_str(&render_json(&run_report, &default_opts)).unwrap();
|
||||
assert_eq!(document["source"], "hello");
|
||||
assert_eq!(document["findings"][0]["letter"], "E");
|
||||
assert_eq!(document["findings"][0]["severity"], "error");
|
||||
assert_eq!(document["findings"][0]["origin"], "lintian");
|
||||
assert_eq!(document["summary"]["failed"], true);
|
||||
|
||||
// An error finding fails at the warning threshold too, but not at
|
||||
// pedantic-only, which nothing in this report reaches.
|
||||
let warn_only = options(&[Level::Warning]);
|
||||
assert_eq!(exit_code(&run_report, &warn_only), 1);
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_str(&render_json(&run_report, &warn_only)).unwrap();
|
||||
assert_eq!(document["summary"]["failed"], true);
|
||||
|
||||
let pedantic_only = options(&[Level::Pedantic]);
|
||||
assert_eq!(exit_code(&run_report, &pedantic_only), 0);
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_str(&render_json(&run_report, &pedantic_only)).unwrap();
|
||||
assert_eq!(document["summary"]["failed"], false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Lint tag model: severities, certainties and static tag metadata.
|
||||
//!
|
||||
//! Tags are the atomic diagnostics of a lint run, named after lintian's
|
||||
//! model: a stable machine-readable name (`missing-debian-copyright-file`),
|
||||
//! a severity, a certainty and a description. Checks declare the tags they
|
||||
//! may emit as static [`Tag`] values; the wrapper's parsed findings carry the
|
||||
//! letter lintian printed instead.
|
||||
|
||||
/// Severity of a finding, matching lintian's severity ladder.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Severity {
|
||||
/// Policy violation or broken package data (`E:`).
|
||||
Error,
|
||||
/// Probable bug or policy deviation (`W:`).
|
||||
Warning,
|
||||
/// Informational note about packaging choices (`I:`).
|
||||
Info,
|
||||
/// Nitpick most packages may legitimately ignore (`P:`).
|
||||
Pedantic,
|
||||
}
|
||||
|
||||
impl Severity {
|
||||
/// The output letter lintian displays this severity as (`E`, `W`, ...).
|
||||
pub fn letter(self) -> char {
|
||||
match self {
|
||||
Severity::Error => 'E',
|
||||
Severity::Warning => 'W',
|
||||
Severity::Info => 'I',
|
||||
Severity::Pedantic => 'P',
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowercase name used in `--fail-on` values and JSON output.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Severity::Error => "error",
|
||||
Severity::Warning => "warning",
|
||||
Severity::Info => "info",
|
||||
Severity::Pedantic => "pedantic",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How sure a check is that a finding is real. Not acted upon yet (a future
|
||||
/// `--fail-on error,certain` would consume it), but captured from day one so
|
||||
/// severity tuning is data-driven later.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Certainty {
|
||||
/// The finding is a fact (e.g. a missing file).
|
||||
Certain,
|
||||
/// The finding is likely but has legitimate exceptions.
|
||||
Possible,
|
||||
/// The finding is a guess from weak signals.
|
||||
WildGuess,
|
||||
}
|
||||
|
||||
/// Static metadata of one tag: what checks declare and the renderer resolves.
|
||||
#[derive(Debug)]
|
||||
pub struct Tag {
|
||||
/// Stable machine-readable name, lintian-compatible kebab-case
|
||||
/// (`pkh-debian-changes-not-committed`).
|
||||
pub name: &'static str,
|
||||
/// Severity the tag reports at.
|
||||
pub severity: Severity,
|
||||
/// How sure checks are when emitting this tag.
|
||||
pub certainty: Certainty,
|
||||
/// Whether the tag is experimental (`X:` output, hidden by default).
|
||||
pub experimental: bool,
|
||||
/// One-paragraph explanation, shown by `--info` and `--list-tags`.
|
||||
pub description: &'static str,
|
||||
/// References (policy sections, URLs) shown by `--info`.
|
||||
pub references: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
/// The output letter for this tag: experimental tags render as `X:`
|
||||
/// regardless of their severity, like lintian.
|
||||
pub fn letter(&self) -> char {
|
||||
if self.experimental {
|
||||
'X'
|
||||
} else {
|
||||
self.severity.letter()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
//! The lintian wrapper: pkh's day-one feature-parity layer.
|
||||
//!
|
||||
//! Lintian only accepts built package files, never source trees, so the
|
||||
//! wrapper needs a source artifact. It lints the `pkh build` output next to
|
||||
//! the tree when it matches the current changelog entry and nothing in the
|
||||
//! tree is newer than it (the fast path: no packing at all); otherwise it
|
||||
//! packs the tree fresh with `dpkg-source -b` inside a temporary directory
|
||||
//! and lints the resulting `.dsc` (`--repack` forces that path). Nothing is
|
||||
//! written back into the linted tree; the temp directory is removed on drop.
|
||||
//!
|
||||
//! Parsing is load-bearing here (findings are merged with the native ones,
|
||||
//! rendered uniformly and exported as JSON), so the parser is pinned by
|
||||
//! golden tests captured from real lintian output. Lintian's own exit code
|
||||
//! is *not* authoritative: lintian uses 2 both for "fail-on met" and for
|
||||
//! runtime errors, while pkh derives the verdict from the parsed findings
|
||||
//! and reserves 2 for actual runtime failures.
|
||||
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use crate::lint::LintOptions;
|
||||
use crate::lint::emit::{Finding, Origin};
|
||||
|
||||
/// What one wrapper run produced: the parsed lintian findings plus `N:`
|
||||
/// notes about how the artifact being linted was obtained.
|
||||
pub struct WrapperOutcome {
|
||||
/// Lintian's findings.
|
||||
pub findings: Vec<Finding>,
|
||||
/// Human-visible notes (artifact reuse, fresh packing) rendered as `N:`.
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Run the wrapper over the source tree at `root`:
|
||||
/// - `Ok(Some(outcome))` — lintian ran; these are its findings and notes,
|
||||
/// - `Ok(None)` — lintian is not installed; the caller falls back to
|
||||
/// native-only with a notice,
|
||||
/// - `Err(message)` — runtime failure (tree unpacked badly, lintian crashed
|
||||
/// without reportable output); the caller exits 2.
|
||||
///
|
||||
/// The artifact linted is the `pkh build` output next to the tree when it
|
||||
/// matches the current changelog entry and no tree content is newer;
|
||||
/// otherwise the tree is packed fresh (with `--repack` forcing that path).
|
||||
pub fn run(root: &Path, options: &LintOptions) -> Result<Option<WrapperOutcome>, String> {
|
||||
let tmp = TempDir::new()?;
|
||||
let root = root
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Cannot lint '{}': {e}", root.display()))?;
|
||||
|
||||
let (dsc, notes) = match usable_build_output(&root, options.repack) {
|
||||
Some(dsc) => {
|
||||
let note = format!(
|
||||
"linting pkh build output {}",
|
||||
crate::report::display_path(&dsc)
|
||||
);
|
||||
(dsc, vec![note])
|
||||
}
|
||||
None => {
|
||||
let dsc = pack(&root, &tmp)?;
|
||||
let reason = if options.repack {
|
||||
"the tree was packed fresh with dpkg-source (--repack ignored \
|
||||
the existing pkh build output)"
|
||||
.to_string()
|
||||
} else if expected_build_output(&root).is_some() {
|
||||
"the tree changed since pkh build, so it was packed fresh \
|
||||
with dpkg-source (rerun pkh build to lint the build output)"
|
||||
.to_string()
|
||||
} else {
|
||||
"no pkh build output next to the tree, so it was packed fresh \
|
||||
with dpkg-source (pkh build produces one)"
|
||||
.to_string()
|
||||
};
|
||||
(dsc, vec![reason])
|
||||
}
|
||||
};
|
||||
|
||||
let mut lintian = Command::new("lintian");
|
||||
lintian
|
||||
.env("LC_ALL", "C")
|
||||
.args(["--no-cfg", "--color", "never"])
|
||||
.arg("--info")
|
||||
.arg(&dsc);
|
||||
// Per-distro scoping: lintian auto-detects the *host* vendor, but pkh
|
||||
// knows the *target* distro (-d); make the two agree, which matters on
|
||||
// cross-distro hosts (linting an Ubuntu package on Debian or back).
|
||||
if let Some(dist) = &options.dist
|
||||
&& matches!(dist.as_str(), "ubuntu" | "debian")
|
||||
{
|
||||
lintian.arg("--profile").arg(dist);
|
||||
}
|
||||
if options.display_info {
|
||||
lintian.arg("--display-info");
|
||||
}
|
||||
if options.pedantic {
|
||||
lintian.arg("--pedantic");
|
||||
}
|
||||
if options.experimental {
|
||||
lintian.arg("--display-experimental");
|
||||
}
|
||||
if options.show_overrides {
|
||||
lintian.arg("--show-overrides");
|
||||
}
|
||||
if !options.suppress_tags.is_empty() {
|
||||
lintian
|
||||
.arg("--suppress-tags")
|
||||
.arg(options.suppress_tags.join(","));
|
||||
}
|
||||
|
||||
let output = match lintian.output() {
|
||||
Ok(output) => output,
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(format!("Could not run lintian: {e}")),
|
||||
};
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let findings = parse(&stdout);
|
||||
if !output.status.success() && findings.is_empty() {
|
||||
return Err(format!(
|
||||
"lintian exited with {} without reporting findings:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
Ok(Some(WrapperOutcome { findings, notes }))
|
||||
}
|
||||
|
||||
/// Pack the tree into an ephemeral source package and return its `.dsc`.
|
||||
///
|
||||
/// Compression is deliberately weak (`-Zgzip -z1`): the artifact only ever
|
||||
/// goes to lintian and is deleted with the temp directory, and xz on a
|
||||
/// large tree dominates the whole run (measured: 9.8 s xz vs 2.7 s gzip on
|
||||
/// a 111 MB tree). Locale-independent subprocess output: dpkg messages can
|
||||
/// be localized, and the error sniffing relies on English wording.
|
||||
fn pack(root: &Path, tmp: &TempDir) -> Result<PathBuf, String> {
|
||||
// 3.0 (quilt) trees need the orig tarball(s) reachable from the working
|
||||
// directory, and dpkg-source searches cwd — link them from the tree's
|
||||
// parent, where pkh build / git ubuntu export-orig leave them.
|
||||
link_orig_tarballs(root, tmp.path());
|
||||
|
||||
let output = Command::new("dpkg-source")
|
||||
.env("LC_ALL", "C")
|
||||
.args(["-b", "-Zgzip", "-z1"])
|
||||
.arg(root)
|
||||
.current_dir(tmp.path())
|
||||
.output()
|
||||
.map_err(|e| format!("Could not run dpkg-source: {e}"))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if stderr.to_lowercase().contains("uncommitted") {
|
||||
return Err(
|
||||
"The source tree has uncommitted changes that dpkg-source refuses \
|
||||
to pack. Commit them first, or use --native to lint with pkh's \
|
||||
native checks only."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
return Err(format!(
|
||||
"dpkg-source -b failed, the tree may not be a valid source package:\n{}",
|
||||
stderr.trim()
|
||||
));
|
||||
}
|
||||
|
||||
find_dsc(tmp.path())
|
||||
}
|
||||
|
||||
/// The `pkh build` output matching the tree's current changelog entry, when
|
||||
/// it exists and no tree content is newer than it: linting a stale artifact
|
||||
/// would report the packaging of the past, so staleness forces a fresh pack.
|
||||
fn usable_build_output(root: &Path, force_repack: bool) -> Option<PathBuf> {
|
||||
if force_repack {
|
||||
return None;
|
||||
}
|
||||
let dsc = expected_build_output(root)?;
|
||||
let built = std::fs::metadata(&dsc).ok()?.modified().ok()?;
|
||||
if tree_newer_than(root, built) {
|
||||
return None;
|
||||
}
|
||||
Some(dsc)
|
||||
}
|
||||
|
||||
/// The `pkh build` output path matching the tree's current changelog entry
|
||||
/// (`../<source>_<version>.dsc`, pkh build's own naming), if it exists.
|
||||
fn expected_build_output(root: &Path) -> Option<PathBuf> {
|
||||
let entry =
|
||||
crate::debian::changelog::parse_changelog_entry(&root.join("debian/changelog")).ok()?;
|
||||
let dsc = root
|
||||
.parent()?
|
||||
.join(format!("{}_{}.dsc", entry.source, entry.version.no_epoch()));
|
||||
std::fs::metadata(&dsc).ok()?;
|
||||
Some(dsc)
|
||||
}
|
||||
|
||||
/// Whether any tree content is newer than `built`. Skips `.git` and `.pc`:
|
||||
/// commits and quilt bookkeeping churn their mtimes without touching what
|
||||
/// the source package contains.
|
||||
fn tree_newer_than(root: &Path, built: SystemTime) -> bool {
|
||||
const SKIP: &[&str] = &[".git", ".pc"];
|
||||
let mut stack = vec![root.to_path_buf()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
if SKIP.iter().any(|skip| name.to_string_lossy() == *skip) {
|
||||
continue;
|
||||
}
|
||||
match entry.file_type() {
|
||||
Ok(ft) if ft.is_dir() => stack.push(entry.path()),
|
||||
_ => {
|
||||
let newer = entry
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.is_some_and(|modified| modified > built);
|
||||
if newer {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Symlink the orig (and orig component) tarballs for the tree's upstream
|
||||
/// version from the tree's parent into `dest`, ignoring absence — native
|
||||
/// trees have none, and missing tarballs surface as a dpkg-source error.
|
||||
fn link_orig_tarballs(root: &Path, dest: &Path) {
|
||||
let Some(parent) = root.parent() else {
|
||||
return;
|
||||
};
|
||||
let Ok(entry) = crate::debian::changelog::parse_changelog_entry(&root.join("debian/changelog"))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let prefixes = [
|
||||
format!("{}_{}.orig.tar.", entry.source, entry.version.upstream),
|
||||
format!("{}_{}.orig-", entry.source, entry.version.upstream),
|
||||
];
|
||||
let Ok(entries) = std::fs::read_dir(parent) else {
|
||||
return;
|
||||
};
|
||||
for candidate in entries.flatten() {
|
||||
let name = candidate.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if !candidate.file_type().is_ok_and(|ft| ft.is_file())
|
||||
|| !prefixes
|
||||
.iter()
|
||||
.any(|prefix| name.starts_with(prefix.as_str()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let _ = std::os::unix::fs::symlink(parent.join(name.as_ref()), dest.join(name.as_ref()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse lintian's output into findings. Tag lines carry the finding; `N:`
|
||||
/// note lines following a tag line are its explanation (`--info` output) and
|
||||
/// attach to it. Anything else is ignored.
|
||||
fn parse(text: &str) -> Vec<Finding> {
|
||||
let tag_line = Regex::new(r"^(?P<letter>[EWIPXOC]): (?P<rest>.*)$").expect("static regex");
|
||||
let subject = Regex::new(
|
||||
r"^(?P<pkg>\S+?)(?: (?P<ptype>source|binary|udeb|changes|buildinfo))?: (?P<tag>\S+)(?: (?P<details>.*))?$",
|
||||
)
|
||||
.expect("static regex");
|
||||
let note_line = Regex::new(r"^N:(?: (?P<text>.*))?$").expect("static regex");
|
||||
|
||||
let mut findings: Vec<Finding> = Vec::new();
|
||||
for line in text.lines() {
|
||||
if let Some(note) = note_line.captures(line) {
|
||||
// Attach to the finding above, like lintian lays out --info.
|
||||
if let (Some(text), Some(last)) = (note.name("text"), findings.last_mut())
|
||||
&& !text.as_str().trim().is_empty()
|
||||
{
|
||||
last.explanation.push(text.as_str().trim().to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(head) = tag_line.captures(line) else {
|
||||
continue;
|
||||
};
|
||||
let Some(subject) = subject.captures(&head["rest"]) else {
|
||||
continue;
|
||||
};
|
||||
findings.push(Finding {
|
||||
letter: head["letter"].chars().next().unwrap_or('E'),
|
||||
tag_name: subject["tag"].to_string(),
|
||||
message: subject
|
||||
.name("details")
|
||||
.map_or(String::new(), |d| d.as_str().to_string()),
|
||||
package: subject["pkg"].to_string(),
|
||||
processable_type: subject.name("ptype").map(|p| p.as_str().to_string()),
|
||||
explanation: Vec::new(),
|
||||
origin: Origin::Lintian,
|
||||
});
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
/// The single `.dsc` the ephemeral source package produced.
|
||||
fn find_dsc(dir: &Path) -> Result<PathBuf, String> {
|
||||
let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.map_err(|e| format!("Cannot read the temporary build directory: {e}"))?
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.extension().is_some_and(|ext| ext == "dsc"))
|
||||
.collect();
|
||||
match entries.pop() {
|
||||
Some(dsc) => Ok(dsc),
|
||||
None => Err(
|
||||
"dpkg-source produced no .dsc; the tree may not be a valid source package".to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Temporary directory removed on drop; the hand-rolled stand-in for
|
||||
/// `tempfile`, which is dev-only in this crate.
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new() -> Result<TempDir, String> {
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let path = std::env::temp_dir().join(format!("pkh-lint-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir(&path)
|
||||
.map_err(|e| format!("Could not create a temporary directory: {e}"))?;
|
||||
Ok(TempDir(path))
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Captured from lintian 2.129.0ubuntu2.1 on a broken native source
|
||||
/// package (default display level).
|
||||
const SOURCE_OUTPUT: &str = "\
|
||||
E: hello source: malformed-debian-changelog-version 0.1-1 (for native) [debian/changelog:1]
|
||||
E: hello source: package-uses-debhelper-but-lacks-build-depends [debian/rules]
|
||||
W: hello source: debhelper-but-no-misc-depends hello
|
||||
W: hello source: debhelper-compat-file-is-missing
|
||||
W: hello source: no-debian-copyright-in-source
|
||||
";
|
||||
|
||||
/// Captured from lintian 2.129.0ubuntu2.1 on a binary package: binary
|
||||
/// findings carry no processable type after the package name.
|
||||
const BINARY_OUTPUT: &str = "\
|
||||
E: badpkg: description-too-short test
|
||||
E: badpkg: extended-description-is-empty
|
||||
W: badpkg: empty-binary-package
|
||||
W: badpkg: recommended-field badpkg_1.0-1_all.deb Priority
|
||||
";
|
||||
|
||||
/// Captured with --show-overrides: overridden findings print as `O:`.
|
||||
const OVERRIDDEN_OUTPUT: &str = "\
|
||||
E: hello source: malformed-debian-changelog-version 0.1-1 (for native) [debian/changelog:1]
|
||||
O: hello source: debhelper-compat-file-is-missing
|
||||
";
|
||||
|
||||
/// Captured with --info: each tag line is followed by `N:` explanation
|
||||
/// lines that belong to it.
|
||||
const INFO_OUTPUT: &str = "\
|
||||
N:
|
||||
E: hello source: malformed-debian-changelog-version 0.1-1 (for native) [debian/changelog:1]
|
||||
N:
|
||||
N: The version string in the latest changelog entry was not parsed correctly.
|
||||
N: Usually, that means it does not conform to policy.
|
||||
N:
|
||||
N:
|
||||
E: hello source: package-uses-debhelper-but-lacks-build-depends [debian/rules]
|
||||
N:
|
||||
N: If a package uses debhelper, it must declare a Build-Depends on debhelper
|
||||
N: or on the debhelper-compat virtual package. For example:
|
||||
N:
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn parses_source_output_with_type() {
|
||||
let findings = parse(SOURCE_OUTPUT);
|
||||
assert_eq!(findings.len(), 5);
|
||||
let first = &findings[0];
|
||||
assert_eq!(first.letter, 'E');
|
||||
assert_eq!(first.package, "hello");
|
||||
assert_eq!(first.processable_type.as_deref(), Some("source"));
|
||||
assert_eq!(first.tag_name, "malformed-debian-changelog-version");
|
||||
assert_eq!(first.message, "0.1-1 (for native) [debian/changelog:1]");
|
||||
assert_eq!(findings[2].letter, 'W');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_binary_output_without_type() {
|
||||
let findings = parse(BINARY_OUTPUT);
|
||||
assert_eq!(findings.len(), 4);
|
||||
let first = &findings[0];
|
||||
assert_eq!(first.package, "badpkg");
|
||||
assert_eq!(first.processable_type, None);
|
||||
assert_eq!(first.tag_name, "description-too-short");
|
||||
// Details containing a file name with dots survive intact.
|
||||
assert_eq!(findings[3].message, "badpkg_1.0-1_all.deb Priority");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_overridden_lines() {
|
||||
let findings = parse(OVERRIDDEN_OUTPUT);
|
||||
assert_eq!(findings.len(), 2);
|
||||
assert_eq!(findings[1].letter, 'O');
|
||||
assert_eq!(findings[1].tag_name, "debhelper-compat-file-is-missing");
|
||||
assert_eq!(findings[1].message, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attaches_info_notes_to_the_preceding_finding() {
|
||||
let findings = parse(INFO_OUTPUT);
|
||||
assert_eq!(findings.len(), 2);
|
||||
assert_eq!(
|
||||
findings[0].explanation,
|
||||
vec![
|
||||
"The version string in the latest changelog entry was not parsed correctly.",
|
||||
"Usually, that means it does not conform to policy.",
|
||||
]
|
||||
);
|
||||
assert_eq!(findings[1].explanation.len(), 2);
|
||||
assert!(findings[1].explanation[0].starts_with("If a package uses debhelper"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_stray_lines() {
|
||||
let findings =
|
||||
parse("N: lintian ran\ngarbage line\nC: hello source: some-classification\n");
|
||||
// The C: classification line parses (kept for JSON), garbage drops.
|
||||
assert_eq!(findings.len(), 1);
|
||||
assert_eq!(findings[0].letter, 'C');
|
||||
}
|
||||
|
||||
/// A lintable tree at `<outer>/<name>` with a changelog entry
|
||||
/// `pkg (1.0-1) resolute`; returns the outer dir (the tree's parent,
|
||||
/// where pkh build would place artifacts).
|
||||
fn tree() -> (tempfile::TempDir, std::path::PathBuf) {
|
||||
let outer = tempfile::tempdir().unwrap();
|
||||
let root = outer.path().join("pkg-1.0");
|
||||
std::fs::create_dir_all(root.join("debian")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("debian/changelog"),
|
||||
"pkg (1.0-1) resolute; urgency=medium\n\n * x\n\n -- J <j@e.org> Sat, 19 Sep 2026 12:00:00 +0000\n",
|
||||
)
|
||||
.unwrap();
|
||||
(outer, root)
|
||||
}
|
||||
|
||||
fn dsc_of(outer: &tempfile::TempDir) -> std::path::PathBuf {
|
||||
outer.path().join("pkg_1.0-1.dsc")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_build_output_is_reused() {
|
||||
let (outer, root) = tree();
|
||||
std::fs::write(dsc_of(&outer), "dummy dsc").unwrap();
|
||||
// The dsc was written after every tree file: current.
|
||||
assert_eq!(usable_build_output(&root, false), Some(dsc_of(&outer)));
|
||||
// Forcing repack skips it.
|
||||
assert_eq!(usable_build_output(&root, true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_or_mismatched_build_output_is_rejected() {
|
||||
let (outer, root) = tree();
|
||||
// A tree file written after the dsc makes the artifact stale. The
|
||||
// sleep crosses the coarse clock tick mtimes are stamped with, so
|
||||
// the control file is strictly newer than the dsc.
|
||||
std::fs::write(dsc_of(&outer), "dummy dsc").unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(root.join("debian/control"), "Source: pkg\n").unwrap();
|
||||
assert_eq!(usable_build_output(&root, false), None);
|
||||
|
||||
// A dsc of a different version does not represent this tree.
|
||||
let old_dsc = outer.path().join("pkg_0.9-1.dsc");
|
||||
std::fs::write(&old_dsc, "dummy dsc").unwrap();
|
||||
assert_eq!(usable_build_output(&root, false), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_build_output_is_rejected() {
|
||||
let (outer, root) = tree();
|
||||
assert_eq!(usable_build_output(&root, false), None);
|
||||
assert!(!dsc_of(&outer).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orig_tarballs_are_linked_for_packing() {
|
||||
let (outer, root) = tree();
|
||||
std::fs::write(outer.path().join("pkg_1.0.orig.tar.xz"), "orig").unwrap();
|
||||
std::fs::write(outer.path().join("pkg_1.0.orig-data.tar.gz"), "comp").unwrap();
|
||||
std::fs::write(outer.path().join("unrelated_1.0.orig.tar.xz"), "no").unwrap();
|
||||
std::fs::write(outer.path().join("pkg_1.0-1.dsc"), "no").unwrap();
|
||||
|
||||
let dest = tempfile::tempdir().unwrap();
|
||||
link_orig_tarballs(&root, dest.path());
|
||||
|
||||
assert!(
|
||||
dest.path()
|
||||
.join("pkg_1.0.orig.tar.xz")
|
||||
.symlink_metadata()
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
dest.path()
|
||||
.join("pkg_1.0.orig-data.tar.gz")
|
||||
.symlink_metadata()
|
||||
.is_ok()
|
||||
);
|
||||
assert!(!dest.path().join("unrelated_1.0.orig.tar.xz").exists());
|
||||
// The dsc is not an orig tarball and must not be linked.
|
||||
assert!(!dest.path().join("pkg_1.0-1.dsc").exists());
|
||||
}
|
||||
}
|
||||
+547
-231
@@ -3,12 +3,9 @@ use std::io::Write;
|
||||
|
||||
extern crate clap;
|
||||
use clap::{Command, arg, command};
|
||||
use pkh::context::ContextConfig;
|
||||
|
||||
extern crate flate2;
|
||||
|
||||
use pkh::changelog::generate_entry;
|
||||
|
||||
use indicatif_log_bridge::LogWrapper;
|
||||
use log::{error, info};
|
||||
|
||||
@@ -23,6 +20,155 @@ fn current_dir_or_exit() -> std::path::PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// CLI-side Ctrl+C wiring. The passive state (interrupted flag, cleanup
|
||||
/// hook registry, reporter slot) lives in `pkh::interrupt`; everything that
|
||||
/// installs, prints or exits lives here: the SIGINT handler only wakes a
|
||||
/// watchdog through a self-pipe (async-signal-safe), and the watchdog runs
|
||||
/// the whole shutdown in thread context — the live view's reporter clears
|
||||
/// the terminal, the notice is printed, further Ctrl+C is absorbed as a
|
||||
/// no-op, the cleanup hooks release their resources, and the process exits
|
||||
/// with the conventional status 130, skipping destructors.
|
||||
mod interrupt {
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
|
||||
|
||||
/// Whether the interrupt notice has been shown; the first caller prints
|
||||
/// it, later ones stay silent
|
||||
static NOTICE_SHOWN: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Whether handler, self-pipe and watchdog are in place
|
||||
static INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Write end of the self-pipe the signal handler wakes the watchdog
|
||||
/// through; `-1` until [`install`] set it up
|
||||
static SELF_PIPE_WRITE: AtomicI32 = AtomicI32::new(-1);
|
||||
|
||||
/// Install the process-global Ctrl+C (SIGINT) handler; idempotent.
|
||||
///
|
||||
/// When the self-pipe or the watchdog cannot be set up, the default
|
||||
/// SIGINT disposition is kept (the process dies immediately) rather
|
||||
/// than installing a handler that could not run the shutdown.
|
||||
pub fn install() {
|
||||
if INSTALLED.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut fds = [0 as libc::c_int; 2];
|
||||
// SAFETY: pipe(2) into a two-element array we own
|
||||
if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
|
||||
INSTALLED.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
let (read_fd, write_fd) = (fds[0], fds[1]);
|
||||
|
||||
// The write end is used from the signal handler: non-blocking, so
|
||||
// even a full pipe degrades to a dropped wake-up instead of
|
||||
// blocking the handler.
|
||||
// SAFETY: fcntl(2) on a pipe file descriptor we just created
|
||||
unsafe {
|
||||
let flags = libc::fcntl(write_fd, libc::F_GETFL);
|
||||
libc::fcntl(write_fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
|
||||
}
|
||||
SELF_PIPE_WRITE.store(write_fd, Ordering::SeqCst);
|
||||
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pkh-interrupt".to_string())
|
||||
.spawn(move || watchdog(read_fd));
|
||||
if spawned.is_err() {
|
||||
// SAFETY: closing pipe file descriptors we just created
|
||||
unsafe {
|
||||
libc::close(read_fd);
|
||||
libc::close(write_fd);
|
||||
}
|
||||
SELF_PIPE_WRITE.store(-1, Ordering::SeqCst);
|
||||
INSTALLED.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
|
||||
// SAFETY: installing a signal handler whose body only records the
|
||||
// interruption and writes to the self-pipe (async-signal-safe)
|
||||
unsafe {
|
||||
libc::signal(libc::SIGINT, on_sigint as *const () as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Never returns: park the calling thread until the watchdog exits the
|
||||
/// process
|
||||
///
|
||||
/// The watchdog owns the interrupt shutdown; a caller that would
|
||||
/// otherwise reach its own `std::process::exit` and kill the process
|
||||
/// mid-cleanup must park here instead.
|
||||
pub fn wait_for_shutdown() -> ! {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
/// Signal handler body: record the interruption and wake the watchdog
|
||||
/// through the self-pipe
|
||||
extern "C" fn on_sigint(_sig: libc::c_int) {
|
||||
pkh::interrupt::mark_interrupted();
|
||||
let fd = SELF_PIPE_WRITE.load(Ordering::SeqCst);
|
||||
if fd >= 0 {
|
||||
// SAFETY: write(2) of one byte to the self-pipe is
|
||||
// async-signal-safe; a failed write (e.g. EAGAIN) drops the
|
||||
// wake-up instead of blocking the handler
|
||||
unsafe {
|
||||
libc::write(fd, b"x".as_ptr().cast(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Watchdog body: block until the signal handler's byte arrives, then
|
||||
/// run the shutdown sequence
|
||||
fn watchdog(read_fd: libc::c_int) {
|
||||
let mut byte = [0u8; 1];
|
||||
// SAFETY: read(2) into a local buffer of the announced length
|
||||
let received = unsafe { libc::read(read_fd, byte.as_mut_ptr().cast(), 1) };
|
||||
// The write end is never closed, so a short read cannot happen in
|
||||
// practice; on error there is nothing to clean up either way.
|
||||
if received > 0 {
|
||||
run_interrupt_sequence();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reporter, notice, cleanup hooks, exit 130: the whole shutdown, run
|
||||
/// in the watchdog thread immediately on Ctrl+C — never in the signal
|
||||
/// handler itself
|
||||
///
|
||||
/// Further Ctrl+C while this runs writes bytes nobody reads: absorbed
|
||||
/// as a no-op (send SIGTERM/SIGKILL if a hook ever hangs).
|
||||
fn run_interrupt_sequence() {
|
||||
let hint =
|
||||
pkh::interrupt::take_reporter().and_then(|report| {
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(report)) {
|
||||
Ok(hint) => hint,
|
||||
Err(_) => {
|
||||
log::error!("Interrupt reporter panicked");
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
show_notice();
|
||||
if let Some(hint) = hint {
|
||||
eprintln!("{hint}");
|
||||
}
|
||||
pkh::interrupt::run_cleanup_hooks();
|
||||
// SAFETY: raw exit bypassing destructors, intended at interrupt time
|
||||
unsafe {
|
||||
libc::_exit(130);
|
||||
}
|
||||
}
|
||||
|
||||
/// Print the interrupt notice, once per process: the first caller
|
||||
/// prints it, later ones stay silent
|
||||
fn show_notice() {
|
||||
if NOTICE_SHOWN.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
eprintln!("CTRL+C: Build interrupted by user.");
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let logger =
|
||||
@@ -34,7 +180,6 @@ fn main() {
|
||||
LogWrapper::new(multi.clone(), logger).try_init().unwrap();
|
||||
let matches = command!()
|
||||
.subcommand_required(true)
|
||||
.disable_version_flag(true)
|
||||
.subcommand(
|
||||
Command::new("new")
|
||||
.about("Scaffold a new Debian source package (buildable right away)")
|
||||
@@ -119,7 +264,29 @@ fn main() {
|
||||
.help("Target series (default: the development series of --dist)"),
|
||||
)
|
||||
.arg(arg!(--release "Write the --series into debian/changelog instead of UNRELEASED").required(false))
|
||||
.arg(arg!(--native "Use the 3.0 (native) source format (no orig tarball)").required(false))
|
||||
.arg(arg!(--native "Use the 3.0 (native) source format (default for a new project skeleton: no orig tarball)").required(false))
|
||||
.arg(
|
||||
clap::Arg::new("quilt")
|
||||
.long("quilt")
|
||||
.action(clap::ArgAction::SetTrue)
|
||||
.conflicts_with("native")
|
||||
.help("Use the 3.0 (quilt) source format with an orig tarball (default when packaging an existing project)"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("orig_from")
|
||||
.long("orig-from")
|
||||
.value_name("MODE")
|
||||
.value_parser(["release", "git", "path", "snapshot"])
|
||||
.conflicts_with("native")
|
||||
.help("How to produce the orig tarball (quilt only): release (download the forge tarball of the tag; network), git (git archive of the tag), path (repack --orig-path), snapshot (tar the working tree). Default: git on a tag, snapshot otherwise"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("orig_path")
|
||||
.long("orig-path")
|
||||
.value_name("FILE|URL")
|
||||
.conflicts_with("native")
|
||||
.help("Tarball used by --orig-from path: a local file or an http(s) URL (.tar, .tar.gz, .tgz, .tar.bz2, .tbz2, .tar.xz), repacked to the orig"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("no_git")
|
||||
.long("no-git")
|
||||
@@ -156,13 +323,20 @@ fn main() {
|
||||
Command::new("chlog")
|
||||
.about("Auto-generate changelog entry, editing it, committing it afterwards")
|
||||
.arg(arg!(-s --series <series> "Target distribution series").required(false))
|
||||
.arg(arg!(--backport "This changelog is for a backport entry").required(false))
|
||||
.arg(arg!(-v --version <version> "Target version").required(false)),
|
||||
.arg(arg!(--backport "Number the entry as a backport of the target series (Debian: 1.0-1 becomes 1.0-1~bpo12+1; Ubuntu: 3.1-1ubuntu2 becomes 3.1-1ubuntu2~24.04.1)").required(false)
|
||||
.conflicts_with_all(["nmu", "rebuild"]))
|
||||
.arg(arg!(--nmu "Number the entry as a non-maintainer upload (1.0-1 becomes 1.0-1.1, native 1.0 becomes 1.0+nmu1)").required(false)
|
||||
.conflicts_with("rebuild"))
|
||||
.arg(arg!(--rebuild "Number the entry as a no-change rebuild (1.0-1 becomes 1.0-1build1)").required(false))
|
||||
.arg(arg!(-v --version <version> "Target version (overrides the --backport/--nmu/--rebuild numbering)").required(false)),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("build")
|
||||
.about("Build the source package (into a .dsc)")
|
||||
.arg(arg!(--verbose "Show raw tool output instead of the live build view").required(false)),
|
||||
.arg(arg!(--verbose "Show raw tool output instead of the live build view").required(false))
|
||||
.arg(arg!(--orig <when> "Original source tarball in the upload [auto, always, never] (default: auto)").required(false)
|
||||
.long_help("Whether the upload distributes the original source tarball(s), like dpkg-genchanges' -sa/-si/-sd source styles.\nauto: include them only when the upstream version changed since the previous changelog entry (the default);\nalways: force inclusion, even for a revision bump of the same upstream version;\nnever: never include them, even for a new upstream version.\nAn explicit value is ignored with a warning for native packages (they have no separate orig tarball).")
|
||||
.value_parser(["auto", "always", "never"])),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("put")
|
||||
@@ -191,31 +365,61 @@ fn main() {
|
||||
.long_help("Show raw tool output instead of the live build view.\nAlso implied by RUST_LOG=debug for pkh's own logs.")),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("context")
|
||||
.about("Manage contexts")
|
||||
.subcommand_required(true)
|
||||
.subcommand(
|
||||
Command::new("create")
|
||||
.about("Create a new context")
|
||||
.arg(arg!(<name> "Context name"))
|
||||
.arg(arg!(--type <type> "Context type: ssh (only type supported for now)"))
|
||||
.arg(arg!(--endpoint <endpoint> "Context endpoint (for example: ssh://user@host:port)"))
|
||||
Command::new("lint")
|
||||
.about("Lint the package (lintian wrapper + pkh-native checks)")
|
||||
.arg(arg!([path] "Source tree to lint (default: the current directory)").required(false))
|
||||
.arg(arg!(-d --dist <dist> "Target distribution (debian, ubuntu)").required(false))
|
||||
.arg(arg!(-s --series <series> "Target distribution series").required(false))
|
||||
.arg(arg!(--native "Run pkh-native checks only, without the lintian wrapper").required(false))
|
||||
.arg(arg!(--info "Show tag explanations under each finding").required(false))
|
||||
.arg(
|
||||
clap::Arg::new("display_info")
|
||||
.long("display-info")
|
||||
.action(clap::ArgAction::SetTrue)
|
||||
.help("Also display info-level tags (I:)"),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("rm")
|
||||
.about("Remove a context")
|
||||
.arg(arg!(<name> "Context name"))
|
||||
.arg(arg!(--pedantic "Also display pedantic tags (P:)").required(false))
|
||||
.arg(arg!(--experimental "Also display experimental tags (X:)").required(false))
|
||||
.arg(
|
||||
clap::Arg::new("show_overrides")
|
||||
.long("show-overrides")
|
||||
.action(clap::ArgAction::SetTrue)
|
||||
.help("Also display overridden tags (O:)"),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("ls")
|
||||
.about("List contexts")
|
||||
.arg(
|
||||
clap::Arg::new("fail_on")
|
||||
.long("fail-on")
|
||||
.value_name("LEVELS")
|
||||
.help("Comma-separated severities failing the run: error, warning, info, pedantic, experimental, override (default: error)"),
|
||||
)
|
||||
.subcommand(Command::new("show").about("Show current context"))
|
||||
.subcommand(
|
||||
Command::new("use")
|
||||
.about("Set current context")
|
||||
.arg(arg!(<name> "Context name"))
|
||||
.arg(
|
||||
clap::Arg::new("suppress_tags")
|
||||
.long("suppress-tags")
|
||||
.value_name("LIST")
|
||||
.help("Comma-separated tag names to ignore for this run"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("check")
|
||||
.long("check")
|
||||
.value_name("NAME")
|
||||
.action(clap::ArgAction::Append)
|
||||
.help("Run only this pkh-native check (can be specified multiple times)"),
|
||||
)
|
||||
.arg(arg!(--repack "Ignore existing pkh build output and pack the tree fresh for linting").required(false))
|
||||
.arg(arg!(--json "Emit the report as JSON").required(false))
|
||||
.arg(
|
||||
clap::Arg::new("color")
|
||||
.long("color")
|
||||
.value_name("WHEN")
|
||||
.value_parser(["auto", "always", "never"])
|
||||
.help("Colorize the report: auto, always or never (default: auto)"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("list_tags")
|
||||
.long("list-tags")
|
||||
.action(clap::ArgAction::SetTrue)
|
||||
.help("Print the pkh-native tag catalog and exit"),
|
||||
),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("prune")
|
||||
@@ -273,6 +477,12 @@ fn main() {
|
||||
.get_one::<bool>("native")
|
||||
.copied()
|
||||
.unwrap_or(false),
|
||||
quilt: sub_matches
|
||||
.get_one::<bool>("quilt")
|
||||
.copied()
|
||||
.unwrap_or(false),
|
||||
orig_from: sub_matches.get_one::<String>("orig_from").cloned(),
|
||||
orig_path: sub_matches.get_one::<String>("orig_path").cloned(),
|
||||
git: !sub_matches
|
||||
.get_one::<bool>("no_git")
|
||||
.copied()
|
||||
@@ -287,11 +497,17 @@ fn main() {
|
||||
// resolves through the same pipeline; without a TTY the resolve
|
||||
// error lists every missing answer. Afterwards the two
|
||||
// verification builds are offered (`--no-verify` skips them;
|
||||
// the structural self-checks inside `scaffold` always run).
|
||||
// the structural self-checks inside `scaffold` always run), with
|
||||
// the scaffold outcome (e.g. a failed vendoring) shaping the
|
||||
// offer.
|
||||
let prompter = pkh::ui::prompt::TerminalPrompter;
|
||||
if let Err(e) = rt.block_on(async {
|
||||
let opts = pkh::new::questions::run(cli).await?;
|
||||
pkh::new::scaffold(opts.clone(), &multi)?;
|
||||
pkh::new::questions::offer_verification(&opts, &multi, no_verify).await;
|
||||
let opts = pkh::new::questions::run(cli, &prompter).await?;
|
||||
let outcome = pkh::new::scaffold(opts.clone(), &multi)?;
|
||||
pkh::new::questions::offer_verification(
|
||||
&opts, &outcome, &multi, no_verify, &prompter,
|
||||
)
|
||||
.await;
|
||||
Ok::<(), Box<dyn std::error::Error>>(())
|
||||
}) {
|
||||
error!("{}", e);
|
||||
@@ -316,15 +532,14 @@ fn main() {
|
||||
let (pb, progress_callback) = pkh::ui::create_progress_bar(&multi);
|
||||
|
||||
// Convert PPA to base URL if provided
|
||||
let base_url = ppa.map(|ppa_str| {
|
||||
// PPA format: user/ppa_name
|
||||
let parts: Vec<&str> = ppa_str.split('/').collect();
|
||||
if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
|
||||
error!("Invalid PPA format: '{}'. Expected: user/ppa_name", ppa_str);
|
||||
let base_url = match ppa.map(pkh::package_info::split_ppa) {
|
||||
Some(Ok((user, name))) => Some(pkh::package_info::ppa_to_base_url(user, name)),
|
||||
Some(Err(e)) => {
|
||||
error!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
pkh::package_info::ppa_to_base_url(parts[0], parts[1])
|
||||
});
|
||||
None => None,
|
||||
};
|
||||
|
||||
// Since pull is async, we need to block on it
|
||||
if let Err(e) = rt.block_on(async {
|
||||
@@ -353,79 +568,74 @@ fn main() {
|
||||
let cwd = current_dir_or_exit();
|
||||
let version = sub_matches.get_one::<String>("version").map(|s| s.as_str());
|
||||
let cli_series = sub_matches.get_one::<String>("series").map(|s| s.as_str());
|
||||
let kind = if sub_matches
|
||||
.get_one::<bool>("backport")
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
{
|
||||
pkh::changelog::EntryKind::Backport
|
||||
} else if sub_matches.get_one::<bool>("nmu").copied().unwrap_or(false) {
|
||||
pkh::changelog::EntryKind::Nmu
|
||||
} else if sub_matches
|
||||
.get_one::<bool>("rebuild")
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
{
|
||||
pkh::changelog::EntryKind::Rebuild
|
||||
} else {
|
||||
pkh::changelog::EntryKind::Normal
|
||||
};
|
||||
|
||||
// Determine target series: CLI flag > interactive selector > current changelog series
|
||||
let target_series = if let Some(s) = cli_series {
|
||||
Some(s.to_string())
|
||||
} else {
|
||||
// Parse current changelog to determine the default series
|
||||
let changelog_path = cwd.join("debian/changelog");
|
||||
match pkh::changelog::parse_changelog_header(&changelog_path) {
|
||||
Ok((_pkg, _ver, current_series)) => {
|
||||
// UNRELEASED is not a real series: offer it as a
|
||||
// pinned first entry (selecting it keeps the changelog
|
||||
// unreleased) on top of the current vendor's series
|
||||
// list, defaulting to the development series. Any
|
||||
// other series resolves through the series list of
|
||||
// its own distribution.
|
||||
match rt.block_on(async {
|
||||
if pkh::distro_info::is_unreleased(¤t_series) {
|
||||
// Vendors keep original casing ("Ubuntu"),
|
||||
// while the series data keys are lowercase
|
||||
let dist = pkh::build::env::current_vendor().to_lowercase();
|
||||
let mut series_list =
|
||||
vec![pkh::distro_info::UNRELEASED.to_string()];
|
||||
series_list.extend(
|
||||
pkh::distro_info::get_ordered_series_name(&dist).await?,
|
||||
);
|
||||
Ok(series_list)
|
||||
} else {
|
||||
let dist =
|
||||
pkh::distro_info::get_dist_from_series(¤t_series).await?;
|
||||
pkh::distro_info::get_ordered_series_name(&dist).await
|
||||
}
|
||||
}) {
|
||||
Ok(series_list) => {
|
||||
// Default to the development series (the
|
||||
// first real entry) when the changelog is
|
||||
// UNRELEASED, not to the pinned entry itself
|
||||
let default = if pkh::distro_info::is_unreleased(¤t_series)
|
||||
&& series_list.len() > 1
|
||||
{
|
||||
series_list[1].clone()
|
||||
} else {
|
||||
current_series.clone()
|
||||
};
|
||||
match pkh::ui::select_series(&series_list, &default) {
|
||||
Ok(selected) => Some(selected),
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Series selection failed: {}. Using current series '{}' instead.",
|
||||
e, current_series
|
||||
);
|
||||
Some(current_series)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
// Could not fetch series list, use current series as default
|
||||
Some(current_series)
|
||||
}
|
||||
match rt.block_on(pkh::changelog::series_candidates(&changelog_path)) {
|
||||
Some(pkh::changelog::SeriesCandidates::Choose {
|
||||
options,
|
||||
values,
|
||||
default,
|
||||
fallback,
|
||||
}) => match pkh::ui::select_series(&options, &default) {
|
||||
Ok(selected) => {
|
||||
Some(pkh::changelog::selected_series(&options, &values, selected))
|
||||
}
|
||||
}
|
||||
Err(_) => None,
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Series selection failed: {}. Using current series '{}' instead.",
|
||||
e, fallback
|
||||
);
|
||||
Some(fallback)
|
||||
}
|
||||
},
|
||||
// Could not fetch the series list: use the current series
|
||||
Some(pkh::changelog::SeriesCandidates::Keep(current)) => Some(current),
|
||||
// No parsable changelog: leave the series decision to
|
||||
// generate_entry
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = generate_entry(
|
||||
let entry = match rt.block_on(pkh::changelog::generate_entry(
|
||||
"debian/changelog",
|
||||
Some(&cwd),
|
||||
version,
|
||||
target_series.as_deref(),
|
||||
) {
|
||||
error!("{}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
kind,
|
||||
)) {
|
||||
Ok(entry) => entry,
|
||||
Err(e) => {
|
||||
error!("{}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"Found package: {}, version: {}",
|
||||
entry.package, entry.previous_version
|
||||
);
|
||||
println!("New version: {}", entry.new_version);
|
||||
println!("Added new changelog entry to {}", entry.path.display());
|
||||
|
||||
let editor = match std::env::var("EDITOR") {
|
||||
Ok(e) => e,
|
||||
@@ -452,33 +662,84 @@ fn main() {
|
||||
}
|
||||
Some(("build", sub_matches)) => {
|
||||
let cwd = current_dir_or_exit();
|
||||
interrupt::install();
|
||||
let verbose = sub_matches
|
||||
.get_one::<bool>("verbose")
|
||||
.copied()
|
||||
.unwrap_or(false);
|
||||
|
||||
// Live build view: disabled by --verbose or when stdout is not a
|
||||
// terminal (DebUi handles the non-TTY case itself)
|
||||
let ui = if verbose {
|
||||
// Live build view, unless --verbose (DebUi additionally disables
|
||||
// itself when stdout is not a terminal)
|
||||
let quiet = pkh::report::Quiet;
|
||||
let live = if verbose {
|
||||
None
|
||||
} else {
|
||||
Some(std::sync::Arc::new(pkh::ui::deb::DebUi::new(&multi)))
|
||||
Some(pkh::ui::deb::DebUi::new(&multi))
|
||||
};
|
||||
let view: &dyn pkh::report::BuildView = live
|
||||
.as_ref()
|
||||
.map(|v| v as &dyn pkh::report::BuildView)
|
||||
.unwrap_or(&quiet);
|
||||
let prompter = pkh::ui::prompt::TerminalPrompter;
|
||||
|
||||
let orig_source = match sub_matches.get_one::<String>("orig").map(String::as_str) {
|
||||
Some("always") => pkh::build::OrigSourceMode::Always,
|
||||
Some("never") => pkh::build::OrigSourceMode::Never,
|
||||
_ => pkh::build::OrigSourceMode::Auto,
|
||||
};
|
||||
|
||||
if let Err(e) = pkh::build::build_source_package(Some(&cwd), ui) {
|
||||
error!("{}", e);
|
||||
// Unmet build dependencies/conflicts exit with status 3,
|
||||
// like dpkg-buildpackage does.
|
||||
if e.downcast_ref::<pkh::debian::deps::UnmetBuildDependencies>()
|
||||
.is_some()
|
||||
{
|
||||
std::process::exit(3);
|
||||
match pkh::build::build_source_package(pkh::build::BuildSourceOptions {
|
||||
source: Some(cwd),
|
||||
options: pkh::build::SourceBuildOptions {
|
||||
orig_source,
|
||||
..Default::default()
|
||||
},
|
||||
view,
|
||||
prompter: &prompter,
|
||||
}) {
|
||||
Ok(output) => {
|
||||
// The live view lists the artifacts itself when it
|
||||
// renders; otherwise (verbose mode or non-TTY stdout)
|
||||
// print them as plain lines.
|
||||
if !view.is_enabled() {
|
||||
for artifact in output.artifacts() {
|
||||
println!(" {}", pkh::report::display_path(&artifact));
|
||||
}
|
||||
}
|
||||
if output.signed {
|
||||
println!("Package built and signed successfully!");
|
||||
} else {
|
||||
println!("Package built successfully (unsigned).");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// On Ctrl+C the interrupt watchdog owns the shutdown
|
||||
// (see `pkh deb`): park here instead of racing it
|
||||
if pkh::interrupt::interrupted() {
|
||||
interrupt::wait_for_shutdown();
|
||||
}
|
||||
// The unmet-dependency diagnostics first, then the
|
||||
// summary: the exact rendering the flow used to do.
|
||||
if let Some(unmet) =
|
||||
e.downcast_ref::<pkh::debian::deps::UnmetBuildDependencies>()
|
||||
{
|
||||
eprintln!("{}", unmet.0.message());
|
||||
}
|
||||
error!("{}", e);
|
||||
// Unmet build dependencies/conflicts exit with status 3,
|
||||
// like dpkg-buildpackage does.
|
||||
if e.downcast_ref::<pkh::debian::deps::UnmetBuildDependencies>()
|
||||
.is_some()
|
||||
{
|
||||
std::process::exit(3);
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Some(("put", sub_matches)) => {
|
||||
let cwd = current_dir_or_exit();
|
||||
interrupt::install();
|
||||
let ppa = sub_matches.get_one::<String>("ppa").map(|s| s.as_str());
|
||||
let changes = sub_matches
|
||||
.get_one::<String>("changes")
|
||||
@@ -497,41 +758,48 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
};
|
||||
|
||||
let view = pkh::ui::deb::DebUi::new(&multi);
|
||||
let prompter = pkh::ui::prompt::TerminalPrompter;
|
||||
let options = pkh::put::PutOptions {
|
||||
ppa: ppa.to_string(),
|
||||
changes,
|
||||
force,
|
||||
cwd,
|
||||
view: &view,
|
||||
prompter: &prompter,
|
||||
};
|
||||
if let Err(e) = rt.block_on(async { pkh::put::put(&options, &multi).await }) {
|
||||
if let Err(e) = rt.block_on(async { pkh::put::put(&options).await }) {
|
||||
// On Ctrl+C the interrupt watchdog owns the shutdown (see
|
||||
// `pkh deb`): park here instead of racing it
|
||||
if pkh::interrupt::interrupted() {
|
||||
interrupt::wait_for_shutdown();
|
||||
}
|
||||
error!("{}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Some(("deb", sub_matches)) => {
|
||||
let cwd = current_dir_or_exit();
|
||||
let series = sub_matches.get_one::<String>("series").map(|s| s.as_str());
|
||||
let pocket = sub_matches.get_one::<String>("pocket").map(|s| s.as_str());
|
||||
let arch = sub_matches.get_one::<String>("arch").map(|s| s.as_str());
|
||||
let cross = sub_matches.get_one::<bool>("cross").unwrap_or(&false);
|
||||
let ppa: Vec<&str> = sub_matches
|
||||
// Ctrl+C during the build must say what happened and release the
|
||||
// ephemeral chroot instead of dying on the default disposition.
|
||||
// The live view (when enabled) registers its own reporter on top
|
||||
// of this to clear the widget first.
|
||||
interrupt::install();
|
||||
let series = sub_matches.get_one::<String>("series").cloned();
|
||||
let pocket = sub_matches.get_one::<String>("pocket").cloned();
|
||||
let arch = sub_matches.get_one::<String>("arch").cloned();
|
||||
let cross = sub_matches
|
||||
.get_one::<bool>("cross")
|
||||
.copied()
|
||||
.unwrap_or(false);
|
||||
let ppa: Vec<String> = sub_matches
|
||||
.get_many::<String>("ppa")
|
||||
.map(|v| v.map(|s| s.as_str()).collect())
|
||||
.map(|v| v.cloned().collect())
|
||||
.unwrap_or_default();
|
||||
let ppa = if ppa.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(ppa.as_slice())
|
||||
};
|
||||
let inject_packages: Vec<&str> = sub_matches
|
||||
let inject: Vec<String> = sub_matches
|
||||
.get_many::<String>("inject")
|
||||
.map(|v| v.map(|s| s.as_str()).collect())
|
||||
.map(|v| v.cloned().collect())
|
||||
.unwrap_or_default();
|
||||
let inject_packages = if inject_packages.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(inject_packages.as_slice())
|
||||
};
|
||||
let mode: Option<&str> = sub_matches.get_one::<String>("mode").map(|s| s.as_str());
|
||||
let mode: Option<pkh::deb::BuildMode> = match mode {
|
||||
Some("local") => Some(pkh::deb::BuildMode::Local),
|
||||
@@ -550,127 +818,51 @@ fn main() {
|
||||
})
|
||||
});
|
||||
|
||||
// Live build view: disabled by --verbose or when stdout is not a
|
||||
// terminal (DebUi handles the non-TTY case itself)
|
||||
let ui = if verbose {
|
||||
// Live build view, unless --verbose (DebUi additionally disables
|
||||
// itself when stdout is not a terminal)
|
||||
let quiet = pkh::report::Quiet;
|
||||
let live = if verbose {
|
||||
None
|
||||
} else {
|
||||
Some(std::sync::Arc::new(pkh::ui::deb::DebUi::new(&multi)))
|
||||
Some(pkh::ui::deb::DebUi::new(&multi))
|
||||
};
|
||||
let view: &dyn pkh::report::BuildView = live
|
||||
.as_ref()
|
||||
.map(|v| v as &dyn pkh::report::BuildView)
|
||||
.unwrap_or(&quiet);
|
||||
|
||||
let result = rt.block_on(async {
|
||||
pkh::deb::build_binary_package(
|
||||
pkh::deb::build_binary_package(pkh::deb::DebBuildOptions {
|
||||
arch,
|
||||
series,
|
||||
pocket,
|
||||
Some(cwd.as_path()),
|
||||
*cross,
|
||||
cwd: Some(cwd.clone()),
|
||||
cross,
|
||||
mode,
|
||||
ppa,
|
||||
inject_packages,
|
||||
None,
|
||||
ui.clone(),
|
||||
inject,
|
||||
jobs,
|
||||
)
|
||||
view,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(artifacts) => {
|
||||
let _ = artifacts;
|
||||
info!("Done.");
|
||||
}
|
||||
Ok(_) => info!("Done."),
|
||||
Err(e) => {
|
||||
// On Ctrl+C the interrupt watchdog owns the shutdown: it
|
||||
// has already shown the notice, is releasing the build
|
||||
// resources, and will exit with 130 — park here instead
|
||||
// of racing it with another exit.
|
||||
if pkh::interrupt::interrupted() {
|
||||
interrupt::wait_for_shutdown();
|
||||
}
|
||||
error!("{}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(("context", sub_matches)) => {
|
||||
let mgr = pkh::context::manager();
|
||||
|
||||
match sub_matches.subcommand() {
|
||||
Some(("create", args)) => {
|
||||
let name = args.get_one::<String>("name").unwrap();
|
||||
let type_str = args
|
||||
.get_one::<String>("type")
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("local");
|
||||
|
||||
let context = match type_str {
|
||||
"local" => ContextConfig::Local,
|
||||
"ssh" => {
|
||||
let endpoint =
|
||||
args.get_one::<String>("endpoint").unwrap_or_else(|| {
|
||||
error!(
|
||||
"An --endpoint is required to create an ssh context. \
|
||||
Expected format: [ssh://][user@]host[:port]"
|
||||
);
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
// Parse host, user, port from endpoint
|
||||
// Formats: [ssh://][user@]host[:port]
|
||||
let endpoint_re = regex::Regex::new(r"^(?:ssh://)?(?:(?P<user>[^@]+)@)?(?P<host>[^:/]+)(?::(?P<port>\d+))?$").unwrap();
|
||||
let endpoint_cap = endpoint_re.captures(endpoint).unwrap_or_else(|| {
|
||||
error!("Invalid endpoint format: '{}'. Expected [ssh://][user@]host[:port]", endpoint);
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let host = endpoint_cap.name("host").unwrap().as_str().to_string();
|
||||
let user = endpoint_cap.name("user").map(|m| m.as_str().to_string());
|
||||
let port = endpoint_cap.name("port").map(|m| {
|
||||
m.as_str().parse::<u16>().unwrap_or_else(|_| {
|
||||
error!("Invalid port number");
|
||||
std::process::exit(1);
|
||||
})
|
||||
});
|
||||
|
||||
ContextConfig::Ssh { host, user, port }
|
||||
}
|
||||
_ => {
|
||||
error!("Unknown context type: {}", type_str);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = mgr.add_context(name, context) {
|
||||
error!("Failed to create context: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
info!("Context '{}' created.", name);
|
||||
}
|
||||
Some(("rm", args)) => {
|
||||
let name = args.get_one::<String>("name").unwrap();
|
||||
if let Err(e) = mgr.remove_context(name) {
|
||||
error!("Failed to remove context: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
info!("Context '{}' removed.", name);
|
||||
}
|
||||
Some(("ls", _)) => {
|
||||
let contexts = mgr.list_contexts();
|
||||
let current = mgr.current_name();
|
||||
for ctx in contexts {
|
||||
if ctx == current {
|
||||
println!("* {}", ctx);
|
||||
} else {
|
||||
println!(" {}", ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(("show", _)) => {}
|
||||
Some(("use", args)) => {
|
||||
let name = args.get_one::<String>("name").unwrap();
|
||||
if let Err(e) = mgr.set_current(name) {
|
||||
error!("Failed to set context: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
info!("Switched to context '{}'.", name);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
Some(("prune", sub_matches)) => {
|
||||
let dry_run = sub_matches
|
||||
.get_one::<bool>("dry_run")
|
||||
@@ -723,6 +915,130 @@ fn main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(("lint", sub_matches)) => {
|
||||
if sub_matches.get_flag("list_tags") {
|
||||
print!("{}", pkh::lint::list_tags());
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
let path = sub_matches
|
||||
.get_one::<String>("path")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(current_dir_or_exit);
|
||||
let fail_on = match pkh::lint::output::parse_fail_on(
|
||||
sub_matches
|
||||
.get_one::<String>("fail_on")
|
||||
.map(String::as_str)
|
||||
.unwrap_or("error"),
|
||||
) {
|
||||
Ok(levels) => levels,
|
||||
Err(e) => {
|
||||
error!("{}", e);
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let options = pkh::lint::LintOptions {
|
||||
path,
|
||||
native: sub_matches.get_flag("native"),
|
||||
fail_on,
|
||||
info: sub_matches.get_flag("info"),
|
||||
display_info: sub_matches.get_flag("display_info"),
|
||||
pedantic: sub_matches.get_flag("pedantic"),
|
||||
experimental: sub_matches.get_flag("experimental"),
|
||||
show_overrides: sub_matches.get_flag("show_overrides"),
|
||||
suppress_tags: sub_matches
|
||||
.get_one::<String>("suppress_tags")
|
||||
.map(|list| {
|
||||
list.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|tag| !tag.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
only_checks: sub_matches
|
||||
.get_many::<String>("check")
|
||||
.map(|values| values.cloned().collect())
|
||||
.unwrap_or_default(),
|
||||
repack: sub_matches.get_flag("repack"),
|
||||
json: sub_matches.get_flag("json"),
|
||||
color: match sub_matches.get_one::<String>("color").map(String::as_str) {
|
||||
Some("always") => pkh::lint::output::ColorMode::Always,
|
||||
Some("never") => pkh::lint::output::ColorMode::Never,
|
||||
_ => pkh::lint::output::ColorMode::Auto,
|
||||
},
|
||||
dist: sub_matches.get_one::<String>("dist").cloned(),
|
||||
series: sub_matches.get_one::<String>("series").cloned(),
|
||||
};
|
||||
|
||||
match pkh::lint::run(&options) {
|
||||
Ok(report) => {
|
||||
if options.json {
|
||||
println!("{}", pkh::lint::output::render_json(&report, &options));
|
||||
} else {
|
||||
print!("{}", pkh::lint::output::render_text(&report, &options));
|
||||
}
|
||||
std::process::exit(pkh::lint::output::exit_code(&report, &options));
|
||||
}
|
||||
Err(e) => {
|
||||
error!("{}", e);
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::interrupt;
|
||||
|
||||
/// End-to-end check of the whole sequence: installed handler → self-pipe
|
||||
/// → watchdog → notice + hooks → exit status 130. The sequence ends in
|
||||
/// `libc::_exit`, so it cannot be exercised in-process: this test
|
||||
/// re-spawns the test binary in child mode (env var), where the test
|
||||
/// installs the handler and raises SIGINT at itself.
|
||||
#[test]
|
||||
fn sigint_sequence_prints_the_notice_and_exits_130() {
|
||||
const CHILD_ENV: &str = "PKH_SIGINT_TEST_CHILD";
|
||||
if std::env::var(CHILD_ENV).is_ok() {
|
||||
// Child mode: install, register a pending hook, then interrupt
|
||||
// ourselves. If the sequence never runs, the sleep below turns
|
||||
// the failure into a wrong (zero) exit code instead of a hang.
|
||||
interrupt::install();
|
||||
// Alive until the watchdog drains it: a dropped guard would
|
||||
// deregister the hook and the drain would run empty
|
||||
let _hook = pkh::interrupt::register_cleanup_hook(Box::new(|| ()));
|
||||
// SAFETY: kill(2) to our own process with SIGINT
|
||||
unsafe {
|
||||
libc::kill(libc::getpid(), libc::SIGINT);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
let exe = std::env::current_exe().expect("locate the test executable");
|
||||
let output = std::process::Command::new(exe)
|
||||
// --nocapture: libtest's capture buffer would otherwise swallow
|
||||
// the watchdog's notice (threads spawned during a test inherit
|
||||
// the capture), and the process exits before the harness prints
|
||||
// anything it captured
|
||||
.args([
|
||||
"--exact",
|
||||
"tests::sigint_sequence_prints_the_notice_and_exits_130",
|
||||
"--test-threads=1",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_ENV, "1")
|
||||
.output()
|
||||
.expect("re-spawn the test binary");
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(output.status.code(), Some(130), "child stderr:\n{stderr}");
|
||||
assert!(
|
||||
stderr.contains("CTRL+C: Build interrupted by user."),
|
||||
"child stderr:\n{stderr}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+192
-58
@@ -12,17 +12,23 @@ use chrono::Datelike;
|
||||
use tar::Builder;
|
||||
use xz2::write::XzEncoder;
|
||||
|
||||
use super::options::NewOptions;
|
||||
use super::options::{NewOptions, SourceFormat};
|
||||
use super::templates::{OutputFile, Template};
|
||||
|
||||
/// `3.0 (quilt)` source format, the pkh new default.
|
||||
/// `3.0 (quilt)` source format, the default when packaging an existing
|
||||
/// project.
|
||||
pub const SOURCE_FORMAT_QUILT: &str = "3.0 (quilt)";
|
||||
/// `3.0 (native)` source format, selected by `--native`.
|
||||
/// `3.0 (native)` source format, the default for a fresh skeleton.
|
||||
pub const SOURCE_FORMAT_NATIVE: &str = "3.0 (native)";
|
||||
|
||||
/// The three source formats pkh knows how to build.
|
||||
pub const KNOWN_SOURCE_FORMATS: [&str; 3] = [SOURCE_FORMAT_QUILT, SOURCE_FORMAT_NATIVE, "1.0"];
|
||||
|
||||
/// Current Debian Policy version, written as the `Standards-Version` of the
|
||||
/// generated `debian/control` (mandatory in the source stanza per policy).
|
||||
/// Bump as policy evolves.
|
||||
pub const DEBIAN_POLICY_VERSION: &str = "4.7.4";
|
||||
|
||||
/// Directory and file names excluded from the orig tarball, at any depth of
|
||||
/// the tree.
|
||||
const ORIG_EXCLUDE: &[&str] = &[
|
||||
@@ -45,7 +51,7 @@ pub fn orig_tarball_path(
|
||||
}
|
||||
|
||||
/// Render every common `debian/` file of the package.
|
||||
pub fn files(opts: &NewOptions, template: &dyn Template) -> Vec<OutputFile> {
|
||||
pub fn files(opts: &NewOptions, template: &Template) -> Vec<OutputFile> {
|
||||
let mut files = vec![
|
||||
source_format(opts),
|
||||
changelog(opts),
|
||||
@@ -54,7 +60,7 @@ pub fn files(opts: &NewOptions, template: &dyn Template) -> Vec<OutputFile> {
|
||||
copyright(opts),
|
||||
debian_gitignore(opts),
|
||||
];
|
||||
if !opts.native {
|
||||
if opts.source_format == SourceFormat::Quilt {
|
||||
files.push(local_options());
|
||||
}
|
||||
if opts.autopkgtest {
|
||||
@@ -89,27 +95,31 @@ fn autopkgtest_smoke(opts: &NewOptions) -> OutputFile {
|
||||
)
|
||||
}
|
||||
|
||||
/// `debian/source/format`: `3.0 (quilt)` by default, `3.0 (native)` with
|
||||
/// `--native`.
|
||||
/// `debian/source/format`: `3.0 (native)` for a skeleton by default,
|
||||
/// `3.0 (quilt)` for an existing project; either can be forced with
|
||||
/// `--native` / `--quilt`.
|
||||
fn source_format(opts: &NewOptions) -> OutputFile {
|
||||
OutputFile::new(
|
||||
"debian/source/format",
|
||||
format!(
|
||||
"{}\n",
|
||||
if opts.native {
|
||||
SOURCE_FORMAT_NATIVE
|
||||
} else {
|
||||
SOURCE_FORMAT_QUILT
|
||||
}
|
||||
),
|
||||
format!("{}\n", opts.source_format.deb_string()),
|
||||
)
|
||||
}
|
||||
|
||||
/// `debian/source/local-options` with `single-debian-patch`, so later
|
||||
/// upstream-tree edits stay representable as one `debian/patches/debian-changes-*`
|
||||
/// patch instead of failing the build (quilt only).
|
||||
/// patch instead of failing the build (quilt only). Common build-output
|
||||
/// directories are excluded from the delta as well: compiling locally before
|
||||
/// a source build must not turn `target/`, `node_modules/` or `.venv/`
|
||||
/// binaries into unrepresentable changes (dpkg ignores `__pycache__` and
|
||||
/// friends by default, but not those).
|
||||
fn local_options() -> OutputFile {
|
||||
OutputFile::new("debian/source/local-options", "single-debian-patch\n")
|
||||
OutputFile::new(
|
||||
"debian/source/local-options",
|
||||
"single-debian-patch\n\
|
||||
extend-diff-ignore = ^target/\n\
|
||||
extend-diff-ignore = ^node_modules/\n\
|
||||
extend-diff-ignore = ^\\.venv/\n",
|
||||
)
|
||||
}
|
||||
|
||||
/// `debian/changelog`: the single initial entry, distribution UNRELEASED by
|
||||
@@ -185,7 +195,7 @@ fn render_continuation_text(text: &str) -> String {
|
||||
/// comes from the template (`all` for shell/empty), and a non-empty
|
||||
/// `opts.depends` (the empty/metapackage flavor) lands in the binary
|
||||
/// stanza's `Depends` field.
|
||||
fn control(opts: &NewOptions, template: &dyn Template) -> OutputFile {
|
||||
fn control(opts: &NewOptions, template: &Template) -> OutputFile {
|
||||
let mut control = String::new();
|
||||
|
||||
// Source stanza.
|
||||
@@ -197,6 +207,7 @@ fn control(opts: &NewOptions, template: &dyn Template) -> OutputFile {
|
||||
opts.maintainer.0, opts.maintainer.1
|
||||
));
|
||||
control.push_str("Rules-Requires-Root: no\n");
|
||||
control.push_str(&format!("Standards-Version: {DEBIAN_POLICY_VERSION}\n"));
|
||||
|
||||
let mut build_depends = vec!["debhelper-compat (= 13)".to_string()];
|
||||
build_depends.extend(template.build_depends(opts));
|
||||
@@ -227,7 +238,7 @@ fn control(opts: &NewOptions, template: &dyn Template) -> OutputFile {
|
||||
/// `debian/rules`: the shebang and `%:` target whose recipe is the
|
||||
/// template's dh line (plus the template's extra overrides, when any),
|
||||
/// written with the executable bit.
|
||||
fn rules(opts: &NewOptions, template: &dyn Template) -> OutputFile {
|
||||
fn rules(opts: &NewOptions, template: &Template) -> OutputFile {
|
||||
let mut contents = format!("#!/usr/bin/make -f\n%:\n\t{}\n", template.rules_dh_line());
|
||||
let extra = template.rules_extra(opts);
|
||||
if !extra.is_empty() {
|
||||
@@ -295,17 +306,19 @@ fn copyright(opts: &NewOptions) -> OutputFile {
|
||||
OutputFile::new("debian/copyright", out)
|
||||
}
|
||||
|
||||
/// `debian/.gitignore`: the debhelper build artifacts.
|
||||
/// `debian/.gitignore`: the debhelper build artifacts. The patterns are
|
||||
/// relative to `debian/` itself (a `debian/`-prefixed pattern would be
|
||||
/// anchored to `debian/debian/` inside this file, per gitignore(5)).
|
||||
fn debian_gitignore(opts: &NewOptions) -> OutputFile {
|
||||
OutputFile::new(
|
||||
"debian/.gitignore",
|
||||
format!(
|
||||
"debian/files\n\
|
||||
debian/.debhelper/\n\
|
||||
debian/*.log\n\
|
||||
debian/{}/\n\
|
||||
debian/debhelper-build-stamp\n\
|
||||
debian/*.substvars\n",
|
||||
"files\n\
|
||||
.debhelper/\n\
|
||||
*.log\n\
|
||||
{}/\n\
|
||||
debhelper-build-stamp\n\
|
||||
*.substvars\n",
|
||||
opts.name
|
||||
),
|
||||
)
|
||||
@@ -322,15 +335,25 @@ pub const ROOT_GITIGNORE_ENTRIES: [&str; 6] = [
|
||||
"target/",
|
||||
];
|
||||
|
||||
/// Merge the root `.gitignore` entries into `existing` (the current file
|
||||
/// contents, when there is one): missing entries are appended, an existing
|
||||
/// file is never overwritten just to duplicate entries. Returns the new
|
||||
/// contents, or `None` when nothing has to be written.
|
||||
pub fn merge_root_gitignore(existing: Option<&str>) -> Option<String> {
|
||||
/// Comment heading a root `.gitignore` freshly created by pkh (the skeleton
|
||||
/// build-artifact section).
|
||||
pub const ROOT_GITIGNORE_HEADER: &str = "# pkh build artifacts";
|
||||
|
||||
/// Merge `entries` into the root `.gitignore` contents `existing` (the
|
||||
/// current file contents, when there is one): missing entries are appended,
|
||||
/// an existing file is never overwritten just to duplicate entries. A fresh
|
||||
/// file is headed by the `header` comment when one is given; appending to a
|
||||
/// user file adds bare entries. Returns the new contents, or `None` when
|
||||
/// nothing has to be written.
|
||||
pub fn merge_gitignore_entries(
|
||||
existing: Option<&str>,
|
||||
entries: &[&str],
|
||||
header: Option<&str>,
|
||||
) -> Option<String> {
|
||||
let have: HashSet<&str> = existing
|
||||
.map(|content| content.lines().map(str::trim).collect())
|
||||
.unwrap_or_default();
|
||||
let missing: Vec<&str> = ROOT_GITIGNORE_ENTRIES
|
||||
let missing: Vec<&str> = entries
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|entry| !have.contains(entry))
|
||||
@@ -345,8 +368,11 @@ pub fn merge_root_gitignore(existing: Option<&str>) -> Option<String> {
|
||||
}
|
||||
// Section comment only for a fresh file; appending to a user file adds
|
||||
// bare entries.
|
||||
if existing.is_none() {
|
||||
out.push_str("# pkh build artifacts\n");
|
||||
if existing.is_none()
|
||||
&& let Some(header) = header
|
||||
{
|
||||
out.push_str(header);
|
||||
out.push('\n');
|
||||
}
|
||||
for entry in missing {
|
||||
out.push_str(entry);
|
||||
@@ -363,6 +389,20 @@ pub fn create_orig_tarball(
|
||||
tree: &Path,
|
||||
name: &str,
|
||||
upstream_version: &str,
|
||||
) -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
|
||||
create_orig_tarball_excluding(tree, name, upstream_version, false)
|
||||
}
|
||||
|
||||
/// [`create_orig_tarball`] with the generated `vendor/` directory of a
|
||||
/// vendored rust package excluded from the snapshot: its contents travel in
|
||||
/// the separate `<name>_<uver>.orig-vendor.tar.xz` component instead (see
|
||||
/// [`super::orig`]), so they can be regenerated independently of the
|
||||
/// upstream sources.
|
||||
pub fn create_orig_tarball_excluding(
|
||||
tree: &Path,
|
||||
name: &str,
|
||||
upstream_version: &str,
|
||||
exclude_vendor: bool,
|
||||
) -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
|
||||
let tarball_path = orig_tarball_path(tree, name, upstream_version).ok_or_else(|| {
|
||||
format!(
|
||||
@@ -387,7 +427,8 @@ pub fn create_orig_tarball(
|
||||
let prefix = format!("{name}-{upstream_version}");
|
||||
// The single top-level directory dpkg-source expects.
|
||||
builder.append_dir(&prefix, tree)?;
|
||||
append_tree(&mut builder, tree, &prefix, 0)?;
|
||||
let top_excludes: &[&str] = if exclude_vendor { &["vendor"] } else { &[] };
|
||||
append_tree(&mut builder, tree, &prefix, 0, ORIG_EXCLUDE, top_excludes)?;
|
||||
|
||||
builder
|
||||
.finish()
|
||||
@@ -395,18 +436,21 @@ pub fn create_orig_tarball(
|
||||
|
||||
log::info!(
|
||||
"Created orig tarball {}",
|
||||
crate::ui::display_path(&tarball_path)
|
||||
crate::report::display_path(&tarball_path)
|
||||
);
|
||||
Ok(tarball_path)
|
||||
}
|
||||
|
||||
/// Recursively append `dir` to the archive under `archive_path`, skipping
|
||||
/// the [`ORIG_EXCLUDE`] names and non-regular files.
|
||||
fn append_tree(
|
||||
/// non-regular files, the names of `excludes` at any depth, the `debian/`
|
||||
/// directory and the names of `top_excludes` at the top level (depth 0).
|
||||
pub(crate) fn append_tree(
|
||||
builder: &mut Builder<XzEncoder<std::fs::File>>,
|
||||
dir: &Path,
|
||||
archive_path: &str,
|
||||
depth: usize,
|
||||
excludes: &[&str],
|
||||
top_excludes: &[&str],
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut entries: Vec<std::fs::DirEntry> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
entries.sort_by_key(|entry| entry.file_name());
|
||||
@@ -416,10 +460,10 @@ fn append_tree(
|
||||
let file_name = entry.file_name();
|
||||
let name = file_name.to_string_lossy().into_owned();
|
||||
|
||||
if depth == 0 && name == "debian" {
|
||||
if depth == 0 && (name == "debian" || top_excludes.contains(&name.as_str())) {
|
||||
continue;
|
||||
}
|
||||
if ORIG_EXCLUDE.contains(&name.as_str()) {
|
||||
if excludes.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -428,7 +472,14 @@ fn append_tree(
|
||||
.map_err(|e| format!("cannot stat '{}': {}", path.display(), e))?;
|
||||
if metadata.is_dir() {
|
||||
builder.append_dir(&entry_archive_path, &path)?;
|
||||
append_tree(builder, &path, &entry_archive_path, depth + 1)?;
|
||||
append_tree(
|
||||
builder,
|
||||
&path,
|
||||
&entry_archive_path,
|
||||
depth + 1,
|
||||
excludes,
|
||||
top_excludes,
|
||||
)?;
|
||||
} else if metadata.is_file() {
|
||||
// The mode (including the exec bit) travels through the header.
|
||||
let mut header = tar::Header::new_gnu();
|
||||
@@ -482,7 +533,7 @@ mod tests {
|
||||
fn opts() -> NewOptions {
|
||||
NewOptions {
|
||||
name: "mytool".into(),
|
||||
template: TemplateId::Shell,
|
||||
template: TemplateId::SHELL,
|
||||
source_dir: SourceDir::Skeleton,
|
||||
upstream_version: "0.1.0".into(),
|
||||
revision: 1,
|
||||
@@ -496,7 +547,8 @@ mod tests {
|
||||
series: "resolute".into(),
|
||||
release: false,
|
||||
depends: Vec::new(),
|
||||
native: false,
|
||||
source_format: SourceFormat::Quilt,
|
||||
orig: None,
|
||||
git: true,
|
||||
autopkgtest: false,
|
||||
pkg_config: false,
|
||||
@@ -507,7 +559,7 @@ mod tests {
|
||||
#[test]
|
||||
fn source_format_and_local_options() {
|
||||
let o = opts();
|
||||
let files = super::files(&o, crate::new::templates::get(TemplateId::Shell).unwrap());
|
||||
let files = super::files(&o, crate::new::templates::get(TemplateId::SHELL).unwrap());
|
||||
let find = |path: &str| {
|
||||
files
|
||||
.iter()
|
||||
@@ -518,16 +570,19 @@ mod tests {
|
||||
assert_eq!(find("debian/source/format").contents, "3.0 (quilt)\n");
|
||||
assert_eq!(
|
||||
find("debian/source/local-options").contents,
|
||||
"single-debian-patch\n"
|
||||
"single-debian-patch\n\
|
||||
extend-diff-ignore = ^target/\n\
|
||||
extend-diff-ignore = ^node_modules/\n\
|
||||
extend-diff-ignore = ^\\.venv/\n"
|
||||
);
|
||||
|
||||
let native = NewOptions {
|
||||
native: true,
|
||||
source_format: SourceFormat::Native,
|
||||
..opts()
|
||||
};
|
||||
let files = super::files(
|
||||
&native,
|
||||
crate::new::templates::get(TemplateId::Shell).unwrap(),
|
||||
crate::new::templates::get(TemplateId::SHELL).unwrap(),
|
||||
);
|
||||
assert!(
|
||||
files
|
||||
@@ -587,7 +642,7 @@ mod tests {
|
||||
#[test]
|
||||
fn control_rendering_and_parse() {
|
||||
let o = opts();
|
||||
let control = super::control(&o, crate::new::templates::get(TemplateId::Shell).unwrap());
|
||||
let control = super::control(&o, crate::new::templates::get(TemplateId::SHELL).unwrap());
|
||||
|
||||
// RFC822 continuation: first dep on the field line, the rest indented.
|
||||
assert!(
|
||||
@@ -601,6 +656,10 @@ mod tests {
|
||||
assert_eq!(parsed.source.get("Section"), Some("utils"));
|
||||
assert_eq!(parsed.source.get("Priority"), Some("optional"));
|
||||
assert_eq!(parsed.source.get("Rules-Requires-Root"), Some("no"));
|
||||
assert_eq!(
|
||||
parsed.source.get("Standards-Version"),
|
||||
Some(DEBIAN_POLICY_VERSION)
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.source.get("Homepage"),
|
||||
Some("https://example.com/mytool")
|
||||
@@ -620,7 +679,7 @@ mod tests {
|
||||
homepage: None,
|
||||
..opts()
|
||||
};
|
||||
let control = super::control(&o, crate::new::templates::get(TemplateId::Shell).unwrap());
|
||||
let control = super::control(&o, crate::new::templates::get(TemplateId::SHELL).unwrap());
|
||||
assert!(!control.contents.contains("Homepage:"));
|
||||
let parsed = crate::debian::ControlInfo::parse_content(&control.contents).unwrap();
|
||||
assert!(parsed.source.get("Homepage").is_none());
|
||||
@@ -629,7 +688,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rules_is_executable_minimal_makefile() {
|
||||
let o = opts();
|
||||
let rules = super::rules(&o, crate::new::templates::get(TemplateId::Shell).unwrap());
|
||||
let rules = super::rules(&o, crate::new::templates::get(TemplateId::SHELL).unwrap());
|
||||
assert!(rules.executable);
|
||||
assert_eq!(rules.contents, "#!/usr/bin/make -f\n%:\n\tdh $@\n");
|
||||
}
|
||||
@@ -642,7 +701,7 @@ mod tests {
|
||||
"version=4\nhttps://github.com/example/mytool/releases .*/v?@ANY_VERSION@\\.tar\\.gz\n"
|
||||
.to_string(),
|
||||
);
|
||||
let files = super::files(&o, crate::new::templates::get(TemplateId::Shell).unwrap());
|
||||
let files = super::files(&o, crate::new::templates::get(TemplateId::SHELL).unwrap());
|
||||
let find = |path: &str| {
|
||||
files
|
||||
.iter()
|
||||
@@ -672,7 +731,7 @@ mod tests {
|
||||
// Without the extras none of the files are rendered.
|
||||
let plain = super::files(
|
||||
&opts(),
|
||||
crate::new::templates::get(TemplateId::Shell).unwrap(),
|
||||
crate::new::templates::get(TemplateId::SHELL).unwrap(),
|
||||
);
|
||||
assert!(!plain.iter().any(|f| f.path.starts_with("debian/tests")));
|
||||
assert!(!plain.iter().any(|f| f.path == "debian/watch"));
|
||||
@@ -709,23 +768,36 @@ mod tests {
|
||||
let g = super::debian_gitignore(&opts());
|
||||
assert_eq!(
|
||||
g.contents,
|
||||
"debian/files\ndebian/.debhelper/\ndebian/*.log\ndebian/mytool/\n\
|
||||
debian/debhelper-build-stamp\ndebian/*.substvars\n"
|
||||
"files\n.debhelper/\n*.log\nmytool/\n\
|
||||
debhelper-build-stamp\n*.substvars\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_gitignore_merge() {
|
||||
fn gitignore_merge() {
|
||||
// Fresh file: header + all entries.
|
||||
let fresh = merge_root_gitignore(None).unwrap();
|
||||
let fresh =
|
||||
merge_gitignore_entries(None, &ROOT_GITIGNORE_ENTRIES, Some(ROOT_GITIGNORE_HEADER))
|
||||
.unwrap();
|
||||
assert!(fresh.starts_with("# pkh build artifacts\n"));
|
||||
for entry in ROOT_GITIGNORE_ENTRIES {
|
||||
assert!(fresh.contains(entry), "{entry} missing");
|
||||
}
|
||||
|
||||
// A fresh file without a header carries the bare entries.
|
||||
assert_eq!(
|
||||
merge_gitignore_entries(None, &["a/", "b"], None).unwrap(),
|
||||
"a/\nb\n"
|
||||
);
|
||||
|
||||
// Existing file: only the missing entries are appended, nothing lost.
|
||||
let existing = "*.deb\nnode_modules/\n";
|
||||
let merged = merge_root_gitignore(Some(existing)).unwrap();
|
||||
let merged = merge_gitignore_entries(
|
||||
Some(existing),
|
||||
&ROOT_GITIGNORE_ENTRIES,
|
||||
Some(ROOT_GITIGNORE_HEADER),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(merged.starts_with(existing));
|
||||
assert!(merged.contains("*.dsc\n"));
|
||||
assert!(!merged.contains("*.deb\n*.deb"));
|
||||
@@ -735,7 +807,31 @@ mod tests {
|
||||
.iter()
|
||||
.map(|e| format!("{e}\n"))
|
||||
.collect();
|
||||
assert!(merge_root_gitignore(Some(&full)).is_none());
|
||||
assert!(
|
||||
merge_gitignore_entries(
|
||||
Some(&full),
|
||||
&ROOT_GITIGNORE_ENTRIES,
|
||||
Some(ROOT_GITIGNORE_HEADER),
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
/// The vendoring entries of the rust template merge into an existing
|
||||
/// user `.gitignore` like any other entry set: appended after the
|
||||
/// user's lines, no header comment, idempotent.
|
||||
#[test]
|
||||
fn gitignore_merge_appends_template_entries() {
|
||||
let entries = ["vendor/", ".cargo/config.toml"];
|
||||
let merged =
|
||||
merge_gitignore_entries(Some("# my project\n*.log\n"), &entries, None).unwrap();
|
||||
assert_eq!(merged, "# my project\n*.log\nvendor/\n.cargo/config.toml\n");
|
||||
|
||||
// Already ignored: nothing to write.
|
||||
assert!(
|
||||
merge_gitignore_entries(Some("vendor/\n.cargo/config.toml\n"), &entries, None)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -789,6 +885,44 @@ mod tests {
|
||||
assert!(err.to_string().contains("already exists"));
|
||||
}
|
||||
|
||||
/// The vendored-rust variant excludes the top-level `vendor/` (it
|
||||
/// travels in the orig-vendor component) but keeps unrelated trees.
|
||||
#[test]
|
||||
fn orig_tarball_vendor_exclusion() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tree = dir.path().join("mytool");
|
||||
std::fs::create_dir_all(tree.join("vendor/serde/src")).unwrap();
|
||||
std::fs::create_dir_all(tree.join("src/vendor")).unwrap();
|
||||
std::fs::write(tree.join("vendor/serde/src/lib.rs"), "code").unwrap();
|
||||
std::fs::write(tree.join("src/vendor/mod.rs"), "code").unwrap();
|
||||
std::fs::write(tree.join("Cargo.toml"), "[package]").unwrap();
|
||||
|
||||
let tarball = create_orig_tarball_excluding(&tree, "mytool", "0.1.0", true).unwrap();
|
||||
let mut archive = tar::Archive::new(xz2::read::XzDecoder::new(
|
||||
std::fs::File::open(&tarball).unwrap(),
|
||||
));
|
||||
let names: Vec<String> = archive
|
||||
.entries()
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path().unwrap().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
// The generated vendored tree is out...
|
||||
assert!(
|
||||
!names.iter().any(|n| n.starts_with("mytool-0.1.0/vendor")),
|
||||
"{names:?}"
|
||||
);
|
||||
// ...an unrelated nested vendor/ stays in...
|
||||
assert!(
|
||||
names.iter().any(|n| n == "mytool-0.1.0/src/vendor/mod.rs"),
|
||||
"{names:?}"
|
||||
);
|
||||
// ...and normal files are unaffected.
|
||||
assert!(
|
||||
names.iter().any(|n| n == "mytool-0.1.0/Cargo.toml"),
|
||||
"{names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_files_sets_exec_bit_and_parents() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
+61
-91
@@ -4,13 +4,16 @@
|
||||
//! The rule set is deliberately simple and table-driven (highest precedence
|
||||
//! first):
|
||||
//!
|
||||
//! 1. well-known build-system marker files at the top level of the
|
||||
//! directory (`Cargo.toml`, `pyproject.toml`/`setup.py`/`setup.cfg`,
|
||||
//! `meson.build`, `CMakeLists.txt`, `configure.ac`, `go.mod`,
|
||||
//! `Makefile`) — more than one distinct template matching is
|
||||
//! [`Detection::Ambiguous`],
|
||||
//! 1. the `detect.files` marker files declared by the template manifests
|
||||
//! (`data/templates/<id>/manifest.yml`, in registry order: `Cargo.toml`,
|
||||
//! `pyproject.toml`/`setup.py`/`setup.cfg`, `meson.build`,
|
||||
//! `CMakeLists.txt`, `configure.ac`, `go.mod`, `Makefile`) looked for at
|
||||
//! the top level of the directory — more than one distinct template
|
||||
//! matching is [`Detection::Ambiguous`]; templates without markers
|
||||
//! (shell: the single-script heuristic below; empty: never detected)
|
||||
//! declare none,
|
||||
//! 2. otherwise, exactly one top-level script (a `*.sh` file, or a file
|
||||
//! whose first line is a `#!` shebang) → [`TemplateId::Shell`],
|
||||
//! whose first line is a `#!` shebang) → [`TemplateId::SHELL`],
|
||||
//! several scripts or none → nothing,
|
||||
//! 3. otherwise [`Detection::Empty`].
|
||||
//!
|
||||
@@ -23,7 +26,9 @@ use std::path::Path;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use super::licenses;
|
||||
use super::options::TemplateId;
|
||||
use super::templates;
|
||||
|
||||
/// Outcome of the detection.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -37,26 +42,18 @@ pub enum Detection {
|
||||
Empty,
|
||||
}
|
||||
|
||||
/// Marker files per template, in precedence order (see the module docs).
|
||||
const MARKERS: [(TemplateId, &[&str]); 7] = [
|
||||
(TemplateId::Rust, &["Cargo.toml"]),
|
||||
(
|
||||
TemplateId::Python,
|
||||
&["pyproject.toml", "setup.py", "setup.cfg"],
|
||||
),
|
||||
(TemplateId::Meson, &["meson.build"]),
|
||||
(TemplateId::Cmake, &["CMakeLists.txt"]),
|
||||
(TemplateId::Autotools, &["configure.ac"]),
|
||||
(TemplateId::Go, &["go.mod"]),
|
||||
(TemplateId::Makefile, &["Makefile"]),
|
||||
];
|
||||
|
||||
/// Detect the template matching the project in `dir`.
|
||||
/// Detect the template matching the project in `dir`: the manifests'
|
||||
/// marker files in registry order (the detection priority), then the
|
||||
/// shell single-script heuristic.
|
||||
pub fn detect(dir: &Path) -> Detection {
|
||||
let mut hits: Vec<TemplateId> = Vec::new();
|
||||
for (id, markers) in MARKERS {
|
||||
if markers.iter().any(|marker| dir.join(marker).exists()) && !hits.contains(&id) {
|
||||
hits.push(id);
|
||||
for template in templates::all() {
|
||||
let markers = template.detect_files();
|
||||
if !markers.is_empty()
|
||||
&& markers.iter().any(|marker| dir.join(marker).exists())
|
||||
&& !hits.contains(&template.id())
|
||||
{
|
||||
hits.push(template.id());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +64,7 @@ pub fn detect(dir: &Path) -> Detection {
|
||||
}
|
||||
|
||||
if single_script(dir).is_some() {
|
||||
Detection::Single(TemplateId::Shell)
|
||||
Detection::Single(TemplateId::SHELL)
|
||||
} else {
|
||||
Detection::Empty
|
||||
}
|
||||
@@ -109,23 +106,14 @@ fn has_shebang(path: &Path) -> bool {
|
||||
content.starts_with(b"#!")
|
||||
}
|
||||
|
||||
/// License files looked at by [`sniff_license`], in preference order.
|
||||
const LICENSE_FILES: [&str; 5] = [
|
||||
"LICENSE",
|
||||
"LICENSE.md",
|
||||
"LICENSE.txt",
|
||||
"COPYING",
|
||||
"COPYING.txt",
|
||||
];
|
||||
|
||||
/// Sniff the license of the project in `dir` from its `LICENSE`/`COPYING`
|
||||
/// file: an `SPDX-License-Identifier:` line wins, otherwise the text is
|
||||
/// matched against a short list of recognizable licenses (MIT, BSD-2/3,
|
||||
/// Apache-2.0, GPL-2/3, LGPL-2.1/3, ISC). `None` when no license file
|
||||
/// exists or nothing recognizable is found.
|
||||
/// matched against the marker sets of the bundled license table
|
||||
/// (`data/licenses.yml`: MIT, BSD-2/3, Apache-2.0, GPL-2/3, LGPL-2.1/3,
|
||||
/// ISC). `None` when no license file exists or nothing recognizable is
|
||||
/// found.
|
||||
pub fn sniff_license(dir: &Path) -> Option<String> {
|
||||
let content = LICENSE_FILES
|
||||
.iter()
|
||||
let content = licenses::detect_files()
|
||||
.find_map(|name| std::fs::read_to_string(dir.join(name)).ok())
|
||||
// Case variants and suffixes (LICENSE-MIT, LICENCE, cpYING…): the
|
||||
// first top-level file whose name looks like a license notice.
|
||||
@@ -166,43 +154,10 @@ pub fn sniff_license(dir: &Path) -> Option<String> {
|
||||
return Some(id);
|
||||
}
|
||||
|
||||
// The recognizable-license markers live in the bundled table; the
|
||||
// LICENSE_TEXTS test below is their behavioral lock.
|
||||
let text = content.to_ascii_lowercase();
|
||||
if text.contains("apache license") && text.contains("version 2") {
|
||||
return Some("Apache-2.0".to_string());
|
||||
}
|
||||
if text.contains("lesser general public license") {
|
||||
return if text.contains("version 3") && !text.contains("version 2.1") {
|
||||
Some("LGPL-3.0+".to_string())
|
||||
} else {
|
||||
Some("LGPL-2.1+".to_string())
|
||||
};
|
||||
}
|
||||
if text.contains("general public license") {
|
||||
return if text.contains("version 3") {
|
||||
Some("GPL-3.0+".to_string())
|
||||
} else {
|
||||
Some("GPL-2.0+".to_string())
|
||||
};
|
||||
}
|
||||
if text.contains("mit license") || text.contains("permission is hereby granted, free of charge")
|
||||
{
|
||||
return Some("MIT".to_string());
|
||||
}
|
||||
if text.contains("isc license")
|
||||
|| text.contains("permission to use, copy, modify, and/or distribute this software")
|
||||
{
|
||||
return Some("ISC".to_string());
|
||||
}
|
||||
if text.contains("redistribution and use in source and binary forms") {
|
||||
// The third clause (name endorsement) is what sets BSD-3 apart
|
||||
// from BSD-2.
|
||||
return if text.contains("endorse or promote") {
|
||||
Some("BSD-3-Clause".to_string())
|
||||
} else {
|
||||
Some("BSD-2-Clause".to_string())
|
||||
};
|
||||
}
|
||||
None
|
||||
licenses::detect_from_text(&text).map(str::to_string)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -217,15 +172,15 @@ mod tests {
|
||||
#[test]
|
||||
fn marker_files_map_to_templates() {
|
||||
let cases = [
|
||||
("Cargo.toml", TemplateId::Rust),
|
||||
("pyproject.toml", TemplateId::Python),
|
||||
("setup.py", TemplateId::Python),
|
||||
("setup.cfg", TemplateId::Python),
|
||||
("meson.build", TemplateId::Meson),
|
||||
("CMakeLists.txt", TemplateId::Cmake),
|
||||
("configure.ac", TemplateId::Autotools),
|
||||
("go.mod", TemplateId::Go),
|
||||
("Makefile", TemplateId::Makefile),
|
||||
("Cargo.toml", TemplateId::RUST),
|
||||
("pyproject.toml", TemplateId::PYTHON),
|
||||
("setup.py", TemplateId::PYTHON),
|
||||
("setup.cfg", TemplateId::PYTHON),
|
||||
("meson.build", TemplateId::MESON),
|
||||
("CMakeLists.txt", TemplateId::CMAKE),
|
||||
("configure.ac", TemplateId::AUTOTOOLS),
|
||||
("go.mod", TemplateId::GO),
|
||||
("Makefile", TemplateId::MAKEFILE),
|
||||
];
|
||||
for (marker, expected) in cases {
|
||||
let dir = tempdir().unwrap();
|
||||
@@ -241,21 +196,21 @@ mod tests {
|
||||
touch(dir.path(), "Makefile");
|
||||
assert_eq!(
|
||||
detect(dir.path()),
|
||||
Detection::Ambiguous(vec![TemplateId::Rust, TemplateId::Makefile])
|
||||
Detection::Ambiguous(vec![TemplateId::RUST, TemplateId::MAKEFILE])
|
||||
);
|
||||
|
||||
let dir = tempdir().unwrap();
|
||||
touch(dir.path(), "pyproject.toml");
|
||||
touch(dir.path(), "setup.py");
|
||||
// Both markers map to the same template: one hit, not ambiguous.
|
||||
assert_eq!(detect(dir.path()), Detection::Single(TemplateId::Python));
|
||||
assert_eq!(detect(dir.path()), Detection::Single(TemplateId::PYTHON));
|
||||
|
||||
let dir = tempdir().unwrap();
|
||||
touch(dir.path(), "meson.build");
|
||||
touch(dir.path(), "CMakeLists.txt");
|
||||
assert_eq!(
|
||||
detect(dir.path()),
|
||||
Detection::Ambiguous(vec![TemplateId::Meson, TemplateId::Cmake])
|
||||
Detection::Ambiguous(vec![TemplateId::MESON, TemplateId::CMAKE])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -264,12 +219,12 @@ mod tests {
|
||||
// .sh extension.
|
||||
let dir = tempdir().unwrap();
|
||||
touch(dir.path(), "run.sh");
|
||||
assert_eq!(detect(dir.path()), Detection::Single(TemplateId::Shell));
|
||||
assert_eq!(detect(dir.path()), Detection::Single(TemplateId::SHELL));
|
||||
|
||||
// Shebang without extension.
|
||||
let dir = tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("run"), "#!/usr/bin/env python3\n").unwrap();
|
||||
assert_eq!(detect(dir.path()), Detection::Single(TemplateId::Shell));
|
||||
assert_eq!(detect(dir.path()), Detection::Single(TemplateId::SHELL));
|
||||
|
||||
// Two scripts: not exactly one, nothing recognized.
|
||||
let dir = tempdir().unwrap();
|
||||
@@ -302,8 +257,10 @@ mod tests {
|
||||
assert_eq!(detect(dir.path()), Detection::Empty);
|
||||
}
|
||||
|
||||
/// Distinctive (shortened) excerpts of the recognizable license texts.
|
||||
const LICENSE_TEXTS: [(&str, &str); 9] = [
|
||||
/// Distinctive (shortened) excerpts of the recognizable license texts:
|
||||
/// the behavioral lock of the marker sets in `data/licenses.yml` — a
|
||||
/// bad marker edit fails here, not on real packages.
|
||||
const LICENSE_TEXTS: [(&str, &str); 11] = [
|
||||
(
|
||||
"MIT",
|
||||
"MIT License\n\nPermission is hereby granted, free of charge, to any person",
|
||||
@@ -337,6 +294,19 @@ mod tests {
|
||||
"ISC",
|
||||
"ISC License\nPermission to use, copy, modify, and/or distribute this software",
|
||||
),
|
||||
// Dual-licensed preamble: the GPL reference outranks the MIT
|
||||
// boilerplate, like the old hardcoded cascade decided.
|
||||
(
|
||||
"GPL-2.0+",
|
||||
"MIT License\n\nAlternatively, under the terms of the GNU General Public License,\
|
||||
\nversion 2 of the License.",
|
||||
),
|
||||
// LGPL text naming both versions: the 2.1 wording wins.
|
||||
(
|
||||
"LGPL-2.1+",
|
||||
"GNU LESSER GENERAL PUBLIC LICENSE\nVersion 2.1, February 1999\n\
|
||||
This is version 2.1; version 3 is available separately.",
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -28,6 +28,23 @@ pub fn ensure_repository(dir: &Path, init: bool) -> Result<bool, Box<dyn std::er
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `dir` sits inside a git work tree (its own or a parent's), in the
|
||||
/// spirit of `git rev-parse --is-inside-work-tree` (like
|
||||
/// [`crate::new::origin::GitOrigin::detect`]). Fail-soft: when `git` cannot
|
||||
/// be run or the probe fails, `dir` counts as outside — the caller keeps the
|
||||
/// behavior it would have without the probe, and the scaffold-time
|
||||
/// repository discovery in [`ensure_repository`] has the final word anyway.
|
||||
pub fn inside_work_tree(dir: &Path) -> bool {
|
||||
let Ok(output) = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--is-inside-work-tree"])
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "true"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -61,4 +78,22 @@ mod tests {
|
||||
assert!(!ensure_repository(&sub, true).unwrap());
|
||||
assert!(!sub.join(".git").exists());
|
||||
}
|
||||
|
||||
/// The probe answers like `git rev-parse --is-inside-work-tree`:
|
||||
/// outside any repository it says no, inside one (at any depth, as a
|
||||
/// skeleton mode scaffold would probe through its parent directory) it
|
||||
/// says yes without touching the tree.
|
||||
#[test]
|
||||
fn inside_work_tree_follows_the_parent_repository() {
|
||||
let dir = tempdir().unwrap();
|
||||
assert!(!inside_work_tree(dir.path()));
|
||||
|
||||
git2::Repository::init(dir.path()).unwrap();
|
||||
assert!(inside_work_tree(dir.path()));
|
||||
|
||||
let sub = dir.path().join("sub");
|
||||
std::fs::create_dir(&sub).unwrap();
|
||||
assert!(inside_work_tree(&sub));
|
||||
assert!(!sub.join(".git").exists());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
//! License reference data for `pkh new`, bundled as `data/licenses.yml`.
|
||||
//!
|
||||
//! The license knowledge of the scaffolder used to live in three places —
|
||||
//! the wizard menu (`questions.rs`), the parse/SPDX mapping (`options.rs`)
|
||||
//! and the license-file sniffing inputs (`detect.rs`) — kept in sync by
|
||||
//! comments only. It is one table now: [`entries`] carries each curated
|
||||
//! license's menu label, accepted spellings and detection markers,
|
||||
//! [`detect_files`] the candidate license file names and [`url_template`]
|
||||
//! the SPDX page URL template, so the lists cannot drift apart and adding
|
||||
//! a license is a YAML entry.
|
||||
//!
|
||||
//! The `License` enum stays in `options.rs` (`NewOptions` and the template
|
||||
//! rendering match on its variants); the enum's variants and the table's
|
||||
//! ids are locked together by a consistency test there. The free-text
|
||||
//! "Other (enter a SPDX identifier)" wizard entry is UX, not data, and
|
||||
//! stays in Rust — like `License::Custom`'s code-driven parse path.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::data::embed_data;
|
||||
|
||||
/// One marker set of the license-text sniff: the set matches when every
|
||||
/// marker of `all` occurs in the lowercased license text and none of
|
||||
/// `unless` does (all-markers-within-a-list, any-marker-list semantics).
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct DetectMarkerSet {
|
||||
/// Substrings that must all occur in the license text
|
||||
pub(crate) all: Vec<String>,
|
||||
/// Substrings that must all be absent for the set to match
|
||||
#[serde(default)]
|
||||
pub(crate) unless: Vec<String>,
|
||||
}
|
||||
|
||||
/// One curated license of the bundled table: everything `pkh new` knows
|
||||
/// about it — identifier, menu label, accepted spellings and sniff markers
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct LicenseEntry {
|
||||
/// SPDX identifier: written to `debian/copyright`, returned by the
|
||||
/// license sniff, substituted into [`url_template`]
|
||||
pub(crate) id: String,
|
||||
/// Label offered by the wizard license menu
|
||||
pub(crate) menu: String,
|
||||
/// Inputs accepted by `License::parse` (case-insensitive); must
|
||||
/// include the id itself
|
||||
pub(crate) spellings: Vec<String>,
|
||||
/// Marker sets of the license-text sniff (see [`detect_from_text`])
|
||||
pub(crate) detect_markers: Vec<DetectMarkerSet>,
|
||||
}
|
||||
|
||||
/// The bundled license table (`data/licenses.yml`): the curated licenses
|
||||
/// plus the shared sniffing inputs and the SPDX URL template
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct LicensesData {
|
||||
/// SPDX license page URL template (`{id}` placeholder)
|
||||
license_url_template: String,
|
||||
/// Candidate license file names of the sniff, in preference order
|
||||
detect_files: Vec<String>,
|
||||
/// The curated licenses, in wizard-menu order
|
||||
licenses: Vec<LicenseEntry>,
|
||||
}
|
||||
|
||||
embed_data! {
|
||||
static ref LICENSES_DATA: LicensesData = "../../data/licenses.yml"
|
||||
}
|
||||
|
||||
/// The curated license entries, in the order offered by the wizard menu
|
||||
pub(crate) fn entries() -> &'static [LicenseEntry] {
|
||||
&LICENSES_DATA.licenses
|
||||
}
|
||||
|
||||
/// The entry whose `spellings` contain `input` (case-insensitive): the
|
||||
/// table lookup behind `License::parse`'s curated arm
|
||||
pub(crate) fn entry_for_spelling(input: &str) -> Option<&'static LicenseEntry> {
|
||||
entries().iter().find(|entry| {
|
||||
entry
|
||||
.spellings
|
||||
.iter()
|
||||
.any(|s| s.eq_ignore_ascii_case(input))
|
||||
})
|
||||
}
|
||||
|
||||
/// The candidate license file names looked at by the license sniff, in
|
||||
/// preference order, shared by every license
|
||||
pub(crate) fn detect_files() -> impl Iterator<Item = &'static str> {
|
||||
LICENSES_DATA.detect_files.iter().map(String::as_str)
|
||||
}
|
||||
|
||||
/// The SPDX identifier of the (lowercased) license `text`, `None` when
|
||||
/// nothing is recognizable: the first entry (menu order) with a matching
|
||||
/// marker set wins. The caller lowercases the text; the markers are
|
||||
/// lowercase substrings.
|
||||
pub(crate) fn detect_from_text(text: &str) -> Option<&'static str> {
|
||||
entries()
|
||||
.iter()
|
||||
.find(|entry| markers_match(entry, text))
|
||||
.map(|entry| entry.id.as_str())
|
||||
}
|
||||
|
||||
/// Whether any marker set of `entry` matches `text` (see
|
||||
/// [`DetectMarkerSet`] for the semantics)
|
||||
fn markers_match(entry: &LicenseEntry, text: &str) -> bool {
|
||||
entry.detect_markers.iter().any(|set| {
|
||||
set.all.iter().all(|marker| text.contains(marker))
|
||||
&& set.unless.iter().all(|marker| !text.contains(marker))
|
||||
})
|
||||
}
|
||||
|
||||
/// The SPDX license page URL template of the table, carrying the license
|
||||
/// identifier as an `{id}` placeholder
|
||||
pub(crate) fn url_template() -> &'static str {
|
||||
LICENSES_DATA.license_url_template.as_str()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every entry is menu-ready: non-empty id/menu, at least one spelling
|
||||
/// and one non-empty marker set, and no duplicate ids or menus (the
|
||||
/// wizard select would silently shadow a duplicate menu label).
|
||||
#[test]
|
||||
fn entries_are_well_formed() {
|
||||
assert!(!entries().is_empty());
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
let mut menus: Vec<&str> = Vec::new();
|
||||
for entry in entries() {
|
||||
assert!(!entry.id.is_empty());
|
||||
assert!(!entry.menu.is_empty());
|
||||
assert!(!entry.spellings.is_empty());
|
||||
assert!(
|
||||
!entry.detect_markers.is_empty(),
|
||||
"entry '{}' has no marker set",
|
||||
entry.id
|
||||
);
|
||||
for set in &entry.detect_markers {
|
||||
assert!(
|
||||
!set.all.is_empty(),
|
||||
"entry '{}' has an empty marker set",
|
||||
entry.id
|
||||
);
|
||||
}
|
||||
ids.push(entry.id.as_str());
|
||||
menus.push(entry.menu.as_str());
|
||||
}
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
menus.sort_unstable();
|
||||
menus.dedup();
|
||||
assert_eq!(ids.len(), entries().len(), "duplicate ids");
|
||||
assert_eq!(menus.len(), entries().len(), "duplicate menus");
|
||||
}
|
||||
|
||||
/// The shared sniffing inputs and the URL template: the canonical file
|
||||
/// names in preference order, and a template the spdx_url
|
||||
/// substitution can render.
|
||||
#[test]
|
||||
fn sniff_inputs_and_url_template() {
|
||||
let files: Vec<&str> = detect_files().collect();
|
||||
assert!(!files.is_empty());
|
||||
assert_eq!(files[0], "LICENSE");
|
||||
assert!(files.contains(&"COPYING"));
|
||||
assert!(url_template().starts_with("https://spdx.org/licenses/"));
|
||||
assert!(url_template().contains("{id}"));
|
||||
}
|
||||
|
||||
/// The marker semantics on hand-built texts: every `all` marker must
|
||||
/// occur, every `unless` marker must not, any set of an entry
|
||||
/// suffices, and the sets are mutually exclusive across entries —
|
||||
/// the LGPL/GPL substring relation and the multi-license texts land
|
||||
/// on the same entry the old hardcoded cascade picked.
|
||||
#[test]
|
||||
fn marker_sets_keep_the_old_cascade_results() {
|
||||
// Nothing recognizable.
|
||||
assert_eq!(detect_from_text("do whatever you want"), None);
|
||||
// Version discrimination of the GPL family.
|
||||
assert_eq!(
|
||||
detect_from_text("gnu general public license\nversion 3"),
|
||||
Some("GPL-3.0+")
|
||||
);
|
||||
assert_eq!(
|
||||
detect_from_text("gnu general public license\nversion 2, june 1991"),
|
||||
Some("GPL-2.0+")
|
||||
);
|
||||
// "lesser general public license" contains "general public
|
||||
// license": LGPL texts must stay on their entries.
|
||||
assert_eq!(
|
||||
detect_from_text("gnu lesser general public license\nversion 3"),
|
||||
Some("LGPL-3.0+")
|
||||
);
|
||||
assert_eq!(
|
||||
detect_from_text("gnu lesser general public license\nversion 2.1"),
|
||||
Some("LGPL-2.1+")
|
||||
);
|
||||
// A text naming both versions is the 2.1 wording (version 2.1
|
||||
// wins), like the old unless-less branch pair did.
|
||||
assert_eq!(
|
||||
detect_from_text("gnu lesser general public license\nversion 3, like version 2.1"),
|
||||
Some("LGPL-2.1+")
|
||||
);
|
||||
// Multi-license texts: the GPL/Apache reference is the stronger
|
||||
// one, so MIT does not steal them.
|
||||
assert_eq!(
|
||||
detect_from_text("mit license\nunder the gnu general public license, version 2"),
|
||||
Some("GPL-2.0+")
|
||||
);
|
||||
assert_eq!(
|
||||
detect_from_text(
|
||||
"permission is hereby granted, free of charge\ndual-licensed under the apache license version 2"
|
||||
),
|
||||
Some("Apache-2.0")
|
||||
);
|
||||
// BSD-2 vs BSD-3: the endorsement clause is the discriminator.
|
||||
assert_eq!(
|
||||
detect_from_text("redistribution and use in source and binary forms"),
|
||||
Some("BSD-2-Clause")
|
||||
);
|
||||
assert_eq!(
|
||||
detect_from_text(
|
||||
"redistribution and use in source and binary forms\nmay be used to endorse or promote"
|
||||
),
|
||||
Some("BSD-3-Clause")
|
||||
);
|
||||
}
|
||||
}
|
||||
+356
-137
@@ -3,8 +3,11 @@
|
||||
//!
|
||||
//! This module orchestrates a scaffold run: target directory checks, project
|
||||
//! detection, in-memory rendering of every file (all-or-nothing write), the
|
||||
//! template post-write hook (e.g. `cargo vendor`), orig tarball creation,
|
||||
//! git initialization, structural verification and the next-steps message.
|
||||
//! root `.gitignore` merge (skeleton build artifacts plus the template's own
|
||||
//! entries, e.g. the rust vendored layout), the template post-write hook
|
||||
//! (e.g. `cargo vendor`), orig tarball creation
|
||||
//! (from the origin the run decided on — see [`origin`] and [`orig`]), git
|
||||
//! initialization, structural verification and the next-steps message.
|
||||
//! The interactive wizard ([`questions`]) fills a [`options::NewCli`] from
|
||||
//! its answers on a TTY and reuses [`options::resolve`] as the single source
|
||||
//! of truth for defaults and validation; without a TTY the same resolution
|
||||
@@ -13,7 +16,11 @@
|
||||
pub mod debian;
|
||||
pub mod detect;
|
||||
pub mod git;
|
||||
/// License reference data for the scaffolder (bundled `data/licenses.yml`)
|
||||
pub(crate) mod licenses;
|
||||
pub mod options;
|
||||
pub mod orig;
|
||||
pub mod origin;
|
||||
pub mod questions;
|
||||
pub mod templates;
|
||||
pub mod verify;
|
||||
@@ -23,8 +30,8 @@ use std::time::Duration;
|
||||
|
||||
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
|
||||
|
||||
use options::NewOptions;
|
||||
use templates::OutputFile;
|
||||
use options::{NewOptions, SourceFormat};
|
||||
use templates::{OutputFile, ScaffoldOutcome};
|
||||
|
||||
/// Scaffold a full Debian source tree from `opts`.
|
||||
///
|
||||
@@ -32,15 +39,24 @@ use templates::OutputFile;
|
||||
/// 1. resolve the template from the registry,
|
||||
/// 2. check the target directory (refuse an existing `debian/control`),
|
||||
/// 3. render every file in memory and check for collisions,
|
||||
/// 4. write the files all-or-nothing (plus the root `.gitignore` in skeleton
|
||||
/// mode, appending to an existing one),
|
||||
/// 4. write the files all-or-nothing (plus the root `.gitignore` merge:
|
||||
/// the skeleton build-artifact entries in skeleton mode and the
|
||||
/// template's own entries — rust: the vendored layout — in every mode,
|
||||
/// appending to an existing file),
|
||||
/// 5. run the template post-write hook (e.g. `cargo vendor`, so the vendored
|
||||
/// sources land inside the orig tarball created next),
|
||||
/// 6. create the orig tarball (quilt only, refusing overwrites),
|
||||
/// 7. `git init` unless `--no-git` or already inside a repository,
|
||||
/// 8. run the structural verification,
|
||||
/// 9. print the success message with the next steps.
|
||||
pub fn scaffold(opts: NewOptions, multi: &MultiProgress) -> Result<(), Box<dyn Error>> {
|
||||
///
|
||||
/// On success the [`ScaffoldOutcome`] of the post-write hook is returned, so
|
||||
/// the caller can adapt the end of the flow (e.g. the verification offer)
|
||||
/// to what the templates managed to do.
|
||||
pub fn scaffold(
|
||||
opts: NewOptions,
|
||||
multi: &MultiProgress,
|
||||
) -> Result<ScaffoldOutcome, Box<dyn Error>> {
|
||||
let pb = multi.add(ProgressBar::new_spinner());
|
||||
pb.enable_steady_tick(Duration::from_millis(50));
|
||||
pb.set_style(
|
||||
@@ -57,15 +73,15 @@ pub fn scaffold(opts: NewOptions, multi: &MultiProgress) -> Result<(), Box<dyn E
|
||||
pb.finish_and_clear();
|
||||
multi.remove(&pb);
|
||||
|
||||
if result.is_ok() {
|
||||
print_success(&opts);
|
||||
if let Ok(outcome) = &result {
|
||||
print_success(&opts, outcome);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The scaffold steps proper, reporting progress through `pb`. Nothing is
|
||||
/// written to the filesystem before every file rendered successfully.
|
||||
fn scaffold_steps(opts: &NewOptions, pb: &ProgressBar) -> Result<(), Box<dyn Error>> {
|
||||
fn scaffold_steps(opts: &NewOptions, pb: &ProgressBar) -> Result<ScaffoldOutcome, Box<dyn Error>> {
|
||||
// 1. Template resolution: an id without a registered template fails
|
||||
// here with the friendly message instead of a parse error.
|
||||
let template = templates::get(opts.template).ok_or_else(|| {
|
||||
@@ -120,7 +136,7 @@ fn scaffold_steps(opts: &NewOptions, pb: &ProgressBar) -> Result<(), Box<dyn Err
|
||||
}
|
||||
|
||||
// Fail before writing anything when the orig tarball already exists.
|
||||
if !opts.native
|
||||
if opts.source_format == SourceFormat::Quilt
|
||||
&& let Some(tarball) =
|
||||
debian::orig_tarball_path(&target, &opts.name, &opts.upstream_version_no_epoch())
|
||||
&& tarball.exists()
|
||||
@@ -161,13 +177,25 @@ fn scaffold_steps(opts: &NewOptions, pb: &ProgressBar) -> Result<(), Box<dyn Err
|
||||
pb.set_message("Writing files");
|
||||
debian::write_files(&target, &files)?;
|
||||
|
||||
// Root .gitignore: skeleton mode only, never overwriting an existing
|
||||
// file (append the missing entries instead).
|
||||
if skeleton
|
||||
&& let Some(contents) = debian::merge_root_gitignore(
|
||||
// Root .gitignore: the skeleton build-artifact entries in skeleton
|
||||
// mode, plus the template's own entries (rust: the vendored layout) in
|
||||
// every mode — missing ones appended, an existing file never
|
||||
// overwritten.
|
||||
let template_gitignore = template.gitignore_entries();
|
||||
let mut entries: Vec<&str> = Vec::new();
|
||||
let mut header = None;
|
||||
if skeleton {
|
||||
entries.extend(debian::ROOT_GITIGNORE_ENTRIES);
|
||||
header = Some(debian::ROOT_GITIGNORE_HEADER);
|
||||
}
|
||||
entries.extend(template_gitignore.iter().map(String::as_str));
|
||||
if !entries.is_empty()
|
||||
&& let Some(contents) = debian::merge_gitignore_entries(
|
||||
std::fs::read_to_string(target.join(".gitignore"))
|
||||
.ok()
|
||||
.as_deref(),
|
||||
&entries,
|
||||
header,
|
||||
)
|
||||
{
|
||||
std::fs::write(target.join(".gitignore"), contents)?;
|
||||
@@ -175,14 +203,34 @@ fn scaffold_steps(opts: &NewOptions, pb: &ProgressBar) -> Result<(), Box<dyn Err
|
||||
|
||||
// 5. Template post-write hook: run before the orig tarball is created,
|
||||
// so files added here (rust: vendor/ + .cargo/config.toml) land
|
||||
// inside it.
|
||||
// inside it (or inside the orig-vendor component). The outcome
|
||||
// (e.g. a failed vendoring) is threaded back to the caller.
|
||||
pb.set_message("Running template hooks");
|
||||
template.post_write(opts, &target)?;
|
||||
let mut outcome = template.post_write(opts, &target)?;
|
||||
|
||||
// 6. Orig tarball (quilt only).
|
||||
if !opts.native {
|
||||
// 6. Orig tarball (quilt only), from the origin the run decided on.
|
||||
// A vendored rust tree gets its `vendor/` directory moved into the
|
||||
// separate dpkg upstream component `orig-vendor`, regenerable
|
||||
// independently of the upstream sources (native packages have no
|
||||
// orig at all: vendor/ simply lives in the tree).
|
||||
if opts.source_format == SourceFormat::Quilt {
|
||||
pb.set_message("Creating orig tarball");
|
||||
debian::create_orig_tarball(&target, &opts.name, &opts.upstream_version_no_epoch())?;
|
||||
let vendored_rust =
|
||||
template.id() == options::TemplateId::RUST && orig::has_vendored_dir(&target);
|
||||
let created = orig::create_orig(
|
||||
&target,
|
||||
&opts.name,
|
||||
&opts.upstream_version_no_epoch(),
|
||||
opts.orig
|
||||
.as_ref()
|
||||
.ok_or("internal error: a quilt scaffold needs an orig-tarball plan")?,
|
||||
vendored_rust,
|
||||
)?;
|
||||
outcome.orig_origin = Some(created.label);
|
||||
if vendored_rust {
|
||||
pb.set_message("Creating the orig-vendor component");
|
||||
orig::create_vendor_component(&target, &opts.name, &opts.upstream_version_no_epoch())?;
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Git.
|
||||
@@ -193,21 +241,24 @@ fn scaffold_steps(opts: &NewOptions, pb: &ProgressBar) -> Result<(), Box<dyn Err
|
||||
pb.set_message("Verifying");
|
||||
verify::verify(&target)?;
|
||||
|
||||
Ok(())
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// The success message: what was created and the next steps.
|
||||
fn print_success(opts: &NewOptions) {
|
||||
fn print_success(opts: &NewOptions, outcome: &ScaffoldOutcome) {
|
||||
let target =
|
||||
opts.target_dir(&std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")));
|
||||
// `display_path` yields an empty string when the target is the cwd
|
||||
// itself (Here mode): show it as `.`.
|
||||
let display = match crate::ui::display_path(&target) {
|
||||
display if display.is_empty() => ".".to_string(),
|
||||
display => display,
|
||||
// itself (Here mode): `Created .` would be cryptic, so spell the
|
||||
// location out; the skeleton/path modes keep the `<dir>` display.
|
||||
let display = crate::report::display_path(&target);
|
||||
let location = if display.is_empty() {
|
||||
"package in the current directory".to_string()
|
||||
} else {
|
||||
display.clone()
|
||||
};
|
||||
log::info!(
|
||||
"Created {display} — {} ({}-{}) for {}/{}, template '{}'",
|
||||
"Created {location} — {} ({}-{}) for {}/{}, template '{}'",
|
||||
opts.name,
|
||||
opts.upstream_version,
|
||||
opts.revision,
|
||||
@@ -215,8 +266,11 @@ fn print_success(opts: &NewOptions) {
|
||||
opts.series,
|
||||
opts.template
|
||||
);
|
||||
if let Some(orig_origin) = &outcome.orig_origin {
|
||||
log::info!("Orig tarball: {orig_origin}");
|
||||
}
|
||||
log::info!("Next steps:");
|
||||
log::info!(" cd {display}");
|
||||
log::info!(" cd {}", if display.is_empty() { "." } else { &display });
|
||||
if opts.release {
|
||||
log::info!(
|
||||
" pkh chlog # for later changes; the entry already targets {}",
|
||||
@@ -233,11 +287,19 @@ fn print_success(opts: &NewOptions) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::new::options::{License, SourceDir, TemplateId};
|
||||
use crate::new::options::{License, OrigOrigin, SourceDir, TemplateId};
|
||||
use serial_test::serial;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn opts(template: TemplateId, name: &str, source_dir: SourceDir) -> NewOptions {
|
||||
// Mirror the resolve() derivation: skeletons are native by default,
|
||||
// existing projects quilt with a working-tree snapshot orig.
|
||||
let (source_format, orig) = match source_dir {
|
||||
SourceDir::Skeleton => (SourceFormat::Native, None),
|
||||
SourceDir::Here | SourceDir::Path(_) => {
|
||||
(SourceFormat::Quilt, Some(OrigOrigin::Snapshot))
|
||||
}
|
||||
};
|
||||
NewOptions {
|
||||
name: name.to_string(),
|
||||
template,
|
||||
@@ -254,7 +316,8 @@ mod tests {
|
||||
series: "resolute".into(),
|
||||
release: false,
|
||||
depends: Vec::new(),
|
||||
native: false,
|
||||
source_format,
|
||||
orig,
|
||||
git: false,
|
||||
autopkgtest: false,
|
||||
pkg_config: false,
|
||||
@@ -264,10 +327,18 @@ mod tests {
|
||||
|
||||
/// Run `scaffold` with the cwd changed to `dir` (restored afterwards);
|
||||
/// must run under `#[serial]` because the cwd is process-global.
|
||||
fn scaffold_in(dir: &std::path::Path, opts: NewOptions) -> Result<(), Box<dyn Error>> {
|
||||
fn scaffold_in(
|
||||
dir: &std::path::Path,
|
||||
opts: NewOptions,
|
||||
) -> Result<ScaffoldOutcome, Box<dyn Error>> {
|
||||
let previous = std::env::current_dir()?;
|
||||
std::env::set_current_dir(dir)?;
|
||||
let result = scaffold(opts, &MultiProgress::new());
|
||||
// Hidden draw target: in tests the spinner would redraw from its
|
||||
// steady-tick thread straight to the real stderr
|
||||
let result = scaffold(
|
||||
opts,
|
||||
&MultiProgress::with_draw_target(crate::ui::progress_draw_target()),
|
||||
);
|
||||
std::env::set_current_dir(previous)?;
|
||||
result
|
||||
}
|
||||
@@ -278,7 +349,7 @@ mod tests {
|
||||
let dir = tempdir().unwrap();
|
||||
scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Shell, "mytool", SourceDir::Skeleton),
|
||||
opts(TemplateId::SHELL, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -291,7 +362,6 @@ mod tests {
|
||||
"debian/rules",
|
||||
"debian/copyright",
|
||||
"debian/source/format",
|
||||
"debian/source/local-options",
|
||||
"debian/.gitignore",
|
||||
"debian/install",
|
||||
"mytool.sh",
|
||||
@@ -326,15 +396,14 @@ mod tests {
|
||||
assert_eq!(version, "0.1.0-1");
|
||||
assert_eq!(distribution, "UNRELEASED");
|
||||
|
||||
// source/format + local-options.
|
||||
// A fresh skeleton is 3.0 (native) by default: no local-options and
|
||||
// no orig tarball anywhere.
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(tree.join("debian/source/format")).unwrap(),
|
||||
"3.0 (quilt)\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(tree.join("debian/source/local-options")).unwrap(),
|
||||
"single-debian-patch\n"
|
||||
"3.0 (native)\n"
|
||||
);
|
||||
assert!(!tree.join("debian/source/local-options").exists());
|
||||
assert!(!dir.path().join("mytool_0.1.0.orig.tar.xz").exists());
|
||||
|
||||
// install mapping.
|
||||
assert_eq!(
|
||||
@@ -346,6 +415,31 @@ mod tests {
|
||||
let gitignore = std::fs::read_to_string(tree.join(".gitignore")).unwrap();
|
||||
assert!(gitignore.contains("*.deb"));
|
||||
assert!(gitignore.contains("target/"));
|
||||
}
|
||||
|
||||
/// A skeleton forced to quilt keeps the snapshot behavior: orig tarball
|
||||
/// with the skeleton files, `debian/` excluded, local-options present.
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_skeleton_forced_quilt_snapshots_the_tree() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut o = opts(TemplateId::SHELL, "mytool", SourceDir::Skeleton);
|
||||
o.source_format = SourceFormat::Quilt;
|
||||
o.orig = Some(OrigOrigin::Snapshot);
|
||||
scaffold_in(dir.path(), o).unwrap();
|
||||
|
||||
let tree = dir.path().join("mytool");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(tree.join("debian/source/format")).unwrap(),
|
||||
"3.0 (quilt)\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(tree.join("debian/source/local-options")).unwrap(),
|
||||
"single-debian-patch\n\
|
||||
extend-diff-ignore = ^target/\n\
|
||||
extend-diff-ignore = ^node_modules/\n\
|
||||
extend-diff-ignore = ^\\.venv/\n"
|
||||
);
|
||||
|
||||
// Orig tarball: contains the skeleton file, excludes debian/.
|
||||
let tarball = dir.path().join("mytool_0.1.0.orig.tar.xz");
|
||||
@@ -377,7 +471,7 @@ mod tests {
|
||||
fn scaffold_empty_base_and_metapackage_flavors() {
|
||||
let dir = tempdir().unwrap();
|
||||
// Metapackage flavor: non-empty depends.
|
||||
let mut o = opts(TemplateId::Empty, "metapkg", SourceDir::Skeleton);
|
||||
let mut o = opts(TemplateId::EMPTY, "metapkg", SourceDir::Skeleton);
|
||||
o.depends = vec!["hello".into(), "hello-data (>= 1.0)".into()];
|
||||
scaffold_in(dir.path(), o).unwrap();
|
||||
|
||||
@@ -389,35 +483,17 @@ mod tests {
|
||||
);
|
||||
assert_eq!(control.binaries[0].get("Architecture"), Some("all"));
|
||||
// No install file, no build-system skeleton: the README stub only.
|
||||
// A native skeleton carries no orig tarball: the README simply
|
||||
// lives in the tree.
|
||||
assert!(!tree.join("debian/install").exists());
|
||||
assert!(tree.join("README").exists());
|
||||
// The tarball excludes debian/ but carries the README.
|
||||
let tarball = dir.path().join("metapkg_0.1.0.orig.tar.xz");
|
||||
let mut archive = tar::Archive::new(xz2::read::XzDecoder::new(
|
||||
std::fs::File::open(&tarball).unwrap(),
|
||||
));
|
||||
let names: Vec<String> = archive
|
||||
.entries()
|
||||
.unwrap()
|
||||
.map(|entry| {
|
||||
entry
|
||||
.unwrap()
|
||||
.path()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
names.iter().any(|n| n == "metapkg-0.1.0/README"),
|
||||
"{names:?}"
|
||||
);
|
||||
assert!(!dir.path().join("metapkg_0.1.0.orig.tar.xz").exists());
|
||||
|
||||
// Empty base flavor: no depends, no Depends field.
|
||||
let dir = tempdir().unwrap();
|
||||
scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Empty, "basepkg", SourceDir::Skeleton),
|
||||
opts(TemplateId::EMPTY, "basepkg", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
let control =
|
||||
@@ -429,7 +505,7 @@ mod tests {
|
||||
#[serial]
|
||||
fn scaffold_release_targets_series() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut o = opts(TemplateId::Empty, "released", SourceDir::Skeleton);
|
||||
let mut o = opts(TemplateId::EMPTY, "released", SourceDir::Skeleton);
|
||||
o.release = true;
|
||||
scaffold_in(dir.path(), o).unwrap();
|
||||
|
||||
@@ -449,10 +525,11 @@ mod tests {
|
||||
let tree = dir.path().join("packdir");
|
||||
std::fs::create_dir_all(&tree).unwrap();
|
||||
std::fs::write(tree.join("run.sh"), "#!/bin/sh\necho hi\n").unwrap();
|
||||
scaffold_in(&tree, opts(TemplateId::Shell, "runtool", SourceDir::Here)).unwrap();
|
||||
scaffold_in(&tree, opts(TemplateId::SHELL, "runtool", SourceDir::Here)).unwrap();
|
||||
|
||||
// debian/ lands directly in the directory; no skeleton file, no
|
||||
// root .gitignore (skeleton mode only), no debian/install (the
|
||||
// root .gitignore (the shell template contributes none and the
|
||||
// artifact entries are skeleton-only), no debian/install (the
|
||||
// generated one would reference the non-existent skeleton script),
|
||||
// and the existing script is left alone.
|
||||
assert!(tree.join("debian/control").exists());
|
||||
@@ -497,7 +574,7 @@ mod tests {
|
||||
std::fs::write(tree.join("debian/control"), "Source: mytool\n").unwrap();
|
||||
let err = scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Shell, "mytool", SourceDir::Skeleton),
|
||||
opts(TemplateId::SHELL, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("debian/control"), "{err}");
|
||||
@@ -508,19 +585,18 @@ mod tests {
|
||||
std::fs::write(dir.path().join("mytool/junk"), "x").unwrap();
|
||||
let err = scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Shell, "mytool", SourceDir::Skeleton),
|
||||
opts(TemplateId::SHELL, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("not empty"), "{err}");
|
||||
|
||||
// Existing orig tarball: nothing gets written.
|
||||
// Existing orig tarball (quilt only): nothing gets written.
|
||||
let dir = tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("mytool_0.1.0.orig.tar.xz"), b"old").unwrap();
|
||||
let err = scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Shell, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap_err();
|
||||
let mut o = opts(TemplateId::SHELL, "mytool", SourceDir::Skeleton);
|
||||
o.source_format = SourceFormat::Quilt;
|
||||
o.orig = Some(OrigOrigin::Snapshot);
|
||||
let err = scaffold_in(dir.path(), o).unwrap_err();
|
||||
assert!(err.to_string().contains("already exists"), "{err}");
|
||||
assert!(!dir.path().join("mytool/debian/control").exists());
|
||||
|
||||
@@ -529,7 +605,7 @@ mod tests {
|
||||
let err = scaffold_in(
|
||||
dir.path(),
|
||||
opts(
|
||||
TemplateId::Shell,
|
||||
TemplateId::SHELL,
|
||||
"mytool",
|
||||
SourceDir::Path(dir.path().join("missing")),
|
||||
),
|
||||
@@ -538,13 +614,17 @@ mod tests {
|
||||
assert!(err.to_string().contains("does not exist"), "{err}");
|
||||
}
|
||||
|
||||
/// The skeleton default is `3.0 (native)`: no orig tarball, no
|
||||
/// `debian/source/local-options`.
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_native_skips_tarball_and_local_options() {
|
||||
fn scaffold_skeleton_defaults_to_native() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut o = opts(TemplateId::Shell, "nativepkg", SourceDir::Skeleton);
|
||||
o.native = true;
|
||||
scaffold_in(dir.path(), o).unwrap();
|
||||
scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::SHELL, "nativepkg", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let tree = dir.path().join("nativepkg");
|
||||
assert!(!dir.path().join("nativepkg_0.1.0.orig.tar.xz").exists());
|
||||
@@ -555,31 +635,44 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// End-to-end rust skeleton: the vendoring hook runs before the orig
|
||||
/// tarball is created, so `.cargo/` (and `vendor/` when dependencies
|
||||
/// exist) travel inside it. The vendoring step needs host cargo; on a
|
||||
/// cargo-less host the scaffold still succeeds with a warning.
|
||||
/// End-to-end rust skeleton: the vendoring hook runs over the tree
|
||||
/// (native format: everything simply lives in the tree, no orig
|
||||
/// tarball). The vendoring step needs host cargo; on a cargo-less host
|
||||
/// the scaffold still succeeds with a warning and a `vendoring_failed`
|
||||
/// outcome. Keyed against the `RUSTUP_TOOLCHAIN` tests of the rust
|
||||
/// template: they mutate the process-global environment the cargo shim
|
||||
/// would pick up mid-vendoring.
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_rust_skeleton_vendors_before_tarball() {
|
||||
#[serial(RUSTUP_TOOLCHAIN)]
|
||||
fn scaffold_rust_skeleton_vendors_into_the_tree() {
|
||||
let dir = tempdir().unwrap();
|
||||
scaffold_in(
|
||||
let outcome = scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Rust, "mytool", SourceDir::Skeleton),
|
||||
opts(TemplateId::RUST, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let has_cargo = crate::new::templates::find_on_path("cargo").is_some();
|
||||
assert_eq!(outcome.vendoring_failed, !has_cargo);
|
||||
// Native skeleton: no orig tarball at all.
|
||||
assert_eq!(outcome.orig_origin, None);
|
||||
assert!(!dir.path().join("mytool_0.1.0.orig.tar.xz").exists());
|
||||
|
||||
let tree = dir.path().join("mytool");
|
||||
assert!(tree.join("Cargo.toml").exists());
|
||||
assert!(tree.join("src/main.rs").exists());
|
||||
// The vendoring step is what creates Cargo.lock for a skeleton.
|
||||
assert_eq!(tree.join("Cargo.lock").exists(), has_cargo);
|
||||
|
||||
// rules: the vendored build overrides, no --locked on a fresh
|
||||
// skeleton without Cargo.lock.
|
||||
// rules: the vendored build overrides, and `--locked` exactly when
|
||||
// the vendoring step left a lockfile behind (it appears after the
|
||||
// rules were rendered, so the hook patches it in).
|
||||
let rules = std::fs::read_to_string(tree.join("debian/rules")).unwrap();
|
||||
assert!(rules.contains("%:\n\tdh $@\n"));
|
||||
assert!(rules.contains("override_dh_auto_build:\n\tcargo build --release --offline\n"));
|
||||
assert!(rules.contains("override_dh_auto_build:\n\tcargo build --release --offline"));
|
||||
assert!(rules.contains("override_dh_auto_install:\n\tinstall -Dm755 target/release/mytool debian/mytool/usr/bin/mytool"));
|
||||
assert!(!rules.contains("--locked"));
|
||||
assert_eq!(rules.contains("--locked"), has_cargo);
|
||||
|
||||
// control: Architecture any + the cargo/rustc build-deps.
|
||||
let control = crate::debian::ControlInfo::parse(&tree.join("debian/control")).unwrap();
|
||||
@@ -589,15 +682,94 @@ mod tests {
|
||||
Some("debhelper-compat (= 13),\ncargo:native,\nrustc:native")
|
||||
);
|
||||
|
||||
// The offline config exists when host cargo vendored the skeleton,
|
||||
// and both it and the skeleton land inside the orig tarball.
|
||||
let has_cargo = crate::new::templates::find_on_path("cargo").is_some();
|
||||
// The offline config exists in the tree when host cargo vendored
|
||||
// the skeleton.
|
||||
if has_cargo {
|
||||
let config = std::fs::read_to_string(tree.join(".cargo/config.toml")).unwrap();
|
||||
assert!(config.contains("[source.crates-io]"), "{config}");
|
||||
assert!(config.contains("[net]\noffline = true"), "{config}");
|
||||
}
|
||||
|
||||
// Root .gitignore: the skeleton build-artifact entries plus the
|
||||
// template's vendoring entries (contributed in every mode).
|
||||
let gitignore = std::fs::read_to_string(tree.join(".gitignore")).unwrap();
|
||||
assert!(gitignore.contains("# pkh build artifacts"), "{gitignore}");
|
||||
assert!(gitignore.contains("*.deb"), "{gitignore}");
|
||||
assert!(gitignore.contains("target/"), "{gitignore}");
|
||||
assert!(gitignore.contains("vendor/\n"), "{gitignore}");
|
||||
assert!(gitignore.contains(".cargo/config.toml\n"), "{gitignore}");
|
||||
}
|
||||
|
||||
/// The rust template's vendoring entries land in the root `.gitignore`
|
||||
/// in every mode: a Here-mode tree gets them appended to its existing
|
||||
/// file (custom lines kept, no header comment), while the skeleton-only
|
||||
/// build-artifact entries do not appear.
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_rust_here_merges_vendoring_gitignore_entries() {
|
||||
let dir = tempdir().unwrap();
|
||||
let tree = dir.path().join("packdir");
|
||||
std::fs::create_dir_all(&tree).unwrap();
|
||||
std::fs::write(tree.join(".gitignore"), "# my project\n*.log\n").unwrap();
|
||||
scaffold_in(&tree, opts(TemplateId::RUST, "mytool", SourceDir::Here)).unwrap();
|
||||
|
||||
let gitignore = std::fs::read_to_string(tree.join(".gitignore")).unwrap();
|
||||
assert!(
|
||||
gitignore.starts_with("# my project\n*.log\n"),
|
||||
"{gitignore}"
|
||||
);
|
||||
assert!(gitignore.contains("vendor/\n"), "{gitignore}");
|
||||
assert!(gitignore.contains(".cargo/config.toml\n"), "{gitignore}");
|
||||
// The build-artifact entries stay skeleton-only.
|
||||
assert!(!gitignore.contains("*.deb"), "{gitignore}");
|
||||
assert!(!gitignore.contains("# pkh build artifacts"), "{gitignore}");
|
||||
}
|
||||
|
||||
/// End-to-end vendored rust quilt package: the vendoring hook creates
|
||||
/// `vendor/`, the main orig excludes it, the dpkg upstream component
|
||||
/// `orig-vendor` carries it, and the real source build
|
||||
/// (`run_source_build`) lists BOTH tarballs in the `.dsc` and succeeds.
|
||||
/// Needs host cargo with a working crates.io sync (skipped gracefully
|
||||
/// when either is unavailable) and the local dpkg tools.
|
||||
#[test]
|
||||
#[serial]
|
||||
#[serial(RUSTUP_TOOLCHAIN)]
|
||||
fn scaffold_rust_quilt_with_deps_vendors_into_a_component() {
|
||||
let dir = tempdir().unwrap();
|
||||
let source = dir.path().join("mytool");
|
||||
std::fs::create_dir_all(source.join("src")).unwrap();
|
||||
// `libc` resolves from the host's cargo registry cache; vendoring
|
||||
// it needs one crates.io index sync.
|
||||
std::fs::write(
|
||||
source.join("Cargo.toml"),
|
||||
"[package]\n\
|
||||
name = \"mytool\"\n\
|
||||
version = \"0.1.0\"\n\
|
||||
edition = \"2021\"\n\
|
||||
\n\
|
||||
[dependencies]\n\
|
||||
libc = \"0.2\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(source.join("src/main.rs"), "fn main() {}\n").unwrap();
|
||||
|
||||
let mut o = opts(TemplateId::RUST, "mytool", SourceDir::Path(source.clone()));
|
||||
o.source_format = SourceFormat::Quilt;
|
||||
o.orig = Some(OrigOrigin::Snapshot);
|
||||
let outcome = scaffold_in(dir.path(), o).unwrap();
|
||||
|
||||
if crate::new::templates::find_on_path("cargo").is_none() || outcome.vendoring_failed {
|
||||
// No cargo on this host or the crates.io sync failed: the
|
||||
// vendoring guarantees of this test cannot hold.
|
||||
log::warn!("cargo/crates.io unavailable; skipping the vendored component checks");
|
||||
return;
|
||||
}
|
||||
assert_eq!(
|
||||
outcome.orig_origin,
|
||||
Some("working tree snapshot".to_string())
|
||||
);
|
||||
|
||||
// The main orig excludes vendor/ but carries the upstream files.
|
||||
let tarball = dir.path().join("mytool_0.1.0.orig.tar.xz");
|
||||
let mut archive = tar::Archive::new(xz2::read::XzDecoder::new(
|
||||
std::fs::File::open(&tarball).unwrap(),
|
||||
@@ -618,28 +790,65 @@ mod tests {
|
||||
names.iter().any(|n| n == "mytool-0.1.0/Cargo.toml"),
|
||||
"{names:?}"
|
||||
);
|
||||
assert!(!names.iter().any(|n| n.contains("vendor")), "{names:?}");
|
||||
|
||||
// The component carries vendor/ under a top-level vendor/ dir.
|
||||
let component = dir.path().join("mytool_0.1.0.orig-vendor.tar.xz");
|
||||
assert!(component.exists());
|
||||
let mut archive = tar::Archive::new(xz2::read::XzDecoder::new(
|
||||
std::fs::File::open(&component).unwrap(),
|
||||
));
|
||||
let names: Vec<String> = archive
|
||||
.entries()
|
||||
.unwrap()
|
||||
.map(|entry| {
|
||||
entry
|
||||
.unwrap()
|
||||
.path()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
names.iter().any(|n| n == "mytool-0.1.0/src/main.rs"),
|
||||
names.iter().any(|n| n.starts_with("vendor/libc/")),
|
||||
"{names:?}"
|
||||
);
|
||||
if has_cargo {
|
||||
assert!(
|
||||
names.iter().any(|n| n == "mytool-0.1.0/.cargo/config.toml"),
|
||||
"{names:?}"
|
||||
);
|
||||
}
|
||||
assert!(!names.iter().any(|n| n.contains("debian")), "{names:?}");
|
||||
|
||||
// The real source build: the .dsc references both tarballs.
|
||||
let output = crate::build::run_source_build(
|
||||
&source,
|
||||
&crate::build::SourceBuildOptions::default(),
|
||||
&crate::report::Quiet,
|
||||
)
|
||||
.unwrap();
|
||||
let dsc = std::fs::read_to_string(&output.dsc).unwrap();
|
||||
assert!(dsc.contains("mytool_0.1.0.orig.tar.xz"), "{dsc}");
|
||||
assert!(dsc.contains("mytool_0.1.0.orig-vendor.tar.xz"), "{dsc}");
|
||||
assert!(
|
||||
output
|
||||
.tarballs
|
||||
.iter()
|
||||
.any(|t| t.ends_with("mytool_0.1.0.orig.tar.xz"))
|
||||
);
|
||||
assert!(
|
||||
output
|
||||
.tarballs
|
||||
.iter()
|
||||
.any(|t| t.ends_with("mytool_0.1.0.orig-vendor.tar.xz"))
|
||||
);
|
||||
assert!(!output.signed);
|
||||
}
|
||||
|
||||
/// End-to-end python skeleton: pyproject-based Build-Depends and the
|
||||
/// module skeleton inside the orig tarball.
|
||||
/// End-to-end python skeleton: pyproject-based Build-Depends (native
|
||||
/// skeleton: the upstream files live in the tree, no orig tarball).
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_python_skeleton_tree() {
|
||||
let dir = tempdir().unwrap();
|
||||
scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Python, "mytool", SourceDir::Skeleton),
|
||||
opts(TemplateId::PYTHON, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -656,49 +865,27 @@ mod tests {
|
||||
let rules = std::fs::read_to_string(tree.join("debian/rules")).unwrap();
|
||||
assert!(rules.contains("%:\n\tdh $@ --with python3 --buildsystem=pybuild\n"));
|
||||
|
||||
let tarball = dir.path().join("mytool_0.1.0.orig.tar.xz");
|
||||
let mut archive = tar::Archive::new(xz2::read::XzDecoder::new(
|
||||
std::fs::File::open(&tarball).unwrap(),
|
||||
));
|
||||
let names: Vec<String> = archive
|
||||
.entries()
|
||||
.unwrap()
|
||||
.map(|entry| {
|
||||
entry
|
||||
.unwrap()
|
||||
.path()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
names.iter().any(|n| n == "mytool-0.1.0/pyproject.toml"),
|
||||
"{names:?}"
|
||||
);
|
||||
assert!(
|
||||
names.iter().any(|n| n == "mytool-0.1.0/mytool/__init__.py"),
|
||||
"{names:?}"
|
||||
);
|
||||
assert!(tree.join("pyproject.toml").exists());
|
||||
assert!(tree.join("mytool/__init__.py").exists());
|
||||
assert!(!dir.path().join("mytool_0.1.0.orig.tar.xz").exists());
|
||||
}
|
||||
|
||||
/// End-to-end: the scaffolded shell tree passes the real source build
|
||||
/// (`dpkg-source` and friends, same prerequisites as the differential
|
||||
/// tests).
|
||||
/// End-to-end: a quilt tree (Here mode over an existing source) passes
|
||||
/// the real source build (`dpkg-source` and friends, same prerequisites
|
||||
/// as the differential tests).
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_then_source_build_produces_artifacts() {
|
||||
let dir = tempdir().unwrap();
|
||||
scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::Shell, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
let tree = dir.path().join("mytool");
|
||||
std::fs::create_dir_all(&tree).unwrap();
|
||||
std::fs::write(tree.join("run.sh"), "#!/bin/sh\necho hi\n").unwrap();
|
||||
scaffold_in(&tree, opts(TemplateId::SHELL, "mytool", SourceDir::Here)).unwrap();
|
||||
|
||||
let output = crate::build::run_source_build(
|
||||
&dir.path().join("mytool"),
|
||||
&crate::build::SourceBuildOptions::default(),
|
||||
None,
|
||||
&crate::report::Quiet,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -713,4 +900,36 @@ mod tests {
|
||||
// UNRELEASED: nothing is signed.
|
||||
assert!(!output.signed);
|
||||
}
|
||||
|
||||
/// End-to-end native: a self-authored skeleton (3.0 (native), no orig
|
||||
/// tarball) builds into a .dsc without any tarball at all.
|
||||
#[test]
|
||||
#[serial]
|
||||
fn scaffold_native_then_source_build_needs_no_tarball() {
|
||||
let dir = tempdir().unwrap();
|
||||
scaffold_in(
|
||||
dir.path(),
|
||||
opts(TemplateId::SHELL, "mytool", SourceDir::Skeleton),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let output = crate::build::run_source_build(
|
||||
&dir.path().join("mytool"),
|
||||
&crate::build::SourceBuildOptions::default(),
|
||||
&crate::report::Quiet,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(output.dsc.exists(), "{:?} missing", output.dsc);
|
||||
assert!(output.changes.exists(), "{:?} missing", output.changes);
|
||||
// 3.0 (native): one self-contained source tarball (debian/ inside),
|
||||
// but no ORIG tarball.
|
||||
assert_eq!(output.tarballs.len(), 1, "{:?}", output.tarballs);
|
||||
assert!(
|
||||
!output.tarballs[0]
|
||||
.file_name()
|
||||
.is_some_and(|name| name.to_string_lossy().contains("orig")),
|
||||
"{:?}",
|
||||
output.tarballs
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+764
-100
File diff suppressed because it is too large
Load Diff
+1648
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,617 @@
|
||||
//! Best-effort git origin detection for `pkh new`.
|
||||
//!
|
||||
//! [`GitOrigin::detect`] inspects the source directory through the `git`
|
||||
//! CLI (fail-soft: any failed query just leaves the corresponding field
|
||||
//! empty, and a non-repo yields `None`) and answers the questions driving
|
||||
//! the source-format and orig-tarball decisions:
|
||||
//!
|
||||
//! - is HEAD exactly on a tag, and which upstream version does it name,
|
||||
//! - which is the last tag reachable from HEAD (for the
|
||||
//! `<tag>+git<YYYYMMDD>.<hash>` version scheme),
|
||||
//! - where does the `origin` remote point: only the hosts of the bundled
|
||||
//! forge table (`data/forges.yml`) are recognized as forges — self-hosted
|
||||
//! GitLab instances are deliberately not part of it (the
|
||||
//! release-download URL shapes differ), and the table also carries each
|
||||
//! forge's tarball URL templates.
|
||||
//!
|
||||
//! Detection never touches the network: adding a remote stores its URL in
|
||||
//! the local config only, which is all this module reads.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::data::embed_data;
|
||||
|
||||
/// Family a forge belongs to. Documentation of which URL-shape family a
|
||||
/// table entry belongs to — the tarball templates fully describe the
|
||||
/// URLs, so nothing branches on the kind (yet). Parsed strictly: an
|
||||
/// unknown kind fails the load rather than being silently ignored.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum ForgeKind {
|
||||
/// `github.com` and its codeload archive service
|
||||
GitHub,
|
||||
/// `gitlab.com`
|
||||
GitLab,
|
||||
}
|
||||
|
||||
/// One entry of the bundled forge table: the release-tarball URL
|
||||
/// templates of a forge host
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ForgeEntry {
|
||||
/// Family of the forge (see [`ForgeKind`]). Kept even though nothing
|
||||
/// branches on it (the templates fully describe the URLs): it
|
||||
/// documents the entry's URL-shape family and the strict enum
|
||||
/// validates it at load time.
|
||||
#[allow(dead_code)]
|
||||
kind: ForgeKind,
|
||||
/// Release-tarball URL templates, best candidate first (tried
|
||||
/// sequentially by the download)
|
||||
tarball_templates: Vec<String>,
|
||||
}
|
||||
|
||||
/// The bundled forge table (`data/forges.yml`): host name → entry
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ForgesData {
|
||||
/// Recognized forge hosts
|
||||
forges: HashMap<String, ForgeEntry>,
|
||||
}
|
||||
|
||||
embed_data! {
|
||||
static ref FORGES_DATA: ForgesData = "../../data/forges.yml"
|
||||
}
|
||||
|
||||
/// A forge hosting the project, parsed from the `origin` remote URL: one
|
||||
/// of the hosts of the bundled forge table, plus the repository it points
|
||||
/// at.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Forge {
|
||||
/// Host name of the forge (the key of its `forges.yml` entry).
|
||||
host: &'static str,
|
||||
/// Repository owner (user or organization).
|
||||
owner: String,
|
||||
/// Repository name, without the `.git` suffix.
|
||||
repo: String,
|
||||
}
|
||||
|
||||
impl Forge {
|
||||
/// Host name of the forge.
|
||||
pub fn host(&self) -> &'static str {
|
||||
self.host
|
||||
}
|
||||
|
||||
/// Parse a remote URL into a [`Forge`], accepting the `https://`,
|
||||
/// `http://`, `git://` and `git@host:` spellings. Only the hosts
|
||||
/// listed in the bundled forge table are recognized; anything else
|
||||
/// (self-hosted GitLab, Bitbucket, plain URLs…) yields `None`.
|
||||
pub fn parse(url: &str) -> Option<Forge> {
|
||||
let url = url.trim();
|
||||
// Normalize `git@host:path` to `host/path` and strip any scheme.
|
||||
let (host, path) = match url.split_once("://") {
|
||||
Some((_scheme, rest)) => rest.split_once('/')?,
|
||||
None => {
|
||||
let (scp, path) = url.split_once(':')?;
|
||||
let host = scp.strip_prefix("git@").unwrap_or(scp);
|
||||
(host, path)
|
||||
}
|
||||
};
|
||||
let host = host.to_ascii_lowercase();
|
||||
// Drop the leading user part of ssh URLs (`git@github.com` handled
|
||||
// above; `ssh://git@github.com/path` keeps `git@github.com` here).
|
||||
let host = host.rsplit('@').next().unwrap_or(&host);
|
||||
let mut segments = path
|
||||
.trim_end_matches('/')
|
||||
.trim_end_matches(".git")
|
||||
.split('/');
|
||||
let owner = segments.next()?;
|
||||
let repo = segments.next()?;
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// The table key doubles as the Forge's host, so the two can never
|
||||
// disagree about how the forge is spelled.
|
||||
let (host, _entry) = FORGES_DATA.forges.get_key_value(host)?;
|
||||
Some(Forge {
|
||||
host,
|
||||
owner: owner.to_string(),
|
||||
repo: repo.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Release-tarball URLs of `tag`, best candidate first: the templates
|
||||
/// of the forge's table entry, with `{owner}`, `{repo}` and `{tag}`
|
||||
/// substituted, in file order (the download tries them sequentially).
|
||||
pub fn release_tarball_urls(&self, tag: &str) -> Vec<String> {
|
||||
let entry = FORGES_DATA
|
||||
.forges
|
||||
.get(self.host)
|
||||
.expect("the host of a parsed Forge is a key of the forge table");
|
||||
entry
|
||||
.tarball_templates
|
||||
.iter()
|
||||
.map(|template| {
|
||||
template
|
||||
.replace("{owner}", &self.owner)
|
||||
.replace("{repo}", &self.repo)
|
||||
.replace("{tag}", tag)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort snapshot of the git state of a source directory (see the
|
||||
/// module docs). Every field degrades to its empty value when the
|
||||
/// corresponding query fails.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct GitOrigin {
|
||||
/// Forge of the `origin` remote, when it is one of the recognized ones.
|
||||
pub forge: Option<Forge>,
|
||||
/// Tag exactly at HEAD, when there is one (name as written, e.g. `v1.2.3`).
|
||||
pub head_tag: Option<String>,
|
||||
/// Every tag of the repository, sorted lexically.
|
||||
pub tags: Vec<String>,
|
||||
/// Last tag reachable from HEAD (used by [`GitOrigin::git_version`]).
|
||||
pub last_tag: Option<String>,
|
||||
/// HEAD commit date as `%Y%m%d`.
|
||||
pub head_date: Option<String>,
|
||||
/// HEAD commit short hash.
|
||||
pub head_hash: Option<String>,
|
||||
/// Whether the worktree carries uncommitted changes (`git status
|
||||
/// --porcelain` non-empty).
|
||||
pub dirty: bool,
|
||||
}
|
||||
|
||||
impl GitOrigin {
|
||||
/// Detect the git origin state of `dir`. Returns `None` when `dir` is
|
||||
/// not inside a git work tree (or git cannot be run); every other
|
||||
/// failure is fail-soft (the field stays empty).
|
||||
pub fn detect(dir: &Path) -> Option<GitOrigin> {
|
||||
// Inside a work tree? (fails outside git; prints "false" in a bare
|
||||
// repository).
|
||||
if git(dir, &["rev-parse", "--is-inside-work-tree"]).as_deref() != Some("true") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut origin = GitOrigin {
|
||||
head_tag: git(dir, &["describe", "--tags", "--exact-match", "HEAD"]),
|
||||
tags: git(dir, &["tag", "--list"])
|
||||
.map(|out| {
|
||||
out.lines()
|
||||
.map(str::to_string)
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
last_tag: git(dir, &["describe", "--tags", "--abbrev=0"]),
|
||||
head_date: git(dir, &["log", "-1", "--date=format:%Y%m%d", "--format=%cd"]),
|
||||
head_hash: git(dir, &["rev-parse", "--short", "HEAD"]),
|
||||
dirty: git(dir, &["status", "--porcelain"]).is_some_and(|out| !out.trim().is_empty()),
|
||||
forge: None,
|
||||
};
|
||||
|
||||
if let Some(url) = git(dir, &["remote", "get-url", "origin"])
|
||||
.or_else(|| git(dir, &["config", "--get", "remote.origin.url"]))
|
||||
{
|
||||
origin.forge = Forge::parse(&url);
|
||||
}
|
||||
|
||||
Some(origin)
|
||||
}
|
||||
|
||||
/// Upstream version named by the tag at HEAD: the tag with a leading
|
||||
/// `v`/`V` (before a digit) stripped, and only when the result is a
|
||||
/// plausible Debian upstream version (no `-`, which is the revision
|
||||
/// separator).
|
||||
pub fn head_tag_version(&self) -> Option<String> {
|
||||
sanitized_tag_version(self.head_tag.as_deref()?)
|
||||
}
|
||||
|
||||
/// Version suggestion for a HEAD between releases:
|
||||
/// `<lasttag>+git<YYYYMMDD>.<shorthash>` (e.g. `1.2.3+git20260916.4b8a2f1`),
|
||||
/// or `None` without a reachable tag, tag-strippable version, date or hash.
|
||||
pub fn git_version(&self) -> Option<String> {
|
||||
let base = sanitized_tag_version(self.last_tag.as_deref()?)?;
|
||||
let date = self.head_date.as_deref()?;
|
||||
let hash = self.head_hash.as_deref()?;
|
||||
Some(format!("{base}+git{date}.{hash}"))
|
||||
}
|
||||
|
||||
/// The repository tag naming `version` (a leading `v`/`V` on the tag is
|
||||
/// ignored), whatever the state of HEAD.
|
||||
pub fn tag_for_version(&self, version: &str) -> Option<&str> {
|
||||
self.tags
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.find(|tag| sanitized_tag_version(tag).as_deref() == Some(version))
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip a leading `v`/`V` (before a digit) off a tag name and keep only
|
||||
/// results usable as a Debian upstream version: no `-` (which is the revision
|
||||
/// separator) and no leading non-digit.
|
||||
fn sanitized_tag_version(tag: &str) -> Option<String> {
|
||||
let stripped = tag
|
||||
.strip_prefix(['v', 'V'])
|
||||
.filter(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
|
||||
.unwrap_or(tag);
|
||||
if stripped.starts_with(|c: char| c.is_ascii_digit()) && !stripped.contains('-') {
|
||||
Some(stripped.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check out `tag` in the repository at `dir`, refusing a dirty worktree:
|
||||
/// pkh never carries uncommitted changes across a checkout. Detached HEAD
|
||||
/// is the expected outcome when packaging a release tag.
|
||||
pub fn checkout_tag(dir: &Path, tag: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if let Some(status) = git(dir, &["status", "--porcelain"])
|
||||
&& !status.trim().is_empty()
|
||||
{
|
||||
return Err(format!(
|
||||
"The working tree of '{}' has uncommitted changes: commit or \
|
||||
stash them before checking out '{tag}' (pkh does not carry \
|
||||
changes across a checkout)",
|
||||
dir.display()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let output = Command::new("git")
|
||||
.args(["checkout", tag])
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.map_err(|e| format!("failed to run 'git checkout': {e}"))?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"'git checkout {tag}' failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run `git` with `args` in `dir`, returning its trimmed stdout when it
|
||||
/// exits successfully (empty output stays an empty string).
|
||||
fn git(dir: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.ok()?;
|
||||
output
|
||||
.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// Whether the host has a usable git CLI (every fixture below needs it).
|
||||
fn have_git() -> bool {
|
||||
Command::new("git")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
}
|
||||
|
||||
/// Run git in `dir`, failing the test on error, with a deterministic
|
||||
/// identity and no signing so host git config cannot break the fixture.
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let status = Command::new("git")
|
||||
.args([
|
||||
"-c",
|
||||
"user.name=Pkh Origin",
|
||||
"-c",
|
||||
"user.email=pkhorigin@example.invalid",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
])
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.env("GIT_AUTHOR_DATE", "2026-09-15T12:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2026-09-15T12:00:00Z")
|
||||
.status()
|
||||
.expect("git should be runnable");
|
||||
assert!(status.success(), "git {args:?} failed");
|
||||
}
|
||||
|
||||
/// A repository with a single commit on 2026-09-15, returning its
|
||||
/// short HEAD hash.
|
||||
fn init_repo(dir: &Path) -> String {
|
||||
git(dir, &["init", "-q"]);
|
||||
std::fs::write(dir.join("file.txt"), "one\n").unwrap();
|
||||
git(dir, &["add", "file.txt"]);
|
||||
git(dir, &["commit", "-q", "-m", "first"]);
|
||||
git_out(dir, &["rev-parse", "--short", "HEAD"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forge_parses_remote_url_shapes() {
|
||||
assert_eq!(
|
||||
Forge::parse("https://github.com/foo/bar.git"),
|
||||
Some(Forge {
|
||||
host: "github.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Forge::parse("git@github.com:foo/bar.git"),
|
||||
Some(Forge {
|
||||
host: "github.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Forge::parse("git://github.com/foo/bar"),
|
||||
Some(Forge {
|
||||
host: "github.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Forge::parse("https://gitlab.com/foo/bar/-/tree/main"),
|
||||
Some(Forge {
|
||||
host: "gitlab.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Forge::parse("ssh://git@gitlab.com/foo/bar.git"),
|
||||
Some(Forge {
|
||||
host: "gitlab.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into()
|
||||
})
|
||||
);
|
||||
// Self-hosted GitLab instances and other hosts are not recognized.
|
||||
assert_eq!(Forge::parse("https://gitlab.example.com/foo/bar.git"), None);
|
||||
assert_eq!(Forge::parse("https://bitbucket.org/foo/bar.git"), None);
|
||||
// Garbage.
|
||||
assert_eq!(Forge::parse("not a url"), None);
|
||||
assert_eq!(Forge::parse("https://github.com/onlyowner"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forge_release_tarball_urls() {
|
||||
let gh = Forge {
|
||||
host: "github.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
gh.release_tarball_urls("v1.2.3"),
|
||||
vec![
|
||||
"https://codeload.github.com/foo/bar/tar.gz/refs/tags/v1.2.3".to_string(),
|
||||
"https://github.com/foo/bar/archive/refs/tags/v1.2.3.tar.gz".to_string(),
|
||||
]
|
||||
);
|
||||
let gl = Forge {
|
||||
host: "gitlab.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
gl.release_tarball_urls("v1.2.3"),
|
||||
vec!["https://gitlab.com/foo/bar/-/archive/v1.2.3/bar-v1.2.3.tar.gz".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
/// Every table entry must be substitutable: a template missing one of
|
||||
/// the placeholders would download from a literal `{name}` URL.
|
||||
#[test]
|
||||
fn forge_templates_carry_every_placeholder() {
|
||||
for (host, entry) in &FORGES_DATA.forges {
|
||||
assert!(
|
||||
!entry.tarball_templates.is_empty(),
|
||||
"forge '{host}' has no tarball template"
|
||||
);
|
||||
for template in &entry.tarball_templates {
|
||||
for placeholder in ["{owner}", "{repo}", "{tag}"] {
|
||||
assert!(
|
||||
template.contains(placeholder),
|
||||
"template '{template}' of forge '{host}' lacks {placeholder}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `kind` field is validated at load time: an unknown forge family
|
||||
/// fails the parse instead of being silently accepted.
|
||||
#[test]
|
||||
fn forge_kind_is_validated() {
|
||||
assert!(serde_yaml::from_str::<ForgeEntry>("kind: github").is_err());
|
||||
assert!(
|
||||
serde_yaml::from_str::<ForgeEntry>(
|
||||
"kind: github\ntarball_templates: ['https://h/{owner}/{repo}/{tag}']"
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
serde_yaml::from_str::<ForgeEntry>(
|
||||
"kind: codeberg\ntarball_templates: ['https://h/{owner}/{repo}/{tag}']"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitized_tag_versions() {
|
||||
assert_eq!(sanitized_tag_version("v1.2.3"), Some("1.2.3".to_string()));
|
||||
assert_eq!(sanitized_tag_version("V2.0"), Some("2.0".to_string()));
|
||||
assert_eq!(sanitized_tag_version("1.2.3"), Some("1.2.3".to_string()));
|
||||
// `v` followed by a non-digit is part of the name, not a marker.
|
||||
assert_eq!(sanitized_tag_version("version-1"), None);
|
||||
// `-` would collide with the Debian revision separator.
|
||||
assert_eq!(sanitized_tag_version("v1.2.3-beta"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_outside_a_repository_is_none() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempdir().unwrap();
|
||||
assert_eq!(GitOrigin::detect(dir.path()), None);
|
||||
// A bare repository is not a work tree either.
|
||||
let bare = tempdir().unwrap();
|
||||
git(bare.path(), &["init", "-q", "--bare"]);
|
||||
assert_eq!(GitOrigin::detect(bare.path()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_plain_repo_without_tags_or_remote() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempdir().unwrap();
|
||||
let hash = init_repo(dir.path());
|
||||
|
||||
let origin = GitOrigin::detect(dir.path()).expect("detected");
|
||||
assert_eq!(origin.forge, None);
|
||||
assert_eq!(origin.head_tag, None);
|
||||
assert!(origin.tags.is_empty());
|
||||
assert_eq!(origin.last_tag, None);
|
||||
assert_eq!(origin.head_hash.as_deref(), Some(hash.as_str()));
|
||||
assert_eq!(origin.head_date.as_deref(), Some("20260915"));
|
||||
assert!(!origin.dirty);
|
||||
// No tags: no version can be derived.
|
||||
assert_eq!(origin.head_tag_version(), None);
|
||||
assert_eq!(origin.git_version(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_head_exactly_on_a_tag() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempdir().unwrap();
|
||||
init_repo(dir.path());
|
||||
git(dir.path(), &["tag", "v1.2.3"]);
|
||||
|
||||
let origin = GitOrigin::detect(dir.path()).expect("detected");
|
||||
assert_eq!(origin.head_tag.as_deref(), Some("v1.2.3"));
|
||||
assert_eq!(origin.last_tag.as_deref(), Some("v1.2.3"));
|
||||
assert_eq!(origin.head_tag_version().as_deref(), Some("1.2.3"));
|
||||
// The query is the stripped version; the raw tag name is not one.
|
||||
assert_eq!(origin.tag_for_version("1.2.3"), Some("v1.2.3"));
|
||||
assert_eq!(origin.tag_for_version("v1.2.3"), None);
|
||||
assert_eq!(origin.tag_for_version("9.9.9"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_between_releases_derives_git_version() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempdir().unwrap();
|
||||
init_repo(dir.path());
|
||||
git(dir.path(), &["tag", "v1.2.3"]);
|
||||
std::fs::write(dir.path().join("file.txt"), "two\n").unwrap();
|
||||
git(dir.path(), &["add", "file.txt"]);
|
||||
git(dir.path(), &["commit", "-q", "-m", "second"]);
|
||||
let hash = git_out(dir.path(), &["rev-parse", "--short", "HEAD"]);
|
||||
|
||||
let origin = GitOrigin::detect(dir.path()).expect("detected");
|
||||
assert_eq!(origin.head_tag, None);
|
||||
assert_eq!(origin.last_tag.as_deref(), Some("v1.2.3"));
|
||||
assert_eq!(origin.tag_for_version("1.2.3"), Some("v1.2.3"));
|
||||
assert_eq!(
|
||||
origin.git_version().as_deref(),
|
||||
Some(format!("1.2.3+git20260915.{hash}").as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_tracks_the_origin_remote() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempdir().unwrap();
|
||||
init_repo(dir.path());
|
||||
// A local path remote: configuring it never touches the network.
|
||||
git(
|
||||
dir.path(),
|
||||
&["remote", "add", "origin", "https://github.com/foo/bar.git"],
|
||||
);
|
||||
|
||||
let origin = GitOrigin::detect(dir.path()).expect("detected");
|
||||
assert_eq!(
|
||||
origin.forge,
|
||||
Some(Forge {
|
||||
host: "github.com",
|
||||
owner: "foo".into(),
|
||||
repo: "bar".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_reports_a_dirty_worktree() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempdir().unwrap();
|
||||
init_repo(dir.path());
|
||||
std::fs::write(dir.path().join("file.txt"), "uncommitted\n").unwrap();
|
||||
|
||||
let origin = GitOrigin::detect(dir.path()).expect("detected");
|
||||
assert!(origin.dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_version_skips_unusable_tags() {
|
||||
// A tag carrying `-` cannot become an upstream version: the scheme
|
||||
// degrades to None instead of proposing an invalid version.
|
||||
let origin = GitOrigin {
|
||||
last_tag: Some("1.2.3-beta".into()),
|
||||
head_date: Some("20260915".into()),
|
||||
head_hash: Some("abc1234".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(origin.git_version(), None);
|
||||
// Date or hash missing: nothing to propose either.
|
||||
assert_eq!(
|
||||
GitOrigin {
|
||||
last_tag: Some("v2.0".into()),
|
||||
..Default::default()
|
||||
}
|
||||
.git_version(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// `git` output trimmed (for the hash assertions above).
|
||||
fn git_out(dir: &Path, args: &[&str]) -> String {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "git {args:?} failed");
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
/// The tag lookup ignores a `v` prefix in either direction.
|
||||
#[test]
|
||||
fn tag_for_version_matches_both_spellings() {
|
||||
let origin = GitOrigin {
|
||||
tags: vec!["1.0".to_string(), "v2.0".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(origin.tag_for_version("1.0"), Some("1.0"));
|
||||
assert_eq!(origin.tag_for_version("2.0"), Some("v2.0"));
|
||||
assert_eq!(origin.tag_for_version("3.0"), None);
|
||||
}
|
||||
}
|
||||
+898
-215
File diff suppressed because it is too large
Load Diff
@@ -1,71 +1,34 @@
|
||||
//! The `autotools` template: a C project with a `configure.ac` built through
|
||||
//! debhelper's auto-detection (dh runs `autoreconf` itself when it finds
|
||||
//! `configure.ac`, debhelper ≥ 10 — no override needed).
|
||||
//!
|
||||
//! The metadata and the `configure.ac`/`Makefile.am`/`hello.c` skeleton
|
||||
//! bodies are manifest data (`data/templates/autotools/manifest.yml`); the
|
||||
//! logic half here is the `AC_INIT` probe and the GNU-gettext detection
|
||||
//! (appending `gettext` to the manifest's Build-Depends).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use super::meson::hello_c;
|
||||
use super::{OutputFile, ProbeResult, Template, source_dir_of};
|
||||
use crate::new::options::{NewOptions, TemplateId};
|
||||
use super::{ProbeResult, TemplateHooks, source_dir_of};
|
||||
use crate::new::options::NewOptions;
|
||||
|
||||
/// C/C++ with Autotools (`configure.ac`).
|
||||
pub struct Autotools;
|
||||
/// The logic half of the autotools template.
|
||||
pub struct Hooks;
|
||||
|
||||
impl Template for Autotools {
|
||||
fn id(&self) -> TemplateId {
|
||||
TemplateId::Autotools
|
||||
}
|
||||
/// The autotools template's hooks, registered in the template registry.
|
||||
pub static HOOKS: Hooks = Hooks;
|
||||
|
||||
/// A minimal `configure.ac`, the matching `Makefile.am` and `hello.c`.
|
||||
/// The first source build runs `autoreconf` (integrated in the dh
|
||||
/// sequence), so no generated configure script is committed.
|
||||
fn skeleton(&self, opts: &NewOptions) -> Vec<OutputFile> {
|
||||
vec![
|
||||
OutputFile::new(
|
||||
"configure.ac",
|
||||
format!(
|
||||
"AC_INIT([{name}], [{version}])\n\
|
||||
AM_INIT_AUTOMAKE([foreign])\n\
|
||||
AC_PROG_CC\n\
|
||||
AC_CONFIG_FILES([Makefile])\n\
|
||||
AC_OUTPUT\n",
|
||||
name = opts.name,
|
||||
version = opts.upstream_version,
|
||||
),
|
||||
),
|
||||
OutputFile::new(
|
||||
"Makefile.am",
|
||||
format!(
|
||||
"bin_PROGRAMS = {command}\n\
|
||||
{command}_SOURCES = hello.c\n",
|
||||
command = opts.command,
|
||||
),
|
||||
),
|
||||
hello_c(opts),
|
||||
]
|
||||
}
|
||||
|
||||
/// No extra debian/ files: plain `dh $@` auto-detects `configure.ac`.
|
||||
fn debian(&self, _opts: &NewOptions) -> Vec<OutputFile> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn build_depends(&self, opts: &NewOptions) -> Vec<String> {
|
||||
let mut deps = vec![
|
||||
"autoconf".to_string(),
|
||||
"automake".to_string(),
|
||||
"libtool".to_string(),
|
||||
];
|
||||
impl TemplateHooks for Hooks {
|
||||
/// A packaged `configure.ac` that sets up GNU gettext (the
|
||||
/// `AM_GNU_GETTEXT` macro, see [`uses_gettext`]) appends `gettext` to
|
||||
/// the manifest's Build-Depends.
|
||||
fn build_depends(&self, opts: &NewOptions, mut base: Vec<String>) -> Vec<String> {
|
||||
if uses_gettext(opts) {
|
||||
deps.push("gettext".to_string());
|
||||
base.push("gettext".to_string());
|
||||
}
|
||||
deps
|
||||
}
|
||||
|
||||
fn architecture(&self, _opts: &NewOptions) -> &'static str {
|
||||
"any"
|
||||
base
|
||||
}
|
||||
|
||||
/// Package name and version from the `AC_INIT` macro of `configure.ac`.
|
||||
@@ -109,13 +72,13 @@ fn uses_gettext(opts: &NewOptions) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::new::options::{License, SourceDir};
|
||||
use crate::new::options::{License, SourceDir, TemplateId};
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn opts() -> NewOptions {
|
||||
NewOptions {
|
||||
name: "mytool".into(),
|
||||
template: TemplateId::Autotools,
|
||||
template: TemplateId::AUTOTOOLS,
|
||||
source_dir: SourceDir::Skeleton,
|
||||
upstream_version: "0.1.0".into(),
|
||||
revision: 1,
|
||||
@@ -129,7 +92,8 @@ mod tests {
|
||||
series: "resolute".into(),
|
||||
release: false,
|
||||
depends: Vec::new(),
|
||||
native: false,
|
||||
source_format: crate::new::options::SourceFormat::Quilt,
|
||||
orig: Some(crate::new::options::OrigOrigin::Snapshot),
|
||||
git: true,
|
||||
autopkgtest: false,
|
||||
pkg_config: false,
|
||||
@@ -140,7 +104,7 @@ mod tests {
|
||||
#[test]
|
||||
fn autotools_template_shape() {
|
||||
let o = opts();
|
||||
let template = super::super::get(TemplateId::Autotools).unwrap();
|
||||
let template = super::super::get(TemplateId::AUTOTOOLS).unwrap();
|
||||
|
||||
assert_eq!(template.architecture(&o), "any");
|
||||
assert_eq!(
|
||||
@@ -155,28 +119,50 @@ mod tests {
|
||||
assert!(template.rules_extra(&o).is_empty());
|
||||
assert!(template.debian(&o).is_empty());
|
||||
|
||||
// Skeleton (manifest data): configure.ac + Makefile.am + hello.c,
|
||||
// byte-exact.
|
||||
let skeleton = template.skeleton(&o);
|
||||
assert_eq!(skeleton.len(), 3);
|
||||
let configure = skeleton
|
||||
.iter()
|
||||
.find(|f| f.path == "configure.ac")
|
||||
.expect("configure.ac skeleton");
|
||||
assert!(
|
||||
configure
|
||||
.contents
|
||||
.starts_with("AC_INIT([mytool], [0.1.0])\n")
|
||||
assert_eq!(
|
||||
configure.contents,
|
||||
"AC_INIT([mytool], [0.1.0])\n\
|
||||
AM_INIT_AUTOMAKE([foreign])\n\
|
||||
AC_PROG_CC\n\
|
||||
AC_CONFIG_FILES([Makefile])\n\
|
||||
AC_OUTPUT\n"
|
||||
);
|
||||
let makefile_am = skeleton
|
||||
.iter()
|
||||
.find(|f| f.path == "Makefile.am")
|
||||
.expect("Makefile.am skeleton");
|
||||
assert!(makefile_am.contents.contains("bin_PROGRAMS = mytool"));
|
||||
assert!(makefile_am.contents.contains("mytool_SOURCES = hello.c"));
|
||||
assert!(skeleton.iter().any(|f| f.path == "hello.c"));
|
||||
assert_eq!(
|
||||
makefile_am.contents,
|
||||
"bin_PROGRAMS = mytool\nmytool_SOURCES = hello.c\n"
|
||||
);
|
||||
let hello = skeleton
|
||||
.iter()
|
||||
.find(|f| f.path == "hello.c")
|
||||
.expect("hello.c skeleton");
|
||||
assert_eq!(
|
||||
hello.contents,
|
||||
"#include <stdio.h>\n\
|
||||
\n\
|
||||
/* Placeholder for mytool, generated by `pkh new`. */\n\
|
||||
int main(void)\n\
|
||||
{\n\
|
||||
\tprintf(\"Hello from mytool!\\n\");\n\
|
||||
\treturn 0;\n\
|
||||
}\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotools_probe_reads_ac_init() {
|
||||
let template = super::super::get(TemplateId::Autotools).unwrap();
|
||||
let template = super::super::get(TemplateId::AUTOTOOLS).unwrap();
|
||||
|
||||
// Bracketed form (the generated skeleton's own shape).
|
||||
let dir = tempdir().unwrap();
|
||||
@@ -221,7 +207,7 @@ mod tests {
|
||||
let o = opts();
|
||||
assert!(!uses_gettext(&o));
|
||||
assert!(
|
||||
!super::super::get(TemplateId::Autotools)
|
||||
!super::super::get(TemplateId::AUTOTOOLS)
|
||||
.unwrap()
|
||||
.build_depends(&o)
|
||||
.contains(&"gettext".to_string())
|
||||
@@ -240,7 +226,7 @@ mod tests {
|
||||
};
|
||||
assert!(uses_gettext(&o));
|
||||
assert!(
|
||||
super::super::get(TemplateId::Autotools)
|
||||
super::super::get(TemplateId::AUTOTOOLS)
|
||||
.unwrap()
|
||||
.build_depends(&o)
|
||||
.contains(&"gettext".to_string())
|
||||
|
||||
+47
-62
@@ -1,63 +1,33 @@
|
||||
//! The `cmake` template: a C/C++ project built with CMake through the
|
||||
//! debhelper cmake buildsystem.
|
||||
//!
|
||||
//! The metadata and the `CMakeLists.txt`/`hello.c` skeleton bodies are
|
||||
//! manifest data (`data/templates/cmake/manifest.yml`); the logic half
|
||||
//! here is the `project()` probe and the wizard's pkg-config opt-in
|
||||
//! (appended to the manifest's Build-Depends).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use super::meson::hello_c;
|
||||
use super::{OutputFile, ProbeResult, Template};
|
||||
use crate::new::options::{NewOptions, TemplateId};
|
||||
use super::{ProbeResult, TemplateHooks};
|
||||
use crate::new::options::NewOptions;
|
||||
|
||||
/// C/C++ with CMake (`CMakeLists.txt`).
|
||||
pub struct Cmake;
|
||||
/// The logic half of the cmake template.
|
||||
pub struct Hooks;
|
||||
|
||||
impl Template for Cmake {
|
||||
fn id(&self) -> TemplateId {
|
||||
TemplateId::Cmake
|
||||
}
|
||||
/// The cmake template's hooks, registered in the template registry.
|
||||
pub static HOOKS: Hooks = Hooks;
|
||||
|
||||
/// A minimal `CMakeLists.txt` (project declaration + one installed
|
||||
/// executable) and the classic `hello.c`.
|
||||
fn skeleton(&self, opts: &NewOptions) -> Vec<OutputFile> {
|
||||
vec![
|
||||
OutputFile::new(
|
||||
"CMakeLists.txt",
|
||||
format!(
|
||||
"cmake_minimum_required(VERSION 3.16)\n\
|
||||
project({name} VERSION {version})\n\
|
||||
\n\
|
||||
add_executable({command} hello.c)\n\
|
||||
install(TARGETS {command} RUNTIME DESTINATION bin)\n",
|
||||
name = opts.name,
|
||||
version = opts.upstream_version,
|
||||
command = opts.command,
|
||||
),
|
||||
),
|
||||
hello_c(opts),
|
||||
]
|
||||
}
|
||||
|
||||
/// No extra debian/ files: debhelper's cmake buildsystem handles the
|
||||
/// configure/build/install steps.
|
||||
fn debian(&self, _opts: &NewOptions) -> Vec<OutputFile> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn build_depends(&self, opts: &NewOptions) -> Vec<String> {
|
||||
let mut deps = vec!["cmake".to_string()];
|
||||
impl TemplateHooks for Hooks {
|
||||
/// The wizard's pkg-config opt-in ([`NewOptions::pkg_config`], offered
|
||||
/// when the project's build file hints at `pkg_check_modules` usage)
|
||||
/// adds `pkg-config` to the manifest's Build-Depends.
|
||||
fn build_depends(&self, opts: &NewOptions, mut base: Vec<String>) -> Vec<String> {
|
||||
if opts.pkg_config {
|
||||
deps.push("pkg-config".to_string());
|
||||
base.push("pkg-config".to_string());
|
||||
}
|
||||
deps
|
||||
}
|
||||
|
||||
fn architecture(&self, _opts: &NewOptions) -> &'static str {
|
||||
"any"
|
||||
}
|
||||
|
||||
fn rules_dh_line(&self) -> String {
|
||||
"dh $@ --buildsystem=cmake".to_string()
|
||||
base
|
||||
}
|
||||
|
||||
/// Project name and version from the `project(<name> VERSION …)`
|
||||
@@ -84,13 +54,13 @@ impl Template for Cmake {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::new::options::{License, SourceDir};
|
||||
use crate::new::options::{License, SourceDir, TemplateId};
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn opts() -> NewOptions {
|
||||
NewOptions {
|
||||
name: "mytool".into(),
|
||||
template: TemplateId::Cmake,
|
||||
template: TemplateId::CMAKE,
|
||||
source_dir: SourceDir::Skeleton,
|
||||
upstream_version: "0.1.0".into(),
|
||||
revision: 1,
|
||||
@@ -104,7 +74,8 @@ mod tests {
|
||||
series: "resolute".into(),
|
||||
release: false,
|
||||
depends: Vec::new(),
|
||||
native: false,
|
||||
source_format: crate::new::options::SourceFormat::Quilt,
|
||||
orig: Some(crate::new::options::OrigOrigin::Snapshot),
|
||||
git: true,
|
||||
autopkgtest: false,
|
||||
pkg_config: false,
|
||||
@@ -115,7 +86,7 @@ mod tests {
|
||||
#[test]
|
||||
fn cmake_template_shape() {
|
||||
let o = opts();
|
||||
let template = super::super::get(TemplateId::Cmake).unwrap();
|
||||
let template = super::super::get(TemplateId::CMAKE).unwrap();
|
||||
|
||||
assert_eq!(template.architecture(&o), "any");
|
||||
assert_eq!(template.build_depends(&o), vec!["cmake".to_string()]);
|
||||
@@ -123,27 +94,41 @@ mod tests {
|
||||
assert!(template.rules_extra(&o).is_empty());
|
||||
assert!(template.debian(&o).is_empty());
|
||||
|
||||
// Skeleton (manifest data): CMakeLists.txt + hello.c, byte-exact.
|
||||
let skeleton = template.skeleton(&o);
|
||||
assert_eq!(skeleton.len(), 2);
|
||||
let cmakelists = skeleton
|
||||
.iter()
|
||||
.find(|f| f.path == "CMakeLists.txt")
|
||||
.expect("CMakeLists.txt skeleton");
|
||||
assert!(
|
||||
cmakelists
|
||||
.contents
|
||||
.contains("project(mytool VERSION 0.1.0)")
|
||||
assert_eq!(
|
||||
cmakelists.contents,
|
||||
"cmake_minimum_required(VERSION 3.16)\n\
|
||||
project(mytool VERSION 0.1.0)\n\
|
||||
\n\
|
||||
add_executable(mytool hello.c)\n\
|
||||
install(TARGETS mytool RUNTIME DESTINATION bin)\n"
|
||||
);
|
||||
assert!(
|
||||
cmakelists
|
||||
.contents
|
||||
.contains("add_executable(mytool hello.c)")
|
||||
let hello = skeleton
|
||||
.iter()
|
||||
.find(|f| f.path == "hello.c")
|
||||
.expect("hello.c skeleton");
|
||||
assert_eq!(
|
||||
hello.contents,
|
||||
"#include <stdio.h>\n\
|
||||
\n\
|
||||
/* Placeholder for mytool, generated by `pkh new`. */\n\
|
||||
int main(void)\n\
|
||||
{\n\
|
||||
\tprintf(\"Hello from mytool!\\n\");\n\
|
||||
\treturn 0;\n\
|
||||
}\n"
|
||||
);
|
||||
assert!(skeleton.iter().any(|f| f.path == "hello.c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmake_probe_reads_project_declaration() {
|
||||
let template = super::super::get(TemplateId::Cmake).unwrap();
|
||||
let template = super::super::get(TemplateId::CMAKE).unwrap();
|
||||
|
||||
let dir = tempdir().unwrap();
|
||||
std::fs::write(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user