Skip to main content

xtask/
fs_helpers.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Helper functions to traverse + enumerate the project's filesystem, used by
5//! multiple task implementations.
6
7use std::path::PathBuf;
8
9use crate::shell::XtaskShell;
10
11/// Return a list of all files that are currently git diffed, including
12/// those which have been staged, but not yet been committed.
13pub fn git_diffed(in_git_hook: bool) -> anyhow::Result<Vec<PathBuf>> {
14    let sh = XtaskShell::new()?;
15
16    let files = sh
17        .cmd("git")
18        .args(["diff", "--diff-filter", "MAR", "--name-only"])
19        .output()?
20        .stdout;
21    let files_cached = sh
22        .cmd("git")
23        .args(["diff", "--diff-filter", "MAR", "--name-only", "--cached"])
24        .output()?
25        .stdout;
26
27    let files = String::from_utf8_lossy(&files);
28    let files_cached = String::from_utf8_lossy(&files_cached);
29
30    // don't include unstaged files when running in a hook context
31    let files: Box<dyn Iterator<Item = _>> = if in_git_hook {
32        Box::new(files_cached.lines())
33    } else {
34        Box::new(files_cached.lines().chain(files.lines()))
35    };
36
37    let mut all_files = files.map(PathBuf::from).collect::<Vec<_>>();
38
39    all_files.sort();
40    all_files.dedup();
41    Ok(all_files)
42}