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
use std::process::exit;
use clap::{Args, Subcommand, ValueEnum};
use crate::common::{args::PathArgs, workspace::auto_detect_workspace_root};
#[derive(Args, Debug)]
pub(crate) struct WorkspaceArgs {
#[command(subcommand)]
command: WorkspaceCommand,
}
#[derive(Debug, Subcommand)]
enum WorkspaceCommand {
/// Get the workspace root folder based on VCS or other litmus files (e.g. `package.json`, `Cargo.toml`)
/// If the folder is part of multiple repositories, at most one will be returned (consistent with the `repo vcs kind` subcommand).
///
/// Also consider `repo vcs root` if you are only looking for VCS roots.
Root(WorkspaceRootArgs),
}
#[derive(Args, Debug)]
pub(crate) struct WorkspaceRootArgs {
#[clap(long)]
fallback: Option<RootFallback>,
#[command(flatten)]
path_args: PathArgs,
}
#[derive(Debug, Clone, ValueEnum, PartialEq, Eq)]
enum RootFallback {
/// Use either the path itself (if it's an existing directory) or its parent (if it's not).
/// Note: due to Rust parsing quirks, non-existent paths are always treated as non-directories (even if they have a trailing slash), i.e. their parent will be returned.
// TODO: always treat paths with a trailing slash as dirs.
#[clap(name = "closest-dir")]
ClosestDir,
}
pub(crate) fn workspace_command(workspace_args: WorkspaceArgs) {
match workspace_args.command {
WorkspaceCommand::Root(workspace_root_args) => {
let path = &workspace_root_args.path_args.path();
let root_path = if let Some(path) = auto_detect_workspace_root(path) {
path
} else {
match workspace_root_args.fallback {
Some(RootFallback::ClosestDir) => {
// TODO: wire things up so that we can tell if the argument had a trailing slash. Probably requires asking `clap` to keep parse into a `String` an `PathBuf` at the same time.
if path.is_dir() {
path.to_string_lossy().to_string()
} else if let Some(parent_path) = path.parent() {
parent_path.to_string_lossy().to_string()
} else {
eprintln!("Could not get parent path");
exit(1);
}
}
None => {
eprintln!("No workspace found. Consider passing: `--fallback closest-dir`");
exit(1)
}
}
};
print!("{}", root_path)
}
};
}