on master help sign in
Move path util functions from helix-term to helix-core (#650)
commitb99db7c6875f74a15dcfb0cfdb3334c837d4aab1 authorKirawi <67773714+kirawi@users.noreply.github.com> dateTue 24 Aug 2021, 21:04 (5 years ago) parentbf5b9a9
7 files changed+106−98
helix-core/src/lib.rs+1 helix-core/src/path.rs+92 helix-term/src/commands.rs+1−2 helix-term/src/ui/mod.rs+1−1 helix-term/src/ui/picker.rs+5−2 helix-view/src/document.rs+5−92 helix-view/src/editor.rs+1−1
helix-core/src/lib.rs+1
@@ -11,6 +11,7 @@ pub mod macros;
1111pub mod match_brackets;
1212pub mod movement;
1313pub mod object;
14+pub mod path;
1415mod position;
1516pub mod register;
1617pub mod search;
helix-core/src/path.rsnew file+92
@@ -0,0 +1,92 @@
1+use std::path::{Component, Path, PathBuf};
2+
3+/// Replaces users home directory from `path` with tilde `~` if the directory
4+/// is available, otherwise returns the path unchanged.
5+pub fn fold_home_dir(path: &Path) -> PathBuf {
6+ if let Ok(home) = super::home_dir() {
7+ if path.starts_with(&home) {
8+ // it's ok to unwrap, the path starts with home dir
9+ return PathBuf::from("~").join(path.strip_prefix(&home).unwrap());
10+ }
11+ }
12+
13+ path.to_path_buf()
14+}
15+
16+/// Expands tilde `~` into users home directory if avilable, otherwise returns the path
17+/// unchanged. The tilde will only be expanded when present as the first component of the path
18+/// and only slash follows it.
19+pub fn expand_tilde(path: &Path) -> PathBuf {
20+ let mut components = path.components().peekable();
21+ if let Some(Component::Normal(c)) = components.peek() {
22+ if c == &"~" {
23+ if let Ok(home) = super::home_dir() {
24+ // it's ok to unwrap, the path starts with `~`
25+ return home.join(path.strip_prefix("~").unwrap());
26+ }
27+ }
28+ }
29+
30+ path.to_path_buf()
31+}
32+
33+/// Normalize a path, removing things like `.` and `..`.
34+///
35+/// CAUTION: This does not resolve symlinks (unlike
36+/// [`std::fs::canonicalize`]). This may cause incorrect or surprising
37+/// behavior at times. This should be used carefully. Unfortunately,
38+/// [`std::fs::canonicalize`] can be hard to use correctly, since it can often
39+/// fail, or on Windows returns annoying device paths. This is a problem Cargo
40+/// needs to improve on.
41+/// Copied from cargo: <https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81>
42+pub fn get_normalized_path(path: &Path) -> PathBuf {
43+ let path = expand_tilde(path);
44+ let mut components = path.components().peekable();
45+ let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
46+ components.next();
47+ PathBuf::from(c.as_os_str())
48+ } else {
49+ PathBuf::new()
50+ };
51+
52+ for component in components {
53+ match component {
54+ Component::Prefix(..) => unreachable!(),
55+ Component::RootDir => {
56+ ret.push(component.as_os_str());
57+ }
58+ Component::CurDir => {}
59+ Component::ParentDir => {
60+ ret.pop();
61+ }
62+ Component::Normal(c) => {
63+ ret.push(c);
64+ }
65+ }
66+ }
67+ ret
68+}
69+
70+/// Returns the canonical, absolute form of a path with all intermediate components normalized.
71+///
72+/// This function is used instead of `std::fs::canonicalize` because we don't want to verify
73+/// here if the path exists, just normalize it's components.
74+pub fn get_canonicalized_path(path: &Path) -> std::io::Result<PathBuf> {
75+ let path = if path.is_relative() {
76+ std::env::current_dir().map(|current_dir| current_dir.join(path))?
77+ } else {
78+ path.to_path_buf()
79+ };
80+
81+ Ok(get_normalized_path(path.as_path()))
82+}
83+
84+pub fn get_relative_path(path: &Path) -> PathBuf {
85+ let path = if path.is_absolute() {
86+ let cwdir = std::env::current_dir().expect("couldn't determine current directory");
87+ path.strip_prefix(cwdir).unwrap_or(path)
88+ } else {
89+ path
90+ };
91+ fold_home_dir(path)
92+}
helix-term/src/commands.rs+1−2
@@ -2291,8 +2291,7 @@ fn buffer_picker(cx: &mut Context) {
22912291 .map(|(id, doc)| (id, doc.path().cloned()))
22922292 .collect(),
22932293 move |(id, path): &(DocumentId, Option<PathBuf>)| {
2294− use helix_view::document::relative_path;
2295− let path = path.as_deref().map(relative_path);
2294+ let path = path.as_deref().map(helix_core::path::get_relative_path);
22962295 match path.as_ref().and_then(|path| path.to_str()) {
22972296 Some(path) => {
22982297 if *id == current {
helix-term/src/ui/mod.rs+1−1
@@ -208,7 +208,7 @@ pub mod completers {
208208 use std::path::Path;
209209
210210 let is_tilde = input.starts_with('~') && input.len() == 1;
211− let path = helix_view::document::expand_tilde(Path::new(input));
211+ let path = helix_core::path::expand_tilde(Path::new(input));
212212
213213 let (dir, file_name) = if input.ends_with('/') {
214214 (path, None)
helix-term/src/ui/picker.rs+5−2
@@ -17,7 +17,6 @@ use std::{borrow::Cow, collections::HashMap, path::PathBuf};
1717use crate::ui::{Prompt, PromptEvent};
1818use helix_core::Position;
1919use helix_view::{
20− document::canonicalize_path,
2120 editor::Action,
2221 graphics::{Color, CursorKind, Margin, Rect, Style},
2322 Document, Editor,
@@ -54,7 +53,11 @@ impl<T> FilePicker<T> {
5453 self.picker
5554 .selection()
5655 .and_then(|current| (self.file_fn)(editor, current))
57− .and_then(|(path, line)| canonicalize_path(&path).ok().zip(Some(line)))
56+ .and_then(|(path, line)| {
57+ helix_core::path::get_canonicalized_path(&path)
58+ .ok()
59+ .zip(Some(line))
60+ })
5861 }
5962
6063 fn calculate_preview(&mut self, editor: &Editor) {
helix-view/src/document.rs+5−92
@@ -4,7 +4,7 @@ use std::cell::Cell;
44use std::collections::HashMap;
55use std::fmt::Display;
66use std::future::Future;
7−use std::path::{Component, Path, PathBuf};
7+use std::path::{Path, PathBuf};
88use std::str::FromStr;
99use std::sync::Arc;
1010
@@ -317,95 +317,6 @@ where
317317 }
318318}
319319
320−/// Expands tilde `~` into users home directory if avilable, otherwise returns the path
321−/// unchanged. The tilde will only be expanded when present as the first component of the path
322−/// and only slash follows it.
323−pub fn expand_tilde(path: &Path) -> PathBuf {
324− let mut components = path.components().peekable();
325− if let Some(Component::Normal(c)) = components.peek() {
326− if c == &"~" {
327− if let Ok(home) = helix_core::home_dir() {
328− // it's ok to unwrap, the path starts with `~`
329− return home.join(path.strip_prefix("~").unwrap());
330− }
331− }
332− }
333−
334− path.to_path_buf()
335−}
336−
337−/// Replaces users home directory from `path` with tilde `~` if the directory
338−/// is available, otherwise returns the path unchanged.
339−pub fn fold_home_dir(path: &Path) -> PathBuf {
340− if let Ok(home) = helix_core::home_dir() {
341− if path.starts_with(&home) {
342− // it's ok to unwrap, the path starts with home dir
343− return PathBuf::from("~").join(path.strip_prefix(&home).unwrap());
344− }
345− }
346−
347− path.to_path_buf()
348−}
349−
350−/// Normalize a path, removing things like `.` and `..`.
351−///
352−/// CAUTION: This does not resolve symlinks (unlike
353−/// [`std::fs::canonicalize`]). This may cause incorrect or surprising
354−/// behavior at times. This should be used carefully. Unfortunately,
355−/// [`std::fs::canonicalize`] can be hard to use correctly, since it can often
356−/// fail, or on Windows returns annoying device paths. This is a problem Cargo
357−/// needs to improve on.
358−/// Copied from cargo: <https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81>
359−pub fn normalize_path(path: &Path) -> PathBuf {
360− let path = expand_tilde(path);
361− let mut components = path.components().peekable();
362− let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
363− components.next();
364− PathBuf::from(c.as_os_str())
365− } else {
366− PathBuf::new()
367− };
368−
369− for component in components {
370− match component {
371− Component::Prefix(..) => unreachable!(),
372− Component::RootDir => {
373− ret.push(component.as_os_str());
374− }
375− Component::CurDir => {}
376− Component::ParentDir => {
377− ret.pop();
378− }
379− Component::Normal(c) => {
380− ret.push(c);
381− }
382− }
383− }
384− ret
385−}
386−
387−/// Returns the canonical, absolute form of a path with all intermediate components normalized.
388−///
389−/// This function is used instead of `std::fs::canonicalize` because we don't want to verify
390−/// here if the path exists, just normalize it's components.
391−pub fn canonicalize_path(path: &Path) -> std::io::Result<PathBuf> {
392− let path = if path.is_relative() {
393− std::env::current_dir().map(|current_dir| current_dir.join(path))?
394− } else {
395− path.to_path_buf()
396− };
397−
398− Ok(normalize_path(&path))
399−}
400−
401−pub fn relative_path(mut path: &Path) -> PathBuf {
402− let cwdir = std::env::current_dir().expect("couldn't determine current directory");
403− if path.is_absolute() {
404− path = path.strip_prefix(cwdir).unwrap_or(path)
405− };
406− fold_home_dir(path)
407−}
408−
409320use helix_lsp::lsp;
410321use url::Url;
411322
@@ -639,7 +550,7 @@ impl Document {
639550 }
640551
641552 pub fn set_path(&mut self, path: &Path) -> Result<(), std::io::Error> {
642− let path = canonicalize_path(path)?;
553+ let path = helix_core::path::get_canonicalized_path(path)?;
643554
644555 // if parent doesn't exist we still want to open the document
645556 // and error out when document is saved
@@ -944,7 +855,9 @@ impl Document {
944855 }
945856
946857 pub fn relative_path(&self) -> Option<PathBuf> {
947− self.path.as_deref().map(relative_path)
858+ self.path
859+ .as_deref()
860+ .map(helix_core::path::get_relative_path)
948861 }
949862
950863 // pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds {
helix-view/src/editor.rs+1−1
@@ -229,7 +229,7 @@ impl Editor {
229229 }
230230
231231 pub fn open(&mut self, path: PathBuf, action: Action) -> Result<DocumentId, Error> {
232− let path = crate::document::canonicalize_path(&path)?;
232+ let path = helix_core::path::get_canonicalized_path(&path)?;
233233
234234 let id = self
235235 .documents()