1use crate::{Runner, output::path_line, process::args};
3use std::{
4 collections::HashSet,
5 ffi::OsString,
6 fs, io,
7 path::{Path, PathBuf},
8};
9use workyard_core::{
10 Control, Problem, ProblemCode,
11 projects::{Catalog, ProjectLocation},
12};
13
14pub struct Coverage {
16 pub root: PathBuf,
18 pub missing: bool,
20 pub issues: Vec<Problem>,
22}
23
24pub struct Discovery {
26 pub catalog: Catalog,
28 pub coverage: Vec<Coverage>,
30}
31
32impl Discovery {
33 pub async fn scan(
35 roots: &[PathBuf],
36 state: &Path,
37 tasks: &Path,
38 runner: &Runner,
39 control: &Control,
40 ) -> Result<Self, Problem> {
41 let mut locations = Vec::new();
42 let mut coverage = Vec::new();
43 let scanner = Scanner {
44 state,
45 tasks,
46 runner,
47 control,
48 };
49 for root in roots {
50 coverage.push(scanner.root(root, &mut locations).await?);
51 }
52 Ok(Self {
53 catalog: Catalog::new(locations),
54 coverage,
55 })
56 }
57}
58
59struct Scanner<'a> {
60 state: &'a Path,
61 tasks: &'a Path,
62 runner: &'a Runner,
63 control: &'a Control,
64}
65
66impl Scanner<'_> {
67 async fn root(
68 &self,
69 root: &Path,
70 locations: &mut Vec<ProjectLocation>,
71 ) -> Result<Coverage, Problem> {
72 let mut report = Coverage {
73 root: root.to_owned(),
74 missing: false,
75 issues: Vec::new(),
76 };
77 let mut pending = vec![root.to_owned()];
78 let mut visited = HashSet::new();
79 while let Some(path) = pending.pop() {
80 self.control.check()?;
81 let directory = match path.canonicalize() {
82 Ok(directory) => directory,
83 Err(error) if path == root && error.kind() == io::ErrorKind::NotFound => {
84 report.missing = true;
85 continue;
86 }
87 Err(error) => {
88 report.issues.push(Problem::io(
89 format!("Open project directory {path:?}"),
90 error,
91 ));
92 continue;
93 }
94 };
95 if directory.starts_with(self.state)
96 || directory.starts_with(self.tasks)
97 || !visited.insert(directory)
98 {
99 continue;
100 }
101
102 match inspect_directory(&path, self.runner, self.control).await {
103 Ok(Some(project)) => locations.push(project),
104 Ok(None) => collect_children(&path, &mut pending, &mut report.issues),
105 Err(problem) if problem.code == ProblemCode::Cancelled => return Err(problem),
106 Err(problem) => report.issues.push(problem),
107 }
108 }
109 Ok(report)
110 }
111}
112
113fn collect_children(directory: &Path, pending: &mut Vec<PathBuf>, issues: &mut Vec<Problem>) {
114 let read_error = |error| Problem::io(format!("Read project directory {directory:?}"), error);
115 let entries = match fs::read_dir(directory) {
116 Ok(entries) => entries,
117 Err(error) => {
118 issues.push(read_error(error));
119 return;
120 }
121 };
122 for entry in entries {
123 let child = entry.and_then(|entry| {
124 let name = entry.file_name();
125 if name == ".workyard" || name == ".git" || !entry.file_type()?.is_dir() {
127 return Ok(None);
128 }
129 Ok(Some(entry.path()))
130 });
131 match child {
132 Ok(Some(path)) => pending.push(path),
133 Ok(None) => {}
134 Err(error) => issues.push(read_error(error)),
135 }
136 }
137}
138
139pub async fn enclosing_project(
141 path: &Path,
142 runner: &Runner,
143 control: &Control,
144) -> Result<Option<ProjectLocation>, Problem> {
145 if !path.is_dir() {
146 return Ok(None);
147 }
148 if let Some(project) = inspect_directory(path, runner, control).await? {
149 return Ok(Some(project));
150 }
151
152 let inside = runner
155 .checked(
156 path,
157 &args(&["rev-parse", "--is-inside-work-tree"]),
158 control,
159 )
160 .await?;
161 let root_option = if inside.trim_ascii() == b"true" {
162 "--show-toplevel"
163 } else {
164 "--git-common-dir"
165 };
166 let output = runner
167 .checked(
168 path,
169 &args(&["rev-parse", "--path-format=absolute", root_option]),
170 control,
171 )
172 .await?;
173 let root = path_line(&output)
174 .map_err(|_| Problem::new(ProblemCode::InvalidGitOutput, "Invalid Git project root."))?;
175 inspect_directory(&root, runner, control).await
176}
177
178async fn inspect_directory(
179 path: &Path,
180 runner: &Runner,
181 control: &Control,
182) -> Result<Option<ProjectLocation>, Problem> {
183 let marker = path.join(".git");
184 let git_dir = match fs::symlink_metadata(&marker) {
185 Ok(_) => marker,
186 Err(error) if error.kind() != io::ErrorKind::NotFound => {
187 return Err(Problem::io(format!("Inspect Git marker {marker:?}"), error));
188 }
189 Err(_) if path.join("HEAD").is_file() && path.join("objects").is_dir() => path.to_owned(),
190 Err(_) => return Ok(None),
191 };
192
193 let args = [
195 OsString::from("--git-dir"),
196 dunce::simplified(&git_dir).into(),
197 "rev-parse".into(),
198 "--path-format=absolute".into(),
199 "--git-common-dir".into(),
200 ];
201 let output = runner.checked(path, &args, control).await?;
202 let common = path_line(&output)
203 .map_err(|_| Problem::new(ProblemCode::InvalidGitOutput, "Invalid Git project path."))?;
204 let identity = workyard_system::directory_identity(&common)?;
205 Ok(Some(ProjectLocation {
206 identity,
207 path: path.to_owned(),
208 }))
209}