##// END OF EJS Templates
rust-dirstate: remove excessive clone() of parameter and return value...
Yuya Nishihara -
r43069:1a535313 default
parent child Browse files
Show More
@@ -1,426 +1,426 b''
1 1 // dirstate_map.rs
2 2 //
3 3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 4 //
5 5 // This software may be used and distributed according to the terms of the
6 6 // GNU General Public License version 2 or any later version.
7 7
8 8 use crate::{
9 9 dirstate::{parsers::PARENT_SIZE, EntryState},
10 10 pack_dirstate, parse_dirstate, CopyMap, DirsIterable, DirsMultiset,
11 11 DirstateEntry, DirstateError, DirstateMapError, DirstateParents,
12 12 DirstateParseError, StateMap,
13 13 };
14 14 use core::borrow::Borrow;
15 15 use std::collections::{HashMap, HashSet};
16 16 use std::convert::TryInto;
17 17 use std::iter::FromIterator;
18 18 use std::ops::Deref;
19 19 use std::time::Duration;
20 20
21 21 pub type FileFoldMap = HashMap<Vec<u8>, Vec<u8>>;
22 22
23 23 const NULL_ID: [u8; 20] = [0; 20];
24 24 const MTIME_UNSET: i32 = -1;
25 25 const SIZE_DIRTY: i32 = -2;
26 26
27 27 #[derive(Default)]
28 28 pub struct DirstateMap {
29 29 state_map: StateMap,
30 30 pub copy_map: CopyMap,
31 31 file_fold_map: Option<FileFoldMap>,
32 32 pub dirs: Option<DirsMultiset>,
33 33 pub all_dirs: Option<DirsMultiset>,
34 34 non_normal_set: HashSet<Vec<u8>>,
35 35 other_parent_set: HashSet<Vec<u8>>,
36 36 parents: Option<DirstateParents>,
37 37 dirty_parents: bool,
38 38 }
39 39
40 40 /// Should only really be used in python interface code, for clarity
41 41 impl Deref for DirstateMap {
42 42 type Target = StateMap;
43 43
44 44 fn deref(&self) -> &Self::Target {
45 45 &self.state_map
46 46 }
47 47 }
48 48
49 49 impl FromIterator<(Vec<u8>, DirstateEntry)> for DirstateMap {
50 50 fn from_iter<I: IntoIterator<Item = (Vec<u8>, DirstateEntry)>>(
51 51 iter: I,
52 52 ) -> Self {
53 53 Self {
54 54 state_map: iter.into_iter().collect(),
55 55 ..Self::default()
56 56 }
57 57 }
58 58 }
59 59
60 60 impl DirstateMap {
61 61 pub fn new() -> Self {
62 62 Self::default()
63 63 }
64 64
65 65 pub fn clear(&mut self) {
66 66 self.state_map.clear();
67 67 self.copy_map.clear();
68 68 self.file_fold_map = None;
69 69 self.non_normal_set.clear();
70 70 self.other_parent_set.clear();
71 self.set_parents(DirstateParents {
71 self.set_parents(&DirstateParents {
72 72 p1: NULL_ID,
73 73 p2: NULL_ID,
74 74 })
75 75 }
76 76
77 77 /// Add a tracked file to the dirstate
78 78 pub fn add_file(
79 79 &mut self,
80 80 filename: &[u8],
81 81 old_state: EntryState,
82 82 entry: DirstateEntry,
83 83 ) {
84 84 if old_state == EntryState::Unknown || old_state == EntryState::Removed
85 85 {
86 86 if let Some(ref mut dirs) = self.dirs {
87 87 dirs.add_path(filename)
88 88 }
89 89 }
90 90 if old_state == EntryState::Unknown {
91 91 if let Some(ref mut all_dirs) = self.all_dirs {
92 92 all_dirs.add_path(filename)
93 93 }
94 94 }
95 95 self.state_map.insert(filename.to_owned(), entry.to_owned());
96 96
97 97 if entry.state != EntryState::Normal || entry.mtime == MTIME_UNSET {
98 98 self.non_normal_set.insert(filename.to_owned());
99 99 }
100 100
101 101 if entry.size == SIZE_DIRTY {
102 102 self.other_parent_set.insert(filename.to_owned());
103 103 }
104 104 }
105 105
106 106 /// Mark a file as removed in the dirstate.
107 107 ///
108 108 /// The `size` parameter is used to store sentinel values that indicate
109 109 /// the file's previous state. In the future, we should refactor this
110 110 /// to be more explicit about what that state is.
111 111 pub fn remove_file(
112 112 &mut self,
113 113 filename: &[u8],
114 114 old_state: EntryState,
115 115 size: i32,
116 116 ) -> Result<(), DirstateMapError> {
117 117 if old_state != EntryState::Unknown && old_state != EntryState::Removed
118 118 {
119 119 if let Some(ref mut dirs) = self.dirs {
120 120 dirs.delete_path(filename)?;
121 121 }
122 122 }
123 123 if old_state == EntryState::Unknown {
124 124 if let Some(ref mut all_dirs) = self.all_dirs {
125 125 all_dirs.add_path(filename);
126 126 }
127 127 }
128 128
129 129 if let Some(ref mut file_fold_map) = self.file_fold_map {
130 130 file_fold_map.remove(&filename.to_ascii_uppercase());
131 131 }
132 132 self.state_map.insert(
133 133 filename.to_owned(),
134 134 DirstateEntry {
135 135 state: EntryState::Removed,
136 136 mode: 0,
137 137 size,
138 138 mtime: 0,
139 139 },
140 140 );
141 141 self.non_normal_set.insert(filename.to_owned());
142 142 Ok(())
143 143 }
144 144
145 145 /// Remove a file from the dirstate.
146 146 /// Returns `true` if the file was previously recorded.
147 147 pub fn drop_file(
148 148 &mut self,
149 149 filename: &[u8],
150 150 old_state: EntryState,
151 151 ) -> Result<bool, DirstateMapError> {
152 152 let exists = self.state_map.remove(filename).is_some();
153 153
154 154 if exists {
155 155 if old_state != EntryState::Removed {
156 156 if let Some(ref mut dirs) = self.dirs {
157 157 dirs.delete_path(filename)?;
158 158 }
159 159 }
160 160 if let Some(ref mut all_dirs) = self.all_dirs {
161 161 all_dirs.delete_path(filename)?;
162 162 }
163 163 }
164 164 if let Some(ref mut file_fold_map) = self.file_fold_map {
165 165 file_fold_map.remove(&filename.to_ascii_uppercase());
166 166 }
167 167 self.non_normal_set.remove(filename);
168 168
169 169 Ok(exists)
170 170 }
171 171
172 172 pub fn clear_ambiguous_times(
173 173 &mut self,
174 174 filenames: Vec<Vec<u8>>,
175 175 now: i32,
176 176 ) {
177 177 for filename in filenames {
178 178 let mut changed = false;
179 179 self.state_map
180 180 .entry(filename.to_owned())
181 181 .and_modify(|entry| {
182 182 if entry.state == EntryState::Normal && entry.mtime == now
183 183 {
184 184 changed = true;
185 185 *entry = DirstateEntry {
186 186 mtime: MTIME_UNSET,
187 187 ..*entry
188 188 };
189 189 }
190 190 });
191 191 if changed {
192 192 self.non_normal_set.insert(filename.to_owned());
193 193 }
194 194 }
195 195 }
196 196
197 197 pub fn non_normal_other_parent_entries(
198 198 &self,
199 199 ) -> (HashSet<Vec<u8>>, HashSet<Vec<u8>>) {
200 200 let mut non_normal = HashSet::new();
201 201 let mut other_parent = HashSet::new();
202 202
203 203 for (
204 204 filename,
205 205 DirstateEntry {
206 206 state, size, mtime, ..
207 207 },
208 208 ) in self.state_map.iter()
209 209 {
210 210 if *state != EntryState::Normal || *mtime == MTIME_UNSET {
211 211 non_normal.insert(filename.to_owned());
212 212 }
213 213 if *state == EntryState::Normal && *size == SIZE_DIRTY {
214 214 other_parent.insert(filename.to_owned());
215 215 }
216 216 }
217 217
218 218 (non_normal, other_parent)
219 219 }
220 220
221 221 /// Both of these setters and their uses appear to be the simplest way to
222 222 /// emulate a Python lazy property, but it is ugly and unidiomatic.
223 223 /// TODO One day, rewriting this struct using the typestate might be a
224 224 /// good idea.
225 225 pub fn set_all_dirs(&mut self) {
226 226 if self.all_dirs.is_none() {
227 227 self.all_dirs = Some(DirsMultiset::new(
228 228 DirsIterable::Dirstate(&self.state_map),
229 229 None,
230 230 ));
231 231 }
232 232 }
233 233
234 234 pub fn set_dirs(&mut self) {
235 235 if self.dirs.is_none() {
236 236 self.dirs = Some(DirsMultiset::new(
237 237 DirsIterable::Dirstate(&self.state_map),
238 238 Some(EntryState::Removed),
239 239 ));
240 240 }
241 241 }
242 242
243 243 pub fn has_tracked_dir(&mut self, directory: &[u8]) -> bool {
244 244 self.set_dirs();
245 245 self.dirs.as_ref().unwrap().contains(directory)
246 246 }
247 247
248 248 pub fn has_dir(&mut self, directory: &[u8]) -> bool {
249 249 self.set_all_dirs();
250 250 self.all_dirs.as_ref().unwrap().contains(directory)
251 251 }
252 252
253 253 pub fn parents(
254 254 &mut self,
255 255 file_contents: &[u8],
256 ) -> Result<DirstateParents, DirstateError> {
256 ) -> Result<&DirstateParents, DirstateError> {
257 257 if let Some(ref parents) = self.parents {
258 return Ok(parents.clone());
258 return Ok(parents);
259 259 }
260 260 let parents;
261 261 if file_contents.len() == PARENT_SIZE * 2 {
262 262 parents = DirstateParents {
263 263 p1: file_contents[..PARENT_SIZE].try_into().unwrap(),
264 264 p2: file_contents[PARENT_SIZE..PARENT_SIZE * 2]
265 265 .try_into()
266 266 .unwrap(),
267 267 };
268 268 } else if file_contents.is_empty() {
269 269 parents = DirstateParents {
270 270 p1: NULL_ID,
271 271 p2: NULL_ID,
272 272 };
273 273 } else {
274 274 return Err(DirstateError::Parse(DirstateParseError::Damaged));
275 275 }
276 276
277 self.parents = Some(parents.to_owned());
278 Ok(parents.clone())
277 self.parents = Some(parents);
278 Ok(self.parents.as_ref().unwrap())
279 279 }
280 280
281 pub fn set_parents(&mut self, parents: DirstateParents) {
281 pub fn set_parents(&mut self, parents: &DirstateParents) {
282 282 self.parents = Some(parents.clone());
283 283 self.dirty_parents = true;
284 284 }
285 285
286 286 pub fn read(
287 287 &mut self,
288 288 file_contents: &[u8],
289 289 ) -> Result<Option<DirstateParents>, DirstateError> {
290 290 if file_contents.is_empty() {
291 291 return Ok(None);
292 292 }
293 293
294 294 let parents = parse_dirstate(
295 295 &mut self.state_map,
296 296 &mut self.copy_map,
297 297 file_contents,
298 298 )?;
299 299
300 300 if !self.dirty_parents {
301 self.set_parents(parents.to_owned());
301 self.set_parents(&parents);
302 302 }
303 303
304 304 Ok(Some(parents))
305 305 }
306 306
307 307 pub fn pack(
308 308 &mut self,
309 309 parents: DirstateParents,
310 310 now: Duration,
311 311 ) -> Result<Vec<u8>, DirstateError> {
312 312 let packed =
313 313 pack_dirstate(&mut self.state_map, &self.copy_map, parents, now)?;
314 314
315 315 self.dirty_parents = false;
316 316
317 317 let result = self.non_normal_other_parent_entries();
318 318 self.non_normal_set = result.0;
319 319 self.other_parent_set = result.1;
320 320 Ok(packed)
321 321 }
322 322
323 pub fn build_file_fold_map(&mut self) -> FileFoldMap {
323 pub fn build_file_fold_map(&mut self) -> &FileFoldMap {
324 324 if let Some(ref file_fold_map) = self.file_fold_map {
325 return file_fold_map.to_owned();
325 return file_fold_map;
326 326 }
327 327 let mut new_file_fold_map = FileFoldMap::new();
328 328 for (filename, DirstateEntry { state, .. }) in self.state_map.borrow()
329 329 {
330 330 if *state == EntryState::Removed {
331 331 new_file_fold_map.insert(
332 332 filename.to_ascii_uppercase().to_owned(),
333 333 filename.to_owned(),
334 334 );
335 335 }
336 336 }
337 337 self.file_fold_map = Some(new_file_fold_map);
338 self.file_fold_map.to_owned().unwrap()
338 self.file_fold_map.as_ref().unwrap()
339 339 }
340 340 }
341 341
342 342 #[cfg(test)]
343 343 mod tests {
344 344 use super::*;
345 345
346 346 #[test]
347 347 fn test_dirs_multiset() {
348 348 let mut map = DirstateMap::new();
349 349 assert!(map.dirs.is_none());
350 350 assert!(map.all_dirs.is_none());
351 351
352 352 assert_eq!(false, map.has_dir(b"nope"));
353 353 assert!(map.all_dirs.is_some());
354 354 assert!(map.dirs.is_none());
355 355
356 356 assert_eq!(false, map.has_tracked_dir(b"nope"));
357 357 assert!(map.dirs.is_some());
358 358 }
359 359
360 360 #[test]
361 361 fn test_add_file() {
362 362 let mut map = DirstateMap::new();
363 363
364 364 assert_eq!(0, map.len());
365 365
366 366 map.add_file(
367 367 b"meh",
368 368 EntryState::Normal,
369 369 DirstateEntry {
370 370 state: EntryState::Normal,
371 371 mode: 1337,
372 372 mtime: 1337,
373 373 size: 1337,
374 374 },
375 375 );
376 376
377 377 assert_eq!(1, map.len());
378 378 assert_eq!(0, map.non_normal_set.len());
379 379 assert_eq!(0, map.other_parent_set.len());
380 380 }
381 381
382 382 #[test]
383 383 fn test_non_normal_other_parent_entries() {
384 384 let map: DirstateMap = [
385 385 (b"f1", (EntryState::Removed, 1337, 1337, 1337)),
386 386 (b"f2", (EntryState::Normal, 1337, 1337, -1)),
387 387 (b"f3", (EntryState::Normal, 1337, 1337, 1337)),
388 388 (b"f4", (EntryState::Normal, 1337, -2, 1337)),
389 389 (b"f5", (EntryState::Added, 1337, 1337, 1337)),
390 390 (b"f6", (EntryState::Added, 1337, 1337, -1)),
391 391 (b"f7", (EntryState::Merged, 1337, 1337, -1)),
392 392 (b"f8", (EntryState::Merged, 1337, 1337, 1337)),
393 393 (b"f9", (EntryState::Merged, 1337, -2, 1337)),
394 394 (b"fa", (EntryState::Added, 1337, -2, 1337)),
395 395 (b"fb", (EntryState::Removed, 1337, -2, 1337)),
396 396 ]
397 397 .iter()
398 398 .map(|(fname, (state, mode, size, mtime))| {
399 399 (
400 400 fname.to_vec(),
401 401 DirstateEntry {
402 402 state: *state,
403 403 mode: *mode,
404 404 size: *size,
405 405 mtime: *mtime,
406 406 },
407 407 )
408 408 })
409 409 .collect();
410 410
411 411 let non_normal = [
412 412 b"f1", b"f2", b"f5", b"f6", b"f7", b"f8", b"f9", b"fa", b"fb",
413 413 ]
414 414 .iter()
415 415 .map(|x| x.to_vec())
416 416 .collect();
417 417
418 418 let mut other_parent = HashSet::new();
419 419 other_parent.insert(b"f4".to_vec());
420 420
421 421 assert_eq!(
422 422 (non_normal, other_parent),
423 423 map.non_normal_other_parent_entries()
424 424 );
425 425 }
426 426 }
@@ -1,515 +1,515 b''
1 1 // dirstate_map.rs
2 2 //
3 3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 4 //
5 5 // This software may be used and distributed according to the terms of the
6 6 // GNU General Public License version 2 or any later version.
7 7
8 8 //! Bindings for the `hg::dirstate::dirstate_map` file provided by the
9 9 //! `hg-core` package.
10 10
11 11 use std::cell::RefCell;
12 12 use std::convert::TryInto;
13 13 use std::time::Duration;
14 14
15 15 use cpython::{
16 16 exc, ObjectProtocol, PyBool, PyBytes, PyClone, PyDict, PyErr, PyObject,
17 17 PyResult, PyTuple, Python, PythonObject, ToPyObject,
18 18 };
19 19 use libc::c_char;
20 20
21 21 use crate::{
22 22 dirstate::copymap::{CopyMap, CopyMapItemsIterator, CopyMapKeysIterator},
23 23 dirstate::{decapsule_make_dirstate_tuple, dirs_multiset::Dirs},
24 24 ref_sharing::PySharedState,
25 25 };
26 26 use hg::{
27 27 DirsIterable, DirsMultiset, DirstateEntry, DirstateMap as RustDirstateMap,
28 28 DirstateParents, DirstateParseError, EntryState, PARENT_SIZE,
29 29 };
30 30
31 31 // TODO
32 32 // This object needs to share references to multiple members of its Rust
33 33 // inner struct, namely `copy_map`, `dirs` and `all_dirs`.
34 34 // Right now `CopyMap` is done, but it needs to have an explicit reference
35 35 // to `RustDirstateMap` which itself needs to have an encapsulation for
36 36 // every method in `CopyMap` (copymapcopy, etc.).
37 37 // This is ugly and hard to maintain.
38 38 // The same logic applies to `dirs` and `all_dirs`, however the `Dirs`
39 39 // `py_class!` is already implemented and does not mention
40 40 // `RustDirstateMap`, rightfully so.
41 41 // All attributes also have to have a separate refcount data attribute for
42 42 // leaks, with all methods that go along for reference sharing.
43 43 py_class!(pub class DirstateMap |py| {
44 44 data inner: RefCell<RustDirstateMap>;
45 45 data py_shared_state: PySharedState;
46 46
47 47 def __new__(_cls, _root: PyObject) -> PyResult<Self> {
48 48 let inner = RustDirstateMap::default();
49 49 Self::create_instance(
50 50 py,
51 51 RefCell::new(inner),
52 52 PySharedState::default()
53 53 )
54 54 }
55 55
56 56 def clear(&self) -> PyResult<PyObject> {
57 57 self.borrow_mut(py)?.clear();
58 58 Ok(py.None())
59 59 }
60 60
61 61 def get(
62 62 &self,
63 63 key: PyObject,
64 64 default: Option<PyObject> = None
65 65 ) -> PyResult<Option<PyObject>> {
66 66 let key = key.extract::<PyBytes>(py)?;
67 67 match self.inner(py).borrow().get(key.data(py)) {
68 68 Some(entry) => {
69 69 // Explicitly go through u8 first, then cast to
70 70 // platform-specific `c_char`.
71 71 let state: u8 = entry.state.into();
72 72 Ok(Some(decapsule_make_dirstate_tuple(py)?(
73 73 state as c_char,
74 74 entry.mode,
75 75 entry.size,
76 76 entry.mtime,
77 77 )))
78 78 },
79 79 None => Ok(default)
80 80 }
81 81 }
82 82
83 83 def addfile(
84 84 &self,
85 85 f: PyObject,
86 86 oldstate: PyObject,
87 87 state: PyObject,
88 88 mode: PyObject,
89 89 size: PyObject,
90 90 mtime: PyObject
91 91 ) -> PyResult<PyObject> {
92 92 self.borrow_mut(py)?.add_file(
93 93 f.extract::<PyBytes>(py)?.data(py),
94 94 oldstate.extract::<PyBytes>(py)?.data(py)[0]
95 95 .try_into()
96 96 .map_err(|e: DirstateParseError| {
97 97 PyErr::new::<exc::ValueError, _>(py, e.to_string())
98 98 })?,
99 99 DirstateEntry {
100 100 state: state.extract::<PyBytes>(py)?.data(py)[0]
101 101 .try_into()
102 102 .map_err(|e: DirstateParseError| {
103 103 PyErr::new::<exc::ValueError, _>(py, e.to_string())
104 104 })?,
105 105 mode: mode.extract(py)?,
106 106 size: size.extract(py)?,
107 107 mtime: mtime.extract(py)?,
108 108 },
109 109 );
110 110 Ok(py.None())
111 111 }
112 112
113 113 def removefile(
114 114 &self,
115 115 f: PyObject,
116 116 oldstate: PyObject,
117 117 size: PyObject
118 118 ) -> PyResult<PyObject> {
119 119 self.borrow_mut(py)?
120 120 .remove_file(
121 121 f.extract::<PyBytes>(py)?.data(py),
122 122 oldstate.extract::<PyBytes>(py)?.data(py)[0]
123 123 .try_into()
124 124 .map_err(|e: DirstateParseError| {
125 125 PyErr::new::<exc::ValueError, _>(py, e.to_string())
126 126 })?,
127 127 size.extract(py)?,
128 128 )
129 129 .or_else(|_| {
130 130 Err(PyErr::new::<exc::OSError, _>(
131 131 py,
132 132 "Dirstate error".to_string(),
133 133 ))
134 134 })?;
135 135 Ok(py.None())
136 136 }
137 137
138 138 def dropfile(
139 139 &self,
140 140 f: PyObject,
141 141 oldstate: PyObject
142 142 ) -> PyResult<PyBool> {
143 143 self.borrow_mut(py)?
144 144 .drop_file(
145 145 f.extract::<PyBytes>(py)?.data(py),
146 146 oldstate.extract::<PyBytes>(py)?.data(py)[0]
147 147 .try_into()
148 148 .map_err(|e: DirstateParseError| {
149 149 PyErr::new::<exc::ValueError, _>(py, e.to_string())
150 150 })?,
151 151 )
152 152 .and_then(|b| Ok(b.to_py_object(py)))
153 153 .or_else(|_| {
154 154 Err(PyErr::new::<exc::OSError, _>(
155 155 py,
156 156 "Dirstate error".to_string(),
157 157 ))
158 158 })
159 159 }
160 160
161 161 def clearambiguoustimes(
162 162 &self,
163 163 files: PyObject,
164 164 now: PyObject
165 165 ) -> PyResult<PyObject> {
166 166 let files: PyResult<Vec<Vec<u8>>> = files
167 167 .iter(py)?
168 168 .map(|filename| {
169 169 Ok(filename?.extract::<PyBytes>(py)?.data(py).to_owned())
170 170 })
171 171 .collect();
172 172 self.inner(py)
173 173 .borrow_mut()
174 174 .clear_ambiguous_times(files?, now.extract(py)?);
175 175 Ok(py.None())
176 176 }
177 177
178 178 // TODO share the reference
179 179 def nonnormalentries(&self) -> PyResult<PyObject> {
180 180 let (non_normal, other_parent) =
181 181 self.inner(py).borrow().non_normal_other_parent_entries();
182 182
183 183 let locals = PyDict::new(py);
184 184 locals.set_item(
185 185 py,
186 186 "non_normal",
187 187 non_normal
188 188 .iter()
189 189 .map(|v| PyBytes::new(py, &v))
190 190 .collect::<Vec<PyBytes>>()
191 191 .to_py_object(py),
192 192 )?;
193 193 locals.set_item(
194 194 py,
195 195 "other_parent",
196 196 other_parent
197 197 .iter()
198 198 .map(|v| PyBytes::new(py, &v))
199 199 .collect::<Vec<PyBytes>>()
200 200 .to_py_object(py),
201 201 )?;
202 202
203 203 py.eval("set(non_normal), set(other_parent)", None, Some(&locals))
204 204 }
205 205
206 206 def hastrackeddir(&self, d: PyObject) -> PyResult<PyBool> {
207 207 let d = d.extract::<PyBytes>(py)?;
208 208 Ok(self
209 209 .inner(py)
210 210 .borrow_mut()
211 211 .has_tracked_dir(d.data(py))
212 212 .to_py_object(py))
213 213 }
214 214
215 215 def hasdir(&self, d: PyObject) -> PyResult<PyBool> {
216 216 let d = d.extract::<PyBytes>(py)?;
217 217 Ok(self
218 218 .inner(py)
219 219 .borrow_mut()
220 220 .has_dir(d.data(py))
221 221 .to_py_object(py))
222 222 }
223 223
224 224 def parents(&self, st: PyObject) -> PyResult<PyTuple> {
225 225 self.inner(py)
226 226 .borrow_mut()
227 227 .parents(st.extract::<PyBytes>(py)?.data(py))
228 228 .and_then(|d| {
229 229 Ok((PyBytes::new(py, &d.p1), PyBytes::new(py, &d.p2))
230 230 .to_py_object(py))
231 231 })
232 232 .or_else(|_| {
233 233 Err(PyErr::new::<exc::OSError, _>(
234 234 py,
235 235 "Dirstate error".to_string(),
236 236 ))
237 237 })
238 238 }
239 239
240 240 def setparents(&self, p1: PyObject, p2: PyObject) -> PyResult<PyObject> {
241 241 let p1 = extract_node_id(py, &p1)?;
242 242 let p2 = extract_node_id(py, &p2)?;
243 243
244 244 self.inner(py)
245 245 .borrow_mut()
246 .set_parents(DirstateParents { p1, p2 });
246 .set_parents(&DirstateParents { p1, p2 });
247 247 Ok(py.None())
248 248 }
249 249
250 250 def read(&self, st: PyObject) -> PyResult<Option<PyObject>> {
251 251 match self
252 252 .inner(py)
253 253 .borrow_mut()
254 254 .read(st.extract::<PyBytes>(py)?.data(py))
255 255 {
256 256 Ok(Some(parents)) => Ok(Some(
257 257 (PyBytes::new(py, &parents.p1), PyBytes::new(py, &parents.p2))
258 258 .to_py_object(py)
259 259 .into_object(),
260 260 )),
261 261 Ok(None) => Ok(Some(py.None())),
262 262 Err(_) => Err(PyErr::new::<exc::OSError, _>(
263 263 py,
264 264 "Dirstate error".to_string(),
265 265 )),
266 266 }
267 267 }
268 268 def write(
269 269 &self,
270 270 p1: PyObject,
271 271 p2: PyObject,
272 272 now: PyObject
273 273 ) -> PyResult<PyBytes> {
274 274 let now = Duration::new(now.extract(py)?, 0);
275 275 let parents = DirstateParents {
276 276 p1: extract_node_id(py, &p1)?,
277 277 p2: extract_node_id(py, &p2)?,
278 278 };
279 279
280 280 match self.borrow_mut(py)?.pack(parents, now) {
281 281 Ok(packed) => Ok(PyBytes::new(py, &packed)),
282 282 Err(_) => Err(PyErr::new::<exc::OSError, _>(
283 283 py,
284 284 "Dirstate error".to_string(),
285 285 )),
286 286 }
287 287 }
288 288
289 289 def filefoldmapasdict(&self) -> PyResult<PyDict> {
290 290 let dict = PyDict::new(py);
291 291 for (key, value) in
292 292 self.borrow_mut(py)?.build_file_fold_map().iter()
293 293 {
294 294 dict.set_item(py, key, value)?;
295 295 }
296 296 Ok(dict)
297 297 }
298 298
299 299 def __len__(&self) -> PyResult<usize> {
300 300 Ok(self.inner(py).borrow().len())
301 301 }
302 302
303 303 def __contains__(&self, key: PyObject) -> PyResult<bool> {
304 304 let key = key.extract::<PyBytes>(py)?;
305 305 Ok(self.inner(py).borrow().contains_key(key.data(py)))
306 306 }
307 307
308 308 def __getitem__(&self, key: PyObject) -> PyResult<PyObject> {
309 309 let key = key.extract::<PyBytes>(py)?;
310 310 let key = key.data(py);
311 311 match self.inner(py).borrow().get(key) {
312 312 Some(entry) => {
313 313 // Explicitly go through u8 first, then cast to
314 314 // platform-specific `c_char`.
315 315 let state: u8 = entry.state.into();
316 316 Ok(decapsule_make_dirstate_tuple(py)?(
317 317 state as c_char,
318 318 entry.mode,
319 319 entry.size,
320 320 entry.mtime,
321 321 ))
322 322 },
323 323 None => Err(PyErr::new::<exc::KeyError, _>(
324 324 py,
325 325 String::from_utf8_lossy(key),
326 326 )),
327 327 }
328 328 }
329 329
330 330 def keys(&self) -> PyResult<DirstateMapKeysIterator> {
331 331 DirstateMapKeysIterator::from_inner(
332 332 py,
333 333 Some(DirstateMapLeakedRef::new(py, &self)),
334 334 Box::new(self.leak_immutable(py)?.iter()),
335 335 )
336 336 }
337 337
338 338 def items(&self) -> PyResult<DirstateMapItemsIterator> {
339 339 DirstateMapItemsIterator::from_inner(
340 340 py,
341 341 Some(DirstateMapLeakedRef::new(py, &self)),
342 342 Box::new(self.leak_immutable(py)?.iter()),
343 343 )
344 344 }
345 345
346 346 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
347 347 DirstateMapKeysIterator::from_inner(
348 348 py,
349 349 Some(DirstateMapLeakedRef::new(py, &self)),
350 350 Box::new(self.leak_immutable(py)?.iter()),
351 351 )
352 352 }
353 353
354 354 def getdirs(&self) -> PyResult<Dirs> {
355 355 // TODO don't copy, share the reference
356 356 self.inner(py).borrow_mut().set_dirs();
357 357 Dirs::from_inner(
358 358 py,
359 359 DirsMultiset::new(
360 360 DirsIterable::Dirstate(&self.inner(py).borrow()),
361 361 Some(EntryState::Removed),
362 362 ),
363 363 )
364 364 }
365 365 def getalldirs(&self) -> PyResult<Dirs> {
366 366 // TODO don't copy, share the reference
367 367 self.inner(py).borrow_mut().set_all_dirs();
368 368 Dirs::from_inner(
369 369 py,
370 370 DirsMultiset::new(
371 371 DirsIterable::Dirstate(&self.inner(py).borrow()),
372 372 None,
373 373 ),
374 374 )
375 375 }
376 376
377 377 // TODO all copymap* methods, see docstring above
378 378 def copymapcopy(&self) -> PyResult<PyDict> {
379 379 let dict = PyDict::new(py);
380 380 for (key, value) in self.inner(py).borrow().copy_map.iter() {
381 381 dict.set_item(py, PyBytes::new(py, key), PyBytes::new(py, value))?;
382 382 }
383 383 Ok(dict)
384 384 }
385 385
386 386 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
387 387 let key = key.extract::<PyBytes>(py)?;
388 388 match self.inner(py).borrow().copy_map.get(key.data(py)) {
389 389 Some(copy) => Ok(PyBytes::new(py, copy)),
390 390 None => Err(PyErr::new::<exc::KeyError, _>(
391 391 py,
392 392 String::from_utf8_lossy(key.data(py)),
393 393 )),
394 394 }
395 395 }
396 396 def copymap(&self) -> PyResult<CopyMap> {
397 397 CopyMap::from_inner(py, self.clone_ref(py))
398 398 }
399 399
400 400 def copymaplen(&self) -> PyResult<usize> {
401 401 Ok(self.inner(py).borrow().copy_map.len())
402 402 }
403 403 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
404 404 let key = key.extract::<PyBytes>(py)?;
405 405 Ok(self.inner(py).borrow().copy_map.contains_key(key.data(py)))
406 406 }
407 407 def copymapget(
408 408 &self,
409 409 key: PyObject,
410 410 default: Option<PyObject>
411 411 ) -> PyResult<Option<PyObject>> {
412 412 let key = key.extract::<PyBytes>(py)?;
413 413 match self.inner(py).borrow().copy_map.get(key.data(py)) {
414 414 Some(copy) => Ok(Some(PyBytes::new(py, copy).into_object())),
415 415 None => Ok(default),
416 416 }
417 417 }
418 418 def copymapsetitem(
419 419 &self,
420 420 key: PyObject,
421 421 value: PyObject
422 422 ) -> PyResult<PyObject> {
423 423 let key = key.extract::<PyBytes>(py)?;
424 424 let value = value.extract::<PyBytes>(py)?;
425 425 self.inner(py)
426 426 .borrow_mut()
427 427 .copy_map
428 428 .insert(key.data(py).to_vec(), value.data(py).to_vec());
429 429 Ok(py.None())
430 430 }
431 431 def copymappop(
432 432 &self,
433 433 key: PyObject,
434 434 default: Option<PyObject>
435 435 ) -> PyResult<Option<PyObject>> {
436 436 let key = key.extract::<PyBytes>(py)?;
437 437 match self.inner(py).borrow_mut().copy_map.remove(key.data(py)) {
438 438 Some(_) => Ok(None),
439 439 None => Ok(default),
440 440 }
441 441 }
442 442
443 443 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
444 444 CopyMapKeysIterator::from_inner(
445 445 py,
446 446 Some(DirstateMapLeakedRef::new(py, &self)),
447 447 Box::new(self.leak_immutable(py)?.copy_map.iter()),
448 448 )
449 449 }
450 450
451 451 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
452 452 CopyMapItemsIterator::from_inner(
453 453 py,
454 454 Some(DirstateMapLeakedRef::new(py, &self)),
455 455 Box::new(self.leak_immutable(py)?.copy_map.iter()),
456 456 )
457 457 }
458 458
459 459 });
460 460
461 461 impl DirstateMap {
462 462 fn translate_key(
463 463 py: Python,
464 464 res: (&Vec<u8>, &DirstateEntry),
465 465 ) -> PyResult<Option<PyBytes>> {
466 466 Ok(Some(PyBytes::new(py, res.0)))
467 467 }
468 468 fn translate_key_value(
469 469 py: Python,
470 470 res: (&Vec<u8>, &DirstateEntry),
471 471 ) -> PyResult<Option<(PyBytes, PyObject)>> {
472 472 let (f, entry) = res;
473 473
474 474 // Explicitly go through u8 first, then cast to
475 475 // platform-specific `c_char`.
476 476 let state: u8 = entry.state.into();
477 477 Ok(Some((
478 478 PyBytes::new(py, f),
479 479 decapsule_make_dirstate_tuple(py)?(
480 480 state as c_char,
481 481 entry.mode,
482 482 entry.size,
483 483 entry.mtime,
484 484 ),
485 485 )))
486 486 }
487 487 }
488 488
489 489 py_shared_ref!(DirstateMap, RustDirstateMap, inner, DirstateMapLeakedRef,);
490 490
491 491 py_shared_mapping_iterator!(
492 492 DirstateMapKeysIterator,
493 493 DirstateMapLeakedRef,
494 494 Vec<u8>,
495 495 DirstateEntry,
496 496 DirstateMap::translate_key,
497 497 Option<PyBytes>
498 498 );
499 499
500 500 py_shared_mapping_iterator!(
501 501 DirstateMapItemsIterator,
502 502 DirstateMapLeakedRef,
503 503 Vec<u8>,
504 504 DirstateEntry,
505 505 DirstateMap::translate_key_value,
506 506 Option<(PyBytes, PyObject)>
507 507 );
508 508
509 509 fn extract_node_id(py: Python, obj: &PyObject) -> PyResult<[u8; PARENT_SIZE]> {
510 510 let bytes = obj.extract::<PyBytes>(py)?;
511 511 match bytes.data(py).try_into() {
512 512 Ok(s) => Ok(s),
513 513 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
514 514 }
515 515 }
General Comments 0
You need to be logged in to leave comments. Login now