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 }}`, and
187 /// `{{ .RolledBack }}` — true if any publisher was rolled back (or
188 /// rollback was attempted and failed) during this run. The same values
189 /// are also exported to the hook process as environment variables:
190 /// `ANODIZER_PUBLISHER`, `ANODIZER_ERROR`, `ANODIZER_VERSION`,
191 /// `ANODIZER_TAG`, `ANODIZER_GROUP`, `ANODIZER_REQUIRED`,
192 /// `ANODIZER_ROLLED_BACK`. A hook's own failure is logged as a warning
193 /// and never changes the release outcome.
194 ///
195 /// Security: the rendered `cmd` string is parsed by `sh -c`, and
196 /// `{{ .Error }}` carries untrusted remote text (HTTP error bodies, git
197 /// stderr) — interpolating it into `cmd` lets crafted error content
198 /// break quoting and execute. Read untrusted values from the env vars
199 /// instead (`$ANODIZER_ERROR`), and pass `anodizer notify --raw` so the
200 /// text is sent literally rather than Tera-rendered. The outbound
201 /// notification body is secret-redacted by default, so a secret reference
202 /// smuggled into the error body is masked (sent as `$NAME`) even without
203 /// `--raw`; `--raw` stays recommended because it avoids re-rendering
204 /// already-final text and keeps untrusted content out of the shell-parsed
205 /// `cmd` string:
206 ///
207 /// ```yaml
208 /// publish:
209 /// on_error:
210 /// - cmd: 'anodizer notify --raw "anodizer: $ANODIZER_PUBLISHER failed @ $ANODIZER_VERSION: $ANODIZER_ERROR"'
211 /// ```
212 pub on_error: Option<Vec<HookEntry>>,
213
214 /// Hooks that fire once per publisher that a triggered rollback REVERTED —
215 /// including a publisher that itself `Succeeded` and was only reverted
216 /// because a sibling required publisher failed (the case `on_error`, which
217 /// fires solely for the failed publisher, never reaches). A publisher whose
218 /// rollback was attempted but could not complete fires this too, with
219 /// `{{ .RollbackFailed }}` set to `true` so the hook can escalate the
220 /// orphaned-artifact case. Each entry is a standard hook (`cmd` / `dir` /
221 /// `env` / `output`); the template surface adds `{{ .Publisher }}`,
222 /// `{{ .Version }}`, `{{ .Tag }}`, `{{ .Group }}`
223 /// (Assets/Manager/Submitter), `{{ .Required }}`, `{{ .RollbackFailed }}`
224 /// (`true` when the revert itself failed), `{{ .Error }}` (the rollback
225 /// failure message, empty on a clean revert), and `{{ .Reason }}` (the
226 /// run-wide sibling failure(s) that triggered the unwind — distinct from
227 /// `{{ .Error }}`; empty on a `--rollback-only` replay). The same values are
228 /// exported to the hook process as `ANODIZER_PUBLISHER`, `ANODIZER_VERSION`,
229 /// `ANODIZER_TAG`, `ANODIZER_GROUP`, `ANODIZER_REQUIRED`,
230 /// `ANODIZER_ROLLBACK_FAILED`, `ANODIZER_ERROR`, and
231 /// `ANODIZER_ROLLBACK_REASON`. A hook's own failure is
232 /// logged as a warning and never changes the release outcome or aborts the
233 /// remaining rollbacks. It is independent of `on_error`: a publisher that
234 /// both failed and was rolled back fires both.
235 ///
236 /// ```yaml
237 /// publish:
238 /// on_rollback:
239 /// - cmd: 'anodizer notify --raw "anodizer: $ANODIZER_PUBLISHER reverted @ $ANODIZER_VERSION (rollback_failed=$ANODIZER_ROLLBACK_FAILED)"'
240 /// ```
241 pub on_rollback: Option<Vec<HookEntry>>,
242}
243
244/// `cargo publish` flag surface.
245///
246/// Presence under `publish:` opts the crate in; use `skip: true` (or a
247/// truthy template) to opt out. There is no `enabled` field — presence is
248/// the on-switch.
249///
250/// Fields intentionally omitted because anodizer owns them:
251/// - `--package` / `--workspace` / `--exclude`: the top-level `crates[]`
252/// axis owns crate selection.
253/// - `--dry-run`: pipeline-level CLI ergonomics (`anodizer release --dry-run`).
254/// - `-v` / `-q` / `--color`: CLI ergonomics, not config.
255/// - `--config` / `-Z`: cargo CLI escape hatches; out of scope.
256#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
257#[serde(default, deny_unknown_fields)]
258pub struct CargoPublishConfig {
259 // ----- Registry selection -----
260 /// Alternate registry name from `~/.cargo/config.toml` (`--registry`).
261 pub registry: Option<String>,
262 /// Registry index URL (`--index`).
263 pub index: Option<String>,
264 /// Seconds to wait for the crates.io sparse index to publish a crate
265 /// before its dependents are pushed (anodizer-original — no `cargo
266 /// publish` equivalent).
267 pub index_timeout: Option<u64>,
268 /// Pre-publish gate that polls crates.io for every workspace-internal
269 /// dep of the crate being published, blocking until each is queryable
270 /// at its expected version. Required for multi-tag-multi-crate
271 /// workspaces (e.g. cfgd) where per-crate tags fire independent
272 /// `Release.yml` runs that would otherwise race the sparse-index
273 /// propagation.
274 ///
275 /// Single-crate workspaces and lockstep-bumped monorepos (anodizer
276 /// itself) leave this off — there is no inter-tag race to gate on.
277 pub wait_for_workspace_deps: Option<WaitForWorkspaceDepsConfig>,
278
279 // ----- Verify / dirty -----
280 /// Skip the local `cargo build --release` verification step (`--no-verify`).
281 pub no_verify: Option<bool>,
282 /// Allow publishing with an uncommitted working tree (`--allow-dirty`).
283 pub allow_dirty: Option<bool>,
284
285 // ----- Feature selection -----
286 /// Crate features to activate (`--features`).
287 pub features: Option<Vec<String>>,
288 /// Activate every feature, including `default` (`--all-features`).
289 pub all_features: Option<bool>,
290 /// Disable the `default` feature set (`--no-default-features`).
291 pub no_default_features: Option<bool>,
292
293 // ----- Compilation -----
294 /// Build target triple for the verification step (`--target`).
295 pub target: Option<String>,
296 /// Override the cargo target directory (`--target-dir`).
297 pub target_dir: Option<PathBuf>,
298 /// Number of parallel compile jobs for verification (`--jobs`).
299 pub jobs: Option<u32>,
300 /// Continue on errors when verifying multiple crates (`--keep-going`).
301 pub keep_going: Option<bool>,
302
303 // ----- Manifest -----
304 /// Path to the crate's `Cargo.toml` (`--manifest-path`).
305 pub manifest_path: Option<PathBuf>,
306 /// Require an up-to-date `Cargo.lock` matching the resolver (`--locked`).
307 pub locked: Option<bool>,
308 /// Require offline resolution; never hit the network (`--offline`).
309 pub offline: Option<bool>,
310 /// Both `--locked` and `--offline` (`--frozen`).
311 pub frozen: Option<bool>,
312
313 // ----- Peer-publisher pattern -----
314 /// Skip this publisher; supports template strings or bool.
315 /// Truthy renders disable the publisher without removing the block.
316 #[serde(default, deserialize_with = "deserialize_string_or_bool_opt")]
317 pub skip: Option<StringOrBool>,
318 /// Override whether this publisher failing should fail the overall release.
319 ///
320 /// Default: `true` — a failure here aborts the release.
321 /// Set to `false` to log failures but continue.
322 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub required: Option<bool>,
324 /// Template-conditional gate: when the rendered result is falsy
325 /// (`"false"` / `"0"` / `"no"` / empty), the cargo publisher is
326 /// skipped. Render failure hard-errors. Config key: the publisher's `if:`.
327 #[serde(rename = "if")]
328 pub if_condition: Option<String>,
329 /// When `true`, a triggered rollback leaves this publisher's work in
330 /// place rather than attempting to undo it. Default `false`.
331 pub retain_on_rollback: Option<bool>,
332}
333
334/// Pre-publish polling gate for `cargo publish`. When `enabled`, the cargo
335/// publisher reads its crate's manifest, identifies every dep that points
336/// at another crate in the same anodize workspace, and polls
337/// `https://index.crates.io/<prefix>/<name>` until each `(name, version)`
338/// pair is queryable. Only then does `cargo publish` run.
339///
340/// Default: disabled. Anodize's own workspaces publish lockstep with one
341/// tag; this feature only kicks in for multi-tag-multi-crate workspaces
342/// like cfgd where downstream crates can otherwise race the sparse-index
343/// propagation of their upstream deps.
344///
345/// Complementary to `cargo.index_timeout`: this gate runs BEFORE publish
346/// (waits for *upstream* deps to land), while `index_timeout` runs AFTER
347/// publish (waits for the *just-published* crate to land before the next
348/// dependent in the same run starts).
349///
350/// ```yaml
351/// publish:
352/// cargo:
353/// wait_for_workspace_deps:
354/// enabled: true
355/// poll_interval: 5s
356/// max_wait: 5m
357/// ```
358#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
359#[serde(default, deny_unknown_fields)]
360pub struct WaitForWorkspaceDepsConfig {
361 /// Master switch. Default `false` preserves today's behavior for
362 /// single-crate workspaces and lockstep monorepos.
363 pub enabled: Option<bool>,
364 /// Time between successive index probes. Humantime-style string
365 /// (e.g. `"5s"`, `"500ms"`, `"1m"`). Default: `"5s"`.
366 pub poll_interval: Option<HumanDuration>,
367 /// Hard ceiling on the total wait. The publisher bails with a clear
368 /// error once `max_wait` elapses without every dep appearing.
369 /// Humantime-style string (e.g. `"5m"`, `"30s"`). Default: `"5m"`.
370 pub max_wait: Option<HumanDuration>,
371}
372
373impl WaitForWorkspaceDepsConfig {
374 /// Default poll interval — short enough to feel snappy when the
375 /// upstream's publish lands quickly, long enough that a 5-minute
376 /// wait window costs at most 60 HTTP probes.
377 pub const DEFAULT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
378
379 /// Default ceiling — five minutes matches the historical
380 /// `index_timeout` default and covers the worst-case sparse-index
381 /// CDN propagation window observed in practice.
382 pub const DEFAULT_MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(300);
383
384 /// Resolve `enabled`, defaulting to `false` (master switch off).
385 pub fn resolved_enabled(&self) -> bool {
386 self.enabled.unwrap_or(false)
387 }
388
389 /// Resolve `poll_interval`, falling back to
390 /// [`Self::DEFAULT_POLL_INTERVAL`].
391 pub fn resolved_poll_interval(&self) -> std::time::Duration {
392 self.poll_interval
393 .map(|d| d.duration())
394 .unwrap_or(Self::DEFAULT_POLL_INTERVAL)
395 }
396
397 /// Resolve `max_wait`, falling back to [`Self::DEFAULT_MAX_WAIT`].
398 pub fn resolved_max_wait(&self) -> std::time::Duration {
399 self.max_wait
400 .map(|d| d.duration())
401 .unwrap_or(Self::DEFAULT_MAX_WAIT)
402 }
403}
404
405// ---------------------------------------------------------------------------
406// Publisher gate overrides
407// ---------------------------------------------------------------------------
408
409/// Uniform access to the `required` / `retain_on_rollback` release-gate
410/// overrides that every publisher config block carries.
411///
412/// The publish registry collapses these overrides across all of a
413/// publisher's config sources (per-crate blocks over the full crate
414/// universe, top-level entry lists) into a single publisher-level value.
415/// Implementing this trait — rather than hand-copying the field accessor
416/// chain per publisher — makes it impossible for a publisher to collapse
417/// `required` but forget the parallel `retain_on_rollback` collapse (or
418/// vice versa).
419pub trait PublisherGateOverrides {
420 /// Config-level `required:` override. `None` keeps the publisher's
421 /// built-in default; `Some(true)` anywhere escalates the release gate.
422 fn required_override(&self) -> Option<bool>;
423 /// Config-level `retain_on_rollback:` override. `Some(true)` anywhere
424 /// opts the publisher's successful work out of rollback.
425 fn retain_on_rollback_override(&self) -> Option<bool>;
426}
427
428macro_rules! impl_publisher_gate_overrides {
429 ($($t:ty),+ $(,)?) => {
430 $(impl PublisherGateOverrides for $t {
431 fn required_override(&self) -> Option<bool> {
432 self.required
433 }
434 fn retain_on_rollback_override(&self) -> Option<bool> {
435 self.retain_on_rollback
436 }
437 })+
438 };
439}
440
441impl_publisher_gate_overrides!(
442 CargoPublishConfig,
443 HomebrewConfig,
444 HomebrewCaskConfig,
445 ScoopConfig,
446 ChocolateyConfig,
447 WingetConfig,
448 AurConfig,
449 AurSourceConfig,
450 KrewConfig,
451 NixConfig,
452 super::ReleaseConfig,
453 super::DockerHubConfig,
454 super::ArtifactoryConfig,
455 super::UploadConfig,
456 super::CloudSmithConfig,
457 super::NpmConfig,
458 super::GemFuryConfig,
459);