##// END OF EJS Templates
rust-dirstatemap: add `set_untracked` method...
Raphaël Gomès -
r49999:119c7e2b default
parent child Browse files
Show More
@@ -1,1435 +1,1494 b''
1 use bytes_cast::BytesCast;
1 use bytes_cast::BytesCast;
2 use micro_timer::timed;
2 use micro_timer::timed;
3 use std::borrow::Cow;
3 use std::borrow::Cow;
4 use std::path::PathBuf;
4 use std::path::PathBuf;
5
5
6 use super::on_disk;
6 use super::on_disk;
7 use super::on_disk::DirstateV2ParseError;
7 use super::on_disk::DirstateV2ParseError;
8 use super::owning::OwningDirstateMap;
8 use super::owning::OwningDirstateMap;
9 use super::path_with_basename::WithBasename;
9 use super::path_with_basename::WithBasename;
10 use crate::dirstate::parsers::pack_entry;
10 use crate::dirstate::parsers::pack_entry;
11 use crate::dirstate::parsers::packed_entry_size;
11 use crate::dirstate::parsers::packed_entry_size;
12 use crate::dirstate::parsers::parse_dirstate_entries;
12 use crate::dirstate::parsers::parse_dirstate_entries;
13 use crate::dirstate::CopyMapIter;
13 use crate::dirstate::CopyMapIter;
14 use crate::dirstate::DirstateV2Data;
14 use crate::dirstate::DirstateV2Data;
15 use crate::dirstate::ParentFileData;
15 use crate::dirstate::ParentFileData;
16 use crate::dirstate::StateMapIter;
16 use crate::dirstate::StateMapIter;
17 use crate::dirstate::TruncatedTimestamp;
17 use crate::dirstate::TruncatedTimestamp;
18 use crate::dirstate::SIZE_FROM_OTHER_PARENT;
18 use crate::dirstate::SIZE_FROM_OTHER_PARENT;
19 use crate::dirstate::SIZE_NON_NORMAL;
19 use crate::dirstate::SIZE_NON_NORMAL;
20 use crate::matchers::Matcher;
20 use crate::matchers::Matcher;
21 use crate::utils::hg_path::{HgPath, HgPathBuf};
21 use crate::utils::hg_path::{HgPath, HgPathBuf};
22 use crate::DirstateEntry;
22 use crate::DirstateEntry;
23 use crate::DirstateError;
23 use crate::DirstateError;
24 use crate::DirstateMapError;
24 use crate::DirstateMapError;
25 use crate::DirstateParents;
25 use crate::DirstateParents;
26 use crate::DirstateStatus;
26 use crate::DirstateStatus;
27 use crate::EntryState;
27 use crate::EntryState;
28 use crate::FastHashbrownMap as FastHashMap;
28 use crate::FastHashbrownMap as FastHashMap;
29 use crate::PatternFileWarning;
29 use crate::PatternFileWarning;
30 use crate::StatusError;
30 use crate::StatusError;
31 use crate::StatusOptions;
31 use crate::StatusOptions;
32
32
33 /// Append to an existing data file if the amount of unreachable data (not used
33 /// Append to an existing data file if the amount of unreachable data (not used
34 /// anymore) is less than this fraction of the total amount of existing data.
34 /// anymore) is less than this fraction of the total amount of existing data.
35 const ACCEPTABLE_UNREACHABLE_BYTES_RATIO: f32 = 0.5;
35 const ACCEPTABLE_UNREACHABLE_BYTES_RATIO: f32 = 0.5;
36
36
37 pub struct DirstateMap<'on_disk> {
37 pub struct DirstateMap<'on_disk> {
38 /// Contents of the `.hg/dirstate` file
38 /// Contents of the `.hg/dirstate` file
39 pub(super) on_disk: &'on_disk [u8],
39 pub(super) on_disk: &'on_disk [u8],
40
40
41 pub(super) root: ChildNodes<'on_disk>,
41 pub(super) root: ChildNodes<'on_disk>,
42
42
43 /// Number of nodes anywhere in the tree that have `.entry.is_some()`.
43 /// Number of nodes anywhere in the tree that have `.entry.is_some()`.
44 pub(super) nodes_with_entry_count: u32,
44 pub(super) nodes_with_entry_count: u32,
45
45
46 /// Number of nodes anywhere in the tree that have
46 /// Number of nodes anywhere in the tree that have
47 /// `.copy_source.is_some()`.
47 /// `.copy_source.is_some()`.
48 pub(super) nodes_with_copy_source_count: u32,
48 pub(super) nodes_with_copy_source_count: u32,
49
49
50 /// See on_disk::Header
50 /// See on_disk::Header
51 pub(super) ignore_patterns_hash: on_disk::IgnorePatternsHash,
51 pub(super) ignore_patterns_hash: on_disk::IgnorePatternsHash,
52
52
53 /// How many bytes of `on_disk` are not used anymore
53 /// How many bytes of `on_disk` are not used anymore
54 pub(super) unreachable_bytes: u32,
54 pub(super) unreachable_bytes: u32,
55 }
55 }
56
56
57 /// Using a plain `HgPathBuf` of the full path from the repository root as a
57 /// Using a plain `HgPathBuf` of the full path from the repository root as a
58 /// map key would also work: all paths in a given map have the same parent
58 /// map key would also work: all paths in a given map have the same parent
59 /// path, so comparing full paths gives the same result as comparing base
59 /// path, so comparing full paths gives the same result as comparing base
60 /// names. However `HashMap` would waste time always re-hashing the same
60 /// names. However `HashMap` would waste time always re-hashing the same
61 /// string prefix.
61 /// string prefix.
62 pub(super) type NodeKey<'on_disk> = WithBasename<Cow<'on_disk, HgPath>>;
62 pub(super) type NodeKey<'on_disk> = WithBasename<Cow<'on_disk, HgPath>>;
63
63
64 /// Similar to `&'tree Cow<'on_disk, HgPath>`, but can also be returned
64 /// Similar to `&'tree Cow<'on_disk, HgPath>`, but can also be returned
65 /// for on-disk nodes that don’t actually have a `Cow` to borrow.
65 /// for on-disk nodes that don’t actually have a `Cow` to borrow.
66 pub(super) enum BorrowedPath<'tree, 'on_disk> {
66 pub(super) enum BorrowedPath<'tree, 'on_disk> {
67 InMemory(&'tree HgPathBuf),
67 InMemory(&'tree HgPathBuf),
68 OnDisk(&'on_disk HgPath),
68 OnDisk(&'on_disk HgPath),
69 }
69 }
70
70
71 pub(super) enum ChildNodes<'on_disk> {
71 pub(super) enum ChildNodes<'on_disk> {
72 InMemory(FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
72 InMemory(FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
73 OnDisk(&'on_disk [on_disk::Node]),
73 OnDisk(&'on_disk [on_disk::Node]),
74 }
74 }
75
75
76 pub(super) enum ChildNodesRef<'tree, 'on_disk> {
76 pub(super) enum ChildNodesRef<'tree, 'on_disk> {
77 InMemory(&'tree FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
77 InMemory(&'tree FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
78 OnDisk(&'on_disk [on_disk::Node]),
78 OnDisk(&'on_disk [on_disk::Node]),
79 }
79 }
80
80
81 pub(super) enum NodeRef<'tree, 'on_disk> {
81 pub(super) enum NodeRef<'tree, 'on_disk> {
82 InMemory(&'tree NodeKey<'on_disk>, &'tree Node<'on_disk>),
82 InMemory(&'tree NodeKey<'on_disk>, &'tree Node<'on_disk>),
83 OnDisk(&'on_disk on_disk::Node),
83 OnDisk(&'on_disk on_disk::Node),
84 }
84 }
85
85
86 impl<'tree, 'on_disk> BorrowedPath<'tree, 'on_disk> {
86 impl<'tree, 'on_disk> BorrowedPath<'tree, 'on_disk> {
87 pub fn detach_from_tree(&self) -> Cow<'on_disk, HgPath> {
87 pub fn detach_from_tree(&self) -> Cow<'on_disk, HgPath> {
88 match *self {
88 match *self {
89 BorrowedPath::InMemory(in_memory) => Cow::Owned(in_memory.clone()),
89 BorrowedPath::InMemory(in_memory) => Cow::Owned(in_memory.clone()),
90 BorrowedPath::OnDisk(on_disk) => Cow::Borrowed(on_disk),
90 BorrowedPath::OnDisk(on_disk) => Cow::Borrowed(on_disk),
91 }
91 }
92 }
92 }
93 }
93 }
94
94
95 impl<'tree, 'on_disk> std::ops::Deref for BorrowedPath<'tree, 'on_disk> {
95 impl<'tree, 'on_disk> std::ops::Deref for BorrowedPath<'tree, 'on_disk> {
96 type Target = HgPath;
96 type Target = HgPath;
97
97
98 fn deref(&self) -> &HgPath {
98 fn deref(&self) -> &HgPath {
99 match *self {
99 match *self {
100 BorrowedPath::InMemory(in_memory) => in_memory,
100 BorrowedPath::InMemory(in_memory) => in_memory,
101 BorrowedPath::OnDisk(on_disk) => on_disk,
101 BorrowedPath::OnDisk(on_disk) => on_disk,
102 }
102 }
103 }
103 }
104 }
104 }
105
105
106 impl Default for ChildNodes<'_> {
106 impl Default for ChildNodes<'_> {
107 fn default() -> Self {
107 fn default() -> Self {
108 ChildNodes::InMemory(Default::default())
108 ChildNodes::InMemory(Default::default())
109 }
109 }
110 }
110 }
111
111
112 impl<'on_disk> ChildNodes<'on_disk> {
112 impl<'on_disk> ChildNodes<'on_disk> {
113 pub(super) fn as_ref<'tree>(
113 pub(super) fn as_ref<'tree>(
114 &'tree self,
114 &'tree self,
115 ) -> ChildNodesRef<'tree, 'on_disk> {
115 ) -> ChildNodesRef<'tree, 'on_disk> {
116 match self {
116 match self {
117 ChildNodes::InMemory(nodes) => ChildNodesRef::InMemory(nodes),
117 ChildNodes::InMemory(nodes) => ChildNodesRef::InMemory(nodes),
118 ChildNodes::OnDisk(nodes) => ChildNodesRef::OnDisk(nodes),
118 ChildNodes::OnDisk(nodes) => ChildNodesRef::OnDisk(nodes),
119 }
119 }
120 }
120 }
121
121
122 pub(super) fn is_empty(&self) -> bool {
122 pub(super) fn is_empty(&self) -> bool {
123 match self {
123 match self {
124 ChildNodes::InMemory(nodes) => nodes.is_empty(),
124 ChildNodes::InMemory(nodes) => nodes.is_empty(),
125 ChildNodes::OnDisk(nodes) => nodes.is_empty(),
125 ChildNodes::OnDisk(nodes) => nodes.is_empty(),
126 }
126 }
127 }
127 }
128
128
129 fn make_mut(
129 fn make_mut(
130 &mut self,
130 &mut self,
131 on_disk: &'on_disk [u8],
131 on_disk: &'on_disk [u8],
132 unreachable_bytes: &mut u32,
132 unreachable_bytes: &mut u32,
133 ) -> Result<
133 ) -> Result<
134 &mut FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>,
134 &mut FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>,
135 DirstateV2ParseError,
135 DirstateV2ParseError,
136 > {
136 > {
137 match self {
137 match self {
138 ChildNodes::InMemory(nodes) => Ok(nodes),
138 ChildNodes::InMemory(nodes) => Ok(nodes),
139 ChildNodes::OnDisk(nodes) => {
139 ChildNodes::OnDisk(nodes) => {
140 *unreachable_bytes +=
140 *unreachable_bytes +=
141 std::mem::size_of_val::<[on_disk::Node]>(nodes) as u32;
141 std::mem::size_of_val::<[on_disk::Node]>(nodes) as u32;
142 let nodes = nodes
142 let nodes = nodes
143 .iter()
143 .iter()
144 .map(|node| {
144 .map(|node| {
145 Ok((
145 Ok((
146 node.path(on_disk)?,
146 node.path(on_disk)?,
147 node.to_in_memory_node(on_disk)?,
147 node.to_in_memory_node(on_disk)?,
148 ))
148 ))
149 })
149 })
150 .collect::<Result<_, _>>()?;
150 .collect::<Result<_, _>>()?;
151 *self = ChildNodes::InMemory(nodes);
151 *self = ChildNodes::InMemory(nodes);
152 match self {
152 match self {
153 ChildNodes::InMemory(nodes) => Ok(nodes),
153 ChildNodes::InMemory(nodes) => Ok(nodes),
154 ChildNodes::OnDisk(_) => unreachable!(),
154 ChildNodes::OnDisk(_) => unreachable!(),
155 }
155 }
156 }
156 }
157 }
157 }
158 }
158 }
159 }
159 }
160
160
161 impl<'tree, 'on_disk> ChildNodesRef<'tree, 'on_disk> {
161 impl<'tree, 'on_disk> ChildNodesRef<'tree, 'on_disk> {
162 pub(super) fn get(
162 pub(super) fn get(
163 &self,
163 &self,
164 base_name: &HgPath,
164 base_name: &HgPath,
165 on_disk: &'on_disk [u8],
165 on_disk: &'on_disk [u8],
166 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
166 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
167 match self {
167 match self {
168 ChildNodesRef::InMemory(nodes) => Ok(nodes
168 ChildNodesRef::InMemory(nodes) => Ok(nodes
169 .get_key_value(base_name)
169 .get_key_value(base_name)
170 .map(|(k, v)| NodeRef::InMemory(k, v))),
170 .map(|(k, v)| NodeRef::InMemory(k, v))),
171 ChildNodesRef::OnDisk(nodes) => {
171 ChildNodesRef::OnDisk(nodes) => {
172 let mut parse_result = Ok(());
172 let mut parse_result = Ok(());
173 let search_result = nodes.binary_search_by(|node| {
173 let search_result = nodes.binary_search_by(|node| {
174 match node.base_name(on_disk) {
174 match node.base_name(on_disk) {
175 Ok(node_base_name) => node_base_name.cmp(base_name),
175 Ok(node_base_name) => node_base_name.cmp(base_name),
176 Err(e) => {
176 Err(e) => {
177 parse_result = Err(e);
177 parse_result = Err(e);
178 // Dummy comparison result, `search_result` won’t
178 // Dummy comparison result, `search_result` won’t
179 // be used since `parse_result` is an error
179 // be used since `parse_result` is an error
180 std::cmp::Ordering::Equal
180 std::cmp::Ordering::Equal
181 }
181 }
182 }
182 }
183 });
183 });
184 parse_result.map(|()| {
184 parse_result.map(|()| {
185 search_result.ok().map(|i| NodeRef::OnDisk(&nodes[i]))
185 search_result.ok().map(|i| NodeRef::OnDisk(&nodes[i]))
186 })
186 })
187 }
187 }
188 }
188 }
189 }
189 }
190
190
191 /// Iterate in undefined order
191 /// Iterate in undefined order
192 pub(super) fn iter(
192 pub(super) fn iter(
193 &self,
193 &self,
194 ) -> impl Iterator<Item = NodeRef<'tree, 'on_disk>> {
194 ) -> impl Iterator<Item = NodeRef<'tree, 'on_disk>> {
195 match self {
195 match self {
196 ChildNodesRef::InMemory(nodes) => itertools::Either::Left(
196 ChildNodesRef::InMemory(nodes) => itertools::Either::Left(
197 nodes.iter().map(|(k, v)| NodeRef::InMemory(k, v)),
197 nodes.iter().map(|(k, v)| NodeRef::InMemory(k, v)),
198 ),
198 ),
199 ChildNodesRef::OnDisk(nodes) => {
199 ChildNodesRef::OnDisk(nodes) => {
200 itertools::Either::Right(nodes.iter().map(NodeRef::OnDisk))
200 itertools::Either::Right(nodes.iter().map(NodeRef::OnDisk))
201 }
201 }
202 }
202 }
203 }
203 }
204
204
205 /// Iterate in parallel in undefined order
205 /// Iterate in parallel in undefined order
206 pub(super) fn par_iter(
206 pub(super) fn par_iter(
207 &self,
207 &self,
208 ) -> impl rayon::iter::ParallelIterator<Item = NodeRef<'tree, 'on_disk>>
208 ) -> impl rayon::iter::ParallelIterator<Item = NodeRef<'tree, 'on_disk>>
209 {
209 {
210 use rayon::prelude::*;
210 use rayon::prelude::*;
211 match self {
211 match self {
212 ChildNodesRef::InMemory(nodes) => rayon::iter::Either::Left(
212 ChildNodesRef::InMemory(nodes) => rayon::iter::Either::Left(
213 nodes.par_iter().map(|(k, v)| NodeRef::InMemory(k, v)),
213 nodes.par_iter().map(|(k, v)| NodeRef::InMemory(k, v)),
214 ),
214 ),
215 ChildNodesRef::OnDisk(nodes) => rayon::iter::Either::Right(
215 ChildNodesRef::OnDisk(nodes) => rayon::iter::Either::Right(
216 nodes.par_iter().map(NodeRef::OnDisk),
216 nodes.par_iter().map(NodeRef::OnDisk),
217 ),
217 ),
218 }
218 }
219 }
219 }
220
220
221 pub(super) fn sorted(&self) -> Vec<NodeRef<'tree, 'on_disk>> {
221 pub(super) fn sorted(&self) -> Vec<NodeRef<'tree, 'on_disk>> {
222 match self {
222 match self {
223 ChildNodesRef::InMemory(nodes) => {
223 ChildNodesRef::InMemory(nodes) => {
224 let mut vec: Vec<_> = nodes
224 let mut vec: Vec<_> = nodes
225 .iter()
225 .iter()
226 .map(|(k, v)| NodeRef::InMemory(k, v))
226 .map(|(k, v)| NodeRef::InMemory(k, v))
227 .collect();
227 .collect();
228 fn sort_key<'a>(node: &'a NodeRef) -> &'a HgPath {
228 fn sort_key<'a>(node: &'a NodeRef) -> &'a HgPath {
229 match node {
229 match node {
230 NodeRef::InMemory(path, _node) => path.base_name(),
230 NodeRef::InMemory(path, _node) => path.base_name(),
231 NodeRef::OnDisk(_) => unreachable!(),
231 NodeRef::OnDisk(_) => unreachable!(),
232 }
232 }
233 }
233 }
234 // `sort_unstable_by_key` doesn’t allow keys borrowing from the
234 // `sort_unstable_by_key` doesn’t allow keys borrowing from the
235 // value: https://github.com/rust-lang/rust/issues/34162
235 // value: https://github.com/rust-lang/rust/issues/34162
236 vec.sort_unstable_by(|a, b| sort_key(a).cmp(sort_key(b)));
236 vec.sort_unstable_by(|a, b| sort_key(a).cmp(sort_key(b)));
237 vec
237 vec
238 }
238 }
239 ChildNodesRef::OnDisk(nodes) => {
239 ChildNodesRef::OnDisk(nodes) => {
240 // Nodes on disk are already sorted
240 // Nodes on disk are already sorted
241 nodes.iter().map(NodeRef::OnDisk).collect()
241 nodes.iter().map(NodeRef::OnDisk).collect()
242 }
242 }
243 }
243 }
244 }
244 }
245 }
245 }
246
246
247 impl<'tree, 'on_disk> NodeRef<'tree, 'on_disk> {
247 impl<'tree, 'on_disk> NodeRef<'tree, 'on_disk> {
248 pub(super) fn full_path(
248 pub(super) fn full_path(
249 &self,
249 &self,
250 on_disk: &'on_disk [u8],
250 on_disk: &'on_disk [u8],
251 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
251 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
252 match self {
252 match self {
253 NodeRef::InMemory(path, _node) => Ok(path.full_path()),
253 NodeRef::InMemory(path, _node) => Ok(path.full_path()),
254 NodeRef::OnDisk(node) => node.full_path(on_disk),
254 NodeRef::OnDisk(node) => node.full_path(on_disk),
255 }
255 }
256 }
256 }
257
257
258 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
258 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
259 /// HgPath>` detached from `'tree`
259 /// HgPath>` detached from `'tree`
260 pub(super) fn full_path_borrowed(
260 pub(super) fn full_path_borrowed(
261 &self,
261 &self,
262 on_disk: &'on_disk [u8],
262 on_disk: &'on_disk [u8],
263 ) -> Result<BorrowedPath<'tree, 'on_disk>, DirstateV2ParseError> {
263 ) -> Result<BorrowedPath<'tree, 'on_disk>, DirstateV2ParseError> {
264 match self {
264 match self {
265 NodeRef::InMemory(path, _node) => match path.full_path() {
265 NodeRef::InMemory(path, _node) => match path.full_path() {
266 Cow::Borrowed(on_disk) => Ok(BorrowedPath::OnDisk(on_disk)),
266 Cow::Borrowed(on_disk) => Ok(BorrowedPath::OnDisk(on_disk)),
267 Cow::Owned(in_memory) => Ok(BorrowedPath::InMemory(in_memory)),
267 Cow::Owned(in_memory) => Ok(BorrowedPath::InMemory(in_memory)),
268 },
268 },
269 NodeRef::OnDisk(node) => {
269 NodeRef::OnDisk(node) => {
270 Ok(BorrowedPath::OnDisk(node.full_path(on_disk)?))
270 Ok(BorrowedPath::OnDisk(node.full_path(on_disk)?))
271 }
271 }
272 }
272 }
273 }
273 }
274
274
275 pub(super) fn base_name(
275 pub(super) fn base_name(
276 &self,
276 &self,
277 on_disk: &'on_disk [u8],
277 on_disk: &'on_disk [u8],
278 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
278 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
279 match self {
279 match self {
280 NodeRef::InMemory(path, _node) => Ok(path.base_name()),
280 NodeRef::InMemory(path, _node) => Ok(path.base_name()),
281 NodeRef::OnDisk(node) => node.base_name(on_disk),
281 NodeRef::OnDisk(node) => node.base_name(on_disk),
282 }
282 }
283 }
283 }
284
284
285 pub(super) fn children(
285 pub(super) fn children(
286 &self,
286 &self,
287 on_disk: &'on_disk [u8],
287 on_disk: &'on_disk [u8],
288 ) -> Result<ChildNodesRef<'tree, 'on_disk>, DirstateV2ParseError> {
288 ) -> Result<ChildNodesRef<'tree, 'on_disk>, DirstateV2ParseError> {
289 match self {
289 match self {
290 NodeRef::InMemory(_path, node) => Ok(node.children.as_ref()),
290 NodeRef::InMemory(_path, node) => Ok(node.children.as_ref()),
291 NodeRef::OnDisk(node) => {
291 NodeRef::OnDisk(node) => {
292 Ok(ChildNodesRef::OnDisk(node.children(on_disk)?))
292 Ok(ChildNodesRef::OnDisk(node.children(on_disk)?))
293 }
293 }
294 }
294 }
295 }
295 }
296
296
297 pub(super) fn has_copy_source(&self) -> bool {
297 pub(super) fn has_copy_source(&self) -> bool {
298 match self {
298 match self {
299 NodeRef::InMemory(_path, node) => node.copy_source.is_some(),
299 NodeRef::InMemory(_path, node) => node.copy_source.is_some(),
300 NodeRef::OnDisk(node) => node.has_copy_source(),
300 NodeRef::OnDisk(node) => node.has_copy_source(),
301 }
301 }
302 }
302 }
303
303
304 pub(super) fn copy_source(
304 pub(super) fn copy_source(
305 &self,
305 &self,
306 on_disk: &'on_disk [u8],
306 on_disk: &'on_disk [u8],
307 ) -> Result<Option<&'tree HgPath>, DirstateV2ParseError> {
307 ) -> Result<Option<&'tree HgPath>, DirstateV2ParseError> {
308 match self {
308 match self {
309 NodeRef::InMemory(_path, node) => {
309 NodeRef::InMemory(_path, node) => {
310 Ok(node.copy_source.as_ref().map(|s| &**s))
310 Ok(node.copy_source.as_ref().map(|s| &**s))
311 }
311 }
312 NodeRef::OnDisk(node) => node.copy_source(on_disk),
312 NodeRef::OnDisk(node) => node.copy_source(on_disk),
313 }
313 }
314 }
314 }
315 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
315 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
316 /// HgPath>` detached from `'tree`
316 /// HgPath>` detached from `'tree`
317 pub(super) fn copy_source_borrowed(
317 pub(super) fn copy_source_borrowed(
318 &self,
318 &self,
319 on_disk: &'on_disk [u8],
319 on_disk: &'on_disk [u8],
320 ) -> Result<Option<BorrowedPath<'tree, 'on_disk>>, DirstateV2ParseError>
320 ) -> Result<Option<BorrowedPath<'tree, 'on_disk>>, DirstateV2ParseError>
321 {
321 {
322 Ok(match self {
322 Ok(match self {
323 NodeRef::InMemory(_path, node) => {
323 NodeRef::InMemory(_path, node) => {
324 node.copy_source.as_ref().map(|source| match source {
324 node.copy_source.as_ref().map(|source| match source {
325 Cow::Borrowed(on_disk) => BorrowedPath::OnDisk(on_disk),
325 Cow::Borrowed(on_disk) => BorrowedPath::OnDisk(on_disk),
326 Cow::Owned(in_memory) => BorrowedPath::InMemory(in_memory),
326 Cow::Owned(in_memory) => BorrowedPath::InMemory(in_memory),
327 })
327 })
328 }
328 }
329 NodeRef::OnDisk(node) => node
329 NodeRef::OnDisk(node) => node
330 .copy_source(on_disk)?
330 .copy_source(on_disk)?
331 .map(|source| BorrowedPath::OnDisk(source)),
331 .map(|source| BorrowedPath::OnDisk(source)),
332 })
332 })
333 }
333 }
334
334
335 pub(super) fn entry(
335 pub(super) fn entry(
336 &self,
336 &self,
337 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
337 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
338 match self {
338 match self {
339 NodeRef::InMemory(_path, node) => {
339 NodeRef::InMemory(_path, node) => {
340 Ok(node.data.as_entry().copied())
340 Ok(node.data.as_entry().copied())
341 }
341 }
342 NodeRef::OnDisk(node) => node.entry(),
342 NodeRef::OnDisk(node) => node.entry(),
343 }
343 }
344 }
344 }
345
345
346 pub(super) fn state(
346 pub(super) fn state(
347 &self,
347 &self,
348 ) -> Result<Option<EntryState>, DirstateV2ParseError> {
348 ) -> Result<Option<EntryState>, DirstateV2ParseError> {
349 Ok(self.entry()?.and_then(|e| {
349 Ok(self.entry()?.and_then(|e| {
350 if e.any_tracked() {
350 if e.any_tracked() {
351 Some(e.state())
351 Some(e.state())
352 } else {
352 } else {
353 None
353 None
354 }
354 }
355 }))
355 }))
356 }
356 }
357
357
358 pub(super) fn cached_directory_mtime(
358 pub(super) fn cached_directory_mtime(
359 &self,
359 &self,
360 ) -> Result<Option<TruncatedTimestamp>, DirstateV2ParseError> {
360 ) -> Result<Option<TruncatedTimestamp>, DirstateV2ParseError> {
361 match self {
361 match self {
362 NodeRef::InMemory(_path, node) => Ok(match node.data {
362 NodeRef::InMemory(_path, node) => Ok(match node.data {
363 NodeData::CachedDirectory { mtime } => Some(mtime),
363 NodeData::CachedDirectory { mtime } => Some(mtime),
364 _ => None,
364 _ => None,
365 }),
365 }),
366 NodeRef::OnDisk(node) => node.cached_directory_mtime(),
366 NodeRef::OnDisk(node) => node.cached_directory_mtime(),
367 }
367 }
368 }
368 }
369
369
370 pub(super) fn descendants_with_entry_count(&self) -> u32 {
370 pub(super) fn descendants_with_entry_count(&self) -> u32 {
371 match self {
371 match self {
372 NodeRef::InMemory(_path, node) => {
372 NodeRef::InMemory(_path, node) => {
373 node.descendants_with_entry_count
373 node.descendants_with_entry_count
374 }
374 }
375 NodeRef::OnDisk(node) => node.descendants_with_entry_count.get(),
375 NodeRef::OnDisk(node) => node.descendants_with_entry_count.get(),
376 }
376 }
377 }
377 }
378
378
379 pub(super) fn tracked_descendants_count(&self) -> u32 {
379 pub(super) fn tracked_descendants_count(&self) -> u32 {
380 match self {
380 match self {
381 NodeRef::InMemory(_path, node) => node.tracked_descendants_count,
381 NodeRef::InMemory(_path, node) => node.tracked_descendants_count,
382 NodeRef::OnDisk(node) => node.tracked_descendants_count.get(),
382 NodeRef::OnDisk(node) => node.tracked_descendants_count.get(),
383 }
383 }
384 }
384 }
385 }
385 }
386
386
387 /// Represents a file or a directory
387 /// Represents a file or a directory
388 #[derive(Default)]
388 #[derive(Default)]
389 pub(super) struct Node<'on_disk> {
389 pub(super) struct Node<'on_disk> {
390 pub(super) data: NodeData,
390 pub(super) data: NodeData,
391
391
392 pub(super) copy_source: Option<Cow<'on_disk, HgPath>>,
392 pub(super) copy_source: Option<Cow<'on_disk, HgPath>>,
393
393
394 pub(super) children: ChildNodes<'on_disk>,
394 pub(super) children: ChildNodes<'on_disk>,
395
395
396 /// How many (non-inclusive) descendants of this node have an entry.
396 /// How many (non-inclusive) descendants of this node have an entry.
397 pub(super) descendants_with_entry_count: u32,
397 pub(super) descendants_with_entry_count: u32,
398
398
399 /// How many (non-inclusive) descendants of this node have an entry whose
399 /// How many (non-inclusive) descendants of this node have an entry whose
400 /// state is "tracked".
400 /// state is "tracked".
401 pub(super) tracked_descendants_count: u32,
401 pub(super) tracked_descendants_count: u32,
402 }
402 }
403
403
404 pub(super) enum NodeData {
404 pub(super) enum NodeData {
405 Entry(DirstateEntry),
405 Entry(DirstateEntry),
406 CachedDirectory { mtime: TruncatedTimestamp },
406 CachedDirectory { mtime: TruncatedTimestamp },
407 None,
407 None,
408 }
408 }
409
409
410 impl Default for NodeData {
410 impl Default for NodeData {
411 fn default() -> Self {
411 fn default() -> Self {
412 NodeData::None
412 NodeData::None
413 }
413 }
414 }
414 }
415
415
416 impl NodeData {
416 impl NodeData {
417 fn has_entry(&self) -> bool {
417 fn has_entry(&self) -> bool {
418 match self {
418 match self {
419 NodeData::Entry(_) => true,
419 NodeData::Entry(_) => true,
420 _ => false,
420 _ => false,
421 }
421 }
422 }
422 }
423
423
424 fn as_entry(&self) -> Option<&DirstateEntry> {
424 fn as_entry(&self) -> Option<&DirstateEntry> {
425 match self {
425 match self {
426 NodeData::Entry(entry) => Some(entry),
426 NodeData::Entry(entry) => Some(entry),
427 _ => None,
427 _ => None,
428 }
428 }
429 }
429 }
430
430
431 fn as_entry_mut(&mut self) -> Option<&mut DirstateEntry> {
431 fn as_entry_mut(&mut self) -> Option<&mut DirstateEntry> {
432 match self {
432 match self {
433 NodeData::Entry(entry) => Some(entry),
433 NodeData::Entry(entry) => Some(entry),
434 _ => None,
434 _ => None,
435 }
435 }
436 }
436 }
437 }
437 }
438
438
439 impl<'on_disk> DirstateMap<'on_disk> {
439 impl<'on_disk> DirstateMap<'on_disk> {
440 pub(super) fn empty(on_disk: &'on_disk [u8]) -> Self {
440 pub(super) fn empty(on_disk: &'on_disk [u8]) -> Self {
441 Self {
441 Self {
442 on_disk,
442 on_disk,
443 root: ChildNodes::default(),
443 root: ChildNodes::default(),
444 nodes_with_entry_count: 0,
444 nodes_with_entry_count: 0,
445 nodes_with_copy_source_count: 0,
445 nodes_with_copy_source_count: 0,
446 ignore_patterns_hash: [0; on_disk::IGNORE_PATTERNS_HASH_LEN],
446 ignore_patterns_hash: [0; on_disk::IGNORE_PATTERNS_HASH_LEN],
447 unreachable_bytes: 0,
447 unreachable_bytes: 0,
448 }
448 }
449 }
449 }
450
450
451 #[timed]
451 #[timed]
452 pub fn new_v2(
452 pub fn new_v2(
453 on_disk: &'on_disk [u8],
453 on_disk: &'on_disk [u8],
454 data_size: usize,
454 data_size: usize,
455 metadata: &[u8],
455 metadata: &[u8],
456 ) -> Result<Self, DirstateError> {
456 ) -> Result<Self, DirstateError> {
457 if let Some(data) = on_disk.get(..data_size) {
457 if let Some(data) = on_disk.get(..data_size) {
458 Ok(on_disk::read(data, metadata)?)
458 Ok(on_disk::read(data, metadata)?)
459 } else {
459 } else {
460 Err(DirstateV2ParseError.into())
460 Err(DirstateV2ParseError.into())
461 }
461 }
462 }
462 }
463
463
464 #[timed]
464 #[timed]
465 pub fn new_v1(
465 pub fn new_v1(
466 on_disk: &'on_disk [u8],
466 on_disk: &'on_disk [u8],
467 ) -> Result<(Self, Option<DirstateParents>), DirstateError> {
467 ) -> Result<(Self, Option<DirstateParents>), DirstateError> {
468 let mut map = Self::empty(on_disk);
468 let mut map = Self::empty(on_disk);
469 if map.on_disk.is_empty() {
469 if map.on_disk.is_empty() {
470 return Ok((map, None));
470 return Ok((map, None));
471 }
471 }
472
472
473 let parents = parse_dirstate_entries(
473 let parents = parse_dirstate_entries(
474 map.on_disk,
474 map.on_disk,
475 |path, entry, copy_source| {
475 |path, entry, copy_source| {
476 let tracked = entry.state().is_tracked();
476 let tracked = entry.state().is_tracked();
477 let node = Self::get_or_insert_node(
477 let node = Self::get_or_insert_node(
478 map.on_disk,
478 map.on_disk,
479 &mut map.unreachable_bytes,
479 &mut map.unreachable_bytes,
480 &mut map.root,
480 &mut map.root,
481 path,
481 path,
482 WithBasename::to_cow_borrowed,
482 WithBasename::to_cow_borrowed,
483 |ancestor| {
483 |ancestor| {
484 if tracked {
484 if tracked {
485 ancestor.tracked_descendants_count += 1
485 ancestor.tracked_descendants_count += 1
486 }
486 }
487 ancestor.descendants_with_entry_count += 1
487 ancestor.descendants_with_entry_count += 1
488 },
488 },
489 )?;
489 )?;
490 assert!(
490 assert!(
491 !node.data.has_entry(),
491 !node.data.has_entry(),
492 "duplicate dirstate entry in read"
492 "duplicate dirstate entry in read"
493 );
493 );
494 assert!(
494 assert!(
495 node.copy_source.is_none(),
495 node.copy_source.is_none(),
496 "duplicate dirstate entry in read"
496 "duplicate dirstate entry in read"
497 );
497 );
498 node.data = NodeData::Entry(*entry);
498 node.data = NodeData::Entry(*entry);
499 node.copy_source = copy_source.map(Cow::Borrowed);
499 node.copy_source = copy_source.map(Cow::Borrowed);
500 map.nodes_with_entry_count += 1;
500 map.nodes_with_entry_count += 1;
501 if copy_source.is_some() {
501 if copy_source.is_some() {
502 map.nodes_with_copy_source_count += 1
502 map.nodes_with_copy_source_count += 1
503 }
503 }
504 Ok(())
504 Ok(())
505 },
505 },
506 )?;
506 )?;
507 let parents = Some(parents.clone());
507 let parents = Some(parents.clone());
508
508
509 Ok((map, parents))
509 Ok((map, parents))
510 }
510 }
511
511
512 /// Assuming dirstate-v2 format, returns whether the next write should
512 /// Assuming dirstate-v2 format, returns whether the next write should
513 /// append to the existing data file that contains `self.on_disk` (true),
513 /// append to the existing data file that contains `self.on_disk` (true),
514 /// or create a new data file from scratch (false).
514 /// or create a new data file from scratch (false).
515 pub(super) fn write_should_append(&self) -> bool {
515 pub(super) fn write_should_append(&self) -> bool {
516 let ratio = self.unreachable_bytes as f32 / self.on_disk.len() as f32;
516 let ratio = self.unreachable_bytes as f32 / self.on_disk.len() as f32;
517 ratio < ACCEPTABLE_UNREACHABLE_BYTES_RATIO
517 ratio < ACCEPTABLE_UNREACHABLE_BYTES_RATIO
518 }
518 }
519
519
520 fn get_node<'tree>(
520 fn get_node<'tree>(
521 &'tree self,
521 &'tree self,
522 path: &HgPath,
522 path: &HgPath,
523 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
523 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
524 let mut children = self.root.as_ref();
524 let mut children = self.root.as_ref();
525 let mut components = path.components();
525 let mut components = path.components();
526 let mut component =
526 let mut component =
527 components.next().expect("expected at least one components");
527 components.next().expect("expected at least one components");
528 loop {
528 loop {
529 if let Some(child) = children.get(component, self.on_disk)? {
529 if let Some(child) = children.get(component, self.on_disk)? {
530 if let Some(next_component) = components.next() {
530 if let Some(next_component) = components.next() {
531 component = next_component;
531 component = next_component;
532 children = child.children(self.on_disk)?;
532 children = child.children(self.on_disk)?;
533 } else {
533 } else {
534 return Ok(Some(child));
534 return Ok(Some(child));
535 }
535 }
536 } else {
536 } else {
537 return Ok(None);
537 return Ok(None);
538 }
538 }
539 }
539 }
540 }
540 }
541
541
542 /// Returns a mutable reference to the node at `path` if it exists
542 /// Returns a mutable reference to the node at `path` if it exists
543 ///
543 ///
544 /// This takes `root` instead of `&mut self` so that callers can mutate
544 /// This takes `root` instead of `&mut self` so that callers can mutate
545 /// other fields while the returned borrow is still valid
545 /// other fields while the returned borrow is still valid
546 fn get_node_mut<'tree>(
546 fn get_node_mut<'tree>(
547 on_disk: &'on_disk [u8],
547 on_disk: &'on_disk [u8],
548 unreachable_bytes: &mut u32,
548 unreachable_bytes: &mut u32,
549 root: &'tree mut ChildNodes<'on_disk>,
549 root: &'tree mut ChildNodes<'on_disk>,
550 path: &HgPath,
550 path: &HgPath,
551 ) -> Result<Option<&'tree mut Node<'on_disk>>, DirstateV2ParseError> {
551 ) -> Result<Option<&'tree mut Node<'on_disk>>, DirstateV2ParseError> {
552 let mut children = root;
552 let mut children = root;
553 let mut components = path.components();
553 let mut components = path.components();
554 let mut component =
554 let mut component =
555 components.next().expect("expected at least one components");
555 components.next().expect("expected at least one components");
556 loop {
556 loop {
557 if let Some(child) = children
557 if let Some(child) = children
558 .make_mut(on_disk, unreachable_bytes)?
558 .make_mut(on_disk, unreachable_bytes)?
559 .get_mut(component)
559 .get_mut(component)
560 {
560 {
561 if let Some(next_component) = components.next() {
561 if let Some(next_component) = components.next() {
562 component = next_component;
562 component = next_component;
563 children = &mut child.children;
563 children = &mut child.children;
564 } else {
564 } else {
565 return Ok(Some(child));
565 return Ok(Some(child));
566 }
566 }
567 } else {
567 } else {
568 return Ok(None);
568 return Ok(None);
569 }
569 }
570 }
570 }
571 }
571 }
572
572
573 pub(super) fn get_or_insert<'tree, 'path>(
573 pub(super) fn get_or_insert<'tree, 'path>(
574 &'tree mut self,
574 &'tree mut self,
575 path: &HgPath,
575 path: &HgPath,
576 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
576 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
577 Self::get_or_insert_node(
577 Self::get_or_insert_node(
578 self.on_disk,
578 self.on_disk,
579 &mut self.unreachable_bytes,
579 &mut self.unreachable_bytes,
580 &mut self.root,
580 &mut self.root,
581 path,
581 path,
582 WithBasename::to_cow_owned,
582 WithBasename::to_cow_owned,
583 |_| {},
583 |_| {},
584 )
584 )
585 }
585 }
586
586
587 fn get_or_insert_node<'tree, 'path>(
587 fn get_or_insert_node<'tree, 'path>(
588 on_disk: &'on_disk [u8],
588 on_disk: &'on_disk [u8],
589 unreachable_bytes: &mut u32,
589 unreachable_bytes: &mut u32,
590 root: &'tree mut ChildNodes<'on_disk>,
590 root: &'tree mut ChildNodes<'on_disk>,
591 path: &'path HgPath,
591 path: &'path HgPath,
592 to_cow: impl Fn(
592 to_cow: impl Fn(
593 WithBasename<&'path HgPath>,
593 WithBasename<&'path HgPath>,
594 ) -> WithBasename<Cow<'on_disk, HgPath>>,
594 ) -> WithBasename<Cow<'on_disk, HgPath>>,
595 mut each_ancestor: impl FnMut(&mut Node),
595 mut each_ancestor: impl FnMut(&mut Node),
596 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
596 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
597 let mut child_nodes = root;
597 let mut child_nodes = root;
598 let mut inclusive_ancestor_paths =
598 let mut inclusive_ancestor_paths =
599 WithBasename::inclusive_ancestors_of(path);
599 WithBasename::inclusive_ancestors_of(path);
600 let mut ancestor_path = inclusive_ancestor_paths
600 let mut ancestor_path = inclusive_ancestor_paths
601 .next()
601 .next()
602 .expect("expected at least one inclusive ancestor");
602 .expect("expected at least one inclusive ancestor");
603 loop {
603 loop {
604 let (_, child_node) = child_nodes
604 let (_, child_node) = child_nodes
605 .make_mut(on_disk, unreachable_bytes)?
605 .make_mut(on_disk, unreachable_bytes)?
606 .raw_entry_mut()
606 .raw_entry_mut()
607 .from_key(ancestor_path.base_name())
607 .from_key(ancestor_path.base_name())
608 .or_insert_with(|| (to_cow(ancestor_path), Node::default()));
608 .or_insert_with(|| (to_cow(ancestor_path), Node::default()));
609 if let Some(next) = inclusive_ancestor_paths.next() {
609 if let Some(next) = inclusive_ancestor_paths.next() {
610 each_ancestor(child_node);
610 each_ancestor(child_node);
611 ancestor_path = next;
611 ancestor_path = next;
612 child_nodes = &mut child_node.children;
612 child_nodes = &mut child_node.children;
613 } else {
613 } else {
614 return Ok(child_node);
614 return Ok(child_node);
615 }
615 }
616 }
616 }
617 }
617 }
618
618
619 fn reset_state(
619 fn reset_state(
620 &mut self,
620 &mut self,
621 filename: &HgPath,
621 filename: &HgPath,
622 old_entry_opt: Option<DirstateEntry>,
622 old_entry_opt: Option<DirstateEntry>,
623 wc_tracked: bool,
623 wc_tracked: bool,
624 p1_tracked: bool,
624 p1_tracked: bool,
625 p2_info: bool,
625 p2_info: bool,
626 has_meaningful_mtime: bool,
626 has_meaningful_mtime: bool,
627 parent_file_data_opt: Option<ParentFileData>,
627 parent_file_data_opt: Option<ParentFileData>,
628 ) -> Result<(), DirstateError> {
628 ) -> Result<(), DirstateError> {
629 let (had_entry, was_tracked) = match old_entry_opt {
629 let (had_entry, was_tracked) = match old_entry_opt {
630 Some(old_entry) => (true, old_entry.tracked()),
630 Some(old_entry) => (true, old_entry.tracked()),
631 None => (false, false),
631 None => (false, false),
632 };
632 };
633 let node = Self::get_or_insert_node(
633 let node = Self::get_or_insert_node(
634 self.on_disk,
634 self.on_disk,
635 &mut self.unreachable_bytes,
635 &mut self.unreachable_bytes,
636 &mut self.root,
636 &mut self.root,
637 filename,
637 filename,
638 WithBasename::to_cow_owned,
638 WithBasename::to_cow_owned,
639 |ancestor| {
639 |ancestor| {
640 if !had_entry {
640 if !had_entry {
641 ancestor.descendants_with_entry_count += 1;
641 ancestor.descendants_with_entry_count += 1;
642 }
642 }
643 if was_tracked {
643 if was_tracked {
644 if !wc_tracked {
644 if !wc_tracked {
645 ancestor.tracked_descendants_count = ancestor
645 ancestor.tracked_descendants_count = ancestor
646 .tracked_descendants_count
646 .tracked_descendants_count
647 .checked_sub(1)
647 .checked_sub(1)
648 .expect("tracked count to be >= 0");
648 .expect("tracked count to be >= 0");
649 }
649 }
650 } else {
650 } else {
651 if wc_tracked {
651 if wc_tracked {
652 ancestor.tracked_descendants_count += 1;
652 ancestor.tracked_descendants_count += 1;
653 }
653 }
654 }
654 }
655 },
655 },
656 )?;
656 )?;
657
657
658 let v2_data = if let Some(parent_file_data) = parent_file_data_opt {
658 let v2_data = if let Some(parent_file_data) = parent_file_data_opt {
659 DirstateV2Data {
659 DirstateV2Data {
660 wc_tracked,
660 wc_tracked,
661 p1_tracked,
661 p1_tracked,
662 p2_info,
662 p2_info,
663 mode_size: parent_file_data.mode_size,
663 mode_size: parent_file_data.mode_size,
664 mtime: if has_meaningful_mtime {
664 mtime: if has_meaningful_mtime {
665 parent_file_data.mtime
665 parent_file_data.mtime
666 } else {
666 } else {
667 None
667 None
668 },
668 },
669 ..Default::default()
669 ..Default::default()
670 }
670 }
671 } else {
671 } else {
672 DirstateV2Data {
672 DirstateV2Data {
673 wc_tracked,
673 wc_tracked,
674 p1_tracked,
674 p1_tracked,
675 p2_info,
675 p2_info,
676 ..Default::default()
676 ..Default::default()
677 }
677 }
678 };
678 };
679 if !had_entry {
679 if !had_entry {
680 self.nodes_with_entry_count += 1;
680 self.nodes_with_entry_count += 1;
681 }
681 }
682 node.data = NodeData::Entry(DirstateEntry::from_v2_data(v2_data));
682 node.data = NodeData::Entry(DirstateEntry::from_v2_data(v2_data));
683 Ok(())
683 Ok(())
684 }
684 }
685
685
686 fn set_tracked(
686 fn set_tracked(
687 &mut self,
687 &mut self,
688 filename: &HgPath,
688 filename: &HgPath,
689 old_entry_opt: Option<DirstateEntry>,
689 old_entry_opt: Option<DirstateEntry>,
690 ) -> Result<bool, DirstateV2ParseError> {
690 ) -> Result<bool, DirstateV2ParseError> {
691 let was_tracked = old_entry_opt.map_or(false, |e| e.tracked());
691 let was_tracked = old_entry_opt.map_or(false, |e| e.tracked());
692 let had_entry = old_entry_opt.is_some();
692 let had_entry = old_entry_opt.is_some();
693 let tracked_count_increment = if was_tracked { 0 } else { 1 };
693 let tracked_count_increment = if was_tracked { 0 } else { 1 };
694 let mut new = false;
694 let mut new = false;
695
695
696 let node = Self::get_or_insert_node(
696 let node = Self::get_or_insert_node(
697 self.on_disk,
697 self.on_disk,
698 &mut self.unreachable_bytes,
698 &mut self.unreachable_bytes,
699 &mut self.root,
699 &mut self.root,
700 filename,
700 filename,
701 WithBasename::to_cow_owned,
701 WithBasename::to_cow_owned,
702 |ancestor| {
702 |ancestor| {
703 if !had_entry {
703 if !had_entry {
704 ancestor.descendants_with_entry_count += 1;
704 ancestor.descendants_with_entry_count += 1;
705 }
705 }
706
706
707 ancestor.tracked_descendants_count += tracked_count_increment;
707 ancestor.tracked_descendants_count += tracked_count_increment;
708 },
708 },
709 )?;
709 )?;
710 let new_entry = if let Some(old_entry) = old_entry_opt {
710 let new_entry = if let Some(old_entry) = old_entry_opt {
711 let mut e = old_entry.clone();
711 let mut e = old_entry.clone();
712 if e.tracked() {
712 if e.tracked() {
713 // XXX
713 // XXX
714 // This is probably overkill for more case, but we need this to
714 // This is probably overkill for more case, but we need this to
715 // fully replace the `normallookup` call with `set_tracked`
715 // fully replace the `normallookup` call with `set_tracked`
716 // one. Consider smoothing this in the future.
716 // one. Consider smoothing this in the future.
717 e.set_possibly_dirty();
717 e.set_possibly_dirty();
718 } else {
718 } else {
719 new = true;
719 new = true;
720 e.set_tracked();
720 e.set_tracked();
721 }
721 }
722 e
722 e
723 } else {
723 } else {
724 self.nodes_with_entry_count += 1;
724 self.nodes_with_entry_count += 1;
725 new = true;
725 new = true;
726 DirstateEntry::new_tracked()
726 DirstateEntry::new_tracked()
727 };
727 };
728 node.data = NodeData::Entry(new_entry);
728 node.data = NodeData::Entry(new_entry);
729 Ok(new)
729 Ok(new)
730 }
730 }
731
731
732 fn add_or_remove_file(
732 fn add_or_remove_file(
733 &mut self,
733 &mut self,
734 path: &HgPath,
734 path: &HgPath,
735 old_state: Option<EntryState>,
735 old_state: Option<EntryState>,
736 new_entry: DirstateEntry,
736 new_entry: DirstateEntry,
737 ) -> Result<(), DirstateV2ParseError> {
737 ) -> Result<(), DirstateV2ParseError> {
738 let had_entry = old_state.is_some();
738 let had_entry = old_state.is_some();
739 let was_tracked = old_state.map_or(false, |s| s.is_tracked());
739 let was_tracked = old_state.map_or(false, |s| s.is_tracked());
740 let tracked_count_increment =
740 let tracked_count_increment =
741 match (was_tracked, new_entry.state().is_tracked()) {
741 match (was_tracked, new_entry.state().is_tracked()) {
742 (false, true) => 1,
742 (false, true) => 1,
743 (true, false) => -1,
743 (true, false) => -1,
744 _ => 0,
744 _ => 0,
745 };
745 };
746
746
747 let node = Self::get_or_insert_node(
747 let node = Self::get_or_insert_node(
748 self.on_disk,
748 self.on_disk,
749 &mut self.unreachable_bytes,
749 &mut self.unreachable_bytes,
750 &mut self.root,
750 &mut self.root,
751 path,
751 path,
752 WithBasename::to_cow_owned,
752 WithBasename::to_cow_owned,
753 |ancestor| {
753 |ancestor| {
754 if !had_entry {
754 if !had_entry {
755 ancestor.descendants_with_entry_count += 1;
755 ancestor.descendants_with_entry_count += 1;
756 }
756 }
757
757
758 // We can’t use `+= increment` because the counter is unsigned,
758 // We can’t use `+= increment` because the counter is unsigned,
759 // and we want debug builds to detect accidental underflow
759 // and we want debug builds to detect accidental underflow
760 // through zero
760 // through zero
761 match tracked_count_increment {
761 match tracked_count_increment {
762 1 => ancestor.tracked_descendants_count += 1,
762 1 => ancestor.tracked_descendants_count += 1,
763 -1 => ancestor.tracked_descendants_count -= 1,
763 -1 => ancestor.tracked_descendants_count -= 1,
764 _ => {}
764 _ => {}
765 }
765 }
766 },
766 },
767 )?;
767 )?;
768 if !had_entry {
768 if !had_entry {
769 self.nodes_with_entry_count += 1
769 self.nodes_with_entry_count += 1
770 }
770 }
771 node.data = NodeData::Entry(new_entry);
771 node.data = NodeData::Entry(new_entry);
772 Ok(())
772 Ok(())
773 }
773 }
774
774
775 /// It is the responsibility of the caller to know that there was an entry
776 /// there before. Does not handle the removal of copy source
777 fn set_untracked(
778 &mut self,
779 filename: &HgPath,
780 old_entry: DirstateEntry,
781 ) -> Result<(), DirstateV2ParseError> {
782 let node = Self::get_or_insert_node(
783 self.on_disk,
784 &mut self.unreachable_bytes,
785 &mut self.root,
786 filename,
787 WithBasename::to_cow_owned,
788 |ancestor| {
789 ancestor.tracked_descendants_count = ancestor
790 .tracked_descendants_count
791 .checked_sub(1)
792 .expect("tracked_descendants_count should be >= 0");
793 },
794 )?;
795 let mut new_entry = old_entry.clone();
796 new_entry.set_untracked();
797 node.data = NodeData::Entry(new_entry);
798 Ok(())
799 }
800
775 fn set_clean(
801 fn set_clean(
776 &mut self,
802 &mut self,
777 filename: &HgPath,
803 filename: &HgPath,
778 old_entry: DirstateEntry,
804 old_entry: DirstateEntry,
779 mode: u32,
805 mode: u32,
780 size: u32,
806 size: u32,
781 mtime: TruncatedTimestamp,
807 mtime: TruncatedTimestamp,
782 ) -> Result<(), DirstateError> {
808 ) -> Result<(), DirstateError> {
783 let node = Self::get_or_insert_node(
809 let node = Self::get_or_insert_node(
784 self.on_disk,
810 self.on_disk,
785 &mut self.unreachable_bytes,
811 &mut self.unreachable_bytes,
786 &mut self.root,
812 &mut self.root,
787 filename,
813 filename,
788 WithBasename::to_cow_owned,
814 WithBasename::to_cow_owned,
789 |ancestor| {
815 |ancestor| {
790 if !old_entry.tracked() {
816 if !old_entry.tracked() {
791 ancestor.tracked_descendants_count += 1;
817 ancestor.tracked_descendants_count += 1;
792 }
818 }
793 },
819 },
794 )?;
820 )?;
795 let mut new_entry = old_entry.clone();
821 let mut new_entry = old_entry.clone();
796 new_entry.set_clean(mode, size, mtime);
822 new_entry.set_clean(mode, size, mtime);
797 node.data = NodeData::Entry(new_entry);
823 node.data = NodeData::Entry(new_entry);
798 Ok(())
824 Ok(())
799 }
825 }
800
826
801 fn set_possibly_dirty(
827 fn set_possibly_dirty(
802 &mut self,
828 &mut self,
803 filename: &HgPath,
829 filename: &HgPath,
804 ) -> Result<(), DirstateError> {
830 ) -> Result<(), DirstateError> {
805 let node = Self::get_or_insert_node(
831 let node = Self::get_or_insert_node(
806 self.on_disk,
832 self.on_disk,
807 &mut self.unreachable_bytes,
833 &mut self.unreachable_bytes,
808 &mut self.root,
834 &mut self.root,
809 filename,
835 filename,
810 WithBasename::to_cow_owned,
836 WithBasename::to_cow_owned,
811 |_ancestor| {},
837 |_ancestor| {},
812 )?;
838 )?;
813 let entry = node.data.as_entry_mut().expect("entry should exist");
839 let entry = node.data.as_entry_mut().expect("entry should exist");
814 entry.set_possibly_dirty();
840 entry.set_possibly_dirty();
815 node.data = NodeData::Entry(*entry);
841 node.data = NodeData::Entry(*entry);
816 Ok(())
842 Ok(())
817 }
843 }
818
844
819 fn iter_nodes<'tree>(
845 fn iter_nodes<'tree>(
820 &'tree self,
846 &'tree self,
821 ) -> impl Iterator<
847 ) -> impl Iterator<
822 Item = Result<NodeRef<'tree, 'on_disk>, DirstateV2ParseError>,
848 Item = Result<NodeRef<'tree, 'on_disk>, DirstateV2ParseError>,
823 > + 'tree {
849 > + 'tree {
824 // Depth first tree traversal.
850 // Depth first tree traversal.
825 //
851 //
826 // If we could afford internal iteration and recursion,
852 // If we could afford internal iteration and recursion,
827 // this would look like:
853 // this would look like:
828 //
854 //
829 // ```
855 // ```
830 // fn traverse_children(
856 // fn traverse_children(
831 // children: &ChildNodes,
857 // children: &ChildNodes,
832 // each: &mut impl FnMut(&Node),
858 // each: &mut impl FnMut(&Node),
833 // ) {
859 // ) {
834 // for child in children.values() {
860 // for child in children.values() {
835 // traverse_children(&child.children, each);
861 // traverse_children(&child.children, each);
836 // each(child);
862 // each(child);
837 // }
863 // }
838 // }
864 // }
839 // ```
865 // ```
840 //
866 //
841 // However we want an external iterator and therefore can’t use the
867 // However we want an external iterator and therefore can’t use the
842 // call stack. Use an explicit stack instead:
868 // call stack. Use an explicit stack instead:
843 let mut stack = Vec::new();
869 let mut stack = Vec::new();
844 let mut iter = self.root.as_ref().iter();
870 let mut iter = self.root.as_ref().iter();
845 std::iter::from_fn(move || {
871 std::iter::from_fn(move || {
846 while let Some(child_node) = iter.next() {
872 while let Some(child_node) = iter.next() {
847 let children = match child_node.children(self.on_disk) {
873 let children = match child_node.children(self.on_disk) {
848 Ok(children) => children,
874 Ok(children) => children,
849 Err(error) => return Some(Err(error)),
875 Err(error) => return Some(Err(error)),
850 };
876 };
851 // Pseudo-recursion
877 // Pseudo-recursion
852 let new_iter = children.iter();
878 let new_iter = children.iter();
853 let old_iter = std::mem::replace(&mut iter, new_iter);
879 let old_iter = std::mem::replace(&mut iter, new_iter);
854 stack.push((child_node, old_iter));
880 stack.push((child_node, old_iter));
855 }
881 }
856 // Found the end of a `children.iter()` iterator.
882 // Found the end of a `children.iter()` iterator.
857 if let Some((child_node, next_iter)) = stack.pop() {
883 if let Some((child_node, next_iter)) = stack.pop() {
858 // "Return" from pseudo-recursion by restoring state from the
884 // "Return" from pseudo-recursion by restoring state from the
859 // explicit stack
885 // explicit stack
860 iter = next_iter;
886 iter = next_iter;
861
887
862 Some(Ok(child_node))
888 Some(Ok(child_node))
863 } else {
889 } else {
864 // Reached the bottom of the stack, we’re done
890 // Reached the bottom of the stack, we’re done
865 None
891 None
866 }
892 }
867 })
893 })
868 }
894 }
869
895
870 fn count_dropped_path(unreachable_bytes: &mut u32, path: &Cow<HgPath>) {
896 fn count_dropped_path(unreachable_bytes: &mut u32, path: &Cow<HgPath>) {
871 if let Cow::Borrowed(path) = path {
897 if let Cow::Borrowed(path) = path {
872 *unreachable_bytes += path.len() as u32
898 *unreachable_bytes += path.len() as u32
873 }
899 }
874 }
900 }
875 }
901 }
876
902
877 /// Like `Iterator::filter_map`, but over a fallible iterator of `Result`s.
903 /// Like `Iterator::filter_map`, but over a fallible iterator of `Result`s.
878 ///
904 ///
879 /// The callback is only called for incoming `Ok` values. Errors are passed
905 /// The callback is only called for incoming `Ok` values. Errors are passed
880 /// through as-is. In order to let it use the `?` operator the callback is
906 /// through as-is. In order to let it use the `?` operator the callback is
881 /// expected to return a `Result` of `Option`, instead of an `Option` of
907 /// expected to return a `Result` of `Option`, instead of an `Option` of
882 /// `Result`.
908 /// `Result`.
883 fn filter_map_results<'a, I, F, A, B, E>(
909 fn filter_map_results<'a, I, F, A, B, E>(
884 iter: I,
910 iter: I,
885 f: F,
911 f: F,
886 ) -> impl Iterator<Item = Result<B, E>> + 'a
912 ) -> impl Iterator<Item = Result<B, E>> + 'a
887 where
913 where
888 I: Iterator<Item = Result<A, E>> + 'a,
914 I: Iterator<Item = Result<A, E>> + 'a,
889 F: Fn(A) -> Result<Option<B>, E> + 'a,
915 F: Fn(A) -> Result<Option<B>, E> + 'a,
890 {
916 {
891 iter.filter_map(move |result| match result {
917 iter.filter_map(move |result| match result {
892 Ok(node) => f(node).transpose(),
918 Ok(node) => f(node).transpose(),
893 Err(e) => Some(Err(e)),
919 Err(e) => Some(Err(e)),
894 })
920 })
895 }
921 }
896
922
897 impl OwningDirstateMap {
923 impl OwningDirstateMap {
898 pub fn clear(&mut self) {
924 pub fn clear(&mut self) {
899 self.with_dmap_mut(|map| {
925 self.with_dmap_mut(|map| {
900 map.root = Default::default();
926 map.root = Default::default();
901 map.nodes_with_entry_count = 0;
927 map.nodes_with_entry_count = 0;
902 map.nodes_with_copy_source_count = 0;
928 map.nodes_with_copy_source_count = 0;
903 });
929 });
904 }
930 }
905
931
906 pub fn set_entry(
932 pub fn set_entry(
907 &mut self,
933 &mut self,
908 filename: &HgPath,
934 filename: &HgPath,
909 entry: DirstateEntry,
935 entry: DirstateEntry,
910 ) -> Result<(), DirstateV2ParseError> {
936 ) -> Result<(), DirstateV2ParseError> {
911 self.with_dmap_mut(|map| {
937 self.with_dmap_mut(|map| {
912 map.get_or_insert(&filename)?.data = NodeData::Entry(entry);
938 map.get_or_insert(&filename)?.data = NodeData::Entry(entry);
913 Ok(())
939 Ok(())
914 })
940 })
915 }
941 }
916
942
917 pub fn add_file(
943 pub fn add_file(
918 &mut self,
944 &mut self,
919 filename: &HgPath,
945 filename: &HgPath,
920 entry: DirstateEntry,
946 entry: DirstateEntry,
921 ) -> Result<(), DirstateError> {
947 ) -> Result<(), DirstateError> {
922 let old_state = self.get(filename)?.map(|e| e.state());
948 let old_state = self.get(filename)?.map(|e| e.state());
923 self.with_dmap_mut(|map| {
949 self.with_dmap_mut(|map| {
924 Ok(map.add_or_remove_file(filename, old_state, entry)?)
950 Ok(map.add_or_remove_file(filename, old_state, entry)?)
925 })
951 })
926 }
952 }
927
953
928 pub fn set_tracked(
954 pub fn set_tracked(
929 &mut self,
955 &mut self,
930 filename: &HgPath,
956 filename: &HgPath,
931 ) -> Result<bool, DirstateV2ParseError> {
957 ) -> Result<bool, DirstateV2ParseError> {
932 let old_entry_opt = self.get(filename)?;
958 let old_entry_opt = self.get(filename)?;
933 self.with_dmap_mut(|map| map.set_tracked(filename, old_entry_opt))
959 self.with_dmap_mut(|map| map.set_tracked(filename, old_entry_opt))
934 }
960 }
935
961
962 pub fn set_untracked(
963 &mut self,
964 filename: &HgPath,
965 ) -> Result<bool, DirstateError> {
966 let old_entry_opt = self.get(filename)?;
967 match old_entry_opt {
968 None => Ok(false),
969 Some(old_entry) => {
970 if !old_entry.tracked() {
971 // `DirstateMap::set_untracked` is not a noop if
972 // already not tracked as it will decrement the
973 // tracked counters while going down.
974 return Ok(true);
975 }
976 if old_entry.added() {
977 // Untracking an "added" entry will just result in a
978 // worthless entry (and other parts of the code will
979 // complain about it), just drop it entirely.
980 self.drop_entry_and_copy_source(filename)?;
981 return Ok(true);
982 }
983 if !old_entry.p2_info() {
984 self.copy_map_remove(filename)?;
985 }
986
987 self.with_dmap_mut(|map| {
988 map.set_untracked(filename, old_entry)?;
989 Ok(true)
990 })
991 }
992 }
993 }
994
936 pub fn set_clean(
995 pub fn set_clean(
937 &mut self,
996 &mut self,
938 filename: &HgPath,
997 filename: &HgPath,
939 mode: u32,
998 mode: u32,
940 size: u32,
999 size: u32,
941 mtime: TruncatedTimestamp,
1000 mtime: TruncatedTimestamp,
942 ) -> Result<(), DirstateError> {
1001 ) -> Result<(), DirstateError> {
943 let old_entry = match self.get(filename)? {
1002 let old_entry = match self.get(filename)? {
944 None => {
1003 None => {
945 return Err(
1004 return Err(
946 DirstateMapError::PathNotFound(filename.into()).into()
1005 DirstateMapError::PathNotFound(filename.into()).into()
947 )
1006 )
948 }
1007 }
949 Some(e) => e,
1008 Some(e) => e,
950 };
1009 };
951 self.copy_map_remove(filename)?;
1010 self.copy_map_remove(filename)?;
952 self.with_dmap_mut(|map| {
1011 self.with_dmap_mut(|map| {
953 map.set_clean(filename, old_entry, mode, size, mtime)
1012 map.set_clean(filename, old_entry, mode, size, mtime)
954 })
1013 })
955 }
1014 }
956
1015
957 pub fn set_possibly_dirty(
1016 pub fn set_possibly_dirty(
958 &mut self,
1017 &mut self,
959 filename: &HgPath,
1018 filename: &HgPath,
960 ) -> Result<(), DirstateError> {
1019 ) -> Result<(), DirstateError> {
961 if self.get(filename)?.is_none() {
1020 if self.get(filename)?.is_none() {
962 return Err(DirstateMapError::PathNotFound(filename.into()).into());
1021 return Err(DirstateMapError::PathNotFound(filename.into()).into());
963 }
1022 }
964 self.with_dmap_mut(|map| map.set_possibly_dirty(filename))
1023 self.with_dmap_mut(|map| map.set_possibly_dirty(filename))
965 }
1024 }
966
1025
967 pub fn reset_state(
1026 pub fn reset_state(
968 &mut self,
1027 &mut self,
969 filename: &HgPath,
1028 filename: &HgPath,
970 wc_tracked: bool,
1029 wc_tracked: bool,
971 p1_tracked: bool,
1030 p1_tracked: bool,
972 p2_info: bool,
1031 p2_info: bool,
973 has_meaningful_mtime: bool,
1032 has_meaningful_mtime: bool,
974 parent_file_data_opt: Option<ParentFileData>,
1033 parent_file_data_opt: Option<ParentFileData>,
975 ) -> Result<(), DirstateError> {
1034 ) -> Result<(), DirstateError> {
976 if !(p1_tracked || p2_info || wc_tracked) {
1035 if !(p1_tracked || p2_info || wc_tracked) {
977 self.drop_entry_and_copy_source(filename)?;
1036 self.drop_entry_and_copy_source(filename)?;
978 return Ok(());
1037 return Ok(());
979 }
1038 }
980 self.copy_map_remove(filename)?;
1039 self.copy_map_remove(filename)?;
981 let old_entry_opt = self.get(filename)?;
1040 let old_entry_opt = self.get(filename)?;
982 self.with_dmap_mut(|map| {
1041 self.with_dmap_mut(|map| {
983 map.reset_state(
1042 map.reset_state(
984 filename,
1043 filename,
985 old_entry_opt,
1044 old_entry_opt,
986 wc_tracked,
1045 wc_tracked,
987 p1_tracked,
1046 p1_tracked,
988 p2_info,
1047 p2_info,
989 has_meaningful_mtime,
1048 has_meaningful_mtime,
990 parent_file_data_opt,
1049 parent_file_data_opt,
991 )
1050 )
992 })
1051 })
993 }
1052 }
994
1053
995 pub fn remove_file(
1054 pub fn remove_file(
996 &mut self,
1055 &mut self,
997 filename: &HgPath,
1056 filename: &HgPath,
998 in_merge: bool,
1057 in_merge: bool,
999 ) -> Result<(), DirstateError> {
1058 ) -> Result<(), DirstateError> {
1000 let old_entry_opt = self.get(filename)?;
1059 let old_entry_opt = self.get(filename)?;
1001 let old_state = old_entry_opt.map(|e| e.state());
1060 let old_state = old_entry_opt.map(|e| e.state());
1002 let mut size = 0;
1061 let mut size = 0;
1003 if in_merge {
1062 if in_merge {
1004 // XXX we should not be able to have 'm' state and 'FROM_P2' if not
1063 // XXX we should not be able to have 'm' state and 'FROM_P2' if not
1005 // during a merge. So I (marmoute) am not sure we need the
1064 // during a merge. So I (marmoute) am not sure we need the
1006 // conditionnal at all. Adding double checking this with assert
1065 // conditionnal at all. Adding double checking this with assert
1007 // would be nice.
1066 // would be nice.
1008 if let Some(old_entry) = old_entry_opt {
1067 if let Some(old_entry) = old_entry_opt {
1009 // backup the previous state
1068 // backup the previous state
1010 if old_entry.state() == EntryState::Merged {
1069 if old_entry.state() == EntryState::Merged {
1011 size = SIZE_NON_NORMAL;
1070 size = SIZE_NON_NORMAL;
1012 } else if old_entry.state() == EntryState::Normal
1071 } else if old_entry.state() == EntryState::Normal
1013 && old_entry.size() == SIZE_FROM_OTHER_PARENT
1072 && old_entry.size() == SIZE_FROM_OTHER_PARENT
1014 {
1073 {
1015 // other parent
1074 // other parent
1016 size = SIZE_FROM_OTHER_PARENT;
1075 size = SIZE_FROM_OTHER_PARENT;
1017 }
1076 }
1018 }
1077 }
1019 }
1078 }
1020 if size == 0 {
1079 if size == 0 {
1021 self.copy_map_remove(filename)?;
1080 self.copy_map_remove(filename)?;
1022 }
1081 }
1023 self.with_dmap_mut(|map| {
1082 self.with_dmap_mut(|map| {
1024 let entry = DirstateEntry::new_removed(size);
1083 let entry = DirstateEntry::new_removed(size);
1025 Ok(map.add_or_remove_file(filename, old_state, entry)?)
1084 Ok(map.add_or_remove_file(filename, old_state, entry)?)
1026 })
1085 })
1027 }
1086 }
1028
1087
1029 pub fn drop_entry_and_copy_source(
1088 pub fn drop_entry_and_copy_source(
1030 &mut self,
1089 &mut self,
1031 filename: &HgPath,
1090 filename: &HgPath,
1032 ) -> Result<(), DirstateError> {
1091 ) -> Result<(), DirstateError> {
1033 let was_tracked = self
1092 let was_tracked = self
1034 .get(filename)?
1093 .get(filename)?
1035 .map_or(false, |e| e.state().is_tracked());
1094 .map_or(false, |e| e.state().is_tracked());
1036 struct Dropped {
1095 struct Dropped {
1037 was_tracked: bool,
1096 was_tracked: bool,
1038 had_entry: bool,
1097 had_entry: bool,
1039 had_copy_source: bool,
1098 had_copy_source: bool,
1040 }
1099 }
1041
1100
1042 /// If this returns `Ok(Some((dropped, removed)))`, then
1101 /// If this returns `Ok(Some((dropped, removed)))`, then
1043 ///
1102 ///
1044 /// * `dropped` is about the leaf node that was at `filename`
1103 /// * `dropped` is about the leaf node that was at `filename`
1045 /// * `removed` is whether this particular level of recursion just
1104 /// * `removed` is whether this particular level of recursion just
1046 /// removed a node in `nodes`.
1105 /// removed a node in `nodes`.
1047 fn recur<'on_disk>(
1106 fn recur<'on_disk>(
1048 on_disk: &'on_disk [u8],
1107 on_disk: &'on_disk [u8],
1049 unreachable_bytes: &mut u32,
1108 unreachable_bytes: &mut u32,
1050 nodes: &mut ChildNodes<'on_disk>,
1109 nodes: &mut ChildNodes<'on_disk>,
1051 path: &HgPath,
1110 path: &HgPath,
1052 ) -> Result<Option<(Dropped, bool)>, DirstateV2ParseError> {
1111 ) -> Result<Option<(Dropped, bool)>, DirstateV2ParseError> {
1053 let (first_path_component, rest_of_path) =
1112 let (first_path_component, rest_of_path) =
1054 path.split_first_component();
1113 path.split_first_component();
1055 let nodes = nodes.make_mut(on_disk, unreachable_bytes)?;
1114 let nodes = nodes.make_mut(on_disk, unreachable_bytes)?;
1056 let node = if let Some(node) = nodes.get_mut(first_path_component)
1115 let node = if let Some(node) = nodes.get_mut(first_path_component)
1057 {
1116 {
1058 node
1117 node
1059 } else {
1118 } else {
1060 return Ok(None);
1119 return Ok(None);
1061 };
1120 };
1062 let dropped;
1121 let dropped;
1063 if let Some(rest) = rest_of_path {
1122 if let Some(rest) = rest_of_path {
1064 if let Some((d, removed)) = recur(
1123 if let Some((d, removed)) = recur(
1065 on_disk,
1124 on_disk,
1066 unreachable_bytes,
1125 unreachable_bytes,
1067 &mut node.children,
1126 &mut node.children,
1068 rest,
1127 rest,
1069 )? {
1128 )? {
1070 dropped = d;
1129 dropped = d;
1071 if dropped.had_entry {
1130 if dropped.had_entry {
1072 node.descendants_with_entry_count = node
1131 node.descendants_with_entry_count = node
1073 .descendants_with_entry_count
1132 .descendants_with_entry_count
1074 .checked_sub(1)
1133 .checked_sub(1)
1075 .expect(
1134 .expect(
1076 "descendants_with_entry_count should be >= 0",
1135 "descendants_with_entry_count should be >= 0",
1077 );
1136 );
1078 }
1137 }
1079 if dropped.was_tracked {
1138 if dropped.was_tracked {
1080 node.tracked_descendants_count = node
1139 node.tracked_descendants_count = node
1081 .tracked_descendants_count
1140 .tracked_descendants_count
1082 .checked_sub(1)
1141 .checked_sub(1)
1083 .expect(
1142 .expect(
1084 "tracked_descendants_count should be >= 0",
1143 "tracked_descendants_count should be >= 0",
1085 );
1144 );
1086 }
1145 }
1087
1146
1088 // Directory caches must be invalidated when removing a
1147 // Directory caches must be invalidated when removing a
1089 // child node
1148 // child node
1090 if removed {
1149 if removed {
1091 if let NodeData::CachedDirectory { .. } = &node.data {
1150 if let NodeData::CachedDirectory { .. } = &node.data {
1092 node.data = NodeData::None
1151 node.data = NodeData::None
1093 }
1152 }
1094 }
1153 }
1095 } else {
1154 } else {
1096 return Ok(None);
1155 return Ok(None);
1097 }
1156 }
1098 } else {
1157 } else {
1099 let entry = node.data.as_entry();
1158 let entry = node.data.as_entry();
1100 let was_tracked = entry.map_or(false, |entry| entry.tracked());
1159 let was_tracked = entry.map_or(false, |entry| entry.tracked());
1101 let had_entry = entry.is_some();
1160 let had_entry = entry.is_some();
1102 if had_entry {
1161 if had_entry {
1103 node.data = NodeData::None
1162 node.data = NodeData::None
1104 }
1163 }
1105 let mut had_copy_source = false;
1164 let mut had_copy_source = false;
1106 if let Some(source) = &node.copy_source {
1165 if let Some(source) = &node.copy_source {
1107 DirstateMap::count_dropped_path(unreachable_bytes, source);
1166 DirstateMap::count_dropped_path(unreachable_bytes, source);
1108 had_copy_source = true;
1167 had_copy_source = true;
1109 node.copy_source = None
1168 node.copy_source = None
1110 }
1169 }
1111 dropped = Dropped {
1170 dropped = Dropped {
1112 was_tracked,
1171 was_tracked,
1113 had_entry,
1172 had_entry,
1114 had_copy_source,
1173 had_copy_source,
1115 };
1174 };
1116 }
1175 }
1117 // After recursion, for both leaf (rest_of_path is None) nodes and
1176 // After recursion, for both leaf (rest_of_path is None) nodes and
1118 // parent nodes, remove a node if it just became empty.
1177 // parent nodes, remove a node if it just became empty.
1119 let remove = !node.data.has_entry()
1178 let remove = !node.data.has_entry()
1120 && node.copy_source.is_none()
1179 && node.copy_source.is_none()
1121 && node.children.is_empty();
1180 && node.children.is_empty();
1122 if remove {
1181 if remove {
1123 let (key, _) =
1182 let (key, _) =
1124 nodes.remove_entry(first_path_component).unwrap();
1183 nodes.remove_entry(first_path_component).unwrap();
1125 DirstateMap::count_dropped_path(
1184 DirstateMap::count_dropped_path(
1126 unreachable_bytes,
1185 unreachable_bytes,
1127 key.full_path(),
1186 key.full_path(),
1128 )
1187 )
1129 }
1188 }
1130 Ok(Some((dropped, remove)))
1189 Ok(Some((dropped, remove)))
1131 }
1190 }
1132
1191
1133 self.with_dmap_mut(|map| {
1192 self.with_dmap_mut(|map| {
1134 if let Some((dropped, _removed)) = recur(
1193 if let Some((dropped, _removed)) = recur(
1135 map.on_disk,
1194 map.on_disk,
1136 &mut map.unreachable_bytes,
1195 &mut map.unreachable_bytes,
1137 &mut map.root,
1196 &mut map.root,
1138 filename,
1197 filename,
1139 )? {
1198 )? {
1140 if dropped.had_entry {
1199 if dropped.had_entry {
1141 map.nodes_with_entry_count = map
1200 map.nodes_with_entry_count = map
1142 .nodes_with_entry_count
1201 .nodes_with_entry_count
1143 .checked_sub(1)
1202 .checked_sub(1)
1144 .expect("nodes_with_entry_count should be >= 0");
1203 .expect("nodes_with_entry_count should be >= 0");
1145 }
1204 }
1146 if dropped.had_copy_source {
1205 if dropped.had_copy_source {
1147 map.nodes_with_copy_source_count = map
1206 map.nodes_with_copy_source_count = map
1148 .nodes_with_copy_source_count
1207 .nodes_with_copy_source_count
1149 .checked_sub(1)
1208 .checked_sub(1)
1150 .expect("nodes_with_copy_source_count should be >= 0");
1209 .expect("nodes_with_copy_source_count should be >= 0");
1151 }
1210 }
1152 } else {
1211 } else {
1153 debug_assert!(!was_tracked);
1212 debug_assert!(!was_tracked);
1154 }
1213 }
1155 Ok(())
1214 Ok(())
1156 })
1215 })
1157 }
1216 }
1158
1217
1159 pub fn has_tracked_dir(
1218 pub fn has_tracked_dir(
1160 &mut self,
1219 &mut self,
1161 directory: &HgPath,
1220 directory: &HgPath,
1162 ) -> Result<bool, DirstateError> {
1221 ) -> Result<bool, DirstateError> {
1163 self.with_dmap_mut(|map| {
1222 self.with_dmap_mut(|map| {
1164 if let Some(node) = map.get_node(directory)? {
1223 if let Some(node) = map.get_node(directory)? {
1165 // A node without a `DirstateEntry` was created to hold child
1224 // A node without a `DirstateEntry` was created to hold child
1166 // nodes, and is therefore a directory.
1225 // nodes, and is therefore a directory.
1167 let state = node.state()?;
1226 let state = node.state()?;
1168 Ok(state.is_none() && node.tracked_descendants_count() > 0)
1227 Ok(state.is_none() && node.tracked_descendants_count() > 0)
1169 } else {
1228 } else {
1170 Ok(false)
1229 Ok(false)
1171 }
1230 }
1172 })
1231 })
1173 }
1232 }
1174
1233
1175 pub fn has_dir(
1234 pub fn has_dir(
1176 &mut self,
1235 &mut self,
1177 directory: &HgPath,
1236 directory: &HgPath,
1178 ) -> Result<bool, DirstateError> {
1237 ) -> Result<bool, DirstateError> {
1179 self.with_dmap_mut(|map| {
1238 self.with_dmap_mut(|map| {
1180 if let Some(node) = map.get_node(directory)? {
1239 if let Some(node) = map.get_node(directory)? {
1181 // A node without a `DirstateEntry` was created to hold child
1240 // A node without a `DirstateEntry` was created to hold child
1182 // nodes, and is therefore a directory.
1241 // nodes, and is therefore a directory.
1183 let state = node.state()?;
1242 let state = node.state()?;
1184 Ok(state.is_none() && node.descendants_with_entry_count() > 0)
1243 Ok(state.is_none() && node.descendants_with_entry_count() > 0)
1185 } else {
1244 } else {
1186 Ok(false)
1245 Ok(false)
1187 }
1246 }
1188 })
1247 })
1189 }
1248 }
1190
1249
1191 #[timed]
1250 #[timed]
1192 pub fn pack_v1(
1251 pub fn pack_v1(
1193 &self,
1252 &self,
1194 parents: DirstateParents,
1253 parents: DirstateParents,
1195 ) -> Result<Vec<u8>, DirstateError> {
1254 ) -> Result<Vec<u8>, DirstateError> {
1196 let map = self.get_map();
1255 let map = self.get_map();
1197 // Optizimation (to be measured?): pre-compute size to avoid `Vec`
1256 // Optizimation (to be measured?): pre-compute size to avoid `Vec`
1198 // reallocations
1257 // reallocations
1199 let mut size = parents.as_bytes().len();
1258 let mut size = parents.as_bytes().len();
1200 for node in map.iter_nodes() {
1259 for node in map.iter_nodes() {
1201 let node = node?;
1260 let node = node?;
1202 if node.entry()?.is_some() {
1261 if node.entry()?.is_some() {
1203 size += packed_entry_size(
1262 size += packed_entry_size(
1204 node.full_path(map.on_disk)?,
1263 node.full_path(map.on_disk)?,
1205 node.copy_source(map.on_disk)?,
1264 node.copy_source(map.on_disk)?,
1206 );
1265 );
1207 }
1266 }
1208 }
1267 }
1209
1268
1210 let mut packed = Vec::with_capacity(size);
1269 let mut packed = Vec::with_capacity(size);
1211 packed.extend(parents.as_bytes());
1270 packed.extend(parents.as_bytes());
1212
1271
1213 for node in map.iter_nodes() {
1272 for node in map.iter_nodes() {
1214 let node = node?;
1273 let node = node?;
1215 if let Some(entry) = node.entry()? {
1274 if let Some(entry) = node.entry()? {
1216 pack_entry(
1275 pack_entry(
1217 node.full_path(map.on_disk)?,
1276 node.full_path(map.on_disk)?,
1218 &entry,
1277 &entry,
1219 node.copy_source(map.on_disk)?,
1278 node.copy_source(map.on_disk)?,
1220 &mut packed,
1279 &mut packed,
1221 );
1280 );
1222 }
1281 }
1223 }
1282 }
1224 Ok(packed)
1283 Ok(packed)
1225 }
1284 }
1226
1285
1227 /// Returns new data and metadata together with whether that data should be
1286 /// Returns new data and metadata together with whether that data should be
1228 /// appended to the existing data file whose content is at
1287 /// appended to the existing data file whose content is at
1229 /// `map.on_disk` (true), instead of written to a new data file
1288 /// `map.on_disk` (true), instead of written to a new data file
1230 /// (false).
1289 /// (false).
1231 #[timed]
1290 #[timed]
1232 pub fn pack_v2(
1291 pub fn pack_v2(
1233 &self,
1292 &self,
1234 can_append: bool,
1293 can_append: bool,
1235 ) -> Result<(Vec<u8>, on_disk::TreeMetadata, bool), DirstateError> {
1294 ) -> Result<(Vec<u8>, on_disk::TreeMetadata, bool), DirstateError> {
1236 let map = self.get_map();
1295 let map = self.get_map();
1237 on_disk::write(map, can_append)
1296 on_disk::write(map, can_append)
1238 }
1297 }
1239
1298
1240 /// `callback` allows the caller to process and do something with the
1299 /// `callback` allows the caller to process and do something with the
1241 /// results of the status. This is needed to do so efficiently (i.e.
1300 /// results of the status. This is needed to do so efficiently (i.e.
1242 /// without cloning the `DirstateStatus` object with its paths) because
1301 /// without cloning the `DirstateStatus` object with its paths) because
1243 /// we need to borrow from `Self`.
1302 /// we need to borrow from `Self`.
1244 pub fn with_status<R>(
1303 pub fn with_status<R>(
1245 &mut self,
1304 &mut self,
1246 matcher: &(dyn Matcher + Sync),
1305 matcher: &(dyn Matcher + Sync),
1247 root_dir: PathBuf,
1306 root_dir: PathBuf,
1248 ignore_files: Vec<PathBuf>,
1307 ignore_files: Vec<PathBuf>,
1249 options: StatusOptions,
1308 options: StatusOptions,
1250 callback: impl for<'r> FnOnce(
1309 callback: impl for<'r> FnOnce(
1251 Result<(DirstateStatus<'r>, Vec<PatternFileWarning>), StatusError>,
1310 Result<(DirstateStatus<'r>, Vec<PatternFileWarning>), StatusError>,
1252 ) -> R,
1311 ) -> R,
1253 ) -> R {
1312 ) -> R {
1254 self.with_dmap_mut(|map| {
1313 self.with_dmap_mut(|map| {
1255 callback(super::status::status(
1314 callback(super::status::status(
1256 map,
1315 map,
1257 matcher,
1316 matcher,
1258 root_dir,
1317 root_dir,
1259 ignore_files,
1318 ignore_files,
1260 options,
1319 options,
1261 ))
1320 ))
1262 })
1321 })
1263 }
1322 }
1264
1323
1265 pub fn copy_map_len(&self) -> usize {
1324 pub fn copy_map_len(&self) -> usize {
1266 let map = self.get_map();
1325 let map = self.get_map();
1267 map.nodes_with_copy_source_count as usize
1326 map.nodes_with_copy_source_count as usize
1268 }
1327 }
1269
1328
1270 pub fn copy_map_iter(&self) -> CopyMapIter<'_> {
1329 pub fn copy_map_iter(&self) -> CopyMapIter<'_> {
1271 let map = self.get_map();
1330 let map = self.get_map();
1272 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1331 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1273 Ok(if let Some(source) = node.copy_source(map.on_disk)? {
1332 Ok(if let Some(source) = node.copy_source(map.on_disk)? {
1274 Some((node.full_path(map.on_disk)?, source))
1333 Some((node.full_path(map.on_disk)?, source))
1275 } else {
1334 } else {
1276 None
1335 None
1277 })
1336 })
1278 }))
1337 }))
1279 }
1338 }
1280
1339
1281 pub fn copy_map_contains_key(
1340 pub fn copy_map_contains_key(
1282 &self,
1341 &self,
1283 key: &HgPath,
1342 key: &HgPath,
1284 ) -> Result<bool, DirstateV2ParseError> {
1343 ) -> Result<bool, DirstateV2ParseError> {
1285 let map = self.get_map();
1344 let map = self.get_map();
1286 Ok(if let Some(node) = map.get_node(key)? {
1345 Ok(if let Some(node) = map.get_node(key)? {
1287 node.has_copy_source()
1346 node.has_copy_source()
1288 } else {
1347 } else {
1289 false
1348 false
1290 })
1349 })
1291 }
1350 }
1292
1351
1293 pub fn copy_map_get(
1352 pub fn copy_map_get(
1294 &self,
1353 &self,
1295 key: &HgPath,
1354 key: &HgPath,
1296 ) -> Result<Option<&HgPath>, DirstateV2ParseError> {
1355 ) -> Result<Option<&HgPath>, DirstateV2ParseError> {
1297 let map = self.get_map();
1356 let map = self.get_map();
1298 if let Some(node) = map.get_node(key)? {
1357 if let Some(node) = map.get_node(key)? {
1299 if let Some(source) = node.copy_source(map.on_disk)? {
1358 if let Some(source) = node.copy_source(map.on_disk)? {
1300 return Ok(Some(source));
1359 return Ok(Some(source));
1301 }
1360 }
1302 }
1361 }
1303 Ok(None)
1362 Ok(None)
1304 }
1363 }
1305
1364
1306 pub fn copy_map_remove(
1365 pub fn copy_map_remove(
1307 &mut self,
1366 &mut self,
1308 key: &HgPath,
1367 key: &HgPath,
1309 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1368 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1310 self.with_dmap_mut(|map| {
1369 self.with_dmap_mut(|map| {
1311 let count = &mut map.nodes_with_copy_source_count;
1370 let count = &mut map.nodes_with_copy_source_count;
1312 let unreachable_bytes = &mut map.unreachable_bytes;
1371 let unreachable_bytes = &mut map.unreachable_bytes;
1313 Ok(DirstateMap::get_node_mut(
1372 Ok(DirstateMap::get_node_mut(
1314 map.on_disk,
1373 map.on_disk,
1315 unreachable_bytes,
1374 unreachable_bytes,
1316 &mut map.root,
1375 &mut map.root,
1317 key,
1376 key,
1318 )?
1377 )?
1319 .and_then(|node| {
1378 .and_then(|node| {
1320 if let Some(source) = &node.copy_source {
1379 if let Some(source) = &node.copy_source {
1321 *count -= 1;
1380 *count -= 1;
1322 DirstateMap::count_dropped_path(unreachable_bytes, source);
1381 DirstateMap::count_dropped_path(unreachable_bytes, source);
1323 }
1382 }
1324 node.copy_source.take().map(Cow::into_owned)
1383 node.copy_source.take().map(Cow::into_owned)
1325 }))
1384 }))
1326 })
1385 })
1327 }
1386 }
1328
1387
1329 pub fn copy_map_insert(
1388 pub fn copy_map_insert(
1330 &mut self,
1389 &mut self,
1331 key: HgPathBuf,
1390 key: HgPathBuf,
1332 value: HgPathBuf,
1391 value: HgPathBuf,
1333 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1392 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1334 self.with_dmap_mut(|map| {
1393 self.with_dmap_mut(|map| {
1335 let node = DirstateMap::get_or_insert_node(
1394 let node = DirstateMap::get_or_insert_node(
1336 map.on_disk,
1395 map.on_disk,
1337 &mut map.unreachable_bytes,
1396 &mut map.unreachable_bytes,
1338 &mut map.root,
1397 &mut map.root,
1339 &key,
1398 &key,
1340 WithBasename::to_cow_owned,
1399 WithBasename::to_cow_owned,
1341 |_ancestor| {},
1400 |_ancestor| {},
1342 )?;
1401 )?;
1343 if node.copy_source.is_none() {
1402 if node.copy_source.is_none() {
1344 map.nodes_with_copy_source_count += 1
1403 map.nodes_with_copy_source_count += 1
1345 }
1404 }
1346 Ok(node.copy_source.replace(value.into()).map(Cow::into_owned))
1405 Ok(node.copy_source.replace(value.into()).map(Cow::into_owned))
1347 })
1406 })
1348 }
1407 }
1349
1408
1350 pub fn len(&self) -> usize {
1409 pub fn len(&self) -> usize {
1351 let map = self.get_map();
1410 let map = self.get_map();
1352 map.nodes_with_entry_count as usize
1411 map.nodes_with_entry_count as usize
1353 }
1412 }
1354
1413
1355 pub fn contains_key(
1414 pub fn contains_key(
1356 &self,
1415 &self,
1357 key: &HgPath,
1416 key: &HgPath,
1358 ) -> Result<bool, DirstateV2ParseError> {
1417 ) -> Result<bool, DirstateV2ParseError> {
1359 Ok(self.get(key)?.is_some())
1418 Ok(self.get(key)?.is_some())
1360 }
1419 }
1361
1420
1362 pub fn get(
1421 pub fn get(
1363 &self,
1422 &self,
1364 key: &HgPath,
1423 key: &HgPath,
1365 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
1424 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
1366 let map = self.get_map();
1425 let map = self.get_map();
1367 Ok(if let Some(node) = map.get_node(key)? {
1426 Ok(if let Some(node) = map.get_node(key)? {
1368 node.entry()?
1427 node.entry()?
1369 } else {
1428 } else {
1370 None
1429 None
1371 })
1430 })
1372 }
1431 }
1373
1432
1374 pub fn iter(&self) -> StateMapIter<'_> {
1433 pub fn iter(&self) -> StateMapIter<'_> {
1375 let map = self.get_map();
1434 let map = self.get_map();
1376 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1435 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1377 Ok(if let Some(entry) = node.entry()? {
1436 Ok(if let Some(entry) = node.entry()? {
1378 Some((node.full_path(map.on_disk)?, entry))
1437 Some((node.full_path(map.on_disk)?, entry))
1379 } else {
1438 } else {
1380 None
1439 None
1381 })
1440 })
1382 }))
1441 }))
1383 }
1442 }
1384
1443
1385 pub fn iter_tracked_dirs(
1444 pub fn iter_tracked_dirs(
1386 &mut self,
1445 &mut self,
1387 ) -> Result<
1446 ) -> Result<
1388 Box<
1447 Box<
1389 dyn Iterator<Item = Result<&HgPath, DirstateV2ParseError>>
1448 dyn Iterator<Item = Result<&HgPath, DirstateV2ParseError>>
1390 + Send
1449 + Send
1391 + '_,
1450 + '_,
1392 >,
1451 >,
1393 DirstateError,
1452 DirstateError,
1394 > {
1453 > {
1395 let map = self.get_map();
1454 let map = self.get_map();
1396 let on_disk = map.on_disk;
1455 let on_disk = map.on_disk;
1397 Ok(Box::new(filter_map_results(
1456 Ok(Box::new(filter_map_results(
1398 map.iter_nodes(),
1457 map.iter_nodes(),
1399 move |node| {
1458 move |node| {
1400 Ok(if node.tracked_descendants_count() > 0 {
1459 Ok(if node.tracked_descendants_count() > 0 {
1401 Some(node.full_path(on_disk)?)
1460 Some(node.full_path(on_disk)?)
1402 } else {
1461 } else {
1403 None
1462 None
1404 })
1463 })
1405 },
1464 },
1406 )))
1465 )))
1407 }
1466 }
1408
1467
1409 pub fn debug_iter(
1468 pub fn debug_iter(
1410 &self,
1469 &self,
1411 all: bool,
1470 all: bool,
1412 ) -> Box<
1471 ) -> Box<
1413 dyn Iterator<
1472 dyn Iterator<
1414 Item = Result<
1473 Item = Result<
1415 (&HgPath, (u8, i32, i32, i32)),
1474 (&HgPath, (u8, i32, i32, i32)),
1416 DirstateV2ParseError,
1475 DirstateV2ParseError,
1417 >,
1476 >,
1418 > + Send
1477 > + Send
1419 + '_,
1478 + '_,
1420 > {
1479 > {
1421 let map = self.get_map();
1480 let map = self.get_map();
1422 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1481 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1423 let debug_tuple = if let Some(entry) = node.entry()? {
1482 let debug_tuple = if let Some(entry) = node.entry()? {
1424 entry.debug_tuple()
1483 entry.debug_tuple()
1425 } else if !all {
1484 } else if !all {
1426 return Ok(None);
1485 return Ok(None);
1427 } else if let Some(mtime) = node.cached_directory_mtime()? {
1486 } else if let Some(mtime) = node.cached_directory_mtime()? {
1428 (b' ', 0, -1, mtime.truncated_seconds() as i32)
1487 (b' ', 0, -1, mtime.truncated_seconds() as i32)
1429 } else {
1488 } else {
1430 (b' ', 0, -1, -1)
1489 (b' ', 0, -1, -1)
1431 };
1490 };
1432 Ok(Some((node.full_path(map.on_disk)?, debug_tuple)))
1491 Ok(Some((node.full_path(map.on_disk)?, debug_tuple)))
1433 }))
1492 }))
1434 }
1493 }
1435 }
1494 }
@@ -1,582 +1,592 b''
1 // dirstate_map.rs
1 // dirstate_map.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 //! Bindings for the `hg::dirstate::dirstate_map` file provided by the
8 //! Bindings for the `hg::dirstate::dirstate_map` file provided by the
9 //! `hg-core` package.
9 //! `hg-core` package.
10
10
11 use std::cell::{RefCell, RefMut};
11 use std::cell::{RefCell, RefMut};
12 use std::convert::TryInto;
12 use std::convert::TryInto;
13
13
14 use cpython::{
14 use cpython::{
15 exc, PyBool, PyBytes, PyClone, PyDict, PyErr, PyList, PyNone, PyObject,
15 exc, PyBool, PyBytes, PyClone, PyDict, PyErr, PyList, PyNone, PyObject,
16 PyResult, Python, PythonObject, ToPyObject, UnsafePyLeaked,
16 PyResult, Python, PythonObject, ToPyObject, UnsafePyLeaked,
17 };
17 };
18 use hg::dirstate::{ParentFileData, TruncatedTimestamp};
18 use hg::dirstate::{ParentFileData, TruncatedTimestamp};
19
19
20 use crate::{
20 use crate::{
21 dirstate::copymap::{CopyMap, CopyMapItemsIterator, CopyMapKeysIterator},
21 dirstate::copymap::{CopyMap, CopyMapItemsIterator, CopyMapKeysIterator},
22 dirstate::item::DirstateItem,
22 dirstate::item::DirstateItem,
23 pybytes_deref::PyBytesDeref,
23 pybytes_deref::PyBytesDeref,
24 };
24 };
25 use hg::{
25 use hg::{
26 dirstate::StateMapIter,
26 dirstate::StateMapIter,
27 dirstate_tree::on_disk::DirstateV2ParseError,
27 dirstate_tree::on_disk::DirstateV2ParseError,
28 dirstate_tree::owning::OwningDirstateMap,
28 dirstate_tree::owning::OwningDirstateMap,
29 revlog::Node,
29 revlog::Node,
30 utils::files::normalize_case,
30 utils::files::normalize_case,
31 utils::hg_path::{HgPath, HgPathBuf},
31 utils::hg_path::{HgPath, HgPathBuf},
32 DirstateEntry, DirstateError, DirstateParents, EntryState,
32 DirstateEntry, DirstateError, DirstateParents, EntryState,
33 };
33 };
34
34
35 // TODO
35 // TODO
36 // This object needs to share references to multiple members of its Rust
36 // This object needs to share references to multiple members of its Rust
37 // inner struct, namely `copy_map`, `dirs` and `all_dirs`.
37 // inner struct, namely `copy_map`, `dirs` and `all_dirs`.
38 // Right now `CopyMap` is done, but it needs to have an explicit reference
38 // Right now `CopyMap` is done, but it needs to have an explicit reference
39 // to `RustDirstateMap` which itself needs to have an encapsulation for
39 // to `RustDirstateMap` which itself needs to have an encapsulation for
40 // every method in `CopyMap` (copymapcopy, etc.).
40 // every method in `CopyMap` (copymapcopy, etc.).
41 // This is ugly and hard to maintain.
41 // This is ugly and hard to maintain.
42 // The same logic applies to `dirs` and `all_dirs`, however the `Dirs`
42 // The same logic applies to `dirs` and `all_dirs`, however the `Dirs`
43 // `py_class!` is already implemented and does not mention
43 // `py_class!` is already implemented and does not mention
44 // `RustDirstateMap`, rightfully so.
44 // `RustDirstateMap`, rightfully so.
45 // All attributes also have to have a separate refcount data attribute for
45 // All attributes also have to have a separate refcount data attribute for
46 // leaks, with all methods that go along for reference sharing.
46 // leaks, with all methods that go along for reference sharing.
47 py_class!(pub class DirstateMap |py| {
47 py_class!(pub class DirstateMap |py| {
48 @shared data inner: OwningDirstateMap;
48 @shared data inner: OwningDirstateMap;
49
49
50 /// Returns a `(dirstate_map, parents)` tuple
50 /// Returns a `(dirstate_map, parents)` tuple
51 @staticmethod
51 @staticmethod
52 def new_v1(
52 def new_v1(
53 on_disk: PyBytes,
53 on_disk: PyBytes,
54 ) -> PyResult<PyObject> {
54 ) -> PyResult<PyObject> {
55 let on_disk = PyBytesDeref::new(py, on_disk);
55 let on_disk = PyBytesDeref::new(py, on_disk);
56 let (map, parents) = OwningDirstateMap::new_v1(on_disk)
56 let (map, parents) = OwningDirstateMap::new_v1(on_disk)
57 .map_err(|e| dirstate_error(py, e))?;
57 .map_err(|e| dirstate_error(py, e))?;
58 let map = Self::create_instance(py, map)?;
58 let map = Self::create_instance(py, map)?;
59 let p1 = PyBytes::new(py, parents.p1.as_bytes());
59 let p1 = PyBytes::new(py, parents.p1.as_bytes());
60 let p2 = PyBytes::new(py, parents.p2.as_bytes());
60 let p2 = PyBytes::new(py, parents.p2.as_bytes());
61 let parents = (p1, p2);
61 let parents = (p1, p2);
62 Ok((map, parents).to_py_object(py).into_object())
62 Ok((map, parents).to_py_object(py).into_object())
63 }
63 }
64
64
65 /// Returns a DirstateMap
65 /// Returns a DirstateMap
66 @staticmethod
66 @staticmethod
67 def new_v2(
67 def new_v2(
68 on_disk: PyBytes,
68 on_disk: PyBytes,
69 data_size: usize,
69 data_size: usize,
70 tree_metadata: PyBytes,
70 tree_metadata: PyBytes,
71 ) -> PyResult<PyObject> {
71 ) -> PyResult<PyObject> {
72 let dirstate_error = |e: DirstateError| {
72 let dirstate_error = |e: DirstateError| {
73 PyErr::new::<exc::OSError, _>(py, format!("Dirstate error: {:?}", e))
73 PyErr::new::<exc::OSError, _>(py, format!("Dirstate error: {:?}", e))
74 };
74 };
75 let on_disk = PyBytesDeref::new(py, on_disk);
75 let on_disk = PyBytesDeref::new(py, on_disk);
76 let map = OwningDirstateMap::new_v2(
76 let map = OwningDirstateMap::new_v2(
77 on_disk, data_size, tree_metadata.data(py),
77 on_disk, data_size, tree_metadata.data(py),
78 ).map_err(dirstate_error)?;
78 ).map_err(dirstate_error)?;
79 let map = Self::create_instance(py, map)?;
79 let map = Self::create_instance(py, map)?;
80 Ok(map.into_object())
80 Ok(map.into_object())
81 }
81 }
82
82
83 def clear(&self) -> PyResult<PyObject> {
83 def clear(&self) -> PyResult<PyObject> {
84 self.inner(py).borrow_mut().clear();
84 self.inner(py).borrow_mut().clear();
85 Ok(py.None())
85 Ok(py.None())
86 }
86 }
87
87
88 def get(
88 def get(
89 &self,
89 &self,
90 key: PyObject,
90 key: PyObject,
91 default: Option<PyObject> = None
91 default: Option<PyObject> = None
92 ) -> PyResult<Option<PyObject>> {
92 ) -> PyResult<Option<PyObject>> {
93 let key = key.extract::<PyBytes>(py)?;
93 let key = key.extract::<PyBytes>(py)?;
94 match self
94 match self
95 .inner(py)
95 .inner(py)
96 .borrow()
96 .borrow()
97 .get(HgPath::new(key.data(py)))
97 .get(HgPath::new(key.data(py)))
98 .map_err(|e| v2_error(py, e))?
98 .map_err(|e| v2_error(py, e))?
99 {
99 {
100 Some(entry) => {
100 Some(entry) => {
101 Ok(Some(DirstateItem::new_as_pyobject(py, entry)?))
101 Ok(Some(DirstateItem::new_as_pyobject(py, entry)?))
102 },
102 },
103 None => Ok(default)
103 None => Ok(default)
104 }
104 }
105 }
105 }
106
106
107 def set_dirstate_item(
107 def set_dirstate_item(
108 &self,
108 &self,
109 path: PyObject,
109 path: PyObject,
110 item: DirstateItem
110 item: DirstateItem
111 ) -> PyResult<PyObject> {
111 ) -> PyResult<PyObject> {
112 let f = path.extract::<PyBytes>(py)?;
112 let f = path.extract::<PyBytes>(py)?;
113 let filename = HgPath::new(f.data(py));
113 let filename = HgPath::new(f.data(py));
114 self.inner(py)
114 self.inner(py)
115 .borrow_mut()
115 .borrow_mut()
116 .set_entry(filename, item.get_entry(py))
116 .set_entry(filename, item.get_entry(py))
117 .map_err(|e| v2_error(py, e))?;
117 .map_err(|e| v2_error(py, e))?;
118 Ok(py.None())
118 Ok(py.None())
119 }
119 }
120
120
121 def addfile(
121 def addfile(
122 &self,
122 &self,
123 f: PyBytes,
123 f: PyBytes,
124 item: DirstateItem,
124 item: DirstateItem,
125 ) -> PyResult<PyNone> {
125 ) -> PyResult<PyNone> {
126 let filename = HgPath::new(f.data(py));
126 let filename = HgPath::new(f.data(py));
127 let entry = item.get_entry(py);
127 let entry = item.get_entry(py);
128 self.inner(py)
128 self.inner(py)
129 .borrow_mut()
129 .borrow_mut()
130 .add_file(filename, entry)
130 .add_file(filename, entry)
131 .map_err(|e |dirstate_error(py, e))?;
131 .map_err(|e |dirstate_error(py, e))?;
132 Ok(PyNone)
132 Ok(PyNone)
133 }
133 }
134
134
135 def set_tracked(&self, f: PyObject) -> PyResult<PyBool> {
135 def set_tracked(&self, f: PyObject) -> PyResult<PyBool> {
136 let bytes = f.extract::<PyBytes>(py)?;
136 let bytes = f.extract::<PyBytes>(py)?;
137 let path = HgPath::new(bytes.data(py));
137 let path = HgPath::new(bytes.data(py));
138 let res = self.inner(py).borrow_mut().set_tracked(path);
138 let res = self.inner(py).borrow_mut().set_tracked(path);
139 let was_tracked = res.or_else(|_| {
139 let was_tracked = res.or_else(|_| {
140 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
140 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
141 })?;
141 })?;
142 Ok(was_tracked.to_py_object(py))
142 Ok(was_tracked.to_py_object(py))
143 }
143 }
144
144
145 def set_untracked(&self, f: PyObject) -> PyResult<PyBool> {
146 let bytes = f.extract::<PyBytes>(py)?;
147 let path = HgPath::new(bytes.data(py));
148 let res = self.inner(py).borrow_mut().set_untracked(path);
149 let was_tracked = res.or_else(|_| {
150 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
151 })?;
152 Ok(was_tracked.to_py_object(py))
153 }
154
145 def set_clean(
155 def set_clean(
146 &self,
156 &self,
147 f: PyObject,
157 f: PyObject,
148 mode: u32,
158 mode: u32,
149 size: u32,
159 size: u32,
150 mtime: (i64, u32, bool)
160 mtime: (i64, u32, bool)
151 ) -> PyResult<PyNone> {
161 ) -> PyResult<PyNone> {
152 let (mtime_s, mtime_ns, second_ambiguous) = mtime;
162 let (mtime_s, mtime_ns, second_ambiguous) = mtime;
153 let timestamp = TruncatedTimestamp::new_truncate(
163 let timestamp = TruncatedTimestamp::new_truncate(
154 mtime_s, mtime_ns, second_ambiguous
164 mtime_s, mtime_ns, second_ambiguous
155 );
165 );
156 let bytes = f.extract::<PyBytes>(py)?;
166 let bytes = f.extract::<PyBytes>(py)?;
157 let path = HgPath::new(bytes.data(py));
167 let path = HgPath::new(bytes.data(py));
158 let res = self.inner(py).borrow_mut().set_clean(
168 let res = self.inner(py).borrow_mut().set_clean(
159 path, mode, size, timestamp,
169 path, mode, size, timestamp,
160 );
170 );
161 res.or_else(|_| {
171 res.or_else(|_| {
162 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
172 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
163 })?;
173 })?;
164 Ok(PyNone)
174 Ok(PyNone)
165 }
175 }
166
176
167 def set_possibly_dirty(&self, f: PyObject) -> PyResult<PyNone> {
177 def set_possibly_dirty(&self, f: PyObject) -> PyResult<PyNone> {
168 let bytes = f.extract::<PyBytes>(py)?;
178 let bytes = f.extract::<PyBytes>(py)?;
169 let path = HgPath::new(bytes.data(py));
179 let path = HgPath::new(bytes.data(py));
170 let res = self.inner(py).borrow_mut().set_possibly_dirty(path);
180 let res = self.inner(py).borrow_mut().set_possibly_dirty(path);
171 res.or_else(|_| {
181 res.or_else(|_| {
172 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
182 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
173 })?;
183 })?;
174 Ok(PyNone)
184 Ok(PyNone)
175 }
185 }
176
186
177 def reset_state(
187 def reset_state(
178 &self,
188 &self,
179 f: PyObject,
189 f: PyObject,
180 wc_tracked: bool,
190 wc_tracked: bool,
181 p1_tracked: bool,
191 p1_tracked: bool,
182 p2_info: bool,
192 p2_info: bool,
183 has_meaningful_mtime: bool,
193 has_meaningful_mtime: bool,
184 parentfiledata: Option<(u32, u32, Option<(i64, u32, bool)>)>,
194 parentfiledata: Option<(u32, u32, Option<(i64, u32, bool)>)>,
185 ) -> PyResult<PyNone> {
195 ) -> PyResult<PyNone> {
186 let mut has_meaningful_mtime = has_meaningful_mtime;
196 let mut has_meaningful_mtime = has_meaningful_mtime;
187 let parent_file_data = match parentfiledata {
197 let parent_file_data = match parentfiledata {
188 None => {
198 None => {
189 has_meaningful_mtime = false;
199 has_meaningful_mtime = false;
190 None
200 None
191 },
201 },
192 Some(data) => {
202 Some(data) => {
193 let (mode, size, mtime_info) = data;
203 let (mode, size, mtime_info) = data;
194 let mtime = if let Some(mtime_info) = mtime_info {
204 let mtime = if let Some(mtime_info) = mtime_info {
195 let (mtime_s, mtime_ns, second_ambiguous) = mtime_info;
205 let (mtime_s, mtime_ns, second_ambiguous) = mtime_info;
196 let timestamp = TruncatedTimestamp::new_truncate(
206 let timestamp = TruncatedTimestamp::new_truncate(
197 mtime_s, mtime_ns, second_ambiguous
207 mtime_s, mtime_ns, second_ambiguous
198 );
208 );
199 Some(timestamp)
209 Some(timestamp)
200 } else {
210 } else {
201 has_meaningful_mtime = false;
211 has_meaningful_mtime = false;
202 None
212 None
203 };
213 };
204 Some(ParentFileData {
214 Some(ParentFileData {
205 mode_size: Some((mode, size)),
215 mode_size: Some((mode, size)),
206 mtime,
216 mtime,
207 })
217 })
208 }
218 }
209 };
219 };
210 let bytes = f.extract::<PyBytes>(py)?;
220 let bytes = f.extract::<PyBytes>(py)?;
211 let path = HgPath::new(bytes.data(py));
221 let path = HgPath::new(bytes.data(py));
212 let res = self.inner(py).borrow_mut().reset_state(
222 let res = self.inner(py).borrow_mut().reset_state(
213 path,
223 path,
214 wc_tracked,
224 wc_tracked,
215 p1_tracked,
225 p1_tracked,
216 p2_info,
226 p2_info,
217 has_meaningful_mtime,
227 has_meaningful_mtime,
218 parent_file_data,
228 parent_file_data,
219 );
229 );
220 res.or_else(|_| {
230 res.or_else(|_| {
221 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
231 Err(PyErr::new::<exc::OSError, _>(py, "Dirstate error".to_string()))
222 })?;
232 })?;
223 Ok(PyNone)
233 Ok(PyNone)
224 }
234 }
225
235
226 def removefile(
236 def removefile(
227 &self,
237 &self,
228 f: PyObject,
238 f: PyObject,
229 in_merge: PyObject
239 in_merge: PyObject
230 ) -> PyResult<PyObject> {
240 ) -> PyResult<PyObject> {
231 self.inner(py).borrow_mut()
241 self.inner(py).borrow_mut()
232 .remove_file(
242 .remove_file(
233 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
243 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
234 in_merge.extract::<PyBool>(py)?.is_true(),
244 in_merge.extract::<PyBool>(py)?.is_true(),
235 )
245 )
236 .or_else(|_| {
246 .or_else(|_| {
237 Err(PyErr::new::<exc::OSError, _>(
247 Err(PyErr::new::<exc::OSError, _>(
238 py,
248 py,
239 "Dirstate error".to_string(),
249 "Dirstate error".to_string(),
240 ))
250 ))
241 })?;
251 })?;
242 Ok(py.None())
252 Ok(py.None())
243 }
253 }
244
254
245 def drop_item_and_copy_source(
255 def drop_item_and_copy_source(
246 &self,
256 &self,
247 f: PyBytes,
257 f: PyBytes,
248 ) -> PyResult<PyNone> {
258 ) -> PyResult<PyNone> {
249 self.inner(py)
259 self.inner(py)
250 .borrow_mut()
260 .borrow_mut()
251 .drop_entry_and_copy_source(HgPath::new(f.data(py)))
261 .drop_entry_and_copy_source(HgPath::new(f.data(py)))
252 .map_err(|e |dirstate_error(py, e))?;
262 .map_err(|e |dirstate_error(py, e))?;
253 Ok(PyNone)
263 Ok(PyNone)
254 }
264 }
255
265
256 def hastrackeddir(&self, d: PyObject) -> PyResult<PyBool> {
266 def hastrackeddir(&self, d: PyObject) -> PyResult<PyBool> {
257 let d = d.extract::<PyBytes>(py)?;
267 let d = d.extract::<PyBytes>(py)?;
258 Ok(self.inner(py).borrow_mut()
268 Ok(self.inner(py).borrow_mut()
259 .has_tracked_dir(HgPath::new(d.data(py)))
269 .has_tracked_dir(HgPath::new(d.data(py)))
260 .map_err(|e| {
270 .map_err(|e| {
261 PyErr::new::<exc::ValueError, _>(py, e.to_string())
271 PyErr::new::<exc::ValueError, _>(py, e.to_string())
262 })?
272 })?
263 .to_py_object(py))
273 .to_py_object(py))
264 }
274 }
265
275
266 def hasdir(&self, d: PyObject) -> PyResult<PyBool> {
276 def hasdir(&self, d: PyObject) -> PyResult<PyBool> {
267 let d = d.extract::<PyBytes>(py)?;
277 let d = d.extract::<PyBytes>(py)?;
268 Ok(self.inner(py).borrow_mut()
278 Ok(self.inner(py).borrow_mut()
269 .has_dir(HgPath::new(d.data(py)))
279 .has_dir(HgPath::new(d.data(py)))
270 .map_err(|e| {
280 .map_err(|e| {
271 PyErr::new::<exc::ValueError, _>(py, e.to_string())
281 PyErr::new::<exc::ValueError, _>(py, e.to_string())
272 })?
282 })?
273 .to_py_object(py))
283 .to_py_object(py))
274 }
284 }
275
285
276 def write_v1(
286 def write_v1(
277 &self,
287 &self,
278 p1: PyObject,
288 p1: PyObject,
279 p2: PyObject,
289 p2: PyObject,
280 ) -> PyResult<PyBytes> {
290 ) -> PyResult<PyBytes> {
281 let inner = self.inner(py).borrow();
291 let inner = self.inner(py).borrow();
282 let parents = DirstateParents {
292 let parents = DirstateParents {
283 p1: extract_node_id(py, &p1)?,
293 p1: extract_node_id(py, &p1)?,
284 p2: extract_node_id(py, &p2)?,
294 p2: extract_node_id(py, &p2)?,
285 };
295 };
286 let result = inner.pack_v1(parents);
296 let result = inner.pack_v1(parents);
287 match result {
297 match result {
288 Ok(packed) => Ok(PyBytes::new(py, &packed)),
298 Ok(packed) => Ok(PyBytes::new(py, &packed)),
289 Err(_) => Err(PyErr::new::<exc::OSError, _>(
299 Err(_) => Err(PyErr::new::<exc::OSError, _>(
290 py,
300 py,
291 "Dirstate error".to_string(),
301 "Dirstate error".to_string(),
292 )),
302 )),
293 }
303 }
294 }
304 }
295
305
296 /// Returns new data together with whether that data should be appended to
306 /// Returns new data together with whether that data should be appended to
297 /// the existing data file whose content is at `self.on_disk` (True),
307 /// the existing data file whose content is at `self.on_disk` (True),
298 /// instead of written to a new data file (False).
308 /// instead of written to a new data file (False).
299 def write_v2(
309 def write_v2(
300 &self,
310 &self,
301 can_append: bool,
311 can_append: bool,
302 ) -> PyResult<PyObject> {
312 ) -> PyResult<PyObject> {
303 let inner = self.inner(py).borrow();
313 let inner = self.inner(py).borrow();
304 let result = inner.pack_v2(can_append);
314 let result = inner.pack_v2(can_append);
305 match result {
315 match result {
306 Ok((packed, tree_metadata, append)) => {
316 Ok((packed, tree_metadata, append)) => {
307 let packed = PyBytes::new(py, &packed);
317 let packed = PyBytes::new(py, &packed);
308 let tree_metadata = PyBytes::new(py, tree_metadata.as_bytes());
318 let tree_metadata = PyBytes::new(py, tree_metadata.as_bytes());
309 let tuple = (packed, tree_metadata, append);
319 let tuple = (packed, tree_metadata, append);
310 Ok(tuple.to_py_object(py).into_object())
320 Ok(tuple.to_py_object(py).into_object())
311 },
321 },
312 Err(_) => Err(PyErr::new::<exc::OSError, _>(
322 Err(_) => Err(PyErr::new::<exc::OSError, _>(
313 py,
323 py,
314 "Dirstate error".to_string(),
324 "Dirstate error".to_string(),
315 )),
325 )),
316 }
326 }
317 }
327 }
318
328
319 def filefoldmapasdict(&self) -> PyResult<PyDict> {
329 def filefoldmapasdict(&self) -> PyResult<PyDict> {
320 let dict = PyDict::new(py);
330 let dict = PyDict::new(py);
321 for item in self.inner(py).borrow_mut().iter() {
331 for item in self.inner(py).borrow_mut().iter() {
322 let (path, entry) = item.map_err(|e| v2_error(py, e))?;
332 let (path, entry) = item.map_err(|e| v2_error(py, e))?;
323 if entry.state() != EntryState::Removed {
333 if entry.state() != EntryState::Removed {
324 let key = normalize_case(path);
334 let key = normalize_case(path);
325 let value = path;
335 let value = path;
326 dict.set_item(
336 dict.set_item(
327 py,
337 py,
328 PyBytes::new(py, key.as_bytes()).into_object(),
338 PyBytes::new(py, key.as_bytes()).into_object(),
329 PyBytes::new(py, value.as_bytes()).into_object(),
339 PyBytes::new(py, value.as_bytes()).into_object(),
330 )?;
340 )?;
331 }
341 }
332 }
342 }
333 Ok(dict)
343 Ok(dict)
334 }
344 }
335
345
336 def __len__(&self) -> PyResult<usize> {
346 def __len__(&self) -> PyResult<usize> {
337 Ok(self.inner(py).borrow().len())
347 Ok(self.inner(py).borrow().len())
338 }
348 }
339
349
340 def __contains__(&self, key: PyObject) -> PyResult<bool> {
350 def __contains__(&self, key: PyObject) -> PyResult<bool> {
341 let key = key.extract::<PyBytes>(py)?;
351 let key = key.extract::<PyBytes>(py)?;
342 self.inner(py)
352 self.inner(py)
343 .borrow()
353 .borrow()
344 .contains_key(HgPath::new(key.data(py)))
354 .contains_key(HgPath::new(key.data(py)))
345 .map_err(|e| v2_error(py, e))
355 .map_err(|e| v2_error(py, e))
346 }
356 }
347
357
348 def __getitem__(&self, key: PyObject) -> PyResult<PyObject> {
358 def __getitem__(&self, key: PyObject) -> PyResult<PyObject> {
349 let key = key.extract::<PyBytes>(py)?;
359 let key = key.extract::<PyBytes>(py)?;
350 let key = HgPath::new(key.data(py));
360 let key = HgPath::new(key.data(py));
351 match self
361 match self
352 .inner(py)
362 .inner(py)
353 .borrow()
363 .borrow()
354 .get(key)
364 .get(key)
355 .map_err(|e| v2_error(py, e))?
365 .map_err(|e| v2_error(py, e))?
356 {
366 {
357 Some(entry) => {
367 Some(entry) => {
358 Ok(DirstateItem::new_as_pyobject(py, entry)?)
368 Ok(DirstateItem::new_as_pyobject(py, entry)?)
359 },
369 },
360 None => Err(PyErr::new::<exc::KeyError, _>(
370 None => Err(PyErr::new::<exc::KeyError, _>(
361 py,
371 py,
362 String::from_utf8_lossy(key.as_bytes()),
372 String::from_utf8_lossy(key.as_bytes()),
363 )),
373 )),
364 }
374 }
365 }
375 }
366
376
367 def keys(&self) -> PyResult<DirstateMapKeysIterator> {
377 def keys(&self) -> PyResult<DirstateMapKeysIterator> {
368 let leaked_ref = self.inner(py).leak_immutable();
378 let leaked_ref = self.inner(py).leak_immutable();
369 DirstateMapKeysIterator::from_inner(
379 DirstateMapKeysIterator::from_inner(
370 py,
380 py,
371 unsafe { leaked_ref.map(py, |o| o.iter()) },
381 unsafe { leaked_ref.map(py, |o| o.iter()) },
372 )
382 )
373 }
383 }
374
384
375 def items(&self) -> PyResult<DirstateMapItemsIterator> {
385 def items(&self) -> PyResult<DirstateMapItemsIterator> {
376 let leaked_ref = self.inner(py).leak_immutable();
386 let leaked_ref = self.inner(py).leak_immutable();
377 DirstateMapItemsIterator::from_inner(
387 DirstateMapItemsIterator::from_inner(
378 py,
388 py,
379 unsafe { leaked_ref.map(py, |o| o.iter()) },
389 unsafe { leaked_ref.map(py, |o| o.iter()) },
380 )
390 )
381 }
391 }
382
392
383 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
393 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
384 let leaked_ref = self.inner(py).leak_immutable();
394 let leaked_ref = self.inner(py).leak_immutable();
385 DirstateMapKeysIterator::from_inner(
395 DirstateMapKeysIterator::from_inner(
386 py,
396 py,
387 unsafe { leaked_ref.map(py, |o| o.iter()) },
397 unsafe { leaked_ref.map(py, |o| o.iter()) },
388 )
398 )
389 }
399 }
390
400
391 // TODO all copymap* methods, see docstring above
401 // TODO all copymap* methods, see docstring above
392 def copymapcopy(&self) -> PyResult<PyDict> {
402 def copymapcopy(&self) -> PyResult<PyDict> {
393 let dict = PyDict::new(py);
403 let dict = PyDict::new(py);
394 for item in self.inner(py).borrow().copy_map_iter() {
404 for item in self.inner(py).borrow().copy_map_iter() {
395 let (key, value) = item.map_err(|e| v2_error(py, e))?;
405 let (key, value) = item.map_err(|e| v2_error(py, e))?;
396 dict.set_item(
406 dict.set_item(
397 py,
407 py,
398 PyBytes::new(py, key.as_bytes()),
408 PyBytes::new(py, key.as_bytes()),
399 PyBytes::new(py, value.as_bytes()),
409 PyBytes::new(py, value.as_bytes()),
400 )?;
410 )?;
401 }
411 }
402 Ok(dict)
412 Ok(dict)
403 }
413 }
404
414
405 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
415 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
406 let key = key.extract::<PyBytes>(py)?;
416 let key = key.extract::<PyBytes>(py)?;
407 match self
417 match self
408 .inner(py)
418 .inner(py)
409 .borrow()
419 .borrow()
410 .copy_map_get(HgPath::new(key.data(py)))
420 .copy_map_get(HgPath::new(key.data(py)))
411 .map_err(|e| v2_error(py, e))?
421 .map_err(|e| v2_error(py, e))?
412 {
422 {
413 Some(copy) => Ok(PyBytes::new(py, copy.as_bytes())),
423 Some(copy) => Ok(PyBytes::new(py, copy.as_bytes())),
414 None => Err(PyErr::new::<exc::KeyError, _>(
424 None => Err(PyErr::new::<exc::KeyError, _>(
415 py,
425 py,
416 String::from_utf8_lossy(key.data(py)),
426 String::from_utf8_lossy(key.data(py)),
417 )),
427 )),
418 }
428 }
419 }
429 }
420 def copymap(&self) -> PyResult<CopyMap> {
430 def copymap(&self) -> PyResult<CopyMap> {
421 CopyMap::from_inner(py, self.clone_ref(py))
431 CopyMap::from_inner(py, self.clone_ref(py))
422 }
432 }
423
433
424 def copymaplen(&self) -> PyResult<usize> {
434 def copymaplen(&self) -> PyResult<usize> {
425 Ok(self.inner(py).borrow().copy_map_len())
435 Ok(self.inner(py).borrow().copy_map_len())
426 }
436 }
427 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
437 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
428 let key = key.extract::<PyBytes>(py)?;
438 let key = key.extract::<PyBytes>(py)?;
429 self.inner(py)
439 self.inner(py)
430 .borrow()
440 .borrow()
431 .copy_map_contains_key(HgPath::new(key.data(py)))
441 .copy_map_contains_key(HgPath::new(key.data(py)))
432 .map_err(|e| v2_error(py, e))
442 .map_err(|e| v2_error(py, e))
433 }
443 }
434 def copymapget(
444 def copymapget(
435 &self,
445 &self,
436 key: PyObject,
446 key: PyObject,
437 default: Option<PyObject>
447 default: Option<PyObject>
438 ) -> PyResult<Option<PyObject>> {
448 ) -> PyResult<Option<PyObject>> {
439 let key = key.extract::<PyBytes>(py)?;
449 let key = key.extract::<PyBytes>(py)?;
440 match self
450 match self
441 .inner(py)
451 .inner(py)
442 .borrow()
452 .borrow()
443 .copy_map_get(HgPath::new(key.data(py)))
453 .copy_map_get(HgPath::new(key.data(py)))
444 .map_err(|e| v2_error(py, e))?
454 .map_err(|e| v2_error(py, e))?
445 {
455 {
446 Some(copy) => Ok(Some(
456 Some(copy) => Ok(Some(
447 PyBytes::new(py, copy.as_bytes()).into_object(),
457 PyBytes::new(py, copy.as_bytes()).into_object(),
448 )),
458 )),
449 None => Ok(default),
459 None => Ok(default),
450 }
460 }
451 }
461 }
452 def copymapsetitem(
462 def copymapsetitem(
453 &self,
463 &self,
454 key: PyObject,
464 key: PyObject,
455 value: PyObject
465 value: PyObject
456 ) -> PyResult<PyObject> {
466 ) -> PyResult<PyObject> {
457 let key = key.extract::<PyBytes>(py)?;
467 let key = key.extract::<PyBytes>(py)?;
458 let value = value.extract::<PyBytes>(py)?;
468 let value = value.extract::<PyBytes>(py)?;
459 self.inner(py)
469 self.inner(py)
460 .borrow_mut()
470 .borrow_mut()
461 .copy_map_insert(
471 .copy_map_insert(
462 HgPathBuf::from_bytes(key.data(py)),
472 HgPathBuf::from_bytes(key.data(py)),
463 HgPathBuf::from_bytes(value.data(py)),
473 HgPathBuf::from_bytes(value.data(py)),
464 )
474 )
465 .map_err(|e| v2_error(py, e))?;
475 .map_err(|e| v2_error(py, e))?;
466 Ok(py.None())
476 Ok(py.None())
467 }
477 }
468 def copymappop(
478 def copymappop(
469 &self,
479 &self,
470 key: PyObject,
480 key: PyObject,
471 default: Option<PyObject>
481 default: Option<PyObject>
472 ) -> PyResult<Option<PyObject>> {
482 ) -> PyResult<Option<PyObject>> {
473 let key = key.extract::<PyBytes>(py)?;
483 let key = key.extract::<PyBytes>(py)?;
474 match self
484 match self
475 .inner(py)
485 .inner(py)
476 .borrow_mut()
486 .borrow_mut()
477 .copy_map_remove(HgPath::new(key.data(py)))
487 .copy_map_remove(HgPath::new(key.data(py)))
478 .map_err(|e| v2_error(py, e))?
488 .map_err(|e| v2_error(py, e))?
479 {
489 {
480 Some(copy) => Ok(Some(
490 Some(copy) => Ok(Some(
481 PyBytes::new(py, copy.as_bytes()).into_object(),
491 PyBytes::new(py, copy.as_bytes()).into_object(),
482 )),
492 )),
483 None => Ok(default),
493 None => Ok(default),
484 }
494 }
485 }
495 }
486
496
487 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
497 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
488 let leaked_ref = self.inner(py).leak_immutable();
498 let leaked_ref = self.inner(py).leak_immutable();
489 CopyMapKeysIterator::from_inner(
499 CopyMapKeysIterator::from_inner(
490 py,
500 py,
491 unsafe { leaked_ref.map(py, |o| o.copy_map_iter()) },
501 unsafe { leaked_ref.map(py, |o| o.copy_map_iter()) },
492 )
502 )
493 }
503 }
494
504
495 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
505 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
496 let leaked_ref = self.inner(py).leak_immutable();
506 let leaked_ref = self.inner(py).leak_immutable();
497 CopyMapItemsIterator::from_inner(
507 CopyMapItemsIterator::from_inner(
498 py,
508 py,
499 unsafe { leaked_ref.map(py, |o| o.copy_map_iter()) },
509 unsafe { leaked_ref.map(py, |o| o.copy_map_iter()) },
500 )
510 )
501 }
511 }
502
512
503 def tracked_dirs(&self) -> PyResult<PyList> {
513 def tracked_dirs(&self) -> PyResult<PyList> {
504 let dirs = PyList::new(py, &[]);
514 let dirs = PyList::new(py, &[]);
505 for path in self.inner(py).borrow_mut().iter_tracked_dirs()
515 for path in self.inner(py).borrow_mut().iter_tracked_dirs()
506 .map_err(|e |dirstate_error(py, e))?
516 .map_err(|e |dirstate_error(py, e))?
507 {
517 {
508 let path = path.map_err(|e| v2_error(py, e))?;
518 let path = path.map_err(|e| v2_error(py, e))?;
509 let path = PyBytes::new(py, path.as_bytes());
519 let path = PyBytes::new(py, path.as_bytes());
510 dirs.append(py, path.into_object())
520 dirs.append(py, path.into_object())
511 }
521 }
512 Ok(dirs)
522 Ok(dirs)
513 }
523 }
514
524
515 def debug_iter(&self, all: bool) -> PyResult<PyList> {
525 def debug_iter(&self, all: bool) -> PyResult<PyList> {
516 let dirs = PyList::new(py, &[]);
526 let dirs = PyList::new(py, &[]);
517 for item in self.inner(py).borrow().debug_iter(all) {
527 for item in self.inner(py).borrow().debug_iter(all) {
518 let (path, (state, mode, size, mtime)) =
528 let (path, (state, mode, size, mtime)) =
519 item.map_err(|e| v2_error(py, e))?;
529 item.map_err(|e| v2_error(py, e))?;
520 let path = PyBytes::new(py, path.as_bytes());
530 let path = PyBytes::new(py, path.as_bytes());
521 let item = (path, state, mode, size, mtime);
531 let item = (path, state, mode, size, mtime);
522 dirs.append(py, item.to_py_object(py).into_object())
532 dirs.append(py, item.to_py_object(py).into_object())
523 }
533 }
524 Ok(dirs)
534 Ok(dirs)
525 }
535 }
526 });
536 });
527
537
528 impl DirstateMap {
538 impl DirstateMap {
529 pub fn get_inner_mut<'a>(
539 pub fn get_inner_mut<'a>(
530 &'a self,
540 &'a self,
531 py: Python<'a>,
541 py: Python<'a>,
532 ) -> RefMut<'a, OwningDirstateMap> {
542 ) -> RefMut<'a, OwningDirstateMap> {
533 self.inner(py).borrow_mut()
543 self.inner(py).borrow_mut()
534 }
544 }
535 fn translate_key(
545 fn translate_key(
536 py: Python,
546 py: Python,
537 res: Result<(&HgPath, DirstateEntry), DirstateV2ParseError>,
547 res: Result<(&HgPath, DirstateEntry), DirstateV2ParseError>,
538 ) -> PyResult<Option<PyBytes>> {
548 ) -> PyResult<Option<PyBytes>> {
539 let (f, _entry) = res.map_err(|e| v2_error(py, e))?;
549 let (f, _entry) = res.map_err(|e| v2_error(py, e))?;
540 Ok(Some(PyBytes::new(py, f.as_bytes())))
550 Ok(Some(PyBytes::new(py, f.as_bytes())))
541 }
551 }
542 fn translate_key_value(
552 fn translate_key_value(
543 py: Python,
553 py: Python,
544 res: Result<(&HgPath, DirstateEntry), DirstateV2ParseError>,
554 res: Result<(&HgPath, DirstateEntry), DirstateV2ParseError>,
545 ) -> PyResult<Option<(PyBytes, PyObject)>> {
555 ) -> PyResult<Option<(PyBytes, PyObject)>> {
546 let (f, entry) = res.map_err(|e| v2_error(py, e))?;
556 let (f, entry) = res.map_err(|e| v2_error(py, e))?;
547 Ok(Some((
557 Ok(Some((
548 PyBytes::new(py, f.as_bytes()),
558 PyBytes::new(py, f.as_bytes()),
549 DirstateItem::new_as_pyobject(py, entry)?,
559 DirstateItem::new_as_pyobject(py, entry)?,
550 )))
560 )))
551 }
561 }
552 }
562 }
553
563
554 py_shared_iterator!(
564 py_shared_iterator!(
555 DirstateMapKeysIterator,
565 DirstateMapKeysIterator,
556 UnsafePyLeaked<StateMapIter<'static>>,
566 UnsafePyLeaked<StateMapIter<'static>>,
557 DirstateMap::translate_key,
567 DirstateMap::translate_key,
558 Option<PyBytes>
568 Option<PyBytes>
559 );
569 );
560
570
561 py_shared_iterator!(
571 py_shared_iterator!(
562 DirstateMapItemsIterator,
572 DirstateMapItemsIterator,
563 UnsafePyLeaked<StateMapIter<'static>>,
573 UnsafePyLeaked<StateMapIter<'static>>,
564 DirstateMap::translate_key_value,
574 DirstateMap::translate_key_value,
565 Option<(PyBytes, PyObject)>
575 Option<(PyBytes, PyObject)>
566 );
576 );
567
577
568 fn extract_node_id(py: Python, obj: &PyObject) -> PyResult<Node> {
578 fn extract_node_id(py: Python, obj: &PyObject) -> PyResult<Node> {
569 let bytes = obj.extract::<PyBytes>(py)?;
579 let bytes = obj.extract::<PyBytes>(py)?;
570 match bytes.data(py).try_into() {
580 match bytes.data(py).try_into() {
571 Ok(s) => Ok(s),
581 Ok(s) => Ok(s),
572 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
582 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
573 }
583 }
574 }
584 }
575
585
576 pub(super) fn v2_error(py: Python<'_>, _: DirstateV2ParseError) -> PyErr {
586 pub(super) fn v2_error(py: Python<'_>, _: DirstateV2ParseError) -> PyErr {
577 PyErr::new::<exc::ValueError, _>(py, "corrupted dirstate-v2")
587 PyErr::new::<exc::ValueError, _>(py, "corrupted dirstate-v2")
578 }
588 }
579
589
580 fn dirstate_error(py: Python<'_>, e: DirstateError) -> PyErr {
590 fn dirstate_error(py: Python<'_>, e: DirstateError) -> PyErr {
581 PyErr::new::<exc::OSError, _>(py, format!("Dirstate error: {:?}", e))
591 PyErr::new::<exc::OSError, _>(py, format!("Dirstate error: {:?}", e))
582 }
592 }
General Comments 0
You need to be logged in to leave comments. Login now