Skip to main content

sokf_core/config/
root.rs

1//! This module finds the repository root and turns the `PATHS` arguments
2//! of a command into a scope.
3
4use std::{
5    collections::BTreeSet,
6    path::{Path, PathBuf},
7};
8
9use crate::{Error, RepoPath, RepoRoot, Result};
10
11/// `discover_root` returns the repository root. When the caller passes
12/// `given`, the root is that directory's canonical path, and the directory
13/// must exist. Otherwise the root is the nearest ancestor of `cwd` that holds
14/// a `.git` directory or file. The root is canonical so that a path resolved
15/// from the current directory, which the operating system reports in
16/// canonical form, lies under it even when `--repo-root` reaches the
17/// directory through a symbolic link, as the temporary directory of macOS
18/// does.
19// sokf-implements: CLI-1_AC-3
20// sokf-implements: CLI-1_AC-4
21// sokf-implements: CLI-1_AC-5
22// sokf-implements: CLI-1_AC-18
23pub fn discover_root(cwd: &Path, given: Option<&Path>) -> Result<RepoRoot> {
24    if let Some(dir) = given {
25        let abs = std::path::absolute(dir).map_err(|e| Error::io(dir, e))?;
26        if !abs.is_dir() {
27            return Err(Error::io(
28                &abs,
29                std::io::Error::new(std::io::ErrorKind::NotFound, "no such directory"),
30            ));
31        }
32        let canonical = dunce::canonicalize(&abs).map_err(|e| Error::io(&abs, e))?;
33        return Ok(RepoRoot::new(canonical));
34    }
35    let abs = std::path::absolute(cwd).map_err(|e| Error::io(cwd, e))?;
36    abs.ancestors()
37        .find(|dir| holds_git(dir))
38        .map(|dir| RepoRoot::new(dir.to_path_buf()))
39        .ok_or(Error::NoRepository)
40}
41
42/// `holds_git` returns whether a `.git` directory or file stands in `dir`,
43/// which marks the top of a git repository.
44pub fn holds_git(dir: &Path) -> bool {
45    dir.join(".git").exists()
46}
47
48/// `Scope` holds the files and directories that the `PATHS` arguments of
49/// `validate` point to (CLI-4_AC-2). When `PATHS` is empty, the scope is the
50/// whole repository.
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct Scope {
53    /// `files` holds the files that the arguments point to.
54    pub files: BTreeSet<RepoPath>,
55    /// `dirs` holds the directories that the arguments point to.
56    pub dirs: BTreeSet<RepoPath>,
57}
58
59impl Scope {
60    /// `all` returns a scope that holds the whole repository.
61    pub fn all() -> Self {
62        let mut s = Scope::default();
63        s.dirs.insert(RepoPath::root());
64        s
65    }
66
67    /// `contains` reports whether `path` is one of the scope's files or lies
68    /// under one of its directories.
69    pub fn contains(&self, path: &RepoPath) -> bool {
70        self.files.contains(path) || self.dirs.iter().any(|d| path.starts_with(d))
71    }
72
73    /// `add` adds a file to the scope. When `validate --fix` moves a file,
74    /// it uses `add` to put the file's new path in the scope.
75    pub fn add(&mut self, path: RepoPath) {
76        self.files.insert(path);
77    }
78}
79
80/// `PathArg` is a path argument, written either as a spec path or as a
81/// filesystem path (CLI-1_AC-7, CLI-1_AC-8).
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct PathArg<'a>(pub &'a str);
84
85impl PathArg<'_> {
86    /// `resolve` returns the path that the argument refers to, but only when
87    /// a file or directory exists there. It first reads an argument that
88    /// begins with `/` as a spec path, and then as an absolute filesystem
89    /// path inside the root. It resolves any other argument from `cwd`. An
90    /// argument can end with `/` only when it refers to a directory.
91    // sokf-implements: CLI-1_AC-7
92    // sokf-implements: CLI-1_AC-8
93    pub fn resolve(&self, root: &RepoRoot, cwd: &Path) -> Option<RepoPath> {
94        let arg = self.0;
95        let dir_only = arg.len() > 1 && arg.ends_with('/');
96        let found = if arg.starts_with('/') {
97            let trimmed = if dir_only {
98                arg.trim_end_matches('/')
99            } else {
100                arg
101            };
102            match RepoPath::parse(trimmed) {
103                Some(spec) if spec.to_fs(root).exists() => Some(spec),
104                _ => Self::existing(root, Path::new(arg)),
105            }
106        } else {
107            Self::existing(root, &cwd.join(arg))
108        };
109        found.filter(|p| !dir_only || p.to_fs(root).is_dir())
110    }
111
112    /// `resolve_new` returns the path of a directory that might not exist
113    /// yet, as in `init DIR`. It resolves an existing path as `resolve` does.
114    /// It reads an absent path that begins with `/` as an absolute filesystem
115    /// path when the path starts with the path of the repository root, and as
116    /// a spec path otherwise. It resolves any other argument from `cwd`. The
117    /// argument can end with `/`, because the path is always a directory.
118    // sokf-implements: CLI-2_AC-23
119    // sokf-implements: CLI-2_AC-29
120    pub fn resolve_new(&self, root: &RepoRoot, cwd: &Path) -> Option<RepoPath> {
121        if let Some(found) = self.resolve(root, cwd) {
122            return Some(found);
123        }
124        let arg = if self.0.len() > 1 {
125            self.0.trim_end_matches('/')
126        } else {
127            self.0
128        };
129        if !arg.starts_with('/') {
130            return RepoPath::from_fs(root, &cwd.join(arg));
131        }
132        let under_root = root.as_path().to_str().is_some_and(|r| {
133            arg == r
134                || arg
135                    .strip_prefix(r)
136                    .is_some_and(|rest| rest.starts_with('/'))
137        });
138        if under_root {
139            RepoPath::from_fs(root, Path::new(arg))
140        } else {
141            RepoPath::parse(arg)
142        }
143    }
144
145    fn existing(root: &RepoRoot, fs: &Path) -> Option<RepoPath> {
146        RepoPath::from_fs(root, fs).filter(|p| p.to_fs(root).exists())
147    }
148}
149
150/// `resolve_paths` turns the `PATHS` arguments into a scope. It refuses a
151/// path that doesn't exist or that lies outside the root.
152// sokf-implements: CLI-4_AC-15
153pub fn resolve_paths(root: &RepoRoot, cwd: &Path, paths: &[PathBuf]) -> Result<Scope> {
154    if paths.is_empty() {
155        return Ok(Scope::all());
156    }
157    let mut scope = Scope::default();
158    for path in paths {
159        let shown = path.display().to_string();
160        let repo_path = path
161            .to_str()
162            .and_then(|s| PathArg(s).resolve(root, cwd))
163            .ok_or(Error::Path(shown))?;
164        if repo_path.to_fs(root).is_dir() {
165            scope.dirs.insert(repo_path);
166        } else {
167            scope.files.insert(repo_path);
168        }
169    }
170    Ok(scope)
171}
172
173#[cfg(test)]
174mod tests {
175    use std::fs;
176
177    use super::*;
178
179    fn temp(name: &str) -> PathBuf {
180        let dir = crate::test_support::fresh_dir(&format!("root-{name}"));
181        fs::create_dir_all(dir.join("k/sub")).unwrap();
182        fs::write(dir.join("k/a.md"), "").unwrap();
183        dir
184    }
185
186    // sokf-tests: CLI-1_AC-4
187    #[test]
188    fn discovers_the_git_ancestor_or_takes_the_given_root() {
189        let dir = temp("discover");
190        assert!(matches!(
191            discover_root(&dir.join("k/sub"), None),
192            Err(Error::NoRepository)
193        ));
194        fs::write(dir.join(".git"), "gitdir: elsewhere").unwrap();
195        assert_eq!(
196            discover_root(&dir.join("k/sub"), None).unwrap().as_path(),
197            dir
198        );
199        assert_eq!(
200            discover_root(&dir.join("k/sub"), Some(&dir.join("k")))
201                .unwrap()
202                .as_path(),
203            dunce::canonicalize(dir.join("k")).unwrap()
204        );
205        assert!(discover_root(&dir, Some(&dir.join("nope"))).is_err());
206        fs::remove_dir_all(&dir).unwrap();
207    }
208
209    #[test]
210    fn resolves_paths_into_files_and_dirs() {
211        let dir = temp("paths");
212        let root = RepoRoot::new(dir.clone());
213        let scope = resolve_paths(&root, &dir, &["k/a.md".into(), "k/sub".into()]).unwrap();
214        assert!(scope.files.contains(&RepoPath::parse("/k/a.md").unwrap()));
215        assert!(scope.dirs.contains(&RepoPath::parse("/k/sub").unwrap()));
216        assert!(scope.contains(&RepoPath::parse("/k/sub/x.md").unwrap()));
217        assert!(!scope.contains(&RepoPath::parse("/k/b.md").unwrap()));
218        // From a subdirectory, a path resolves relative to that directory.
219        let scope = resolve_paths(&root, &dir.join("k"), &["a.md".into()]).unwrap();
220        assert!(scope.contains(&RepoPath::parse("/k/a.md").unwrap()));
221        // An absolute path also resolves.
222        let scope = resolve_paths(&root, &dir, &[dir.join("k")]).unwrap();
223        assert!(scope.dirs.contains(&RepoPath::parse("/k").unwrap()));
224        assert!(matches!(
225            resolve_paths(&root, &dir, &["k/missing.md".into()]),
226            Err(Error::Path(_))
227        ));
228        assert!(matches!(
229            resolve_paths(&root, &dir, &["../outside".into()]),
230            Err(Error::Path(_))
231        ));
232        assert_eq!(resolve_paths(&root, &dir, &[]).unwrap(), Scope::all());
233        // A spec path also resolves (CLI-1_AC-7).
234        let scope = resolve_paths(&root, &dir.join("k/sub"), &["/k/a.md".into()]).unwrap();
235        assert!(scope.files.contains(&RepoPath::parse("/k/a.md").unwrap()));
236        fs::remove_dir_all(&dir).unwrap();
237    }
238
239    // sokf-tests: CLI-1_AC-7
240    // sokf-tests: CLI-1_AC-8
241    #[test]
242    fn a_path_argument_has_two_spellings() {
243        let dir = temp("patharg");
244        let root = RepoRoot::new(dir.clone());
245        let p = |s: &str| RepoPath::parse(s).unwrap();
246        // An argument that begins with `/` is a spec path when that path exists.
247        assert_eq!(PathArg("/k/a.md").resolve(&root, &dir), Some(p("/k/a.md")));
248        assert_eq!(PathArg("/k/sub/").resolve(&root, &dir), Some(p("/k/sub")));
249        // A trailing `/` means a directory, never a file.
250        assert_eq!(PathArg("/k/a.md/").resolve(&root, &dir), None);
251        assert_eq!(PathArg("a.md/").resolve(&root, &dir.join("k")), None);
252        assert_eq!(PathArg("/").resolve(&root, &dir), Some(p("/")));
253        // When no spec path exists there, an argument that begins with `/`
254        // is an absolute filesystem path inside the root.
255        let abs = dir.join("k/a.md");
256        assert_eq!(
257            PathArg(abs.to_str().unwrap()).resolve(&root, &dir),
258            Some(p("/k/a.md"))
259        );
260        assert_eq!(
261            PathArg(dir.to_str().unwrap()).resolve(&root, &dir),
262            Some(p("/"))
263        );
264        // Any other argument resolves from the current directory.
265        assert_eq!(
266            PathArg("a.md").resolve(&root, &dir.join("k")),
267            Some(p("/k/a.md"))
268        );
269        assert_eq!(
270            PathArg("./a.md").resolve(&root, &dir.join("k")),
271            Some(p("/k/a.md"))
272        );
273        assert_eq!(
274            PathArg("sub/").resolve(&root, &dir.join("k")),
275            Some(p("/k/sub"))
276        );
277        assert_eq!(PathArg("..").resolve(&root, &dir.join("k")), Some(p("/")));
278        // An argument that points to nothing, or to a path outside the root,
279        // resolves to no path.
280        assert_eq!(PathArg("/k/missing.md").resolve(&root, &dir), None);
281        assert_eq!(PathArg("missing.md").resolve(&root, &dir), None);
282        assert_eq!(PathArg("../outside").resolve(&root, &dir), None);
283        assert_eq!(PathArg("/definitely/not/here").resolve(&root, &dir), None);
284        fs::remove_dir_all(&dir).unwrap();
285    }
286
287    // sokf-tests: CLI-2_AC-23
288    // sokf-tests: CLI-2_AC-29
289    #[test]
290    fn a_new_path_resolves_in_every_spelling() {
291        let dir = temp("new");
292        let root = RepoRoot::new(dir.clone());
293        let p = |s: &str| RepoPath::parse(s).unwrap();
294        // An existing path resolves as `resolve` does.
295        assert_eq!(PathArg("k/sub").resolve_new(&root, &dir), Some(p("/k/sub")));
296        assert_eq!(
297            PathArg("/k/a.md").resolve_new(&root, &dir),
298            Some(p("/k/a.md"))
299        );
300        // An absent spec path resolves, with or without a trailing slash.
301        assert_eq!(
302            PathArg("/docs/kb").resolve_new(&root, &dir),
303            Some(p("/docs/kb"))
304        );
305        assert_eq!(
306            PathArg("/docs/kb/").resolve_new(&root, &dir),
307            Some(p("/docs/kb"))
308        );
309        // An absent absolute path inside the repository resolves.
310        let abs = dir.join("docs/kb");
311        assert_eq!(
312            PathArg(abs.to_str().unwrap()).resolve_new(&root, &dir),
313            Some(p("/docs/kb"))
314        );
315        // An absent absolute path outside the repository reads as a spec path.
316        assert_eq!(
317            PathArg("/definitely/not/here").resolve_new(&root, &dir),
318            Some(p("/definitely/not/here"))
319        );
320        // A relative path resolves from the current directory, and one that
321        // leaves the repository resolves to no path.
322        assert_eq!(
323            PathArg("kb").resolve_new(&root, &dir.join("k")),
324            Some(p("/k/kb"))
325        );
326        assert_eq!(
327            PathArg("new/dir/").resolve_new(&root, &dir),
328            Some(p("/new/dir"))
329        );
330        assert_eq!(PathArg("../outside").resolve_new(&root, &dir), None);
331        fs::remove_dir_all(&dir).unwrap();
332    }
333
334    #[test]
335    fn scope_all_contains_everything_and_add_names_a_file() {
336        let all = Scope::all();
337        assert!(all.contains(&RepoPath::parse("/x/y.md").unwrap()));
338        let mut s = Scope::default();
339        assert!(!s.contains(&RepoPath::parse("/x.md").unwrap()));
340        s.add(RepoPath::parse("/x.md").unwrap());
341        assert!(s.contains(&RepoPath::parse("/x.md").unwrap()));
342    }
343}