Skip to content

Commit e99ae36

Browse files
committed
extract compact logic into separate function
1 parent 6c4c817 commit e99ae36

File tree

1 file changed

+36
-27
lines changed

1 file changed

+36
-27
lines changed

src/main.rs

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,42 @@ extern crate dirs;
77

88
fn main() -> std::io::Result<()> {
99
let path = get_cwd()?;
10+
11+
print!("{}", compact_path(path));
12+
Ok(())
13+
}
14+
15+
/// Gets the current working directory, or parsed from first CLI argument if
16+
/// provided.
17+
fn get_cwd() -> std::io::Result<PathBuf> {
18+
let argv: Vec<String> = env::args().collect();
19+
let path = match argv.get(1) {
20+
Some(p) => fs::canonicalize(PathBuf::from(p))
21+
.or(Ok(PathBuf::from(p))),
22+
_ => env::current_dir(),
23+
};
24+
path
25+
}
26+
27+
/// Gets the home directory.
28+
fn get_home() -> PathBuf {
29+
let home = match dirs::home_dir() {
30+
Some(p) => p,
31+
None => Path::new("").to_path_buf(),
32+
};
33+
home
34+
}
35+
36+
/// Compacts a provided PathBuf and returns it as a string
37+
fn compact_path(path: PathBuf) -> String {
1038
let home = get_home();
1139

40+
let mut output = String::new();
41+
1242
// If the path includes the home directory, strip it out and print "~"
1343
let np = match path.strip_prefix(format!("{}", home.display())) {
1444
Ok(p) => {
15-
print!("~/");
45+
output.push_str(&"~/");
1646
p.to_path_buf()
1747
},
1848
Err(_) => path,
@@ -30,13 +60,13 @@ fn main() -> std::io::Result<()> {
3060
let mut first: bool = false;
3161
for frag in components.iter() {
3262
if first {
33-
print!("/");
63+
output.push_str(&"/");
3464
}
3565
first = true;
3666

3767
// Just print the full fragment if it's already short
3868
if frag.len() <= 4 {
39-
print!("{}", frag);
69+
output.push_str(frag);
4070
continue;
4171
}
4272

@@ -50,35 +80,14 @@ fn main() -> std::io::Result<()> {
5080

5181
// If there's only one word, just print the first 3 characters
5282
if parts.len() == 1 {
53-
print!("{}", &frag[..3]);
83+
output.push_str(&frag[..3]);
5484
continue;
5585
}
5686

5787
// Print the first character of each part
5888
for part in parts {
59-
print!("{}", &part[..1]);
89+
output.push_str(&part[..1]);
6090
}
6191
}
62-
Ok(())
63-
}
64-
65-
/// Gets the current working directory, or parsed from first CLI argument if
66-
/// provided.
67-
fn get_cwd() -> std::io::Result<PathBuf> {
68-
let argv: Vec<String> = env::args().collect();
69-
let path = match argv.get(1) {
70-
Some(p) => fs::canonicalize(PathBuf::from(p))
71-
.or(Ok(PathBuf::from(p))),
72-
_ => env::current_dir(),
73-
};
74-
path
75-
}
76-
77-
/// Gets the home directory.
78-
fn get_home() -> PathBuf {
79-
let home = match dirs::home_dir() {
80-
Some(p) => p,
81-
None => Path::new("").to_path_buf(),
82-
};
83-
home
92+
output
8493
}

0 commit comments

Comments
 (0)