Skip to main content

git_policy_cli/
shadow_create.rs

1//! What:
2//!  Creates the shadow repository of one published transaction:
3//!       an empty bare repository,
4//!       its config and alternates,
5//!       the linked shared entries,
6//!       the conclusion state,
7//!       and the ref snapshot.
8//! Why:
9//!  The shadow is a separate repository rather than a registered worktree,
10//!  so `git worktree list` never shows it and preparation creates no ref in the real repository.
11//!  Its object store receives the objects native `git commit` writes,
12//!  and its alternates name the real object directory,
13//!  so a real `git prune` cannot delete a pending commit
14//!  (`src/shadow-repository/shadow-repository.ts`).
15//!
16//! In TS you'd write (pseudocode):
17//! ```ts
18//! await createShadowRepository({ gitPath, cwd, capture, transactionId, transactionDirectory });
19//! ```
20
21/// Shadow path, redirect variables and the shadow request.
22use super::shadow_git::{REPOSITORY_REDIRECT_VARIABLES, shadow_repository_path};
23/// Invocation capture.
24use super::capture_invocation::InvocationCapture;
25/// Format copy and config text.
26use super::shadow_config::{format_shadow_config, read_repository_format};
27/// Entry links.
28use super::shadow_links::link_shadow_entries;
29/// Conclusion copy and ref snapshot.
30use super::conclusion_copy::copy_conclusion_state;
31use super::shadow_refs::write_shadow_refs;
32/// Private directory creation and file writes.
33use super::private_storage::create_private_directory;
34/// Process context and one required Git start.
35use super::transaction_git::{GitContext, GitFailure, GitRequest, run_git_checked};
36/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
37use std::path::{Path, PathBuf};
38/// Strings for the redirect variable list.
39use std::ffi::OsString;
40
41/// What:
42///  Overwrites a file the shadow's `git init` already created, with private mode.
43/// Why:
44///   The incumbent's `writeFile` replaces the template `config` and `alternates`,
45///  while the exclusive writer used for new files would refuse them.
46///
47/// In TS you'd write (pseudocode):
48/// ```ts
49/// await writeFile(path, bytes, { mode: 0o600 });
50/// ```
51fn overwrite_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
52    std::fs::write(path, bytes)?;
53    return set_private_file(path);
54}
55
56/// What:
57///  Gives a file the private file mode on Unix.
58/// Why:
59///   The shadow config names the real hooks directory and worktree; it stays private to the account.
60///
61/// In TS you'd write (pseudocode):
62/// ```ts
63/// await chmod(path, 0o600);
64/// ```
65#[cfg(unix)]
66fn set_private_file(path: &Path) -> std::io::Result<()> {
67    use std::os::unix::fs::PermissionsExt;
68    return std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
69}
70
71/// Windows has no mode bits for this file; the incumbent's ACL work is not ported.
72#[cfg(windows)]
73fn set_private_file(_path: &Path) -> std::io::Result<()> {
74    return Ok(());
75}
76
77/// What:
78///  Creates the shadow's parent directories as private directories.
79/// Why:
80///   The incumbent creates `cli-git/shadow` with mode 0700.
81///
82/// In TS you'd write (pseudocode):
83/// ```ts
84/// await mkdir(dirname(shadowPath), { recursive: true, mode: 0o700 });
85/// ```
86fn create_parent(shadow: &Path) -> std::io::Result<()> {
87    let parent: &Path = shadow.parent().unwrap_or(shadow);
88    if let Some(grandparent) = parent.parent() {
89        ensure_private_directory(grandparent)?;
90    }
91    return ensure_private_directory(parent);
92}
93
94/// What:
95///  Create a private directory unless another process made it first.
96/// Why:
97///   Concurrent commits of one repository race to create the shared `cli-git/shadow` parents; whoever loses has
98///   nothing left to do. A path that exists as anything but a directory is still a failure.
99///
100/// In TS you'd write (pseudocode):
101/// ```ts
102/// await mkdir(directory, { mode: 0o700 }).catch((error) => { if (error.code !== 'EEXIST') throw error; });
103/// ```
104pub fn ensure_private_directory(directory: &Path) -> std::io::Result<()> {
105    match create_private_directory(directory) {
106        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && directory.is_dir() => return Ok(()),
107        other => return other,
108    }
109}
110
111/// What:
112///  Creates the shadow repository of one published transaction.
113/// Why:
114///   Every step runs before any native Git command reads the shadow,
115///  so the first read already sees the real config, objects, links and refs.
116///
117/// In TS you'd write (pseudocode):
118/// ```ts
119/// await createShadowRepository({ gitPath, cwd, capture, transactionId, transactionDirectory });
120/// ```
121pub fn create_shadow_repository(
122    context: &GitContext,
123    cwd: &Path,
124    capture: &InvocationCapture,
125    transaction_id: &str,
126    transaction_directory: &Path,
127) -> Result<PathBuf, GitFailure> {
128    let layout = &capture.layout;
129    let shadow: PathBuf = shadow_repository_path(layout.common_dir.as_path(), transaction_id);
130    create_parent(shadow.as_path())
131        .map_err(|error| { return GitFailure(format!("creating {} failed: {error}", shadow.display())); })?;
132    let format_argument: String = format!("--object-format={}", layout.object_format);
133    let mut arguments: Vec<String> = vec![
134        String::from("init"),
135        String::from("--bare"),
136        String::from("--quiet"),
137        String::from("--template="),
138        format_argument,
139    ];
140    if layout.ref_format == super::transaction_journal::RefFormat::Reftable {
141        arguments.push(String::from("--ref-format=reftable"));
142    }
143    arguments.push(shadow.display().to_string());
144    let mut init: GitRequest = GitRequest::new(layout.common_dir.as_path(), &arguments);
145    init.without_prefix = true;
146    init.unset = REPOSITORY_REDIRECT_VARIABLES.iter().map(|name| { return OsString::from(*name); }).collect();
147    run_git_checked(context, &init)?;
148    set_private_directory_mode(shadow.as_path())
149        .map_err(|error| { return GitFailure(format!("protecting {} failed: {error}", shadow.display())); })?;
150    let format = read_repository_format(context, layout.common_dir.as_path())?;
151    let config_text: String =
152        format_shadow_config(&format, layout.common_dir.as_path(), layout.repository_root.as_path());
153    overwrite_private(shadow.join("config").as_path(), config_text.as_bytes())
154        .map_err(|error| { return GitFailure(format!("writing the shadow config failed: {error}")); })?;
155    overwrite_private(
156        shadow.join("objects").join("info").join("alternates").as_path(),
157        format!("{}\n", layout.object_directory.display()).as_bytes(),
158    )
159    .map_err(|error| { return GitFailure(format!("writing the shadow alternates failed: {error}")); })?;
160    link_shadow_entries(shadow.as_path(), layout.common_dir.as_path(), layout.git_dir.as_path())
161        .map_err(|error| { return GitFailure(format!("linking the shadow entries failed: {error}")); })?;
162    copy_conclusion_state(
163        context,
164        cwd,
165        layout.git_dir.as_path(),
166        shadow.as_path(),
167        transaction_directory,
168        layout.ref_format,
169    )?;
170    write_shadow_refs(
171        context,
172        cwd,
173        shadow.as_path(),
174        layout.ref_format,
175        layout.target_ref.as_str(),
176        &layout.symbolic_head,
177        &capture.base,
178    )?;
179    return Ok(shadow);
180}
181
182/// What:
183///  Gives the shadow directory the private mode.
184/// Why:
185///   The shadow holds the transaction's objects and refs.
186///
187/// In TS you'd write (pseudocode):
188/// ```ts
189/// await chmod(shadowPath, 0o700);
190/// ```
191#[cfg(unix)]
192fn set_private_directory_mode(path: &Path) -> std::io::Result<()> {
193    use std::os::unix::fs::PermissionsExt;
194    return std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
195}
196
197/// Windows has no mode bits for the shadow directory.
198#[cfg(windows)]
199fn set_private_directory_mode(_path: &Path) -> std::io::Result<()> {
200    return Ok(());
201}
202
203/// Shadow creation controls stay out of the release executable.
204#[cfg(test)]
205#[path = "shadow_create_tests.rs"]
206mod tests;