what-stack 0.1.0

Detect project roots and technology stacks from container image names, project config files, and process names
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
//! Project-root detection.
//!
//! Project detection walks upward from process paths and looks for marker
//! files such as `package.json`, `Cargo.toml`, `go.mod`, `pyproject.toml`, and
//! project-file extensions such as `.csproj` and `.fsproj`.

use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

#[cfg(unix)]
use std::ffi::CStr;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;

use crate::ProjectInput;

const PROJECT_MARKERS: &[&str] = &[
    "package.json",
    "Cargo.toml",
    "go.mod",
    "go.work",
    "pyproject.toml",
    "requirements.txt",
    "setup.py",
    "Pipfile",
    "pom.xml",
    "build.gradle",
    "build.gradle.kts",
    "composer.json",
    "Gemfile",
    "mix.exs",
    "deno.json",
    "deno.jsonc",
    "bun.lockb",
    "bun.lock",
];

const PROJECT_MARKER_EXTENSIONS: &[&str] = &["csproj", "fsproj"];

/// Maximum number of directories tested during one upward project walk.
///
/// The starting directory counts as the first. This cap is a safety net for
/// unusual paths and very deep directory trees. The value is intentionally high
/// enough for common monorepos while bounding worst-case filesystem work.
pub const MAX_WALK_DEPTH: usize = 64;

/// Resolve a project root from process-like path inputs without caching.
///
/// The fallback order is:
///
/// 1. Walk upward from the working directory set by [`ProjectInput::cwd`].
/// 2. Walk upward from the parent directory of the executable set by
///    [`ProjectInput::exe`].
/// 3. Walk upward from the parent directory of each absolute path in the
///    arguments set by [`ProjectInput::cmd`].
///
/// The first marker hit wins. Relative command-line paths are ignored because
/// they are ambiguous without a reliable process working directory. `home` is
/// the same optional ceiling as in [`find_project_root`].
///
/// Use [`StackDetector::detect_project_root`](crate::StackDetector::detect_project_root)
/// for repeated lookups; it applies the same order with caching and its own
/// configured home ceiling.
///
/// # Examples
///
/// ```
/// use what_stack::{ProjectInput, resolve_project_root};
///
/// assert_eq!(resolve_project_root(ProjectInput::new(), None), None);
/// ```
#[must_use]
pub fn resolve_project_root(input: ProjectInput<'_>, home: Option<&Path>) -> Option<PathBuf> {
    project_root_candidates(input).find_map(|start| find_project_root(start, home))
}

/// Starting directories for a project walk, in fallback order.
pub fn project_root_candidates(input: ProjectInput<'_>) -> impl Iterator<Item = &Path> + '_ {
    input
        .cwd
        .into_iter()
        .chain(input.exe.and_then(Path::parent))
        .chain(absolute_cmd_parents(input.cmd))
}

/// Walk upward from `start` looking for project marker files.
///
/// `home` is an optional ceiling. When the walk reaches `home`, it stops before
/// testing that directory for markers. This avoids accidental matches from
/// marker files stored directly in a user's home directory. On Windows the
/// ceiling comparison ignores ASCII case, matching the file system.
///
/// At most [`MAX_WALK_DEPTH`] directories are tested, starting with `start`.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use what_stack::find_project_root;
///
/// assert_eq!(find_project_root(Path::new("."), Some(Path::new("."))), None);
/// ```
#[must_use]
pub fn find_project_root(start: &Path, home: Option<&Path>) -> Option<PathBuf> {
    walk_ancestors(start, home).find(|dir| has_marker(dir))
}

/// Return the display name for a project root path.
///
/// The returned label is derived only from the final path component. It does
/// not read package manifests or normalize workspace names.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use what_stack::project_name;
///
/// assert_eq!(project_name(Path::new("/workspace/api")).as_deref(), Some("api"));
/// ```
#[must_use]
pub fn project_name(root: &Path) -> Option<Cow<'_, str>> {
    root.file_name().map(OsStr::to_string_lossy)
}

pub fn walk_ancestors<'a>(
    start: &'a Path,
    home: Option<&'a Path>,
) -> impl Iterator<Item = PathBuf> + 'a {
    let mut current = Some(start.to_path_buf());
    let mut depth = 0;

    std::iter::from_fn(move || {
        let dir = current.as_ref()?.clone();

        if depth >= MAX_WALK_DEPTH {
            current = None;
            return None;
        }

        if let Some(home_dir) = home
            && paths_equal(&dir, home_dir)
        {
            current = None;
            return None;
        }

        depth += 1;

        let mut next = dir.clone();
        if next.pop() && next != dir {
            current = Some(next);
        } else {
            current = None;
        }

        Some(dir)
    })
}

