release-kit 0.9.14

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! `rk profile`: what a target resolves to, and what the catalog selects
//! for it.
//!
//! Read-only. The command resolves the target configuration the way every
//! landing verb does, keeps the source of each value, computes the one
//! projection, and reports every domain value with its source, the
//! unknown categories, the observation's proposal where it answered the
//! release mode, every capability with its status, the omissions, and the
//! conflicts. It writes nothing and judges nothing: judgment belongs to
//! `rk status --check` and `rk setup check`.
//!
//! SATISFIES project-profile:the-profile-command-writes-nothing

use std::collections::BTreeMap;

use serde::Serialize;

use crate::cli::profile::ProfileArgs;
use crate::diagnostic::{Diagnostic, Reason};
use crate::error::RkError;
use crate::landing::manifest::{self, Provider};
use crate::landing::{self, Params};
use crate::output::Output;
use crate::profile::{self, CapabilityRequests, GitWorkflow, ProfileSnapshot, Proposal, Source};
use crate::projection::{Projection, ProjectionInput, TargetEvidence};
use crate::stage::{CapabilityNote, Note};

/// The machine form of a profile report.
#[derive(Debug, Serialize)]
struct Report {
    /// The shape version of this document.
    schema: &'static str,
    /// The target directory.
    target: String,
    /// What the project is.
    profile: ProfileSnapshot,
    /// How topic branches reach the trunk.
    git: GitWorkflow,
    /// Which optional products the target requests.
    capabilities: CapabilityRequests,
    /// The project path on the forge, empty where the project has none.
    repo: String,
    /// The two security answers.
    security: Security,
    /// The setup answers the release gate renders.
    setup: Setup,
    /// The landing declaration: the rendered destinations the project
    /// deliberately edits. Its own domain, never a profile fact or a
    /// capability request.
    landing: LandingDeclaration,
    /// The source of each value, keyed by its configuration path.
    sources: BTreeMap<&'static str, Source>,
    /// The category names the catalog does not know.
    unknown: Vec<String>,
    /// What the observation proposed for the release, where nothing above
    /// it answered the mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    proposal: Option<Proposal>,
    /// Every capability, in catalog order, with its status and its
    /// destinations.
    selection: Vec<CapabilityNote>,
    /// The destinations the target's own state withholds.
    omissions: Vec<Note>,
    /// The block destinations whose document offers the block no place.
    collisions: Vec<Note>,
    /// What plausibly follows.
    next: Vec<String>,
}

/// The landing declaration, by destination.
#[derive(Debug, Serialize)]
struct LandingDeclaration {
    /// Each accepted deviation, with its reason and accepted digest.
    accepted_drift: BTreeMap<String, crate::config::AcceptedDrift>,
}

/// The three security answers.
#[derive(Debug, Serialize)]
struct Security {
    /// The contact, empty for the forge's own wording.
    contact: String,
    /// The acknowledgment window.
    response: String,
    /// The paragraph naming what the project does not own, empty where the
    /// policy states none.
    scope: String,
}

/// The setup answers a landing renders.
#[derive(Debug, Serialize)]
struct Setup {
    /// The check the release gate believes, empty where nothing answered it.
    required_check: String,
    /// The workflow whose completion wakes the release gate, empty where
    /// nothing answered it.
    required_workflow: String,
    /// The bot identity's name, empty where the forge's default applies.
    bot_name: String,
}

