native-packages 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ec10e4325aa358b66b54463b9ae2b6c76bd7715f133479acc026e769cf3d70f9
4
- data.tar.gz: 23f0be78b2606bb4d7e22a8117fd5c2b8120dcaf9893531d7a9e2ac693a4fb6a
3
+ metadata.gz: d78377a2d7cdc87ef54c8238fe51302249c47bc36a4e042bbadf87165f9e25cb
4
+ data.tar.gz: 8d9fab565be763ed933a85c2fde86111fca6d0fac0eec0e462ffe88bced75b70
5
5
  SHA512:
6
- metadata.gz: e20c7c977a8d097f7c3abf4d5e372a4b0ff1ddde227d5b105ca3c51a2a6c8d2bc351cbcef849f20fd894cf088335f4924cdea483340e162418a37bbe44e106a0
7
- data.tar.gz: a2662f46985ac1dae617a7527050b80ff8bab863838fe64182f1cc35fe532cc2fb96267fb918fc901508039abeb376e6ce5a477b2157eaf821dc00c0b34e037c
6
+ metadata.gz: '0240281e3e29f2721a8322c73727fe04cf6c84061981bc30a7d5afce1403dc3807f0cb845711726a3172e91a1f73b5fda61981dd30690174cbb10dfaf4312c39'
7
+ data.tar.gz: 8267024bd5dbc3802a7f56e4d68683fe7670fbe2a24f50936825808533798cd60cebd966f0bbc63552b677e96f213426f21e401bbaa2a18779825236118ced0f
data/CONTRIBUTING.md CHANGED
@@ -18,7 +18,7 @@ To check the packaged gem and standalone command:
18
18
 
19
19
  ```sh
20
20
  gem build native-packages.gemspec
21
- ruby test/gem_install.rb native-packages-0.13.0.gem
21
+ ruby test/gem_install.rb native-packages-0.14.1.gem
22
22
  ```
23
23
 
24
24
  See [Releasing the gem](docs/releasing.md) for publication and
@@ -19,7 +19,7 @@ own compiled executable, or build the tiny example below.
19
19
  You need Ruby 3.2 or later. Install the version used by these guides:
20
20
 
21
21
  ```sh
22
- gem install native-packages --version 0.13.0
22
+ gem install native-packages --version 0.14.1
23
23
  ```
24
24
 
25
25
  For Linux packages, install **nFPM 2.47.0**, the helper native-packages uses to
@@ -81,7 +81,7 @@ Open the generated `native-packages.yaml` and replace its contents with:
81
81
  ```yaml
82
82
  schema: 1
83
83
  tool:
84
- version: '0.13.0'
84
+ version: '0.14.1'
85
85
  nfpm: '2.47.0'
86
86
 
87
87
  nfpm:
@@ -24,7 +24,7 @@ packaging:
24
24
  needs: release
25
25
  permissions:
26
26
  contents: write
27
- uses: crmne/native-packages/.github/workflows/package.yml@v0.13.0
27
+ uses: crmne/native-packages/.github/workflows/package.yml@v0.14.1
28
28
  with:
29
29
  version: ${{ github.ref_name }}
30
30
  publish: true
@@ -39,7 +39,7 @@ The configuration must include `release.repository` and a `release_asset`
39
39
  for each selected target. See [Publishing a release](publishing.md).
40
40
 
41
41
  Use the same native-packages release for the workflow and `tool.version`.
42
- For an immutable workflow reference, replace `v0.13.0` with that release's
42
+ For an immutable workflow reference, replace `v0.14.1` with that release's
43
43
  full commit SHA.
44
44
 
45
45
  ## Build without publishing
@@ -57,7 +57,7 @@ permissions:
57
57
  contents: read
58
58
  jobs:
59
59
  packaging:
60
- uses: crmne/native-packages/.github/workflows/package.yml@v0.13.0
60
+ uses: crmne/native-packages/.github/workflows/package.yml@v0.14.1
61
61
  ```
62
62
 
63
63
  Validation does not compile the app or check that future release inputs exist.
@@ -72,7 +72,7 @@ packaging:
72
72
  needs: build
73
73
  permissions:
74
74
  contents: write
75
- uses: crmne/native-packages/.github/workflows/package.yml@v0.13.0
75
+ uses: crmne/native-packages/.github/workflows/package.yml@v0.14.1
76
76
  with:
77
77
  version: '1.2.3'
78
78
  source-artifact: linux-binaries
@@ -129,7 +129,8 @@ GitHub repository:
129
129
  | AUR group `aur` | `PUBLISH_AUR=true` | `AUR_SSH_KEY`, `AUR_KNOWN_HOSTS` |
130
130
  | Destination or group `homebrew` | `PUBLISH_HOMEBREW=true` | `HOMEBREW_TAP_SSH_KEY` or `HOMEBREW_TAP_GITHUB_TOKEN` |
131
131
 
132
- These steps run only with `publish: true`. For Homebrew, prefer a deploy key
132
+ These steps run only with `publish: true` and a version that is not a
133
+ prerelease; a prerelease only gets its release assets. For Homebrew, prefer a deploy key
133
134
  with write access to the tap alone (`gh repo deploy-key add KEY.pub --repo
134
135
  OWNER/homebrew-tap --allow-write`) stored as `HOMEBREW_TAP_SSH_KEY`: GitHub URLs in that step then go over SSH,
135
136
  checked against GitHub's published host keys. A token
@@ -139,6 +140,28 @@ Use `secrets: inherit` as in the release example, or pass the named secrets
139
140
  explicitly. If another tool already publishes a destination, keep one
140
141
  publisher responsible for it.
141
142
 
