ok/jj
1
0
Fork 0
forked from mirrors/jj

cli: simplify relative_path() by leveraging ancestors() iterator

Just code cleanup. There should be no behavior change.
This commit is contained in:
Yuya Nishihara 2022-10-20 17:36:34 +09:00
parent f3a9b06cc8
commit 58977f8cbf

View file

@ -15,7 +15,7 @@
use std::io::{Stderr, Stdout, Write}; use std::io::{Stderr, Stdout, Write};
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use std::str::FromStr; use std::str::FromStr;
use std::{fmt, io}; use std::{fmt, io, iter};
use atty::Stream; use atty::Stream;
use jujutsu_lib::repo_path::{RepoPath, RepoPathComponent, RepoPathJoin}; use jujutsu_lib::repo_path::{RepoPath, RepoPathComponent, RepoPathJoin};
@ -209,25 +209,26 @@ pub enum FilePathParseError {
InputNotInRepo(String), InputNotInRepo(String),
} }
pub fn relative_path(mut from: &Path, to: &Path) -> PathBuf { /// Turns the given `to` path into relative path starting from the `from` path.
let mut result = PathBuf::from(""); ///
loop { /// Both `from` and `to` paths are supposed to be absolute and normalized in the
if let Ok(suffix) = to.strip_prefix(from) { /// same manner.
result = result.join(suffix); pub fn relative_path(from: &Path, to: &Path) -> PathBuf {
break; // Find common prefix.
} for (i, base) in from.ancestors().enumerate() {
if let Some(parent) = from.parent() { if let Ok(suffix) = to.strip_prefix(base) {
result = result.join(".."); if i == 0 && suffix.as_os_str().is_empty() {
from = parent; return ".".into();
} else { } else {
result = to.to_path_buf(); let mut result = PathBuf::from_iter(iter::repeat("..").take(i));
break; result.push(suffix);
return result;
} }
} }
if result.as_os_str().is_empty() {
result = PathBuf::from(".");
} }
result
// No common prefix found. Return the original (absolute) path.
to.to_owned()
} }
#[cfg(test)] #[cfg(test)]