Skip to main content

git_editor/
output.rs

1//! Output routing.
2//!
3//! Human-readable progress goes through [`say!`](crate::say) /
4//! [`say_inline!`](crate::say_inline): stdout normally, stderr in `--json`
5//! mode, so stdout carries nothing but the JSON document.
6
7use std::sync::atomic::{AtomicBool, Ordering};
8
9static JSON_MODE: AtomicBool = AtomicBool::new(false);
10
11pub fn set_json_mode(enabled: bool) {
12    JSON_MODE.store(enabled, Ordering::Relaxed);
13}
14
15pub fn json_mode() -> bool {
16    JSON_MODE.load(Ordering::Relaxed)
17}
18
19/// `println!` that moves to stderr in `--json` mode.
20#[macro_export]
21macro_rules! say {
22    ($($arg:tt)*) => {
23        if $crate::output::json_mode() {
24            eprintln!($($arg)*)
25        } else {
26            println!($($arg)*)
27        }
28    };
29}
30
31/// `print!` that moves to stderr in `--json` mode.
32#[macro_export]
33macro_rules! say_inline {
34    ($($arg:tt)*) => {
35        if $crate::output::json_mode() {
36            eprint!($($arg)*)
37        } else {
38            print!($($arg)*)
39        }
40    };
41}
42
43use crate::rewrite::engine::{GitTime, Outcome};
44use crate::utils::dates::to_rfc3339;
45use crate::utils::simulation::SimulationResult;
46use crate::utils::types::CommitInfo;
47use serde_json::{json, Value};
48
49/// Print one JSON document on stdout.
50pub fn emit(value: &Value) {
51    println!(
52        "{}",
53        serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string())
54    );
55}
56
57fn person(name: &str, email: &str, seconds: i64, offset: i32) -> Value {
58    json!({
59        "name": name,
60        "email": email,
61        "date": to_rfc3339(GitTime::new(seconds, offset)),
62    })
63}
64
65/// `-s --json`: the branch history, newest first (numbers match `--commit`/`--select`).
66pub fn history_json(branch: Option<&str>, head: Option<String>, commits: &[CommitInfo]) -> Value {
67    let commits: Vec<Value> = commits
68        .iter()
69        .enumerate()
70        .map(|(i, c)| {
71            json!({
72                "number": i + 1,
73                "oid": c.oid.to_string(),
74                "short": c.short_hash,
75                "author": person(&c.author_name, &c.author_email, c.timestamp.and_utc().timestamp(), c.author_offset_min),
76                "committer": person(&c.committer_name, &c.committer_email, c.committer_timestamp.and_utc().timestamp(), c.committer_offset_min),
77                "subject": c.message.lines().next().unwrap_or(""),
78                "message": c.message,
79                "message_is_utf8": c.message_is_utf8,
80                "parents": c.parent_count,
81            })
82        })
83        .collect();
84    json!({
85        "ok": true,
86        "command": "history",
87        "branch": branch,
88        "head": head,
89        "total_commits": commits.len(),
90        "commits": commits,
91    })
92}
93
94fn from_to<T: ToString>(from: T, to: &Option<T>) -> Value {
95    to.as_ref().map_or(
96        Value::Null,
97        |to| json!({ "from": from.to_string(), "to": to.to_string() }),
98    )
99}
100
101/// Preview of a plan (`--simulate`, or the summary before a confirmation).
102pub fn simulation_json(result: &SimulationResult) -> Value {
103    let utc = |t: chrono::NaiveDateTime| t.format("%Y-%m-%dT%H:%M:%SZ").to_string();
104    let changes: Vec<Value> = result
105        .changes
106        .iter()
107        .filter(|c| c.has_changes())
108        .map(|c| {
109            json!({
110                "oid": c.commit_oid.to_string(),
111                "short": c.short_hash,
112                "author_name": from_to(c.original_author.clone(), &c.new_author),
113                "author_email": from_to(c.original_email.clone(), &c.new_email),
114                "date": from_to(utc(c.original_timestamp), &c.new_timestamp.map(utc)),
115                "message": from_to(c.original_message.clone(), &c.new_message),
116            })
117        })
118        .collect();
119    json!({
120        "ok": true,
121        "command": "simulate",
122        "mode": result.operation_mode,
123        "total_commits": result.stats.total_commits,
124        "commits_to_change": result.stats.commits_to_change,
125        "changes": changes,
126    })
127}
128
129/// Result of a rewrite.
130pub fn outcome_json(outcome: &Outcome) -> Value {
131    let rewritten: Vec<Value> = outcome
132        .rewritten
133        .iter()
134        .map(|(old, new)| json!({ "old": old.to_string(), "new": new.to_string() }))
135        .collect();
136    json!({
137        "ok": true,
138        "command": "rewrite",
139        "changed": outcome.changed(),
140        "branch": outcome.branch,
141        "old_head": outcome.old_head.to_string(),
142        "new_head": outcome.new_head.to_string(),
143        "backup_ref": outcome.backup_ref,
144        "rewritten": rewritten,
145        "reused": outcome.reused,
146        "signatures_dropped": outcome.signatures_dropped,
147        "stale_refs": outcome.stale_refs,
148    })
149}
150
151/// Error document; `exit_code` mirrors the process status (1 error, 130 cancelled).
152pub fn error_json(message: &str, exit_code: i32) -> Value {
153    json!({
154        "ok": false,
155        "error": message,
156        "cancelled": exit_code == 130,
157        "exit_code": exit_code,
158    })
159}