/// One line stating the three domains and the identity, for every human
/// report that names a resolved target.
#[must_use]
pub fn describe(
    profile: &ProfileSnapshot,
    git: &GitWorkflow,
    capabilities: &CapabilityRequests,
    repo: &str,
) -> String {
    let technologies = if profile.technologies.is_empty() {
        "none".to_owned()
    } else {
        profile.technologies.join(", ")
    };
    let release = match profile.release.mode {
        profile::ReleaseMode::Automatic => format!(
            "automatic (driver {}, style {}, line prefix {})",
            profile.release.driver.as_deref().unwrap_or("unresolved"),
            profile
                .release
                .style
                .map_or("unresolved", crate::landing::Style::as_str),
            profile
                .release
                .line_prefix
                .as_deref()
                .unwrap_or(crate::config::LINE_PREFIX_DEFAULT)
        ),
        other => other.as_str().to_owned(),
    };
    let mut requested: Vec<&str> = Vec::new();
    if capabilities.nix_packaging {
        requested.push("nix_packaging");
    }
    if capabilities.reporting_policy {
        requested.push("reporting_policy");
    }
    if capabilities.scorecard {
        requested.push("scorecard");
    }
    if capabilities.workflow_guards() {
        requested.push("workflow_guards");
    }
    let scanning = capabilities.code_scanning.map(Provider::as_str);
    format!(
        "technologies {technologies}; forge {}; repo {}; release {release}; trunk {}; checkout mode {}; integration {}; merge form {}; requests {}{}",
        profile.forge.as_deref().unwrap_or("none"),
        match repo {
            "" => "none",
            crate::projection::REPO_PLACEHOLDER => "unresolved",
            named => named,
        },
        git.trunk,
        git.checkout_mode.as_str(),
        git.integration.as_str(),
        git.merge_form.as_str(),
        if requested.is_empty() {
            "none".to_owned()
        } else {
            requested.join(", ")
        },
        scanning.map_or_else(String::new, |provider| format!(
            ", code_scanning {provider}"
        ))
    )
}

