-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
directory.rs
1789 lines (1589 loc) · 58.3 KB
/
directory.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[cfg(not(target_os = "windows"))]
use super::utils::directory_nix as directory_utils;
#[cfg(target_os = "windows")]
use super::utils::directory_win as directory_utils;
use super::utils::path::PathExt as SPathExt;
use indexmap::IndexMap;
use path_slash::{PathBufExt, PathExt};
use std::borrow::Cow;
use std::iter::FromIterator;
use std::path::{Path, PathBuf};
use unicode_segmentation::UnicodeSegmentation;
use super::{Context, Module};
use super::utils::directory::truncate;
use crate::config::ModuleConfig;
use crate::configs::directory::DirectoryConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current logical or physical directory
///
/// Will perform path contraction, substitution, and truncation.
///
/// **Contraction**
/// - Paths beginning with the home directory or with a git repo right inside
/// the home directory will be contracted to `~`, or the set `HOME_SYMBOL`
/// - Paths containing a git repo will contract to begin at the repo root
///
/// **Substitution**
/// Paths will undergo user-provided substitutions of substrings
///
/// **Truncation**
/// Paths will be limited in length to `3` path components by default.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("directory");
let config: DirectoryConfig = DirectoryConfig::try_load(module.config);
let home_symbol = String::from(config.home_symbol);
let home_dir = context
.get_home()
.expect("Unable to determine HOME_DIR for user");
let physical_dir = &context.current_dir;
let display_dir = if config.use_logical_path {
&context.logical_dir
} else {
&context.current_dir
};
log::debug!("Home dir: {:?}", &home_dir);
log::debug!("Physical dir: {:?}", &physical_dir);
log::debug!("Display dir: {:?}", &display_dir);
// Attempt repository path contraction (if we are in a git repository)
// Otherwise use the logical path, automatically contracting
let repo = context.get_repo().ok();
let dir_string = if config.truncate_to_repo {
repo.and_then(|r| r.workdir.as_ref())
.filter(|&root| root != &home_dir)
.and_then(|root| contract_repo_path(display_dir, root))
} else {
None
};
let mut is_truncated = dir_string.is_some();
// the home directory if required.
let dir_string = dir_string
.unwrap_or_else(|| contract_path(display_dir, &home_dir, &home_symbol).to_string());
#[cfg(windows)]
let dir_string = remove_extended_path_prefix(dir_string);
// Apply path substitutions
let dir_string = substitute_path(dir_string, &config.substitutions);
// Truncate the dir string to the maximum number of path components
let dir_string =
if let Some(truncated) = truncate(&dir_string, config.truncation_length as usize) {
is_truncated = true;
truncated
} else {
dir_string
};
let prefix = if is_truncated {
// Substitutions could have changed the prefix, so don't allow them and
// fish-style path contraction together
if config.fish_style_pwd_dir_length > 0 && config.substitutions.is_empty() {
// If user is using fish style path, we need to add the segment first
let contracted_home_dir = contract_path(display_dir, &home_dir, &home_symbol);
to_fish_style(
config.fish_style_pwd_dir_length as usize,
contracted_home_dir.to_string(),
&dir_string,
)
} else {
String::from(config.truncation_symbol)
}
} else {
String::from("")
};
let path_vec = match &repo.and_then(|r| r.workdir.as_ref()) {
Some(repo_root) if config.repo_root_style.is_some() => {
let contracted_path = contract_repo_path(display_dir, repo_root)?;
let repo_path_vec: Vec<&str> = contracted_path.split('/').collect();
let after_repo_root = contracted_path.replacen(repo_path_vec[0], "", 1);
let num_segments_after_root = after_repo_root.split('/').count();
if config.truncation_length == 0
|| ((num_segments_after_root - 1) as i64) < config.truncation_length
{
let root = repo_path_vec[0];
let before = dir_string.replace(&contracted_path, "");
[prefix + &before, root.to_string(), after_repo_root]
} else {
["".to_string(), "".to_string(), prefix + &dir_string]
}
}
_ => ["".to_string(), "".to_string(), prefix + &dir_string],
};
let path_vec = if config.use_os_path_sep {
path_vec.map(|i| convert_path_sep(&i))
} else {
path_vec
};
let lock_symbol = String::from(config.read_only);
let display_format = if path_vec[0].is_empty() && path_vec[1].is_empty() {
config.format
} else {
config.repo_root_format
};
let repo_root_style = config.repo_root_style.unwrap_or(config.style);
let parsed = StringFormatter::new(display_format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
"read_only_style" => Some(Ok(config.read_only_style)),
"repo_root_style" => Some(Ok(repo_root_style)),
_ => None,
})
.map(|variable| match variable {
"path" => Some(Ok(&path_vec[2])),
"before_root_path" => Some(Ok(&path_vec[0])),
"repo_root" => Some(Ok(&path_vec[1])),
"read_only" => {
if is_readonly_dir(physical_dir) {
Some(Ok(&lock_symbol))
} else {
None
}
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `directory`:\n{}", error);
return None;
}
});
Some(module)
}
#[cfg(windows)]
fn remove_extended_path_prefix(path: String) -> String {
fn try_trim_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
if !s.starts_with(prefix) {
return None;
}
Some(&s[prefix.len()..])
}
// Trim any Windows extended-path prefix from the display path
if let Some(unc) = try_trim_prefix(&path, r"\\?\UNC\") {
return format!(r"\\{}", unc);
}
if let Some(p) = try_trim_prefix(&path, r"\\?\") {
return p.to_string();
}
path
}
fn is_readonly_dir(path: &Path) -> bool {
match directory_utils::is_write_allowed(path) {
Ok(res) => !res,
Err(e) => {
log::debug!(
"Failed to determine read only status of directory '{:?}': {}",
path,
e
);
false
}
}
}
/// Contract the root component of a path
///
/// Replaces the `top_level_path` in a given `full_path` with the provided
/// `top_level_replacement`.
fn contract_path<'a>(
full_path: &'a Path,
top_level_path: &'a Path,
top_level_replacement: &'a str,
) -> Cow<'a, str> {
if !full_path.normalised_starts_with(top_level_path) {
return full_path.to_slash_lossy();
}
if full_path.normalised_equals(top_level_path) {
return Cow::from(top_level_replacement);
}
// Because we've done a normalised path comparison above
// we can safely ignore the Prefix components when doing this
// strip_prefix operation.
let sub_path = full_path
.without_prefix()
.strip_prefix(top_level_path.without_prefix())
.unwrap_or(full_path);
Cow::from(format!(
"{replacement}{separator}{path}",
replacement = top_level_replacement,
separator = "/",
path = sub_path.to_slash_lossy()
))
}
/// Contract the root component of a path based on the real path
///
/// Replaces the `top_level_path` in a given `full_path` with the provided
/// `top_level_replacement` by walking ancestors and comparing its real path.
fn contract_repo_path(full_path: &Path, top_level_path: &Path) -> Option<String> {
let top_level_real_path = real_path(top_level_path);
// Walk ancestors to preserve logical path in `full_path`.
// If we'd just `full_real_path.strip_prefix(top_level_real_path)`,
// then it wouldn't preserve logical path. It would've returned physical path.
for (i, ancestor) in full_path.ancestors().enumerate() {
let ancestor_real_path = real_path(ancestor);
if ancestor_real_path != top_level_real_path {
continue;
}
let components: Vec<_> = full_path.components().collect();
let repo_name = components[components.len() - i - 1]
.as_os_str()
.to_string_lossy();
if i == 0 {
return Some(repo_name.to_string());
}
let path = PathBuf::from_iter(&components[components.len() - i..]);
return Some(format!(
"{repo_name}{separator}{path}",
repo_name = repo_name,
separator = "/",
path = path.to_slash_lossy()
));
}
None
}
fn real_path<P: AsRef<Path>>(path: P) -> PathBuf {
let path = path.as_ref();
let mut buf = PathBuf::new();
for component in path.components() {
let next = buf.join(component);
if let Ok(realpath) = next.read_link() {
if realpath.is_absolute() {
buf = realpath;
} else {
buf.push(realpath);
}
} else {
buf = next;
}
}
buf.canonicalize().unwrap_or_else(|_| path.into())
}
/// Perform a list of string substitutions on the path
///
/// Given a list of (from, to) pairs, this will perform the string
/// substitutions, in order, on the path. Any non-pair of strings is ignored.
fn substitute_path(dir_string: String, substitutions: &IndexMap<String, &str>) -> String {
let mut substituted_dir = dir_string;
for substitution_pair in substitutions {
substituted_dir = substituted_dir.replace(substitution_pair.0, substitution_pair.1);
}
substituted_dir
}
/// Takes part before contracted path and replaces it with fish style path
///
/// Will take the first letter of each directory before the contracted path and
/// use that in the path instead. See the following example.
///
/// Absolute Path: `/Users/Bob/Projects/work/a_repo`
/// Contracted Path: `a_repo`
/// With Fish Style: `~/P/w/a_repo`
///
/// Absolute Path: `/some/Path/not/in_a/repo/but_nested`
/// Contracted Path: `in_a/repo/but_nested`
/// With Fish Style: `/s/P/n/in_a/repo/but_nested`
fn to_fish_style(pwd_dir_length: usize, dir_string: String, truncated_dir_string: &str) -> String {
let replaced_dir_string = dir_string.trim_end_matches(truncated_dir_string).to_owned();
let components = replaced_dir_string.split('/').collect::<Vec<&str>>();
if components.is_empty() {
return replaced_dir_string;
}
components
.into_iter()
.map(|word| -> String {
let chars = UnicodeSegmentation::graphemes(word, true).collect::<Vec<&str>>();
match word {
"" => "".to_string(),
_ if chars.len() <= pwd_dir_length => word.to_string(),
_ if word.starts_with('.') => chars[..=pwd_dir_length].join(""),
_ => chars[..pwd_dir_length].join(""),
}
})
.collect::<Vec<_>>()
.join("/")
}
/// Convert the path separators in `path` to the OS specific path separators.
fn convert_path_sep(path: &str) -> String {
return PathBuf::from_slash(path).to_string_lossy().into_owned();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use crate::utils::create_command;
use crate::utils::home_dir;
use ansi_term::Color;
#[cfg(not(target_os = "windows"))]
use std::os::unix::fs::symlink;
#[cfg(target_os = "windows")]
use std::os::windows::fs::symlink_dir as symlink;
use std::path::Path;
use std::{fs, io};
use tempfile::TempDir;
#[test]
fn contract_home_directory() {
let full_path = Path::new("/Users/astronaut/schematics/rocket");
let home = Path::new("/Users/astronaut");
let output = contract_path(full_path, home, "~");
assert_eq!(output, "~/schematics/rocket");
}
#[test]
fn contract_repo_directory() -> io::Result<()> {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let repo_dir = tmp_dir.path().join("dev").join("rocket-controls");
let src_dir = repo_dir.join("src");
fs::create_dir_all(&src_dir)?;
init_repo(&repo_dir)?;
let src_variations = [src_dir.clone(), dunce::canonicalize(src_dir).unwrap()];
let repo_variations = [repo_dir.clone(), dunce::canonicalize(repo_dir).unwrap()];
for src_dir in &src_variations {
for repo_dir in &repo_variations {
let output = contract_repo_path(src_dir, repo_dir);
assert_eq!(output, Some("rocket-controls/src".to_string()));
}
}
tmp_dir.close()
}
#[test]
#[cfg(windows)]
fn contract_windows_style_home_directory() {
let path_variations = [
r"\\?\C:\Users\astronaut\schematics\rocket",
r"C:\Users\astronaut\schematics\rocket",
];
let home_path_variations = [r"\\?\C:\Users\astronaut", r"C:\Users\astronaut"];
for path in &path_variations {
for home_path in &home_path_variations {
let path = Path::new(path);
let home_path = Path::new(home_path);
let output = contract_path(path, home_path, "~");
assert_eq!(output, "~/schematics/rocket");
}
}
}
#[test]
#[cfg(target_os = "windows")]
fn contract_windows_style_repo_directory() {
let full_path = Path::new("C:\\Users\\astronaut\\dev\\rocket-controls\\src");
let repo_root = Path::new("C:\\Users\\astronaut\\dev\\rocket-controls");
let output = contract_path(full_path, repo_root, "rocket-controls");
assert_eq!(output, "rocket-controls/src");
}
#[test]
#[cfg(target_os = "windows")]
fn contract_windows_style_no_top_level_directory() {
let full_path = Path::new("C:\\Some\\Other\\Path");
let top_level_path = Path::new("C:\\Users\\astronaut");
let output = contract_path(full_path, top_level_path, "~");
assert_eq!(output, "C:/Some/Other/Path");
}
#[test]
#[cfg(target_os = "windows")]
fn contract_windows_style_root_directory() {
let full_path = Path::new("C:\\");
let top_level_path = Path::new("C:\\Users\\astronaut");
let output = contract_path(full_path, top_level_path, "~");
assert_eq!(output, "C:\\");
}
#[test]
fn substitute_prefix_and_middle() {
let full_path = "/absolute/path/foo/bar/baz";
let mut substitutions = IndexMap::new();
substitutions.insert("/absolute/path".to_string(), "");
substitutions.insert("/bar/".to_string(), "/");
let output = substitute_path(full_path.to_string(), &substitutions);
assert_eq!(output, "/foo/baz");
}
#[test]
fn fish_style_with_user_home_contracted_path() {
let path = "~/starship/engines/booster/rocket";
let output = to_fish_style(1, path.to_string(), "engines/booster/rocket");
assert_eq!(output, "~/s/");
}
#[test]
fn fish_style_with_user_home_contracted_path_and_dot_dir() {
let path = "~/.starship/engines/booster/rocket";
let output = to_fish_style(1, path.to_string(), "engines/booster/rocket");
assert_eq!(output, "~/.s/");
}
#[test]
fn fish_style_with_no_contracted_path() {
// `truncation_length = 2`
let path = "/absolute/Path/not/in_a/repo/but_nested";
let output = to_fish_style(1, path.to_string(), "repo/but_nested");
assert_eq!(output, "/a/P/n/i/");
}
#[test]
fn fish_style_with_pwd_dir_len_no_contracted_path() {
// `truncation_length = 2`
let path = "/absolute/Path/not/in_a/repo/but_nested";
let output = to_fish_style(2, path.to_string(), "repo/but_nested");
assert_eq!(output, "/ab/Pa/no/in/");
}
#[test]
fn fish_style_with_duplicate_directories() {
let path = "~/starship/tmp/C++/C++/C++";
let output = to_fish_style(1, path.to_string(), "C++");
assert_eq!(output, "~/s/t/C/C/");
}
#[test]
fn fish_style_with_unicode() {
let path = "~/starship/tmp/目录/a̐éö̲/目录";
let output = to_fish_style(1, path.to_string(), "目录");
assert_eq!(output, "~/s/t/目/a̐/");
}
fn init_repo(path: &Path) -> io::Result<()> {
create_command("git")?
.args(&["init"])
.current_dir(path)
.output()
.map(|_| ())
}
fn make_known_tempdir(root: &Path) -> io::Result<(TempDir, String)> {
fs::create_dir_all(root)?;
let dir = TempDir::new_in(root)?;
let path = dir
.path()
.file_name()
.unwrap()
.to_string_lossy()
.to_string();
Ok((dir, path))
}
#[cfg(not(target_os = "windows"))]
mod linux {
use super::*;
#[test]
#[ignore]
fn symlinked_subdirectory_git_repo_out_of_tree() -> io::Result<()> {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let repo_dir = tmp_dir.path().join("above-repo").join("rocket-controls");
let src_dir = repo_dir.join("src/meters/fuel-gauge");
let symlink_dir = tmp_dir.path().join("fuel-gauge");
fs::create_dir_all(&src_dir)?;
init_repo(&repo_dir)?;
symlink(&src_dir, &symlink_dir)?;
let actual = ModuleRenderer::new("directory")
.env("HOME", tmp_dir.path().to_str().unwrap())
.path(symlink_dir)
.collect();
let expected = Some(format!("{} ", Color::Cyan.bold().paint("~/fuel-gauge")));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn git_repo_in_home_directory_truncate_to_repo_true() -> io::Result<()> {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("src/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(tmp_dir.path())?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
// `truncate_to_repo = true` should attempt to display the truncated path
truncate_to_repo = true
truncation_length = 5
})
.path(dir)
.env("HOME", tmp_dir.path().to_str().unwrap())
.collect();
let expected = Some(format!("{} ", Color::Cyan.bold().paint("~/src/fuel-gauge")));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn directory_in_root() {
let actual = ModuleRenderer::new("directory").path("/etc").collect();
let expected = Some(format!(
"{}{} ",
Color::Cyan.bold().paint("/etc"),
Color::Red.normal().paint("🔒")
));
assert_eq!(expected, actual);
}
}
#[test]
fn home_directory_default_home_symbol() {
let actual = ModuleRenderer::new("directory")
.path(home_dir().unwrap())
.collect();
let expected = Some(format!("{} ", Color::Cyan.bold().paint("~")));
assert_eq!(expected, actual);
}
#[test]
fn home_directory_custom_home_symbol() {
let actual = ModuleRenderer::new("directory")
.path(home_dir().unwrap())
.config(toml::toml! {
[directory]
home_symbol = "🚀"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep("🚀"))
));
assert_eq!(expected, actual);
}
#[test]
fn home_directory_custom_home_symbol_subdirectories() {
let actual = ModuleRenderer::new("directory")
.path(home_dir().unwrap().join("path/subpath"))
.config(toml::toml! {
[directory]
home_symbol = "🚀"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("🚀/path/subpath"))
));
assert_eq!(expected, actual);
}
#[test]
fn substituted_truncated_path() {
let actual = ModuleRenderer::new("directory")
.path("/some/long/network/path/workspace/a/b/c/dev")
.config(toml::toml! {
[directory]
truncation_length = 4
[directory.substitutions]
"/some/long/network/path" = "/some/net"
"a/b/c" = "d"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("net/workspace/d/dev"))
));
assert_eq!(expected, actual);
}
#[test]
fn substitution_order() {
let actual = ModuleRenderer::new("directory")
.path("/path/to/sub")
.config(toml::toml! {
[directory.substitutions]
"/path/to/sub" = "/correct/order"
"/to/sub" = "/wrong/order"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep("/correct/order"))
));
assert_eq!(expected, actual);
}
#[test]
fn strange_substitution() {
let strange_sub = "/\\/;,!";
let actual = ModuleRenderer::new("directory")
.path("/foo/bar/regular/path")
.config(toml::toml! {
[directory]
truncation_length = 0
fish_style_pwd_dir_length = 2 // Overridden by substitutions
[directory.substitutions]
"regular" = strange_sub
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("/foo/bar/{}/path", strange_sub)))
));
assert_eq!(expected, actual);
}
#[test]
fn directory_in_home() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("starship");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("~/{}/starship", name)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn truncated_directory_in_home() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("engine/schematics");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("{}/engine/schematics", name)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn fish_directory_in_home() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("starship/schematics");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 1
fish_style_pwd_dir_length = 2
})
.path(&dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&format!(
"~/{}/st/schematics",
name.split_at(3).0
)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn root_directory() {
// Note: We have disable the read_only settings here due to false positives when running
// the tests on Windows as a non-admin.
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
read_only = ""
read_only_style = ""
})
.path("/")
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep("/"))
));
assert_eq!(expected, actual);
}
#[test]
fn truncated_directory_in_root() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("{}/thrusters/rocket", name)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn truncated_directory_config_large() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 100
})
.path(&dir)
.collect();
let dir_str = dir.to_slash_lossy().to_string();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(
&truncate(&dir_str, 100).unwrap_or(dir_str)
))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn fish_style_directory_config_large() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 1
fish_style_pwd_dir_length = 100
})
.path(&dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&to_fish_style(
100,
dir.to_slash_lossy().to_string(),
""
)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn truncated_directory_config_small() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 2
})
.path(dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("{}/rocket", name)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn fish_directory_config_small() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 2
fish_style_pwd_dir_length = 1
})
.path(&dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&format!(
"{}/thrusters/rocket",
to_fish_style(1, dir.to_slash_lossy().to_string(), "/thrusters/rocket")
)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn git_repo_root() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("rocket-controls");
fs::create_dir(&repo_dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory").path(repo_dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("rocket-controls"))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn directory_in_git_repo() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("rocket-controls");
let dir = repo_dir.join("src");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("rocket-controls/src"))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn truncated_directory_in_git_repo() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("rocket-controls");
let dir = repo_dir.join("src/meters/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("src/meters/fuel-gauge"))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn directory_in_git_repo_truncate_to_repo_false() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("above-repo").join("rocket-controls");
let dir = repo_dir.join("src/meters/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
// Don't truncate the path at all.
truncation_length = 5
truncate_to_repo = false
})
.path(dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(
"above-repo/rocket-controls/src/meters/fuel-gauge"
))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn fish_path_directory_in_git_repo_truncate_to_repo_false() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let repo_dir = tmp_dir.path().join("above-repo").join("rocket-controls");
let dir = repo_dir.join("src/meters/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
// Don't truncate the path at all.
truncation_length = 5
truncate_to_repo = false
fish_style_pwd_dir_length = 1
})
.path(dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&format!(
"{}/above-repo/rocket-controls/src/meters/fuel-gauge",
to_fish_style(1, tmp_dir.path().to_slash_lossy().to_string(), "")