@@ -7,12 +7,42 @@ extern crate dirs;
7
7
8
8
fn main ( ) -> std:: io:: Result < ( ) > {
9
9
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 {
10
38
let home = get_home ( ) ;
11
39
40
+ let mut output = String :: new ( ) ;
41
+
12
42
// If the path includes the home directory, strip it out and print "~"
13
43
let np = match path. strip_prefix ( format ! ( "{}" , home. display( ) ) ) {
14
44
Ok ( p) => {
15
- print ! ( "~/" ) ;
45
+ output . push_str ( & "~/" ) ;
16
46
p. to_path_buf ( )
17
47
} ,
18
48
Err ( _) => path,
@@ -30,13 +60,13 @@ fn main() -> std::io::Result<()> {
30
60
let mut first: bool = false ;
31
61
for frag in components. iter ( ) {
32
62
if first {
33
- print ! ( "/" ) ;
63
+ output . push_str ( & "/" ) ;
34
64
}
35
65
first = true ;
36
66
37
67
// Just print the full fragment if it's already short
38
68
if frag. len ( ) <= 4 {
39
- print ! ( "{}" , frag) ;
69
+ output . push_str ( frag) ;
40
70
continue ;
41
71
}
42
72
@@ -50,35 +80,14 @@ fn main() -> std::io::Result<()> {
50
80
51
81
// If there's only one word, just print the first 3 characters
52
82
if parts. len ( ) == 1 {
53
- print ! ( "{}" , & frag[ ..3 ] ) ;
83
+ output . push_str ( & frag[ ..3 ] ) ;
54
84
continue ;
55
85
}
56
86
57
87
// Print the first character of each part
58
88
for part in parts {
59
- print ! ( "{}" , & part[ ..1 ] ) ;
89
+ output . push_str ( & part[ ..1 ] ) ;
60
90
}
61
91
}
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
84
93
}
0 commit comments