Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 1.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Writing a changeset's files into a plain directory: no workspace, no
5//! state, no `.braid` file and no `.git` guard.
6
7use std::fs;
8use std::io;
9use std::path::Path;
10
11use braid_engine::{EMPTY_TREE, read_changeset};
12use braid_format::ObjectId;
13use braid_store::Store;
14
15use crate::checkout::{self, Mode};
16use crate::error::Error;
17use crate::fsprobe::FileSystem;
18use crate::safe::Root;
19
20/// Writes the files of `changeset` into `dir`, which must be empty or not
21/// exist yet (its parent must), and returns how many it wrote.
22///
23/// The checkout is a workspace's, with the same safety: every write goes
24/// through directory handles that never follow a symlink, regular files get
25/// mode 0644 or 0755 only, gitlinks are empty directories, and names this
26/// platform cannot hold, or that would collide on its file system, are
27/// refused before anything is written. Nothing else goes into `dir`: it is
28/// not a workspace, braid keeps no state for it, and git run inside it finds
29/// whatever repository is around it, as anywhere else.
30pub fn materialize(store: &Store, changeset: ObjectId, dir: &Path) -> Result<usize, Error> {
31 match fs::read_dir(dir) {
32 Ok(mut entries) => {
33 if entries.next().is_some() {
34 return Err(Error::DirectoryNotEmpty(dir.to_path_buf()));
35 }
36 }
37 Err(err) if err.kind() == io::ErrorKind::NotFound => {
38 fs::create_dir(dir).map_err(Error::io("create", dir))?;
39 }
40 Err(err) => return Err(Error::io("read", dir)(err)),
41 }
42 let to = read_changeset(store, changeset)?.root;
43 let root = Root::open(dir)?;
44 let fs = FileSystem::probe(root.dir());
45 let plan = checkout::plan(store, &root, fs, EMPTY_TREE, to, Mode::Checked)?;
46 checkout::apply(store, &root, &plan)
47}