OXYGENHUB
# 978470f76e66 oxygen / src / cli / sync.rs
5.8 KiB · Rust · last changed Pack merging above 16 packs; modern CLI presentation (colour, spinners, --plain, NO_COLOR); oxy prompt with manifest-based dirty check and docs/prompt.md 1 month ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Commands that talk to remotes, and the reference server.
2
3
use super::format::plural;
4
use super::open;
135212de Andy McCall ↶ 5
use super::ui;
fce44ae9 Andy McCall ↶ 6
use anyhow::{Context, Result};
7
use oxy_core::repo::Repo;
8
use std::path::PathBuf;
9
10
pub fn clone(url: &str, dest: Option<PathBuf>) -> Result<i32> {
11
    let dest = dest.unwrap_or_else(|| {
12
        let base = url.trim_end_matches('/').rsplit('/').next().unwrap_or("repo");
13
        PathBuf::from(base)
14
    });
135212de Andy McCall ↶ 15
    let sp = ui::spinner(&format!("Cloning {url}…"));
fce44ae9 Andy McCall ↶ 16
    let repo = Repo::clone(url, &dest)?;
17
    let heads = repo.bookmark_heads()?;
135212de Andy McCall ↶ 18
    sp.done(&format!("{} into {} ({} on {}: {})", ui::ok("Cloned"), ui::path(repo.root().display()), url, ui::id(&repo.config.bookmark), plural(heads.len(), "head")));
fce44ae9 Andy McCall ↶ 19
    Ok(0)
20
}
21
22
pub fn remote_add(name: &str, url: &str) -> Result<i32> {
23
    let mut repo = open()?;
24
    repo.config.set(&format!("remote.{name}.url"), url)?;
25
    repo.save_config()?;
26
    println!("Added remote {name} = {url}");
27
    Ok(0)
28
}
29
30
pub fn remote_remove(name: &str) -> Result<i32> {
31
    let mut repo = open()?;
32
    repo.config.set(&format!("remote.{name}.url"), "")?;
33
    repo.save_config()?;
34
    println!("Removed remote {name}");
35
    Ok(0)
36
}
37
38
pub fn remote_list() -> Result<i32> {
39
    let repo = open()?;
40
    let view = repo.view()?;
41
    for (name, url) in &repo.config.remotes {
42
        println!("{name}\t{url}");
43
        if let Some(bms) = view.remotes.get(name) {
44
            for (bm, st) in bms {
45
                let heads = repo.store().get_state(st).map(|s| s.heads.len()).unwrap_or(0);
46
                println!("    {bm}: {}", plural(heads, "head"));
47
            }
48
        }
49
    }
50
    Ok(0)
51
}
52
53
fn remote_name(remote: Option<&str>) -> String {
54
    remote.unwrap_or("origin").to_string()
55
}
56
57
pub fn fetch(remote: Option<&str>) -> Result<i32> {
58
    let repo = open()?;
59
    let remote = remote_name(remote);
135212de Andy McCall ↶ 60
    let sp = ui::spinner(&format!("Fetching from {remote}…"));
83e0677b Andy McCall ↶ 61
    let report = repo.fetch(&remote)?;
135212de Andy McCall ↶ 62
    sp.clear();
83e0677b Andy McCall ↶ 63
    for (name, heads, n) in &report.refs {
135212de Andy McCall ↶ 64
        println!("{} {}, {}", ui::id(format!("{remote}/{name}")), plural(heads.len(), "head"), plural(*n, "new change"));
83e0677b Andy McCall ↶ 65
    }
66
    if report.unverified {
135212de Andy McCall ↶ 67
        eprintln!("{} {remote} has no trust policy; nothing fetched from it was verified", ui::warn("warning:"));
fce44ae9 Andy McCall ↶ 68
    }
69
    Ok(0)
70
}
71
72
pub fn pull(remote: Option<&str>) -> Result<i32> {
73
    let repo = open()?;
74
    let remote = remote_name(remote);
135212de Andy McCall ↶ 75
    let sp = ui::spinner(&format!("Pulling from {remote}…"));
fce44ae9 Andy McCall ↶ 76
    let r = repo.pull(&remote)?;
77
    if !r.changed {
135212de Andy McCall ↶ 78
        sp.done(&ui::dim("Already up to date."));
fce44ae9 Andy McCall ↶ 79
        return Ok(0);
80
    }
135212de Andy McCall ↶ 81
    sp.done(&format!(
82
        "{} {} now has {}{}",
83
        ui::ok("Pulled:"),
84
        ui::id(&repo.config.bookmark),
fce44ae9 Andy McCall ↶ 85
        plural(r.heads.len(), "head"),
86
        if r.checked_out { "; working copy updated" } else { "; run `oxy checkout` to update the working copy" }
135212de Andy McCall ↶ 87
    ));
fce44ae9 Andy McCall ↶ 88
    let snap = repo.snapshot("oxy pull")?;
89
    if snap.base_snapshot.is_conflicted() {
135212de Andy McCall ↶ 90
        println!("  {}", ui::warn("the result has conflicts; see oxy status"));
fce44ae9 Andy McCall ↶ 91
    }
92
    Ok(0)
93
}
94
95
pub fn push(remote: Option<&str>, force: bool) -> Result<i32> {
96
    let repo = open()?;
97
    let remote = remote_name(remote);
135212de Andy McCall ↶ 98
    let sp = ui::spinner(&format!("Pushing to {remote}…"));
99
    let results = repo.push(&remote, force)?;
100
    sp.clear();
fce44ae9 Andy McCall ↶ 101
    let mut code = 0;
135212de Andy McCall ↶ 102
    for r in results {
fce44ae9 Andy McCall ↶ 103
        if r.ok {
135212de Andy McCall ↶ 104
            println!("{} {}", ui::id(format!("{remote}/{}", r.name)), ui::ok(if r.reason.is_empty() { "updated" } else { r.reason.as_str() }));
fce44ae9 Andy McCall ↶ 105
        } else {
135212de Andy McCall ↶ 106
            println!("{} {} {}", ui::id(format!("{remote}/{}", r.name)), ui::err("rejected:"), r.reason);
fce44ae9 Andy McCall ↶ 107
            code = 1;
108
        }
109
    }
110
    Ok(code)
111
}
112
2b5ee371 Andy McCall ↶ 113
pub fn serve(root: PathBuf, bind: &str, tokens: Vec<String>, tls: Option<(PathBuf, PathBuf)>) -> Result<i32> {
fce44ae9 Andy McCall ↶ 114
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
115
    let root = root.canonicalize()?;
2b5ee371 Andy McCall ↶ 116
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
fce44ae9 Andy McCall ↶ 117
    println!(
2b5ee371 Andy McCall ↶ 118
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
fce44ae9 Andy McCall ↶ 119
        root.display(),
2b5ee371 Andy McCall ↶ 120
        if tls.is_some() { "https" } else { "http" },
fce44ae9 Andy McCall ↶ 121
        if tokens.is_empty() { "open: no push tokens configured" } else { "push requires a token" }
122
    );
2b5ee371 Andy McCall ↶ 123
    if tls.is_none() && !bind.starts_with("127.") && !bind.starts_with("localhost") && !bind.starts_with("[::1]") {
124
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
125
    }
126
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
fce44ae9 Andy McCall ↶ 127
    Ok(0)
128
}
79ab8528 Andy McCall ↶ 129
130
pub fn git_export(git_dir: &std::path::Path) -> Result<i32> {
131
    let repo = open()?;
135212de Andy McCall ↶ 132
    let sp = ui::spinner("Exporting to Git…");
79ab8528 Andy McCall ↶ 133
    let r = repo.git_export(git_dir)?;
135212de Andy McCall ↶ 134
    sp.clear();
79ab8528 Andy McCall ↶ 135
    println!(
136
        "Exported {} to {} (branch {}: {}{}); {} already exported.",
137
        plural(r.exported, "change"),
138
        git_dir.display(),
139
        r.branch,
140
        plural(r.heads, "head"),
141
        if r.heads > 1 { ", joined by a synthetic merge commit" } else { "" },
142
        r.skipped
143
    );
144
    Ok(0)
145
}
c3069537 Andy McCall ↶ 146
147
pub fn git_import(git_dir: &std::path::Path, dest: &std::path::Path, branch: &str) -> Result<i32> {
148
    let repo = Repo::init(dest)?;
149
    let started = std::time::Instant::now();
135212de Andy McCall ↶ 150
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
c3069537 Andy McCall ↶ 151
    let r = repo.import_git(git_dir, branch)?;
135212de Andy McCall ↶ 152
    sp.clear();
c3069537 Andy McCall ↶ 153
    println!(
154
        "Imported {} ({} merges) from {} {branch} into {} in {:.1?}: {} now has {}.{}",
155
        plural(r.commits, "commit"),
156
        r.merges,
157
        git_dir.display(),
158
        repo.root().display(),
159
        started.elapsed(),
160
        repo.config.bookmark,
161
        plural(r.heads, "head"),
162
        if r.skipped_submodules > 0 { format!(" Skipped {} submodule entries.", r.skipped_submodules) } else { String::new() }
163
    );
164
    Ok(0)
165
}