Skip to main content

release_kit/commands/
guide.rs

1//! `rk guide`: print a runbook with what detection knows filled in.
2//!
3//! The line between substituted and not is honesty, not convenience: a
4//! value detection resolved — the project path, the forge, the technology —
5//! is filled in, and a value `rk` would have to guess stays a placeholder.
6//! `<release pr>` and its siblings exist only once a bot has opened them; a
7//! substituted-but-stale number merges someone else's work, where a visible
8//! placeholder fails loudly.
9
10use crate::cli::guide::GuideArgs;
11use crate::commands::walk;
12use crate::detect;
13use crate::embedded;
14use crate::error::RkError;
15use crate::output::Output;
16
17/// Print one runbook, or list them.
18///
19/// # Errors
20///
21/// Returns [`RkError::NotFound`] for an unknown runbook and
22/// [`RkError::Usage`] when neither a name nor `--list` is given, or a flag
23/// value is not one of the known axes.
24pub fn run(args: &GuideArgs) -> Result<(), RkError> {
25    let out = Output::human();
26    let entries = walk(&embedded::RUNBOOKS);
27    if args.list {
28        for (path, _) in &entries {
29            out.result_line(path.trim_end_matches(".md").to_ascii_lowercase());
30        }
31        return Ok(());
32    }
33    let Some(name) = args.name.as_deref() else {
34        return Err(RkError::Usage(
35            "name a runbook, or pass --list to see them".into(),
36        ));
37    };
38    let wanted = name.to_ascii_lowercase();
39    let wanted = wanted.trim_end_matches(".md");
40    let Some((_, contents)) = entries
41        .iter()
42        .find(|(path, _)| path.trim_end_matches(".md").eq_ignore_ascii_case(wanted))
43    else {
44        return Err(RkError::NotFound {
45            kind: "runbook",
46            name: name.to_owned(),
47        });
48    };
49    let text = String::from_utf8_lossy(contents);
50
51    let forge = match args.forge.as_deref() {
52        Some(value) => Some(
53            detect::Forge::parse(value)
54                .ok_or_else(|| {
55                    RkError::Usage(format!(
56                        "unknown forge '{value}'; the forges are: github, gitlab"
57                    ))
58                })?
59                .as_str(),
60        ),
61        None => None,
62    };
63    let tech = match args.tech.as_deref() {
64        Some(value @ ("rust" | "python" | "bash")) => Some(value.to_owned()),
65        Some(other) => {
66            return Err(RkError::Usage(format!(
67                "unknown tech '{other}'; the bindings are: rust, python, bash"
68            )));
69        }
70        None => None,
71    };
72
73    let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
74    let detected = detect::detect(&cwd);
75    let forge = forge.or_else(|| detected.forge.map(detect::Forge::as_str));
76    let tech = tech.or_else(|| detect::tech_of(&cwd).map(str::to_owned));
77    let repo = args.repo.clone().or(detected.repo);
78
79    let rendered = render(&text, forge, tech.as_deref(), repo.as_deref());
80    let unresolved = repo.is_none() && rendered.contains("<repo>");
81    out.result_raw(&rendered);
82    if unresolved {
83        out.frame("note: <repo> is unresolved; pass --repo <owner/name> to fill it");
84    }
85    Ok(())
86}
87
88/// Which axis a variant label selects on.
89fn axis_of(selector: &str) -> Option<&'static str> {
90    match selector {
91        "github" | "gitlab" => Some("forge"),
92        "rust" | "python" | "bash" => Some("tech"),
93        _ => None,
94    }
95}
96
97/// The selector of a variant label line, `On <selector>:`.
98fn label_of(line: &str) -> Option<&str> {
99    let selector = line.strip_prefix("On ")?.strip_suffix(":")?;
100    axis_of(selector).map(|_| selector)
101}
102
103/// Render one runbook: keep the matching variant of every resolved axis and
104/// drop its siblings, substitute `<repo>` where it is known, and leave
105/// everything else byte-identical.
106fn render(text: &str, forge: Option<&str>, tech: Option<&str>, repo: Option<&str>) -> String {
107    let lines: Vec<&str> = text.split('\n').collect();
108    let mut out: Vec<String> = Vec::with_capacity(lines.len());
109    let mut idx = 0;
110    while idx < lines.len() {
111        let line = lines[idx];
112        let Some(selector) = label_of(line) else {
113            out.push(substitute(line, repo));
114            idx += 1;
115            continue;
116        };
117        let resolved = match axis_of(selector) {
118            Some("forge") => forge,
119            Some("tech") => tech,
120            _ => None,
121        };
122        let Some(resolved) = resolved else {
123            out.push(substitute(line, repo));
124            idx += 1;
125            continue;
126        };
127        // The variant grammar: the label line, one blank line, then one
128        // fenced block or one paragraph.
129        let body_start = idx + 2;
130        let body_end = if lines.get(body_start).is_some_and(|l| l.starts_with("```")) {
131            lines[body_start + 1..]
132                .iter()
133                .position(|l| l.starts_with("```"))
134                .map_or(lines.len(), |offset| body_start + 1 + offset + 1)
135        } else {
136            lines[body_start..]
137                .iter()
138                .position(|l| l.trim().is_empty())
139                .map_or(lines.len(), |offset| body_start + offset)
140        };
141        if selector == resolved {
142            for kept in lines.iter().take(body_end).skip(body_start) {
143                out.push(substitute(kept, repo));
144            }
145            idx = body_end;
146        } else {
147            idx = body_end;
148            // Swallow one following blank line, so a dropped variant does
149            // not leave a double gap.
150            if lines.get(idx).is_some_and(|l| l.trim().is_empty()) {
151                idx += 1;
152            }
153        }
154    }
155    out.join("\n")
156}
157
158/// Fill `<repo>` where detection or `--repo` resolved it; everything else
159/// stays a placeholder.
160fn substitute(line: &str, repo: Option<&str>) -> String {
161    repo.map_or_else(|| line.to_owned(), |slug| line.replace("<repo>", slug))
162}
163
164#[cfg(test)]
165mod tests {
166    use super::render;
167
168    const DOC: &str = "# T\n\nOn github:\n\n```bash\ngh pr list --repo <repo>\n```\n\nOn gitlab:\n\n```bash\nglab mr list\n```\n\ntail <release pr>\n";
169
170    /// Nothing resolved: the output is byte-identical to the source.
171    #[test]
172    fn an_unresolved_render_is_byte_identical() {
173        assert_eq!(render(DOC, None, None, None), DOC);
174    }
175
176    /// A resolved forge keeps its variant, drops the sibling and both
177    /// labels, and a resolved repo fills `<repo>` while `<release pr>`
178    /// stays a placeholder.
179    #[test]
180    fn a_resolved_render_selects_and_substitutes() {
181        let rendered = render(DOC, Some("github"), None, Some("acme/widget"));
182        assert!(rendered.contains("gh pr list --repo acme/widget"));
183        assert!(!rendered.contains("glab"));
184        assert!(!rendered.contains("On github:"));
185        assert!(!rendered.contains("<repo>"));
186        assert!(rendered.contains("<release pr>"));
187        let gitlab = render(DOC, Some("gitlab"), None, None);
188        assert!(gitlab.contains("glab mr list"));
189        assert!(!gitlab.contains("gh pr list"));
190    }
191
192    /// A paragraph variant is selected the same way a fenced one is.
193    #[test]
194    fn a_paragraph_variant_renders() {
195        let doc = "On github:\n\nthe force-push refresh survives.\n\nOn gitlab:\n\nthe request is replaced.\n\nend\n";
196        let rendered = render(doc, Some("gitlab"), None, None);
197        assert_eq!(rendered, "the request is replaced.\n\nend\n");
198    }
199}