##// END OF EJS Templates
dirstate-tree: Add map `get` and `contains_key` methods...
Simon Sapin -
r47869:3da19db3 default
parent child Browse files
Show More
@@ -1,303 +1,323
1 use std::collections::BTreeMap;
1 use std::collections::BTreeMap;
2 use std::path::PathBuf;
2 use std::path::PathBuf;
3 use std::time::Duration;
3 use std::time::Duration;
4
4
5 use super::path_with_basename::WithBasename;
5 use super::path_with_basename::WithBasename;
6 use crate::dirstate::parsers::parse_dirstate_entries;
6 use crate::dirstate::parsers::parse_dirstate_entries;
7 use crate::dirstate::parsers::parse_dirstate_parents;
7 use crate::dirstate::parsers::parse_dirstate_parents;
8
8
9 use crate::matchers::Matcher;
9 use crate::matchers::Matcher;
10 use crate::revlog::node::NULL_NODE;
10 use crate::revlog::node::NULL_NODE;
11 use crate::utils::hg_path::{HgPath, HgPathBuf};
11 use crate::utils::hg_path::{HgPath, HgPathBuf};
12 use crate::CopyMapIter;
12 use crate::CopyMapIter;
13 use crate::DirstateEntry;
13 use crate::DirstateEntry;
14 use crate::DirstateError;
14 use crate::DirstateError;
15 use crate::DirstateMapError;
15 use crate::DirstateMapError;
16 use crate::DirstateParents;
16 use crate::DirstateParents;
17 use crate::DirstateStatus;
17 use crate::DirstateStatus;
18 use crate::EntryState;
18 use crate::EntryState;
19 use crate::FastHashMap;
19 use crate::FastHashMap;
20 use crate::HgPathCow;
20 use crate::HgPathCow;
21 use crate::PatternFileWarning;
21 use crate::PatternFileWarning;
22 use crate::StateMapIter;
22 use crate::StateMapIter;
23 use crate::StatusError;
23 use crate::StatusError;
24 use crate::StatusOptions;
24 use crate::StatusOptions;
25
25
26 pub struct DirstateMap {
26 pub struct DirstateMap {
27 parents: Option<DirstateParents>,
27 parents: Option<DirstateParents>,
28 dirty_parents: bool,
28 dirty_parents: bool,
29 root: ChildNodes,
29 root: ChildNodes,
30 }
30 }
31
31
32 /// Using a plain `HgPathBuf` of the full path from the repository root as a
32 /// Using a plain `HgPathBuf` of the full path from the repository root as a
33 /// map key would also work: all paths in a given map have the same parent
33 /// map key would also work: all paths in a given map have the same parent
34 /// path, so comparing full paths gives the same result as comparing base
34 /// path, so comparing full paths gives the same result as comparing base
35 /// names. However `BTreeMap` would waste time always re-comparing the same
35 /// names. However `BTreeMap` would waste time always re-comparing the same
36 /// string prefix.
36 /// string prefix.
37 type ChildNodes = BTreeMap<WithBasename<HgPathBuf>, Node>;
37 type ChildNodes = BTreeMap<WithBasename<HgPathBuf>, Node>;
38
38
39 #[derive(Default)]
39 #[derive(Default)]
40 struct Node {
40 struct Node {
41 entry: Option<DirstateEntry>,
41 entry: Option<DirstateEntry>,
42 copy_source: Option<HgPathBuf>,
42 copy_source: Option<HgPathBuf>,
43 children: ChildNodes,
43 children: ChildNodes,
44 }
44 }
45
45
46 impl DirstateMap {
46 impl DirstateMap {
47 pub fn new() -> Self {
47 pub fn new() -> Self {
48 Self {
48 Self {
49 parents: None,
49 parents: None,
50 dirty_parents: false,
50 dirty_parents: false,
51 root: ChildNodes::new(),
51 root: ChildNodes::new(),
52 }
52 }
53 }
53 }
54
54
55 fn get_node(&self, path: &HgPath) -> Option<&Node> {
56 let mut children = &self.root;
57 let mut components = path.components();
58 let mut component =
59 components.next().expect("expected at least one components");
60 loop {
61 let child = children.get(component)?;
62 if let Some(next_component) = components.next() {
63 component = next_component;
64 children = &child.children;
65 } else {
66 return Some(child);
67 }
68 }
69 }
70
55 fn get_or_insert_node(&mut self, path: &HgPath) -> &mut Node {
71 fn get_or_insert_node(&mut self, path: &HgPath) -> &mut Node {
56 let mut child_nodes = &mut self.root;
72 let mut child_nodes = &mut self.root;
57 let mut inclusive_ancestor_paths =
73 let mut inclusive_ancestor_paths =
58 WithBasename::inclusive_ancestors_of(path);
74 WithBasename::inclusive_ancestors_of(path);
59 let mut ancestor_path = inclusive_ancestor_paths
75 let mut ancestor_path = inclusive_ancestor_paths
60 .next()
76 .next()
61 .expect("expected at least one inclusive ancestor");
77 .expect("expected at least one inclusive ancestor");
62 loop {
78 loop {
63 // TODO: can we avoid double lookup in all cases without allocating
79 // TODO: can we avoid double lookup in all cases without allocating
64 // an owned key in cases where the map already contains that key?
80 // an owned key in cases where the map already contains that key?
65 let child_node =
81 let child_node =
66 if child_nodes.contains_key(ancestor_path.base_name()) {
82 if child_nodes.contains_key(ancestor_path.base_name()) {
67 child_nodes.get_mut(ancestor_path.base_name()).unwrap()
83 child_nodes.get_mut(ancestor_path.base_name()).unwrap()
68 } else {
84 } else {
69 // This is always a vacant entry, using `.entry()` lets us
85 // This is always a vacant entry, using `.entry()` lets us
70 // return a `&mut Node` of the newly-inserted node without
86 // return a `&mut Node` of the newly-inserted node without
71 // yet another lookup. `BTreeMap::insert` doesn’t do this.
87 // yet another lookup. `BTreeMap::insert` doesn’t do this.
72 child_nodes.entry(ancestor_path.to_owned()).or_default()
88 child_nodes.entry(ancestor_path.to_owned()).or_default()
73 };
89 };
74 if let Some(next) = inclusive_ancestor_paths.next() {
90 if let Some(next) = inclusive_ancestor_paths.next() {
75 ancestor_path = next;
91 ancestor_path = next;
76 child_nodes = &mut child_node.children;
92 child_nodes = &mut child_node.children;
77 } else {
93 } else {
78 return child_node;
94 return child_node;
79 }
95 }
80 }
96 }
81 }
97 }
82 }
98 }
83
99
84 impl super::dispatch::DirstateMapMethods for DirstateMap {
100 impl super::dispatch::DirstateMapMethods for DirstateMap {
85 fn clear(&mut self) {
101 fn clear(&mut self) {
86 self.set_parents(&DirstateParents {
102 self.set_parents(&DirstateParents {
87 p1: NULL_NODE,
103 p1: NULL_NODE,
88 p2: NULL_NODE,
104 p2: NULL_NODE,
89 });
105 });
90 self.root.clear()
106 self.root.clear()
91 }
107 }
92
108
93 fn add_file(
109 fn add_file(
94 &mut self,
110 &mut self,
95 _filename: &HgPath,
111 _filename: &HgPath,
96 _old_state: EntryState,
112 _old_state: EntryState,
97 _entry: DirstateEntry,
113 _entry: DirstateEntry,
98 ) -> Result<(), DirstateMapError> {
114 ) -> Result<(), DirstateMapError> {
99 todo!()
115 todo!()
100 }
116 }
101
117
102 fn remove_file(
118 fn remove_file(
103 &mut self,
119 &mut self,
104 _filename: &HgPath,
120 _filename: &HgPath,
105 _old_state: EntryState,
121 _old_state: EntryState,
106 _size: i32,
122 _size: i32,
107 ) -> Result<(), DirstateMapError> {
123 ) -> Result<(), DirstateMapError> {
108 todo!()
124 todo!()
109 }
125 }
110
126
111 fn drop_file(
127 fn drop_file(
112 &mut self,
128 &mut self,
113 _filename: &HgPath,
129 _filename: &HgPath,
114 _old_state: EntryState,
130 _old_state: EntryState,
115 ) -> Result<bool, DirstateMapError> {
131 ) -> Result<bool, DirstateMapError> {
116 todo!()
132 todo!()
117 }
133 }
118
134
119 fn clear_ambiguous_times(
135 fn clear_ambiguous_times(
120 &mut self,
136 &mut self,
121 _filenames: Vec<HgPathBuf>,
137 _filenames: Vec<HgPathBuf>,
122 _now: i32,
138 _now: i32,
123 ) {
139 ) {
124 todo!()
140 todo!()
125 }
141 }
126
142
127 fn non_normal_entries_contains(&mut self, _key: &HgPath) -> bool {
143 fn non_normal_entries_contains(&mut self, _key: &HgPath) -> bool {
128 todo!()
144 todo!()
129 }
145 }
130
146
131 fn non_normal_entries_remove(&mut self, _key: &HgPath) -> bool {
147 fn non_normal_entries_remove(&mut self, _key: &HgPath) -> bool {
132 todo!()
148 todo!()
133 }
149 }
134
150
135 fn non_normal_or_other_parent_paths(
151 fn non_normal_or_other_parent_paths(
136 &mut self,
152 &mut self,
137 ) -> Box<dyn Iterator<Item = &HgPathBuf> + '_> {
153 ) -> Box<dyn Iterator<Item = &HgPathBuf> + '_> {
138 todo!()
154 todo!()
139 }
155 }
140
156
141 fn set_non_normal_other_parent_entries(&mut self, _force: bool) {
157 fn set_non_normal_other_parent_entries(&mut self, _force: bool) {
142 todo!()
158 todo!()
143 }
159 }
144
160
145 fn iter_non_normal_paths(
161 fn iter_non_normal_paths(
146 &mut self,
162 &mut self,
147 ) -> Box<dyn Iterator<Item = &HgPathBuf> + Send + '_> {
163 ) -> Box<dyn Iterator<Item = &HgPathBuf> + Send + '_> {
148 todo!()
164 todo!()
149 }
165 }
150
166
151 fn iter_non_normal_paths_panic(
167 fn iter_non_normal_paths_panic(
152 &self,
168 &self,
153 ) -> Box<dyn Iterator<Item = &HgPathBuf> + Send + '_> {
169 ) -> Box<dyn Iterator<Item = &HgPathBuf> + Send + '_> {
154 todo!()
170 todo!()
155 }
171 }
156
172
157 fn iter_other_parent_paths(
173 fn iter_other_parent_paths(
158 &mut self,
174 &mut self,
159 ) -> Box<dyn Iterator<Item = &HgPathBuf> + Send + '_> {
175 ) -> Box<dyn Iterator<Item = &HgPathBuf> + Send + '_> {
160 todo!()
176 todo!()
161 }
177 }
162
178
163 fn has_tracked_dir(
179 fn has_tracked_dir(
164 &mut self,
180 &mut self,
165 _directory: &HgPath,
181 _directory: &HgPath,
166 ) -> Result<bool, DirstateMapError> {
182 ) -> Result<bool, DirstateMapError> {
167 todo!()
183 todo!()
168 }
184 }
169
185
170 fn has_dir(
186 fn has_dir(
171 &mut self,
187 &mut self,
172 _directory: &HgPath,
188 _directory: &HgPath,
173 ) -> Result<bool, DirstateMapError> {
189 ) -> Result<bool, DirstateMapError> {
174 todo!()
190 todo!()
175 }
191 }
176
192
177 fn parents(
193 fn parents(
178 &mut self,
194 &mut self,
179 file_contents: &[u8],
195 file_contents: &[u8],
180 ) -> Result<&DirstateParents, DirstateError> {
196 ) -> Result<&DirstateParents, DirstateError> {
181 if self.parents.is_none() {
197 if self.parents.is_none() {
182 let parents = if !file_contents.is_empty() {
198 let parents = if !file_contents.is_empty() {
183 parse_dirstate_parents(file_contents)?.clone()
199 parse_dirstate_parents(file_contents)?.clone()
184 } else {
200 } else {
185 DirstateParents {
201 DirstateParents {
186 p1: NULL_NODE,
202 p1: NULL_NODE,
187 p2: NULL_NODE,
203 p2: NULL_NODE,
188 }
204 }
189 };
205 };
190 self.parents = Some(parents);
206 self.parents = Some(parents);
191 }
207 }
192 Ok(self.parents.as_ref().unwrap())
208 Ok(self.parents.as_ref().unwrap())
193 }
209 }
194
210
195 fn set_parents(&mut self, parents: &DirstateParents) {
211 fn set_parents(&mut self, parents: &DirstateParents) {
196 self.parents = Some(parents.clone());
212 self.parents = Some(parents.clone());
197 self.dirty_parents = true;
213 self.dirty_parents = true;
198 }
214 }
199
215
200 fn read<'a>(
216 fn read<'a>(
201 &mut self,
217 &mut self,
202 file_contents: &'a [u8],
218 file_contents: &'a [u8],
203 ) -> Result<Option<&'a DirstateParents>, DirstateError> {
219 ) -> Result<Option<&'a DirstateParents>, DirstateError> {
204 if file_contents.is_empty() {
220 if file_contents.is_empty() {
205 return Ok(None);
221 return Ok(None);
206 }
222 }
207
223
208 let parents = parse_dirstate_entries(
224 let parents = parse_dirstate_entries(
209 file_contents,
225 file_contents,
210 |path, entry, copy_source| {
226 |path, entry, copy_source| {
211 let node = self.get_or_insert_node(path);
227 let node = self.get_or_insert_node(path);
212 node.entry = Some(*entry);
228 node.entry = Some(*entry);
213 node.copy_source = copy_source.map(HgPath::to_owned);
229 node.copy_source = copy_source.map(HgPath::to_owned);
214 },
230 },
215 )?;
231 )?;
216
232
217 if !self.dirty_parents {
233 if !self.dirty_parents {
218 self.set_parents(parents);
234 self.set_parents(parents);
219 }
235 }
220
236
221 Ok(Some(parents))
237 Ok(Some(parents))
222 }
238 }
223
239
224 fn pack(
240 fn pack(
225 &mut self,
241 &mut self,
226 _parents: DirstateParents,
242 _parents: DirstateParents,
227 _now: Duration,
243 _now: Duration,
228 ) -> Result<Vec<u8>, DirstateError> {
244 ) -> Result<Vec<u8>, DirstateError> {
229 todo!()
245 todo!()
230 }
246 }
231
247
232 fn build_file_fold_map(&mut self) -> &FastHashMap<HgPathBuf, HgPathBuf> {
248 fn build_file_fold_map(&mut self) -> &FastHashMap<HgPathBuf, HgPathBuf> {
233 todo!()
249 todo!()
234 }
250 }
235
251
236 fn set_all_dirs(&mut self) -> Result<(), DirstateMapError> {
252 fn set_all_dirs(&mut self) -> Result<(), DirstateMapError> {
237 todo!()
253 todo!()
238 }
254 }
239
255
240 fn set_dirs(&mut self) -> Result<(), DirstateMapError> {
256 fn set_dirs(&mut self) -> Result<(), DirstateMapError> {
241 todo!()
257 todo!()
242 }
258 }
243
259
244 fn status<'a>(
260 fn status<'a>(
245 &'a self,
261 &'a self,
246 _matcher: &'a (dyn Matcher + Sync),
262 _matcher: &'a (dyn Matcher + Sync),
247 _root_dir: PathBuf,
263 _root_dir: PathBuf,
248 _ignore_files: Vec<PathBuf>,
264 _ignore_files: Vec<PathBuf>,
249 _options: StatusOptions,
265 _options: StatusOptions,
250 ) -> Result<
266 ) -> Result<
251 (
267 (
252 (Vec<HgPathCow<'a>>, DirstateStatus<'a>),
268 (Vec<HgPathCow<'a>>, DirstateStatus<'a>),
253 Vec<PatternFileWarning>,
269 Vec<PatternFileWarning>,
254 ),
270 ),
255 StatusError,
271 StatusError,
256 > {
272 > {
257 todo!()
273 todo!()
258 }
274 }
259
275
260 fn copy_map_len(&self) -> usize {
276 fn copy_map_len(&self) -> usize {
261 todo!()
277 todo!()
262 }
278 }
263
279
264 fn copy_map_iter(&self) -> CopyMapIter<'_> {
280 fn copy_map_iter(&self) -> CopyMapIter<'_> {
265 todo!()
281 todo!()
266 }
282 }
267
283
268 fn copy_map_contains_key(&self, _key: &HgPath) -> bool {
284 fn copy_map_contains_key(&self, key: &HgPath) -> bool {
269 todo!()
285 if let Some(node) = self.get_node(key) {
286 node.copy_source.is_some()
287 } else {
288 false
289 }
270 }
290 }
271
291
272 fn copy_map_get(&self, _key: &HgPath) -> Option<&HgPathBuf> {
292 fn copy_map_get(&self, key: &HgPath) -> Option<&HgPathBuf> {
273 todo!()
293 self.get_node(key)?.copy_source.as_ref()
274 }
294 }
275
295
276 fn copy_map_remove(&mut self, _key: &HgPath) -> Option<HgPathBuf> {
296 fn copy_map_remove(&mut self, _key: &HgPath) -> Option<HgPathBuf> {
277 todo!()
297 todo!()
278 }
298 }
279
299
280 fn copy_map_insert(
300 fn copy_map_insert(
281 &mut self,
301 &mut self,
282 _key: HgPathBuf,
302 _key: HgPathBuf,
283 _value: HgPathBuf,
303 _value: HgPathBuf,
284 ) -> Option<HgPathBuf> {
304 ) -> Option<HgPathBuf> {
285 todo!()
305 todo!()
286 }
306 }
287
307
288 fn len(&self) -> usize {
308 fn len(&self) -> usize {
289 todo!()
309 todo!()
290 }
310 }
291
311
292 fn contains_key(&self, _key: &HgPath) -> bool {
312 fn contains_key(&self, key: &HgPath) -> bool {
293 todo!()
313 self.get(key).is_some()
294 }
314 }
295
315
296 fn get(&self, _key: &HgPath) -> Option<&DirstateEntry> {
316 fn get(&self, key: &HgPath) -> Option<&DirstateEntry> {
297 todo!()
317 self.get_node(key)?.entry.as_ref()
298 }
318 }
299
319
300 fn iter(&self) -> StateMapIter<'_> {
320 fn iter(&self) -> StateMapIter<'_> {
301 todo!()
321 todo!()
302 }
322 }
303 }
323 }
@@ -1,780 +1,785
1 // hg_path.rs
1 // hg_path.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 use std::borrow::Borrow;
8 use std::borrow::Borrow;
9 use std::convert::TryFrom;
9 use std::convert::TryFrom;
10 use std::ffi::{OsStr, OsString};
10 use std::ffi::{OsStr, OsString};
11 use std::fmt;
11 use std::fmt;
12 use std::ops::Deref;
12 use std::ops::Deref;
13 use std::path::{Path, PathBuf};
13 use std::path::{Path, PathBuf};
14
14
15 #[derive(Debug, Eq, PartialEq)]
15 #[derive(Debug, Eq, PartialEq)]
16 pub enum HgPathError {
16 pub enum HgPathError {
17 /// Bytes from the invalid `HgPath`
17 /// Bytes from the invalid `HgPath`
18 LeadingSlash(Vec<u8>),
18 LeadingSlash(Vec<u8>),
19 ConsecutiveSlashes {
19 ConsecutiveSlashes {
20 bytes: Vec<u8>,
20 bytes: Vec<u8>,
21 second_slash_index: usize,
21 second_slash_index: usize,
22 },
22 },
23 ContainsNullByte {
23 ContainsNullByte {
24 bytes: Vec<u8>,
24 bytes: Vec<u8>,
25 null_byte_index: usize,
25 null_byte_index: usize,
26 },
26 },
27 /// Bytes
27 /// Bytes
28 DecodeError(Vec<u8>),
28 DecodeError(Vec<u8>),
29 /// The rest come from audit errors
29 /// The rest come from audit errors
30 EndsWithSlash(HgPathBuf),
30 EndsWithSlash(HgPathBuf),
31 ContainsIllegalComponent(HgPathBuf),
31 ContainsIllegalComponent(HgPathBuf),
32 /// Path is inside the `.hg` folder
32 /// Path is inside the `.hg` folder
33 InsideDotHg(HgPathBuf),
33 InsideDotHg(HgPathBuf),
34 IsInsideNestedRepo {
34 IsInsideNestedRepo {
35 path: HgPathBuf,
35 path: HgPathBuf,
36 nested_repo: HgPathBuf,
36 nested_repo: HgPathBuf,
37 },
37 },
38 TraversesSymbolicLink {
38 TraversesSymbolicLink {
39 path: HgPathBuf,
39 path: HgPathBuf,
40 symlink: HgPathBuf,
40 symlink: HgPathBuf,
41 },
41 },
42 NotFsCompliant(HgPathBuf),
42 NotFsCompliant(HgPathBuf),
43 /// `path` is the smallest invalid path
43 /// `path` is the smallest invalid path
44 NotUnderRoot {
44 NotUnderRoot {
45 path: PathBuf,
45 path: PathBuf,
46 root: PathBuf,
46 root: PathBuf,
47 },
47 },
48 }
48 }
49
49
50 impl fmt::Display for HgPathError {
50 impl fmt::Display for HgPathError {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 match self {
52 match self {
53 HgPathError::LeadingSlash(bytes) => {
53 HgPathError::LeadingSlash(bytes) => {
54 write!(f, "Invalid HgPath '{:?}': has a leading slash.", bytes)
54 write!(f, "Invalid HgPath '{:?}': has a leading slash.", bytes)
55 }
55 }
56 HgPathError::ConsecutiveSlashes {
56 HgPathError::ConsecutiveSlashes {
57 bytes,
57 bytes,
58 second_slash_index: pos,
58 second_slash_index: pos,
59 } => write!(
59 } => write!(
60 f,
60 f,
61 "Invalid HgPath '{:?}': consecutive slashes at pos {}.",
61 "Invalid HgPath '{:?}': consecutive slashes at pos {}.",
62 bytes, pos
62 bytes, pos
63 ),
63 ),
64 HgPathError::ContainsNullByte {
64 HgPathError::ContainsNullByte {
65 bytes,
65 bytes,
66 null_byte_index: pos,
66 null_byte_index: pos,
67 } => write!(
67 } => write!(
68 f,
68 f,
69 "Invalid HgPath '{:?}': contains null byte at pos {}.",
69 "Invalid HgPath '{:?}': contains null byte at pos {}.",
70 bytes, pos
70 bytes, pos
71 ),
71 ),
72 HgPathError::DecodeError(bytes) => write!(
72 HgPathError::DecodeError(bytes) => write!(
73 f,
73 f,
74 "Invalid HgPath '{:?}': could not be decoded.",
74 "Invalid HgPath '{:?}': could not be decoded.",
75 bytes
75 bytes
76 ),
76 ),
77 HgPathError::EndsWithSlash(path) => {
77 HgPathError::EndsWithSlash(path) => {
78 write!(f, "Audit failed for '{}': ends with a slash.", path)
78 write!(f, "Audit failed for '{}': ends with a slash.", path)
79 }
79 }
80 HgPathError::ContainsIllegalComponent(path) => write!(
80 HgPathError::ContainsIllegalComponent(path) => write!(
81 f,
81 f,
82 "Audit failed for '{}': contains an illegal component.",
82 "Audit failed for '{}': contains an illegal component.",
83 path
83 path
84 ),
84 ),
85 HgPathError::InsideDotHg(path) => write!(
85 HgPathError::InsideDotHg(path) => write!(
86 f,
86 f,
87 "Audit failed for '{}': is inside the '.hg' folder.",
87 "Audit failed for '{}': is inside the '.hg' folder.",
88 path
88 path
89 ),
89 ),
90 HgPathError::IsInsideNestedRepo {
90 HgPathError::IsInsideNestedRepo {
91 path,
91 path,
92 nested_repo: nested,
92 nested_repo: nested,
93 } => {
93 } => {
94 write!(f,
94 write!(f,
95 "Audit failed for '{}': is inside a nested repository '{}'.",
95 "Audit failed for '{}': is inside a nested repository '{}'.",
96 path, nested
96 path, nested
97 )
97 )
98 }
98 }
99 HgPathError::TraversesSymbolicLink { path, symlink } => write!(
99 HgPathError::TraversesSymbolicLink { path, symlink } => write!(
100 f,
100 f,
101 "Audit failed for '{}': traverses symbolic link '{}'.",
101 "Audit failed for '{}': traverses symbolic link '{}'.",
102 path, symlink
102 path, symlink
103 ),
103 ),
104 HgPathError::NotFsCompliant(path) => write!(
104 HgPathError::NotFsCompliant(path) => write!(
105 f,
105 f,
106 "Audit failed for '{}': cannot be turned into a \
106 "Audit failed for '{}': cannot be turned into a \
107 filesystem path.",
107 filesystem path.",
108 path
108 path
109 ),
109 ),
110 HgPathError::NotUnderRoot { path, root } => write!(
110 HgPathError::NotUnderRoot { path, root } => write!(
111 f,
111 f,
112 "Audit failed for '{}': not under root {}.",
112 "Audit failed for '{}': not under root {}.",
113 path.display(),
113 path.display(),
114 root.display()
114 root.display()
115 ),
115 ),
116 }
116 }
117 }
117 }
118 }
118 }
119
119
120 impl From<HgPathError> for std::io::Error {
120 impl From<HgPathError> for std::io::Error {
121 fn from(e: HgPathError) -> Self {
121 fn from(e: HgPathError) -> Self {
122 std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
122 std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
123 }
123 }
124 }
124 }
125
125
126 /// This is a repository-relative path (or canonical path):
126 /// This is a repository-relative path (or canonical path):
127 /// - no null characters
127 /// - no null characters
128 /// - `/` separates directories
128 /// - `/` separates directories
129 /// - no consecutive slashes
129 /// - no consecutive slashes
130 /// - no leading slash,
130 /// - no leading slash,
131 /// - no `.` nor `..` of special meaning
131 /// - no `.` nor `..` of special meaning
132 /// - stored in repository and shared across platforms
132 /// - stored in repository and shared across platforms
133 ///
133 ///
134 /// Note: there is no guarantee of any `HgPath` being well-formed at any point
134 /// Note: there is no guarantee of any `HgPath` being well-formed at any point
135 /// in its lifetime for performance reasons and to ease ergonomics. It is
135 /// in its lifetime for performance reasons and to ease ergonomics. It is
136 /// however checked using the `check_state` method before any file-system
136 /// however checked using the `check_state` method before any file-system
137 /// operation.
137 /// operation.
138 ///
138 ///
139 /// This allows us to be encoding-transparent as much as possible, until really
139 /// This allows us to be encoding-transparent as much as possible, until really
140 /// needed; `HgPath` can be transformed into a platform-specific path (`OsStr`
140 /// needed; `HgPath` can be transformed into a platform-specific path (`OsStr`
141 /// or `Path`) whenever more complex operations are needed:
141 /// or `Path`) whenever more complex operations are needed:
142 /// On Unix, it's just byte-to-byte conversion. On Windows, it has to be
142 /// On Unix, it's just byte-to-byte conversion. On Windows, it has to be
143 /// decoded from MBCS to WTF-8. If WindowsUTF8Plan is implemented, the source
143 /// decoded from MBCS to WTF-8. If WindowsUTF8Plan is implemented, the source
144 /// character encoding will be determined on a per-repository basis.
144 /// character encoding will be determined on a per-repository basis.
145 //
145 //
146 // FIXME: (adapted from a comment in the stdlib)
146 // FIXME: (adapted from a comment in the stdlib)
147 // `HgPath::new()` current implementation relies on `Slice` being
147 // `HgPath::new()` current implementation relies on `Slice` being
148 // layout-compatible with `[u8]`.
148 // layout-compatible with `[u8]`.
149 // When attribute privacy is implemented, `Slice` should be annotated as
149 // When attribute privacy is implemented, `Slice` should be annotated as
150 // `#[repr(transparent)]`.
150 // `#[repr(transparent)]`.
151 // Anyway, `Slice` representation and layout are considered implementation
151 // Anyway, `Slice` representation and layout are considered implementation
152 // detail, are not documented and must not be relied upon.
152 // detail, are not documented and must not be relied upon.
153 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash)]
153 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash)]
154 pub struct HgPath {
154 pub struct HgPath {
155 inner: [u8],
155 inner: [u8],
156 }
156 }
157
157
158 impl HgPath {
158 impl HgPath {
159 pub fn new<S: AsRef<[u8]> + ?Sized>(s: &S) -> &Self {
159 pub fn new<S: AsRef<[u8]> + ?Sized>(s: &S) -> &Self {
160 unsafe { &*(s.as_ref() as *const [u8] as *const Self) }
160 unsafe { &*(s.as_ref() as *const [u8] as *const Self) }
161 }
161 }
162 pub fn is_empty(&self) -> bool {
162 pub fn is_empty(&self) -> bool {
163 self.inner.is_empty()
163 self.inner.is_empty()
164 }
164 }
165 pub fn len(&self) -> usize {
165 pub fn len(&self) -> usize {
166 self.inner.len()
166 self.inner.len()
167 }
167 }
168 fn to_hg_path_buf(&self) -> HgPathBuf {
168 fn to_hg_path_buf(&self) -> HgPathBuf {
169 HgPathBuf {
169 HgPathBuf {
170 inner: self.inner.to_owned(),
170 inner: self.inner.to_owned(),
171 }
171 }
172 }
172 }
173 pub fn bytes(&self) -> std::slice::Iter<u8> {
173 pub fn bytes(&self) -> std::slice::Iter<u8> {
174 self.inner.iter()
174 self.inner.iter()
175 }
175 }
176 pub fn to_ascii_uppercase(&self) -> HgPathBuf {
176 pub fn to_ascii_uppercase(&self) -> HgPathBuf {
177 HgPathBuf::from(self.inner.to_ascii_uppercase())
177 HgPathBuf::from(self.inner.to_ascii_uppercase())
178 }
178 }
179 pub fn to_ascii_lowercase(&self) -> HgPathBuf {
179 pub fn to_ascii_lowercase(&self) -> HgPathBuf {
180 HgPathBuf::from(self.inner.to_ascii_lowercase())
180 HgPathBuf::from(self.inner.to_ascii_lowercase())
181 }
181 }
182 pub fn as_bytes(&self) -> &[u8] {
182 pub fn as_bytes(&self) -> &[u8] {
183 &self.inner
183 &self.inner
184 }
184 }
185 pub fn contains(&self, other: u8) -> bool {
185 pub fn contains(&self, other: u8) -> bool {
186 self.inner.contains(&other)
186 self.inner.contains(&other)
187 }
187 }
188 pub fn starts_with(&self, needle: impl AsRef<Self>) -> bool {
188 pub fn starts_with(&self, needle: impl AsRef<Self>) -> bool {
189 self.inner.starts_with(needle.as_ref().as_bytes())
189 self.inner.starts_with(needle.as_ref().as_bytes())
190 }
190 }
191 pub fn trim_trailing_slash(&self) -> &Self {
191 pub fn trim_trailing_slash(&self) -> &Self {
192 Self::new(if self.inner.last() == Some(&b'/') {
192 Self::new(if self.inner.last() == Some(&b'/') {
193 &self.inner[..self.inner.len() - 1]
193 &self.inner[..self.inner.len() - 1]
194 } else {
194 } else {
195 &self.inner[..]
195 &self.inner[..]
196 })
196 })
197 }
197 }
198 /// Returns a tuple of slices `(base, filename)` resulting from the split
198 /// Returns a tuple of slices `(base, filename)` resulting from the split
199 /// at the rightmost `/`, if any.
199 /// at the rightmost `/`, if any.
200 ///
200 ///
201 /// # Examples:
201 /// # Examples:
202 ///
202 ///
203 /// ```
203 /// ```
204 /// use hg::utils::hg_path::HgPath;
204 /// use hg::utils::hg_path::HgPath;
205 ///
205 ///
206 /// let path = HgPath::new(b"cool/hg/path").split_filename();
206 /// let path = HgPath::new(b"cool/hg/path").split_filename();
207 /// assert_eq!(path, (HgPath::new(b"cool/hg"), HgPath::new(b"path")));
207 /// assert_eq!(path, (HgPath::new(b"cool/hg"), HgPath::new(b"path")));
208 ///
208 ///
209 /// let path = HgPath::new(b"pathwithoutsep").split_filename();
209 /// let path = HgPath::new(b"pathwithoutsep").split_filename();
210 /// assert_eq!(path, (HgPath::new(b""), HgPath::new(b"pathwithoutsep")));
210 /// assert_eq!(path, (HgPath::new(b""), HgPath::new(b"pathwithoutsep")));
211 /// ```
211 /// ```
212 pub fn split_filename(&self) -> (&Self, &Self) {
212 pub fn split_filename(&self) -> (&Self, &Self) {
213 match &self.inner.iter().rposition(|c| *c == b'/') {
213 match &self.inner.iter().rposition(|c| *c == b'/') {
214 None => (HgPath::new(""), &self),
214 None => (HgPath::new(""), &self),
215 Some(size) => (
215 Some(size) => (
216 HgPath::new(&self.inner[..*size]),
216 HgPath::new(&self.inner[..*size]),
217 HgPath::new(&self.inner[*size + 1..]),
217 HgPath::new(&self.inner[*size + 1..]),
218 ),
218 ),
219 }
219 }
220 }
220 }
221 pub fn join<T: ?Sized + AsRef<Self>>(&self, other: &T) -> HgPathBuf {
221 pub fn join<T: ?Sized + AsRef<Self>>(&self, other: &T) -> HgPathBuf {
222 let mut inner = self.inner.to_owned();
222 let mut inner = self.inner.to_owned();
223 if !inner.is_empty() && inner.last() != Some(&b'/') {
223 if !inner.is_empty() && inner.last() != Some(&b'/') {
224 inner.push(b'/');
224 inner.push(b'/');
225 }
225 }
226 inner.extend(other.as_ref().bytes());
226 inner.extend(other.as_ref().bytes());
227 HgPathBuf::from_bytes(&inner)
227 HgPathBuf::from_bytes(&inner)
228 }
228 }
229
230 pub fn components(&self) -> impl Iterator<Item = &HgPath> {
231 self.inner.split(|&byte| byte == b'/').map(HgPath::new)
232 }
233
229 pub fn parent(&self) -> &Self {
234 pub fn parent(&self) -> &Self {
230 let inner = self.as_bytes();
235 let inner = self.as_bytes();
231 HgPath::new(match inner.iter().rposition(|b| *b == b'/') {
236 HgPath::new(match inner.iter().rposition(|b| *b == b'/') {
232 Some(pos) => &inner[..pos],
237 Some(pos) => &inner[..pos],
233 None => &[],
238 None => &[],
234 })
239 })
235 }
240 }
236 /// Given a base directory, returns the slice of `self` relative to the
241 /// Given a base directory, returns the slice of `self` relative to the
237 /// base directory. If `base` is not a directory (does not end with a
242 /// base directory. If `base` is not a directory (does not end with a
238 /// `b'/'`), returns `None`.
243 /// `b'/'`), returns `None`.
239 pub fn relative_to(&self, base: impl AsRef<Self>) -> Option<&Self> {
244 pub fn relative_to(&self, base: impl AsRef<Self>) -> Option<&Self> {
240 let base = base.as_ref();
245 let base = base.as_ref();
241 if base.is_empty() {
246 if base.is_empty() {
242 return Some(self);
247 return Some(self);
243 }
248 }
244 let is_dir = base.as_bytes().ends_with(b"/");
249 let is_dir = base.as_bytes().ends_with(b"/");
245 if is_dir && self.starts_with(base) {
250 if is_dir && self.starts_with(base) {
246 Some(Self::new(&self.inner[base.len()..]))
251 Some(Self::new(&self.inner[base.len()..]))
247 } else {
252 } else {
248 None
253 None
249 }
254 }
250 }
255 }
251
256
252 #[cfg(windows)]
257 #[cfg(windows)]
253 /// Copied from the Python stdlib's `os.path.splitdrive` implementation.
258 /// Copied from the Python stdlib's `os.path.splitdrive` implementation.
254 ///
259 ///
255 /// Split a pathname into drive/UNC sharepoint and relative path
260 /// Split a pathname into drive/UNC sharepoint and relative path
256 /// specifiers. Returns a 2-tuple (drive_or_unc, path); either part may
261 /// specifiers. Returns a 2-tuple (drive_or_unc, path); either part may
257 /// be empty.
262 /// be empty.
258 ///
263 ///
259 /// If you assign
264 /// If you assign
260 /// result = split_drive(p)
265 /// result = split_drive(p)
261 /// It is always true that:
266 /// It is always true that:
262 /// result[0] + result[1] == p
267 /// result[0] + result[1] == p
263 ///
268 ///
264 /// If the path contained a drive letter, drive_or_unc will contain
269 /// If the path contained a drive letter, drive_or_unc will contain
265 /// everything up to and including the colon.
270 /// everything up to and including the colon.
266 /// e.g. split_drive("c:/dir") returns ("c:", "/dir")
271 /// e.g. split_drive("c:/dir") returns ("c:", "/dir")
267 ///
272 ///
268 /// If the path contained a UNC path, the drive_or_unc will contain the
273 /// If the path contained a UNC path, the drive_or_unc will contain the
269 /// host name and share up to but not including the fourth directory
274 /// host name and share up to but not including the fourth directory
270 /// separator character.
275 /// separator character.
271 /// e.g. split_drive("//host/computer/dir") returns ("//host/computer",
276 /// e.g. split_drive("//host/computer/dir") returns ("//host/computer",
272 /// "/dir")
277 /// "/dir")
273 ///
278 ///
274 /// Paths cannot contain both a drive letter and a UNC path.
279 /// Paths cannot contain both a drive letter and a UNC path.
275 pub fn split_drive<'a>(&self) -> (&HgPath, &HgPath) {
280 pub fn split_drive<'a>(&self) -> (&HgPath, &HgPath) {
276 let bytes = self.as_bytes();
281 let bytes = self.as_bytes();
277 let is_sep = |b| std::path::is_separator(b as char);
282 let is_sep = |b| std::path::is_separator(b as char);
278
283
279 if self.len() < 2 {
284 if self.len() < 2 {
280 (HgPath::new(b""), &self)
285 (HgPath::new(b""), &self)
281 } else if is_sep(bytes[0])
286 } else if is_sep(bytes[0])
282 && is_sep(bytes[1])
287 && is_sep(bytes[1])
283 && (self.len() == 2 || !is_sep(bytes[2]))
288 && (self.len() == 2 || !is_sep(bytes[2]))
284 {
289 {
285 // Is a UNC path:
290 // Is a UNC path:
286 // vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
291 // vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
287 // \\machine\mountpoint\directory\etc\...
292 // \\machine\mountpoint\directory\etc\...
288 // directory ^^^^^^^^^^^^^^^
293 // directory ^^^^^^^^^^^^^^^
289
294
290 let machine_end_index = bytes[2..].iter().position(|b| is_sep(*b));
295 let machine_end_index = bytes[2..].iter().position(|b| is_sep(*b));
291 let mountpoint_start_index = if let Some(i) = machine_end_index {
296 let mountpoint_start_index = if let Some(i) = machine_end_index {
292 i + 2
297 i + 2
293 } else {
298 } else {
294 return (HgPath::new(b""), &self);
299 return (HgPath::new(b""), &self);
295 };
300 };
296
301
297 match bytes[mountpoint_start_index + 1..]
302 match bytes[mountpoint_start_index + 1..]
298 .iter()
303 .iter()
299 .position(|b| is_sep(*b))
304 .position(|b| is_sep(*b))
300 {
305 {
301 // A UNC path can't have two slashes in a row
306 // A UNC path can't have two slashes in a row
302 // (after the initial two)
307 // (after the initial two)
303 Some(0) => (HgPath::new(b""), &self),
308 Some(0) => (HgPath::new(b""), &self),
304 Some(i) => {
309 Some(i) => {
305 let (a, b) =
310 let (a, b) =
306 bytes.split_at(mountpoint_start_index + 1 + i);
311 bytes.split_at(mountpoint_start_index + 1 + i);
307 (HgPath::new(a), HgPath::new(b))
312 (HgPath::new(a), HgPath::new(b))
308 }
313 }
309 None => (&self, HgPath::new(b"")),
314 None => (&self, HgPath::new(b"")),
310 }
315 }
311 } else if bytes[1] == b':' {
316 } else if bytes[1] == b':' {
312 // Drive path c:\directory
317 // Drive path c:\directory
313 let (a, b) = bytes.split_at(2);
318 let (a, b) = bytes.split_at(2);
314 (HgPath::new(a), HgPath::new(b))
319 (HgPath::new(a), HgPath::new(b))
315 } else {
320 } else {
316 (HgPath::new(b""), &self)
321 (HgPath::new(b""), &self)
317 }
322 }
318 }
323 }
319
324
320 #[cfg(unix)]
325 #[cfg(unix)]
321 /// Split a pathname into drive and path. On Posix, drive is always empty.
326 /// Split a pathname into drive and path. On Posix, drive is always empty.
322 pub fn split_drive(&self) -> (&HgPath, &HgPath) {
327 pub fn split_drive(&self) -> (&HgPath, &HgPath) {
323 (HgPath::new(b""), &self)
328 (HgPath::new(b""), &self)
324 }
329 }
325
330
326 /// Checks for errors in the path, short-circuiting at the first one.
331 /// Checks for errors in the path, short-circuiting at the first one.
327 /// This generates fine-grained errors useful for debugging.
332 /// This generates fine-grained errors useful for debugging.
328 /// To simply check if the path is valid during tests, use `is_valid`.
333 /// To simply check if the path is valid during tests, use `is_valid`.
329 pub fn check_state(&self) -> Result<(), HgPathError> {
334 pub fn check_state(&self) -> Result<(), HgPathError> {
330 if self.is_empty() {
335 if self.is_empty() {
331 return Ok(());
336 return Ok(());
332 }
337 }
333 let bytes = self.as_bytes();
338 let bytes = self.as_bytes();
334 let mut previous_byte = None;
339 let mut previous_byte = None;
335
340
336 if bytes[0] == b'/' {
341 if bytes[0] == b'/' {
337 return Err(HgPathError::LeadingSlash(bytes.to_vec()));
342 return Err(HgPathError::LeadingSlash(bytes.to_vec()));
338 }
343 }
339 for (index, byte) in bytes.iter().enumerate() {
344 for (index, byte) in bytes.iter().enumerate() {
340 match byte {
345 match byte {
341 0 => {
346 0 => {
342 return Err(HgPathError::ContainsNullByte {
347 return Err(HgPathError::ContainsNullByte {
343 bytes: bytes.to_vec(),
348 bytes: bytes.to_vec(),
344 null_byte_index: index,
349 null_byte_index: index,
345 })
350 })
346 }
351 }
347 b'/' => {
352 b'/' => {
348 if previous_byte.is_some() && previous_byte == Some(b'/') {
353 if previous_byte.is_some() && previous_byte == Some(b'/') {
349 return Err(HgPathError::ConsecutiveSlashes {
354 return Err(HgPathError::ConsecutiveSlashes {
350 bytes: bytes.to_vec(),
355 bytes: bytes.to_vec(),
351 second_slash_index: index,
356 second_slash_index: index,
352 });
357 });
353 }
358 }
354 }
359 }
355 _ => (),
360 _ => (),
356 };
361 };
357 previous_byte = Some(*byte);
362 previous_byte = Some(*byte);
358 }
363 }
359 Ok(())
364 Ok(())
360 }
365 }
361
366
362 #[cfg(test)]
367 #[cfg(test)]
363 /// Only usable during tests to force developers to handle invalid states
368 /// Only usable during tests to force developers to handle invalid states
364 fn is_valid(&self) -> bool {
369 fn is_valid(&self) -> bool {
365 self.check_state().is_ok()
370 self.check_state().is_ok()
366 }
371 }
367 }
372 }
368
373
369 impl fmt::Debug for HgPath {
374 impl fmt::Debug for HgPath {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 write!(f, "HgPath({:?})", String::from_utf8_lossy(&self.inner))
376 write!(f, "HgPath({:?})", String::from_utf8_lossy(&self.inner))
372 }
377 }
373 }
378 }
374
379
375 impl fmt::Display for HgPath {
380 impl fmt::Display for HgPath {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 write!(f, "{}", String::from_utf8_lossy(&self.inner))
382 write!(f, "{}", String::from_utf8_lossy(&self.inner))
378 }
383 }
379 }
384 }
380
385
381 #[derive(
386 #[derive(
382 Default, Eq, Ord, Clone, PartialEq, PartialOrd, Hash, derive_more::From,
387 Default, Eq, Ord, Clone, PartialEq, PartialOrd, Hash, derive_more::From,
383 )]
388 )]
384 pub struct HgPathBuf {
389 pub struct HgPathBuf {
385 inner: Vec<u8>,
390 inner: Vec<u8>,
386 }
391 }
387
392
388 impl HgPathBuf {
393 impl HgPathBuf {
389 pub fn new() -> Self {
394 pub fn new() -> Self {
390 Default::default()
395 Default::default()
391 }
396 }
392 pub fn push(&mut self, byte: u8) {
397 pub fn push(&mut self, byte: u8) {
393 self.inner.push(byte);
398 self.inner.push(byte);
394 }
399 }
395 pub fn from_bytes(s: &[u8]) -> HgPathBuf {
400 pub fn from_bytes(s: &[u8]) -> HgPathBuf {
396 HgPath::new(s).to_owned()
401 HgPath::new(s).to_owned()
397 }
402 }
398 pub fn into_vec(self) -> Vec<u8> {
403 pub fn into_vec(self) -> Vec<u8> {
399 self.inner
404 self.inner
400 }
405 }
401 }
406 }
402
407
403 impl fmt::Debug for HgPathBuf {
408 impl fmt::Debug for HgPathBuf {
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 write!(f, "HgPathBuf({:?})", String::from_utf8_lossy(&self.inner))
410 write!(f, "HgPathBuf({:?})", String::from_utf8_lossy(&self.inner))
406 }
411 }
407 }
412 }
408
413
409 impl fmt::Display for HgPathBuf {
414 impl fmt::Display for HgPathBuf {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 write!(f, "{}", String::from_utf8_lossy(&self.inner))
416 write!(f, "{}", String::from_utf8_lossy(&self.inner))
412 }
417 }
413 }
418 }
414
419
415 impl Deref for HgPathBuf {
420 impl Deref for HgPathBuf {
416 type Target = HgPath;
421 type Target = HgPath;
417
422
418 #[inline]
423 #[inline]
419 fn deref(&self) -> &HgPath {
424 fn deref(&self) -> &HgPath {
420 &HgPath::new(&self.inner)
425 &HgPath::new(&self.inner)
421 }
426 }
422 }
427 }
423
428
424 impl<T: ?Sized + AsRef<HgPath>> From<&T> for HgPathBuf {
429 impl<T: ?Sized + AsRef<HgPath>> From<&T> for HgPathBuf {
425 fn from(s: &T) -> HgPathBuf {
430 fn from(s: &T) -> HgPathBuf {
426 s.as_ref().to_owned()
431 s.as_ref().to_owned()
427 }
432 }
428 }
433 }
429
434
430 impl Into<Vec<u8>> for HgPathBuf {
435 impl Into<Vec<u8>> for HgPathBuf {
431 fn into(self) -> Vec<u8> {
436 fn into(self) -> Vec<u8> {
432 self.inner
437 self.inner
433 }
438 }
434 }
439 }
435
440
436 impl Borrow<HgPath> for HgPathBuf {
441 impl Borrow<HgPath> for HgPathBuf {
437 fn borrow(&self) -> &HgPath {
442 fn borrow(&self) -> &HgPath {
438 &HgPath::new(self.as_bytes())
443 &HgPath::new(self.as_bytes())
439 }
444 }
440 }
445 }
441
446
442 impl ToOwned for HgPath {
447 impl ToOwned for HgPath {
443 type Owned = HgPathBuf;
448 type Owned = HgPathBuf;
444
449
445 fn to_owned(&self) -> HgPathBuf {
450 fn to_owned(&self) -> HgPathBuf {
446 self.to_hg_path_buf()
451 self.to_hg_path_buf()
447 }
452 }
448 }
453 }
449
454
450 impl AsRef<HgPath> for HgPath {
455 impl AsRef<HgPath> for HgPath {
451 fn as_ref(&self) -> &HgPath {
456 fn as_ref(&self) -> &HgPath {
452 self
457 self
453 }
458 }
454 }
459 }
455
460
456 impl AsRef<HgPath> for HgPathBuf {
461 impl AsRef<HgPath> for HgPathBuf {
457 fn as_ref(&self) -> &HgPath {
462 fn as_ref(&self) -> &HgPath {
458 self
463 self
459 }
464 }
460 }
465 }
461
466
462 impl Extend<u8> for HgPathBuf {
467 impl Extend<u8> for HgPathBuf {
463 fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
468 fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
464 self.inner.extend(iter);
469 self.inner.extend(iter);
465 }
470 }
466 }
471 }
467
472
468 /// TODO: Once https://www.mercurial-scm.org/wiki/WindowsUTF8Plan is
473 /// TODO: Once https://www.mercurial-scm.org/wiki/WindowsUTF8Plan is
469 /// implemented, these conversion utils will have to work differently depending
474 /// implemented, these conversion utils will have to work differently depending
470 /// on the repository encoding: either `UTF-8` or `MBCS`.
475 /// on the repository encoding: either `UTF-8` or `MBCS`.
471
476
472 pub fn hg_path_to_os_string<P: AsRef<HgPath>>(
477 pub fn hg_path_to_os_string<P: AsRef<HgPath>>(
473 hg_path: P,
478 hg_path: P,
474 ) -> Result<OsString, HgPathError> {
479 ) -> Result<OsString, HgPathError> {
475 hg_path.as_ref().check_state()?;
480 hg_path.as_ref().check_state()?;
476 let os_str;
481 let os_str;
477 #[cfg(unix)]
482 #[cfg(unix)]
478 {
483 {
479 use std::os::unix::ffi::OsStrExt;
484 use std::os::unix::ffi::OsStrExt;
480 os_str = std::ffi::OsStr::from_bytes(&hg_path.as_ref().as_bytes());
485 os_str = std::ffi::OsStr::from_bytes(&hg_path.as_ref().as_bytes());
481 }
486 }
482 // TODO Handle other platforms
487 // TODO Handle other platforms
483 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
488 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
484 Ok(os_str.to_os_string())
489 Ok(os_str.to_os_string())
485 }
490 }
486
491
487 pub fn hg_path_to_path_buf<P: AsRef<HgPath>>(
492 pub fn hg_path_to_path_buf<P: AsRef<HgPath>>(
488 hg_path: P,
493 hg_path: P,
489 ) -> Result<PathBuf, HgPathError> {
494 ) -> Result<PathBuf, HgPathError> {
490 Ok(Path::new(&hg_path_to_os_string(hg_path)?).to_path_buf())
495 Ok(Path::new(&hg_path_to_os_string(hg_path)?).to_path_buf())
491 }
496 }
492
497
493 pub fn os_string_to_hg_path_buf<S: AsRef<OsStr>>(
498 pub fn os_string_to_hg_path_buf<S: AsRef<OsStr>>(
494 os_string: S,
499 os_string: S,
495 ) -> Result<HgPathBuf, HgPathError> {
500 ) -> Result<HgPathBuf, HgPathError> {
496 let buf;
501 let buf;
497 #[cfg(unix)]
502 #[cfg(unix)]
498 {
503 {
499 use std::os::unix::ffi::OsStrExt;
504 use std::os::unix::ffi::OsStrExt;
500 buf = HgPathBuf::from_bytes(&os_string.as_ref().as_bytes());
505 buf = HgPathBuf::from_bytes(&os_string.as_ref().as_bytes());
501 }
506 }
502 // TODO Handle other platforms
507 // TODO Handle other platforms
503 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
508 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
504
509
505 buf.check_state()?;
510 buf.check_state()?;
506 Ok(buf)
511 Ok(buf)
507 }
512 }
508
513
509 pub fn path_to_hg_path_buf<P: AsRef<Path>>(
514 pub fn path_to_hg_path_buf<P: AsRef<Path>>(
510 path: P,
515 path: P,
511 ) -> Result<HgPathBuf, HgPathError> {
516 ) -> Result<HgPathBuf, HgPathError> {
512 let buf;
517 let buf;
513 let os_str = path.as_ref().as_os_str();
518 let os_str = path.as_ref().as_os_str();
514 #[cfg(unix)]
519 #[cfg(unix)]
515 {
520 {
516 use std::os::unix::ffi::OsStrExt;
521 use std::os::unix::ffi::OsStrExt;
517 buf = HgPathBuf::from_bytes(&os_str.as_bytes());
522 buf = HgPathBuf::from_bytes(&os_str.as_bytes());
518 }
523 }
519 // TODO Handle other platforms
524 // TODO Handle other platforms
520 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
525 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
521
526
522 buf.check_state()?;
527 buf.check_state()?;
523 Ok(buf)
528 Ok(buf)
524 }
529 }
525
530
526 impl TryFrom<PathBuf> for HgPathBuf {
531 impl TryFrom<PathBuf> for HgPathBuf {
527 type Error = HgPathError;
532 type Error = HgPathError;
528 fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
533 fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
529 path_to_hg_path_buf(path)
534 path_to_hg_path_buf(path)
530 }
535 }
531 }
536 }
532
537
533 #[cfg(test)]
538 #[cfg(test)]
534 mod tests {
539 mod tests {
535 use super::*;
540 use super::*;
536 use pretty_assertions::assert_eq;
541 use pretty_assertions::assert_eq;
537
542
538 #[test]
543 #[test]
539 fn test_path_states() {
544 fn test_path_states() {
540 assert_eq!(
545 assert_eq!(
541 Err(HgPathError::LeadingSlash(b"/".to_vec())),
546 Err(HgPathError::LeadingSlash(b"/".to_vec())),
542 HgPath::new(b"/").check_state()
547 HgPath::new(b"/").check_state()
543 );
548 );
544 assert_eq!(
549 assert_eq!(
545 Err(HgPathError::ConsecutiveSlashes {
550 Err(HgPathError::ConsecutiveSlashes {
546 bytes: b"a/b//c".to_vec(),
551 bytes: b"a/b//c".to_vec(),
547 second_slash_index: 4
552 second_slash_index: 4
548 }),
553 }),
549 HgPath::new(b"a/b//c").check_state()
554 HgPath::new(b"a/b//c").check_state()
550 );
555 );
551 assert_eq!(
556 assert_eq!(
552 Err(HgPathError::ContainsNullByte {
557 Err(HgPathError::ContainsNullByte {
553 bytes: b"a/b/\0c".to_vec(),
558 bytes: b"a/b/\0c".to_vec(),
554 null_byte_index: 4
559 null_byte_index: 4
555 }),
560 }),
556 HgPath::new(b"a/b/\0c").check_state()
561 HgPath::new(b"a/b/\0c").check_state()
557 );
562 );
558 // TODO test HgPathError::DecodeError for the Windows implementation.
563 // TODO test HgPathError::DecodeError for the Windows implementation.
559 assert_eq!(true, HgPath::new(b"").is_valid());
564 assert_eq!(true, HgPath::new(b"").is_valid());
560 assert_eq!(true, HgPath::new(b"a/b/c").is_valid());
565 assert_eq!(true, HgPath::new(b"a/b/c").is_valid());
561 // Backslashes in paths are not significant, but allowed
566 // Backslashes in paths are not significant, but allowed
562 assert_eq!(true, HgPath::new(br"a\b/c").is_valid());
567 assert_eq!(true, HgPath::new(br"a\b/c").is_valid());
563 // Dots in paths are not significant, but allowed
568 // Dots in paths are not significant, but allowed
564 assert_eq!(true, HgPath::new(b"a/b/../c/").is_valid());
569 assert_eq!(true, HgPath::new(b"a/b/../c/").is_valid());
565 assert_eq!(true, HgPath::new(b"./a/b/../c/").is_valid());
570 assert_eq!(true, HgPath::new(b"./a/b/../c/").is_valid());
566 }
571 }
567
572
568 #[test]
573 #[test]
569 fn test_iter() {
574 fn test_iter() {
570 let path = HgPath::new(b"a");
575 let path = HgPath::new(b"a");
571 let mut iter = path.bytes();
576 let mut iter = path.bytes();
572 assert_eq!(Some(&b'a'), iter.next());
577 assert_eq!(Some(&b'a'), iter.next());
573 assert_eq!(None, iter.next_back());
578 assert_eq!(None, iter.next_back());
574 assert_eq!(None, iter.next());
579 assert_eq!(None, iter.next());
575
580
576 let path = HgPath::new(b"a");
581 let path = HgPath::new(b"a");
577 let mut iter = path.bytes();
582 let mut iter = path.bytes();
578 assert_eq!(Some(&b'a'), iter.next_back());
583 assert_eq!(Some(&b'a'), iter.next_back());
579 assert_eq!(None, iter.next_back());
584 assert_eq!(None, iter.next_back());
580 assert_eq!(None, iter.next());
585 assert_eq!(None, iter.next());
581
586
582 let path = HgPath::new(b"abc");
587 let path = HgPath::new(b"abc");
583 let mut iter = path.bytes();
588 let mut iter = path.bytes();
584 assert_eq!(Some(&b'a'), iter.next());
589 assert_eq!(Some(&b'a'), iter.next());
585 assert_eq!(Some(&b'c'), iter.next_back());
590 assert_eq!(Some(&b'c'), iter.next_back());
586 assert_eq!(Some(&b'b'), iter.next_back());
591 assert_eq!(Some(&b'b'), iter.next_back());
587 assert_eq!(None, iter.next_back());
592 assert_eq!(None, iter.next_back());
588 assert_eq!(None, iter.next());
593 assert_eq!(None, iter.next());
589
594
590 let path = HgPath::new(b"abc");
595 let path = HgPath::new(b"abc");
591 let mut iter = path.bytes();
596 let mut iter = path.bytes();
592 assert_eq!(Some(&b'a'), iter.next());
597 assert_eq!(Some(&b'a'), iter.next());
593 assert_eq!(Some(&b'b'), iter.next());
598 assert_eq!(Some(&b'b'), iter.next());
594 assert_eq!(Some(&b'c'), iter.next());
599 assert_eq!(Some(&b'c'), iter.next());
595 assert_eq!(None, iter.next_back());
600 assert_eq!(None, iter.next_back());
596 assert_eq!(None, iter.next());
601 assert_eq!(None, iter.next());
597
602
598 let path = HgPath::new(b"abc");
603 let path = HgPath::new(b"abc");
599 let iter = path.bytes();
604 let iter = path.bytes();
600 let mut vec = Vec::new();
605 let mut vec = Vec::new();
601 vec.extend(iter);
606 vec.extend(iter);
602 assert_eq!(vec![b'a', b'b', b'c'], vec);
607 assert_eq!(vec![b'a', b'b', b'c'], vec);
603
608
604 let path = HgPath::new(b"abc");
609 let path = HgPath::new(b"abc");
605 let mut iter = path.bytes();
610 let mut iter = path.bytes();
606 assert_eq!(Some(2), iter.rposition(|c| *c == b'c'));
611 assert_eq!(Some(2), iter.rposition(|c| *c == b'c'));
607
612
608 let path = HgPath::new(b"abc");
613 let path = HgPath::new(b"abc");
609 let mut iter = path.bytes();
614 let mut iter = path.bytes();
610 assert_eq!(None, iter.rposition(|c| *c == b'd'));
615 assert_eq!(None, iter.rposition(|c| *c == b'd'));
611 }
616 }
612
617
613 #[test]
618 #[test]
614 fn test_join() {
619 fn test_join() {
615 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"b"));
620 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"b"));
616 assert_eq!(b"a/b", path.as_bytes());
621 assert_eq!(b"a/b", path.as_bytes());
617
622
618 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"b/c"));
623 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"b/c"));
619 assert_eq!(b"a/b/c", path.as_bytes());
624 assert_eq!(b"a/b/c", path.as_bytes());
620
625
621 // No leading slash if empty before join
626 // No leading slash if empty before join
622 let path = HgPathBuf::new().join(HgPath::new(b"b/c"));
627 let path = HgPathBuf::new().join(HgPath::new(b"b/c"));
623 assert_eq!(b"b/c", path.as_bytes());
628 assert_eq!(b"b/c", path.as_bytes());
624
629
625 // The leading slash is an invalid representation of an `HgPath`, but
630 // The leading slash is an invalid representation of an `HgPath`, but
626 // it can happen. This creates another invalid representation of
631 // it can happen. This creates another invalid representation of
627 // consecutive bytes.
632 // consecutive bytes.
628 // TODO What should be done in this case? Should we silently remove
633 // TODO What should be done in this case? Should we silently remove
629 // the extra slash? Should we change the signature to a problematic
634 // the extra slash? Should we change the signature to a problematic
630 // `Result<HgPathBuf, HgPathError>`, or should we just keep it so and
635 // `Result<HgPathBuf, HgPathError>`, or should we just keep it so and
631 // let the error happen upon filesystem interaction?
636 // let the error happen upon filesystem interaction?
632 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"/b"));
637 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"/b"));
633 assert_eq!(b"a//b", path.as_bytes());
638 assert_eq!(b"a//b", path.as_bytes());
634 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"/b"));
639 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"/b"));
635 assert_eq!(b"a//b", path.as_bytes());
640 assert_eq!(b"a//b", path.as_bytes());
636 }
641 }
637
642
638 #[test]
643 #[test]
639 fn test_relative_to() {
644 fn test_relative_to() {
640 let path = HgPath::new(b"");
645 let path = HgPath::new(b"");
641 let base = HgPath::new(b"");
646 let base = HgPath::new(b"");
642 assert_eq!(Some(path), path.relative_to(base));
647 assert_eq!(Some(path), path.relative_to(base));
643
648
644 let path = HgPath::new(b"path");
649 let path = HgPath::new(b"path");
645 let base = HgPath::new(b"");
650 let base = HgPath::new(b"");
646 assert_eq!(Some(path), path.relative_to(base));
651 assert_eq!(Some(path), path.relative_to(base));
647
652
648 let path = HgPath::new(b"a");
653 let path = HgPath::new(b"a");
649 let base = HgPath::new(b"b");
654 let base = HgPath::new(b"b");
650 assert_eq!(None, path.relative_to(base));
655 assert_eq!(None, path.relative_to(base));
651
656
652 let path = HgPath::new(b"a/b");
657 let path = HgPath::new(b"a/b");
653 let base = HgPath::new(b"a");
658 let base = HgPath::new(b"a");
654 assert_eq!(None, path.relative_to(base));
659 assert_eq!(None, path.relative_to(base));
655
660
656 let path = HgPath::new(b"a/b");
661 let path = HgPath::new(b"a/b");
657 let base = HgPath::new(b"a/");
662 let base = HgPath::new(b"a/");
658 assert_eq!(Some(HgPath::new(b"b")), path.relative_to(base));
663 assert_eq!(Some(HgPath::new(b"b")), path.relative_to(base));
659
664
660 let path = HgPath::new(b"nested/path/to/b");
665 let path = HgPath::new(b"nested/path/to/b");
661 let base = HgPath::new(b"nested/path/");
666 let base = HgPath::new(b"nested/path/");
662 assert_eq!(Some(HgPath::new(b"to/b")), path.relative_to(base));
667 assert_eq!(Some(HgPath::new(b"to/b")), path.relative_to(base));
663
668
664 let path = HgPath::new(b"ends/with/dir/");
669 let path = HgPath::new(b"ends/with/dir/");
665 let base = HgPath::new(b"ends/");
670 let base = HgPath::new(b"ends/");
666 assert_eq!(Some(HgPath::new(b"with/dir/")), path.relative_to(base));
671 assert_eq!(Some(HgPath::new(b"with/dir/")), path.relative_to(base));
667 }
672 }
668
673
669 #[test]
674 #[test]
670 #[cfg(unix)]
675 #[cfg(unix)]
671 fn test_split_drive() {
676 fn test_split_drive() {
672 // Taken from the Python stdlib's tests
677 // Taken from the Python stdlib's tests
673 assert_eq!(
678 assert_eq!(
674 HgPath::new(br"/foo/bar").split_drive(),
679 HgPath::new(br"/foo/bar").split_drive(),
675 (HgPath::new(b""), HgPath::new(br"/foo/bar"))
680 (HgPath::new(b""), HgPath::new(br"/foo/bar"))
676 );
681 );
677 assert_eq!(
682 assert_eq!(
678 HgPath::new(br"foo:bar").split_drive(),
683 HgPath::new(br"foo:bar").split_drive(),
679 (HgPath::new(b""), HgPath::new(br"foo:bar"))
684 (HgPath::new(b""), HgPath::new(br"foo:bar"))
680 );
685 );
681 assert_eq!(
686 assert_eq!(
682 HgPath::new(br":foo:bar").split_drive(),
687 HgPath::new(br":foo:bar").split_drive(),
683 (HgPath::new(b""), HgPath::new(br":foo:bar"))
688 (HgPath::new(b""), HgPath::new(br":foo:bar"))
684 );
689 );
685 // Also try NT paths; should not split them
690 // Also try NT paths; should not split them
686 assert_eq!(
691 assert_eq!(
687 HgPath::new(br"c:\foo\bar").split_drive(),
692 HgPath::new(br"c:\foo\bar").split_drive(),
688 (HgPath::new(b""), HgPath::new(br"c:\foo\bar"))
693 (HgPath::new(b""), HgPath::new(br"c:\foo\bar"))
689 );
694 );
690 assert_eq!(
695 assert_eq!(
691 HgPath::new(b"c:/foo/bar").split_drive(),
696 HgPath::new(b"c:/foo/bar").split_drive(),
692 (HgPath::new(b""), HgPath::new(br"c:/foo/bar"))
697 (HgPath::new(b""), HgPath::new(br"c:/foo/bar"))
693 );
698 );
694 assert_eq!(
699 assert_eq!(
695 HgPath::new(br"\\conky\mountpoint\foo\bar").split_drive(),
700 HgPath::new(br"\\conky\mountpoint\foo\bar").split_drive(),
696 (
701 (
697 HgPath::new(b""),
702 HgPath::new(b""),
698 HgPath::new(br"\\conky\mountpoint\foo\bar")
703 HgPath::new(br"\\conky\mountpoint\foo\bar")
699 )
704 )
700 );
705 );
701 }
706 }
702
707
703 #[test]
708 #[test]
704 #[cfg(windows)]
709 #[cfg(windows)]
705 fn test_split_drive() {
710 fn test_split_drive() {
706 assert_eq!(
711 assert_eq!(
707 HgPath::new(br"c:\foo\bar").split_drive(),
712 HgPath::new(br"c:\foo\bar").split_drive(),
708 (HgPath::new(br"c:"), HgPath::new(br"\foo\bar"))
713 (HgPath::new(br"c:"), HgPath::new(br"\foo\bar"))
709 );
714 );
710 assert_eq!(
715 assert_eq!(
711 HgPath::new(b"c:/foo/bar").split_drive(),
716 HgPath::new(b"c:/foo/bar").split_drive(),
712 (HgPath::new(br"c:"), HgPath::new(br"/foo/bar"))
717 (HgPath::new(br"c:"), HgPath::new(br"/foo/bar"))
713 );
718 );
714 assert_eq!(
719 assert_eq!(
715 HgPath::new(br"\\conky\mountpoint\foo\bar").split_drive(),
720 HgPath::new(br"\\conky\mountpoint\foo\bar").split_drive(),
716 (
721 (
717 HgPath::new(br"\\conky\mountpoint"),
722 HgPath::new(br"\\conky\mountpoint"),
718 HgPath::new(br"\foo\bar")
723 HgPath::new(br"\foo\bar")
719 )
724 )
720 );
725 );
721 assert_eq!(
726 assert_eq!(
722 HgPath::new(br"//conky/mountpoint/foo/bar").split_drive(),
727 HgPath::new(br"//conky/mountpoint/foo/bar").split_drive(),
723 (
728 (
724 HgPath::new(br"//conky/mountpoint"),
729 HgPath::new(br"//conky/mountpoint"),
725 HgPath::new(br"/foo/bar")
730 HgPath::new(br"/foo/bar")
726 )
731 )
727 );
732 );
728 assert_eq!(
733 assert_eq!(
729 HgPath::new(br"\\\conky\mountpoint\foo\bar").split_drive(),
734 HgPath::new(br"\\\conky\mountpoint\foo\bar").split_drive(),
730 (
735 (
731 HgPath::new(br""),
736 HgPath::new(br""),
732 HgPath::new(br"\\\conky\mountpoint\foo\bar")
737 HgPath::new(br"\\\conky\mountpoint\foo\bar")
733 )
738 )
734 );
739 );
735 assert_eq!(
740 assert_eq!(
736 HgPath::new(br"///conky/mountpoint/foo/bar").split_drive(),
741 HgPath::new(br"///conky/mountpoint/foo/bar").split_drive(),
737 (
742 (
738 HgPath::new(br""),
743 HgPath::new(br""),
739 HgPath::new(br"///conky/mountpoint/foo/bar")
744 HgPath::new(br"///conky/mountpoint/foo/bar")
740 )
745 )
741 );
746 );
742 assert_eq!(
747 assert_eq!(
743 HgPath::new(br"\\conky\\mountpoint\foo\bar").split_drive(),
748 HgPath::new(br"\\conky\\mountpoint\foo\bar").split_drive(),
744 (
749 (
745 HgPath::new(br""),
750 HgPath::new(br""),
746 HgPath::new(br"\\conky\\mountpoint\foo\bar")
751 HgPath::new(br"\\conky\\mountpoint\foo\bar")
747 )
752 )
748 );
753 );
749 assert_eq!(
754 assert_eq!(
750 HgPath::new(br"//conky//mountpoint/foo/bar").split_drive(),
755 HgPath::new(br"//conky//mountpoint/foo/bar").split_drive(),
751 (
756 (
752 HgPath::new(br""),
757 HgPath::new(br""),
753 HgPath::new(br"//conky//mountpoint/foo/bar")
758 HgPath::new(br"//conky//mountpoint/foo/bar")
754 )
759 )
755 );
760 );
756 // UNC part containing U+0130
761 // UNC part containing U+0130
757 assert_eq!(
762 assert_eq!(
758 HgPath::new(b"//conky/MOUNTPO\xc4\xb0NT/foo/bar").split_drive(),
763 HgPath::new(b"//conky/MOUNTPO\xc4\xb0NT/foo/bar").split_drive(),
759 (
764 (
760 HgPath::new(b"//conky/MOUNTPO\xc4\xb0NT"),
765 HgPath::new(b"//conky/MOUNTPO\xc4\xb0NT"),
761 HgPath::new(br"/foo/bar")
766 HgPath::new(br"/foo/bar")
762 )
767 )
763 );
768 );
764 }
769 }
765
770
766 #[test]
771 #[test]
767 fn test_parent() {
772 fn test_parent() {
768 let path = HgPath::new(b"");
773 let path = HgPath::new(b"");
769 assert_eq!(path.parent(), path);
774 assert_eq!(path.parent(), path);
770
775
771 let path = HgPath::new(b"a");
776 let path = HgPath::new(b"a");
772 assert_eq!(path.parent(), HgPath::new(b""));
777 assert_eq!(path.parent(), HgPath::new(b""));
773
778
774 let path = HgPath::new(b"a/b");
779 let path = HgPath::new(b"a/b");
775 assert_eq!(path.parent(), HgPath::new(b"a"));
780 assert_eq!(path.parent(), HgPath::new(b"a"));
776
781
777 let path = HgPath::new(b"a/other/b");
782 let path = HgPath::new(b"a/other/b");
778 assert_eq!(path.parent(), HgPath::new(b"a/other"));
783 assert_eq!(path.parent(), HgPath::new(b"a/other"));
779 }
784 }
780 }
785 }
General Comments 0
You need to be logged in to leave comments. Login now