fn absolute_cmd_parents(cmd: &[OsString]) -> impl Iterator<Item = &Path> + '_ {
    cmd.iter().filter_map(|arg| {
        let path = Path::new(arg.as_os_str());
        path.is_absolute().then(|| path.parent()).flatten()
    })
}

pub fn has_marker(dir: &Path) -> bool {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return false;
    };

    entries.filter_map(Result::ok).any(|entry| {
        let file_name = entry.file_name();
        let Some(name) = file_name.to_str() else {
            return false;
        };

        PROJECT_MARKERS.contains(&name)
            || Path::new(name)
                .extension()
                .and_then(OsStr::to_str)
                .is_some_and(|extension| PROJECT_MARKER_EXTENSIONS.contains(&extension))
    })
}

/// Compare two paths component by component.
///
/// Windows file systems are case-insensitive, so components are compared
/// ignoring ASCII case there. Other platforms compare exactly.
pub fn paths_equal(left: &Path, right: &Path) -> bool {
    #[cfg(windows)]
    {
        let mut left = left.components();
        let mut right = right.components();
        loop {
            match (left.next(), right.next()) {
                (None, None) => return true,
                (Some(a), Some(b)) if components_equal(a, b) => {}
                _ => return false,
            }
        }
    }
    #[cfg(not(windows))]
    {
        left == right
    }
}

/// Return whether `path` lies at or below `prefix`, comparing whole components
/// with the same case rules as [`paths_equal`].
pub fn path_starts_with(path: &Path, prefix: &Path) -> bool {
    #[cfg(windows)]
    {
        let mut path = path.components();
        prefix.components().all(|expected| {
            path.next()
                .is_some_and(|actual| components_equal(actual, expected))
        })
    }
    #[cfg(not(windows))]
    {
        path.starts_with(prefix)
    }
}

#[cfg(windows)]
fn components_equal(left: std::path::Component<'_>, right: std::path::Component<'_>) -> bool {
    left.as_os_str().eq_ignore_ascii_case(right.as_os_str())
}

/// Return the current user's home directory, when it can be determined.
///
/// On Unix, this prefers passwd-database lookup for the invoking user. During
/// `sudo` sessions it uses `SUDO_UID` to find the original user's home, falling
/// back to `SUDO_HOME` and then `HOME` when passwd lookup is unavailable. On
/// Windows, it reads `USERPROFILE`. On other targets (for example `wasm32`), it
/// returns `None`.
///
/// [`StackDetector::new`](crate::StackDetector::new) calls this once to set its
/// home ceiling. Callers of [`find_project_root`] or [`resolve_project_root`]
/// should call it once and reuse the result.
#[must_use]
pub fn home_dir() -> Option<PathBuf> {
    #[cfg(unix)]
    {
        select_home_dir(
            preferred_home_uid().and_then(home_dir_from_uid),
            sudo_home_dir(),
            std::env::var_os("HOME").map(PathBuf::from),
        )
    }
    #[cfg(windows)]
    {
        std::env::var_os("USERPROFILE").map(PathBuf::from)
    }
    #[cfg(not(any(unix, windows)))]
    {
        None
    }
}

#[cfg(unix)]
fn select_home_dir(
    passwd_home: Option<PathBuf>,
    sudo_home: Option<PathBuf>,
    env_home: Option<PathBuf>,
) -> Option<PathBuf> {
    passwd_home.or(sudo_home).or(env_home)
}

#[cfg(unix)]
fn sudo_home_dir() -> Option<PathBuf> {
    (current_effective_uid() == 0)
        .then(|| std::env::var_os("SUDO_HOME"))
        .flatten()
        .filter(|home| !home.is_empty())
        .map(PathBuf::from)
}

#[cfg(unix)]
fn preferred_home_uid() -> Option<libc::uid_t> {
    preferred_home_uid_from_env(
        std::env::var_os("SUDO_UID").as_deref(),
        current_effective_uid(),
    )
}

#[cfg(unix)]
fn preferred_home_uid_from_env(
    sudo_uid: Option<&OsStr>,
    current_euid: libc::uid_t,
) -> Option<libc::uid_t> {
    if current_euid == 0 {
        sudo_uid
            .and_then(OsStr::to_str)
            .and_then(|value| value.parse::<libc::uid_t>().ok())
            .or(Some(current_euid))
    } else {
        Some(current_euid)
    }
}

#[cfg(unix)]
fn current_effective_uid() -> libc::uid_t {
    // Safety: `geteuid` has no preconditions and only returns the caller's euid.
    unsafe { libc::geteuid() }
}

