OXYGENHUB
# 5b1114a04905 oxygen / src / main.rs
12.0 KiB · Rust · last changed Import the Oxygen specification and the first Rust implementation (root change) 1 month ago source blame history raw
1
//! `oxy`: command-line interface for Oxygen.
2
3
use anyhow::{bail, Context, Result};
4
use clap::{Parser, Subcommand};
5
use oxy_core::repo::{ChangeStatus, Repo, SignatureStatus};
6
use std::path::PathBuf;
7
8
#[derive(Parser)]
9
#[command(name = "oxy", version, about = "Oxygen: breathing fresh air into version control")]
10
struct Cli {
11
    #[command(subcommand)]
12
    cmd: Cmd,
13
}
14
15
#[derive(Subcommand)]
16
enum Cmd {
17
    /// Create a repository in PATH (default: current directory)
18
    Init { path: Option<PathBuf> },
19
    /// Show the working copy: changed paths and conflicts
20
    Status,
21
    /// Record the working copy as a change on the current bookmark
22
    Commit {
23
        #[arg(short, long)]
24
        message: String,
25
        /// Extra explicit dependencies (ChangeId prefix, #hash prefix)
26
        #[arg(long = "depends-on")]
27
        depends_on: Vec<String>,
28
    },
29
    /// List changes reachable from the bookmark and the working copy
30
    Log,
31
    /// Show what the working copy changes against its base
32
    Diff,
33
    /// Show one change (ChangeId prefix, #hash prefix, or @)
34
    Show { change: String },
35
    /// Move the working copy to the state formed by CHANGE... (default: the bookmark heads)
36
    Checkout {
37
        changes: Vec<String>,
38
        /// Throw away uncommitted working-copy changes
39
        #[arg(long)]
40
        discard: bool,
41
    },
42
    /// Undo the last operation
43
    Undo,
44
    /// Manage the signing identity
45
    Identity {
46
        #[command(subcommand)]
47
        cmd: IdentityCmd,
48
    },
49
    /// Verify the signatures on a change (default: every change in the log)
50
    Verify { change: Option<String> },
51
    /// Set a repository configuration key (author.name, author.email, author.key, core.sign, workspace.bookmark)
52
    Config { key: String, value: String },
53
    /// List operations
54
    #[command(name = "op")]
55
    Op {
56
        #[command(subcommand)]
57
        cmd: OpCmd,
58
    },
59
}
60
61
#[derive(Subcommand)]
62
enum OpCmd {
63
    Log,
64
}
65
66
#[derive(Subcommand)]
67
enum IdentityCmd {
68
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it the author
69
    Create {
70
        #[arg(long)]
71
        name: Option<String>,
72
        #[arg(long)]
73
        email: Option<String>,
74
    },
75
    /// Show the configured identity
76
    Show,
77
}
78
79
fn signature_line(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
80
    Ok(match repo.verify_change(h)? {
81
        SignatureStatus::Unsigned => "unsigned".to_string(),
82
        SignatureStatus::Valid { key, name, email } => format!("signed by {name} <{email}> key {}", key.short(12)),
83
        SignatureStatus::Invalid(why) => format!("INVALID signature: {why}"),
84
    })
85
}
86
87
fn main() {
88
    // Behave like other CLI tools when output is piped into `head`: die
89
    // quietly on SIGPIPE instead of panicking on a failed write.
90
    #[cfg(unix)]
91
    unsafe {
92
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
93
    }
94
    match run() {
95
        Ok(code) => std::process::exit(code),
96
        Err(e) => {
97
            eprintln!("error: {e:#}");
98
            std::process::exit(1);
99
        }
100
    }
101
}
102
103
fn open() -> Result<Repo> {
104
    Repo::open(&std::env::current_dir()?).context("opening repository")
105
}
106
107
fn short_id(c: &oxy_core::objects::Change) -> String {
108
    c.change_id.short(8)
109
}
110
111
fn when(ms: u64) -> String {
112
    let secs = (ms / 1000) as i64;
113
    let days = secs.div_euclid(86_400);
114
    let rem = secs.rem_euclid(86_400);
115
    // Civil-from-days (Howard Hinnant), UTC.
116
    let z = days + 719_468;
117
    let era = z.div_euclid(146_097);
118
    let doe = z - era * 146_097;
119
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
120
    let y = yoe + era * 400;
121
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
122
    let mp = (5 * doy + 2) / 153;
123
    let d = doy - (153 * mp + 2) / 5 + 1;
124
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
125
    let y = if m <= 2 { y + 1 } else { y };
126
    format!("{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z", rem / 3600, (rem % 3600) / 60, rem % 60)
127
}
128
129
fn run() -> Result<i32> {
130
    let cli = Cli::parse();
131
    match cli.cmd {
132
        Cmd::Init { path } => {
133
            let path = path.unwrap_or(std::env::current_dir()?);
134
            let repo = Repo::init(&path)?;
135
            println!("Initialized oxy repository in {}", repo.root().display());
136
            println!("Bookmark: {}   Author: {} <{}>", repo.config.bookmark, repo.config.author_name, repo.config.author_email);
137
            Ok(0)
138
        }
139
        Cmd::Status => {
140
            let repo = open()?;
141
            let snap = repo.snapshot("oxy status")?;
142
            let heads = repo.bookmark_heads()?;
143
            println!(
144
                "Working copy: {} on {} ({} head{})",
145
                snap.wc.change_id.short(8),
146
                repo.config.bookmark,
147
                heads.len(),
148
                if heads.len() == 1 { "" } else { "s" }
149
            );
150
            if snap.statuses.is_empty() {
151
                println!("The working copy is clean.");
152
            }
153
            for s in &snap.statuses {
154
                let tag = match s.status {
155
                    ChangeStatus::Added => "A",
156
                    ChangeStatus::Modified => "M",
157
                    ChangeStatus::Removed => "D",
158
                    ChangeStatus::ModeChanged => "X",
159
                    ChangeStatus::ConflictEdited => "C!",
160
                };
161
                println!("{tag:2} {}", s.path);
162
            }
163
            let mut code = 0;
164
            if snap.base_snapshot.is_conflicted() {
165
                println!("\nConflicts in the base state:");
166
                for c in &snap.base_snapshot.tree.conflicts {
167
                    println!("  tree: {c:?}");
168
                }
169
                for (p, f) in &snap.base_snapshot.files {
170
                    if f.is_conflicted() {
171
                        println!("  {p}");
172
                    }
173
                }
174
                code = 2;
175
            }
176
            Ok(code)
177
        }
178
        Cmd::Commit { message, depends_on } => {
179
            let repo = open()?;
180
            let mut deps = Vec::new();
181
            for d in &depends_on {
182
                deps.push(repo.resolve_change(d)?);
183
            }
184
            let h = repo.commit(&message, &deps)?;
185
            let c = repo.store().get_change(&h)?;
186
            println!("Committed {} #{}: {}", short_id(&c), h.short(12), message.lines().next().unwrap_or(""));
187
            Ok(0)
188
        }
189
        Cmd::Log => {
190
            let repo = open()?;
191
            repo.snapshot("oxy log")?;
192
            for e in repo.log()? {
193
                let c = &e.change;
194
                let mut flags = Vec::new();
195
                if e.is_working_copy {
196
                    flags.push("working copy");
197
                }
198
                if e.is_head {
199
                    flags.push("head");
200
                }
201
                let flags = if flags.is_empty() { String::new() } else { format!(" ({})", flags.join(", ")) };
202
                println!("{} #{}{}", short_id(c), e.hash.short(12), flags);
203
                println!("    {}", when(c.hlc.wall_ms));
204
                if !c.deps.is_empty() {
205
                    println!("    deps: {}", c.deps.iter().map(|d| format!("#{}", d.short(12))).collect::<Vec<_>>().join(" "));
206
                }
207
                let msg = if c.message.is_empty() { "(no description)" } else { &c.message };
208
                for line in msg.lines() {
209
                    println!("    {line}");
210
                }
211
                println!();
212
            }
213
            Ok(0)
214
        }
215
        Cmd::Diff => {
216
            let repo = open()?;
217
            let snap = repo.snapshot("oxy diff")?;
218
            print!("{}", oxy_core::repo::render_change(&snap.wc, &snap.base, &snap.base_snapshot));
219
            Ok(0)
220
        }
221
        Cmd::Show { change } => {
222
            let repo = open()?;
223
            repo.snapshot("oxy show")?;
224
            let h = repo.resolve_change(&change)?;
225
            let c = repo.store().get_change(&h)?;
226
            println!("change {} #{}", short_id(&c), h);
227
            println!("kind:   {:?}", c.kind);
228
            println!("date:   {}", when(c.hlc.wall_ms));
229
            println!("deps:   {}", c.deps.iter().map(|d| format!("#{}", d.short(12))).collect::<Vec<_>>().join(" "));
230
            println!("sig:    {}", signature_line(&repo, &h)?);
231
            println!("\n{}\n", if c.message.is_empty() { "(no description)" } else { &c.message });
232
            print!("{}", repo.describe_change(&h)?);
233
            Ok(0)
234
        }
235
        Cmd::Checkout { changes, discard } => {
236
            let repo = open()?;
237
            let heads = if changes.is_empty() {
238
                repo.bookmark_heads()?
239
            } else {
240
                changes.iter().map(|c| repo.resolve_change(c)).collect::<Result<Vec<_>, _>>()?
241
            };
242
            let spec = if changes.is_empty() { repo.config.bookmark.clone() } else { changes.join(" ") };
243
            let r = repo.checkout(&heads, discard, &format!("oxy checkout {spec}"))?;
244
            println!("Working copy now on {spec}: {} file(s) written, {} removed", r.written, r.removed);
245
            if r.conflicted {
246
                println!("This state has conflicts; see oxy status.");
247
            }
248
            Ok(0)
249
        }
250
        Cmd::Undo => {
251
            let repo = open()?;
252
            let op = repo.undo()?;
253
            println!("Undid the last operation; now at: {}", op.command);
254
            Ok(0)
255
        }
256
        Cmd::Identity { cmd: IdentityCmd::Create { name, email } } => {
257
            let mut repo = open()?;
258
            let name = name.unwrap_or_else(|| repo.config.author_name.clone());
259
            let email = email.unwrap_or_else(|| repo.config.author_email.clone());
260
            let (key, _) = repo.create_identity(&name, &email)?;
261
            println!("Created identity {name} <{email}>");
262
            println!("KeyId: {key}");
263
            println!("Secret key stored under {}", oxy_core::repo::default_keys_dir().display());
264
            if !repo.config.sign_changes {
265
                println!("Changes will carry this author; run `oxy config core.sign change` to sign each commit.");
266
            }
267
            Ok(0)
268
        }
269
        Cmd::Identity { cmd: IdentityCmd::Show } => {
270
            let repo = open()?;
271
            match repo.config.author_key {
272
                None => println!("No identity configured; run `oxy identity create`."),
273
                Some(key) => {
274
                    let id = repo.identity(&key)?;
275
                    println!("{} <{}>", id.name, id.email);
276
                    println!("KeyId:   {key}");
277
                    println!("Created: {}", when(id.created));
278
                    println!("Secret:  {}", if repo.secret_key()?.is_some() { "available" } else { "NOT FOUND in key directory" });
279
                    println!("Signing: {}", if repo.config.sign_changes { "every change (core.sign = change)" } else { "at push via seals (core.sign = seal)" });
280
                }
281
            }
282
            Ok(0)
283
        }
284
        Cmd::Verify { change } => {
285
            let repo = open()?;
286
            let hashes: Vec<oxy_core::hash::ChangeHash> = match change {
287
                Some(c) => vec![repo.resolve_change(&c)?],
288
                None => repo.log()?.into_iter().filter(|e| !e.is_working_copy).map(|e| e.hash).collect(),
289
            };
290
            let mut bad = 0;
291
            for h in hashes {
292
                let c = repo.store().get_change(&h)?;
293
                let line = signature_line(&repo, &h)?;
294
                if line.starts_with("INVALID") {
295
                    bad += 1;
296
                }
297
                println!("{} #{}  {}", short_id(&c), h.short(12), line);
298
            }
299
            Ok(if bad > 0 { 1 } else { 0 })
300
        }
301
        Cmd::Config { key, value } => {
302
            let mut repo = open()?;
303
            repo.config.set(&key, &value)?;
304
            repo.save_config()?;
305
            println!("{key} = {value}");
306
            Ok(0)
307
        }
308
        Cmd::Op { cmd: OpCmd::Log } => {
309
            let repo = open()?;
310
            for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
311
                println!("{}{} {}  {}", if i == 0 { "@ " } else { "  " }, r.short(12), when(op.hlc.wall_ms), op.command);
312
            }
313
            Ok(0)
314
        }
315
    }
316
    .map_err(|e: anyhow::Error| e)
317
    .or_else(|e| {
318
        if e.to_string().is_empty() {
319
            bail!("unknown error")
320
        } else {
321
            Err(e)
322
        }
323
    })
324
}