anodizer_core/config/publishers/mod.rs
1use std::path::PathBuf;
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6use super::aur_source::AurSourceConfig;
7use super::hooks::HookEntry;
8use super::string_or_bool::HumanDuration;
9use super::{StringOrBool, deserialize_string_or_bool_opt};
10
11mod homebrew;
12pub use homebrew::*;
13
14mod chocolatey;
15pub use chocolatey::*;
16
17mod winget;
18pub use winget::*;
19
20mod aur;
21pub use aur::*;
22
23mod krew;
24pub use krew::*;
25
26mod nix;
27pub use nix::*;
28
29mod schemastore;
30pub use schemastore::{SchemaEntry, SchemaMode, SchemastoreConfig};
31
32// ---------------------------------------------------------------------------
33// Shared publisher config types: RepositoryConfig, CommitAuthorConfig
34// ---------------------------------------------------------------------------
35
36/// Shared repository configuration used by all git-based publishers
37/// (Homebrew, Scoop, Winget, Krew, Nix). A repository reference.
38#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
39#[serde(default, deny_unknown_fields)]
40pub struct RepositoryConfig {
41 /// Repository owner (GitHub user or organization).
42 pub owner: Option<String>,
43 /// Repository name.
44 pub name: Option<String>,
45 /// Auth token for the repository. Falls back to env-based resolution.
46 pub token: Option<String>,
47 /// Token type: "github" (default), "gitlab", "gitea".
48 pub token_type: Option<String>,
49 /// Branch to push to (default: repo default branch).
50 pub branch: Option<String>,
51 /// Git-specific settings for SSH-based publishing.
52 pub git: Option<GitRepoConfig>,
53 /// Pull request settings for fork-based workflows.
54 pub pull_request: Option<PullRequestConfig>,
55}
56
57/// Git-specific repository settings for SSH-based publishing.
58#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
59#[serde(default, deny_unknown_fields)]
60pub struct GitRepoConfig {
61 /// Git URL (e.g. `ssh://git@github.com/owner/repo.git`).
62 pub url: Option<String>,
63 /// Custom SSH command (e.g. `ssh -i /path/to/key`).
64 pub ssh_command: Option<String>,
65 /// Path to SSH private key file.
66 pub private_key: Option<String>,
67}
68
69/// Pull request configuration for fork-based publisher workflows.
70#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
71#[serde(default, deny_unknown_fields)]
72pub struct PullRequestConfig {
73 /// Enable PR creation instead of direct push.
74 pub enabled: Option<bool>,
75 /// Create PR as draft.
76 pub draft: Option<bool>,
77 /// Body text for the pull request.
78 pub body: Option<String>,
79 /// Target base repository/branch for the PR.
80 pub base: Option<PullRequestBaseConfig>,
81}
82
83/// Target base for pull requests (upstream repo to PR against).
84#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
85#[serde(default, deny_unknown_fields)]
86pub struct PullRequestBaseConfig {
87 /// Owner of the upstream repository to PR against.
88 pub owner: Option<String>,
89 /// Name of the upstream repository to PR against.
90 pub name: Option<String>,
91 /// Base branch of the upstream repository to target with the PR.
92 pub branch: Option<String>,
93}
94
95/// Shared commit author configuration with optional GPG/SSH signing.
96/// Commit-author identity for publisher commits.
97#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
98#[serde(default, deny_unknown_fields)]
99pub struct CommitAuthorConfig {
100 /// Git commit author display name.
101 pub name: Option<String>,
102 /// Git commit author email address.
103 pub email: Option<String>,
104 /// Commit signing configuration.
105 pub signing: Option<CommitSigningConfig>,
106 /// When true, omit the explicit `-c user.name=` / `-c user.email=`
107 /// overrides at commit time and let the running git client use the
108 /// invoking GitHub App's identity (i.e. the `<app-slug>[bot]@users.noreply.github.com`
109 /// account that the GitHub Actions checkout step has already configured
110 /// in the repo's local git config).
111 ///
112 /// The use-github-app-token toggle
113 /// uses the local git identity; the canonical use-case is
114 /// PRs against `homebrew/homebrew-core` / `kubernetes-sigs/krew-index`
115 /// / `microsoft/winget-pkgs` opened from a GitHub App workflow, where
116 /// EasyCLA / DCO / signed-commit policies require the App's identity
117 /// (rather than a per-user bot identity) to land the merge.
118 #[serde(default)]
119 pub use_github_app_token: bool,
120}
121
122impl CommitAuthorConfig {
123 /// Fill in the anodizer default name/email when either field is empty.
124 /// The commit-author defaulting, which
125 /// runs during the Default pass — so validation messages that reference
126 /// commit-author identity see non-empty strings rather than blanks.
127 pub fn normalize_defaults(&mut self) {
128 if self.name.as_deref().is_none_or(str::is_empty) {
129 self.name = Some("anodizer".to_string());
130 }
131 if self.email.as_deref().is_none_or(str::is_empty) {
132 self.email = Some("bot@anodizer.dev".to_string());
133 }
134 }
135}
136
137/// Commit signing configuration (GPG, x509, or SSH).
138#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
139#[serde(default, deny_unknown_fields)]
140pub struct CommitSigningConfig {
141 /// Enable commit signing.
142 pub enabled: Option<bool>,
143 /// Signing key identifier.
144 pub key: Option<String>,
145 /// Signing program (e.g. `gpg`, `gpg2`).
146 pub program: Option<String>,
147 /// Signing format: "openpgp" (default), "x509", or "ssh".
148 pub format: Option<String>,
149}
150
151// ---------------------------------------------------------------------------
152// PublishConfig
153// ---------------------------------------------------------------------------
154
155#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
156#[serde(default, deny_unknown_fields)]
157pub struct PublishConfig {
158 /// Publish to crates.io. Presence opts in; use `cargo: { skip: true }` to opt out.
159 pub cargo: Option<CargoPublishConfig>,
160 /// Homebrew formula publishing configuration.
161 pub homebrew: Option<HomebrewConfig>,
162 /// Homebrew Cask publishing configuration (macOS .app bundles).
163 ///
164 /// Uses the unified `HomebrewCaskConfig` which carries all fields from both
165 /// the per-crate cask config and the top-level `homebrew_casks:` config.
166 pub homebrew_cask: Option<HomebrewCaskConfig>,
167 /// Scoop manifest publishing configuration.
168 pub scoop: Option<ScoopConfig>,
169 /// Chocolatey package publishing configuration.
170 pub chocolatey: Option<ChocolateyConfig>,
171 /// WinGet manifest publishing configuration.
172 pub winget: Option<WingetConfig>,
173 /// AUR (Arch User Repository) binary package publishing configuration.
174 pub aur: Option<AurConfig>,
175 /// AUR source package publishing configuration (source-only PKGBUILD, not -bin).
176 pub aur_source: Option<AurSourceConfig>,
177 /// Krew (kubectl plugin manager) manifest publishing configuration.
178 pub krew: Option<KrewConfig>,
179 /// Nix derivation publishing configuration.
180 pub nix: Option<NixConfig>,
181
182 /// Hooks that fire once per FAILED publisher, after rollback has been
183 /// attempted. Each entry is a standard hook (`cmd` / `dir` / `env` /
184 /// `output`); the template surface adds `{{ .Publisher }}`,
185 /// `{{ .Error }}`, `{{ .Version }}`, `{{ .Tag }}`, `{{ .Group }}`
186 /// (Assets/Manager/Submitter), `{{ .Required }}`,
187 /// `{{ .RolledBack }}` — true if any publisher was rolled back (or
188 /// rollback was attempted and failed) during this run — and
189 /// `{{ .RunReport }}`, the path of this run's already-written
190 /// `dist/run-<id>/report.json` (per-publisher outcomes including
191 /// rollback results; empty in snapshot/dry-run or when the report
192 /// could not be persisted). The same values
193 /// are also exported to the hook process as environment variables:
194 /// `ANODIZER_PUBLISHER`, `ANODIZER_ERROR`, `ANODIZER_VERSION`,
195 /// `ANODIZER_TAG`, `ANODIZER_GROUP`, `ANODIZER_REQUIRED`,
196 /// `ANODIZER_ROLLED_BACK`, `ANODIZER_RUN_REPORT`. A hook's own
197 /// failure is logged as a warning and never changes the release outcome.
198 ///
199 /// Security: the rendered `cmd` string is parsed by `sh -c`, and
200 /// `{{ .Error }}` carries untrusted remote text (HTTP error bodies, git
201 /// stderr) — interpolating it into `cmd` lets crafted error content
202 /// break quoting and execute. Read untrusted values from the env vars
203 /// instead (`$ANODIZER_ERROR`), and pass `anodizer notify --raw` so the
204 /// text is sent literally rather than Tera-rendered. The outbound
205 /// notification body is secret-redacted by default, so a secret reference
206 /// smuggled into the error body is masked (sent as `$NAME`) even without
207 /// `--raw`; `--raw` stays recommended because it avoids re-rendering
208 /// already-final text and keeps untrusted content out of the shell-parsed
209 /// `cmd` string:
210 ///
211 /// ```yaml
212 /// publish:
213 /// on_error:
214 /// - cmd: 'anodizer notify --raw "anodizer: $ANODIZER_PUBLISHER failed @ $ANODIZER_VERSION: $ANODIZER_ERROR"'
215 /// ```
216 pub on_error: Option<Vec<HookEntry>>,
217
218 /// Hooks that fire once per publisher that a triggered rollback REVERTED —
219 /// including a publisher that itself `Succeeded` and was only reverted
220 /// because a sibling required publisher failed (the case `on_error`, which
221 /// fires solely for the failed publisher, never reaches). A publisher whose
222 /// rollback was attempted but could not complete fires this too, with
223 /// `{{ .RollbackFailed }}` set to `true` so the hook can escalate the
224 /// orphaned-artifact case. Each entry is a standard hook (`cmd` / `dir` /
225 /// `env` / `output`); the template surface adds `{{ .Publisher }}`,
226 /// `{{ .Version }}`, `{{ .Tag }}`, `{{ .Group }}`
227 /// (Assets/Manager/Submitter), `{{ .Required }}`, `{{ .RollbackFailed }}`
228 /// (`true` when the revert itself failed), `{{ .Error }}` (the rollback
229 /// failure message, empty on a clean revert), and `{{ .Reason }}` (the
230 /// run-wide sibling failure(s) that triggered the unwind — distinct from
231 /// `{{ .Error }}`; empty on a `--rollback-only` replay). The same values are
232 /// exported to the hook process as `ANODIZER_PUBLISHER`, `ANODIZER_VERSION`,
233 /// `ANODIZER_TAG`, `ANODIZER_GROUP`, `ANODIZER_REQUIRED`,
234 /// `ANODIZER_ROLLBACK_FAILED`, `ANODIZER_ERROR`, and
235 /// `ANODIZER_ROLLBACK_REASON`. A hook's own failure is
236 /// logged as a warning and never changes the release outcome or aborts the
237 /// remaining rollbacks. It is independent of `on_error`: a publisher that
238 /// both failed and was rolled back fires both.
239 ///
240 /// ```yaml
241 /// publish:
242 /// on_rollback:
243 /// - cmd: 'anodizer notify --raw "anodizer: $ANODIZER_PUBLISHER reverted @ $ANODIZER_VERSION (rollback_failed=$ANODIZER_ROLLBACK_FAILED)"'
244 /// ```
245 pub on_rollback: Option<Vec<HookEntry>>,
246}
247
248/// `cargo publish` flag surface.
249///
250/// Presence under `publish:` opts the crate in; use `skip: true` (or a
251/// truthy template) to opt out. There is no `enabled` field — presence is
252/// the on-switch.
253///
254/// Fields intentionally omitted because anodizer owns them:
255/// - `--package` / `--workspace` / `--exclude`: the top-level `crates[]`
256/// axis owns crate selection.
257/// - `--dry-run`: pipeline-level CLI ergonomics (`anodizer release --dry-run`).
258/// - `-v` / `-q` / `--color`: CLI ergonomics, not config.
259/// - `--config` / `-Z`: cargo CLI escape hatches; out of scope.
260#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
261#[serde(default, deny_unknown_fields)]
262pub struct CargoPublishConfig {
263 // ----- Registry selection -----
264 /// Alternate registry name from `~/.cargo/config.toml` (`--registry`).
265 pub registry: Option<String>,
266 /// Registry index URL (`--index`).
267 pub index: Option<String>,
268 /// Seconds to wait for the crates.io sparse index to publish a crate
269 /// before its dependents are pushed (anodizer-original — no `cargo
270 /// publish` equivalent).
271 pub index_timeout: Option<u64>,
272 /// Pre-publish gate that polls crates.io for every workspace-internal
273 /// dep of the crate being published, blocking until each is queryable
274 /// at its expected version. Required for multi-tag-multi-crate
275 /// workspaces (e.g. cfgd) where per-crate tags fire independent
276 /// `Release.yml` runs that would otherwise race the sparse-index
277 /// propagation.
278 ///
279 /// Single-crate workspaces and lockstep-bumped monorepos (anodizer
280 /// itself) leave this off — there is no inter-tag race to gate on.
281 pub wait_for_workspace_deps: Option<WaitForWorkspaceDepsConfig>,
282
283 // ----- Verify / dirty -----
284 /// Skip the local `cargo build --release` verification step (`--no-verify`).
285 pub no_verify: Option<bool>,
286 /// Allow publishing with an uncommitted working tree (`--allow-dirty`).
287 pub allow_dirty: Option<bool>,
288
289 // ----- Feature selection -----
290 /// Crate features to activate (`--features`).
291 pub features: Option<Vec<String>>,
292 /// Activate every feature, including `default` (`--all-features`).
293 pub all_features: Option<bool>,
294 /// Disable the `default` feature set (`--no-default-features`).
295 pub no_default_features: Option<bool>,
296
297 // ----- Compilation -----
298 /// Build target triple for the verification step (`--target`).
299 pub target: Option<String>,
300 /// Override the cargo target directory (`--target-dir`).
301 pub target_dir: Option<PathBuf>,
302 /// Number of parallel compile jobs for verification (`--jobs`).
303 pub jobs: Option<u32>,
304 /// Continue on errors when verifying multiple crates (`--keep-going`).
305 pub keep_going: Option<bool>,
306
307 // ----- Manifest -----
308 /// Path to the crate's `Cargo.toml` (`--manifest-path`).
309 pub manifest_path: Option<PathBuf>,
310 /// Require an up-to-date `Cargo.lock` matching the resolver (`--locked`).
311 pub locked: Option<bool>,
312 /// Require offline resolution; never hit the network (`--offline`).
313 pub offline: Option<bool>,
314 /// Both `--locked` and `--offline` (`--frozen`).
315 pub frozen: Option<bool>,
316
317 // ----- Peer-publisher pattern -----
318 /// Skip this publisher; supports template strings or bool.
319 /// Truthy renders disable the publisher without removing the block.
320 #[serde(default, deserialize_with = "deserialize_string_or_bool_opt")]
321 pub skip: Option<StringOrBool>,
322 /// Override whether this publisher failing should fail the overall release.
323 ///
324 /// Default: `true` — a failure here aborts the release.
325 /// Set to `false` to log failures but continue.
326 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub required: Option<bool>,
328 /// Template-conditional gate: when the rendered result is falsy
329 /// (`"false"` / `"0"` / `"no"` / empty), the cargo publisher is
330 /// skipped. Render failure hard-errors. Config key: the publisher's `if:`.
331 #[serde(rename = "if")]
332 pub if_condition: Option<String>,
333 /// When `true`, a triggered rollback leaves this publisher's work in
334 /// place rather than attempting to undo it. Default `false`.
335 pub retain_on_rollback: Option<bool>,
336}
337
338/// Pre-publish polling gate for `cargo publish`. When `enabled`, the cargo
339/// publisher reads its crate's manifest, identifies every dep that points
340/// at another crate in the same anodize workspace, and polls
341/// `https://index.crates.io/<prefix>/<name>` until each `(name, version)`
342/// pair is queryable. Only then does `cargo publish` run.
343///
344/// Default: disabled. Anodize's own workspaces publish lockstep with one
345/// tag; this feature only kicks in for multi-tag-multi-crate workspaces
346/// like cfgd where downstream crates can otherwise race the sparse-index
347/// propagation of their upstream deps.
348///
349/// Complementary to `cargo.index_timeout`: this gate runs BEFORE publish
350/// (waits for *upstream* deps to land), while `index_timeout` runs AFTER
351/// publish (waits for the *just-published* crate to land before the next
352/// dependent in the same run starts).
353///
354/// ```yaml
355/// publish:
356/// cargo:
357/// wait_for_workspace_deps:
358/// enabled: true
359/// poll_interval: 5s
360/// max_wait: 5m
361/// ```
362#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
363#[serde(default, deny_unknown_fields)]
364pub struct WaitForWorkspaceDepsConfig {
365 /// Master switch. Default `false` preserves today's behavior for
366 /// single-crate workspaces and lockstep monorepos.
367 pub enabled: Option<bool>,
368 /// Time between successive index probes. Humantime-style string
369 /// (e.g. `"5s"`, `"500ms"`, `"1m"`). Default: `"5s"`.
370 pub poll_interval: Option<HumanDuration>,
371 /// Hard ceiling on the total wait. The publisher bails with a clear
372 /// error once `max_wait` elapses without every dep appearing.
373 /// Humantime-style string (e.g. `"5m"`, `"30s"`). Default: `"5m"`.
374 pub max_wait: Option<HumanDuration>,
375}
376
377impl WaitForWorkspaceDepsConfig {
378 /// Default poll interval — short enough to feel snappy when the
379 /// upstream's publish lands quickly, long enough that a 5-minute
380 /// wait window costs at most 60 HTTP probes.
381 pub const DEFAULT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
382
383 /// Default ceiling — five minutes matches the historical
384 /// `index_timeout` default and covers the worst-case sparse-index
385 /// CDN propagation window observed in practice.
386 pub const DEFAULT_MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(300);
387
388 /// Resolve `enabled`, defaulting to `false` (master switch off).
389 pub fn resolved_enabled(&self) -> bool {
390 self.enabled.unwrap_or(false)
391 }
392
393 /// Resolve `poll_interval`, falling back to
394 /// [`Self::DEFAULT_POLL_INTERVAL`].
395 pub fn resolved_poll_interval(&self) -> std::time::Duration {
396 self.poll_interval
397 .map(|d| d.duration())
398 .unwrap_or(Self::DEFAULT_POLL_INTERVAL)
399 }
400
401 /// Resolve `max_wait`, falling back to [`Self::DEFAULT_MAX_WAIT`].
402 pub fn resolved_max_wait(&self) -> std::time::Duration {
403 self.max_wait
404 .map(|d| d.duration())
405 .unwrap_or(Self::DEFAULT_MAX_WAIT)
406 }
407}
408
409// ---------------------------------------------------------------------------
410// Publisher gate overrides
411// ---------------------------------------------------------------------------
412
413/// Uniform access to the `required` / `retain_on_rollback` release-gate
414/// overrides that every publisher config block carries.
415///
416/// The publish registry collapses these overrides across all of a
417/// publisher's config sources (per-crate blocks over the full crate
418/// universe, top-level entry lists) into a single publisher-level value.
419/// Implementing this trait — rather than hand-copying the field accessor
420/// chain per publisher — makes it impossible for a publisher to collapse
421/// `required` but forget the parallel `retain_on_rollback` collapse (or
422/// vice versa).
423pub trait PublisherGateOverrides {
424 /// Config-level `required:` override. `None` keeps the publisher's
425 /// built-in default; `Some(true)` anywhere escalates the release gate.
426 fn required_override(&self) -> Option<bool>;
427 /// Config-level `retain_on_rollback:` override. `Some(true)` anywhere
428 /// opts the publisher's successful work out of rollback.
429 fn retain_on_rollback_override(&self) -> Option<bool>;
430}
431
432macro_rules! impl_publisher_gate_overrides {
433 ($($t:ty),+ $(,)?) => {
434 $(impl PublisherGateOverrides for $t {
435 fn required_override(&self) -> Option<bool> {
436 self.required
437 }
438 fn retain_on_rollback_override(&self) -> Option<bool> {
439 self.retain_on_rollback
440 }
441 })+
442 };
443}
444
445impl_publisher_gate_overrides!(
446 CargoPublishConfig,
447 HomebrewConfig,
448 HomebrewCaskConfig,
449 ScoopConfig,
450 ChocolateyConfig,
451 WingetConfig,
452 AurConfig,
453 AurSourceConfig,
454 KrewConfig,
455 NixConfig,
456 super::ReleaseConfig,
457 super::DockerHubConfig,
458 super::ArtifactoryConfig,
459 super::UploadConfig,
460 super::CloudSmithConfig,
461 super::NpmConfig,
462 super::GemFuryConfig,
463);