#[cfg(unix)]
fn home_dir_from_uid(uid: libc::uid_t) -> Option<PathBuf> {
    let mut buffer = vec![0_u8; passwd_buffer_len()];
    let mut passwd = std::mem::MaybeUninit::<libc::passwd>::zeroed();
    let mut result = std::ptr::null_mut();
    // Safety: all pointers reference valid stack/heap storage for this call,
    // and `buffer` remains alive until `passwd.pw_dir` has been copied.
    let status = unsafe {
        libc::getpwuid_r(
            uid,
            passwd.as_mut_ptr(),
            buffer.as_mut_ptr().cast(),
            buffer.len(),
            &raw mut result,
        )
    };

    if status != 0 || result.is_null() {
        return None;
    }

    // Safety: `getpwuid_r` succeeded and initialized `passwd`.
    let passwd = unsafe { passwd.assume_init() };
    if passwd.pw_dir.is_null() {
        return None;
    }

    // Safety: successful passwd records expose a nul-terminated directory path.
    let home = unsafe { CStr::from_ptr(passwd.pw_dir) };
    Some(Path::new(OsStr::from_bytes(home.to_bytes())).to_path_buf())
}

#[cfg(unix)]
fn passwd_buffer_len() -> usize {
    const DEFAULT_PASSWD_BUFFER_LEN: usize = 1024;

    // Safety: `sysconf` has no preconditions for this constant.
    match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
        size if size > 0 => usize::try_from(size).unwrap_or(DEFAULT_PASSWD_BUFFER_LEN),
        _ => DEFAULT_PASSWD_BUFFER_LEN,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn path_helpers_match_exact_paths_and_whole_component_prefixes() {
        let root = Path::new("/workspace/app");
        assert!(paths_equal(root, Path::new("/workspace/app")));
        assert!(!paths_equal(root, Path::new("/workspace/app/src")));
        assert!(!paths_equal(root, Path::new("/workspace")));
        assert!(path_starts_with(Path::new("/workspace/app/bin/x"), root));
        assert!(path_starts_with(root, root));
        assert!(!path_starts_with(Path::new("/workspace/application"), root));
        assert!(!path_starts_with(Path::new("/workspace"), root));
    }

    #[cfg(windows)]
    #[test]
    fn path_helpers_ignore_ascii_case_on_windows() {
        let root = Path::new(r"C:\Users\Dev\App");
        assert!(paths_equal(root, Path::new(r"c:\users\dev\app")));
        assert!(paths_equal(root, Path::new("c:/USERS/dev/app")));
        assert!(path_starts_with(
            Path::new(r"c:\USERS\dev\app\bin\x.exe"),
            root
        ));
        assert!(!path_starts_with(Path::new(r"c:\users\dev\apps"), root));
    }

    #[cfg(not(windows))]
    #[test]
    fn path_helpers_are_case_sensitive_off_windows() {
        let root = Path::new("/home/dev/App");
        assert!(!paths_equal(root, Path::new("/home/dev/app")));
        assert!(!path_starts_with(Path::new("/home/dev/app/bin"), root));
    }

    #[cfg(unix)]
    #[test]
    fn preferred_home_uid_from_env_prefers_sudo_uid_for_root_sessions() {
        assert_eq!(
            preferred_home_uid_from_env(Some(OsStr::new("1000")), 0),
            Some(1000),
            "sudo sessions should prefer the invoking user's uid"
        );
    }

    #[cfg(unix)]
    #[test]
    fn preferred_home_uid_from_env_ignores_sudo_uid_for_non_root_sessions() {
        assert_eq!(
            preferred_home_uid_from_env(Some(OsStr::new("1000")), 2000),
            Some(2000),
            "non-root sessions should keep the current effective uid"
        );
    }

    #[cfg(unix)]
    #[test]
    fn preferred_home_uid_from_env_falls_back_when_sudo_uid_is_invalid() {
        assert_eq!(
            preferred_home_uid_from_env(Some(OsStr::new("not-a-uid")), 0),
            Some(0),
            "invalid sudo metadata should not break home-directory lookup"
        );
    }

    #[cfg(unix)]
    #[test]
    fn select_home_dir_prefers_passwd_lookup_over_sudo_home() {
        let passwd_home = Some(PathBuf::from("/home/invoking-user"));
        let sudo_home = Some(PathBuf::from("/root"));
        let env_home = Some(PathBuf::from("/tmp/fallback"));

        assert_eq!(
            select_home_dir(passwd_home.clone(), sudo_home, env_home),
            passwd_home,
            "passwd-database resolution should win over environment-derived sudo home"
        );
    }

    #[cfg(unix)]
    #[test]
    fn select_home_dir_falls_back_to_sudo_home_before_home_env() {
        let sudo_home = Some(PathBuf::from("/home/invoking-user"));
        let env_home = Some(PathBuf::from("/root"));

        assert_eq!(
            select_home_dir(None, sudo_home.clone(), env_home),
            sudo_home,
            "sudo home should remain the fallback when passwd lookup is unavailable"
        );
    }
}