OXYGENHUB
# 141b1fb2ebe9 oxygen / crates / oxy-core / src / repo / subrepos.rs
12.5 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 1 month ago source blame history raw
1
//! Subrepositories in the working copy (spec §7.8): reading pins from
2
//! nested repositories, moving them to pins, and the `oxy submodule`
3
//! commands.
4
5
use super::*;
6
use crate::subrepo::{Module, Modules, Pin};
7
use std::process::Command;
8
9
/// What syncing a nested repository to its pin did.
10
#[derive(Clone, Debug, PartialEq, Eq)]
11
pub enum SubrepoSync {
12
    Updated,
13
    UpToDate,
14
    Missing,
15
    Dirty,
16
    Failed(String),
17
}
18
19
/// One subrepo as `oxy submodule status` shows it.
20
#[derive(Clone, Debug)]
21
pub struct SubrepoInfo {
22
    pub path: String,
23
    pub pin: Pin,
24
    pub url: Option<String>,
25
    /// The nested repository's own pin now, if present.
26
    pub actual: Option<Pin>,
27
    pub dirty: bool,
28
}
29
30
fn git_out(dir: &Path, args: &[&str]) -> Result<String> {
31
    let out = Command::new("git")
32
        .arg("-C")
33
        .arg(dir)
34
        .args(args)
35
        .output()
36
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
37
    if !out.status.success() {
38
        return fail(format!(
39
            "git {} in {}: {}",
40
            args.join(" "),
41
            dir.display(),
42
            String::from_utf8_lossy(&out.stderr).trim()
43
        ));
44
    }
45
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
46
}
47
48
/// The pin a nested repository at `dir` is at: its current bookmark's
49
/// heads for an Oxygen repository, `HEAD` for a Git one.
50
pub(crate) fn read_pin(dir: &Path, bookmark_hint: Option<&str>) -> Result<Pin> {
51
    if dir.join(OXY_DIR).exists() {
52
        let nested = Repo::open(dir)?;
53
        return Ok(Pin::Oxy {
54
            repo: nested.id()?,
55
            heads: nested.bookmark_heads()?,
56
            bookmark: nested.config.bookmark.clone(),
57
        });
58
    }
59
    if dir.join(".git").exists() {
60
        let sha = git_out(dir, &["rev-parse", "HEAD"])?;
61
        return Ok(Pin::Git {
62
            sha,
63
            branch: bookmark_hint.unwrap_or("HEAD").to_string(),
64
        });
65
    }
66
    fail(format!("{} is not a repository", dir.display()))
67
}
68
69
/// Whether a nested repository has uncommitted work.
70
fn nested_dirty(dir: &Path) -> Result<bool> {
71
    if dir.join(OXY_DIR).exists() {
72
        let nested = Repo::open(dir)?;
73
        let snap = nested.snapshot("oxy submodule")?;
74
        return Ok(!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty());
75
    }
76
    Ok(!git_out(dir, &["status", "--porcelain"])?.is_empty())
77
}
78
79
/// Whether `url` names an Oxygen repository (else it is taken to be Git).
80
fn is_oxy_url(url: &str) -> bool {
81
    if url.starts_with("http://") || url.starts_with("https://") {
82
        return crate::protocol::open_remote(url, &RemoteOptions::default())
83
            .and_then(|r| r.repo_id())
84
            .is_ok();
85
    }
86
    let p = Path::new(url.strip_prefix("file://").unwrap_or(url));
87
    p.join(OXY_DIR).exists()
88
}
89
90
impl Repo {
91
    pub(crate) fn modules_on_disk(&self) -> Modules {
92
        fs::read_to_string(self.root.join(".oxymodules"))
93
            .map(|t| Modules::parse(&t))
94
            .unwrap_or_default()
95
    }
96
97
    fn write_modules(&self, m: &Modules) -> Result<()> {
98
        if m.entries.is_empty() {
99
            let _ = fs::remove_file(self.root.join(".oxymodules"));
100
            return Ok(());
101
        }
102
        write_atomic(&self.root.join(".oxymodules"), m.to_text().as_bytes())
103
    }
104
105
    /// Bring the nested repository at `path` to `pin`, cloning it first when
106
    /// `init` and it is absent.
107
    pub(crate) fn sync_subrepo(&self, path: &str, pin: &Pin, init: bool) -> Result<SubrepoSync> {
108
        let dir = self.root.join(path);
109
        let module = self.modules_on_disk().entries.get(path).cloned();
110
        let present = dir.join(OXY_DIR).exists() || dir.join(".git").exists();
111
        let cloned = !present;
112
        if !present {
113
            if !init {
114
                return Ok(SubrepoSync::Missing);
115
            }
116
            let Some(m) = &module else {
117
                return Ok(SubrepoSync::Failed(
118
                    "no .oxymodules entry to clone from".into(),
119
                ));
120
            };
121
            if let Some(parent) = dir.parent() {
122
                fs::create_dir_all(parent)?;
123
            }
124
            let _ = fs::remove_dir(&dir);
125
            let r = match pin {
126
                Pin::Oxy { .. } => Repo::clone(&m.url, &dir).map(|_| ()),
127
                Pin::Git { .. } => Command::new("git")
128
                    .args(["clone", "-q", &m.url])
129
                    .arg(&dir)
130
                    .status()
131
                    .map_err(|e| RepoError::Msg(e.to_string()))
132
                    .and_then(|s| {
133
                        if s.success() {
134
                            Ok(())
135
                        } else {
136
                            fail(format!("git clone {} failed", m.url))
137
                        }
138
                    }),
139
            };
140
            if let Err(e) = r {
141
                return Ok(SubrepoSync::Failed(format!("cloning {}: {e}", m.url)));
142
            }
143
        }
144
        let actual = read_pin(&dir, module.as_ref().and_then(|m| m.bookmark.as_deref()))?;
145
        let same = match (pin, &actual) {
146
            (Pin::Oxy { heads: a, .. }, Pin::Oxy { heads: b, .. }) => {
147
                let (mut a, mut b) = (a.clone(), b.clone());
148
                a.sort();
149
                b.sort();
150
                a == b
151
            }
152
            (Pin::Git { sha: a, .. }, Pin::Git { sha: b, .. }) => a == b,
153
            _ => false,
154
        };
155
        if same {
156
            return Ok(if cloned {
157
                SubrepoSync::Updated
158
            } else {
159
                SubrepoSync::UpToDate
160
            });
161
        }
162
        if nested_dirty(&dir)? {
163
            return Ok(SubrepoSync::Dirty);
164
        }
165
        match pin {
166
            Pin::Oxy { heads, .. } => {
167
                let nested = Repo::open(&dir)?;
168
                if nested.load_state(heads).is_err() {
169
                    // The pinned changes are not here yet: fetch from origin.
170
                    if let Err(e) = nested.fetch("origin") {
171
                        return Ok(SubrepoSync::Failed(format!(
172
                            "fetching the pinned changes: {e}"
173
                        )));
174
                    }
175
                }
176
                match nested.checkout(heads, false, "oxy submodule update") {
177
                    Ok(_) => {
178
                        let _ = nested.bookmark_set(&nested.config.bookmark, heads);
179
                        Ok(SubrepoSync::Updated)
180
                    }
181
                    Err(e) => Ok(SubrepoSync::Failed(e.to_string())),
182
                }
183
            }
184
            Pin::Git { sha, .. } => {
185
                if git_out(&dir, &["cat-file", "-e", &format!("{sha}^{{commit}}")]).is_err() {
186
                    if let Err(e) = git_out(&dir, &["fetch", "-q", "origin"]) {
187
                        return Ok(SubrepoSync::Failed(e.to_string()));
188
                    }
189
                }
190
                match git_out(&dir, &["checkout", "-q", "--detach", sha]) {
191
                    Ok(_) => Ok(SubrepoSync::Updated),
192
                    Err(e) => Ok(SubrepoSync::Failed(e.to_string())),
193
                }
194
            }
195
        }
196
    }
197
198
    /// Every subrepo of the working copy's base state.
199
    pub fn subrepos(&self) -> Result<Vec<SubrepoInfo>> {
200
        let (_, wc) = self.working_copy()?;
201
        let snap = self.load_state(&wc.deps)?.materialize();
202
        let modules = self.modules_on_disk();
203
        let mut out = Vec::new();
204
        for (path, f) in &snap.files {
205
            if f.kind != NodeKind::Subrepo {
206
                continue;
207
            }
208
            let FileContent::Opaque { blobs } = &f.content else {
209
                continue;
210
            };
211
            let Some(b) = blobs.first() else { continue };
212
            let pin = Pin::decode(&self.read_blob(b)?)?;
213
            let dir = self.root.join(path);
214
            let present = dir.join(OXY_DIR).exists() || dir.join(".git").exists();
215
            let actual = if present {
216
                read_pin(
217
                    &dir,
218
                    modules
219
                        .entries
220
                        .get(path)
221
                        .and_then(|m| m.bookmark.as_deref()),
222
                )
223
                .ok()
224
            } else {
225
                None
226
            };
227
            let dirty = present && nested_dirty(&dir).unwrap_or(false);
228
            out.push(SubrepoInfo {
229
                path: path.clone(),
230
                pin,
231
                url: modules.entries.get(path).map(|m| m.url.clone()),
232
                actual,
233
                dirty,
234
            });
235
        }
236
        Ok(out)
237
    }
238
239
    /// Clone `url` at `path`, register it in `.oxymodules`, and return the
240
    /// pin the next snapshot will record.
241
    pub fn submodule_add(&self, url: &str, path: &str, bookmark: Option<&str>) -> Result<Pin> {
242
        let path = path.trim_end_matches('/').to_string();
243
        if path.is_empty()
244
            || path.starts_with('/')
245
            || path.split('/').any(|c| c == ".." || c == ".")
246
        {
247
            return fail(format!("{path:?} is not a valid subrepo path"));
248
        }
249
        let dir = self.root.join(&path);
250
        if dir.exists() && fs::read_dir(&dir)?.next().is_some() {
251
            return fail(format!("{path} exists and is not empty"));
252
        }
253
        if let Some(parent) = dir.parent() {
254
            fs::create_dir_all(parent)?;
255
        }
256
        let git = !is_oxy_url(url);
257
        if git {
258
            let mut cmd = Command::new("git");
259
            cmd.args(["clone", "-q"]);
260
            if let Some(b) = bookmark {
261
                cmd.args(["--branch", b]);
262
            }
263
            let status = cmd
264
                .arg(url)
265
                .arg(&dir)
266
                .status()
267
                .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
268
            if !status.success() {
269
                return fail(format!("git clone {url} failed"));
270
            }
271
        } else {
272
            let _ = fs::remove_dir(&dir);
273
            let mut nested = Repo::clone(url, &dir)?;
274
            if let Some(b) = bookmark {
275
                nested.bookmark_switch(b, true)?;
276
            }
277
        }
278
        let mut modules = self.modules_on_disk();
279
        modules.entries.insert(
280
            path.clone(),
281
            Module {
282
                url: url.to_string(),
283
                bookmark: bookmark.map(str::to_string),
284
                git,
285
            },
286
        );
287
        self.write_modules(&modules)?;
288
        read_pin(&dir, bookmark)
289
    }
290
291
    /// Bring nested repositories to their pins (`paths` empty = all).
292
    pub fn submodule_update(
293
        &self,
294
        init: bool,
295
        paths: &[String],
296
    ) -> Result<Vec<(String, SubrepoSync)>> {
297
        let mut out = Vec::new();
298
        for s in self.subrepos()? {
299
            if !paths.is_empty() && !paths.iter().any(|p| p.trim_end_matches('/') == s.path) {
300
                continue;
301
            }
302
            let r = self.sync_subrepo(&s.path, &s.pin, init)?;
303
            out.push((s.path, r));
304
        }
305
        Ok(out)
306
    }
307
308
    /// Drop the `.oxymodules` entry; the node goes with the next snapshot
309
    /// only if the directory is removed, since a registered or tracked
310
    /// nested repository keeps contributing its pin. Here the directory is
311
    /// left in place and the node is removed explicitly from the working
312
    /// copy's next change by unregistering and moving the directory aside.
313
    pub fn submodule_remove(&self, path: &str) -> Result<()> {
314
        let path = path.trim_end_matches('/').to_string();
315
        let mut modules = self.modules_on_disk();
316
        let known = modules.entries.remove(&path).is_some()
317
            || self.subrepos()?.iter().any(|s| s.path == path);
318
        if !known {
319
            return fail(format!("{path} is not a subrepo"));
320
        }
321
        self.write_modules(&modules)?;
322
        // The directory stays; the walker ignores an unregistered nested
323
        // repository unless tracked, so mark it as removed for the next
324
        // snapshot by recording an explicit removal.
325
        let dir = self.oxy.join("subrepos-removed");
326
        fs::create_dir_all(&dir)?;
327
        write_atomic(&dir.join(path.replace('/', "%2F")), b"")?;
328
        Ok(())
329
    }
330
331
    /// Paths whose subrepo node was removed with `oxy submodule remove` and
332
    /// whose directory is still on disk.
333
    pub(crate) fn removed_subrepos(&self) -> BTreeSet<String> {
334
        let mut out = BTreeSet::new();
335
        if let Ok(rd) = fs::read_dir(self.oxy.join("subrepos-removed")) {
336
            for e in rd.flatten() {
337
                out.insert(e.file_name().to_string_lossy().replace("%2F", "/"));
338
            }
339
        }
340
        out
341
    }
342
343
    pub(crate) fn clear_removed_subrepo(&self, path: &str) {
344
        let _ = fs::remove_file(
345
            self.oxy
346
                .join("subrepos-removed")
347
                .join(path.replace('/', "%2F")),
348
        );
349
    }
350
}