Debian Codegraph @

rust/hg-core/src/narrow/shape.rs

raw
1 //! The core of the logic for narrow shapes, which enable a composable algebra
2 //! for slicing a repo's history along its files.
3
4 use std::collections::HashSet;
5 use std::io::Write;
6 use std::sync::Arc;
7 use std::sync::RwLock;
8 use std::sync::RwLockReadGuard;
9 use std::sync::RwLockWriteGuard;
10
11 use itertools::Itertools;
12 use lazy_static::lazy_static;
13 use regex::Regex;
14 use serde::Deserialize;
15 use serde::Serialize;
16 use sha2::Digest;
17 use sha2::Sha256;
18
19 use crate::errors::HgError;
20 use crate::exit_codes;
21 use crate::file_patterns::FilePattern;
22 use crate::file_patterns::PatternError;
23 use crate::file_patterns::PatternSyntax;
24 use crate::matchers::ShapeMatcher;
25 use crate::repo::Repo;
26 use crate::utils::hg_path::HgPath;
27 use crate::utils::hg_path::HgPathBuf;
28 use crate::utils::hg_path::HgPathError;
29 use crate::utils::hg_path::HgPathErrorKind;
30 use crate::FastHashMap;
31
32 lazy_static! {
33 /// Only lower case ASCII alpha num, `-` and `.`
34 static ref SHARD_NAME_REGEX: Regex =
35 Regex::new(r"^[-\.[[:lower:]][[:digit:]]]+$").unwrap();
36
37 /// Special files that need to be included in every single shape
38 static ref HG_FILES_SHARD_PATHS: Vec<String> = vec![
39 ".hgignore".to_string(),
40 ".hgtags".to_string(),
41 ".hgsub".to_string(),
42 ".hgsubstate".to_string(),
43 ];
44 }
45
46 /// Errors specific to handling shapes
47 #[derive(Debug, PartialEq)]
48 pub enum Error {
49 /// A shard was declared with an empty name
50 EmptyShardName,
51 /// A shard was declared with a name that only has dots and/or hyphens
52 DotOrHyphenOnlyShardName(String),
53 /// A shard was declared with an invalid name that is not only dots
54 /// and/or hyphens
55 InvalidShardName(String),
56 /// A shard was declared with a reserved name
57 ReservedName(String),
58 /// The following shards form a cycle
59 CycleInShards(Vec<ShardName>),
60 /// This path was found in two (or more) separate shards
61 PathInMultipleShards(HgPathBuf),
62 /// Two (or more) shards share the same name
63 DuplicateShard(ShardName),
64 /// This shard was defined without `paths` and `requires`
65 ShardMissingPathsAndRequires(String),
66 /// An invalid file pattern was given
67 PatternError(PatternError),
68 /// The config contains an invalid path, with this error
69 InvalidPath(HgPathError),
70 /// This config parsed correctly, but is of this unknown version
71 UnknownVersion(usize),
72 /// The config failed to parse, here is the error
73 ParseError(toml::de::Error),
74 }
75
76 impl From<Error> for HgError {
77 fn from(value: Error) -> Self {
78 let exit_code = match value {
79 Error::EmptyShardName
80 | Error::DotOrHyphenOnlyShardName(_)
81 | Error::InvalidShardName(_)
82 | Error::ReservedName(_)
83 | Error::CycleInShards(_)
84 | Error::PathInMultipleShards(_)
85 | Error::DuplicateShard(_)
86 | Error::ShardMissingPathsAndRequires(_)
87 | Error::InvalidPath(_)
88 | Error::UnknownVersion(_) => exit_codes::CONFIG_ERROR_ABORT,
89 Error::ParseError(_) => exit_codes::CONFIG_PARSE_ERROR_ABORT,
90 Error::PatternError(_) => exit_codes::INPUT_ERROR,
91 };
92 let explanation = match value {
93 Error::EmptyShardName => {
94 "shard names must not be empty".to_string()
95 }
96 Error::DotOrHyphenOnlyShardName(name) => format!(
97 "invalid shard name '{name}': \
98 missing lowercase alphanumeric character"
99 ),
100 Error::InvalidShardName(name) => format!(
101 "invalid shard name '{name}': \
102 only lowercase alphanumeric, hyphen or dot are accepted"
103 ),
104 Error::ReservedName(name) => {
105 format!("shard name '{name}' is reserved")
106 }
107 Error::CycleInShards(shard_names) => {
108 let cycle = shard_names.into_iter().join("->");
109 format!("shards form a cycle: {cycle}")
110 }
111 Error::PathInMultipleShards(path) => {
112 format!(
113 "path is found in multiple shards: {}",
114 String::from_utf8_lossy(path.as_bytes())
115 )
116 }
117 Error::DuplicateShard(name) => {
118 format!("shard '{name}' defined multiple times")
119 }
120 Error::ShardMissingPathsAndRequires(name) => {
121 format!("shard '{name}' needs one of `paths` or `requires`")
122 }
123 Error::InvalidPath(err) => {
124 format!("`server-shapes` contains an invalid path: {err}")
125 }
126 Error::UnknownVersion(version) => {
127 format!("unknown `server-shapes` version '{version}'")
128 }
129 Error::ParseError(err) => {
130 format!("error parsing `server-shapes`:\n{err}")
131 }
132 Error::PatternError(err) => {
133 format!("invalid pattern {err}")
134 }
135 };
136
137 Self::abort(explanation, exit_code, None)
138 }
139 }
140
141 const HG_FILES_SHARD: &str = ".hg-files";
142
143 /// Canonical name within a repo for a [`Shard`].
144 /// Is restricted in which bytes can be used, see [`Self::new`].
145 #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
146 pub struct ShardName(String);
147
148 impl std::fmt::Display for ShardName {
149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 self.0.fmt(f)
151 }
152 }
153
154 impl ShardName {
155 fn new(name: String) -> Result<Self, Error> {
156 if name.is_empty() {
157 return Err(Error::EmptyShardName);
158 }
159 if name.as_bytes().iter().all(|b| *b == b'.' || *b == b'-') {
160 return Err(Error::DotOrHyphenOnlyShardName(name));
161 }
162 if !SHARD_NAME_REGEX.is_match(&name) {
163 return Err(Error::InvalidShardName(name));
164 }
165 Ok(Self(name))
166 }
167 }
168
169 /// Defines a subset of files in this repo's history.
170 /// Shards in a repo's [`StoreShards`] are mutually exclusive.
171 ///
172 /// This is a "config-facing" or "admin-facing" concept and should not be
173 /// apparent to most users.
174 #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
175 pub struct Shard {
176 /// The canonical name for this shard for a given repo
177 name: ShardName,
178 /// The repo paths that this shard covers across the history of its repo
179 paths: Vec<HgPathBuf>,
180 /// Other shards that this shard depends on
181 requires: Vec<ShardName>,
182 /// Whether this shard can be used within or as a [`Shape`]
183 shape: bool,
184 }
185
186 /// The set of all [`Shard`] that make up a repository.
187 ///
188 /// TODO make this self-referencing if all the cloning ends up being expensive
189 #[derive(Debug)]
190 pub struct StoreShards {
191 /// All [`Shard`] in the current repo, mapped by their [`ShardName`]
192 shards: FastHashMap<ShardName, Shard>,
193 /// All paths explicitly declared by the shards, mapped to their shard
194 path_to_shard: FastHashMap<HgPathBuf, Shard>,
195 }
196
197 impl StoreShards {
198 #[tracing::instrument(level = "debug", skip_all)]
199 pub fn from_repo_config(repo: &Repo) -> Result<Self, HgError> {
200 let config = match repo.store_vfs().try_read("server-shapes")? {
201 Some(data) => toml::from_slice(&data).map_err(|e| {
202 // We've failed to parse this to the expected structure,
203 // it could be for many different reasons.
204 // Give a better error message if it's only because it's a
205 // different version that also turns out to be incompatible
206 // with this deserialization.
207 // It's a little fragile, but it's better than nothing.
208 let re = regex::bytes::Regex::new(r"^version\s*=\s*(\d+)$")
209 .expect("valid regex");
210 if let Some(captures) = re.captures(&data) {
211 if let Some(version) = captures.get(1) {
212 let version =
213 String::from_utf8_lossy(version.as_bytes())
214 .parse::<usize>()
215 .expect("parsing an integer from a regex");
216 return Error::UnknownVersion(version);
217 }
218 }
219 Error::ParseError(e)
220 })?,
221 None => ShapesConfig::default(),
222 };
223 Ok(Self::from_config(config)?)
224 }
225
226 pub(crate) fn from_config(config: ShapesConfig) -> Result<Self, Error> {
227 let ShapesConfig { version, mut shards } = config;
228 if version != 0 {
229 return Err(Error::UnknownVersion(version as usize));
230 }
231 let shards_len_before = shards.len();
232 shards.push(ShardConfig {
233 name: "base".to_string(),
234 paths: Some(vec!["".to_string()]),
235 shape: false,
236 requires: None,
237 });
238 shards.push(ShardConfig {
239 name: "full".to_string(),
240 paths: None,
241 shape: true,
242 requires: Some(
243 shards
244 .iter()
245 .map(|shard| shard.name.to_owned())
246 .sorted()
247 .collect(),
248 ),
249 });
250 // This shard is included in all other shards. Having a shape that
251 // doesn't include those special files seems like an anti-feature.
252 shards.push(ShardConfig {
253 name: HG_FILES_SHARD.to_string(),
254 paths: Some(HG_FILES_SHARD_PATHS.clone()),
255 shape: false,
256 requires: None,
257 });
258 let reserved_range = shards_len_before..shards.len();
259 let mut path_to_shard = FastHashMap::default();
260 let mut validated_shards = FastHashMap::default();
261 shards.into_iter().enumerate().try_for_each(|(idx, config)| {
262 Self::validate_shard(
263 config,
264 !reserved_range.contains(&idx),
265 &mut path_to_shard,
266 &mut validated_shards,
267 )
268 })?;
269
270 let slf = Self { shards: validated_shards, path_to_shard };
271 // Make sure we can generate all shapes and catch the last errors
272 slf.all_shapes()?;
273 Ok(slf)
274 }
275
276 /// Make sure the shard config is valid, create the shard struct and add
277 /// to the path -> shard mapping
278 fn validate_shard(
279 shard_config: ShardConfig,
280 user_provided: bool,
281 path_to_shard: &mut FastHashMap<HgPathBuf, Shard>,
282 shards: &mut FastHashMap<ShardName, Shard>,
283 ) -> Result<(), Error> {
284 let ShardConfig { name, shape, paths, requires } = shard_config;
285 if user_provided
286 && matches!(name.as_str(), "base" | "full" | HG_FILES_SHARD)
287 {
288 return Err(Error::ReservedName(name));
289 }
290
291 if paths.is_none() && requires.is_none() {
292 return Err(Error::ShardMissingPathsAndRequires(name));
293 }
294
295 let mut hg_paths = vec![];
296 if let Some(config_paths) = paths {
297 for path in config_paths {
298 let on_err = |e: HgPathErrorKind| Error::InvalidPath(e.into());
299 let hg_path = HgPathBuf::from_bytes(
300 path.as_bytes()
301 .strip_suffix(b"/")
302 .unwrap_or(path.as_bytes()),
303 );
304 hg_path.check_state().map_err(on_err)?;
305 hg_paths.push(hg_path);
306 }
307 }
308
309 let mut requires_names = if name != HG_FILES_SHARD {
310 let hg_files_shard_name =
311 ShardName::new(HG_FILES_SHARD.to_string())
312 .expect("valid shard name");
313 vec![hg_files_shard_name]
314 } else {
315 vec![]
316 };
317 if let Some(requirements) = requires {
318 for requirement in requirements {
319 let name = ShardName::new(requirement)?;
320 requires_names.push(name);
321 }
322 }
323 requires_names.sort();
324
325 let name = ShardName::new(name)?;
326 let shard = Shard {
327 name: name.to_owned(),
328 paths: hg_paths.to_owned(),
329 requires: requires_names,
330 shape,
331 };
332 for path in hg_paths {
333 if path_to_shard.insert(path.to_owned(), shard.to_owned()).is_some()
334 {
335 return Err(Error::PathInMultipleShards(path));
336 }
337 }
338
339 if shards.insert(name.to_owned(), shard).is_some() {
340 return Err(Error::DuplicateShard(name));
341 }
342 Ok(())
343 }
344
345 /// Return all user-facing [`Shard`] as [`Shape`]
346 pub fn all_shapes(&self) -> Result<Vec<Shape>, Error> {
347 let mut all: Vec<_> =
348 self.shards.iter().filter(|(_, shard)| shard.shape).collect();
349 all.sort();
350 all.into_iter()
351 .map(|(name, shard)| Shape::new(name.to_owned(), self, &[shard]))
352 .collect()
353 }
354
355 /// Return the [`Shape`] of name `name`, or `None`.
356 pub fn shape(&self, name: &str) -> Result<Option<Shape>, Error> {
357 let shard_name = ShardName::new(name.to_string())?;
358 if let Some(shard) = self.shards.get(&shard_name) {
359 if shard.shape {
360 let shape = Shape::new(shard_name, self, &[shard])?;
361 return Ok(Some(shape));
362 }
363 }
364 Ok(None)
365 }
366
367 /// Gather all recursive dependent shards for `shard`
368 fn dependencies<'a>(
369 &'a self,
370 shard: &'a Shard,
371 ) -> Result<FastHashMap<&'a ShardName, &'a Shard>, Error> {
372 let mut acc = FastHashMap::default();
373 self.dependencies_from(shard, &[], &mut acc)?;
374 Ok(acc)
375 }
376
377 /// Gather all recursive dependent shards for `shard`, given that the path
378 /// through dependencies is `from` (to detect cycles) and we should
379 /// accumulate the dependencies in `acc`.
380 fn dependencies_from<'a>(
381 &'a self,
382 shard: &'a Shard,
383 from: &[&'a ShardName],
384 acc: &mut FastHashMap<&'a ShardName, &'a Shard>,
385 ) -> Result<(), Error> {
386 // TODO cache dependencies?
387 for name in &shard.requires {
388 if from.contains(&name) {
389 let mut cycle: Vec<ShardName> =
390 from.iter().map(|n| (*n).to_owned()).collect();
391 cycle.push(name.to_owned());
392 return Err(Error::CycleInShards(cycle));
393 }
394 let sub_shard = &self.shards[name];
395 acc.insert(name, sub_shard);
396 let mut from = from.to_vec();
397 from.push(name);
398 self.dependencies_from(sub_shard, &from, acc)?;
399 }
400
401 Ok(())
402 }
403 }
404
405 /// Represents a named narrow view into the repo's files (at the history level).
406 ///
407 /// This is a user-facing concept.
408 #[derive(Debug, Clone)]
409 pub struct Shape {
410 name: ShardName,
411 pub(crate) tree: ShardTreeNode,
412 }
413
414 impl Shape {
415 pub fn new(
416 name: ShardName,
417 store_shards: &StoreShards,
418 shards: &[&Shard],
419 ) -> Result<Self, Error> {
420 let mut expanded_shards = vec![];
421 for shard in shards {
422 expanded_shards.push(*shard);
423 expanded_shards.extend(store_shards.dependencies(shard)?.values())
424 }
425 let tree = ShardTreeNode::from_shards(store_shards, &expanded_shards)?;
426 Ok(Self { name, tree })
427 }
428
429 /// Returns a [`Matcher`] that expresses the constraints of this shape
430 pub fn matcher(&self) -> ShapeMatcher {
431 ShapeMatcher::new(self.to_owned())
432 }
433
434 pub fn store_fingerprint(&self) -> [u8; 32] {
435 self.tree.fingerprint()
436 }
437
438 pub fn patterns(&self) -> (Vec<HgPathBuf>, Vec<HgPathBuf>) {
439 self.tree.flat()
440 }
441
442 pub fn name(&self) -> &ShardName {
443 &self.name
444 }
445
446 pub fn from_patterns(
447 includes: &[FilePattern],
448 excludes: &[FilePattern],
449 ) -> Result<Self, Error> {
450 let tree = ShardTreeNode::from_patterns(includes, excludes)?;
451 let name = ShardName::new("hg-internal".into()).expect("valid name");
452 Ok(Self { name, tree })
453 }
454 }
455
456 /// Matches the os-disk config for a single shard inside the [`ShapesConfig`]
457 #[derive(Debug, Serialize, Deserialize)]
458 struct ShardConfig {
459 /// Canonical name for this shard. Used both in UI and protocol
460 name: String,
461 #[serde(default)]
462 /// Whether this shard is also a user-accessible shape
463 shape: bool,
464 /// The paths that this shard concerns. Can only be none if this shard
465 /// has [`Self::requires`]
466 paths: Option<Vec<String>>,
467
468 // TODO encoded paths for non-utf8 paths
469 // encoded_paths: Option<Vec<String>>,
470 /// Names of the shards that this shard depends on, to build a hierarchy
471 requires: Option<Vec<String>>,
472 }
473
474 /// Matches the on-disk format for admins to define their repo's shards and
475 /// shapes
476 #[derive(Debug, Serialize, Deserialize, Default)]
477 pub struct ShapesConfig {
478 // XXX should there be a `[meta]` section?
479 /// The version of this config. For now only version `0` exists.
480 version: u32,
481 /// The shards and shapes defined by the repo's admins.
482 shards: Vec<ShardConfig>,
483 }
484
485 /// A temporary structure useful to create a [`ShardTreeNode`], since it
486 /// temporarily requires mutable aliasing.
487 #[derive(Clone)]
488 pub struct TempShardTreeNode {
489 /// The [`ZeroPath`] (rooted by `b""`) that this node concerns
490 path: ZeroPath,
491 /// Whether this path is included or excluded
492 included: bool,
493 /// The set of mutably aliased child nodes (describing rules for sub-paths)
494 children: Vec<Arc<PanickingRwLock<Self>>>,
495 }
496
497 impl std::fmt::Debug for TempShardTreeNode {
498 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
499 f.debug_struct("TempShardTreeNode")
500 .field("path", &self.path)
501 .field("included", &self.included)
502 // Remove the `RwLock` noise from the debug output
503 .field(
504 "children",
505 &self
506 .children
507 .iter()
508 .map(|node| node.read().to_owned())
509 .collect::<Vec<Self>>(),
510 )
511 .finish()
512 }
513 }
514
515 impl TempShardTreeNode {
516 /// `true` if `self` is a sub-path of `other`
517 fn sub_path_of(&self, other: &Self) -> bool {
518 // Paths are both `ZeroPath`, which ensures this property.
519 self.path.sub_path_of(&other.path)
520 }
521 /// Create a [`ShardTreeNode`] from this finished temp tree
522 fn finish(&self) -> ShardTreeNode {
523 ShardTreeNode {
524 path: HgPathBuf::from(&self.path),
525 included: self.included,
526 children: self
527 .children
528 .iter()
529 .map(|child| child.read().finish())
530 .collect(),
531 }
532 }
533 }
534
535 /// A node within a tree of narrow patterns.
536 ///
537 /// It is used to create a normalized representation of potentially nested
538 /// include and exclude patterns to uniquely identify semantically equivalent
539 /// rules, as well as generating an associated file matcher.
540 #[derive(Clone, Debug)]
541 pub struct ShardTreeNode {
542 /// The path (rooted by `b""`) that this node concerns
543 pub(crate) path: HgPathBuf,
544 /// Whether this path is included or excluded
545 pub(crate) included: bool,
546 /// The set of child nodes (describing rules for sub-paths)
547 pub(crate) children: Vec<Self>,
548 }
549
550 impl ShardTreeNode {
551 /// Create the tree expressed by the server shapes config
552 pub fn from_shards<'a>(
553 store_shards: &'a StoreShards,
554 shards: &[&'a Shard],
555 ) -> Result<Self, Error> {
556 let mut shard_paths = HashSet::new();
557 // Gather all paths recursively
558 for shard in shards {
559 shard_paths.extend(shard.paths.iter().map(|path| path.as_bytes()));
560 shard_paths.extend(
561 store_shards
562 .dependencies(shard)?
563 .values()
564 .flat_map(|shard| &shard.paths)
565 .map(|p| p.as_bytes()),
566 );
567 }
568 assert!(!shard_paths.is_empty());
569 Self::from_paths(
570 store_shards.path_to_shard.keys().map(|path| path.as_bytes()),
571 shard_paths,
572 )
573 }
574
575 /// Create the tree expressed by old-style include and exclude patterns
576 pub fn from_patterns<'a>(
577 includes: &'a [FilePattern],
578 excludes: &'a [FilePattern],
579 ) -> Result<Self, Error> {
580 let check_pattern = |pattern: &'a FilePattern| {
581 if pattern.syntax != PatternSyntax::Path {
582 let syntax = format!("{:?}", pattern.syntax);
583 Err(PatternError::UnsupportedSyntax(syntax))
584 } else {
585 Ok(pattern.raw.as_slice())
586 }
587 };
588 let mut include_paths = includes
589 .iter()
590 .map(check_pattern)
591 .collect::<Result<HashSet<&[u8]>, _>>()
592 .map_err(Error::PatternError)?;
593
594 let exclude_paths = excludes
595 .iter()
596 .map(check_pattern)
597 .collect::<Result<HashSet<&[u8]>, _>>()
598 .map_err(Error::PatternError)?;
599
600 let empty_path = b"".as_slice();
601 // `clone` passes `path:.` by default which is supposed to include
602 // everything. This is the wrong API IMO and is a serialization detail
603 // hitting internal logic (empty paths are annoying in text formats).
604 let empty_path_alt = b".".as_slice();
605
606 let root = if include_paths.contains(&empty_path)
607 || include_paths.contains(&empty_path_alt)
608 || include_paths.is_empty()
609 {
610 include_paths.remove(&empty_path_alt);
611 // Need to include everything by default
612 include_paths.insert(empty_path);
613 vec![]
614 } else {
615 vec![empty_path]
616 };
617
618 Self::from_paths(
619 root.into_iter().chain(include_paths.clone()).chain(exclude_paths),
620 include_paths,
621 )
622 }
623
624 /// `paths` is the iterator of all paths (included or not) and `includes`
625 /// contains only the paths that are included.
626 fn from_paths<Paths, Bytes>(
627 paths: Paths,
628 includes: HashSet<&[u8]>,
629 ) -> Result<Self, Error>
630 where
631 Paths: Iterator<Item = Bytes>,
632 Bytes: AsRef<[u8]>,
633 {
634 // Generate a flat sequence of nodes, sorted via ZeroPath
635 let mut nodes = paths
636 .map(|path| {
637 Ok(Arc::new(PanickingRwLock::new(TempShardTreeNode {
638 path: ZeroPath::new(path.as_ref())?,
639 included: includes.contains(path.as_ref()),
640 children: vec![],
641 })))
642 })
643 .collect::<Result<Vec<_>, Error>>()?;
644 nodes.sort_by(|a, b| a.read().path.cmp(&b.read().path));
645
646 // Create the tree by looping over the nodes and keeping track of
647 // where we are in the recursion via a stack
648 let mut stack: Vec<Arc<PanickingRwLock<TempShardTreeNode>>> = vec![];
649 for node in nodes {
650 while !stack.is_empty()
651 && !node
652 .read()
653 .sub_path_of(&stack.last().expect("not empty").read())
654 {
655 stack.pop();
656 }
657 if let Some(last) = stack.last_mut() {
658 // Only insert children that are not redundant
659 if last.read().included != node.read().included {
660 last.write().children.push(node.clone());
661 stack.push(node);
662 }
663 } else {
664 stack.push(node);
665 }
666 }
667 let root = stack.into_iter().next().expect("should have one element");
668 let root = Arc::into_inner(root)
669 .expect("should have only one ref")
670 .into_inner();
671
672 Ok(root.finish())
673 }
674
675 /// Do not call this directly, use [`deepest_prefix_node`].
676 fn deepest_node_impl(&self, path: &HgPath, skip: usize) -> Option<&Self> {
677 let path_bytes = path.as_bytes();
678 let self_bytes = self.path.as_bytes();
679
680 // If the matched path doesn't match the current node, exit.
681 if !self_bytes.is_empty() // The root node matches all
682 && !(
683 // The matched path starts with the node path
684 path_bytes[skip..].starts_with(&self_bytes[skip..])
685 // ...up to a directory boundary or the end of the path
686 && (path_bytes.len() == self_bytes.len()
687 || (path_bytes[self_bytes.len()] == b'/')))
688 {
689 return None;
690 }
691
692 // Check if a child has a better match
693 for child in &self.children {
694 assert_ne!(self.included, child.included);
695 let c_match = child.deepest_node_impl(path, self_bytes.len());
696 if c_match.is_some() {
697 // There can only be up to one matching child.
698 //
699 // The tree optimization ensures that the inclusion value of a
700 // node is always different than the inclusion value of its
701 // children. As a result, all children have the same inclusion
702 // value.
703 //
704 // So if two children were to match, it would mean that one of
705 // them would be a prefix of the other, with the same inclusion
706 // value, at the same level. In this case the node with the
707 // longer match would be redundant with the other one, but in
708 // practice such nodes have been optimized away already.
709 return c_match;
710 }
711 }
712 Some(self)
713 }
714
715 /// Get the fingerprint for this node. It will return a different hash for
716 /// a semantically different node, allowing for a quick comparison.
717 pub fn fingerprint(&self) -> [u8; 32] {
718 let mut hasher = Sha256::new();
719 self.serialize(&mut hasher).expect("writing to a hasher never fails");
720 hasher.finalize().into()
721 }
722
723 /// Return the node normalized as two flat sets of includes and excludes
724 fn flat(&self) -> (Vec<HgPathBuf>, Vec<HgPathBuf>) {
725 let mut includes = vec![];
726 let mut excludes = vec![];
727
728 if self.included {
729 includes.push(self.path.clone());
730 } else {
731 excludes.push(self.path.clone());
732 }
733
734 for child in self.children.iter() {
735 let (sub_includes, sub_excludes) = child.flat();
736 includes.extend(sub_includes);
737 excludes.extend(sub_excludes);
738 }
739
740 (includes, excludes)
741 }
742
743 /// Serialize this node with the following binary format:
744 ///
745 /// `<HEADER>\n<NUM>\n[<MARKER>/<PATH>\n...]`
746 ///
747 /// With:
748 /// - `<HEADER>` being the literal ascii bytes `shape-v1` to help identify
749 /// the format easily, and as a sanity check
750 /// - `<NUM>` is the number of paths as a little-endian 64bits integer
751 /// - `[X...]` is syntax for "for each element, do X"
752 /// - `<MARKER>` is either the literal ascii bytes `inc` or `exc`,
753 /// depending on whether this path is included or excluded
754 /// - `<PATH>` is the raw bytes of each path, rooted at the empty path
755 fn serialize(&self, mut buf: impl Write) -> Result<(), std::io::Error> {
756 let (includes, excludes) = self.flat();
757
758 buf.write_all(b"shape-v1\n")?;
759 let sorted_paths = includes
760 .into_iter()
761 .map(|i| (i, true))
762 .chain(excludes.into_iter().map(|i| (i, false)))
763 // sort by zero path so we get the children next to the parents
764 .sorted_by(|a, b| a.0.cmp(&b.0));
765
766 let number_of_paths: u64 =
767 sorted_paths.len().try_into().expect("too many paths");
768 buf.write_all(&number_of_paths.to_le_bytes())?;
769 for (path, included) in sorted_paths {
770 buf.write_all(if included { b"inc" } else { b"exc" })?;
771 buf.write_all(b"/")?;
772 buf.write_all(path.as_bytes())?;
773 buf.write_all(b"\n")?;
774 }
775
776 Ok(())
777 }
778 }
779
780 /// Returns the deepest node in `root` whose path is a prefix of
781 /// (or is exactly) `path`.
782 ///
783 /// # Panics
784 ///
785 /// Panics if `root` is not the root node (i.e. if it has a non-empty path).
786 pub(crate) fn deepest_prefix_node<'tree>(
787 root: &'tree ShardTreeNode,
788 path: &HgPath,
789 ) -> &'tree ShardTreeNode {
790 assert!(root.path.is_empty());
791 if path.is_empty() {
792 return root;
793 }
794 root.deepest_node_impl(path, 0).unwrap_or(root)
795 }
796
797 /// An [`HgPathBuf`] with all `/` in `path` replaced with `\0`, and surrounded
798 /// by `\0`.
799 /// This ensures that a path and its subpath get sorted next to each other
800 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
801 struct ZeroPath(Vec<u8>);
802
803 impl std::fmt::Debug for ZeroPath {
804 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
805 f.debug_tuple("ZeroPath").field(&self.to_hg_path_buf()).finish()
806 }
807 }
808
809 impl ZeroPath {
810 fn new(bytes: &[u8]) -> Result<Self, Error> {
811 let mut path = Vec::with_capacity(bytes.len());
812 for (idx, byte) in bytes.iter().enumerate() {
813 if idx == 0 {
814 if *byte == b'/' {
815 let err = HgPathErrorKind::LeadingSlash(bytes.to_owned());
816 return Err(Error::InvalidPath(err.into()));
817 }
818 path.push(b'\0');
819 }
820 assert_ne!(*byte, b'\0');
821 if idx == bytes.len() - 1 {
822 if *byte == b'/' {
823 let err = HgPathErrorKind::EndsWithSlash(
824 HgPathBuf::from_bytes(bytes),
825 );
826 return Err(Error::InvalidPath(err.into()));
827 }
828 path.push(*byte);
829 path.push(b'\0');
830 } else if *byte == b'/' {
831 path.push(b'\0');
832 } else {
833 path.push(*byte);
834 }
835 }
836 if path.is_empty() {
837 path.push(b'\0');
838 }
839 Ok(Self(path))
840 }
841
842 fn to_hg_path_buf(&self) -> HgPathBuf {
843 self.into()
844 }
845
846 fn sub_path_of(&self, other: &Self) -> bool {
847 self.0.starts_with(&other.0)
848 }
849 }
850
851 impl TryFrom<&HgPath> for ZeroPath {
852 type Error = Error;
853
854 fn try_from(path: &HgPath) -> Result<Self, Error> {
855 Self::new(path.as_bytes())
856 }
857 }
858
859 impl From<&ZeroPath> for HgPathBuf {
860 fn from(path: &ZeroPath) -> Self {
861 let bytes = path.0.as_slice();
862 let mut path = Vec::with_capacity(bytes.len());
863 for (idx, byte) in bytes.iter().enumerate() {
864 if idx == 0 {
865 assert_eq!(*byte, b'\0');
866 continue;
867 }
868 assert_ne!(*byte, b'/');
869 if idx == bytes.len() - 1 {
870 assert_eq!(*byte, b'\0');
871 continue;
872 } else if *byte == b'\0' {
873 path.push(b'/');
874 } else {
875 path.push(*byte);
876 }
877 }
878 path.into()
879 }
880 }
881
882 #[derive(Debug)]
883 /// Quality-of-life struct to help with unwrapping panics by default.
884 /// We only need a [`RwLock`] to work around the borrow checker for the tree
885 /// structure (RefCell wouldn't work because we need to be [`Sync`] + [`Send`]),
886 /// we don't *actually* do anything concurrent, so this is fine if the
887 /// implementation is correct, which it would break very loudly if it weren't.
888 struct PanickingRwLock<T: ?Sized>(RwLock<T>);
889
890 impl<T> PanickingRwLock<T> {
891 pub fn new(inner: T) -> Self {
892 Self(RwLock::new(inner))
893 }
894
895 pub fn read(&self) -> RwLockReadGuard<T> {
896 self.0.read().expect("propagate panic")
897 }
898
899 pub fn write(&self) -> RwLockWriteGuard<T> {
900 self.0.write().expect("propagate panic")
901 }
902
903 pub fn into_inner(self) -> T
904 where
905 T: Sized,
906 {
907 self.0.into_inner().expect("propagate panic")
908 }
909 }
910
911 #[cfg(test)]
912 mod tests {
913 use pretty_assertions::assert_eq;
914
915 use super::*;
916 use crate::matchers::Matcher;
917 use crate::matchers::VisitChildrenSet;
918
919 /// produce a valid store sharding
920 ///
921 /// See [`test_patterns`] for each shard patterns.
922 fn valid_store_shards() -> (StoreShards, Vec<&'static str>) {
923 // Leading whitespace does not matter in TOML, I think this is more
924 // readable
925 let valid_config = r#"
926 version = 0
927
928 [[shards]]
929 name = "foo"
930 paths = ["foo"]
931 requires = ["baz", "base"]
932 shape = true
933
934 [[shards]]
935 name = "stone"
936 paths = ["stone"]
937 shape = true
938
939 [[shards]]
940 name = "lizard"
941 paths = ["stone/liz/ard"]
942
943 [[shards]]
944 name = "lizzie"
945 paths = ["stone/liz/zie"]
946
947 [[shards]]
948 name = "borden"
949 paths = ["stone/liz/zie/bor/den"]
950 requires = ["stone"]
951 shape = true
952
953 [[shards]]
954 name = "mummy"
955 paths = ["stone/mummy"]
956 shape = true
957
958 [[shards]]
959 name = "chamber"
960 paths = ["stone/mummy/chamber"]
961 requires = ["stone"]
962 shape = true
963
964 [[shards]]
965 name = "inner"
966 paths = ["stone/mummy/chamber/inner"]
967
968 [[shards]]
969 name = "bar"
970 paths = ["bar"]
971 shape = true
972
973 [[shards]]
974 name = "baz"
975 paths = ["bar/baz"]
976
977 [[shards]]
978 name = "bazik"
979 paths = ["bar/baz/ik"]
980 requires = ["bar"]
981 shape = true
982
983 [[shards]]
984 name = "baziku"
985 paths = ["bar/baz/ik/u"]
986
987 [[shards]]
988 name = "baron"
989 requires = ["bar", "baziku"]
990 shape = true
991
992 [[shards]]
993 name = "nested"
994 paths = ["some/super/nested/file"]
995 shape = true
996 "#;
997
998 // Make sure we can load this config
999 let config_result = toml::from_str::<ShapesConfig>(valid_config);
1000 assert!(config_result.is_ok(), "{:?}", config_result);
1001 let config = config_result.unwrap();
1002
1003 // We can create a storeshards
1004 let store_shards_result = StoreShards::from_config(config);
1005 assert!(store_shards_result.is_ok(), "{:?}", store_shards_result);
1006 let store_shards = store_shards_result.unwrap();
1007
1008 let all_shard_names = vec![
1009 ".hg-files",
1010 "bar",
1011 "baron",
1012 "base",
1013 "baz",
1014 "bazik",
1015 "baziku",
1016 "borden",
1017 "chamber",
1018 "foo",
1019 "full",
1020 "inner",
1021 "lizard",
1022 "lizzie",
1023 "mummy",
1024 "nested",
1025 "stone",
1026 ];
1027 // Shards are as expected, along with the implicit shards
1028 assert_eq!(
1029 all_shard_names,
1030 store_shards
1031 .shards
1032 .keys()
1033 .sorted()
1034 .map(|k| k.to_string())
1035 .collect::<Vec<_>>(),
1036 );
1037
1038 let all_shape_names = vec![
1039 "bar", "baron", "bazik", "borden", "chamber", "foo", "full",
1040 "mummy", "nested", "stone",
1041 ];
1042 // Shapes are as expected, along with the implicit shapes
1043 assert_eq!(
1044 all_shape_names,
1045 store_shards
1046 .all_shapes()
1047 .unwrap()
1048 .into_iter()
1049 .map(|shape| shape.name().to_string())
1050 .collect::<Vec<_>>(),
1051 );
1052 (store_shards, all_shape_names)
1053 }
1054
1055 #[test]
1056 fn test_dependencies() {
1057 let (store_shards, _) = valid_store_shards();
1058
1059 fn assert_dependencies(
1060 store_shards: &StoreShards,
1061 shard_name: &str,
1062 expected: Vec<&str>,
1063 ) {
1064 let dependencies = store_shards
1065 .dependencies(
1066 &store_shards.shards
1067 [&ShardName::new(shard_name.to_string()).unwrap()],
1068 )
1069 .unwrap()
1070 .into_keys()
1071 .sorted()
1072 .map(|n| n.to_string());
1073 let dependencies = dependencies.collect::<Vec<String>>();
1074 assert_eq!(expected, dependencies, "for shard {}", shard_name);
1075 }
1076
1077 assert_dependencies(&store_shards, "bar", vec![".hg-files"]);
1078 assert_dependencies(
1079 &store_shards,
1080 "foo",
1081 vec![".hg-files", "base", "baz"],
1082 );
1083 assert_dependencies(
1084 &store_shards,
1085 "full",
1086 vec![
1087 ".hg-files",
1088 "bar",
1089 "baron",
1090 "base",
1091 "baz",
1092 "bazik",
1093 "baziku",
1094 "borden",
1095 "chamber",
1096 "foo",
1097 "inner",
1098 "lizard",
1099 "lizzie",
1100 "mummy",
1101 "nested",
1102 "stone",
1103 ],
1104 );
1105 }
1106
1107 #[test]
1108 fn test_patterns() {
1109 let (store_shards, all_shape_names) = valid_store_shards();
1110
1111 fn assert_patterns(
1112 store_shards: &StoreShards,
1113 shard_name: &str,
1114 expected_includes: &[&str],
1115 expected_excludes: &[&str],
1116 ) {
1117 let shape = store_shards.shape(shard_name).unwrap().unwrap();
1118 dbg!(&shard_name);
1119 dbg!(&shape.tree);
1120 let (includes, excludes) = shape.patterns();
1121 let expected_includes = expected_includes
1122 .iter()
1123 .map(|p| HgPathBuf::from_bytes(p.as_bytes()))
1124 .collect::<Vec<_>>();
1125 let expected_excludes = expected_excludes
1126 .iter()
1127 .map(|p| HgPathBuf::from_bytes(p.as_bytes()))
1128 .collect::<Vec<_>>();
1129 assert_eq!(
1130 expected_includes, includes,
1131 "wrong includes for shape {}",
1132 shard_name
1133 );
1134 assert_eq!(
1135 expected_excludes, excludes,
1136 "wrong excludes for shape {}",
1137 shard_name
1138 );
1139 }
1140
1141 // Test the patterns for each shape (<include>, <exclude>)
1142 type Patterns<'a> = (&'a [&'a str], &'a [&'a str]);
1143 let shape_to_patterns: &[(&str, Patterns)] = &[
1144 ("full", (&[""], &[])),
1145 (
1146 "bar",
1147 (
1148 &[".hgignore", ".hgsub", ".hgsubstate", ".hgtags", "bar"],
1149 &["", "bar/baz"],
1150 ),
1151 ),
1152 (
1153 "baron",
1154 (
1155 &[
1156 ".hgignore",
1157 ".hgsub",
1158 ".hgsubstate",
1159 ".hgtags",
1160 "bar",
1161 "bar/baz/ik/u",
1162 ],
1163 &["", "bar/baz"],
1164 ),
1165 ),
1166 (
1167 "bazik",
1168 (
1169 &[
1170 ".hgignore",
1171 ".hgsub",
1172 ".hgsubstate",
1173 ".hgtags",
1174 "bar",
1175 "bar/baz/ik",
1176 ],
1177 &["", "bar/baz", "bar/baz/ik/u"],
1178 ),
1179 ),
1180 (
1181 "foo",
1182 (
1183 &["", "bar/baz"],
1184 &["bar", "bar/baz/ik", "some/super/nested/file", "stone"],
1185 ),
1186 ),
1187 (
1188 "stone",
1189 (
1190 &[".hgignore", ".hgsub", ".hgsubstate", ".hgtags", "stone"],
1191 &["", "stone/liz/ard", "stone/liz/zie", "stone/mummy"],
1192 ),
1193 ),
1194 (
1195 "borden",
1196 (
1197 &[
1198 ".hgignore",
1199 ".hgsub",
1200 ".hgsubstate",
1201 ".hgtags",
1202 "stone",
1203 "stone/liz/zie/bor/den",
1204 ],
1205 &["", "stone/liz/ard", "stone/liz/zie", "stone/mummy"],
1206 ),
1207 ),
1208 (
1209 "mummy",
1210 (
1211 &[
1212 ".hgignore",
1213 ".hgsub",
1214 ".hgsubstate",
1215 ".hgtags",
1216 "stone/mummy",
1217 ],
1218 &["", "stone/mummy/chamber"],
1219 ),
1220 ),
1221 (
1222 "chamber",
1223 (
1224 &[
1225 ".hgignore",
1226 ".hgsub",
1227 ".hgsubstate",
1228 ".hgtags",
1229 "stone",
1230 "stone/mummy/chamber",
1231 ],
1232 &[
1233 "",
1234 "stone/liz/ard",
1235 "stone/liz/zie",
1236 "stone/mummy",
1237 "stone/mummy/chamber/inner",
1238 ],
1239 ),
1240 ),
1241 (
1242 "nested",
1243 (
1244 &[
1245 ".hgignore",
1246 ".hgsub",
1247 ".hgsubstate",
1248 ".hgtags",
1249 "some/super/nested/file",
1250 ],
1251 &[""],
1252 ),
1253 ),
1254 ];
1255
1256 for (shard_name, (expected_includes, expected_excludes)) in
1257 shape_to_patterns
1258 {
1259 assert_patterns(
1260 &store_shards,
1261 shard_name,
1262 expected_includes,
1263 expected_excludes,
1264 );
1265 }
1266
1267 // Make sure we've tested all names
1268 assert_eq!(
1269 all_shape_names,
1270 shape_to_patterns
1271 .iter()
1272 .map(|(n, _)| *n)
1273 .sorted()
1274 .collect::<Vec<&str>>(),
1275 );
1276 }
1277
1278 /// Test that every shape matches the right files
1279 #[test]
1280 fn test_matcher_simple() {
1281 let (store_shards, all_shape_names) = valid_store_shards();
1282
1283 let files_to_shape: &[(&str, &[&str])] = &[
1284 // the core mercurial file shoudl always be included
1285 (".hgignore", &all_shape_names),
1286 (".hgsub", &all_shape_names),
1287 (".hgsubstate", &all_shape_names),
1288 (".hgtags", &all_shape_names),
1289 // babar is not matched by any explicit shard,
1290 // So it selected by "base". In addition "foo" depends on "base"
1291 ("babar/v", &["full", "foo"]),
1292 // `bar/` is matched by the "bar" shard and its dependencies
1293 ("bar/ba/v", &["full", "bar", "baron", "bazik"]),
1294 // we match full name only
1295 ("barbar/v", &["full", "foo"]),
1296 // However `bar/baz` is explicitly matched by "baz" (a shard), so
1297 // it isn't contained in "bar". It appears in "foo" (a
1298 // shape that include on "baz")
1299 ("bar/baz/f", &["full", "foo"]),
1300 ("bar/baz/g", &["full", "foo"]),
1301 ("bar/baz/i", &["full", "foo"]),
1302 ("bar/baz/blu/toto", &["full", "foo"]),
1303 // We match full name only
1304 ("bar/bazar", &["full", "bar", "baron", "bazik"]),
1305 // Again `bar/bar/ik` is matched by the "bazik" shard so it is
1306 // considered independently
1307 ("bar/baz/ik/U/j", &["full", "bazik"]),
1308 ("bar/baz/ik/U/k", &["full", "bazik"]),
1309 ("bar/baz/ik/U/m", &["full", "bazik"]),
1310 ("bar/baz/ik/h", &["full", "bazik"]),
1311 ("bar/baz/ik/i", &["full", "bazik"]),
1312 ("bar/baz/ik/o/l", &["full", "bazik"]),
1313 // `bar/baz/ik/u` is part of the "baziku" shard included in the
1314 // "baron" sharp
1315 ("bar/baz/ik/u/j", &["full", "baron"]),
1316 ("bar/baz/ik/u/k", &["full", "baron"]),
1317 ("bar/baz/ik/u/m", &["full", "baron"]),
1318 ("bar/baz/ik/u/klm/foo", &["full", "baron"]),
1319 // We match full name only
1320 ("bar/baz/ik/ups", &["full", "bazik"]),
1321 ("bar/baz/ik/ups/klm/bar", &["full", "bazik"]),
1322 // both "baron" and "bazik" includes "bar"
1323 ("bar/d", &["full", "bar", "baron", "bazik"]),
1324 ("bar/e", &["full", "bar", "baron", "bazik"]),
1325 // `foo/` is matched by the "foo" shape and no other
1326 ("foo/a", &["full", "foo"]),
1327 ("foo/b", &["full", "foo"]),
1328 ("foo/c", &["full", "foo"]),
1329 ("foo/y", &["full", "foo"]),
1330 // `stone/liz/` has three excluded directory within
1331 ("stone/foo", &["full", "stone", "borden", "chamber"]),
1332 ("stone/liz", &["full", "stone", "borden", "chamber"]),
1333 ("stone/mummy", &["full", "mummy"]),
1334 ("stone/mummy/return", &["full", "mummy"]),
1335 ("stone/mummy/chamber", &["full", "chamber"]),
1336 ("stone/mummy/chamber/inner", &["full"]),
1337 ("stone/mummy/chamber/babar", &["full", "chamber"]),
1338 ("stone/mummy/chamber/inner/babar", &["full"]),
1339 (
1340 "stone/liz/chamber/babar",
1341 &["full", "stone", "borden", "chamber"],
1342 ),
1343 ("stone/liz/chamber", &["full", "stone", "borden", "chamber"]),
1344 (
1345 "stone/liz/chamber/inner",
1346 &["full", "stone", "borden", "chamber"],
1347 ),
1348 (
1349 "stone/liz/chamber/inner/babar",
1350 &["full", "stone", "borden", "chamber"],
1351 ),
1352 ("stone/liz/foo", &["full", "stone", "borden", "chamber"]),
1353 ("stone/liz/babar", &["full", "stone", "borden", "chamber"]),
1354 ("stone/liz/ard", &["full"]),
1355 ("stone/liz/ard/babar", &["full"]),
1356 ("stone/liz/on", &["full", "stone", "borden", "chamber"]),
1357 ("stone/liz/on/babar", &["full", "stone", "borden", "chamber"]),
1358 ("stone/liz/zie", &["full"]),
1359 ("stone/liz/zie/babar", &["full"]),
1360 ("stone/liz/zie/bor", &["full"]),
1361 ("stone/liz/zie/bor/den", &["full", "borden"]),
1362 ("stone/liz/zie/bor/den/babar", &["full", "borden"]),
1363 // various unmatched stuff
1364 ("oops", &["full", "foo"]),
1365 ("some/super/other/nested", &["full", "foo"]),
1366 ("w", &["full", "foo"]),
1367 ("y", &["full", "foo"]),
1368 ("z", &["full", "foo"]),
1369 ];
1370
1371 let shape_to_matcher: Vec<_> = all_shape_names
1372 .iter()
1373 .map(|name| {
1374 let shape = store_shards.shape(name).unwrap().unwrap();
1375 let matcher = shape.matcher();
1376 (shape.name().to_string(), matcher)
1377 })
1378 .collect();
1379 for (file, expected_shapes) in files_to_shape {
1380 let mut expected: Vec<_> = expected_shapes.to_vec();
1381 expected.sort();
1382 let file = HgPath::new(file.as_bytes());
1383
1384 let matching: Vec<_> = shape_to_matcher
1385 .iter()
1386 .filter(|(_, matcher)| matcher.matches(file))
1387 .map(|(name, _)| name)
1388 .collect();
1389 assert_eq!(
1390 &expected, &matching,
1391 "file '{file}' doesn't match the expected shapes"
1392 );
1393 }
1394 }
1395
1396 #[test]
1397 fn test_deepest_prefix_node() {
1398 let (store_shards, _) = valid_store_shards();
1399
1400 #[track_caller]
1401 fn assert_node(node: &ShardTreeNode, expect: &[u8]) {
1402 assert_eq!(node.path.as_ref(), HgPath::new(expect));
1403 }
1404
1405 // Full should always return the root node
1406 let shape = store_shards.shape("full").unwrap().unwrap();
1407 let node = deepest_prefix_node(&shape.tree, HgPath::new(b""));
1408 assert_node(node, b"");
1409 assert_eq!(node.included, true);
1410 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"root"));
1411 assert_node(node, b"");
1412 assert_eq!(node.included, true);
1413 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"bar/baz"));
1414 assert_node(node, b"");
1415 assert_eq!(node.included, true);
1416
1417 // Test simple nested shape
1418 let shape = store_shards.shape("bar").unwrap().unwrap();
1419 let node = deepest_prefix_node(&shape.tree, HgPath::new(b""));
1420 assert_node(node, b"");
1421 assert_eq!(node.included, false);
1422 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"root"));
1423 assert_node(node, b"");
1424 assert_eq!(node.included, false);
1425 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"bar/test"));
1426 assert_node(node, b"bar");
1427 assert_eq!(node.included, true);
1428 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"bar/baz"));
1429 assert_node(node, b"bar/baz");
1430 assert_eq!(node.included, false);
1431 let node = deepest_prefix_node(
1432 &shape.tree,
1433 HgPath::new(b"bar/baz/nested/deeper"),
1434 );
1435 assert_node(node, b"bar/baz");
1436 assert_eq!(node.included, false);
1437
1438 // Test doubly nested shape
1439 let shape = store_shards.shape("baron").unwrap().unwrap();
1440 dbg!(&shape);
1441 let node = deepest_prefix_node(&shape.tree, HgPath::new(b""));
1442 assert_node(node, b"");
1443 assert_eq!(node.included, false);
1444 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"root"));
1445 assert_node(node, b"");
1446 assert_eq!(node.included, false);
1447 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"bar/test"));
1448 assert_node(node, b"bar");
1449 assert_eq!(node.included, true);
1450 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"bar/baz"));
1451 assert_node(node, b"bar/baz");
1452 assert_eq!(node.included, false);
1453 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"bar/bazik"));
1454 assert_node(node, b"bar");
1455 assert_eq!(node.included, true);
1456 let node = deepest_prefix_node(
1457 &shape.tree,
1458 HgPath::new(b"bar/baz/nested/deeper"),
1459 );
1460 assert_node(node, b"bar/baz");
1461 assert_eq!(node.included, false);
1462 let node =
1463 deepest_prefix_node(&shape.tree, HgPath::new(b"bar/baz/ik/u"));
1464 assert_node(node, b"bar/baz/ik/u");
1465 assert_eq!(node.included, true);
1466 let node =
1467 deepest_prefix_node(&shape.tree, HgPath::new(b"bar/baz/ik/ui"));
1468 assert_node(node, b"bar/baz");
1469 assert_eq!(node.included, false);
1470
1471 let shape = store_shards.shape("stone").unwrap().unwrap();
1472 dbg!(&shape.tree);
1473 let node = deepest_prefix_node(&shape.tree, HgPath::new(b"stone/liz"));
1474 assert_node(node, b"stone");
1475 assert_eq!(node.included, true);
1476
1477 let shape = store_shards.shape("borden").unwrap().unwrap();
1478 dbg!(&shape.tree);
1479 let node =
1480 deepest_prefix_node(&shape.tree, HgPath::new(b"stone/liz/zie/bor"));
1481 assert_node(node, b"stone/liz/zie");
1482 assert_eq!(node.included, false);
1483
1484 let shape = store_shards.shape("mummy").unwrap().unwrap();
1485 dbg!(&shape.tree);
1486 let node = deepest_prefix_node(
1487 &shape.tree,
1488 HgPath::new(b"stone/mummy/chamber"),
1489 );
1490 assert_node(node, b"stone/mummy/chamber");
1491 assert_eq!(node.included, false);
1492 }
1493
1494 #[test]
1495 fn test_matcher_visit_children_set() {
1496 let (store_shards, _all_shape_names) = valid_store_shards();
1497 let shape = store_shards.shape("bar").unwrap().unwrap();
1498 let matcher = shape.matcher();
1499 // Test an exact match on a non-included node
1500 assert_eq!(
1501 matcher.visit_children_set(HgPath::new(b"")),
1502 VisitChildrenSet::Set(
1503 ["bar", ".hgignore", ".hgsubstate", ".hgtags", ".hgsub"]
1504 .iter()
1505 .map(|path| HgPathBuf::from_bytes(path.as_bytes()))
1506 .collect()
1507 )
1508 );
1509 // Test an exact match on an included node
1510 assert_eq!(
1511 matcher.visit_children_set(HgPath::new(b"bar")),
1512 VisitChildrenSet::Recursive,
1513 );
1514 // Test a prefix match on an included node
1515 assert_eq!(
1516 matcher.visit_children_set(HgPath::new(b"bar/file")),
1517 VisitChildrenSet::Recursive,
1518 );
1519 // Test a no match
1520 assert_eq!(
1521 matcher.visit_children_set(HgPath::new(b"other")),
1522 VisitChildrenSet::Empty,
1523 );
1524
1525 let shape = store_shards.shape("bazik").unwrap().unwrap();
1526 let matcher = shape.matcher();
1527 // Test an exact match on a non-included node, through a `requires`
1528 assert_eq!(
1529 matcher.visit_children_set(HgPath::new(b"")),
1530 VisitChildrenSet::Set(
1531 ["bar", ".hgignore", ".hgsubstate", ".hgtags", ".hgsub"]
1532 .iter()
1533 .map(|path| HgPathBuf::from_bytes(path.as_bytes()))
1534 .collect()
1535 )
1536 );
1537 // Test a nested no-match
1538 assert_eq!(
1539 matcher.visit_children_set(HgPath::new(b"bar/baz/other")),
1540 VisitChildrenSet::Empty
1541 );
1542 // Test a prefix match on a non-included-non-root node
1543 assert_eq!(
1544 matcher.visit_children_set(HgPath::new(b"bar/baz")),
1545 VisitChildrenSet::Set(HashSet::from_iter([HgPathBuf::from_bytes(
1546 b"bar/baz/ik"
1547 )]))
1548 );
1549 // Test a nested exact match
1550 assert_eq!(
1551 matcher.visit_children_set(HgPath::new(b"bar/baz/ik")),
1552 VisitChildrenSet::Recursive
1553 );
1554 }
1555
1556 #[test]
1557 fn test_config_invalid() {
1558 let pairs = &[
1559 (
1560 r#"
1561 version=0
1562 [[shards]]
1563 name="full"
1564 paths=[""]
1565 "#,
1566 Error::ReservedName("full".to_string()),
1567 ),
1568 (
1569 r#"
1570 version=0
1571 [[shards]]
1572 name="base"
1573 paths=[""]
1574 "#,
1575 Error::ReservedName("base".to_string()),
1576 ),
1577 (
1578 r#"
1579 version=0
1580 [[shards]]
1581 name=".hg-files"
1582 paths=[""]
1583 "#,
1584 Error::ReservedName(".hg-files".to_string()),
1585 ),
1586 (
1587 r#"
1588 version=999
1589 [[shards]]
1590 name="babar"
1591 paths=["babar"]
1592 "#,
1593 Error::UnknownVersion(999),
1594 ),
1595 (
1596 r#"
1597 version=0
1598 [[shards]]
1599 name="Babar"
1600 paths=["babar"]
1601 "#,
1602 Error::InvalidShardName("Babar".to_string()),
1603 ),
1604 (
1605 r#"
1606 version=0
1607 [[shards]]
1608 name=""
1609 paths=["babar"]
1610 "#,
1611 Error::EmptyShardName,
1612 ),
1613 (
1614 r#"
1615 version=0
1616 [[shards]]
1617 name="."
1618 paths=["babar"]
1619 "#,
1620 Error::DotOrHyphenOnlyShardName(".".to_string()),
1621 ),
1622 (
1623 r#"
1624 version=0
1625 [[shards]]
1626 name="-"
1627 paths=["babar"]
1628 "#,
1629 Error::DotOrHyphenOnlyShardName("-".to_string()),
1630 ),
1631 (
1632 r#"
1633 version=0
1634 [[shards]]
1635 name="-.-"
1636 paths=["babar"]
1637 "#,
1638 Error::DotOrHyphenOnlyShardName("-.-".to_string()),
1639 ),
1640 (
1641 r#"
1642 version=0
1643 [[shards]]
1644 name="duplicate"
1645 paths=["babar"]
1646 [[shards]]
1647 name="duplicate"
1648 paths=["babar2"]
1649 "#,
1650 Error::DuplicateShard(
1651 ShardName::new("duplicate".to_string()).unwrap(),
1652 ),
1653 ),
1654 (
1655 r#"
1656 version=0
1657 [[shards]]
1658 name="too-little"
1659 "#,
1660 Error::ShardMissingPathsAndRequires("too-little".to_string()),
1661 ),
1662 (
1663 r#"
1664 version=0
1665 [[shards]]
1666 name = "myshard"
1667 paths = ["secret"]
1668 [[shards]]
1669 name = "myshard2"
1670 paths = ["secret"]
1671 "#,
1672 Error::PathInMultipleShards(HgPathBuf::from_bytes(b"secret")),
1673 ),
1674 (
1675 r#"
1676 version=0
1677 [[shards]]
1678 name = "myshard"
1679 # Needs two slashes because we allow one trailing slash that
1680 # is stripped internally for quality of life
1681 paths = ["badpath//"]
1682 "#,
1683 Error::InvalidPath(
1684 HgPathErrorKind::EndsWithSlash(HgPathBuf::from_bytes(
1685 b"badpath/",
1686 ))
1687 .into(),
1688 ),
1689 ),
1690 (
1691 r#"
1692 version=0
1693 [[shards]]
1694 name = "myshard"
1695 paths = ["badpath//bad"]
1696 "#,
1697 Error::InvalidPath(
1698 HgPathErrorKind::ConsecutiveSlashes {
1699 bytes: b"badpath//bad".to_vec(),
1700 second_slash_index: 8,
1701 }
1702 .into(),
1703 ),
1704 ),
1705 (
1706 r#"
1707 version=0
1708 [[shards]]
1709 name="recursive"
1710 requires=["recursive"]
1711 "#,
1712 Error::CycleInShards(vec![
1713 ShardName::new("recursive".to_string()).unwrap(),
1714 ShardName::new("recursive".to_string()).unwrap(),
1715 ]),
1716 ),
1717 (
1718 r#"
1719 version=0
1720 [[shards]]
1721 name="cyclic1"
1722 requires=["cyclic2"]
1723 [[shards]]
1724 name="cyclic2"
1725 requires=["cyclic3"]
1726 [[shards]]
1727 name="cyclic3"
1728 requires=["cyclic4"]
1729 [[shards]]
1730 name="cyclic4"
1731 requires=["cyclic1"]
1732 "#,
1733 Error::CycleInShards(vec![
1734 ShardName::new("cyclic1".to_string()).unwrap(),
1735 ShardName::new("cyclic2".to_string()).unwrap(),
1736 ShardName::new("cyclic3".to_string()).unwrap(),
1737 ShardName::new("cyclic4".to_string()).unwrap(),
1738 ShardName::new("cyclic1".to_string()).unwrap(),
1739 ]),
1740 ),
1741 ];
1742
1743 for (config, expected_error) in pairs {
1744 let config = toml::from_str::<ShapesConfig>(config)
1745 .expect("should be syntactically valid");
1746 let actual_error = StoreShards::from_config(config)
1747 .expect_err("should be an error at this stage");
1748 assert_eq!(expected_error, &actual_error);
1749 }
1750 }
1751 }