/// Report the target's resolution and selection.
///
/// # Errors
///
/// Returns [`RkError::Missing`] for a target that is not a directory, and
/// the resolution's own refusals for a malformed release intent.
#[allow(
    clippy::too_many_lines,
    reason = "one pass reports every domain, source, capability, and omission, and splitting it would separate a value from the report line that states it"
)]
pub fn run(args: &ProfileArgs) -> Result<(), RkError> {
    let out = Output::new(args.json);
    if !args.target.is_dir() {
        return Err(RkError::missing(
            Diagnostic::new(
                Reason::TargetNotFound,
                format!("target {} is not a directory", args.target),
            )
            .expected("an existing repository to resolve for"),
        ));
    }
    let config = crate::config::load(args.target.as_std_path())?;
    let record = manifest::load(&args.target)?;
    let resolved = profile::resolve(
        &args.target,
        &landing::Inputs {
            nix: args.nix_packaging.then_some(true),
            reporting_policy: args.reporting_policy.then_some(true),
            scorecard: args.scorecard.then_some(true),
            workflow_guards: args.workflow_guards.then_some(true),
            code_scanning: args
                .code_scanning
                .as_deref()
                .map(Provider::parse)
                .transpose()?,
            ..args.profile.inputs()?
        },
        config.as_ref(),
        record.as_ref(),
        landing::Purpose::Preview,
    )?;
    let params: &Params = &resolved.params;
    let evidence = TargetEvidence::gather(&args.target, record.as_ref())?;
    let projection = Projection::compute(&ProjectionInput {
        params: params.clone(),
        evidence,
    })?;
    // The landing declaration is a committed answer of class N: only the
    // configuration states it, and it must name what this landing selects.
    let accepted_drift = config
        .as_ref()
        .map(|config| config.landing.accepted_drift.clone())
        .unwrap_or_default();
    landing::accepted_drift_faults(&projection, record.as_ref(), config.as_ref())?;
    let mut sources = resolved.sources.clone();
    sources.insert(
        "landing.accepted_drift",
        if accepted_drift.is_empty() {
            profile::Source::Default
        } else {
            profile::Source::Config
        },
    );
    for (destination, entry) in &accepted_drift {
        out.result_line(format!(
            "landing declaration: accepted drift on {destination} ({}), from config",
            entry.reason
        ));
    }

    out.result_line(format!(
        "profile: {}",
        describe(
            params.profile(),
            params.git(),
            params.capabilities(),
            params.repo()
        )
    ));
    // Where an automatic rust release publishes, stated beside its source
    // so an unanswered target reads crates.io as the default it is.
    if let Some(answer) = params.registry() {
        out.result_line(format!(
            "registry: {} ({})",
            answer.as_str(),
            resolved
                .sources
                .get("profile.release.registry")
                .map_or("default", |source| source.as_str())
        ));
    }
    for (key, source) in &resolved.sources {
        out.result_line(format!("source {key}: {}", source.as_str()));
    }
    for name in &resolved.unknown {
        out.result_line(format!("unknown {name}: preserved; no adapter drives it"));
    }
    if let Some(proposal) = &resolved.proposal {
        out.result_line(format!(
            "proposal: {}",
            match proposal {
                Proposal::None => "no release-bearing technology, so the release mode is none".to_owned(),
                Proposal::Automatic { driver } => format!("an automatic release driven by {driver}"),
                Proposal::Ambiguous { drivers } => format!(
                    "ambiguous: {} are release-bearing; an apply refuses until --release-driver names one",
                    drivers.join(" and ")
                ),
            }
        ));
    }
    let selection: Vec<CapabilityNote> = projection
        .capabilities
        .iter()
        .map(|selection| CapabilityNote::of(selection, &projection))
        .collect();
    for note in &selection {
        let mut line = format!("{} {}", note.status, note.id);
        if !note.destinations.is_empty() {
            line.push_str(": ");
            line.push_str(&note.destinations.join(", "));
        }
        if let Some(reason) = &note.reason {
            line.push_str(" (");
            line.push_str(reason);
            line.push(')');
        }
        out.result_line(line);
        if let Some(action) = &note.action {
            out.result_line(format!("  action: {action}"));
        }
    }
    let omissions: Vec<Note> = projection
        .omissions
        .iter()
        .map(|omission| Note {
            destination: omission.destination.clone(),
            reason: omission.reason.clone(),
            action: omission.action.clone(),
        })
        .collect();
    let collisions: Vec<Note> = projection
        .collisions
        .iter()
        .map(|collision| Note {
            destination: collision.destination.clone(),
            reason: collision.reason.clone(),
            action: None,
        })
        .collect();
    for note in &omissions {
        out.result_line(format!("withheld {}: {}", note.destination, note.reason));
    }
    for note in &collisions {
        out.result_line(format!("collision {}: {}", note.destination, note.reason));
    }
    // `rk upgrade` takes each capability as `on|off`, and `rk init` takes
    // the boolean ones as bare flags. The follow-up command must parse, so
    // it renders the verb's own spelling rather than one of them twice.
    let (verb, capabilities) = if record.is_some() {
        ("upgrade", params.capability_toggles())
    } else {
        ("init", params.capability_flags())
    };
    let mut next = vec![format!(
        "rk {verb}{}{capabilities} --target {} previews the landing under these answers",
        params.canonical_flags(),
        args.target
    )];
    if let Some(Proposal::Ambiguous { drivers }) = &resolved.proposal {
        next.insert(
            0,
            format!(
                "name the driver before an apply: --release-driver <{}>",
                drivers.join("|")
            ),
        );
    }
    if let Some(reason) = projection.release_unavailable() {
        next.insert(
            0,
            format!("an apply refuses until the release automation resolves: {reason}"),
        );
    }
    next.push(format!(
        "rk stage --target {} stages the complete candidate for a byte comparison",
        args.target
    ));
    out.next(&next);
    out.emit(&Report {
        schema: "rk.profile/5",
        target: args.target.to_string(),
        profile: params.profile().clone(),
        git: params.git().clone(),
        capabilities: params.capabilities().clone(),
        repo: params.repo().to_owned(),
        security: Security {
            contact: params.security_contact().to_owned(),
            response: params.security_response().to_owned(),
            scope: params.security_scope().to_owned(),
        },
        setup: Setup {
            required_check: params.required_check().to_owned(),
            required_workflow: params.required_workflow().to_owned(),
            bot_name: resolved.bot_name.clone(),
        },
        landing: LandingDeclaration { accepted_drift },
        sources,
        unknown: resolved.unknown,
        proposal: resolved.proposal,
        selection,
        omissions,
        collisions,
        next,
    })
}

