##// END OF EJS Templates
rust: Add Repo::dirstate_map and use it in `rhg status`...
Simon Sapin -
r48768:81aedf1f default
parent child Browse files
Show More
@@ -1,160 +1,160 b''
1 // dirstate module
1 // dirstate module
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 crate::dirstate_tree::on_disk::DirstateV2ParseError;
8 use crate::dirstate_tree::on_disk::DirstateV2ParseError;
9 use crate::errors::HgError;
9 use crate::errors::HgError;
10 use crate::revlog::node::NULL_NODE;
10 use crate::revlog::node::NULL_NODE;
11 use crate::revlog::Node;
11 use crate::revlog::Node;
12 use crate::utils::hg_path::{HgPath, HgPathBuf};
12 use crate::utils::hg_path::{HgPath, HgPathBuf};
13 use crate::FastHashMap;
13 use crate::FastHashMap;
14 use bytes_cast::{unaligned, BytesCast};
14 use bytes_cast::{unaligned, BytesCast};
15 use std::convert::TryFrom;
15 use std::convert::TryFrom;
16
16
17 pub mod dirs_multiset;
17 pub mod dirs_multiset;
18 pub mod dirstate_map;
18 pub mod dirstate_map;
19 pub mod parsers;
19 pub mod parsers;
20 pub mod status;
20 pub mod status;
21
21
22 #[derive(Debug, PartialEq, Clone, BytesCast)]
22 #[derive(Debug, PartialEq, Copy, Clone, BytesCast)]
23 #[repr(C)]
23 #[repr(C)]
24 pub struct DirstateParents {
24 pub struct DirstateParents {
25 pub p1: Node,
25 pub p1: Node,
26 pub p2: Node,
26 pub p2: Node,
27 }
27 }
28
28
29 impl DirstateParents {
29 impl DirstateParents {
30 pub const NULL: Self = Self {
30 pub const NULL: Self = Self {
31 p1: NULL_NODE,
31 p1: NULL_NODE,
32 p2: NULL_NODE,
32 p2: NULL_NODE,
33 };
33 };
34 }
34 }
35
35
36 /// The C implementation uses all signed types. This will be an issue
36 /// The C implementation uses all signed types. This will be an issue
37 /// either when 4GB+ source files are commonplace or in 2038, whichever
37 /// either when 4GB+ source files are commonplace or in 2038, whichever
38 /// comes first.
38 /// comes first.
39 #[derive(Debug, PartialEq, Copy, Clone)]
39 #[derive(Debug, PartialEq, Copy, Clone)]
40 pub struct DirstateEntry {
40 pub struct DirstateEntry {
41 pub state: EntryState,
41 pub state: EntryState,
42 pub mode: i32,
42 pub mode: i32,
43 pub mtime: i32,
43 pub mtime: i32,
44 pub size: i32,
44 pub size: i32,
45 }
45 }
46
46
47 impl DirstateEntry {
47 impl DirstateEntry {
48 pub fn is_non_normal(&self) -> bool {
48 pub fn is_non_normal(&self) -> bool {
49 self.state != EntryState::Normal || self.mtime == MTIME_UNSET
49 self.state != EntryState::Normal || self.mtime == MTIME_UNSET
50 }
50 }
51
51
52 pub fn is_from_other_parent(&self) -> bool {
52 pub fn is_from_other_parent(&self) -> bool {
53 self.state == EntryState::Normal && self.size == SIZE_FROM_OTHER_PARENT
53 self.state == EntryState::Normal && self.size == SIZE_FROM_OTHER_PARENT
54 }
54 }
55
55
56 // TODO: other platforms
56 // TODO: other platforms
57 #[cfg(unix)]
57 #[cfg(unix)]
58 pub fn mode_changed(
58 pub fn mode_changed(
59 &self,
59 &self,
60 filesystem_metadata: &std::fs::Metadata,
60 filesystem_metadata: &std::fs::Metadata,
61 ) -> bool {
61 ) -> bool {
62 use std::os::unix::fs::MetadataExt;
62 use std::os::unix::fs::MetadataExt;
63 const EXEC_BIT_MASK: u32 = 0o100;
63 const EXEC_BIT_MASK: u32 = 0o100;
64 let dirstate_exec_bit = (self.mode as u32) & EXEC_BIT_MASK;
64 let dirstate_exec_bit = (self.mode as u32) & EXEC_BIT_MASK;
65 let fs_exec_bit = filesystem_metadata.mode() & EXEC_BIT_MASK;
65 let fs_exec_bit = filesystem_metadata.mode() & EXEC_BIT_MASK;
66 dirstate_exec_bit != fs_exec_bit
66 dirstate_exec_bit != fs_exec_bit
67 }
67 }
68
68
69 /// Returns a `(state, mode, size, mtime)` tuple as for
69 /// Returns a `(state, mode, size, mtime)` tuple as for
70 /// `DirstateMapMethods::debug_iter`.
70 /// `DirstateMapMethods::debug_iter`.
71 pub fn debug_tuple(&self) -> (u8, i32, i32, i32) {
71 pub fn debug_tuple(&self) -> (u8, i32, i32, i32) {
72 (self.state.into(), self.mode, self.size, self.mtime)
72 (self.state.into(), self.mode, self.size, self.mtime)
73 }
73 }
74 }
74 }
75
75
76 #[derive(BytesCast)]
76 #[derive(BytesCast)]
77 #[repr(C)]
77 #[repr(C)]
78 struct RawEntry {
78 struct RawEntry {
79 state: u8,
79 state: u8,
80 mode: unaligned::I32Be,
80 mode: unaligned::I32Be,
81 size: unaligned::I32Be,
81 size: unaligned::I32Be,
82 mtime: unaligned::I32Be,
82 mtime: unaligned::I32Be,
83 length: unaligned::I32Be,
83 length: unaligned::I32Be,
84 }
84 }
85
85
86 pub const V1_RANGEMASK: i32 = 0x7FFFFFFF;
86 pub const V1_RANGEMASK: i32 = 0x7FFFFFFF;
87
87
88 pub const MTIME_UNSET: i32 = -1;
88 pub const MTIME_UNSET: i32 = -1;
89
89
90 /// A `DirstateEntry` with a size of `-2` means that it was merged from the
90 /// A `DirstateEntry` with a size of `-2` means that it was merged from the
91 /// other parent. This allows revert to pick the right status back during a
91 /// other parent. This allows revert to pick the right status back during a
92 /// merge.
92 /// merge.
93 pub const SIZE_FROM_OTHER_PARENT: i32 = -2;
93 pub const SIZE_FROM_OTHER_PARENT: i32 = -2;
94 /// A special value used for internal representation of special case in
94 /// A special value used for internal representation of special case in
95 /// dirstate v1 format.
95 /// dirstate v1 format.
96 pub const SIZE_NON_NORMAL: i32 = -1;
96 pub const SIZE_NON_NORMAL: i32 = -1;
97
97
98 pub type StateMap = FastHashMap<HgPathBuf, DirstateEntry>;
98 pub type StateMap = FastHashMap<HgPathBuf, DirstateEntry>;
99 pub type StateMapIter<'a> = Box<
99 pub type StateMapIter<'a> = Box<
100 dyn Iterator<
100 dyn Iterator<
101 Item = Result<(&'a HgPath, DirstateEntry), DirstateV2ParseError>,
101 Item = Result<(&'a HgPath, DirstateEntry), DirstateV2ParseError>,
102 > + Send
102 > + Send
103 + 'a,
103 + 'a,
104 >;
104 >;
105
105
106 pub type CopyMap = FastHashMap<HgPathBuf, HgPathBuf>;
106 pub type CopyMap = FastHashMap<HgPathBuf, HgPathBuf>;
107 pub type CopyMapIter<'a> = Box<
107 pub type CopyMapIter<'a> = Box<
108 dyn Iterator<Item = Result<(&'a HgPath, &'a HgPath), DirstateV2ParseError>>
108 dyn Iterator<Item = Result<(&'a HgPath, &'a HgPath), DirstateV2ParseError>>
109 + Send
109 + Send
110 + 'a,
110 + 'a,
111 >;
111 >;
112
112
113 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
113 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
114 pub enum EntryState {
114 pub enum EntryState {
115 Normal,
115 Normal,
116 Added,
116 Added,
117 Removed,
117 Removed,
118 Merged,
118 Merged,
119 Unknown,
119 Unknown,
120 }
120 }
121
121
122 impl EntryState {
122 impl EntryState {
123 pub fn is_tracked(self) -> bool {
123 pub fn is_tracked(self) -> bool {
124 use EntryState::*;
124 use EntryState::*;
125 match self {
125 match self {
126 Normal | Added | Merged => true,
126 Normal | Added | Merged => true,
127 Removed | Unknown => false,
127 Removed | Unknown => false,
128 }
128 }
129 }
129 }
130 }
130 }
131
131
132 impl TryFrom<u8> for EntryState {
132 impl TryFrom<u8> for EntryState {
133 type Error = HgError;
133 type Error = HgError;
134
134
135 fn try_from(value: u8) -> Result<Self, Self::Error> {
135 fn try_from(value: u8) -> Result<Self, Self::Error> {
136 match value {
136 match value {
137 b'n' => Ok(EntryState::Normal),
137 b'n' => Ok(EntryState::Normal),
138 b'a' => Ok(EntryState::Added),
138 b'a' => Ok(EntryState::Added),
139 b'r' => Ok(EntryState::Removed),
139 b'r' => Ok(EntryState::Removed),
140 b'm' => Ok(EntryState::Merged),
140 b'm' => Ok(EntryState::Merged),
141 b'?' => Ok(EntryState::Unknown),
141 b'?' => Ok(EntryState::Unknown),
142 _ => Err(HgError::CorruptedRepository(format!(
142 _ => Err(HgError::CorruptedRepository(format!(
143 "Incorrect dirstate entry state {}",
143 "Incorrect dirstate entry state {}",
144 value
144 value
145 ))),
145 ))),
146 }
146 }
147 }
147 }
148 }
148 }
149
149
150 impl Into<u8> for EntryState {
150 impl Into<u8> for EntryState {
151 fn into(self) -> u8 {
151 fn into(self) -> u8 {
152 match self {
152 match self {
153 EntryState::Normal => b'n',
153 EntryState::Normal => b'n',
154 EntryState::Added => b'a',
154 EntryState::Added => b'a',
155 EntryState::Removed => b'r',
155 EntryState::Removed => b'r',
156 EntryState::Merged => b'm',
156 EntryState::Merged => b'm',
157 EntryState::Unknown => b'?',
157 EntryState::Unknown => b'?',
158 }
158 }
159 }
159 }
160 }
160 }
@@ -1,246 +1,339 b''
1 use crate::config::{Config, ConfigError, ConfigParseError};
1 use crate::config::{Config, ConfigError, ConfigParseError};
2 use crate::dirstate::DirstateParents;
3 use crate::dirstate_tree::dirstate_map::DirstateMap;
4 use crate::dirstate_tree::owning::OwningDirstateMap;
2 use crate::errors::HgError;
5 use crate::errors::HgError;
6 use crate::errors::HgResultExt;
3 use crate::exit_codes;
7 use crate::exit_codes;
4 use crate::requirements;
8 use crate::requirements;
5 use crate::utils::files::get_path_from_bytes;
9 use crate::utils::files::get_path_from_bytes;
6 use crate::utils::SliceExt;
10 use crate::utils::SliceExt;
7 use crate::vfs::{is_dir, is_file, Vfs};
11 use crate::vfs::{is_dir, is_file, Vfs};
12 use crate::DirstateError;
13 use std::cell::{Cell, Ref, RefCell, RefMut};
8 use std::collections::HashSet;
14 use std::collections::HashSet;
9 use std::path::{Path, PathBuf};
15 use std::path::{Path, PathBuf};
10
16
11 /// A repository on disk
17 /// A repository on disk
12 pub struct Repo {
18 pub struct Repo {
13 working_directory: PathBuf,
19 working_directory: PathBuf,
14 dot_hg: PathBuf,
20 dot_hg: PathBuf,
15 store: PathBuf,
21 store: PathBuf,
16 requirements: HashSet<String>,
22 requirements: HashSet<String>,
17 config: Config,
23 config: Config,
24 // None means not known/initialized yet
25 dirstate_parents: Cell<Option<DirstateParents>>,
26 dirstate_map: RefCell<Option<OwningDirstateMap>>,
18 }
27 }
19
28
20 #[derive(Debug, derive_more::From)]
29 #[derive(Debug, derive_more::From)]
21 pub enum RepoError {
30 pub enum RepoError {
22 NotFound {
31 NotFound {
23 at: PathBuf,
32 at: PathBuf,
24 },
33 },
25 #[from]
34 #[from]
26 ConfigParseError(ConfigParseError),
35 ConfigParseError(ConfigParseError),
27 #[from]
36 #[from]
28 Other(HgError),
37 Other(HgError),
29 }
38 }
30
39
31 impl From<ConfigError> for RepoError {
40 impl From<ConfigError> for RepoError {
32 fn from(error: ConfigError) -> Self {
41 fn from(error: ConfigError) -> Self {
33 match error {
42 match error {
34 ConfigError::Parse(error) => error.into(),
43 ConfigError::Parse(error) => error.into(),
35 ConfigError::Other(error) => error.into(),
44 ConfigError::Other(error) => error.into(),
36 }
45 }
37 }
46 }
38 }
47 }
39
48
40 impl Repo {
49 impl Repo {
41 /// tries to find nearest repository root in current working directory or
50 /// tries to find nearest repository root in current working directory or
42 /// its ancestors
51 /// its ancestors
43 pub fn find_repo_root() -> Result<PathBuf, RepoError> {
52 pub fn find_repo_root() -> Result<PathBuf, RepoError> {
44 let current_directory = crate::utils::current_dir()?;
53 let current_directory = crate::utils::current_dir()?;
45 // ancestors() is inclusive: it first yields `current_directory`
54 // ancestors() is inclusive: it first yields `current_directory`
46 // as-is.
55 // as-is.
47 for ancestor in current_directory.ancestors() {
56 for ancestor in current_directory.ancestors() {
48 if is_dir(ancestor.join(".hg"))? {
57 if is_dir(ancestor.join(".hg"))? {
49 return Ok(ancestor.to_path_buf());
58 return Ok(ancestor.to_path_buf());
50 }
59 }
51 }
60 }
52 return Err(RepoError::NotFound {
61 return Err(RepoError::NotFound {
53 at: current_directory,
62 at: current_directory,
54 });
63 });
55 }
64 }
56
65
57 /// Find a repository, either at the given path (which must contain a `.hg`
66 /// Find a repository, either at the given path (which must contain a `.hg`
58 /// sub-directory) or by searching the current directory and its
67 /// sub-directory) or by searching the current directory and its
59 /// ancestors.
68 /// ancestors.
60 ///
69 ///
61 /// A method with two very different "modes" like this usually a code smell
70 /// A method with two very different "modes" like this usually a code smell
62 /// to make two methods instead, but in this case an `Option` is what rhg
71 /// to make two methods instead, but in this case an `Option` is what rhg
63 /// sub-commands get from Clap for the `-R` / `--repository` CLI argument.
72 /// sub-commands get from Clap for the `-R` / `--repository` CLI argument.
64 /// Having two methods would just move that `if` to almost all callers.
73 /// Having two methods would just move that `if` to almost all callers.
65 pub fn find(
74 pub fn find(
66 config: &Config,
75 config: &Config,
67 explicit_path: Option<PathBuf>,
76 explicit_path: Option<PathBuf>,
68 ) -> Result<Self, RepoError> {
77 ) -> Result<Self, RepoError> {
69 if let Some(root) = explicit_path {
78 if let Some(root) = explicit_path {
70 if is_dir(root.join(".hg"))? {
79 if is_dir(root.join(".hg"))? {
71 Self::new_at_path(root.to_owned(), config)
80 Self::new_at_path(root.to_owned(), config)
72 } else if is_file(&root)? {
81 } else if is_file(&root)? {
73 Err(HgError::unsupported("bundle repository").into())
82 Err(HgError::unsupported("bundle repository").into())
74 } else {
83 } else {
75 Err(RepoError::NotFound {
84 Err(RepoError::NotFound {
76 at: root.to_owned(),
85 at: root.to_owned(),
77 })
86 })
78 }
87 }
79 } else {
88 } else {
80 let root = Self::find_repo_root()?;
89 let root = Self::find_repo_root()?;
81 Self::new_at_path(root, config)
90 Self::new_at_path(root, config)
82 }
91 }
83 }
92 }
84
93
85 /// To be called after checking that `.hg` is a sub-directory
94 /// To be called after checking that `.hg` is a sub-directory
86 fn new_at_path(
95 fn new_at_path(
87 working_directory: PathBuf,
96 working_directory: PathBuf,
88 config: &Config,
97 config: &Config,
89 ) -> Result<Self, RepoError> {
98 ) -> Result<Self, RepoError> {
90 let dot_hg = working_directory.join(".hg");
99 let dot_hg = working_directory.join(".hg");
91
100
92 let mut repo_config_files = Vec::new();
101 let mut repo_config_files = Vec::new();
93 repo_config_files.push(dot_hg.join("hgrc"));
102 repo_config_files.push(dot_hg.join("hgrc"));
94 repo_config_files.push(dot_hg.join("hgrc-not-shared"));
103 repo_config_files.push(dot_hg.join("hgrc-not-shared"));
95
104
96 let hg_vfs = Vfs { base: &dot_hg };
105 let hg_vfs = Vfs { base: &dot_hg };
97 let mut reqs = requirements::load_if_exists(hg_vfs)?;
106 let mut reqs = requirements::load_if_exists(hg_vfs)?;
98 let relative =
107 let relative =
99 reqs.contains(requirements::RELATIVE_SHARED_REQUIREMENT);
108 reqs.contains(requirements::RELATIVE_SHARED_REQUIREMENT);
100 let shared =
109 let shared =
101 reqs.contains(requirements::SHARED_REQUIREMENT) || relative;
110 reqs.contains(requirements::SHARED_REQUIREMENT) || relative;
102
111
103 // From `mercurial/localrepo.py`:
112 // From `mercurial/localrepo.py`:
104 //
113 //
105 // if .hg/requires contains the sharesafe requirement, it means
114 // if .hg/requires contains the sharesafe requirement, it means
106 // there exists a `.hg/store/requires` too and we should read it
115 // there exists a `.hg/store/requires` too and we should read it
107 // NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement
116 // NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement
108 // is present. We never write SHARESAFE_REQUIREMENT for a repo if store
117 // is present. We never write SHARESAFE_REQUIREMENT for a repo if store
109 // is not present, refer checkrequirementscompat() for that
118 // is not present, refer checkrequirementscompat() for that
110 //
119 //
111 // However, if SHARESAFE_REQUIREMENT is not present, it means that the
120 // However, if SHARESAFE_REQUIREMENT is not present, it means that the
112 // repository was shared the old way. We check the share source
121 // repository was shared the old way. We check the share source
113 // .hg/requires for SHARESAFE_REQUIREMENT to detect whether the
122 // .hg/requires for SHARESAFE_REQUIREMENT to detect whether the
114 // current repository needs to be reshared
123 // current repository needs to be reshared
115 let share_safe = reqs.contains(requirements::SHARESAFE_REQUIREMENT);
124 let share_safe = reqs.contains(requirements::SHARESAFE_REQUIREMENT);
116
125
117 let store_path;
126 let store_path;
118 if !shared {
127 if !shared {
119 store_path = dot_hg.join("store");
128 store_path = dot_hg.join("store");
120 } else {
129 } else {
121 let bytes = hg_vfs.read("sharedpath")?;
130 let bytes = hg_vfs.read("sharedpath")?;
122 let mut shared_path =
131 let mut shared_path =
123 get_path_from_bytes(bytes.trim_end_matches(|b| b == b'\n'))
132 get_path_from_bytes(bytes.trim_end_matches(|b| b == b'\n'))
124 .to_owned();
133 .to_owned();
125 if relative {
134 if relative {
126 shared_path = dot_hg.join(shared_path)
135 shared_path = dot_hg.join(shared_path)
127 }
136 }
128 if !is_dir(&shared_path)? {
137 if !is_dir(&shared_path)? {
129 return Err(HgError::corrupted(format!(
138 return Err(HgError::corrupted(format!(
130 ".hg/sharedpath points to nonexistent directory {}",
139 ".hg/sharedpath points to nonexistent directory {}",
131 shared_path.display()
140 shared_path.display()
132 ))
141 ))
133 .into());
142 .into());
134 }
143 }
135
144
136 store_path = shared_path.join("store");
145 store_path = shared_path.join("store");
137
146
138 let source_is_share_safe =
147 let source_is_share_safe =
139 requirements::load(Vfs { base: &shared_path })?
148 requirements::load(Vfs { base: &shared_path })?
140 .contains(requirements::SHARESAFE_REQUIREMENT);
149 .contains(requirements::SHARESAFE_REQUIREMENT);
141
150
142 if share_safe && !source_is_share_safe {
151 if share_safe && !source_is_share_safe {
143 return Err(match config
152 return Err(match config
144 .get(b"share", b"safe-mismatch.source-not-safe")
153 .get(b"share", b"safe-mismatch.source-not-safe")
145 {
154 {
146 Some(b"abort") | None => HgError::abort(
155 Some(b"abort") | None => HgError::abort(
147 "abort: share source does not support share-safe requirement\n\
156 "abort: share source does not support share-safe requirement\n\
148 (see `hg help config.format.use-share-safe` for more information)",
157 (see `hg help config.format.use-share-safe` for more information)",
149 exit_codes::ABORT,
158 exit_codes::ABORT,
150 ),
159 ),
151 _ => HgError::unsupported("share-safe downgrade"),
160 _ => HgError::unsupported("share-safe downgrade"),
152 }
161 }
153 .into());
162 .into());
154 } else if source_is_share_safe && !share_safe {
163 } else if source_is_share_safe && !share_safe {
155 return Err(
164 return Err(
156 match config.get(b"share", b"safe-mismatch.source-safe") {
165 match config.get(b"share", b"safe-mismatch.source-safe") {
157 Some(b"abort") | None => HgError::abort(
166 Some(b"abort") | None => HgError::abort(
158 "abort: version mismatch: source uses share-safe \
167 "abort: version mismatch: source uses share-safe \
159 functionality while the current share does not\n\
168 functionality while the current share does not\n\
160 (see `hg help config.format.use-share-safe` for more information)",
169 (see `hg help config.format.use-share-safe` for more information)",
161 exit_codes::ABORT,
170 exit_codes::ABORT,
162 ),
171 ),
163 _ => HgError::unsupported("share-safe upgrade"),
172 _ => HgError::unsupported("share-safe upgrade"),
164 }
173 }
165 .into(),
174 .into(),
166 );
175 );
167 }
176 }
168
177
169 if share_safe {
178 if share_safe {
170 repo_config_files.insert(0, shared_path.join("hgrc"))
179 repo_config_files.insert(0, shared_path.join("hgrc"))
171 }
180 }
172 }
181 }
173 if share_safe {
182 if share_safe {
174 reqs.extend(requirements::load(Vfs { base: &store_path })?);
183 reqs.extend(requirements::load(Vfs { base: &store_path })?);
175 }
184 }
176
185
177 let repo_config = if std::env::var_os("HGRCSKIPREPO").is_none() {
186 let repo_config = if std::env::var_os("HGRCSKIPREPO").is_none() {
178 config.combine_with_repo(&repo_config_files)?
187 config.combine_with_repo(&repo_config_files)?
179 } else {
188 } else {
180 config.clone()
189 config.clone()
181 };
190 };
182
191
183 let repo = Self {
192 let repo = Self {
184 requirements: reqs,
193 requirements: reqs,
185 working_directory,
194 working_directory,
186 store: store_path,
195 store: store_path,
187 dot_hg,
196 dot_hg,
188 config: repo_config,
197 config: repo_config,
198 dirstate_parents: Cell::new(None),
199 dirstate_map: RefCell::new(None),
189 };
200 };
190
201
191 requirements::check(&repo)?;
202 requirements::check(&repo)?;
192
203
193 Ok(repo)
204 Ok(repo)
194 }
205 }
195
206
196 pub fn working_directory_path(&self) -> &Path {
207 pub fn working_directory_path(&self) -> &Path {
197 &self.working_directory
208 &self.working_directory
198 }
209 }
199
210
200 pub fn requirements(&self) -> &HashSet<String> {
211 pub fn requirements(&self) -> &HashSet<String> {
201 &self.requirements
212 &self.requirements
202 }
213 }
203
214
204 pub fn config(&self) -> &Config {
215 pub fn config(&self) -> &Config {
205 &self.config
216 &self.config
206 }
217 }
207
218
208 /// For accessing repository files (in `.hg`), except for the store
219 /// For accessing repository files (in `.hg`), except for the store
209 /// (`.hg/store`).
220 /// (`.hg/store`).
210 pub fn hg_vfs(&self) -> Vfs<'_> {
221 pub fn hg_vfs(&self) -> Vfs<'_> {
211 Vfs { base: &self.dot_hg }
222 Vfs { base: &self.dot_hg }
212 }
223 }
213
224
214 /// For accessing repository store files (in `.hg/store`)
225 /// For accessing repository store files (in `.hg/store`)
215 pub fn store_vfs(&self) -> Vfs<'_> {
226 pub fn store_vfs(&self) -> Vfs<'_> {
216 Vfs { base: &self.store }
227 Vfs { base: &self.store }
217 }
228 }
218
229
219 /// For accessing the working copy
230 /// For accessing the working copy
220 pub fn working_directory_vfs(&self) -> Vfs<'_> {
231 pub fn working_directory_vfs(&self) -> Vfs<'_> {
221 Vfs {
232 Vfs {
222 base: &self.working_directory,
233 base: &self.working_directory,
223 }
234 }
224 }
235 }
225
236
226 pub fn has_dirstate_v2(&self) -> bool {
237 pub fn has_dirstate_v2(&self) -> bool {
227 self.requirements
238 self.requirements
228 .contains(requirements::DIRSTATE_V2_REQUIREMENT)
239 .contains(requirements::DIRSTATE_V2_REQUIREMENT)
229 }
240 }
230
241
231 pub fn dirstate_parents(
242 fn dirstate_file_contents(&self) -> Result<Vec<u8>, HgError> {
232 &self,
243 Ok(self
233 ) -> Result<crate::dirstate::DirstateParents, HgError> {
244 .hg_vfs()
234 let dirstate = self.hg_vfs().mmap_open("dirstate")?;
245 .read("dirstate")
235 if dirstate.is_empty() {
246 .io_not_found_as_none()?
236 return Ok(crate::dirstate::DirstateParents::NULL);
247 .unwrap_or(Vec::new()))
237 }
248 }
238 let parents = if self.has_dirstate_v2() {
249
250 pub fn dirstate_parents(&self) -> Result<DirstateParents, HgError> {
251 if let Some(parents) = self.dirstate_parents.get() {
252 return Ok(parents);
253 }
254 let dirstate = self.dirstate_file_contents()?;
255 let parents = if dirstate.is_empty() {
256 DirstateParents::NULL
257 } else if self.has_dirstate_v2() {
239 crate::dirstate_tree::on_disk::read_docket(&dirstate)?.parents()
258 crate::dirstate_tree::on_disk::read_docket(&dirstate)?.parents()
240 } else {
259 } else {
241 crate::dirstate::parsers::parse_dirstate_parents(&dirstate)?
260 crate::dirstate::parsers::parse_dirstate_parents(&dirstate)?
242 .clone()
261 .clone()
243 };
262 };
263 self.dirstate_parents.set(Some(parents));
244 Ok(parents)
264 Ok(parents)
245 }
265 }
266
267 fn new_dirstate_map(&self) -> Result<OwningDirstateMap, DirstateError> {
268 let dirstate_file_contents = self.dirstate_file_contents()?;
269 if dirstate_file_contents.is_empty() {
270 self.dirstate_parents.set(Some(DirstateParents::NULL));
271 Ok(OwningDirstateMap::new_empty(Vec::new()))
272 } else if self.has_dirstate_v2() {
273 let docket = crate::dirstate_tree::on_disk::read_docket(
274 &dirstate_file_contents,
275 )?;
276 self.dirstate_parents.set(Some(docket.parents()));
277 let data_size = docket.data_size();
278 let metadata = docket.tree_metadata();
279 let mut map = if let Some(data_mmap) = self
280 .hg_vfs()
281 .mmap_open(docket.data_filename())
282 .io_not_found_as_none()?
283 {
284 OwningDirstateMap::new_empty(MmapWrapper(data_mmap))
285 } else {
286 OwningDirstateMap::new_empty(Vec::new())
287 };
288 let (on_disk, placeholder) = map.get_mut_pair();
289 *placeholder = DirstateMap::new_v2(on_disk, data_size, metadata)?;
290 Ok(map)
291 } else {
292 let mut map = OwningDirstateMap::new_empty(dirstate_file_contents);
293 let (on_disk, placeholder) = map.get_mut_pair();
294 let (inner, parents) = DirstateMap::new_v1(on_disk)?;
295 self.dirstate_parents
296 .set(Some(parents.unwrap_or(DirstateParents::NULL)));
297 *placeholder = inner;
298 Ok(map)
246 }
299 }
300 }
301
302 pub fn dirstate_map(
303 &self,
304 ) -> Result<Ref<OwningDirstateMap>, DirstateError> {
305 let mut borrowed = self.dirstate_map.borrow();
306 if borrowed.is_none() {
307 drop(borrowed);
308 // Only use `borrow_mut` if it is really needed to avoid panic in
309 // case there is another outstanding borrow but mutation is not
310 // needed.
311 *self.dirstate_map.borrow_mut() = Some(self.new_dirstate_map()?);
312 borrowed = self.dirstate_map.borrow()
313 }
314 Ok(Ref::map(borrowed, |option| option.as_ref().unwrap()))
315 }
316
317 pub fn dirstate_map_mut(
318 &self,
319 ) -> Result<RefMut<OwningDirstateMap>, DirstateError> {
320 let mut borrowed = self.dirstate_map.borrow_mut();
321 if borrowed.is_none() {
322 *borrowed = Some(self.new_dirstate_map()?);
323 }
324 Ok(RefMut::map(borrowed, |option| option.as_mut().unwrap()))
325 }
326 }
327
328 // TODO: remove this when https://github.com/RazrFalcon/memmap2-rs/pull/22 is on crates.io
329 struct MmapWrapper(memmap2::Mmap);
330
331 impl std::ops::Deref for MmapWrapper {
332 type Target = [u8];
333
334 fn deref(&self) -> &[u8] {
335 self.0.deref()
336 }
337 }
338
339 unsafe impl stable_deref_trait::StableDeref for MmapWrapper {}
@@ -1,347 +1,305 b''
1 // status.rs
1 // status.rs
2 //
2 //
3 // Copyright 2020, Georges Racinet <georges.racinets@octobus.net>
3 // Copyright 2020, Georges Racinet <georges.racinets@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 crate::error::CommandError;
8 use crate::error::CommandError;
9 use crate::ui::Ui;
9 use crate::ui::Ui;
10 use clap::{Arg, SubCommand};
10 use clap::{Arg, SubCommand};
11 use hg;
11 use hg;
12 use hg::dirstate_tree::dirstate_map::DirstateMap;
12 use hg::dirstate_tree::dispatch::DirstateMapMethods;
13 use hg::dirstate_tree::on_disk;
14 use hg::errors::HgResultExt;
15 use hg::errors::IoResultExt;
13 use hg::errors::IoResultExt;
16 use hg::matchers::AlwaysMatcher;
14 use hg::matchers::AlwaysMatcher;
17 use hg::operations::cat;
15 use hg::operations::cat;
18 use hg::repo::Repo;
16 use hg::repo::Repo;
19 use hg::revlog::node::Node;
17 use hg::revlog::node::Node;
20 use hg::utils::hg_path::{hg_path_to_os_string, HgPath};
18 use hg::utils::hg_path::{hg_path_to_os_string, HgPath};
21 use hg::StatusError;
19 use hg::StatusError;
22 use hg::{HgPathCow, StatusOptions};
20 use hg::{HgPathCow, StatusOptions};
23 use log::{info, warn};
21 use log::{info, warn};
24 use std::convert::TryInto;
22 use std::convert::TryInto;
25 use std::fs;
23 use std::fs;
26 use std::io::BufReader;
24 use std::io::BufReader;
27 use std::io::Read;
25 use std::io::Read;
28
26
29 pub const HELP_TEXT: &str = "
27 pub const HELP_TEXT: &str = "
30 Show changed files in the working directory
28 Show changed files in the working directory
31
29
32 This is a pure Rust version of `hg status`.
30 This is a pure Rust version of `hg status`.
33
31
34 Some options might be missing, check the list below.
32 Some options might be missing, check the list below.
35 ";
33 ";
36
34
37 pub fn args() -> clap::App<'static, 'static> {
35 pub fn args() -> clap::App<'static, 'static> {
38 SubCommand::with_name("status")
36 SubCommand::with_name("status")
39 .alias("st")
37 .alias("st")
40 .about(HELP_TEXT)
38 .about(HELP_TEXT)
41 .arg(
39 .arg(
42 Arg::with_name("all")
40 Arg::with_name("all")
43 .help("show status of all files")
41 .help("show status of all files")
44 .short("-A")
42 .short("-A")
45 .long("--all"),
43 .long("--all"),
46 )
44 )
47 .arg(
45 .arg(
48 Arg::with_name("modified")
46 Arg::with_name("modified")
49 .help("show only modified files")
47 .help("show only modified files")
50 .short("-m")
48 .short("-m")
51 .long("--modified"),
49 .long("--modified"),
52 )
50 )
53 .arg(
51 .arg(
54 Arg::with_name("added")
52 Arg::with_name("added")
55 .help("show only added files")
53 .help("show only added files")
56 .short("-a")
54 .short("-a")
57 .long("--added"),
55 .long("--added"),
58 )
56 )
59 .arg(
57 .arg(
60 Arg::with_name("removed")
58 Arg::with_name("removed")
61 .help("show only removed files")
59 .help("show only removed files")
62 .short("-r")
60 .short("-r")
63 .long("--removed"),
61 .long("--removed"),
64 )
62 )
65 .arg(
63 .arg(
66 Arg::with_name("clean")
64 Arg::with_name("clean")
67 .help("show only clean files")
65 .help("show only clean files")
68 .short("-c")
66 .short("-c")
69 .long("--clean"),
67 .long("--clean"),
70 )
68 )
71 .arg(
69 .arg(
72 Arg::with_name("deleted")
70 Arg::with_name("deleted")
73 .help("show only deleted files")
71 .help("show only deleted files")
74 .short("-d")
72 .short("-d")
75 .long("--deleted"),
73 .long("--deleted"),
76 )
74 )
77 .arg(
75 .arg(
78 Arg::with_name("unknown")
76 Arg::with_name("unknown")
79 .help("show only unknown (not tracked) files")
77 .help("show only unknown (not tracked) files")
80 .short("-u")
78 .short("-u")
81 .long("--unknown"),
79 .long("--unknown"),
82 )
80 )
83 .arg(
81 .arg(
84 Arg::with_name("ignored")
82 Arg::with_name("ignored")
85 .help("show only ignored files")
83 .help("show only ignored files")
86 .short("-i")
84 .short("-i")
87 .long("--ignored"),
85 .long("--ignored"),
88 )
86 )
89 }
87 }
90
88
91 /// Pure data type allowing the caller to specify file states to display
89 /// Pure data type allowing the caller to specify file states to display
92 #[derive(Copy, Clone, Debug)]
90 #[derive(Copy, Clone, Debug)]
93 pub struct DisplayStates {
91 pub struct DisplayStates {
94 pub modified: bool,
92 pub modified: bool,
95 pub added: bool,
93 pub added: bool,
96 pub removed: bool,
94 pub removed: bool,
97 pub clean: bool,
95 pub clean: bool,
98 pub deleted: bool,
96 pub deleted: bool,
99 pub unknown: bool,
97 pub unknown: bool,
100 pub ignored: bool,
98 pub ignored: bool,
101 }
99 }
102
100
103 pub const DEFAULT_DISPLAY_STATES: DisplayStates = DisplayStates {
101 pub const DEFAULT_DISPLAY_STATES: DisplayStates = DisplayStates {
104 modified: true,
102 modified: true,
105 added: true,
103 added: true,
106 removed: true,
104 removed: true,
107 clean: false,
105 clean: false,
108 deleted: true,
106 deleted: true,
109 unknown: true,
107 unknown: true,
110 ignored: false,
108 ignored: false,
111 };
109 };
112
110
113 pub const ALL_DISPLAY_STATES: DisplayStates = DisplayStates {
111 pub const ALL_DISPLAY_STATES: DisplayStates = DisplayStates {
114 modified: true,
112 modified: true,
115 added: true,
113 added: true,
116 removed: true,
114 removed: true,
117 clean: true,
115 clean: true,
118 deleted: true,
116 deleted: true,
119 unknown: true,
117 unknown: true,
120 ignored: true,
118 ignored: true,
121 };
119 };
122
120
123 impl DisplayStates {
121 impl DisplayStates {
124 pub fn is_empty(&self) -> bool {
122 pub fn is_empty(&self) -> bool {
125 !(self.modified
123 !(self.modified
126 || self.added
124 || self.added
127 || self.removed
125 || self.removed
128 || self.clean
126 || self.clean
129 || self.deleted
127 || self.deleted
130 || self.unknown
128 || self.unknown
131 || self.ignored)
129 || self.ignored)
132 }
130 }
133 }
131 }
134
132
135 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
133 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
136 let status_enabled_default = false;
134 let status_enabled_default = false;
137 let status_enabled = invocation.config.get_option(b"rhg", b"status")?;
135 let status_enabled = invocation.config.get_option(b"rhg", b"status")?;
138 if !status_enabled.unwrap_or(status_enabled_default) {
136 if !status_enabled.unwrap_or(status_enabled_default) {
139 return Err(CommandError::unsupported(
137 return Err(CommandError::unsupported(
140 "status is experimental in rhg (enable it with 'rhg.status = true' \
138 "status is experimental in rhg (enable it with 'rhg.status = true' \
141 or enable fallback with 'rhg.on-unsupported = fallback')"
139 or enable fallback with 'rhg.on-unsupported = fallback')"
142 ));
140 ));
143 }
141 }
144
142
145 let ui = invocation.ui;
143 let ui = invocation.ui;
146 let args = invocation.subcommand_args;
144 let args = invocation.subcommand_args;
147 let display_states = if args.is_present("all") {
145 let display_states = if args.is_present("all") {
148 // TODO when implementing `--quiet`: it excludes clean files
146 // TODO when implementing `--quiet`: it excludes clean files
149 // from `--all`
147 // from `--all`
150 ALL_DISPLAY_STATES
148 ALL_DISPLAY_STATES
151 } else {
149 } else {
152 let requested = DisplayStates {
150 let requested = DisplayStates {
153 modified: args.is_present("modified"),
151 modified: args.is_present("modified"),
154 added: args.is_present("added"),
152 added: args.is_present("added"),
155 removed: args.is_present("removed"),
153 removed: args.is_present("removed"),
156 clean: args.is_present("clean"),
154 clean: args.is_present("clean"),
157 deleted: args.is_present("deleted"),
155 deleted: args.is_present("deleted"),
158 unknown: args.is_present("unknown"),
156 unknown: args.is_present("unknown"),
159 ignored: args.is_present("ignored"),
157 ignored: args.is_present("ignored"),
160 };
158 };
161 if requested.is_empty() {
159 if requested.is_empty() {
162 DEFAULT_DISPLAY_STATES
160 DEFAULT_DISPLAY_STATES
163 } else {
161 } else {
164 requested
162 requested
165 }
163 }
166 };
164 };
167
165
168 let repo = invocation.repo?;
166 let repo = invocation.repo?;
169 let dirstate_data_mmap;
167 let mut dmap = repo.dirstate_map_mut()?;
170 let (mut dmap, parents) = if repo.has_dirstate_v2() {
171 let docket_data =
172 repo.hg_vfs().read("dirstate").io_not_found_as_none()?;
173 let parents;
174 let dirstate_data;
175 let data_size;
176 let docket;
177 let tree_metadata;
178 if let Some(docket_data) = &docket_data {
179 docket = on_disk::read_docket(docket_data)?;
180 tree_metadata = docket.tree_metadata();
181 parents = Some(docket.parents());
182 data_size = docket.data_size();
183 dirstate_data_mmap = repo
184 .hg_vfs()
185 .mmap_open(docket.data_filename())
186 .io_not_found_as_none()?;
187 dirstate_data = dirstate_data_mmap.as_deref().unwrap_or(b"");
188 } else {
189 parents = None;
190 tree_metadata = b"";
191 data_size = 0;
192 dirstate_data = b"";
193 }
194 let dmap =
195 DirstateMap::new_v2(dirstate_data, data_size, tree_metadata)?;
196 (dmap, parents)
197 } else {
198 dirstate_data_mmap =
199 repo.hg_vfs().mmap_open("dirstate").io_not_found_as_none()?;
200 let dirstate_data = dirstate_data_mmap.as_deref().unwrap_or(b"");
201 DirstateMap::new_v1(dirstate_data)?
202 };
203
168
204 let options = StatusOptions {
169 let options = StatusOptions {
205 // TODO should be provided by the dirstate parsing and
170 // TODO should be provided by the dirstate parsing and
206 // hence be stored on dmap. Using a value that assumes we aren't
171 // hence be stored on dmap. Using a value that assumes we aren't
207 // below the time resolution granularity of the FS and the
172 // below the time resolution granularity of the FS and the
208 // dirstate.
173 // dirstate.
209 last_normal_time: 0,
174 last_normal_time: 0,
210 // we're currently supporting file systems with exec flags only
175 // we're currently supporting file systems with exec flags only
211 // anyway
176 // anyway
212 check_exec: true,
177 check_exec: true,
213 list_clean: display_states.clean,
178 list_clean: display_states.clean,
214 list_unknown: display_states.unknown,
179 list_unknown: display_states.unknown,
215 list_ignored: display_states.ignored,
180 list_ignored: display_states.ignored,
216 collect_traversed_dirs: false,
181 collect_traversed_dirs: false,
217 };
182 };
218 let ignore_file = repo.working_directory_vfs().join(".hgignore"); // TODO hardcoded
183 let ignore_file = repo.working_directory_vfs().join(".hgignore"); // TODO hardcoded
219 let (mut ds_status, pattern_warnings) = hg::dirstate_tree::status::status(
184 let (mut ds_status, pattern_warnings) = dmap.status(
220 &mut dmap,
221 &AlwaysMatcher,
185 &AlwaysMatcher,
222 repo.working_directory_path().to_owned(),
186 repo.working_directory_path().to_owned(),
223 vec![ignore_file],
187 vec![ignore_file],
224 options,
188 options,
225 )?;
189 )?;
226 if !pattern_warnings.is_empty() {
190 if !pattern_warnings.is_empty() {
227 warn!("Pattern warnings: {:?}", &pattern_warnings);
191 warn!("Pattern warnings: {:?}", &pattern_warnings);
228 }
192 }
229
193
230 if !ds_status.bad.is_empty() {
194 if !ds_status.bad.is_empty() {
231 warn!("Bad matches {:?}", &(ds_status.bad))
195 warn!("Bad matches {:?}", &(ds_status.bad))
232 }
196 }
233 if !ds_status.unsure.is_empty() {
197 if !ds_status.unsure.is_empty() {
234 info!(
198 info!(
235 "Files to be rechecked by retrieval from filelog: {:?}",
199 "Files to be rechecked by retrieval from filelog: {:?}",
236 &ds_status.unsure
200 &ds_status.unsure
237 );
201 );
238 }
202 }
239 if !ds_status.unsure.is_empty()
203 if !ds_status.unsure.is_empty()
240 && (display_states.modified || display_states.clean)
204 && (display_states.modified || display_states.clean)
241 {
205 {
242 let p1: Node = parents
206 let p1: Node = repo.dirstate_parents()?.p1.into();
243 .expect(
244 "Dirstate with no parents should not list any file to
245 be rechecked for modifications",
246 )
247 .p1
248 .into();
249 let p1_hex = format!("{:x}", p1);
207 let p1_hex = format!("{:x}", p1);
250 for to_check in ds_status.unsure {
208 for to_check in ds_status.unsure {
251 if cat_file_is_modified(repo, &to_check, &p1_hex)? {
209 if cat_file_is_modified(repo, &to_check, &p1_hex)? {
252 if display_states.modified {
210 if display_states.modified {
253 ds_status.modified.push(to_check);
211 ds_status.modified.push(to_check);
254 }
212 }
255 } else {
213 } else {
256 if display_states.clean {
214 if display_states.clean {
257 ds_status.clean.push(to_check);
215 ds_status.clean.push(to_check);
258 }
216 }
259 }
217 }
260 }
218 }
261 }
219 }
262 if display_states.modified {
220 if display_states.modified {
263 display_status_paths(ui, &mut ds_status.modified, b"M")?;
221 display_status_paths(ui, &mut ds_status.modified, b"M")?;
264 }
222 }
265 if display_states.added {
223 if display_states.added {
266 display_status_paths(ui, &mut ds_status.added, b"A")?;
224 display_status_paths(ui, &mut ds_status.added, b"A")?;
267 }
225 }
268 if display_states.removed {
226 if display_states.removed {
269 display_status_paths(ui, &mut ds_status.removed, b"R")?;
227 display_status_paths(ui, &mut ds_status.removed, b"R")?;
270 }
228 }
271 if display_states.deleted {
229 if display_states.deleted {
272 display_status_paths(ui, &mut ds_status.deleted, b"!")?;
230 display_status_paths(ui, &mut ds_status.deleted, b"!")?;
273 }
231 }
274 if display_states.unknown {
232 if display_states.unknown {
275 display_status_paths(ui, &mut ds_status.unknown, b"?")?;
233 display_status_paths(ui, &mut ds_status.unknown, b"?")?;
276 }
234 }
277 if display_states.ignored {
235 if display_states.ignored {
278 display_status_paths(ui, &mut ds_status.ignored, b"I")?;
236 display_status_paths(ui, &mut ds_status.ignored, b"I")?;
279 }
237 }
280 if display_states.clean {
238 if display_states.clean {
281 display_status_paths(ui, &mut ds_status.clean, b"C")?;
239 display_status_paths(ui, &mut ds_status.clean, b"C")?;
282 }
240 }
283 Ok(())
241 Ok(())
284 }
242 }
285
243
286 // Probably more elegant to use a Deref or Borrow trait rather than
244 // Probably more elegant to use a Deref or Borrow trait rather than
287 // harcode HgPathBuf, but probably not really useful at this point
245 // harcode HgPathBuf, but probably not really useful at this point
288 fn display_status_paths(
246 fn display_status_paths(
289 ui: &Ui,
247 ui: &Ui,
290 paths: &mut [HgPathCow],
248 paths: &mut [HgPathCow],
291 status_prefix: &[u8],
249 status_prefix: &[u8],
292 ) -> Result<(), CommandError> {
250 ) -> Result<(), CommandError> {
293 paths.sort_unstable();
251 paths.sort_unstable();
294 for path in paths {
252 for path in paths {
295 // Same TODO as in commands::root
253 // Same TODO as in commands::root
296 let bytes: &[u8] = path.as_bytes();
254 let bytes: &[u8] = path.as_bytes();
297 // TODO optim, probably lots of unneeded copies here, especially
255 // TODO optim, probably lots of unneeded copies here, especially
298 // if out stream is buffered
256 // if out stream is buffered
299 ui.write_stdout(&[status_prefix, b" ", bytes, b"\n"].concat())?;
257 ui.write_stdout(&[status_prefix, b" ", bytes, b"\n"].concat())?;
300 }
258 }
301 Ok(())
259 Ok(())
302 }
260 }
303
261
304 /// Check if a file is modified by comparing actual repo store and file system.
262 /// Check if a file is modified by comparing actual repo store and file system.
305 ///
263 ///
306 /// This meant to be used for those that the dirstate cannot resolve, due
264 /// This meant to be used for those that the dirstate cannot resolve, due
307 /// to time resolution limits.
265 /// to time resolution limits.
308 ///
266 ///
309 /// TODO: detect permission bits and similar metadata modifications
267 /// TODO: detect permission bits and similar metadata modifications
310 fn cat_file_is_modified(
268 fn cat_file_is_modified(
311 repo: &Repo,
269 repo: &Repo,
312 hg_path: &HgPath,
270 hg_path: &HgPath,
313 rev: &str,
271 rev: &str,
314 ) -> Result<bool, CommandError> {
272 ) -> Result<bool, CommandError> {
315 // TODO CatRev expects &[HgPathBuf], something like
273 // TODO CatRev expects &[HgPathBuf], something like
316 // &[impl Deref<HgPath>] would be nicer and should avoid the copy
274 // &[impl Deref<HgPath>] would be nicer and should avoid the copy
317 let path_bufs = [hg_path.into()];
275 let path_bufs = [hg_path.into()];
318 // TODO IIUC CatRev returns a simple Vec<u8> for all files
276 // TODO IIUC CatRev returns a simple Vec<u8> for all files
319 // being able to tell them apart as (path, bytes) would be nicer
277 // being able to tell them apart as (path, bytes) would be nicer
320 // and OPTIM would allow manifest resolution just once.
278 // and OPTIM would allow manifest resolution just once.
321 let output = cat(repo, rev, &path_bufs).map_err(|e| (e, rev))?;
279 let output = cat(repo, rev, &path_bufs).map_err(|e| (e, rev))?;
322
280
323 let fs_path = repo
281 let fs_path = repo
324 .working_directory_vfs()
282 .working_directory_vfs()
325 .join(hg_path_to_os_string(hg_path).expect("HgPath conversion"));
283 .join(hg_path_to_os_string(hg_path).expect("HgPath conversion"));
326 let hg_data_len: u64 = match output.concatenated.len().try_into() {
284 let hg_data_len: u64 = match output.concatenated.len().try_into() {
327 Ok(v) => v,
285 Ok(v) => v,
328 Err(_) => {
286 Err(_) => {
329 // conversion of data length to u64 failed,
287 // conversion of data length to u64 failed,
330 // good luck for any file to have this content
288 // good luck for any file to have this content
331 return Ok(true);
289 return Ok(true);
332 }
290 }
333 };
291 };
334 let fobj = fs::File::open(&fs_path).when_reading_file(&fs_path)?;
292 let fobj = fs::File::open(&fs_path).when_reading_file(&fs_path)?;
335 if fobj.metadata().map_err(|e| StatusError::from(e))?.len() != hg_data_len
293 if fobj.metadata().map_err(|e| StatusError::from(e))?.len() != hg_data_len
336 {
294 {
337 return Ok(true);
295 return Ok(true);
338 }
296 }
339 for (fs_byte, hg_byte) in
297 for (fs_byte, hg_byte) in
340 BufReader::new(fobj).bytes().zip(output.concatenated)
298 BufReader::new(fobj).bytes().zip(output.concatenated)
341 {
299 {
342 if fs_byte.map_err(|e| StatusError::from(e))? != hg_byte {
300 if fs_byte.map_err(|e| StatusError::from(e))? != hg_byte {
343 return Ok(true);
301 return Ok(true);
344 }
302 }
345 }
303 }
346 Ok(false)
304 Ok(false)
347 }
305 }
General Comments 0
You need to be logged in to leave comments. Login now