143
+ ## Publish hosted repositories
144
+
145
+ An `apt`, `dnf` or `pacman` section with a
146
+ [bucket](hosted-repositories.md#publish-to-a-bucket) is published by the
147
+ workflow right after the release assets are attached. Set the repository
148
+ variable `PUBLISH_HOSTED=true` and these secrets in your application's
149
+ GitHub repository:
150
+
151
+ | Secret | Purpose |
152
+ | --- | --- |
153
+ | `NATIVE_PACKAGES_GPG_KEY` | The repository signing key's armored secret key. |
154
+ | `NATIVE_PACKAGES_GPG_PASSPHRASE` | Its passphrase, if it has one. |
155
+ | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | Credentials that can read, write and delete in the bucket. |
156
+
157
+ The step runs only with `publish: true` and a version that is not a
158
+ prerelease, and publishes every section with a `bucket`; sections that only
159
+ write a directory are left to your own steps, since the runner's copy would
160
+ be lost. It installs `createrepo_c` when there is a DNF repository. A
161
+ section's `directory`, if set, is kept in the Actions cache between runs, so
162
+ only new files are downloaded; publishing corrects whatever an older copy
163
+ holds. A missing secret, or a publication that fails, fails the job.
164
+
142
165
  ## Multiple jobs and configurations
143
166
 
144
167
  The reusable workflow gives different configuration paths and target
@@ -65,12 +65,13 @@ flatpak:
65
65
 
66
66
  | Field | Purpose |
67
67
  | --- | --- |
68
- | `directory` | Required. Where the repository is written, relative to the configuration file. |
68
+ | `directory` | Required, unless `bucket` is set. Where the repository is written, relative to the configuration file. With `bucket`, a working copy of the bucket, kept between publications to save downloads; a temporary directory if omitted. |
69
69
  | `url` | Required. The `https://` URL at which that directory is served. |
70
70
  | `signing_key` | Required. The signing key's full fingerprint. |
71
71
  | `keep` | APT, DNF and pacman only. How many versions of each package and architecture to keep. Defaults to `3`. |
72
72
  | `suite`, `component` | APT only. Default to `stable` and `main`. |
73
73
  | `name` | APT, DNF and pacman only. The repository's name: it names the key and source files users download, APT's `Origin` and `Label`, and the section in `.repo` files and `pacman.conf`. Defaults to the package name; set it when several apps share the repository. |
74
+ | `bucket` | APT, DNF and pacman only. Publish into an S3-compatible bucket; see [Publish to a bucket](#publish-to-a-bucket). |
74
75
  | `title`, `homepage` | Flatpak only. The repository's name in software centers (defaults to the package name) and an `https://` homepage. |
75
76
 
76
77
  ## 3. Publish
@@ -94,12 +95,87 @@ indexes are rebuilt from every package in the directory, whichever app
94
95
  published it, and `keep` counts versions of each package separately, so
95
96
  publishing one app leaves the others' packages listed. For this to hold, the
96
97
  directory must contain everything already published before you publish into
97
- it: when the repository lives in object storage rather than a Git checkout,
98
- download it first, publish, then upload it, and let one release publish at a
99
- time. Use the same signing key for every app, and give each repository the
100
- same `name` in every app's configuration, such as the name of your site,
101
- rather than an app's: users then add one `example.sources`, `example.repo` or
102
- `[example]` section and get every app from it.
98
+ it, and one release must publish at a time. A [bucket](#publish-to-a-bucket)
99
+ takes care of both. Use the same signing key for every app, and give each
100
+ repository the same `name` in every app's configuration, such as the name of
101
+ your site, rather than an app's: users then add one `example.sources`,
102
+ `example.repo` or `[example]` section and get every app from it.
103
+
104
+ ### Publish to a bucket
105
+
106
+ Each repository can live in an S3-compatible bucket, such as Cloudflare R2
107
+ or Amazon S3, served from the bucket's public URL or a domain in front of it.
108
+ Every app's release then publishes straight into it:
109
+
110
+ ```yaml
111
+ apt:
112
+ url: https://packages.example.org/apt
113
+ name: example
114
+ signing_key: 0123456789ABCDEF0123456789ABCDEF01234567
115
+ bucket:
116
+ endpoint: https://ACCOUNT_ID.r2.cloudflarestorage.com
117
+ name: packages
118
+ prefix: apt
119
+ pacman:
120
+ url: https://packages.example.org/arch
121
+ name: example
122
+ signing_key: 0123456789ABCDEF0123456789ABCDEF01234567
123
+ bucket:
124
+ endpoint: https://ACCOUNT_ID.r2.cloudflarestorage.com
125
+ name: packages
126
+ prefix: arch
127
+ ```
128
+
129
+ | Field | Purpose |
130
+ | --- | --- |
131
+ | `endpoint` | Required. The bucket service's `https://` URL, without a path. |
132
+ | `name` | Required. The bucket's name. |
133
+ | `prefix` | Required. The folder in the bucket that holds this repository and nothing else, such as `apt`. Repositories cannot share or nest folders. |
134
+ | `region` | The bucket's region. Defaults to `auto`, which R2 expects; S3 needs the real one. |
135
+ | `lock_timeout` | How many seconds to wait for another publication to finish. Defaults to `900`. |
136
+
137
+ The credentials come from `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`
138
+ (and `AWS_SESSION_TOKEN` if you use one), which native-packages removes from
139
+ its environment before running any other program. On R2, make an API token
140
+ with Object Read & Write permission for this bucket alone. Then
141
+ `publish --to apt,pacman`:
142
+
143
+ 1. Takes the lock: it creates `PREFIX/.lock`, recording who publishes and
144
+ since when, only if no such object exists. If another publication holds
145
+ it, it waits, up to `lock_timeout`. A lock older than 30 minutes belongs
146
+ to a publication that died; it is broken with a warning.
147
+ 2. Copies the repository from the bucket into `directory`, downloading only
148
+ the files it lacks or holds in another version. Rebuilding the indexes
149
+ reads every package, so the working copy holds them all; keep
150
+ `directory` between runs (in a CI cache, for example) to download only
151
+ what changed. R2 does not charge for these downloads.
152
+ 3. Publishes there, as without a bucket.
153
+ 4. Uploads what changed: first the packages and their signatures, with
154
+ `Cache-Control: public, max-age=31536000, immutable`, then the indexes,
155
+ with `public, max-age=60`, and last the files that point at them
156
+ (`InRelease`, `repomd.xml`, the pacman databases). Each file gets its
157
+ content type.
158
+ 5. Deletes what pruning removed, once the indexes no longer list it, and
159
+ releases the lock, also when publishing fails.
160
+
161
+ A package already in the bucket can only be published again unchanged.
162
+ `PREFIX/.published` records every package file ever uploaded with its
163
+ SHA-256, so one deleted from the bucket and published again with other
164
+ contents is refused too: caches may hold the old one for a year. Give a
165
+ rebuilt package a new version or release number instead.
166
+
167
+ A release workflow passes the secrets to the publish step:
168
+
169
+ ```yaml
170
+ - run: native-packages publish --from dist/native-packages --to github,apt,dnf,pacman
171
+ env:
172
+ GH_TOKEN: ${{ github.token }}
173
+ NATIVE_PACKAGES_GPG_KEY: ${{ secrets.NATIVE_PACKAGES_GPG_KEY }}
174
+ AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
175
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
176
+ ```
177
+
178
+ Publishing DNF repositories still needs `createrepo_c` on the runner.
103
179
 
104
180
  ## APT
105
181
 
@@ -33,7 +33,7 @@ Here is a complete configuration for an ARM64 Mac app and an x86-64 Windows app:
33
33
  ```yaml
34
34
  schema: 1
35
35
  tool:
36
- version: '0.13.0'
36
+ version: '0.14.1'
37
37
  nfpm: '2.47.0'
38
38
  nfpm:
39
39
  name: hello
@@ -67,7 +67,7 @@ Package publication's separate `packaging-checksums.txt` is also unchanged.
67
67
 
68
68
  ## Attest in the application's build job
69
69
 
70
- The examples use `v0.13.0` for readability. For release workflows, replace it
70
+ The examples use `v0.14.1` for readability. For release workflows, replace it
71
71
  with that release's reviewed full commit SHA, not a mutable branch.
72
72
  After producing the final package, before uploading it, add this step to the
73
73
  job that built it:
@@ -79,7 +79,7 @@ permissions:
79
79
  attestations: write
80
80
  steps:
81
81
  # Existing checkout, build, platform signing and packaging steps go here.
82
- - uses: crmne/native-packages/.github/actions/attest@v0.13.0
82
+ - uses: crmne/native-packages/.github/actions/attest@v0.14.1
83
83
  with:
84
84
  subject-path: dist/*.tar.gz
85
85
  ```
@@ -108,7 +108,7 @@ and install Ruby 3.2 or later with Ed25519-capable OpenSSL before the signing
108
108
  step. Then call:
109
109
 
110
110
  ```yaml
111
- - uses: crmne/native-packages/.github/actions/sign-release@v0.13.0
111
+ - uses: crmne/native-packages/.github/actions/sign-release@v0.14.1
112
112
  with:
113
113
  directory: dist/release
114
114
  public-key: assets/update-public-key.hex
@@ -152,7 +152,7 @@ jobs:
152
152
  - uses: ruby/setup-ruby@v1
153
153
  with:
154
154
  ruby-version: '4.0'
155
- - run: gem install native-packages --version 0.13.0 --no-document
155
+ - run: gem install native-packages --version 0.14.1 --no-document
156
156
  - run: cargo build --locked --release --target x86_64-pc-windows-msvc
157
157
  - name: Sign in to Azure for code signing
158
158
  if: vars.AZURE_SIGNING_PROFILE != ''
@@ -99,7 +99,9 @@ native-packages publish --from dist/linux --to github --target linux-amd64
99
99
  `--from` selects the build directory; `--to` lists destinations separated by
100
100
  commas. `github` uploads release assets, `snapcraft` uploads snaps to the
101
101
  Snap Store, and `apt`, `dnf`, `pacman` and `flatpak` write the signed repositories configured under
102
- `apt`, `dnf`, `pacman` and `flatpak.repository`. Other names select entries or groups in `repositories`.
102
+ `apt`, `dnf`, `pacman` and `flatpak.repository`. An APT, DNF or pacman
103
+ repository with a `bucket` is published into it under the bucket's lock;
104
+ see [Publish to a bucket](../_guides/hosted-repositories.md#publish-to-a-bucket). Other names select entries or groups in `repositories`.
103
105
 
104
106
  The build must be complete and its recorded files unmodified. Repeated
105
107
  `--target` options require exactly those targets, with all their formats.
@@ -222,7 +224,7 @@ If several gem versions are installed, RubyGems lets you select the one required
222
224
  by the configuration:
223
225
 
224
226
  ```sh
225
- native-packages _0.13.0_ build --version 1.2.3
227
+ native-packages _0.14.1_ build --version 1.2.3
226
228
  ```
227
229
 
228
230
  Bundler also works if you prefer to manage the gem in a Gemfile.
@@ -28,7 +28,7 @@ expressions. Use the replacement values listed below.
28
28
  | Field | Purpose |
29
29
  | --- | --- |
30
30
  | `schema` | Required. Set to `1`. |
31
- | `tool.version` | Required. Exact native-packages version, such as `'0.13.0'`. |
31
+ | `tool.version` | Required. Exact native-packages version, such as `'0.14.1'`. |
32
32
  | `tool.nfpm` | Required. Set to `'2.47.0'`, including in native-only configurations. |
33
33
  | `nfpm` | Shared package metadata and installed-file mappings, or a relative YAML filename. Requires `name`. |
34
34
  | `targets` | Required. Named build targets; use `{}` for recipe-only projects. |
@@ -43,9 +43,9 @@ expressions. Use the replacement values listed below.
43
43
  | `windows` | Optional. `windows.signing` turns on [Windows code signing](#windows-signing). |
44
44
  | `flatpak` | Required by `flatpak` targets: the app ID, runtime, command and permissions. See [Flatpak](platforms.md#flatpak). |
45
45
  | `snap` | Required by `snap` targets: the base, confinement and apps, and the Snap Store channels. See [Snap](platforms.md#snap). |
46
- | `apt` | Optional signed APT repository for `publish --to apt`. See [Hosted package repositories](../_guides/hosted-repositories.md). |
47
- | `dnf` | Optional signed DNF repository for `publish --to dnf`. See [Hosted package repositories](../_guides/hosted-repositories.md). |
48
- | `pacman` | Optional signed pacman repository for `publish --to pacman`. See [Hosted package repositories](../_guides/hosted-repositories.md). |
46
+ | `apt` | Optional signed APT repository for `publish --to apt`, in a directory or an S3-compatible bucket. See [Hosted package repositories](../_guides/hosted-repositories.md). |
47
+ | `dnf` | Optional signed DNF repository for `publish --to dnf`, in a directory or a bucket. See [Hosted package repositories](../_guides/hosted-repositories.md). |
48
+ | `pacman` | Optional signed pacman repository for `publish --to pacman`, in a directory or a bucket. See [Hosted package repositories](../_guides/hosted-repositories.md). |
49
49
 
50
50
  Quote tool versions so they remain strings. A version mismatch reports the
51
51
  command needed to install and select the configured gem.
@@ -23,8 +23,8 @@ working on with `doctor --target ID` and `build --target ID --dry-run`.
23
23
  Install and select the version named in the error:
24
24
 
25
25
  ```sh
26
- gem install native-packages --version 0.13.0
27
- native-packages _0.13.0_ doctor
26
+ gem install native-packages --version 0.14.1
27
+ native-packages _0.14.1_ doctor
28
28
  ```
29
29
 
30
30
  `tool.version` is an exact match. In CI, use the matching released reusable
@@ -1,7 +1,7 @@
1
1
  # Supply the listed build outputs before running this example.
2
2
  schema: 1
3
3
  tool:
4
- version: '0.13.0'
4
+ version: '0.14.1'
5
5
  nfpm: '2.47.0'
6
6
  nfpm:
7
7
  name: example-app
@@ -3,7 +3,7 @@
3
3
  # packaging/org.example.App.metainfo.xml before building.
4
4
  schema: 1
5
5
  tool:
6
- version: '0.13.0'
6
+ version: '0.14.1'
7
7
  nfpm: '2.47.0'
8
8
  nfpm:
9
9
  name: example-app
@@ -1,6 +1,6 @@
1
1
  schema: 1
2
2
  tool:
3
- version: '0.13.0'
3
+ version: '0.14.1'
4
4
  nfpm: '2.47.0'
5
5
  nfpm:
6
6
  name: example-app
@@ -12,7 +12,8 @@ module NativePackages
12
12
  # by this class without Debian's own tools. Beside them go the public key
13
13
  # (NAME.gpg) and a deb822 NAME.sources file for users to install.
14
14
  class AptRepository < HostedRepository
15
- KEYS = (HostedRepository::KEYS + %w[name suite component]).freeze
15
+ SECTION = "apt"
16
+ KEYS = (HostedRepository::KEYS + %w[name bucket suite component]).freeze
16
17
  WORD = /\A[a-z0-9][a-z0-9._-]*\z/
17
18
  # The order apt-ftparchive writes; other fields follow in their own order.
18
19
  FIELDS = %w[Package Version Architecture].freeze
@@ -26,10 +27,6 @@ module NativePackages
26
27
  end
27
28
  end
28
29
 
29
- def initialize(configuration)
30
- super(configuration, configuration.data.fetch("apt") { raise Error, "configure apt to publish --to apt" })
31
- end
32
-
33
30
  def suite = settings.fetch("suite", "stable")
34
31
  def component = settings.fetch("component", "main")
35
32
 
@@ -104,10 +101,11 @@ module NativePackages
104
101
 
105
102
  def publish(debs, secret: nil, passphrase: nil)
106
103
  raise Error, "the build contains no deb packages to publish --to apt" if debs.empty?
107
- debs.each do |path|
104
+ names = debs.map do |path|
108
105
  package = self.class.fields(self.class.control(path)).fetch("Package")
109
106
  prefix = package.start_with?("lib") ? package[0, 4] : package[0]
110
107
  place(path, directory / "pool" / component / prefix / package / path.basename)
108
+ package
111
109
  end
112
110
  entries = Pathname.glob(directory / "pool/**/*.deb").sort.to_h do |path|
113
111
  control = self.class.control(path)
@@ -116,14 +114,19 @@ module NativePackages
116
114
  end
117
115
  entries = prune(entries) { |left, right| self.class.compare(left, right) }
118
116
  signer(secret: secret, passphrase: passphrase).session { |signing| write_indexes(entries, signing) }
119
- puts "Published #{entries.length} package#{"s" unless entries.length == 1} to #{directory}. Install with:", *instructions.map { |line| " #{line}" }
117
+ puts "Published #{entries.length} package#{"s" unless entries.length == 1} to #{directory}. Install with:", *instructions(names.uniq).map { |line| " #{line}" }
120
118
  end
121
119
 
122
- def instructions
120
+ # Package files keep their contents once published; indexes change.
121
+ def immutable = Pathname.glob(directory / "pool/**/*.deb").sort
122
+
123
+ def entry_points = %w[Release Release.gpg InRelease].map { |file| directory / "dists" / suite / file }
124
+
125
+ def instructions(packages = [name])
123
126
  ["sudo install -d -m 0755 /etc/apt/keyrings",
124
127
  "sudo curl -fsSLo /etc/apt/keyrings/#{repository}.gpg #{url}/#{repository}.gpg",
125
128
  "sudo curl -fsSLo /etc/apt/sources.list.d/#{repository}.sources #{url}/#{repository}.sources",
126
- "sudo apt update && sudo apt install #{name}"]
129
+ "sudo apt update && sudo apt install #{packages.join(' ')}"]
127
130
  end
128
131
 
129
132
  private
@@ -143,7 +146,7 @@ module NativePackages
143
146
  write(dists / "#{relative}.gz", gzip(text))
144
147
  [relative, "#{relative}.gz"]
145
148
  end
146
- write(dists / "Release", release(dists, architectures, indexes))
149
+ write(dists / "Release", release_text(dists, architectures, indexes))
147
150
  signing.clearsign(dists / "Release", dists / "InRelease")
148
151
  signing.detach_sign(dists / "Release", dists / "Release.gpg")
149
152
  write(directory / "#{repository}.gpg", signing.public_key)
@@ -165,7 +168,7 @@ module NativePackages
165
168
  "MD5sum: #{Digest::MD5.hexdigest(bytes)}\nSHA1: #{Digest::SHA1.hexdigest(bytes)}\nSHA256: #{Digest::SHA256.hexdigest(bytes)}\n"
166
169
  end
167
170
 
168
- def release(dists, architectures, indexes)
171
+ def release_text(dists, architectures, indexes)
169
172
  epoch = ENV["SOURCE_DATE_EPOCH"] ? Integer(ENV.fetch("SOURCE_DATE_EPOCH")) : Time.now.to_i
170
173
  lines = ["Origin: #{repository}", "Label: #{repository}", "Suite: #{suite}", "Codename: #{suite}",
171
174
  "Date: #{Time.at(epoch).utc.strftime('%a, %d %b %Y %H:%M:%S UTC')}", "Architectures: #{architectures.join(' ')}",
@@ -0,0 +1,265 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "etc"
5
+ require "json"
6
+ require "net/http"
7
+ require "openssl"
8
+ require "securerandom"
9
+ require "socket"
10
+ require "time"
11
+ require "uri"
12
+
13
+ module NativePackages
14
+ # An S3-compatible bucket, such as Cloudflare R2 or Amazon S3, spoken to
15
+ # with plain HTTP requests signed with AWS Signature Version 4. Keys are
16
+ # addressed path-style (ENDPOINT/BUCKET/KEY), which R2, S3 and MinIO all
17
+ # accept.
18
+ class Bucket
19
+ KEYS = %w[endpoint name prefix region lock_timeout].freeze
20
+ ACCESS = "AWS_ACCESS_KEY_ID"
21
+ SECRET = "AWS_SECRET_ACCESS_KEY"
22
+ SESSION = "AWS_SESSION_TOKEN"
23
+ NAME = /\A[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]\z/
24
+ PREFIX = %r{\A[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*\z}
25
+ LOCK_TIMEOUT = 15 * 60
26
+ # A lock older than this belongs to a publication that died.
27
+ STALE = 30 * 60
28
+ ATTEMPTS = 4
29
+
30
+ # The credentials from the environment, removed from it so that no later
31
+ # subprocess inherits them.
32
+ def self.environment = { access: ENV.delete(ACCESS), secret: ENV.delete(SECRET), session: ENV.delete(SESSION) }
33
+
34
+ def self.check(settings, label)
35
+ raise Error, "#{label}: expected a mapping" unless settings.is_a?(Hash)
36
+ unknown = settings.keys - KEYS
37
+ raise Error, "#{label}: unknown fields #{unknown.join(', ')}" unless unknown.empty?
38
+ endpoint = settings["endpoint"]
39
+ # Plain HTTP only reaches a server on this machine, such as a test one.
40
+ unless endpoint.is_a?(String) && (%r{\Ahttps://[^\s/]+/?\z}.match?(endpoint) || %r{\Ahttp://(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?/?\z}.match?(endpoint))
41
+ raise Error, "#{label}.endpoint: expected the bucket service's https:// URL, without a path"
42
+ end
43
+ raise Error, "#{label}.name: expected the bucket's name" unless NAME.match?(settings["name"].to_s)
44
+ # Publishing deletes what the repository no longer holds under the
45
+ # prefix, so the repository never shares the bucket's root.
46
+ unless PREFIX.match?(settings["prefix"].to_s) && settings["prefix"].split("/").none? { |part| %w[. ..].include?(part) }
47
+ raise Error, "#{label}.prefix: name the folder in the bucket that holds this repository alone, such as apt"
48
+ end
49
+ raise Error, "#{label}.region: expected a string" if settings.key?("region") && !settings["region"].is_a?(String)
50
+ timeout = settings.fetch("lock_timeout", LOCK_TIMEOUT)
51
+ raise Error, "#{label}.lock_timeout: expected seconds to wait for another publication (0 or more)" unless timeout.is_a?(Integer) && !timeout.negative?
52
+ end
53
+
54
+ # Fails if two repositories write into the same bucket folder, or one into
55
+ # another's, since each deletes what it does not hold.
56
+ def self.check_overlaps(sections)
57
+ places = sections.filter_map do |label, settings|
58
+ bucket = settings.is_a?(Hash) && settings["bucket"]
59
+ [label, bucket["endpoint"].to_s.chomp("/"), bucket["name"], "#{bucket['prefix']}/"] if bucket.is_a?(Hash)
60
+ end
61
+ places.combination(2).each do |(first, *one), (second, *other)|
62
+ next unless one[0, 2] == other[0, 2] && (one[2].start_with?(other[2]) || other[2].start_with?(one[2]))
63
+ raise Error, "#{first}.bucket and #{second}.bucket: give each repository a prefix of its own"
64
+ end
65
+ nil
66
+ end
67
+
68
+ attr_reader :prefix, :lock_timeout
69
+
70
+ def initialize(settings, access: nil, secret: nil, session: nil)
71
+ missing = [[ACCESS, access], [SECRET, secret]].select { |_, value| value.to_s.empty? }.map(&:first)
72
+ raise Error, "set #{missing.join(' and ')} to publish to the bucket" unless missing.empty?
73
+ @endpoint = URI(settings.fetch("endpoint").chomp("/"))
74
+ @bucket = settings.fetch("name")
75
+ @prefix = settings.fetch("prefix")
76
+ @region = settings.fetch("region", "auto")
77
+ @lock_timeout = settings.fetch("lock_timeout", LOCK_TIMEOUT)
78
+ @access, @secret, @session = access, secret, session
79
+ end
80
+
81
+ def key(relative) = "#{prefix}/#{relative}"
82
+
83
+ # Every object under the prefix: key => [size, ETag without quotes].
84
+ def list
85
+ objects = {}
86
+ token = nil
87
+ loop do
88
+ query = { "list-type" => "2", "prefix" => "#{prefix}/" }
89
+ query["continuation-token"] = token if token
90
+ body = request("GET", nil, query: query, expect: [200]).body
91
+ body.scan(%r{<Contents>(.*?)</Contents>}m).each do |(entry)|
92
+ objects[text(entry, "Key")] = [Integer(text(entry, "Size")), text(entry, "ETag").delete('"')]
93
+ end
94
+ break unless text(body, "IsTruncated") == "true"
95
+ token = text(body, "NextContinuationToken")
96
+ end
97
+ objects
98
+ end
99
+
100
+ # The object's bytes, or nil if there is none.
101
+ def get(key)
102
+ response = request("GET", key, expect: [200, 404])
103
+ response.code == "404" ? nil : [response.body, response["etag"].to_s.delete('"')]
104
+ end
105
+
106
+ # The object's Content-Type and Cache-Control, or nil if there is none.
107
+ def head(key)
108
+ response = request("HEAD", key, expect: [200, 404])
109
+ response.code == "404" ? nil : { "content-type" => response["content-type"], "cache-control" => response["cache-control"] }
110
+ end
111
+
112
+ # Writes the object at `key` to `destination`, checking its MD5 against
113
+ # the ETag when that is one.
114
+ def download(key, destination, etag)
115
+ body, = get(key)
116
+ raise Error, "#{key} disappeared from the bucket while it was locked" unless body
117
+ raise Error, "#{key} arrived damaged" if etag.match?(/\A\h{32}\z/) && Digest::MD5.hexdigest(body) != etag
118
+ destination.dirname.mkpath
119
+ destination.binwrite(body)
120
+ end
121
+
122
+ # Stores `body` at `key`. With `create`, only if there is no such object
123
+ # yet: returns false if there was one.
124
+ def put(key, body, content_type:, cache_control:, create: false)
125
+ headers = { "content-type" => content_type, "cache-control" => cache_control }
126
+ headers["if-none-match"] = "*" if create
127
+ response = request("PUT", key, body: body, headers: headers, expect: create ? [200, 409, 412] : [200])
128
+ response.code == "200"
129
+ end
130
+
131
+ # Deletes `key`; with `etag`, only that version of it.
132
+ def delete(key, etag: nil)
133
+ request("DELETE", key, headers: etag ? { "if-match" => %("#{etag}") } : {}, expect: [200, 204, 404, 412])
134
+ end
135
+
136
+ # Runs the block holding the lock at PREFIX/.lock, which only one writer
137
+ # can create: others wait for it, up to `lock_timeout` seconds, and one
138
+ # older than STALE is broken, loudly.
139
+ def locked
140
+ token = SecureRandom.hex(16)
141
+ owner = ENV["GITHUB_REPOSITORY"] && ENV["GITHUB_RUN_ID"] ? "#{ENV['GITHUB_SERVER_URL'] || 'https://github.com'}/#{ENV['GITHUB_REPOSITORY']}/actions/runs/#{ENV['GITHUB_RUN_ID']}" : "#{Etc.getlogin || 'someone'}@#{Socket.gethostname} (pid #{Process.pid})"
142
+ body = JSON.generate("owner" => owner, "created" => Time.now.utc.iso8601, "token" => token)
143
+ deadline = monotonic + lock_timeout
144
+ delay = 1.0
145
+ until put(key(".lock"), body, content_type: "application/json", cache_control: "no-store", create: true)
146
+ held, etag = get(key(".lock"))
147
+ if held
148
+ details = begin
149
+ JSON.parse(held)
150
+ rescue JSON::ParserError
151
+ {}
152
+ end
153
+ created = Time.iso8601(details["created"].to_s) rescue Time.at(0)
154
+ if Time.now - created > STALE
155
+ warn "native-packages: WARNING: breaking the lock on #{@bucket}/#{prefix}, held by #{details['owner'] || 'unknown'} since #{details['created'] || 'an unknown time'}, more than #{STALE / 60} minutes ago"
156
+ delete(key(".lock"), etag: etag)
157
+ next
158
+ end
159
+ if monotonic + delay > deadline
160
+ raise Error, "#{@bucket}/#{prefix} is locked by #{details['owner'] || 'another publication'} since #{details['created']}; gave up after #{lock_timeout} seconds"
161
+ end
162
+ puts "Waiting for #{details['owner'] || 'another publication'} to finish publishing to #{@bucket}/#{prefix}"
163
+ sleep delay
164
+ delay = [delay * 2, 30.0].min
165
+ end
166
+ end
167
+ @token = token
168
+ begin
169
+ yield
170
+ ensure
171
+ @token = nil
172
+ held, etag = get(key(".lock"))
173
+ if held && (JSON.parse(held)["token"] rescue nil) == token
174
+ delete(key(".lock"), etag: etag)
175
+ else
176
+ warn "native-packages: WARNING: the lock on #{@bucket}/#{prefix} was broken by another publication while this one held it"
177
+ end
178
+ end
179
+ end
180
+
181
+ # Fails unless this publication still holds the lock.
182
+ def check_lock
183
+ held, = get(key(".lock"))
184
+ owned = held && (JSON.parse(held)["token"] rescue nil) == @token
185
+ raise Error, "lost the lock on #{@bucket}/#{prefix} to another publication; nothing was uploaded" unless owned
186
+ end
187
+
188
+ private
189
+
190
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
191
+
192
+ def text(xml, tag)
193
+ value = xml[%r{<#{tag}>(.*?)</#{tag}>}m, 1]
194
+ value&.gsub(/&(lt|gt|quot|apos|amp|#(\d+)|#x(\h+));/) do
195
+ { "lt" => "<", "gt" => ">", "quot" => '"', "apos" => "'", "amp" => "&" }.fetch(Regexp.last_match(1)) do
196
+ (Regexp.last_match(2) ? Regexp.last_match(2).to_i : Regexp.last_match(3).to_i(16)).chr(Encoding::UTF_8)
197
+ end
198
+ end
199
+ end
200
+
201
+ # RFC 3986 encoding, as Signature Version 4 requires.
202
+ def escape(value, slash: true)
203
+ value.to_s.b.gsub(/[^A-Za-z0-9_.~\-#{slash ? '/' : ''}]/n) { |byte| format("%%%02X", byte.ord) }
204
+ end
205
+
206
+ def connection
207
+ @connection ||= Net::HTTP.new(@endpoint.host, @endpoint.port).tap do |http|
208
+ http.use_ssl = @endpoint.scheme == "https"
209
+ http.open_timeout = 30
210
+ http.read_timeout = 300
211
+ http.write_timeout = 300
212
+ end
213
+ end
214
+
215
+ # A signed request, retried on server and network errors. Fails on any
216
+ # status outside `expect`, naming the bucket's error code.
217
+ def request(method, key, query: {}, body: "", headers: {}, expect: [200])
218
+ path = "/#{escape(@bucket)}#{key ? "/#{escape(key)}" : ''}"
219
+ canonical_query = query.sort.map { |name, value| "#{escape(name, slash: false)}=#{escape(value, slash: false)}" }.join("&")
220
+ attempt = 0
221
+ begin
222
+ attempt += 1
223
+ signed = sign(method, path, canonical_query, body, headers)
224
+ request = Net::HTTPGenericRequest.new(method, !body.empty?, method != "HEAD", canonical_query.empty? ? path : "#{path}?#{canonical_query}")
225
+ signed.each { |name, value| request[name] = value }
226
+ # Objects such as Packages.gz arrive as stored, never decompressed.
227
+ request["accept-encoding"] = "identity"
228
+ request.body = body unless body.empty?
229
+ response = connection.request(request)
230
+ raise Retry, "#{method} #{key || @bucket}: HTTP #{response.code}" if response.code.start_with?("5") && attempt < ATTEMPTS
231
+ unless expect.include?(response.code.to_i)
232
+ code = response.body.to_s[%r{<Code>(.*?)</Code>}, 1]
233
+ raise Error, "bucket #{method} #{key || @bucket} failed: HTTP #{response.code}#{code ? " #{code}" : ''}"
234
+ end
235
+ response
236
+ rescue Retry, IOError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => error
237
+ raise Error, "bucket #{method} #{key || @bucket} failed: #{error.message}" if attempt >= ATTEMPTS
238
+ @connection&.finish rescue nil
239
+ @connection = nil
240
+ sleep 2**attempt
241
+ retry
242
+ end
243
+ end
244
+
245
+ class Retry < StandardError; end
246
+
247
+ def sign(method, path, query, body, extra)
248
+ time = Time.now.utc
249
+ stamp = time.strftime("%Y%m%dT%H%M%SZ")
250
+ date = stamp[0, 8]
251
+ payload = Digest::SHA256.hexdigest(body)
252
+ default_port = @endpoint.port == (@endpoint.scheme == "https" ? 443 : 80)
253
+ headers = extra.merge("host" => default_port ? @endpoint.host : "#{@endpoint.host}:#{@endpoint.port}",
254
+ "x-amz-date" => stamp, "x-amz-content-sha256" => payload)
255
+ headers["x-amz-security-token"] = @session if @session && !@session.empty?
256
+ names = headers.keys.map(&:downcase).sort
257
+ canonical = [method, path, query, names.map { |name| "#{name}:#{headers.fetch(name).to_s.strip}\n" }.join, names.join(";"), payload].join("\n")
258
+ scope = "#{date}/#{@region}/s3/aws4_request"
259
+ digest = OpenSSL::Digest.new("SHA256")
260
+ signing_key = ["AWS4#{@secret}", date, @region, "s3", "aws4_request"].reduce { |key, part| OpenSSL::HMAC.digest(digest, key, part) }
261
+ signature = OpenSSL::HMAC.hexdigest(digest, signing_key, ["AWS4-HMAC-SHA256", stamp, scope, Digest::SHA256.hexdigest(canonical)].join("\n"))
262
+ headers.merge("authorization" => "AWS4-HMAC-SHA256 Credential=#{@access}/#{scope}, SignedHeaders=#{names.join(';')}, Signature=#{signature}")
263
+ end
264
+ end
265
+ end
@@ -426,6 +426,8 @@ module NativePackages
426
426
  end
427
427
  # Read once: the signing key leaves the environment when it is read.
428
428
  signing = OpenPGP.environment unless (destinations & HOSTED).empty?
429
+ # Likewise the bucket's credentials, when a repository has a bucket.
430
+ credentials = Bucket.environment if (destinations & HOSTED).any? { |name| configuration.data[name].is_a?(Hash) && configuration.data[name]["bucket"] }
429
431
  destinations.each do |destination|
430
432
  if destination == "github"
431
433
  paths = manifest.fetch("packages").flat_map { |entry| [entry.fetch("path"), entry["zsync"]].compact.map { |path| output / path } }
@@ -439,13 +441,13 @@ module NativePackages
439
441
  run "gh", "release", "upload", "v#{manifest.fetch('version')}", *paths, checksums, "--repo", project.repository, "--clobber"
440
442
  end
441
443
  elsif destination == "apt"
442
- AptRepository.new(configuration).publish(packages(manifest, output, "deb"), **signing)
444
+ AptRepository.for(configuration).release(packages(manifest, output, "deb"), signing: signing, credentials: credentials || {})
443
445
  elsif destination == "dnf"
444
- DnfRepository.new(configuration).publish(packages(manifest, output, "rpm"), **signing)
446
+ DnfRepository.for(configuration).release(packages(manifest, output, "rpm"), signing: signing, credentials: credentials || {})
445
447
  elsif destination == "pacman"
446
- PacmanRepository.new(configuration).publish(packages(manifest, output, "archlinux"), **signing)
448
+ PacmanRepository.for(configuration).release(packages(manifest, output, "archlinux"), signing: signing, credentials: credentials || {})
447
449
  elsif destination == "flatpak"
448
- FlatpakRepository.new(configuration).publish(packages(manifest, output, "flatpak"), **signing)
450
+ FlatpakRepository.for(configuration).publish(packages(manifest, output, "flatpak"), **signing)
449
451
  elsif destination == "snapcraft"
450
452
  Snap.new(configuration).publish(packages(manifest, output, "snap"))
451
453
  else
@@ -193,6 +193,7 @@ module NativePackages
193
193
  AptRepository.validate(data)
194
194
  DnfRepository.validate(data)
195
195
  PacmanRepository.validate(data)
196
+ Bucket.check_overlaps(data.slice("apt", "dnf", "pacman"))
196
197
  FlatpakRepository.validate(data)
197
198
  project.repositories
198
199
  true
@@ -8,17 +8,14 @@ module NativePackages
8
8
  # beside it as repomd.xml.asc. Beside them go the public key (NAME.asc) and
9
9
  # a NAME.repo file for users to install.
10
10
  class DnfRepository < HostedRepository
11
+ SECTION = "dnf"
11
12
  TAGS = { 1000 => "name", 1001 => "version", 1002 => "release", 1003 => "epoch", 1022 => "arch", 1044 => "sourcerpm" }.freeze
12
13
  # Signature header tags for DSA, RSA, PGP, GPG and OpenPGP signatures.
13
14
  SIGNATURES = [267, 268, 1002, 1005, 278].freeze
14
15
 
15
16
  def self.validate(data)
16
17
  settings = data["dnf"]
17
- check(settings, "dnf", KEYS + %w[name]) unless settings.nil?
18
- end
19
-
20
- def initialize(configuration)
21
- super(configuration, configuration.data.fetch("dnf") { raise Error, "configure dnf to publish --to dnf" })
18
+ check(settings, "dnf", KEYS + %w[name bucket]) unless settings.nil?
22
19
  end
23
20
 
24
21
  # The name, version, release, epoch and architecture of the RPM at
@@ -96,9 +93,10 @@ module NativePackages
96
93
  def publish(rpms, secret: nil, passphrase: nil)
97
94
  raise Error, "the build contains no rpm packages to publish --to dnf" if rpms.empty?
98
95
  raise Error, "install createrepo_c to publish --to dnf" unless available?("createrepo_c")
99
- rpms.each do |path|
100
- self.class.header(path)
96
+ names = rpms.map do |path|
97
+ header = self.class.header(path)
101
98
  place(path, directory / "packages" / path.basename)
99
+ header.fetch("name")
102
100
  end
103
101
  entries = Pathname.glob(directory / "packages/*.rpm").sort.to_h do |path|
104
102
  header = self.class.header(path)
@@ -121,11 +119,20 @@ module NativePackages
121
119
  gpgcheck=#{signed ? 1 : 0}
122
120
  gpgkey=#{url}/#{repository}.asc
123
121
  REPO
124
- puts "Published #{entries.length} package#{"s" unless entries.length == 1} to #{directory}. Install with:", *instructions.map { |line| " #{line}" }
122
+ puts "Published #{entries.length} package#{"s" unless entries.length == 1} to #{directory}. Install with:", *instructions(names.uniq).map { |line| " #{line}" }
125
123
  end
126
124
 
127
- def instructions
128
- ["sudo curl -fsSLo /etc/yum.repos.d/#{repository}.repo #{url}/#{repository}.repo", "sudo dnf install #{name}"]
125
+ # The packages, and the metadata createrepo_c names after its checksum;
126
+ # repomd.xml, which points at the current metadata, changes.
127
+ def immutable
128
+ metadata = Pathname.glob(directory / "repodata/*").select { |path| path.file? && /\A\h{32,}-/.match?(path.basename.to_s) }
129
+ (Pathname.glob(directory / "packages/*.rpm") + metadata).sort
130
+ end
131
+
132
+ def entry_points = [directory / "repodata/repomd.xml", directory / "repodata/repomd.xml.asc"]
133
+
134
+ def instructions(packages = [name])
135
+ ["sudo curl -fsSLo /etc/yum.repos.d/#{repository}.repo #{url}/#{repository}.repo", "sudo dnf install #{packages.join(' ')}"]
129
136
  end
130
137
  end
131
138
  end
@@ -27,10 +27,12 @@ module NativePackages
27
27
  end
28
28
  end
29
29
 
30
+ def self.for(configuration) = new(configuration)
31
+
30
32
  def initialize(configuration)
31
33
  settings = configuration.data.fetch("flatpak", {})["repository"]
32
34
  raise Error, "configure flatpak.repository to publish --to flatpak" unless settings
33
- super(configuration, settings)
35
+ super(settings, root: configuration.root, package: configuration.name)
34
36
  @flatpak = Flatpak.new(configuration)
35
37
  end
36
38
 
@@ -2,18 +2,32 @@
2
2
 
3
3
  require "stringio"
4
4
  require "zlib"
5
+ require "set"
6
+ require_relative "bucket"
5
7
  require_relative "openpgp"
6
8
 
7
9
  module NativePackages
8
10
  # A signed package repository that native-packages writes into a directory,
9
- # such as a GitHub Pages checkout, to be served as static files. Writing is
10
- # all it does: the release process commits and pushes the directory.
11
+ # such as a GitHub Pages checkout, to be served as static files. Without a
12
+ # bucket, writing is all it does: the release process commits and pushes
13
+ # the directory. With one, publishing takes the bucket's lock, mirrors the
14
+ # repository into the directory, publishes there and uploads the changes.
11
15
  class HostedRepository
12
16
  include Support
13
17
  KEYS = %w[directory url keep signing_key].freeze
14
18
  KEEP = 3
15
19
  # A repository name: a file name and, for DNF and pacman, a section name.
16
20
  NAME = /\A[a-z0-9][a-z0-9_-]*\z/
21
+ # Files that never change once published, and everything else.
22
+ IMMUTABLE = "public, max-age=31536000, immutable"
23
+ MUTABLE = "public, max-age=60"
24
+ # Bucket objects that are not part of the repository's files.
25
+ LOCK = ".lock"
26
+ MANIFEST = ".published"
27
+ TYPES = { ".deb" => "application/vnd.debian.binary-package", ".rpm" => "application/x-rpm", ".zst" => "application/zstd",
28
+ ".xz" => "application/x-xz", ".gz" => "application/gzip", ".xml" => "application/xml", ".sig" => "application/pgp-signature",
29
+ ".asc" => "application/pgp-keys", ".gpg" => "application/pgp-keys", ".sources" => "text/plain; charset=utf-8",
30
+ ".repo" => "text/plain; charset=utf-8", ".db" => "application/gzip", ".files" => "application/gzip" }.freeze
17
31
  attr_reader :root, :name, :settings, :directory
18
32
 
19
33
  # Checks the settings shared by every hosted repository, under `label`.
@@ -21,7 +35,12 @@ module NativePackages
21
35
  raise Error, "#{label}: expected a mapping" unless settings.is_a?(Hash)
22
36
  unknown = settings.keys - keys
23
37
  raise Error, "#{label}: unknown fields #{unknown.join(', ')}" unless unknown.empty?
24
- raise Error, "#{label}.directory: name the directory to write the repository into" unless settings["directory"].is_a?(String) && !settings["directory"].empty?
38
+ if settings.key?("bucket")
39
+ Bucket.check(settings["bucket"], "#{label}.bucket")
40
+ raise Error, "#{label}.directory: expected a directory to keep a copy of the bucket in" if settings.key?("directory") && !(settings["directory"].is_a?(String) && !settings["directory"].empty?)
41
+ else
42
+ raise Error, "#{label}.directory: name the directory to write the repository into" unless settings["directory"].is_a?(String) && !settings["directory"].empty?
43
+ end
25
44
  unless settings["url"].is_a?(String) && %r{\Ahttps://[^\s/]+(?:/\S*)?\z}.match?(settings["url"])
26
45
  raise Error, "#{label}.url: expected the https:// URL the directory is served at"
27
46
  end
@@ -33,20 +52,50 @@ module NativePackages
33
52
  OpenPGP.fingerprint(settings["signing_key"], "#{label}.signing_key")
34
53
  end
35
54
 
36
- def initialize(configuration, settings)
37
- @root = configuration.root
38
- @name = configuration.name
55
+ # The repository a project's configuration sets up under SECTION.
56
+ def self.for(configuration)
57
+ settings = configuration.data.fetch(self::SECTION) { raise Error, "configure #{self::SECTION} to publish --to #{self::SECTION}" }
58
+ new(settings, root: configuration.root, package: configuration.name)
59
+ end
60
+
61
+ # `settings` is the repository's section, with its directory relative to
62
+ # `root`. `package`, the app's package name, is the default repository
63
+ # name; a repository shared by several apps names itself.
64
+ def initialize(settings, root:, package: nil)
65
+ @root = Pathname.new(root)
66
+ @name = package
39
67
  @settings = settings
40
- @directory = Pathname.new(settings.fetch("directory")).expand_path(root)
68
+ @directory = settings["directory"] && Pathname.new(settings.fetch("directory")).expand_path(root)
69
+ end
70
+
71
+ # Publishes `packages` into the directory, or into the bucket when one
72
+ # is configured, with `signing` (OpenPGP.environment) and `credentials`
73
+ # (Bucket.environment).
74
+ def release(packages, signing: {}, credentials: {})
75
+ return publish(packages, **signing) unless settings["bucket"]
76
+ bucket = Bucket.new(settings.fetch("bucket"), **credentials)
77
+ return synchronize(bucket, packages, signing) if directory
78
+ Dir.mktmpdir("native-packages-repository-") do |copy|
79
+ @directory = Pathname.new(copy)
80
+ synchronize(bucket, packages, signing)
81
+ ensure
82
+ @directory = nil
83
+ end
41
84
  end
42
85
 
86
+ # The files that never change once published, which caches may keep.
87
+ def immutable = []
88
+
89
+ # The files clients read first, which point at the rest: uploaded last.
90
+ def entry_points = []
91
+
43
92
  def url = settings.fetch("url").chomp("/")
44
93
  def keep = settings.fetch("keep", KEEP)
45
94
 
46
95
  # The name of the files users install (key, source list) and of the
47
96
  # repository itself, shared by every app that publishes into it. Defaults
48
97
  # to the package name.
49
- def repository = settings.fetch("name", name)
98
+ def repository = settings.fetch("name") { name or raise Error, "#{self.class::SECTION}.name: name the repository" }
50
99
 
51
100
  def signer(secret: nil, passphrase: nil)
52
101
  OpenPGP.new(OpenPGP.fingerprint(settings.fetch("signing_key"), "signing_key"), secret: secret, passphrase: passphrase)
@@ -84,6 +133,81 @@ module NativePackages
84
133
 
85
134
  private
86
135
 
136
+ def synchronize(bucket, packages, signing)
137
+ bucket.locked do
138
+ remote = bucket.list.filter_map do |key, (size, etag)|
139
+ relative = key.delete_prefix("#{bucket.prefix}/")
140
+ [relative, [size, etag]] unless [LOCK, MANIFEST].include?(relative) || relative.end_with?("/")
141
+ end.to_h
142
+ mirror(bucket, remote)
143
+ history = bucket.get(bucket.key(MANIFEST))&.first.to_s.lines.to_h { |line| line.chomp.split(" ", 2).reverse }
144
+ publish(packages, **signing)
145
+ upload(bucket, remote, history)
146
+ end
147
+ end
148
+
149
+ # Makes the directory hold exactly the bucket's files, downloading only
150
+ # those it lacks or holds in another version.
151
+ def mirror(bucket, remote)
152
+ directory.mkpath
153
+ files(directory).each { |path| path.delete unless remote.key?(path.relative_path_from(directory).to_s) }
154
+ count = 0
155
+ remote.each do |relative, (size, etag)|
156
+ path = directory / relative_path(relative)
157
+ next if path.file? && path.size == size && (!etag.match?(/\A\h{32}\z/) || Digest::MD5.file(path).hexdigest == etag)
158
+ bucket.download(bucket.key(relative), path, etag)
159
+ count += 1
160
+ end
161
+ puts "Downloaded #{count} of #{remote.length} files from the bucket"
162
+ end
163
+
164
+ # Uploads what publishing added or changed, package files first and the
165
+ # files that point at them last, then deletes what it removed.
166
+ def upload(bucket, remote, history)
167
+ local = files(directory).to_h { |path| [path.relative_path_from(directory).to_s, path] }
168
+ fixed = immutable.to_set { |path| path.relative_path_from(directory).to_s }
169
+ changed = local.reject do |relative, path|
170
+ size, etag = remote[relative]
171
+ # Mirrored files are as the bucket holds them when publishing left them alone.
172
+ size == path.size && (etag.match?(/\A\h{32}\z/) ? Digest::MD5.file(path).hexdigest == etag : fixed.include?(relative))
173
+ end
174
+ packages = changed.keys.select { |relative| fixed.include?(relative) && !relative.end_with?(".sig") && !relative.include?("repodata/") }
175
+ changed.each_key do |relative|
176
+ next unless fixed.include?(relative)
177
+ raise Error, "#{relative} is already in the bucket with different contents" if remote.key?(relative)
178
+ digest = Digest::SHA256.file(local.fetch(relative)).hexdigest
179
+ if packages.include?(relative) && history.key?(relative) && history[relative] != digest
180
+ raise Error, "#{relative} was published before with different contents, and caches may still hold it; publish it with a new version or release number"
181
+ end
182
+ end
183
+ bucket.check_lock
184
+ first = entry_points.to_set { |path| path.relative_path_from(directory).to_s }
185
+ ordered = changed.keys.sort_by { |relative| [first.include?(relative) ? 1 : 0, relative] }
186
+ lasting, current = ordered.partition { |relative| fixed.include?(relative) }
187
+ put = ->(relative, cache) { bucket.put(bucket.key(relative), local.fetch(relative).binread, content_type: content_type(relative), cache_control: cache) }
188
+ lasting.each { |relative| put.call(relative, IMMUTABLE) }
189
+ unless packages.empty?
190
+ # Recorded for good, so a package pruned and published again with
191
+ # other contents is refused while caches may still hold the old one.
192
+ packages.each { |relative| history[relative] = Digest::SHA256.file(local.fetch(relative)).hexdigest }
193
+ bucket.put(bucket.key(MANIFEST), history.sort.map { |relative, digest| "#{digest} #{relative}\n" }.join,
194
+ content_type: "text/plain; charset=utf-8", cache_control: "no-store")
195
+ end
196
+ # Indexes after the packages they list, and the files that point at
197
+ # the indexes last.
198
+ current.each { |relative| put.call(relative, MUTABLE) }
199
+ removed = (remote.keys - local.keys).sort
200
+ removed.each { |relative| bucket.delete(bucket.key(relative)) }
201
+ puts "Uploaded #{changed.length} and deleted #{removed.length} files in the bucket under #{bucket.prefix}/"
202
+ end
203
+
204
+ def content_type(relative)
205
+ name = File.basename(relative)
206
+ return "application/pgp-signature" if name.end_with?(".gpg", ".asc") && %w[Release.gpg repomd.xml.asc].include?(name)
207
+ return "text/plain; charset=utf-8" if %w[Release InRelease Packages].include?(name)
208
+ TYPES.fetch(File.extname(name), "application/octet-stream")
209
+ end
210
+
87
211
  # The same bytes for the same index: no name or time in the header.
88
212
  def gzip(text)
89
213
  io = StringIO.new("".b)
@@ -14,7 +14,8 @@ module NativePackages
14
14
  # the same file, as are REPO.files and REPO.files.tar.gz. Beside the
15
15
  # architectures goes the public key (REPO.asc) for users to trust.
16
16
  class PacmanRepository < HostedRepository
17
- KEYS = (HostedRepository::KEYS + %w[name]).freeze
17
+ SECTION = "pacman"
18
+ KEYS = (HostedRepository::KEYS + %w[name bucket]).freeze
18
19
  # The architecture directories an `any` package goes into when the
19
20
  # repository has none yet.
20
21
  ARCHITECTURES = %w[x86_64 aarch64].freeze
@@ -30,10 +31,6 @@ module NativePackages
30
31
  check(settings, "pacman", KEYS)
31
32
  end
32
33
 
33
- def initialize(configuration)
34
- super(configuration, configuration.data.fetch("pacman") { raise Error, "configure pacman to publish --to pacman" })
35
- end
36
-
37
34
  # The fields of the package at `path`, from its .PKGINFO: single values
38
35
  # as strings, repeatable ones as arrays.
39
36
  def self.info(path)
@@ -132,15 +129,21 @@ module NativePackages
132
129
  end
133
130
  write(directory / "#{repository}.asc", signing.public_key(armor: true))
134
131
  end
135
- puts "Published #{remaining.length} package#{"s" unless remaining.length == 1} to #{directory}. Install with:", *instructions.map { |line| " #{line}" }
132
+ puts "Published #{remaining.length} package#{"s" unless remaining.length == 1} to #{directory}. Install with:", *instructions(infos.values.map { |info| info.fetch("pkgname") }.uniq).map { |line| " #{line}" }
136
133
  end
137
134
 
138
- def instructions
135
+ # Packages and their signatures, which are written once; the databases
136
+ # change.
137
+ def immutable = published.flat_map { |path| [path, Pathname.new("#{path}.sig")] }.select(&:file?)
138
+
139
+ def entry_points = Pathname.glob(directory / "*/#{repository}.{db,files}{,.tar.gz}{,.sig}").sort
140
+
141
+ def instructions(packages = [name])
139
142
  fingerprint = OpenPGP.fingerprint(settings.fetch("signing_key"), "signing_key")
140
143
  ["curl -fsSL #{url}/#{repository}.asc | sudo pacman-key --add -",
141
144
  "sudo pacman-key --lsign-key #{fingerprint}",
142
145
  "printf '\\n[#{repository}]\\nSigLevel = Required\\nServer = #{url}/$arch\\n' | sudo tee -a /etc/pacman.conf",
143
- "sudo pacman -Syu #{name}"]
146
+ "sudo pacman -Syu #{packages.join(' ')}"]
144
147
  end
145
148
 
146
149
  private
@@ -62,9 +62,21 @@ module NativePackages
62
62
  output.strip
63
63
  end
64
64
 
65
+ # Whether the remote has no refs at all, as the repository of a package
66
+ # that was never published (a new AUR package's, for one).
67
+ def empty_remote?(name, url) = git(name, "ls-remote", url).empty?
68
+
69
+ # Whether `ref` exists in the checkout.
70
+ def ref?(name, ref) = git(name, "rev-parse", "--verify", "--quiet", "#{ref}^{commit}", allow_failure: true).last.success?
71
+
72
+ # The ID of the empty tree, which a first publication's diff starts from.
73
+ def empty_tree(name) = git(name, "hash-object", "-t", "tree", "--stdin")
74
+
65
75
  def refresh(name, entry)
66
76
  cache.mkpath
67
77
  path = checkout(name)
78
+ @empty ||= {}
79
+ @empty[name] = empty_remote?(name, entry.fetch("url"))
68
80
  if path.exist?
69
81
  raise Error, "#{path} is not a managed checkout" unless (path / ".git").directory?
70
82
  unless git(name, "remote", "get-url", "upstream") == entry.fetch("url") &&
@@ -74,15 +86,22 @@ module NativePackages
74
86
  end
75
87
  else
76
88
  path.dirname.mkpath
77
- git(name, "clone", "--filter=blob:none", "--depth=1", "--no-checkout", "--origin", "upstream",
78
- "--branch", entry.fetch("branch"), entry.fetch("url"), path)
89
+ if @empty[name]
90
+ # Nothing to clone: start the configured branch, unborn, to push it.
91
+ git(name, "init", "--initial-branch=#{entry.fetch('branch')}", path)
92
+ git(name, "remote", "add", "upstream", entry.fetch("url"))
93
+ else
94
+ git(name, "clone", "--filter=blob:none", "--depth=1", "--no-checkout", "--origin", "upstream",
95
+ "--branch", entry.fetch("branch"), entry.fetch("url"), path)
96
+ end
79
97
  git(name, "remote", "add", "origin", entry.fetch("fork_url", entry.fetch("url")))
80
98
  git(name, "remote", "set-url", "--push", "origin", entry.fetch("push_url", entry.fetch("url")))
81
99
  unless entry.fetch("package_path") == "."
82
100
  git(name, "sparse-checkout", "set", "--cone", entry.fetch("package_path"), ".github")
83
101
  end
84
- git(name, "checkout", "--detach", "upstream/#{entry.fetch('branch')}")
102
+ git(name, "checkout", "--detach", "upstream/#{entry.fetch('branch')}") unless @empty[name]
85
103
  end
104
+ return path if @empty[name]
86
105
  [entry.fetch("branch"), entry["status_branch"]].compact.uniq.each do |branch|
87
106
  git(name, "fetch", "--depth=1", "upstream", "+refs/heads/#{branch}:refs/remotes/upstream/#{branch}")
88
107
  end
@@ -208,16 +227,22 @@ module NativePackages
208
227
  end
209
228
  git(name, "check-ref-format", "--branch", branch)
210
229
  remote = remote_head(name, branch)
211
- base = "upstream/#{entry.fetch('branch')}"
212
- if remote && branch != entry.fetch("branch")
213
- git(name, "fetch", "--depth=1", "origin", "+refs/heads/#{branch}:refs/remotes/origin/#{branch}")
214
- base = "origin/#{branch}"
215
- end
216
- prevent_downgrade(name, repository_version(name, entry, base), version)
217
- prevent_downgrade(name, repository_version(name, entry, "upstream/#{entry.fetch('branch')}"), version)
218
- base_commit = git(name, "rev-parse", base)
219
230
  local_branch = "packaging/#{name}/#{version}-#{SecureRandom.hex(4)}"
220
- git(name, "switch", "-c", local_branch, base)
231
+ if @empty[name]
232
+ # A first publication: the package's files become the first commit.
233
+ base_commit = empty_tree(name)
234
+ git(name, "switch", "--orphan", local_branch)
235
+ else
236
+ base = "upstream/#{entry.fetch('branch')}"
237
+ if remote && branch != entry.fetch("branch")
238
+ git(name, "fetch", "--depth=1", "origin", "+refs/heads/#{branch}:refs/remotes/origin/#{branch}")
239
+ base = "origin/#{branch}"
240
+ end
241
+ prevent_downgrade(name, repository_version(name, entry, base), version)
242
+ prevent_downgrade(name, repository_version(name, entry, "upstream/#{entry.fetch('branch')}"), version)
243
+ base_commit = git(name, "rev-parse", base)
244
+ git(name, "switch", "-c", local_branch, base)
245
+ end
221
246
  # Compute every destination before writing; a symlink must never redirect a copy.
222
247
  destinations = sources.to_h { |relative, file| [contained_path(path, relative), file] }
223
248
  destinations.each do |target, source|
@@ -277,7 +302,8 @@ module NativePackages
277
302
  end
278
303
  raise Error, "#{name}: unstaged edits exist; review and git add them first" unless git(name, "diff", "--name-only").empty?
279
304
  raise Error, "#{name}: untracked files exist in the checkout" unless git(name, "ls-files", "--others", "--exclude-standard").empty?
280
- head = git(name, "rev-parse", "HEAD")
305
+ # Empty before a first publication's commit.
306
+ head = git(name, "rev-parse", "--verify", "--quiet", "HEAD", allow_failure: true).first.strip
281
307
  remote = remote_head(name, record.fetch("destination_branch"))
282
308
  unless remote == record["remote_commit"] || remote == head
283
309
  _, ancestry = git(name, "merge-base", "--is-ancestor", remote || "", head, allow_failure: true)
@@ -395,7 +421,11 @@ module NativePackages
395
421
  refresh(name, entry) unless offline
396
422
  if (checkout(name) / ".git").directory?
397
423
  row["upstream_branch"] = entry.fetch("status_branch", entry.fetch("branch"))
398
- row["upstream_version"] = repository_version(name, entry, "upstream/#{row.fetch('upstream_branch')}")
424
+ if ref?(name, "upstream/#{row.fetch('upstream_branch')}")
425
+ row["upstream_version"] = repository_version(name, entry, "upstream/#{row.fetch('upstream_branch')}")
426
+ else
427
+ row["upstream_state"] = "not published yet"
428
+ end
399
429
  row["local_changes"] = !git(name, "status", "--porcelain").empty?
400
430
  else
401
431
  row["remote_error"] = "not fetched (offline)"
@@ -416,7 +446,7 @@ module NativePackages
416
446
  else
417
447
  puts "TARGET UPSTREAM LOCAL OPEN REQUESTS"
418
448
  rows.each do |row|
419
- version = row["remote_error"] ? "unknown" : row["upstream_version"] || (entries.fetch(row.fetch("target"))["branch"] ? "absent" : "manual")
449
+ version = row["remote_error"] ? "unknown" : row["upstream_version"] || row["upstream_state"] || (entries.fetch(row.fetch("target"))["branch"] ? "absent" : "manual")
420
450
  puts "#{row.fetch('target').ljust(14)} #{version.ljust(14)} #{[row['local_version'], row['local_state']].compact.join(' ').ljust(22)} #{Array(row['requests']).map { |request| request.fetch('url') }.join(' ')}"
421
451
  %w[remote_error request_error notes].each { |key| puts " #{row[key]}" if row[key] }
422
452
  end
@@ -12,7 +12,7 @@ require "tmpdir"
12
12
  require "yaml"
13
13
 
14
14
  module NativePackages
15
- VERSION = "0.13.0"
15
+ VERSION = "0.14.1"
16
16
  class Error < StandardError; end
17
17
 
18
18
  module Support
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: native-packages
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.13.0
4
+ version: 0.14.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Carmine Paolino
@@ -58,6 +58,7 @@ files:
58
58
  - lib/native_packages.rb
59
59
  - lib/native_packages/appimage.rb
60
60
  - lib/native_packages/apt_repository.rb
61
+ - lib/native_packages/bucket.rb
61
62
  - lib/native_packages/build.rb
62
63
  - lib/native_packages/cli.rb
63
64
  - lib/native_packages/configuration.rb