forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.2 MiBc8ea10cTahinli27 days ago292 commits

setup.rs127 lines, 4.3 KiBHistoryRawDownload
1//! Managed gitconfig and hook shims, written into the data dir at boot.
2
3use std::fs::{self, File};
4use std::io::Write;
5use std::os::unix::fs::PermissionsExt;
6use std::path::Path;
7
8use crate::error::{Error, Result};
9
10/// Quotes a value for a git config file. Control characters are rejected.
11fn quote_config_value(v: &str) -> Result<String> {
12 if v.chars().any(char::is_control) {
13 return Err(Error::InvalidInput(format!(
14 "config value contains control characters: {v:?}"
15 )));
16 }
17 Ok(format!(
18 "\"{}\"",
19 v.replace('\\', "\\\\").replace('"', "\\\"")
20 ))
21}
22
23/// Writes `name` in `dir` atomically: temp file, fsync, rename, then fsync the directory.
24fn write_atomic(dir: &Path, name: &str, contents: &[u8], mode: u32) -> Result<()> {
25 let tmp = dir.join(format!(".{name}.tmp"));
26 {
27 let mut f = fs::OpenOptions::new()
28 .write(true)
29 .create(true)
30 .truncate(true)
31 .open(&tmp)?;
32 f.write_all(contents)?;
33 f.set_permissions(fs::Permissions::from_mode(mode))?;
34 f.sync_all()?;
35 }
36 fs::rename(&tmp, dir.join(name))?;
37 File::open(dir)?.sync_all()?;
38 Ok(())
39}
40
41/// Writes `data_dir/gitconfig`: core.hooksPath, fsck, fsync, uploadpack and receive settings.
42pub fn write_managed_gitconfig(data_dir: &Path) -> Result<()> {
43 if !data_dir.is_absolute() {
44 return Err(Error::InvalidInput(format!(
45 "data dir must be absolute: {}",
46 data_dir.display()
47 )));
48 }
49 let hooks = data_dir.join("hooks");
50 let hooks = hooks
51 .to_str()
52 .ok_or_else(|| Error::InvalidInput("data dir is not valid UTF-8".into()))?;
53 let hooks = quote_config_value(hooks)?;
54
55 // `committed` hardens loose objects and packs; `reference` hardens ref updates.
56 // `uploadpack.allowRefInWant` stays off: with it, upload-pack writes wanted-refs before
57 // shallow-info, the client wants the reverse, and `git clone --depth` fails.
58 let body = format!(
59 "[core]\n\
60 \thooksPath = {hooks}\n\
61 \tfsync = committed,reference\n\
62 \tfsyncMethod = fsync\n\
63 \tcommitGraph = true\n\
64 [receive]\n\
65 \tfsckObjects = true\n\
66 \tadvertisePushOptions = true\n\
67 \tdenyNonFastForwards = false\n\
68 [transfer]\n\
69 \tfsckObjects = true\n\
70 \thideRefs = refs/forge-internal/\n\
71 [fetch]\n\
72 \tfsckObjects = true\n\
73 \twriteCommitGraph = true\n\
74 [uploadpack]\n\
75 \tallowFilter = true\n\
76 \thideRefs = refs/forge-internal/\n\
77 [protocol \"file\"]\n\
78 \tallow = never\n\
79 [protocol \"ext\"]\n\
80 \tallow = never\n"
81 );
82 fs::create_dir_all(data_dir)?;
83 write_atomic(data_dir, "gitconfig", body.as_bytes(), 0o644)
84}
85
86/// Writes `data_dir/hooks/{pre-receive,post-receive}` as `exec <forge_bin> hook <name>`, mode 0755.
87/// `forge_bin` must be absolute and contain no quotes or control characters.
88pub fn write_hook_shims(data_dir: &Path, forge_bin: &Path) -> Result<()> {
89 let bin = forge_bin
90 .to_str()
91 .ok_or_else(|| Error::InvalidInput("forge binary path is not valid UTF-8".into()))?;
92 if !forge_bin.is_absolute() {
93 return Err(Error::InvalidInput(format!(
94 "forge binary path must be absolute: {bin}"
95 )));
96 }
97 if bin.chars().any(|c| c == '\'' || c.is_control()) {
98 return Err(Error::InvalidInput(format!(
99 "forge binary path contains a quote or control character: {bin:?}"
100 )));
101 }
102 let hooks = data_dir.join("hooks");
103 fs::create_dir_all(&hooks)?;
104 for name in ["pre-receive", "post-receive"] {
105 let body = format!("#!/bin/sh\nexec '{bin}' hook {name}\n");
106 write_atomic(&hooks, name, body.as_bytes(), 0o755)?;
107 }
108 Ok(())
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 #[test]
116 fn managed_gitconfig_enables_commit_graph() {
117 let tmp = tempfile::tempdir().expect("tempdir");
118 write_managed_gitconfig(tmp.path()).expect("write gitconfig");
119 let body = fs::read_to_string(tmp.path().join("gitconfig")).expect("read gitconfig");
120 assert!(body.contains("\tcommitGraph = true\n"));
121 assert!(body.contains("\twriteCommitGraph = true\n"));
122 assert!(
123 !body.contains("gc.auto"),
124 "gc.auto must stay at its default"
125 );
126 }
127}