Debian Codegraph @

rust/hg-pyo3/src/dirstate/status.rs

raw
1 // status.rs
2 //
3 // Copyright 2019 Raphaël Gomès <[email protected]>
4 // 2025 Georges Racinet <[email protected]>
5 //
6 // This software may be used and distributed according to the terms of the
7 // GNU General Public License version 2 or any later version.
8 //! Bindings for the `hg::status` module provided by the
9 //! `hg-core` crate. From Python, this will be seen as the
10 //! `pyo3_rustext.dirstate.status` function.
11 use std::path::Path;
12
13 use hg::dirstate::status::BadMatch;
14 use hg::dirstate::status::DirstateStatus;
15 use hg::dirstate::status::StatusError;
16 use hg::dirstate::status::StatusOptions;
17 use hg::dirstate::status::StatusPath;
18 use hg::file_patterns::parse_pattern_syntax_kind;
19 use hg::file_patterns::FilePattern;
20 use hg::file_patterns::PatternError;
21 use hg::matchers::AlwaysMatcher;
22 use hg::matchers::DifferenceMatcher;
23 use hg::matchers::FileMatcher;
24 use hg::matchers::IncludeMatcher;
25 use hg::matchers::IntersectionMatcher;
26 use hg::matchers::Matcher;
27 use hg::matchers::NeverMatcher;
28 use hg::matchers::PatternMatcher;
29 use hg::matchers::UnionMatcher;
30 use hg::utils::files::get_path_from_bytes;
31 use hg::utils::hg_path::HgPath;
32 use hg::warnings::HgWarningContext;
33 use pyo3::intern;
34 use pyo3::prelude::*;
35 use pyo3::types::PyBytes;
36 use pyo3::types::PyList;
37 use pyo3::types::PyTuple;
38
39 use super::dirstate_map::DirstateMap;
40 use crate::exceptions::to_string_value_error;
41 use crate::exceptions::FallbackError;
42 use crate::path::paths_py_list;
43 use crate::path::paths_pyiter_collect;
44 use crate::path::PyHgPathRef;
45 use crate::utils::hg_warnings_to_py_warnings;
46
47 fn status_path_py_list(
48 py: Python,
49 paths: &[StatusPath<'_>],
50 ) -> PyResult<Py<PyList>> {
51 paths_py_list(py, paths.iter().map(|item| &*item.path))
52 }
53
54 fn collect_bad_matches(
55 py: Python,
56 collection: &[(impl AsRef<HgPath>, BadMatch)],
57 ) -> PyResult<Py<PyList>> {
58 let get_error_message = |code: i32| -> String {
59 // hg-pyo3 here calling the Python interpreter
60 // using `os.strerror`. This seems to be equivalent and infallible
61 std::io::Error::from_raw_os_error(code).to_string()
62 };
63 Ok(PyList::new(
64 py,
65 collection.iter().map(|(path, bad_match)| {
66 let message = match bad_match {
67 BadMatch::OsError(code) => get_error_message(*code),
68 BadMatch::BadType(bad_type) => {
69 format!("unsupported file type (type is {})", bad_type)
70 }
71 };
72 (PyHgPathRef(path.as_ref()), message)
73 }),
74 )?
75 .unbind())
76 }
77
78 fn collect_kindpats(
79 py: Python,
80 matcher: &Bound<'_, PyAny>,
81 ) -> PyResult<Vec<FilePattern>> {
82 matcher
83 .getattr(intern!(py, "_kindpats"))?
84 .try_iter()?
85 .map(|k| {
86 let k = k?;
87 let py_syntax = k.get_item(0)?;
88 let py_pattern = k.get_item(1)?;
89 let py_source = k.get_item(2)?;
90
91 Ok(FilePattern::new(
92 parse_pattern_syntax_kind(
93 py_syntax.cast::<PyBytes>()?.as_bytes(),
94 )
95 .map_err(|e| handle_fallback(StatusError::Pattern(e)))?,
96 py_pattern.cast::<PyBytes>()?.as_bytes(),
97 get_path_from_bytes(py_source.cast::<PyBytes>()?.as_bytes()),
98 ))
99 })
100 .collect()
101 }
102
103 fn extract_matcher(
104 matcher: &Bound<'_, PyAny>,
105 ) -> PyResult<Box<dyn Matcher + Send>> {
106 let py = matcher.py();
107 let tampered = matcher
108 .call_method0(intern!(py, "was_tampered_with_nonrec"))?
109 .extract::<bool>()?;
110 if tampered {
111 return Err(handle_fallback(StatusError::Pattern(
112 PatternError::UnsupportedSyntax(
113 "Pattern matcher was tampered with!".to_string(),
114 ),
115 )));
116 };
117
118 match matcher.get_type().name()?.to_str()? {
119 "alwaysmatcher" => Ok(Box::new(AlwaysMatcher)),
120 "nevermatcher" => Ok(Box::new(NeverMatcher)),
121 "exactmatcher" => {
122 let files = matcher.call_method0(intern!(py, "files"))?;
123 let files: Vec<_> = paths_pyiter_collect(&files)?;
124 Ok(Box::new(
125 FileMatcher::new(files).map_err(to_string_value_error)?,
126 ))
127 }
128 "includematcher" => {
129 // Get the patterns from Python even though most of them are
130 // redundant with those we will parse later on, as they include
131 // those passed from the command line.
132 let file_patterns = collect_kindpats(py, matcher)?;
133 Ok(Box::new(
134 IncludeMatcher::new(file_patterns)
135 .map_err(|e| handle_fallback(e.into()))?,
136 ))
137 }
138 "unionmatcher" => {
139 let matchers: PyResult<Vec<_>> = matcher
140 .getattr("_matchers")?
141 .try_iter()?
142 .map(|py_matcher| extract_matcher(&py_matcher?))
143 .collect();
144
145 Ok(Box::new(UnionMatcher::new(matchers?)))
146 }
147 "intersectionmatcher" => {
148 let m1 = extract_matcher(&matcher.getattr("_m1")?)?;
149 let m2 = extract_matcher(&matcher.getattr("_m2")?)?;
150 Ok(Box::new(IntersectionMatcher::new(m1, m2)))
151 }
152 "differencematcher" => {
153 let m1 = extract_matcher(&matcher.getattr("_m1")?)?;
154 let m2 = extract_matcher(&matcher.getattr("_m2")?)?;
155 Ok(Box::new(DifferenceMatcher::new(m1, m2)))
156 }
157 "patternmatcher" => {
158 let patterns = collect_kindpats(py, matcher)?;
159 Ok(Box::new(
160 PatternMatcher::new(patterns)
161 .map_err(|e| handle_fallback(e.into()))?,
162 ))
163 }
164
165 m => Err(FallbackError::new_err(format!("Unsupported matcher {m}"))),
166 }
167 }
168
169 fn handle_fallback(err: StatusError) -> PyErr {
170 match err {
171 StatusError::Pattern(e) => {
172 let as_string = e.to_string();
173 tracing::debug!("Rust status fallback, see trace-level logs");
174 tracing::trace!("{}", as_string);
175 FallbackError::new_err(as_string)
176 }
177 e => to_string_value_error(e),
178 }
179 }
180
181 #[pyfunction]
182 #[allow(clippy::too_many_arguments)]
183 pub(super) fn status(
184 py: Python,
185 dmap: &Bound<'_, DirstateMap>,
186 matcher: &Bound<'_, PyAny>,
187 root_dir: &Bound<'_, PyBytes>,
188 ignore_files: &Bound<'_, PyList>,
189 check_exec: bool,
190 list_clean: bool,
191 list_ignored: bool,
192 list_unknown: bool,
193 collect_traversed_dirs: bool,
194 empty_dirs_keep_files: bool,
195 ) -> PyResult<Py<PyTuple>> {
196 let root_dir = get_path_from_bytes(root_dir.as_bytes());
197
198 let ignore_files: PyResult<Vec<_>> = ignore_files
199 .try_iter()?
200 .map(|res| {
201 let ob = res?;
202 let file = ob.cast::<PyBytes>()?.as_bytes();
203 Ok(get_path_from_bytes(file).to_owned())
204 })
205 .collect();
206 let ignore_files = ignore_files?;
207 // The caller may call `copymap.items()` separately
208 let list_copies = false;
209
210 let after_status = |res: Result<DirstateStatus<'_>, StatusError>,
211 warnings| {
212 let status_res = res.map_err(handle_fallback)?;
213 build_response(py, status_res, warnings, root_dir)
214 };
215
216 let matcher = extract_matcher(matcher)?;
217
218 DirstateMap::with_inner_write(dmap, |_dm_ref, mut inner| {
219 inner.with_status(
220 &matcher,
221 root_dir.to_path_buf(),
222 ignore_files,
223 StatusOptions {
224 check_exec,
225 list_clean,
226 list_ignored,
227 list_unknown,
228 list_copies,
229 collect_traversed_dirs,
230 empty_dirs_keep_files,
231 },
232 after_status,
233 )
234 })
235 }
236
237 fn build_response(
238 py: Python,
239 status_res: DirstateStatus,
240 warnings: HgWarningContext,
241 root_dir: &Path,
242 ) -> PyResult<Py<PyTuple>> {
243 let modified = status_path_py_list(py, &status_res.modified)?;
244 let added = status_path_py_list(py, &status_res.added)?;
245 let removed = status_path_py_list(py, &status_res.removed)?;
246 let deleted = status_path_py_list(py, &status_res.deleted)?;
247 let clean = status_path_py_list(py, &status_res.clean)?;
248 let ignored = status_path_py_list(py, &status_res.ignored)?;
249 let unknown = status_path_py_list(py, &status_res.unknown)?;
250 let unsure = status_path_py_list(py, &status_res.unsure)?;
251 let bad = collect_bad_matches(py, &status_res.bad)?;
252 let empty_dirs = paths_py_list(py, status_res.empty_dirs.iter())?;
253 let py_warnings = hg_warnings_to_py_warnings(py, warnings, root_dir)?;
254
255 let response = (
256 unsure,
257 modified,
258 added,
259 removed,
260 deleted,
261 clean,
262 ignored,
263 unknown,
264 py_warnings,
265 bad,
266 empty_dirs,
267 status_res.dirty,
268 );
269 Ok(response.into_pyobject(py)?.into())
270 }