jujutsu_lib/
repo_path.rs

1// Copyright 2020 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::{Debug, Error, Formatter};
16use std::path::{Component, Path, PathBuf};
17
18use itertools::Itertools;
19use thiserror::Error;
20
21use crate::file_util;
22
23content_hash! {
24    #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
25    pub struct RepoPathComponent {
26        value: String,
27    }
28}
29
30impl RepoPathComponent {
31    pub fn as_str(&self) -> &str {
32        &self.value
33    }
34
35    pub fn string(&self) -> String {
36        self.value.to_string()
37    }
38}
39
40impl From<&str> for RepoPathComponent {
41    fn from(value: &str) -> Self {
42        RepoPathComponent::from(value.to_owned())
43    }
44}
45
46impl From<String> for RepoPathComponent {
47    fn from(value: String) -> Self {
48        assert!(!value.contains('/'));
49        RepoPathComponent { value }
50    }
51}
52
53#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct RepoPath {
55    components: Vec<RepoPathComponent>,
56}
57
58impl Debug for RepoPath {
59    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
60        f.write_fmt(format_args!("{:?}", &self.to_internal_file_string()))
61    }
62}
63
64impl RepoPath {
65    pub fn root() -> Self {
66        RepoPath { components: vec![] }
67    }
68
69    pub fn from_internal_string(value: &str) -> Self {
70        assert!(!value.ends_with('/'));
71        if value.is_empty() {
72            RepoPath::root()
73        } else {
74            let components = value
75                .split('/')
76                .map(|value| RepoPathComponent {
77                    value: value.to_string(),
78                })
79                .collect();
80            RepoPath { components }
81        }
82    }
83
84    pub fn from_components(components: Vec<RepoPathComponent>) -> Self {
85        RepoPath { components }
86    }
87
88    /// Parses an `input` path into a `RepoPath` relative to `base`.
89    ///
90    /// The `cwd` and `base` paths are supposed to be absolute and normalized in
91    /// the same manner. The `input` path may be either relative to `cwd` or
92    /// absolute.
93    pub fn parse_fs_path(cwd: &Path, base: &Path, input: &str) -> Result<Self, FsPathParseError> {
94        let abs_input_path = file_util::normalize_path(&cwd.join(input));
95        let repo_relative_path = file_util::relative_path(base, &abs_input_path);
96        if repo_relative_path == Path::new(".") {
97            return Ok(RepoPath::root());
98        }
99        let components = repo_relative_path
100            .components()
101            .map(|c| match c {
102                Component::Normal(a) => Ok(RepoPathComponent::from(a.to_str().unwrap())),
103                _ => Err(FsPathParseError::InputNotInRepo(input.to_string())),
104            })
105            .try_collect()?;
106        Ok(RepoPath::from_components(components))
107    }
108
109    /// The full string form used internally, not for presenting to users (where
110    /// we may want to use the platform's separator). This format includes a
111    /// trailing slash, unless this path represents the root directory. That
112    /// way it can be concatenated with a basename and produce a valid path.
113    pub fn to_internal_dir_string(&self) -> String {
114        let mut result = String::new();
115        for component in &self.components {
116            result.push_str(component.as_str());
117            result.push('/');
118        }
119        result
120    }
121
122    /// The full string form used internally, not for presenting to users (where
123    /// we may want to use the platform's separator).
124    pub fn to_internal_file_string(&self) -> String {
125        let strings = self
126            .components
127            .iter()
128            .map(|component| component.value.clone())
129            .collect_vec();
130        strings.join("/")
131    }
132
133    pub fn to_fs_path(&self, base: &Path) -> PathBuf {
134        let mut result = base.to_owned();
135        for dir in &self.components {
136            result = result.join(&dir.value);
137        }
138        result
139    }
140
141    pub fn is_root(&self) -> bool {
142        self.components.is_empty()
143    }
144
145    pub fn contains(&self, other: &RepoPath) -> bool {
146        other.components.starts_with(&self.components)
147    }
148
149    pub fn parent(&self) -> Option<RepoPath> {
150        if self.is_root() {
151            None
152        } else {
153            Some(RepoPath {
154                components: self.components[0..self.components.len() - 1].to_vec(),
155            })
156        }
157    }
158
159    pub fn split(&self) -> Option<(RepoPath, &RepoPathComponent)> {
160        if self.is_root() {
161            None
162        } else {
163            Some((self.parent().unwrap(), self.components.last().unwrap()))
164        }
165    }
166
167    pub fn components(&self) -> &Vec<RepoPathComponent> {
168        &self.components
169    }
170}
171
172pub trait RepoPathJoin<T> {
173    type Result;
174
175    fn join(&self, entry: &T) -> Self::Result;
176}
177
178impl RepoPathJoin<RepoPathComponent> for RepoPath {
179    type Result = RepoPath;
180
181    fn join(&self, entry: &RepoPathComponent) -> RepoPath {
182        let mut components: Vec<RepoPathComponent> = self.components.clone();
183        components.push(entry.clone());
184        RepoPath { components }
185    }
186}
187
188#[derive(Clone, Debug, Eq, Error, PartialEq)]
189pub enum FsPathParseError {
190    #[error(r#"Path "{0}" is not in the repo"#)]
191    InputNotInRepo(String),
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn test_is_root() {
200        assert!(RepoPath::root().is_root());
201        assert!(RepoPath::from_internal_string("").is_root());
202        assert!(!RepoPath::from_internal_string("foo").is_root());
203    }
204
205    #[test]
206    fn test_to_internal_string() {
207        assert_eq!(RepoPath::root().to_internal_file_string(), "");
208        assert_eq!(
209            RepoPath::from_internal_string("dir").to_internal_file_string(),
210            "dir"
211        );
212        assert_eq!(
213            RepoPath::from_internal_string("dir/file").to_internal_file_string(),
214            "dir/file"
215        );
216    }
217
218    #[test]
219    fn test_order() {
220        assert!(RepoPath::root() < RepoPath::from_internal_string("dir"));
221        assert!(RepoPath::from_internal_string("dir") < RepoPath::from_internal_string("dirx"));
222        // '#' < '/'
223        assert!(RepoPath::from_internal_string("dir") < RepoPath::from_internal_string("dir#"));
224        assert!(RepoPath::from_internal_string("dir") < RepoPath::from_internal_string("dir/sub"));
225
226        assert!(RepoPath::from_internal_string("abc") < RepoPath::from_internal_string("dir/file"));
227        assert!(RepoPath::from_internal_string("dir") < RepoPath::from_internal_string("dir/file"));
228        assert!(RepoPath::from_internal_string("dis") > RepoPath::from_internal_string("dir/file"));
229        assert!(RepoPath::from_internal_string("xyz") > RepoPath::from_internal_string("dir/file"));
230        assert!(
231            RepoPath::from_internal_string("dir1/xyz") < RepoPath::from_internal_string("dir2/abc")
232        );
233    }
234
235    #[test]
236    fn test_join() {
237        let root = RepoPath::root();
238        let dir = root.join(&RepoPathComponent::from("dir"));
239        assert_eq!(dir, RepoPath::from_internal_string("dir"));
240        let subdir = dir.join(&RepoPathComponent::from("subdir"));
241        assert_eq!(subdir, RepoPath::from_internal_string("dir/subdir"));
242        assert_eq!(
243            subdir.join(&RepoPathComponent::from("file")),
244            RepoPath::from_internal_string("dir/subdir/file")
245        );
246    }
247
248    #[test]
249    fn test_parent() {
250        let root = RepoPath::root();
251        let dir_component = RepoPathComponent::from("dir");
252        let subdir_component = RepoPathComponent::from("subdir");
253
254        let dir = root.join(&dir_component);
255        let subdir = dir.join(&subdir_component);
256
257        assert_eq!(root.parent(), None);
258        assert_eq!(dir.parent(), Some(root));
259        assert_eq!(subdir.parent(), Some(dir));
260    }
261
262    #[test]
263    fn test_split() {
264        let root = RepoPath::root();
265        let dir_component = RepoPathComponent::from("dir");
266        let file_component = RepoPathComponent::from("file");
267
268        let dir = root.join(&dir_component);
269        let file = dir.join(&file_component);
270
271        assert_eq!(root.split(), None);
272        assert_eq!(dir.split(), Some((root, &dir_component)));
273        assert_eq!(file.split(), Some((dir, &file_component)));
274    }
275
276    #[test]
277    fn test_components() {
278        assert_eq!(RepoPath::root().components(), &vec![]);
279        assert_eq!(
280            RepoPath::from_internal_string("dir").components(),
281            &vec![RepoPathComponent::from("dir")]
282        );
283        assert_eq!(
284            RepoPath::from_internal_string("dir/subdir").components(),
285            &vec![
286                RepoPathComponent::from("dir"),
287                RepoPathComponent::from("subdir")
288            ]
289        );
290    }
291
292    #[test]
293    fn test_to_fs_path() {
294        assert_eq!(
295            RepoPath::from_internal_string("").to_fs_path(Path::new("base/dir")),
296            Path::new("base/dir")
297        );
298        assert_eq!(
299            RepoPath::from_internal_string("").to_fs_path(Path::new("")),
300            Path::new("")
301        );
302        assert_eq!(
303            RepoPath::from_internal_string("file").to_fs_path(Path::new("base/dir")),
304            Path::new("base/dir/file")
305        );
306        assert_eq!(
307            RepoPath::from_internal_string("some/deep/dir/file").to_fs_path(Path::new("base/dir")),
308            Path::new("base/dir/some/deep/dir/file")
309        );
310        assert_eq!(
311            RepoPath::from_internal_string("dir/file").to_fs_path(Path::new("")),
312            Path::new("dir/file")
313        );
314    }
315
316    #[test]
317    fn parse_fs_path_wc_in_cwd() {
318        let temp_dir = testutils::new_temp_dir();
319        let cwd_path = temp_dir.path().join("repo");
320        let wc_path = cwd_path.clone();
321
322        assert_eq!(
323            RepoPath::parse_fs_path(&cwd_path, &wc_path, ""),
324            Ok(RepoPath::root())
325        );
326        assert_eq!(
327            RepoPath::parse_fs_path(&cwd_path, &wc_path, "."),
328            Ok(RepoPath::root())
329        );
330        assert_eq!(
331            RepoPath::parse_fs_path(&cwd_path, &wc_path, "file"),
332            Ok(RepoPath::from_internal_string("file"))
333        );
334        // Both slash and the platform's separator are allowed
335        assert_eq!(
336            RepoPath::parse_fs_path(
337                &cwd_path,
338                &wc_path,
339                &format!("dir{}file", std::path::MAIN_SEPARATOR)
340            ),
341            Ok(RepoPath::from_internal_string("dir/file"))
342        );
343        assert_eq!(
344            RepoPath::parse_fs_path(&cwd_path, &wc_path, "dir/file"),
345            Ok(RepoPath::from_internal_string("dir/file"))
346        );
347        assert_eq!(
348            RepoPath::parse_fs_path(&cwd_path, &wc_path, ".."),
349            Err(FsPathParseError::InputNotInRepo("..".to_string()))
350        );
351        assert_eq!(
352            RepoPath::parse_fs_path(&cwd_path, &cwd_path, "../repo"),
353            Ok(RepoPath::root())
354        );
355        assert_eq!(
356            RepoPath::parse_fs_path(&cwd_path, &cwd_path, "../repo/file"),
357            Ok(RepoPath::from_internal_string("file"))
358        );
359        // Input may be absolute path with ".."
360        assert_eq!(
361            RepoPath::parse_fs_path(
362                &cwd_path,
363                &cwd_path,
364                cwd_path.join("../repo").to_str().unwrap()
365            ),
366            Ok(RepoPath::root())
367        );
368    }
369
370    #[test]
371    fn parse_fs_path_wc_in_cwd_parent() {
372        let temp_dir = testutils::new_temp_dir();
373        let cwd_path = temp_dir.path().join("dir");
374        let wc_path = cwd_path.parent().unwrap().to_path_buf();
375
376        assert_eq!(
377            RepoPath::parse_fs_path(&cwd_path, &wc_path, ""),
378            Ok(RepoPath::from_internal_string("dir"))
379        );
380        assert_eq!(
381            RepoPath::parse_fs_path(&cwd_path, &wc_path, "."),
382            Ok(RepoPath::from_internal_string("dir"))
383        );
384        assert_eq!(
385            RepoPath::parse_fs_path(&cwd_path, &wc_path, "file"),
386            Ok(RepoPath::from_internal_string("dir/file"))
387        );
388        assert_eq!(
389            RepoPath::parse_fs_path(&cwd_path, &wc_path, "subdir/file"),
390            Ok(RepoPath::from_internal_string("dir/subdir/file"))
391        );
392        assert_eq!(
393            RepoPath::parse_fs_path(&cwd_path, &wc_path, ".."),
394            Ok(RepoPath::root())
395        );
396        assert_eq!(
397            RepoPath::parse_fs_path(&cwd_path, &wc_path, "../.."),
398            Err(FsPathParseError::InputNotInRepo("../..".to_string()))
399        );
400        assert_eq!(
401            RepoPath::parse_fs_path(&cwd_path, &wc_path, "../other-dir/file"),
402            Ok(RepoPath::from_internal_string("other-dir/file"))
403        );
404    }
405
406    #[test]
407    fn parse_fs_path_wc_in_cwd_child() {
408        let temp_dir = testutils::new_temp_dir();
409        let cwd_path = temp_dir.path().join("cwd");
410        let wc_path = cwd_path.join("repo");
411
412        assert_eq!(
413            RepoPath::parse_fs_path(&cwd_path, &wc_path, ""),
414            Err(FsPathParseError::InputNotInRepo("".to_string()))
415        );
416        assert_eq!(
417            RepoPath::parse_fs_path(&cwd_path, &wc_path, "not-repo"),
418            Err(FsPathParseError::InputNotInRepo("not-repo".to_string()))
419        );
420        assert_eq!(
421            RepoPath::parse_fs_path(&cwd_path, &wc_path, "repo"),
422            Ok(RepoPath::root())
423        );
424        assert_eq!(
425            RepoPath::parse_fs_path(&cwd_path, &wc_path, "repo/file"),
426            Ok(RepoPath::from_internal_string("file"))
427        );
428        assert_eq!(
429            RepoPath::parse_fs_path(&cwd_path, &wc_path, "repo/dir/file"),
430            Ok(RepoPath::from_internal_string("dir/file"))
431        );
432    }
433}