Debian Codegraph @

rust/rhg/src/commands/files.rs

raw
1 use clap::Arg;
2 use hg::file_patterns::parse_pattern_args;
3 use hg::matchers::IntersectionMatcher;
4 use hg::narrow;
5 use hg::operations::list_revset_tracked_files;
6 use hg::repo::Repo;
7 use hg::utils::files::get_bytes_from_os_str;
8 use hg::utils::filter_map_results;
9 use hg::utils::hg_path::HgPath;
10 use hg::warnings::format::write_warning;
11 use hg::warnings::HgWarningContext;
12 use rayon::prelude::*;
13
14 use crate::error::CommandError;
15 use crate::ui::relative_paths;
16 use crate::ui::RelativePaths;
17 use crate::ui::Ui;
18 use crate::utils::path_utils::RelativizePaths;
19
20 pub const HELP_TEXT: &str = "
21 List tracked files.
22
23 Returns 0 on success.
24 ";
25
26 pub fn args() -> clap::Command {
27 clap::command!("files")
28 .args_override_self(true)
29 .arg(
30 Arg::new("rev")
31 .help("search the repository as it is in REV")
32 .short('r')
33 .long("rev")
34 .value_name("REV"),
35 )
36 .arg(
37 Arg::new("file")
38 .value_parser(clap::value_parser!(std::ffi::OsString))
39 .help("show only these files")
40 .action(clap::ArgAction::Append),
41 )
42 .arg(
43 Arg::new("print0")
44 .required(false)
45 .short('0')
46 .long("print0")
47 .action(clap::ArgAction::SetTrue)
48 .help("end filenames with NUL, for use with xargs"),
49 )
50 .about(HELP_TEXT)
51 }
52
53 #[tracing::instrument(level = "debug", skip_all, name = "rhg files")]
54 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
55 let relative_paths = match relative_paths(invocation.config)? {
56 RelativePaths::Legacy => true,
57 RelativePaths::Bool(v) => v,
58 };
59
60 let args = invocation.subcommand_args;
61 let rev = args.get_one::<String>("rev");
62 let delimiter = if args.get_flag("print0") {
63 b"\0"
64 } else {
65 b"\n"
66 };
67
68 let repo = invocation.repo?;
69
70 // It seems better if this check is removed: this would correspond to
71 // automatically enabling the extension if the repo requires it.
72 // However we need this check to be in sync with vanilla hg so hg tests
73 // pass.
74 if repo.has_sparse()
75 && invocation.config.get(b"extensions", b"sparse").is_none()
76 {
77 return Err(CommandError::unsupported(
78 "repo is using sparse, but sparse extension is not enabled",
79 ));
80 }
81
82 let warning_context = HgWarningContext::new();
83 let matcher = narrow::matcher(repo, warning_context.sender())?;
84
85 let mut stderr = invocation.ui.stderr_locked();
86 // Can't really do anything if writing to stderr failed
87 let _ = warning_context.finish(|warning| {
88 write_warning(&warning, &mut stderr, repo.working_directory_path())
89 });
90
91 let matcher = match args.get_many::<std::ffi::OsString>("file") {
92 None => matcher,
93 Some(files) => {
94 let patterns: Vec<Vec<u8>> = files
95 .filter(|s| !s.is_empty())
96 .map(get_bytes_from_os_str)
97 .collect();
98 for file in &patterns {
99 if file.starts_with(b"set:") {
100 return Err(CommandError::unsupported("fileset"));
101 }
102 }
103 let cwd = hg::utils::current_dir()?;
104 let root = repo.working_directory_path();
105 let file_patterns = parse_pattern_args(patterns, &cwd, root)?;
106 let files_matcher =
107 hg::matchers::PatternMatcher::new(file_patterns)?;
108 Box::new(IntersectionMatcher::new(Box::new(files_matcher), matcher))
109 }
110 };
111
112 if let Some(rev) = rev {
113 let files = list_revset_tracked_files(repo, rev, matcher)?;
114 display_files(
115 invocation.ui,
116 repo,
117 relative_paths,
118 delimiter,
119 files.iter().map::<Result<_, CommandError>, _>(|f| {
120 let (f, _, _) = f?;
121 Ok(f)
122 }),
123 )
124 } else {
125 // The dirstate always reflects the sparse narrowspec.
126 let dirstate = repo.dirstate_map()?;
127 let files_res: Result<Vec<_>, _> =
128 filter_map_results(dirstate.iter(), |(path, entry)| {
129 Ok(if entry.tracked() && matcher.matches(path) {
130 Some(path)
131 } else {
132 None
133 })
134 })
135 .collect();
136
137 let mut files = files_res?;
138 files.par_sort_unstable();
139
140 display_files(
141 invocation.ui,
142 repo,
143 relative_paths,
144 delimiter,
145 files.into_iter().map::<Result<_, CommandError>, _>(Ok),
146 )
147 }
148 }
149
150 fn display_files<'a, E>(
151 ui: &Ui,
152 repo: &Repo,
153 relative_paths: bool,
154 delimiter: &[u8],
155 files: impl IntoIterator<Item = Result<&'a HgPath, E>>,
156 ) -> Result<(), CommandError>
157 where
158 CommandError: From<E>,
159 {
160 let mut stdout = ui.stdout_buffer();
161 let mut any = false;
162
163 let relativize = RelativizePaths::new(repo)?;
164 for result in files {
165 let path = result?;
166 if relative_paths {
167 stdout.write_all(&relativize.relativize(path))?;
168 } else {
169 stdout.write_all(path.as_bytes())?;
170 }
171 stdout.write_all(delimiter)?;
172 any = true;
173 }
174
175 stdout.flush()?;
176 if any {
177 Ok(())
178 } else {
179 Err(CommandError::Unsuccessful)
180 }
181 }