OXYGENHUB
# b288cd254343 oxygen / src / main.rs
13.7 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
    /// Report which conflicts of the working copy's base are resolved by the current files
43
    Resolve,
44
    /// Undo the last operation
45
    Undo,
46
    /// Manage the signing identity
47
    Identity {
48
        #[command(subcommand)]
49
        cmd: IdentityCmd,
50
    },
51
    /// Verify the signatures on a change (default: every change in the log)
52
    Verify { change: Option<String> },
53
    /// Set a repository configuration key (author.name, author.email, author.key, core.sign, workspace.bookmark)
54
    Config { key: String, value: String },
55
    /// List operations
56
    #[command(name = "op")]
57
    Op {
58
        #[command(subcommand)]
59
        cmd: OpCmd,
60
    },
61
}
62
63
#[derive(Subcommand)]
64
enum OpCmd {
65
    Log,
66
}
67
68
#[derive(Subcommand)]
69
enum IdentityCmd {
70
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it the author
71
    Create {
72
        #[arg(long)]
73
        name: Option<String>,
74
        #[arg(long)]
75
        email: Option<String>,
76
    },
77
    /// Show the configured identity
78
    Show,
79
}
80
81
fn signature_line(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
82
    Ok(match repo.verify_change(h)? {
83
        SignatureStatus::Unsigned => "unsigned".to_string(),
84
        SignatureStatus::Valid { key, name, email } => format!("signed by {name} <{email}> key {}", key.short(12)),
85
        SignatureStatus::Invalid(why) => format!("INVALID signature: {why}"),
86
    })
87
}
88
89
fn main() {
90
    match run() {
91
        Ok(code) => std::process::exit(code),
92
        Err(e) => {
93
            eprintln!("error: {e:#}");
94
            std::process::exit(1);
95
        }
96
    }
97
}
98
99
fn open() -> Result<Repo> {
100
    Repo::open(&std::env::current_dir()?).context("opening repository")
101
}
102
103
fn short_id(c: &oxy_core::objects::Change) -> String {
104
    c.change_id.short(8)
105
}
106
107
fn when(ms: u64) -> String {
108
    let secs = (ms / 1000) as i64;
109
    let days = secs.div_euclid(86_400);
110
    let rem = secs.rem_euclid(86_400);
111
    // Civil-from-days (Howard Hinnant), UTC.
112
    let z = days + 719_468;
113
    let era = z.div_euclid(146_097);
114
    let doe = z - era * 146_097;
115
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
116
    let y = yoe + era * 400;
117
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
118
    let mp = (5 * doy + 2) / 153;
119
    let d = doy - (153 * mp + 2) / 5 + 1;
120
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
121
    let y = if m <= 2 { y + 1 } else { y };
122
    format!("{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z", rem / 3600, (rem % 3600) / 60, rem % 60)
123
}
124
125
fn run() -> Result<i32> {
126
    let cli = Cli::parse();
127
    match cli.cmd {
128
        Cmd::Init { path } => {
129
            let path = path.unwrap_or(std::env::current_dir()?);
130
            let repo = Repo::init(&path)?;
131
            println!("Initialized oxy repository in {}", repo.root().display());
132
            println!("Bookmark: {}   Author: {} <{}>", repo.config.bookmark, repo.config.author_name, repo.config.author_email);
133
            Ok(0)
134
        }
135
        Cmd::Status => {
136
            let repo = open()?;
137
            let snap = repo.snapshot("oxy status")?;
138
            let heads = repo.bookmark_heads()?;
139
            println!(
140
                "Working copy: {} on {} ({} head{})",
141
                snap.wc.change_id.short(8),
142
                repo.config.bookmark,
143
                heads.len(),
144
                if heads.len() == 1 { "" } else { "s" }
145
            );
146
            if snap.statuses.is_empty() {
147
                println!("The working copy is clean.");
148
            }
149
            for s in &snap.statuses {
150
                let tag = match s.status {
151
                    ChangeStatus::Added => "A",
152
                    ChangeStatus::Modified => "M",
153
                    ChangeStatus::Removed => "D",
154
                    ChangeStatus::ModeChanged => "X",
155
                    ChangeStatus::ConflictEdited => "C!",
156
                    ChangeStatus::Resolved => "R",
157
                };
158
                println!("{tag:2} {}", s.path);
159
            }
160
            let mut code = 0;
161
            if snap.base_snapshot.is_conflicted() {
162
                println!("\nConflicts in the base state (edit the marked files, or the .oxy-conflict-N candidates, then commit):");
163
                for c in &snap.base_snapshot.tree.conflicts {
164
                    println!("  tree: {c:?}");
165
                }
166
                for (p, f) in &snap.base_snapshot.files {
167
                    if f.is_conflicted() {
168
                        let state = match snap.statuses.iter().find(|s| s.path == *p).map(|s| s.status) {
169
                            Some(ChangeStatus::Resolved) => "resolved in working copy",
170
                            Some(ChangeStatus::ConflictEdited) => "markers remain",
171
                            _ => "unresolved",
172
                        };
173
                        println!("  {p}  ({state})");
174
                    }
175
                }
176
                code = 2;
177
            }
178
            Ok(code)
179
        }
180
        Cmd::Commit { message, depends_on } => {
181
            let repo = open()?;
182
            let mut deps = Vec::new();
183
            for d in &depends_on {
184
                deps.push(repo.resolve_change(d)?);
185
            }
186
            let h = repo.commit(&message, &deps)?;
187
            let c = repo.store().get_change(&h)?;
188
            println!("Committed {} #{}: {}", short_id(&c), h.short(12), message.lines().next().unwrap_or(""));
189
            Ok(0)
190
        }
191
        Cmd::Log => {
192
            let repo = open()?;
193
            repo.snapshot("oxy log")?;
194
            for e in repo.log()? {
195
                let c = &e.change;
196
                let mut flags = Vec::new();
197
                if e.is_working_copy {
198
                    flags.push("working copy");
199
                }
200
                if e.is_head {
201
                    flags.push("head");
202
                }
203
                let flags = if flags.is_empty() { String::new() } else { format!(" ({})", flags.join(", ")) };
204
                println!("{} #{}{}", short_id(c), e.hash.short(12), flags);
205
                println!("    {}", when(c.hlc.wall_ms));
206
                if !c.deps.is_empty() {
207
                    println!("    deps: {}", c.deps.iter().map(|d| format!("#{}", d.short(12))).collect::<Vec<_>>().join(" "));
208
                }
209
                let msg = if c.message.is_empty() { "(no description)" } else { &c.message };
210
                for line in msg.lines() {
211
                    println!("    {line}");
212
                }
213
                println!();
214
            }
215
            Ok(0)
216
        }
217
        Cmd::Diff => {
218
            let repo = open()?;
219
            let snap = repo.snapshot("oxy diff")?;
220
            print!("{}", oxy_core::repo::render_change(&snap.wc, &snap.base, &snap.base_snapshot));
221
            Ok(0)
222
        }
223
        Cmd::Show { change } => {
224
            let repo = open()?;
225
            repo.snapshot("oxy show")?;
226
            let h = repo.resolve_change(&change)?;
227
            let c = repo.store().get_change(&h)?;
228
            println!("change {} #{}", short_id(&c), h);
229
            println!("kind:   {:?}", c.kind);
230
            println!("date:   {}", when(c.hlc.wall_ms));
231
            println!("deps:   {}", c.deps.iter().map(|d| format!("#{}", d.short(12))).collect::<Vec<_>>().join(" "));
232
            println!("sig:    {}", signature_line(&repo, &h)?);
233
            println!("\n{}\n", if c.message.is_empty() { "(no description)" } else { &c.message });
234
            print!("{}", repo.describe_change(&h)?);
235
            Ok(0)
236
        }
237
        Cmd::Checkout { changes, discard } => {
238
            let repo = open()?;
239
            let heads = if changes.is_empty() {
240
                repo.bookmark_heads()?
241
            } else {
242
                changes.iter().map(|c| repo.resolve_change(c)).collect::<Result<Vec<_>, _>>()?
243
            };
244
            let spec = if changes.is_empty() { repo.config.bookmark.clone() } else { changes.join(" ") };
245
            let r = repo.checkout(&heads, discard, &format!("oxy checkout {spec}"))?;
246
            println!("Working copy now on {spec}: {} file(s) written, {} removed", r.written, r.removed);
247
            if r.conflicted {
248
                println!("This state has conflicts; see oxy status.");
249
            }
250
            Ok(0)
251
        }
252
        Cmd::Resolve => {
253
            let repo = open()?;
254
            let snap = repo.snapshot("oxy resolve")?;
255
            if !snap.base_snapshot.is_conflicted() {
256
                println!("The working copy's base has no conflicts.");
257
                return Ok(0);
258
            }
259
            let mut remaining = 0;
260
            for (p, f) in &snap.base_snapshot.files {
261
                if !f.is_conflicted() {
262
                    continue;
263
                }
264
                match snap.statuses.iter().find(|s| s.path == *p).map(|s| s.status) {
265
                    Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
266
                    Some(ChangeStatus::ConflictEdited) => {
267
                        remaining += 1;
268
                        println!("markers    {p}");
269
                    }
270
                    _ => {
271
                        remaining += 1;
272
                        println!("unresolved {p}");
273
                    }
274
                }
275
            }
276
            for c in &snap.base_snapshot.tree.conflicts {
277
                remaining += 1;
278
                println!("tree       {c:?}");
279
            }
280
            if remaining == 0 {
281
                println!("All conflicts are resolved; `oxy commit` will record the resolution.");
282
                Ok(0)
283
            } else {
284
                Ok(2)
285
            }
286
        }
287
        Cmd::Undo => {
288
            let repo = open()?;
289
            let op = repo.undo()?;
290
            println!("Undid the last operation; now at: {}", op.command);
291
            Ok(0)
292
        }
293
        Cmd::Identity { cmd: IdentityCmd::Create { name, email } } => {
294
            let mut repo = open()?;
295
            let name = name.unwrap_or_else(|| repo.config.author_name.clone());
296
            let email = email.unwrap_or_else(|| repo.config.author_email.clone());
297
            let (key, _) = repo.create_identity(&name, &email)?;
298
            println!("Created identity {name} <{email}>");
299
            println!("KeyId: {key}");
300
            println!("Secret key stored under {}", oxy_core::repo::default_keys_dir().display());
301
            if !repo.config.sign_changes {
302
                println!("Changes will carry this author; run `oxy config core.sign change` to sign each commit.");
303
            }
304
            Ok(0)
305
        }
306
        Cmd::Identity { cmd: IdentityCmd::Show } => {
307
            let repo = open()?;
308
            match repo.config.author_key {
309
                None => println!("No identity configured; run `oxy identity create`."),
310
                Some(key) => {
311
                    let id = repo.identity(&key)?;
312
                    println!("{} <{}>", id.name, id.email);
313
                    println!("KeyId:   {key}");
314
                    println!("Created: {}", when(id.created));
315
                    println!("Secret:  {}", if repo.secret_key()?.is_some() { "available" } else { "NOT FOUND in key directory" });
316
                    println!("Signing: {}", if repo.config.sign_changes { "every change (core.sign = change)" } else { "at push via seals (core.sign = seal)" });
317
                }
318
            }
319
            Ok(0)
320
        }
321
        Cmd::Verify { change } => {
322
            let repo = open()?;
323
            let hashes: Vec<oxy_core::hash::ChangeHash> = match change {
324
                Some(c) => vec![repo.resolve_change(&c)?],
325
                None => repo.log()?.into_iter().filter(|e| !e.is_working_copy).map(|e| e.hash).collect(),
326
            };
327
            let mut bad = 0;
328
            for h in hashes {
329
                let c = repo.store().get_change(&h)?;
330
                let line = signature_line(&repo, &h)?;
331
                if line.starts_with("INVALID") {
332
                    bad += 1;
333
                }
334
                println!("{} #{}  {}", short_id(&c), h.short(12), line);
335
            }
336
            Ok(if bad > 0 { 1 } else { 0 })
337
        }
338
        Cmd::Config { key, value } => {
339
            let mut repo = open()?;
340
            repo.config.set(&key, &value)?;
341
            repo.save_config()?;
342
            println!("{key} = {value}");
343
            Ok(0)
344
        }
345
        Cmd::Op { cmd: OpCmd::Log } => {
346
            let repo = open()?;
347
            for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
348
                println!("{}{} {}  {}", if i == 0 { "@ " } else { "  " }, r.short(12), when(op.hlc.wall_ms), op.command);
349
            }
350
            Ok(0)
351
        }
352
    }
353
    .map_err(|e: anyhow::Error| e)
354
    .or_else(|e| {
355
        if e.to_string().is_empty() {
356
            bail!("unknown error")
357
        } else {
358
            Err(e)
359
        }
360
    })
361
}