#[cfg(test)]
mod tests {
    use super::{Report, Security, Setup};
    use crate::landing::{CheckoutMode, Integration};
    use crate::profile::{
        CapabilityRequests, GitWorkflow, ProfileSnapshot, Proposal, ReleaseIntent, ReleaseMode,
        Source,
    };
    use crate::stage::{CapabilityNote, Note};

    /// The complete `rk.profile/5` shape, held by snapshot.
    #[test]
    fn the_profile_report_schema_snapshot_holds() {
        let report = Report {
            schema: "rk.profile/5",
            target: "/tmp/t".into(),
            profile: ProfileSnapshot {
                technologies: vec!["python".into(), "rust".into()],
                forge: Some("github".into()),
                release: ReleaseIntent {
                    mode: ReleaseMode::Automatic,
                    driver: Some("rust".into()),
                    style: Some(crate::landing::Style::Trunk),
                    line_prefix: Some("release/".into()),
                    registry: None,
                    build: None,
                },
            },
            git: GitWorkflow {
                trunk: "master".into(),
                checkout_mode: CheckoutMode::LinkedWorktree,
                integration: Integration::Local,
                merge_form: crate::landing::MergeForm::Squash,
            },
            capabilities: CapabilityRequests {
                nix_packaging: false,
                reporting_policy: true,
                scorecard: false,
                code_scanning: None,
                workflow_guards: Some(false),
            },
            repo: "acme/widget".into(),
            security: Security {
                contact: String::new(),
                response: "best-effort".into(),
                scope: String::new(),
            },
            setup: Setup {
                required_check: String::new(),
                required_workflow: String::new(),
                bot_name: String::new(),
            },
            landing: super::LandingDeclaration {
                accepted_drift: std::collections::BTreeMap::new(),
            },
            sources: std::iter::once(("profile.technologies", Source::Observation)).collect(),
            unknown: vec![],
            proposal: Some(Proposal::Ambiguous {
                drivers: vec!["python".into(), "rust".into()],
            }),
            selection: vec![CapabilityNote {
                id: "git.guards".into(),
                status: "selected".into(),
                reason: None,
                action: None,
                destinations: vec!["AGENTS.md".into()],
            }],
            omissions: vec![Note {
                destination: ".gitlab-ci.yml".into(),
                reason: "the target owns it".into(),
                action: Some("add the include".into()),
            }],
            collisions: vec![],
            next: vec!["rk init --target /tmp/t previews the landing".into()],
        };
        assert_eq!(
            serde_json::to_string(&report).expect("a report serializes"),
            r#"{"schema":"rk.profile/5","target":"/tmp/t","profile":{"technologies":["python","rust"],"forge":"github","release":{"mode":"automatic","driver":"rust","style":"trunk","line_prefix":"release/"}},"git":{"trunk":"master","checkout_mode":"linked-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":false,"reporting_policy":true,"scorecard":false,"workflow_guards":false},"repo":"acme/widget","security":{"contact":"","response":"best-effort","scope":""},"setup":{"required_check":"","required_workflow":"","bot_name":""},"landing":{"accepted_drift":{}},"sources":{"profile.technologies":"observation"},"unknown":[],"proposal":{"state":"ambiguous","drivers":["python","rust"]},"selection":[{"id":"git.guards","status":"selected","destinations":["AGENTS.md"]}],"omissions":[{"destination":".gitlab-ci.yml","reason":"the target owns it","action":"add the include"}],"collisions":[],"next":["rk init --target /tmp/t previews the landing"]}"#
        );
    }
}