mekle 0.2.0

Fast project discovery tool for developers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Deciding which directory a marker file really belongs to.
//!
//! A manifest deep inside a monorepo names a member, not a project, so each
//! marker is walked upwards until it reaches the repository or workspace that
//! owns it.

use super::is_covered;
use crate::{
    config::Config,
    error::Result,
    fs::{self, content::ContentTest},
    git::{GIT_DIR, marks_repository},
};
use std::{
    collections::{BTreeSet, HashMap, HashSet},
    path::{Path, PathBuf},
    sync::RwLock,
};

/// A `Cargo.toml` declares a workspace by opening a `[workspace]` table.
const CARGO_WORKSPACE: ContentTest = ContentTest::LineStartsWith("[workspace]");

/// Manifests that make the directory holding them a workspace root, and what
/// each one has to contain to count.
const WORKSPACE_RULES: [(&str, ContentTest); 8] = [
    (
        "package.json",
        ContentTest::ContainsAny(&[r#""workspaces""#, r#""workspace""#]),
    ),
    (
        "deno.json",
        ContentTest::ContainsAny(&[r#""workspaces""#, r#""imports""#]),
    ),
    (
        "deno.jsonc",
        ContentTest::ContainsAny(&[r#""workspaces""#, r#""imports""#]),
    ),
    ("bunfig.toml", ContentTest::ContainsAny(&["workspaces"])),
    ("Cargo.toml", CARGO_WORKSPACE),
    ("rush.json", ContentTest::NonEmpty),
    ("nx.json", ContentTest::NonEmpty),
    ("turbo.json", ContentTest::NonEmpty),
];

const POISONED: &str = "resolver cache lock poisoned";

#[derive(Debug)]
pub struct RootResolver {
    marker_files: Box<[String]>,
    workspace_files: Box<[String]>,
    workspace_cache: RwLock<HashMap<PathBuf, bool>>,
    cargo_workspace_cache: RwLock<HashMap<PathBuf, bool>>,
    root_cache: RwLock<HashMap<(PathBuf, MarkerType), PathBuf>>,
}

impl RootResolver {
    #[must_use]
    pub fn new(workspace_files: Vec<String>) -> Self {
        Self {
            marker_files: Box::default(),
            workspace_files: workspace_files.into(),
            workspace_cache: RwLock::default(),
            cargo_workspace_cache: RwLock::default(),
            root_cache: RwLock::default(),
        }
    }

    #[must_use]
    pub fn from_config(config: &Config) -> Self {
        Self {
            marker_files: config.marker_files.clone().into(),
            workspace_files: config.workspace_files.clone().into(),
            workspace_cache: RwLock::default(),
            cargo_workspace_cache: RwLock::default(),
            root_cache: RwLock::default(),
        }
    }

    /// Resolves an arbitrary directory to the most specific project root that
    /// discovery would report for one of its ancestors.
    ///
    /// # Errors
    ///
    /// Returns an error if a marker or workspace manifest cannot be inspected.
    ///
    /// # Panics
    ///
    /// Panics if a cache lock is poisoned.
    pub fn resolve_directory(&self, dir: &Path) -> Result<PathBuf> {
        let absolute_dir = absolute_path(dir)?;
        let mut projects = HashSet::new();
        let mut candidates = BTreeSet::new();

        for ancestor in absolute_dir.ancestors() {
            if is_git_repo(ancestor)? {
                projects.insert(ancestor.to_path_buf());
            }

            for marker_name in &self.marker_files {
                if fs::exists(&ancestor.join(marker_name))? {
                    candidates.insert(self.resolve(ancestor, marker_name)?);
                }
            }
        }

        for candidate in candidates {
            if !is_covered(&candidate, &projects) {
                projects.insert(candidate);
            }
        }

        let root = projects
            .into_iter()
            .filter(|candidate| absolute_dir.starts_with(candidate))
            .max_by_key(|candidate| candidate.components().count())
            .unwrap_or(absolute_dir);

        display_resolved_root(dir, root)
    }

    /// Resolves a marker's project root.
    ///
    /// # Errors
    ///
    /// Returns an error if a workspace manifest cannot be read.
    ///
    /// # Panics
    ///
    /// Panics if a cache lock is poisoned.
    pub fn resolve(&self, dir: &Path, marker_name: &str) -> Result<PathBuf> {
        let absolute_dir = absolute_path(dir)?;
        let cache_key = (absolute_dir, MarkerType::from(marker_name));

        if let Some(root) = self.root_cache.read().expect(POISONED).get(&cache_key) {
            return display_resolved_root(dir, root.clone());
        }

        let root = match &cache_key.1 {
            MarkerType::PackageJson | MarkerType::DenoJson => {
                ascend_to_root(&cache_key.0, |parent| self.is_workspace_root(parent))?
            }
            MarkerType::CargoToml => {
                ascend_to_root(&cache_key.0, |parent| self.is_cargo_workspace_root(parent))?
            }
            MarkerType::BuildFile(name) => ascend_to_highest_build_file(&cache_key.0, name)?,
            MarkerType::OtherConfig => ascend_to_root(&cache_key.0, |_| Ok(false))?,
        };

        self.root_cache
            .write()
            .expect(POISONED)
            .insert(cache_key, root.clone());

        display_resolved_root(dir, root)
    }

    fn is_workspace_root(&self, dir: &Path) -> Result<bool> {
        if let Some(&cached) = self.workspace_cache.read().expect(POISONED).get(dir) {
            return Ok(cached);
        }

        let is_root = self.declares_a_workspace(dir)?;

        self.workspace_cache
            .write()
            .expect(POISONED)
            .insert(dir.to_path_buf(), is_root);

        Ok(is_root)
    }

    fn is_cargo_workspace_root(&self, dir: &Path) -> Result<bool> {
        if let Some(&cached) = self.cargo_workspace_cache.read().expect(POISONED).get(dir) {
            return Ok(cached);
        }

        let is_root = CARGO_WORKSPACE.matches_file(&dir.join("Cargo.toml"))?;

        self.cargo_workspace_cache
            .write()
            .expect(POISONED)
            .insert(dir.to_path_buf(), is_root);

        Ok(is_root)
    }

    /// Reports whether any known manifest in `dir` declares a workspace, either
    /// by its contents or by merely being present.
    fn declares_a_workspace(&self, dir: &Path) -> Result<bool> {
        for (file, test) in WORKSPACE_RULES {
            if test.matches_file(&dir.join(file))? {
                return Ok(true);
            }
        }

        for file in &self.workspace_files {
            if fs::exists(&dir.join(file))? {
                return Ok(true);
            }
        }

        Ok(false)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum MarkerType {
    PackageJson,
    CargoToml,
    DenoJson,
    BuildFile(String),
    OtherConfig,
}

impl From<&str> for MarkerType {
    fn from(file_name: &str) -> Self {
        match file_name {
            "package.json" => Self::PackageJson,
            "Cargo.toml" => Self::CargoToml,
            "deno.json" | "deno.jsonc" => Self::DenoJson,
            "Makefile" | "CMakeLists.txt" | "justfile" | "Justfile" => {
                Self::BuildFile(file_name.to_owned())
            }
            _ => Self::OtherConfig,
        }
    }
}

fn ancestors_above(dir: &Path) -> impl Iterator<Item = &Path> {
    dir.ancestors()
        .skip(1)
        .take_while(|ancestor| !ancestor.as_os_str().is_empty())
}

fn absolute_path(path: &Path) -> Result<PathBuf> {
    std::path::absolute(path).map_err(|source| crate::error::Error::ResolvePath {
        path: path.to_path_buf(),
        source,
    })
}

fn display_resolved_root(input: &Path, root: PathBuf) -> Result<PathBuf> {
    if input.is_absolute() {
        Ok(root)
    } else {
        relative_to_current_dir(&root)
    }
}

/// Keeps relative inputs relative in discovery output, including roots above
/// the current directory.
fn relative_to_current_dir(path: &Path) -> Result<PathBuf> {
    let current_dir =
        std::env::current_dir().map_err(|source| crate::error::Error::ResolvePath {
            path: path.to_path_buf(),
            source,
        })?;
    let current_components = current_dir.components().collect::<Vec<_>>();
    let path_components = path.components().collect::<Vec<_>>();
    let shared = current_components
        .iter()
        .zip(&path_components)
        .take_while(|(left, right)| left == right)
        .count();

    let mut relative = PathBuf::new();
    for component in &current_components[shared..] {
        if matches!(component, std::path::Component::Normal(_)) {
            relative.push("..");
        }
    }
    for component in &path_components[shared..] {
        relative.push(component.as_os_str());
    }

    if relative.as_os_str().is_empty() {
        relative.push(".");
    }

    Ok(relative)
}

/// Reports whether `dir` is the root of a repository, worktree, or submodule.
fn is_git_repo(dir: &Path) -> Result<bool> {
    marks_repository(&dir.join(GIT_DIR))
}

fn ascend_to_root<F>(dir: &Path, is_root: F) -> Result<PathBuf>
where
    F: Fn(&Path) -> Result<bool>,
{
    if is_git_repo(dir)? {
        return Ok(dir.to_path_buf());
    }

    for parent in ancestors_above(dir) {
        if is_git_repo(parent)? || is_root(parent)? {
            return Ok(parent.to_path_buf());
        }
    }

    Ok(dir.to_path_buf())
}

fn ascend_to_highest_build_file(dir: &Path, build_file: &str) -> Result<PathBuf> {
    if is_git_repo(dir)? {
        return Ok(dir.to_path_buf());
    }

    let mut highest = dir;

    for parent in ancestors_above(dir) {
        if fs::exists(&parent.join(build_file))? {
            highest = parent;
        }

        if is_git_repo(parent)? {
            return Ok(parent.to_path_buf());
        }
    }

    Ok(highest.to_path_buf())
}

#[cfg(test)]
mod tests {
    use super::*;
    use claims::{assert_none, assert_ok_eq, assert_some_eq};
    use rstest::rstest;
    use std::fs::{create_dir_all, write};
    use tempfile::TempDir;

    fn repo_with_nested_dirs(root: &Path) -> PathBuf {
        create_dir_all(root.join(".git")).expect("create .git");
        let leaf = root.join("a/b");
        create_dir_all(&leaf).expect("create nested dirs");
        leaf
    }

    fn holds(file: &'static str) -> impl Fn(&Path) -> Result<bool> {
        move |dir: &Path| fs::exists(&dir.join(file))
    }

    #[rstest]
    #[case("package.json", MarkerType::PackageJson)]
    #[case("Cargo.toml", MarkerType::CargoToml)]
    #[case("deno.json", MarkerType::DenoJson)]
    #[case("deno.jsonc", MarkerType::DenoJson)]
    #[case("justfile", MarkerType::BuildFile("justfile".into()))]
    #[case("CMakeLists.txt", MarkerType::BuildFile("CMakeLists.txt".into()))]
    #[case("go.mod", MarkerType::OtherConfig)]
    #[case("never-heard-of-it", MarkerType::OtherConfig)]
    fn classifies_markers(#[case] file_name: &str, #[case] expected: MarkerType) {
        assert_eq!(MarkerType::from(file_name), expected);
    }

    #[test]
    fn ancestors_skip_the_directory_itself() {
        let mut ancestors = ancestors_above(Path::new("/one/two/three"));

        assert_some_eq!(ancestors.next(), Path::new("/one/two"));
        assert_some_eq!(ancestors.next(), Path::new("/one"));
        assert_some_eq!(ancestors.next(), Path::new("/"));
        assert_none!(ancestors.next());
    }

    #[test]
    fn relative_ancestors_stop_before_the_empty_path() {
        assert_none!(ancestors_above(Path::new("relative")).next());
    }

    #[test]
    fn ascent_stops_at_the_enclosing_repository() {
        let temp = TempDir::new().expect("create temp dir");
        let leaf = repo_with_nested_dirs(temp.path());

        assert_ok_eq!(
            ascend_to_root(&leaf, holds("never-exists")),
            temp.path().to_path_buf()
        );
    }

    #[test]
    fn a_nearer_workspace_root_wins() {
        let temp = TempDir::new().expect("create temp dir");
        let leaf = repo_with_nested_dirs(temp.path());
        write(temp.path().join("a/pnpm-workspace.yaml"), "").expect("write workspace file");

        assert_ok_eq!(
            ascend_to_root(&leaf, holds("pnpm-workspace.yaml")),
            temp.path().join("a")
        );
    }

    #[test]
    fn directory_resolution_uses_discovery_coverage_rules() {
        let temp = TempDir::new().expect("create temp dir");
        let service = temp.path().join("service");
        let tool = service.join("tool");
        let plugin = tool.join("plugin");
        let nested = plugin.join("src");
        for project in [&service, &tool, &plugin] {
            create_dir_all(project).expect("create project dir");
            write(project.join("go.mod"), "module example\n").expect("write marker");
        }
        create_dir_all(&nested).expect("create nested dir");
        let mut config = Config::defaults().expect("load default config");
        config.marker_files = vec!["go.mod".to_owned()];
        let resolver = RootResolver::from_config(&config);

        assert_ok_eq!(resolver.resolve_directory(&nested), tool);
    }

    #[test]
    fn a_worktree_outranks_the_repository_and_workspace_around_it() {
        let temp = TempDir::new().expect("create temp dir");
        create_dir_all(temp.path().join(GIT_DIR)).expect("create .git");
        write(
            temp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"feature/crates/*\"]\n",
        )
        .expect("write workspace manifest");

        let worktree = temp.path().join("feature");
        let admin = temp.path().join(".git/worktrees/feature");
        create_dir_all(&admin).expect("create worktree admin dir");
        let member = worktree.join("crates/one");
        create_dir_all(&member).expect("create member dir");
        write(
            worktree.join(GIT_DIR),
            format!("gitdir: {}\n", admin.display()),
        )
        .expect("write worktree .git file");
        write(member.join("Cargo.toml"), "[package]\nname = \"one\"\n")
            .expect("write member manifest");

        let resolver = RootResolver::new(Vec::new());

        assert_ok_eq!(resolver.resolve(&member, "Cargo.toml"), worktree);
    }

    #[test]
    fn ascent_falls_back_to_the_starting_directory() {
        let dir = Path::new("no-ancestors");

        assert_ok_eq!(
            ascend_to_root(dir, holds("never-exists")),
            dir.to_path_buf()
        );
    }

    #[test]
    fn build_file_ascent_stops_at_the_repository() {
        let temp = TempDir::new().expect("create temp dir");
        let leaf = repo_with_nested_dirs(temp.path());
        write(leaf.join("Makefile"), "").expect("write leaf Makefile");
        write(temp.path().join("a/Makefile"), "").expect("write parent Makefile");

        assert_ok_eq!(
            ascend_to_highest_build_file(&leaf, "Makefile"),
            temp.path().to_path_buf()
        );
    }

    #[test]
    fn build_file_ascent_without_a_repository_keeps_the_start() {
        let dir = Path::new("no-ancestors");
        assert_ok_eq!(
            ascend_to_highest_build_file(dir, "Makefile"),
            dir.to_path_buf()
        );
    }
}