Skip to main content

surjection_core/remote/
folder.rs

1//! Folder remotes (SPEC 9.6): a local or network directory holding one
2//! subfolder per machine, written only by that machine:
3//!
4//! ```text
5//! <path>/<store_id>/<machine_id>/
6//!   machine.json   written last
7//!   store.git/     repo-per-machine: a bare repository
8//!   latest/        mirror: the HEAD tree and EXPORT.json
9//!   archives/      archive: surjection-<yyyymmdd-hhmmss>-<shortsha>.zip
10//! ```
11//!
12//! Readers accept only names of that grammar (ULID store and machine
13//! folders, the files above) and only the ids `machine.json` lists;
14//! everything else is skipped, and names that match a sync tool's conflict
15//! or temp pattern, or refs `machine.json` does not list, are reported as
16//! `sync_artifact_ignored`. Nothing a reader skips is ever deleted.
17//! A remote that is not there (`remote_unreachable`) never blocks local
18//! work; Surjection never creates the remote's own folder or mounts anything.
19
20use std::collections::BTreeMap;
21use std::io::{Read, Write};
22use std::path::{Path, PathBuf};
23
24use crate::env::Os;
25use crate::error::{CoreError, ErrorCode};
26use crate::fs::Fs;
27use crate::model::ids::{self, IdKind};
28use crate::remote::config::{DEFAULT_KEEP, FolderMode, RemoteConfig, RemoteKind};
29use crate::remote::manifest::{EXPORT_FILE, ExportInfo, MANIFEST_SCHEMA, MachineManifest};
30use crate::remote::sync_artifacts::{Artifact, artifact_tool};
31use crate::remote::unc::{UncResolver, resolve};
32use crate::store::merge::{Files, MergeOutcome, PendingMerge, RecordedConflict, write_merge_state};
33use crate::store::{CommitId, Machine, Store, bare_commit_subject, utc_datetime};
34
35const STORE_GIT: &str = "store.git";
36const LATEST: &str = "latest";
37const ARCHIVES: &str = "archives";
38
39/// The directory a folder remote resolves to now, or `remote_unreachable`.
40pub fn reachable_root(
41    fs: &dyn Fs,
42    os: Os,
43    unc: &dyn UncResolver,
44    remote: &RemoteConfig,
45) -> Result<PathBuf, CoreError> {
46    if remote.kind != RemoteKind::Folder {
47        return Err(CoreError::new(
48            ErrorCode::InvalidValue,
49            format!("{} is a {} remote", remote.name, remote.kind.as_str()),
50        ));
51    }
52    let typed = remote.path.as_deref().ok_or_else(|| {
53        CoreError::new(
54            ErrorCode::MissingField,
55            format!("remote {} has no path", remote.name),
56        )
57    })?;
58    let root = resolve(os, unc, Path::new(typed));
59    if !fs.is_dir(&root) {
60        return Err(CoreError::new(
61            ErrorCode::RemoteUnreachable,
62            format!(
63                "remote {} is not reachable (drive unplugged or share not mounted?); local work \
64                 goes on and the next push tries again",
65                remote.name
66            ),
67        )
68        .with_path(&root));
69    }
70    Ok(root)
71}
72
73/// What a push wrote.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct PushOutcome {
76    /// This machine's subfolder.
77    pub dir: PathBuf,
78    pub mode: FolderMode,
79    pub head: CommitId,
80    /// The archive written (archive mode).
81    pub archive: Option<String>,
82}
83
84/// Pushes the store to a folder remote, in its mode.
85pub fn push(
86    store: &Store<'_>,
87    remote: &RemoteConfig,
88    unc: &dyn UncResolver,
89    app_version: &str,
90) -> Result<PushOutcome, CoreError> {
91    let fs = store.fs();
92    let env = store.env();
93    let root = reachable_root(fs, env.os(), unc, remote)?;
94    let machine = Machine::load_or_create(env, fs, store.state_dir())?;
95    let dir = root.join(store.store_id()).join(&machine.id);
96    fs.create_dir_all(&dir)
97        .map_err(|err| io("cannot create directory", &dir, &err))?;
98    let mode = remote.folder_mode();
99    let mut manifest = MachineManifest {
100        schema: MANIFEST_SCHEMA,
101        store_id: store.store_id().to_owned(),
102        machine_id: machine.id.clone(),
103        label: machine.label.clone(),
104        os: env.os().as_str().to_owned(),
105        app_version: app_version.to_owned(),
106        pushed_at: utc_datetime(env.now()).to_string(),
107        head: None,
108        tags: BTreeMap::new(),
109        mirror: None,
110        archives: Vec::new(),
111    };
112    let head = store.head()?;
113    let mut archive = None;
114    match mode {
115        FolderMode::RepoPerMachine => {
116            let (head, tags) = store.export_bare(&dir.join(STORE_GIT))?;
117            manifest.head = Some(head.to_string());
118            manifest.tags = tags;
119        }
120        FolderMode::Mirror => {
121            write_mirror(store, &dir, &head, &machine.id)?;
122            manifest.head = Some(head.to_string());
123            manifest.mirror = Some(head.to_string());
124        }
125        FolderMode::Archive => {
126            let keep = remote.keep.unwrap_or(DEFAULT_KEEP).max(1) as usize;
127            let (name, kept) = write_archive(store, &dir, &head, &machine.id, keep)?;
128            manifest.head = Some(head.to_string());
129            manifest.archives = kept;
130            archive = Some(name);
131        }
132    }
133    manifest.write(fs, &dir)?;
134    Ok(PushOutcome {
135        dir,
136        mode,
137        head,
138        archive,
139    })
140}
141
142fn io(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
143    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
144}
145
146/// A random suffix for temp names.
147fn suffix() -> Result<String, CoreError> {
148    let mut random = [0u8; 4];
149    getrandom::fill(&mut random).map_err(|err| {
150        CoreError::new(
151            ErrorCode::IoError,
152            format!("cannot read random bytes: {err}"),
153        )
154    })?;
155    Ok(random.iter().map(|b| format!("{b:02x}")).collect())
156}
157
158fn export_info(store: &Store<'_>, head: &CommitId, machine_id: &str) -> Result<Vec<u8>, CoreError> {
159    let info = ExportInfo {
160        schema: 1,
161        commit: head.to_string(),
162        time: utc_datetime(store.env().now()).to_string(),
163        machine: machine_id.to_owned(),
164    };
165    serde_json::to_vec_pretty(&info).map_err(|err| {
166        CoreError::new(
167            ErrorCode::InvalidValue,
168            format!("cannot write export: {err}"),
169        )
170    })
171}
172
173/// `latest/`: the HEAD tree and `EXPORT.json`, written into a temp folder
174/// and swapped in by renames.
175fn write_mirror(
176    store: &Store<'_>,
177    dir: &Path,
178    head: &CommitId,
179    machine_id: &str,
180) -> Result<(), CoreError> {
181    let fs = store.fs();
182    let tag = suffix()?;
183    let temp = dir.join(format!(".{LATEST}.surjection-{tag}.tmp"));
184    let mut files = store.files_at(head)?;
185    files.insert(
186        EXPORT_FILE.to_owned(),
187        export_info(store, head, machine_id)?,
188    );
189    let written = files.iter().try_for_each(|(relative, bytes)| {
190        let path = relative
191            .split('/')
192            .fold(temp.clone(), |path, part| path.join(part));
193        if let Some(parent) = path.parent() {
194            fs.create_dir_all(parent)
195                .map_err(|err| io("cannot create directory", parent, &err))?;
196        }
197        fs.write(&path, bytes)
198            .map_err(|err| io("cannot write file", &path, &err))
199    });
200    // Nothing of a failed push stays behind in the synced folder.
201    let discard = || {
202        let _ = fs.remove_dir_all(&temp);
203    };
204    if let Err(err) = written {
205        discard();
206        return Err(err);
207    }
208    let latest = dir.join(LATEST);
209    let old = dir.join(format!(".{LATEST}.surjection-{tag}.old"));
210    if fs.exists(&latest)
211        && let Err(err) = fs.replace(&latest, &old)
212    {
213        discard();
214        return Err(io("cannot move the old mirror", &latest, &err));
215    }
216    if let Err(err) = fs.replace(&temp, &latest) {
217        if fs.exists(&old) {
218            let _ = fs.replace(&old, &latest);
219        }
220        discard();
221        return Err(io("cannot move the mirror in place", &latest, &err));
222    }
223    if fs.exists(&old) {
224        let _ = fs.remove_dir_all(&old);
225    }
226    Ok(())
227}
228
229/// Whether `name` is an archive name this module writes.
230fn is_archive_name(name: &str) -> bool {
231    name.strip_prefix("surjection-")
232        .and_then(|rest| rest.strip_suffix(".zip"))
233        .is_some_and(|core| {
234            let parts: Vec<&str> = core.split('-').collect();
235            parts.len() == 3
236                && parts[0].len() == 8
237                && parts[1].len() == 6
238                && parts[..2]
239                    .iter()
240                    .all(|p| p.bytes().all(|b| b.is_ascii_digit()))
241                && !parts[2].is_empty()
242                && parts[2].bytes().all(|b| b.is_ascii_hexdigit())
243        })
244}
245
246/// A zip of `files`.
247fn zip_bytes(files: &Files) -> Result<Vec<u8>, CoreError> {
248    let zip_error = |err: zip::result::ZipError| {
249        CoreError::new(
250            ErrorCode::IoError,
251            format!("cannot write the archive: {err}"),
252        )
253    };
254    let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
255    let options = zip::write::SimpleFileOptions::default()
256        .compression_method(zip::CompressionMethod::Deflated);
257    for (name, bytes) in files {
258        writer
259            .start_file(name.as_str(), options)
260            .map_err(zip_error)?;
261        writer
262            .write_all(bytes)
263            .map_err(|err| CoreError::new(ErrorCode::IoError, err.to_string()))?;
264    }
265    Ok(writer.finish().map_err(zip_error)?.into_inner())
266}
267
268/// The store at `rev` as a zip with `EXPORT.json` (what `restore --from`
269/// reads, SPEC 10 item 5), and its name `surjection-<ts>-<shortsha>.zip`.
270pub fn export_zip(
271    store: &Store<'_>,
272    rev: &CommitId,
273    machine_id: &str,
274) -> Result<(String, Vec<u8>), CoreError> {
275    let stamp = crate::apply::backup::timestamp(store.env().now());
276    // 20260101T000000Z -> 20260101-000000
277    let stamp = format!("{}-{}", &stamp[..8], &stamp[9..15]);
278    let name = format!("surjection-{stamp}-{}.zip", &rev.as_str()[..12]);
279    let mut files = store.files_at(rev)?;
280    files.insert(EXPORT_FILE.to_owned(), export_info(store, rev, machine_id)?);
281    Ok((name, zip_bytes(&files)?))
282}
283
284/// `archives/surjection-<ts>-<shortsha>.zip`, then the oldest archives beyond
285/// `keep` are deleted. Returns the new name and the archives kept.
286fn write_archive(
287    store: &Store<'_>,
288    dir: &Path,
289    head: &CommitId,
290    machine_id: &str,
291    keep: usize,
292) -> Result<(String, Vec<String>), CoreError> {
293    let fs = store.fs();
294    let archives = dir.join(ARCHIVES);
295    fs.create_dir_all(&archives)
296        .map_err(|err| io("cannot create directory", &archives, &err))?;
297    let (name, bytes) = export_zip(store, head, machine_id)?;
298    let temp = archives.join(format!(".{name}.surjection-{}.tmp", suffix()?));
299    fs.write_new(&temp, &bytes, None)
300        .map_err(|err| io("cannot write the archive", &temp, &err))?;
301    let path = archives.join(&name);
302    fs.replace(&temp, &path).map_err(|err| {
303        let _ = fs.remove_file(&temp);
304        io("cannot move the archive in place", &path, &err)
305    })?;
306    let mut kept: Vec<String> = fs
307        .read_dir(&archives)
308        .map_err(|err| io("cannot list archives", &archives, &err))?
309        .into_iter()
310        .filter_map(|path| path.file_name()?.to_str().map(str::to_owned))
311        .filter(|name| is_archive_name(name))
312        .collect();
313    kept.sort();
314    while kept.len() > keep {
315        let oldest = kept.remove(0);
316        let _ = fs.remove_file(&archives.join(&oldest));
317    }
318    Ok((name, kept))
319}
320
321/// One machine of a folder remote, from its `machine.json`.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct MachineEntry {
324    pub store_id: String,
325    pub machine_id: String,
326    pub dir: PathBuf,
327    pub manifest: MachineManifest,
328    /// The subject of the head commit, when the machine has `store.git`.
329    pub subject: Option<String>,
330}
331
332impl MachineEntry {
333    /// Whether the machine's latest push was `repo-per-machine`: a
334    /// `store.git` left from before a switch to `mirror` or `archive` does
335    /// not hold the head the manifest names.
336    pub fn has_repo(&self, fs: &dyn Fs) -> bool {
337        self.manifest.head.is_some()
338            && self.manifest.mirror.is_none()
339            && self.manifest.archives.is_empty()
340            && fs.is_dir(&self.dir.join(STORE_GIT))
341    }
342}
343
344/// What a folder remote holds.
345#[derive(Debug, Clone, Default, PartialEq, Eq)]
346pub struct Listing {
347    pub machines: Vec<MachineEntry>,
348    /// Sync tool artifacts and unlisted refs, never read, never deleted.
349    pub artifacts: Vec<Artifact>,
350}
351
352/// Lists the machines under `root` (of store `store_id`, or of every
353/// store), reporting sync artifacts on the way.
354pub fn list(fs: &dyn Fs, root: &Path, store_id: Option<&str>) -> Result<Listing, CoreError> {
355    let mut listing = Listing::default();
356    for store_dir in read_dir(fs, root)? {
357        let name = file_name(&store_dir);
358        if !fs.is_dir(&store_dir) || !ids::is_valid(IdKind::Store, &name) {
359            report(&mut listing, &store_dir, &name);
360            continue;
361        }
362        if store_id.is_some_and(|id| id != name) {
363            continue;
364        }
365        // A folder a sync tool or its owner removes meanwhile is skipped.
366        let Ok(machine_dirs) = fs.read_dir(&store_dir) else {
367            continue;
368        };
369        for machine_dir in machine_dirs {
370            let machine = file_name(&machine_dir);
371            if !fs.is_dir(&machine_dir) || !ids::is_valid(IdKind::Machine, &machine) {
372                report(&mut listing, &machine_dir, &machine);
373                continue;
374            }
375            let manifest = MachineManifest::load(fs, &machine_dir)
376                .filter(|m| m.machine_id == machine && m.store_id == name);
377            scan_machine_dir(fs, &machine_dir, manifest.as_ref(), &mut listing)?;
378            let Some(manifest) = manifest else {
379                continue;
380            };
381            let subject = manifest
382                .head
383                .as_deref()
384                .and_then(|head| bare_commit_subject(&machine_dir.join(STORE_GIT), head));
385            listing.machines.push(MachineEntry {
386                store_id: name.clone(),
387                machine_id: machine,
388                dir: machine_dir,
389                manifest,
390                subject,
391            });
392        }
393    }
394    Ok(listing)
395}
396
397fn read_dir(fs: &dyn Fs, dir: &Path) -> Result<Vec<PathBuf>, CoreError> {
398    fs.read_dir(dir)
399        .map_err(|err| io("cannot list directory", dir, &err))
400}
401
402fn file_name(path: &Path) -> String {
403    path.file_name()
404        .map(|name| name.to_string_lossy().into_owned())
405        .unwrap_or_default()
406}
407
408fn report(listing: &mut Listing, path: &Path, name: &str) {
409    if let Some(tool) = artifact_tool(name)
410        && !listing.artifacts.iter().any(|a| a.path == path)
411    {
412        listing.artifacts.push(Artifact {
413            path: path.to_path_buf(),
414            tool,
415        });
416    }
417}
418
419/// Reports artifacts anywhere in a machine subfolder, and refs in
420/// `store.git` that `machine.json` does not list.
421fn scan_machine_dir(
422    fs: &dyn Fs,
423    dir: &Path,
424    manifest: Option<&MachineManifest>,
425    listing: &mut Listing,
426) -> Result<(), CoreError> {
427    let mut stack = vec![dir.to_path_buf()];
428    while let Some(current) = stack.pop() {
429        let Ok(entries) = fs.read_dir(&current) else {
430            continue;
431        };
432        for path in entries {
433            let name = file_name(&path);
434            report(listing, &path, &name);
435            if fs.is_dir(&path) {
436                stack.push(path);
437            }
438        }
439    }
440    let refs = dir.join(STORE_GIT).join("refs");
441    if !fs.is_dir(&refs) {
442        return Ok(());
443    }
444    let mut stack = vec![refs.clone()];
445    while let Some(current) = stack.pop() {
446        let Ok(entries) = fs.read_dir(&current) else {
447            continue;
448        };
449        for path in entries {
450            if fs.is_dir(&path) {
451                stack.push(path);
452                continue;
453            }
454            let Ok(relative) = path.strip_prefix(dir.join(STORE_GIT)) else {
455                continue;
456            };
457            let refname = relative
458                .components()
459                .map(|part| part.as_os_str().to_string_lossy().into_owned())
460                .collect::<Vec<_>>()
461                .join("/");
462            let listed = manifest.is_some_and(|m| {
463                refname == format!("refs/heads/{}", crate::store::BRANCH)
464                    || refname
465                        .strip_prefix("refs/tags/")
466                        .is_some_and(|tag| m.tags.contains_key(tag))
467            });
468            if !listed && !listing.artifacts.iter().any(|a| a.path == path) {
469                listing.artifacts.push(Artifact {
470                    path,
471                    tool: "unlisted ref",
472                });
473            }
474        }
475    }
476    Ok(())
477}
478
479/// What merging one incoming head did: a sibling machine of a folder
480/// remote, or a git remote's `main` (no machine).
481#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct SiblingPull {
483    pub machine_id: Option<String>,
484    pub label: String,
485    /// The merge, or why there was none (`remote_incomplete`).
486    pub outcome: Result<MergeOutcome, CoreError>,
487}
488
489/// What a pull did.
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub struct PullReport {
492    pub remote: String,
493    /// `auto/pre-pull/<ts>`, made before the first change.
494    pub tag: Option<String>,
495    pub head_before: CommitId,
496    pub head_after: CommitId,
497    pub siblings: Vec<SiblingPull>,
498    pub artifacts: Vec<Artifact>,
499    /// Tags created from siblings.
500    pub tags_imported: Vec<String>,
501    /// Existing tags a git fetch moved (SPEC 9.6's `+refs/tags/*`); folder
502    /// pulls never move a tag.
503    pub tags_moved: Vec<String>,
504}
505
506impl PullReport {
507    pub fn conflicts(&self) -> usize {
508        self.siblings
509            .iter()
510            .map(|s| match &s.outcome {
511                Ok(MergeOutcome::Conflicts { conflicts, .. }) => conflicts.len(),
512                _ => 0,
513            })
514            .sum()
515    }
516}
517
518/// Pulls every sibling machine of this store from a folder remote and
519/// merges each head (SPEC 9.9). Conflicts go to
520/// `state/merge/MERGE_STATE.json`; HEAD stays where it was for them.
521pub fn pull(
522    store: &Store<'_>,
523    remote: &RemoteConfig,
524    unc: &dyn UncResolver,
525) -> Result<PullReport, CoreError> {
526    let fs = store.fs();
527    let root = reachable_root(fs, store.env().os(), unc, remote)?;
528    let machine = Machine::load_or_create(store.env(), fs, store.state_dir())?;
529    let listing = list(fs, &root, Some(store.store_id()))?;
530    let head_before = store.head()?;
531    let mut report = PullReport {
532        remote: remote.name.clone(),
533        tag: None,
534        head_before: head_before.clone(),
535        head_after: head_before,
536        siblings: Vec::new(),
537        artifacts: listing.artifacts,
538        tags_imported: Vec::new(),
539        tags_moved: Vec::new(),
540    };
541    let mut pending = Vec::new();
542    let mut attempted = Vec::new();
543    for sibling in listing.machines {
544        if sibling.machine_id == machine.id || !sibling.has_repo(fs) {
545            continue;
546        }
547        let source = format!("{}/{}", remote.name, sibling.machine_id);
548        let head = sibling.manifest.head.clone().expect("has_repo checks it");
549        let bare = sibling.dir.join(STORE_GIT);
550        let mut ids: Vec<String> = vec![head.clone()];
551        ids.extend(sibling.manifest.tags.values().cloned());
552        let origin = format!(
553            "Machine \"{}\" on the remote \"{}\"",
554            sibling.manifest.label, remote.name
555        );
556        // A newer machine is refused before anything of it is imported.
557        let outcome = newer_manifest(&sibling.manifest, &origin)
558            .and_then(|()| store.import_objects(&bare, &ids))
559            .and_then(|()| {
560                let incoming = CommitId::from_text(&head)?;
561                store.check_incoming(&incoming, &origin)?;
562                report
563                    .tags_imported
564                    .extend(store.import_tags(&sibling.manifest.tags)?);
565                if report.tag.is_none() && !store.contains(&incoming) {
566                    report.tag = Some(store.create_auto_tag("pre-pull")?);
567                }
568                let label = format!("{}/{}", remote.name, sibling.manifest.label);
569                store.merge_incoming(&incoming, &label)
570            });
571        // A sibling that did not merge this time (incomplete, or an
572        // error) keeps the conflicts recorded for it before.
573        if outcome.is_ok() {
574            attempted.push(source.clone());
575        }
576        if let Ok(MergeOutcome::Conflicts { base, conflicts }) = &outcome {
577            pending.push(PendingMerge {
578                source,
579                incoming: head.clone(),
580                base: base.as_ref().map(ToString::to_string),
581                conflicts: conflicts.iter().map(RecordedConflict::from).collect(),
582            });
583        }
584        report.siblings.push(SiblingPull {
585            machine_id: Some(sibling.machine_id),
586            label: sibling.manifest.label,
587            outcome,
588        });
589    }
590    write_merge_state(fs, store.state_dir(), &attempted, &pending)?;
591    report.head_after = store.head()?;
592    Ok(report)
593}
594
595/// `unsupported_schema` for a `machine.json` a newer Surjection wrote.
596fn newer_manifest(manifest: &MachineManifest, origin: &str) -> Result<(), CoreError> {
597    if manifest.schema <= MANIFEST_SCHEMA {
598        return Ok(());
599    }
600    let product = crate::brand::PRODUCT_NAME;
601    Err(CoreError::new(
602        ErrorCode::UnsupportedSchema,
603        format!(
604            "{origin} was pushed by a newer {product} (schema {}; this version reads up to \
605             {MANIFEST_SCHEMA}). Update {product}.",
606            manifest.schema
607        ),
608    ))
609}
610
611/// Where a restore takes a store from (`surject restore --from`).
612#[derive(Debug, Clone, PartialEq, Eq)]
613pub enum Source {
614    /// A bare repository: its `main` (or the listed head) and tags.
615    Repo {
616        bare: PathBuf,
617        head: String,
618        tags: BTreeMap<String, String>,
619    },
620    /// An exported tree (a mirror's `latest/`).
621    Mirror { dir: PathBuf },
622    /// A zip export.
623    Zip { file: PathBuf },
624}
625
626/// A path given to `restore --from`: one source, or a folder remote whose
627/// machines the user picks from.
628#[derive(Debug, Clone, PartialEq, Eq)]
629pub enum SourceChoice {
630    One {
631        source: Source,
632        /// The machine it comes from, when known.
633        machine: Option<Box<MachineEntry>>,
634    },
635    /// More than one machine and no `--machine`.
636    Choose(Vec<MachineEntry>),
637}
638
639/// Opens `path` for a restore: a zip, a bare repository, a mirror, a
640/// machine subfolder, or a folder remote (`machine` picks by id or exact
641/// label; an ambiguous label fails and names the ids).
642pub fn open_source(
643    fs: &dyn Fs,
644    path: &Path,
645    machine: Option<&str>,
646) -> Result<SourceChoice, CoreError> {
647    let not_store = || {
648        CoreError::new(
649            ErrorCode::NotFound,
650            "no Surjection store there: expected a folder remote, a machine folder, a bare \
651             repository, a mirror or a zip",
652        )
653        .with_path(path)
654    };
655    if !fs.exists(path) {
656        return Err(
657            CoreError::new(ErrorCode::RemoteUnreachable, "the path does not exist").with_path(path),
658        );
659    }
660    if !fs.is_dir(path) {
661        return if path
662            .extension()
663            .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
664        {
665            Ok(SourceChoice::One {
666                source: Source::Zip {
667                    file: path.to_path_buf(),
668                },
669                machine: None,
670            })
671        } else {
672            Err(not_store())
673        };
674    }
675    if fs.exists(&path.join("HEAD")) && fs.is_dir(&path.join("objects")) {
676        let (head, tags) = crate::store::bare_refs(path).ok_or_else(not_store)?;
677        return Ok(SourceChoice::One {
678            source: Source::Repo {
679                bare: path.to_path_buf(),
680                head,
681                tags,
682            },
683            machine: None,
684        });
685    }
686    if fs.exists(&path.join(EXPORT_FILE)) {
687        return Ok(SourceChoice::One {
688            source: Source::Mirror {
689                dir: path.to_path_buf(),
690            },
691            machine: None,
692        });
693    }
694    if let Some(manifest) = MachineManifest::load(fs, path) {
695        let entry = MachineEntry {
696            store_id: manifest.store_id.clone(),
697            machine_id: manifest.machine_id.clone(),
698            dir: path.to_path_buf(),
699            subject: None,
700            manifest,
701        };
702        let source = machine_source(fs, &entry).ok_or_else(not_store)?;
703        return Ok(SourceChoice::One {
704            source,
705            machine: Some(Box::new(entry)),
706        });
707    }
708    // A store folder (`<root>/<store_id>`): its machines.
709    let name = file_name(path);
710    let listing = match path.parent() {
711        Some(parent) if ids::is_valid(IdKind::Store, &name) => list(fs, parent, Some(&name))?,
712        _ => list(fs, path, None)?,
713    };
714    let mut candidates = listing.machines;
715    if let Some(wanted) = machine {
716        let by_id: Vec<MachineEntry> = candidates
717            .iter()
718            .filter(|m| m.machine_id.eq_ignore_ascii_case(wanted))
719            .cloned()
720            .collect();
721        candidates = if by_id.is_empty() {
722            candidates
723                .into_iter()
724                .filter(|m| m.manifest.label == wanted)
725                .collect()
726        } else {
727            by_id
728        };
729        match candidates.len() {
730            0 => {
731                return Err(CoreError::new(
732                    ErrorCode::NotFound,
733                    format!("no machine {wanted:?} in that folder remote"),
734                ));
735            }
736            1 => {}
737            _ => {
738                let ids: Vec<&str> = candidates.iter().map(|m| m.machine_id.as_str()).collect();
739                return Err(CoreError::new(
740                    ErrorCode::InvalidValue,
741                    format!(
742                        "several machines are labeled {wanted:?}; pick one by id: {}",
743                        ids.join(", ")
744                    ),
745                ));
746            }
747        }
748    }
749    match candidates.len() {
750        0 => Err(not_store()),
751        1 => {
752            let entry = candidates.remove(0);
753            let source = machine_source(fs, &entry).ok_or_else(not_store)?;
754            Ok(SourceChoice::One {
755                source,
756                machine: Some(Box::new(entry)),
757            })
758        }
759        _ => Ok(SourceChoice::Choose(candidates)),
760    }
761}
762
763/// The source a machine subfolder offers: its repository, else its mirror,
764/// else its newest listed archive.
765fn machine_source(fs: &dyn Fs, entry: &MachineEntry) -> Option<Source> {
766    if entry.has_repo(fs) {
767        return Some(Source::Repo {
768            bare: entry.dir.join(STORE_GIT),
769            head: entry.manifest.head.clone()?,
770            tags: entry.manifest.tags.clone(),
771        });
772    }
773    if entry.manifest.mirror.is_some() && fs.is_dir(&entry.dir.join(LATEST)) {
774        return Some(Source::Mirror {
775            dir: entry.dir.join(LATEST),
776        });
777    }
778    let newest = entry
779        .manifest
780        .archives
781        .iter()
782        .filter(|name| is_archive_name(name))
783        .max()?;
784    let file = entry.dir.join(ARCHIVES).join(newest);
785    fs.exists(&file).then_some(Source::Zip { file })
786}
787
788/// The store files of an exported tree (mirror or zip), without
789/// `EXPORT.json`, and the sync tool artifacts skipped on the way (a
790/// `desktop.ini` or a conflicted copy in `latest/` is not a store file).
791/// Paths that are not plain store-relative paths (absolute, `..`, `.git`)
792/// are refused (zip-slip).
793#[derive(Debug, Clone, Default, PartialEq, Eq)]
794pub struct Export {
795    pub files: Files,
796    pub artifacts: Vec<Artifact>,
797}
798
799pub fn export_files(fs: &dyn Fs, source: &Source) -> Result<Export, CoreError> {
800    let mut export = Export::default();
801    let mut add = |name: String, bytes: Vec<u8>, origin: PathBuf| -> Result<(), CoreError> {
802        let name = name.replace('\\', "/");
803        if name == EXPORT_FILE || name.ends_with('/') {
804            return Ok(());
805        }
806        if let Some(tool) = name.split('/').find_map(artifact_tool) {
807            export.artifacts.push(Artifact { path: origin, tool });
808            return Ok(());
809        }
810        let plain = !name.is_empty()
811            && !name.starts_with('/')
812            && !name.contains(':')
813            && name
814                .split('/')
815                .all(|part| !part.is_empty() && part != "." && part != ".." && part != ".git");
816        if !plain {
817            return Err(CoreError::new(
818                ErrorCode::InvalidPath,
819                format!("the export holds a path outside the store: {name:?}"),
820            ));
821        }
822        export.files.insert(name, bytes);
823        Ok(())
824    };
825    match source {
826        Source::Mirror { dir } => {
827            let mut stack = vec![dir.clone()];
828            while let Some(current) = stack.pop() {
829                for path in read_dir(fs, &current)? {
830                    if fs.is_dir(&path) {
831                        stack.push(path);
832                        continue;
833                    }
834                    let relative = path
835                        .strip_prefix(dir)
836                        .expect("below the mirror")
837                        .components()
838                        .map(|part| part.as_os_str().to_string_lossy().into_owned())
839                        .collect::<Vec<_>>()
840                        .join("/");
841                    let bytes = fs
842                        .read(&path)
843                        .map_err(|err| io("cannot read file", &path, &err))?;
844                    add(relative, bytes, path)?;
845                }
846            }
847        }
848        Source::Zip { file } => {
849            let bytes = fs
850                .read(file)
851                .map_err(|err| io("cannot read file", file, &err))?;
852            let zip_error = |err: zip::result::ZipError| {
853                CoreError::new(ErrorCode::ParseError, format!("not a readable zip: {err}"))
854                    .with_path(file)
855            };
856            let mut archive =
857                zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(zip_error)?;
858            for index in 0..archive.len() {
859                let mut entry = archive.by_index(index).map_err(zip_error)?;
860                if entry.is_dir() {
861                    continue;
862                }
863                let name = entry.name().map_err(zip_error)?.into_owned();
864                let mut content = Vec::new();
865                entry
866                    .read_to_end(&mut content)
867                    .map_err(|err| io("cannot read the zip", file, &err))?;
868                let origin = file.join(&name);
869                add(name, content, origin)?;
870            }
871        }
872        Source::Repo { .. } => {
873            return Err(CoreError::new(
874                ErrorCode::InvalidValue,
875                "a repository is restored with its history, not as files",
876            ));
877        }
878    }
879    Ok(export)
880}