-
Notifications
You must be signed in to change notification settings - Fork 45
/
filesystem.rs
1029 lines (908 loc) · 33 KB
/
filesystem.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
use anyhow::{Context, Result};
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{self, ErrorKind, Read};
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::Command;
use crate::config::UnixUser;
// === Serialize/deserialize files ===
/// Returns Ok(None) if file was not found, otherwise Ok(Some(data)) or Err
pub fn load_file<T>(filename: &Path) -> Result<Option<T>>
where
T: DeserializeOwned,
{
let mut buf = String::new();
let mut f = match File::open(filename) {
Ok(f) => Ok(f),
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
e => e,
}
.context("open file")?;
f.read_to_string(&mut buf).context("read file")?;
let data = toml::from_str::<T>(&buf).context("deserialize file contents")?;
Ok(Some(data))
}
pub fn save_file<T>(filename: &Path, data: T) -> Result<()>
where
T: Serialize,
{
let data = toml::to_string(&data).context("serialize data")?;
fs::write(filename, &data).context("write to file")
}
// === Mockable filesystem ===
#[cfg_attr(test, mockall::automock)]
pub trait Filesystem {
/// Check state of expected symlink on disk
fn compare_symlink(&mut self, source: &Path, link: &Path) -> Result<SymlinkComparison>;
/// Check state of expected symbolic link on disk
fn compare_template(&mut self, target: &Path, cache: &Path) -> Result<TemplateComparison>;
/// Check source file for whether it should be a symlink or a template
fn is_template(&mut self, source: &Path) -> Result<bool>;
/// Removes a file or folder, elevating privileges if needed
fn remove_file(&mut self, path: &Path) -> Result<()>;
/// Read contents of file into a string
fn read_to_string(&mut self, path: &Path) -> Result<String>;
/// Write string to file, without elevating privileges
fn write(&mut self, path: &Path, content: String) -> Result<()>;
/// Delete parents of target file if they're empty
fn delete_parents(&mut self, path: &Path, no_ask: bool) -> Result<()>;
/// Makes a symlink owned by the selected user, elevating privileges as needed
fn make_symlink(&mut self, link: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()>;
/// Create directory (and its parents) owned by the selected user,
/// elevating privileges as needed
fn create_dir_all(&mut self, path: &Path, owner: &Option<UnixUser>) -> Result<()>;
/// Copy readable file to target existing location.
/// Target file will be owned by the selected user. Privileges elevated as needed.
fn copy_file(&mut self, source: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()>;
/// If owner.is_some, elevates privileges and sets file to that owner
/// If owner.is_none, ensures file is owned by the current user (elevating privileges if needed)
fn set_owner(&mut self, file: &Path, owner: &Option<UnixUser>) -> Result<()>;
/// Copy file mode, elevating privileges as needed. (Does not change owner)
fn copy_permissions(
&mut self,
source: &Path,
target: &Path,
owner: &Option<UnixUser>,
) -> Result<()>;
}
// == Windows Filesystem ==
#[cfg(windows)]
pub struct RealFilesystem {
interactive: bool,
}
#[cfg(windows)]
impl RealFilesystem {
pub fn new(interactive: bool) -> RealFilesystem {
RealFilesystem { interactive }
}
}
#[cfg(windows)]
impl Filesystem for RealFilesystem {
fn compare_symlink(&mut self, source: &Path, link: &Path) -> Result<SymlinkComparison> {
let source_state = get_file_state(source).context("get source state")?;
trace!("Source state: {:#?}", source_state);
let link_state = get_file_state(link).context("get link state")?;
trace!("Link state: {:#?}", link_state);
let source = real_path(source).context("get real path of source")?;
Ok(compare_symlink(&source, source_state, link_state))
}
fn compare_template(&mut self, target: &Path, cache: &Path) -> Result<TemplateComparison> {
let target_state = get_file_state(target).context("get state of target")?;
trace!("Target state: {:#?}", target_state);
let cache_state = get_file_state(cache).context("get state of cache")?;
trace!("Cache state: {:#?}", cache_state);
Ok(compare_template(target_state, cache_state))
}
fn is_template(&mut self, source: &Path) -> Result<bool> {
is_template(source)
}
fn remove_file(&mut self, path: &Path) -> Result<()> {
let metadata = path.metadata().context("get metadata")?;
if metadata.is_dir() {
std::fs::remove_dir_all(path).context("remove directory")
} else {
std::fs::remove_file(path).context("remove file")
}
}
fn read_to_string(&mut self, path: &Path) -> Result<String> {
fs::read_to_string(path).context("read from file")
}
fn write(&mut self, path: &Path, content: String) -> Result<()> {
fs::write(path, content).context("write to file")
}
fn delete_parents(&mut self, path: &Path, no_ask: bool) -> Result<()> {
let mut path = path.parent().context("get parent")?;
while path.is_dir()
&& path
.read_dir()
.context("read the contents of parent directory")?
.next()
.is_none()
{
if (!self.interactive || no_ask)
|| ask_boolean(&format!(
"Directory at {:?} is now empty. Delete [y/N]? ",
path
))
{
std::fs::remove_dir(path).context(format!("remove directory {:?}", path))?;
}
path = path.parent().context(format!("get parent of {:?}", path))?;
}
Ok(())
}
fn make_symlink(&mut self, link: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()> {
use std::os::windows::fs;
if let Some(owner) = owner {
warn!(
"Ignoring `owner`={:?} when creating symlink {:?} -> {:?}",
owner, link, target
);
}
fs::symlink_file(
real_path(target).context("get real path of source file")?,
link,
)
.context("create symlink")
}
fn create_dir_all(&mut self, path: &Path, owner: &Option<UnixUser>) -> Result<()> {
if let Some(owner) = owner {
warn!(
"Ignoring `owner`={:?} when creating directory {:?}",
owner, path
);
}
std::fs::create_dir_all(path).context("create directories")
}
fn copy_file(&mut self, source: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()> {
if let Some(owner) = owner {
warn!(
"Ignoring `owner`={:?} when copying {:?} -> {:?}",
owner, source, target
);
}
std::fs::copy(source, target).context("copy file")?;
Ok(())
}
fn set_owner(&mut self, file: &Path, owner: &Option<UnixUser>) -> Result<()> {
if owner.is_some() {
warn!("ignoring `owner` field on file {:?}", file);
}
Ok(())
}
fn copy_permissions(
&mut self,
source: &Path,
target: &Path,
owner: &Option<UnixUser>,
) -> Result<()> {
if let Some(owner) = owner {
warn!(
"Ignoring `owner`={:?} when copying permissions {:?} -> {:?}",
owner, source, target
);
}
std::fs::set_permissions(
target,
source
.metadata()
.context("get source metadata")?
.permissions(),
)
.context("set target permissions")
}
}
// == Unix Filesystem ==
#[cfg(unix)]
pub struct RealFilesystem {
interactive: bool,
sudo_occurred: bool,
}
#[cfg(unix)]
impl RealFilesystem {
pub fn new(interactive: bool) -> RealFilesystem {
RealFilesystem {
sudo_occurred: false,
interactive,
}
}
fn sudo(&mut self, goal: impl AsRef<str>) -> Command {
if !self.sudo_occurred {
warn!("Elevating permissions ({})", goal.as_ref());
if !log_enabled!(log::Level::Debug) {
warn!("To see more than the first time elevated permissions are used, use verbosity 2 or more (-vv)");
}
self.sudo_occurred = true;
} else {
debug!("Elevating permissions ({})", goal.as_ref());
}
Command::new("sudo")
}
fn is_owned_by_user(&self, path: &Path) -> Result<bool> {
use std::os::unix::fs::MetadataExt;
let file_uid = path.metadata().context("get file metadata")?.uid();
let process_uid = unsafe { libc::geteuid() };
Ok(file_uid == process_uid)
}
}
#[cfg(unix)]
impl Filesystem for RealFilesystem {
fn compare_symlink(&mut self, source: &Path, link: &Path) -> Result<SymlinkComparison> {
let source_state = get_file_state(source).context("get source state")?;
let link_state = get_file_state(link).context("get link state")?;
let source = real_path(source).context("get real path of source")?;
Ok(compare_symlink(&source, source_state, link_state))
}
fn compare_template(&mut self, target: &Path, cache: &Path) -> Result<TemplateComparison> {
let target_state = get_file_state(target).context("get state of target")?;
let cache_state = get_file_state(cache).context("get state of cache")?;
Ok(compare_template(target_state, cache_state))
}
fn is_template(&mut self, source: &Path) -> Result<bool> {
is_template(source)
}
fn remove_file(&mut self, path: &Path) -> Result<()> {
let metadata = path.metadata().context("get metadata")?;
let result = if metadata.is_dir() {
std::fs::remove_dir_all(path)
} else {
std::fs::remove_file(path)
};
match result {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
let success = self
.sudo(format!("removing file {:?} as root", path))
.arg("rm")
.arg("-r")
.arg(path)
.spawn()
.context("spawn sudo rm command")?
.wait()
.context("wait for sudo rm command")?
.success();
anyhow::ensure!(success, "sudo rm command failed");
Ok(())
}
Err(e) => Err(e).context("remove file"),
}
}
fn read_to_string(&mut self, path: &Path) -> Result<String> {
fs::read_to_string(path).context("read from file")
}
fn write(&mut self, path: &Path, content: String) -> Result<()> {
fs::write(path, content).context("write to file")
}
fn delete_parents(&mut self, path: &Path, no_ask: bool) -> Result<()> {
let mut path = path.parent().context("get parent")?;
while path.is_dir()
&& path
.read_dir()
.context("read the contents of parent directory")?
.next()
.is_none()
{
if (!self.interactive || no_ask)
|| ask_boolean(&format!(
"Directory at {:?} is now empty. Delete [y/N]? ",
path
))
{
match std::fs::remove_dir(path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
let success = self
.sudo(format!("removing directory {:?}", path))
.arg("rmdir")
.arg(path)
.spawn()
.context("spawn sudo rmdir")?
.wait()
.context("wait for sudo rmdir")?
.success();
anyhow::ensure!(success, "sudo rmdir failed");
}
Err(e) => {
Err(e).context("remove dir")?;
}
}
}
path = path.parent().context(format!("get parent of {:?}", path))?;
}
Ok(())
}
fn make_symlink(&mut self, link: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()> {
use std::os::unix::fs;
if let Some(owner) = owner {
let success = self
.sudo(format!(
"creating symlink {:?} -> {:?} from user {:?}",
link, target, owner
))
.arg("-u")
.arg(owner.as_sudo_arg())
.arg("ln")
.arg("-s")
.arg(real_path(target).context("get real path of source file")?)
.arg(link)
.spawn()
.context("spawn sudo ln")?
.wait()
.context("wait for sudo ln")?
.success();
anyhow::ensure!(success, "sudo ln failed");
} else {
debug!(
"Creating symlink {:?} -> {:?} as current user...",
link, target
);
fs::symlink(
real_path(target).context("get real path of source file")?,
link,
)
.context("create symlink")?;
}
Ok(())
}
fn create_dir_all(&mut self, path: &Path, owner: &Option<UnixUser>) -> Result<()> {
if let Some(owner) = owner {
let success = self
.sudo(format!(
"Creating directory {:?} from user {:?}...",
path, owner
))
.arg("-u")
.arg(owner.as_sudo_arg())
.arg("mkdir")
.arg("-p")
.arg(path)
.spawn()
.context("spawn sudo mkdir")?
.wait()
.context("wait for sudo mkdir")?
.success();
anyhow::ensure!(success, "sudo mkdir failed");
} else {
debug!("Creating directory {:?} as current user...", path);
std::fs::create_dir_all(path).context("create directories")?;
}
Ok(())
}
fn copy_file(&mut self, source: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()> {
use std::io::Write;
if let Some(owner) = owner {
let contents = std::fs::read_to_string(source)
.context("read source file contents as current user")?;
let mut child = self
.sudo(format!(
"Copying {:?} -> {:?} as user {:?}",
source, target, owner
))
.arg("-u")
.arg(owner.as_sudo_arg())
.arg("tee")
.arg(target)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.spawn()
.context("spawn sudo tee")?;
// At this point we should've gone through another sudo at the mkdir step already,
// so sudo will not ask for the password
child
.stdin
.as_ref()
.expect("has stdin")
.write_all(contents.as_bytes())
.context("give input to tee")?;
let success = child.wait().context("wait for sudo tee")?.success();
anyhow::ensure!(success, "sudo tee failed");
} else {
debug!("Copying {:?} -> {:?} as current user", source, target);
std::fs::copy(source, target).context("copy file")?;
}
Ok(())
}
fn set_owner(&mut self, file: &Path, owner: &Option<UnixUser>) -> Result<()> {
if self
.is_owned_by_user(file)
.context("detect if file is owned by the current user")?
&& owner.is_none()
{
// Nothing to do, no need to elevate
return Ok(());
}
let owner = owner.clone().unwrap_or(UnixUser::Name(
std::env::var("USER").context("get USER env var")?,
));
let success = self
.sudo(format!("Setting owner of {:?} to {:?}...", file, owner))
.arg("chown")
.arg(owner.as_chown_arg())
.arg("-h") // no-dereference
.arg(file)
.spawn()
.context("spawn sudo chown command")?
.wait()
.context("wait for sudo chown command")?
.success();
anyhow::ensure!(success, "sudo chown command failed");
Ok(())
}
fn copy_permissions(
&mut self,
source: &Path,
target: &Path,
owner: &Option<UnixUser>,
) -> Result<()> {
if let Some(owner) = owner {
let success = self
.sudo(format!(
"Copying permissions {:?} -> {:?} as user {:?}",
source, target, owner
))
.arg("chmod")
.arg("--reference")
.arg(source)
.arg(target)
.spawn()
.context("spawn sudo chmod command")?
.wait()
.context("wait for sudo chmod command")?
.success();
anyhow::ensure!(success, "sudo chmod failed");
} else {
debug!(
"Copying permissions {:?} -> {:?} as current user",
source, target
);
std::fs::set_permissions(
target,
source
.metadata()
.context("get source metadata")?
.permissions(),
)
.context("set target permissions")?;
}
Ok(())
}
}
// == Dry run Filesystem ==
pub struct DryRunFilesystem {
file_states: BTreeMap<PathBuf, FileState>,
}
#[derive(Debug, Clone, PartialEq)]
enum FileState {
/// None if file is invalid UTF-8
File(Option<String>),
SymbolicLink(PathBuf),
Directory,
Missing,
}
impl DryRunFilesystem {
pub fn new() -> DryRunFilesystem {
DryRunFilesystem {
file_states: BTreeMap::new(),
}
}
fn get_state(&mut self, path: &Path) -> Result<FileState> {
match self.file_states.get(path) {
Some(state) => Ok(state.clone()),
None => get_file_state(path),
}
}
}
impl Filesystem for DryRunFilesystem {
fn compare_symlink(&mut self, source: &Path, link: &Path) -> Result<SymlinkComparison> {
let source_state = if let Some(state) = self.file_states.get(source) {
debug!("Cached (probably not actual) source state: {:?}", state);
state.clone()
} else {
let state = get_file_state(source).context("get source state")?;
debug!("Source state: {:?}", state);
state
};
let link_state = if let Some(state) = self.file_states.get(link) {
debug!("Cached (probably not actual) link state: {:?}", state);
state.clone()
} else {
let state = get_file_state(link).context("get link state")?;
debug!("Link state: {:?}", state);
state
};
let source = real_path(source).context("get real path of source")?;
Ok(compare_symlink(&source, source_state, link_state))
}
fn compare_template(&mut self, target: &Path, cache: &Path) -> Result<TemplateComparison> {
let target_state = if let Some(state) = self.file_states.get(target) {
debug!("Cached (probably not actual) target state: {:?}", state);
state.clone()
} else {
let state = get_file_state(target).context("get state of target")?;
debug!("Target state: {:?}", state);
state
};
let cache_state = if let Some(state) = self.file_states.get(cache) {
debug!("Cached (probably not actual) cache state: {:?}", state);
state.clone()
} else {
let state = get_file_state(cache).context("get state of cache")?;
debug!("Cache state: {:?}", state);
state
};
Ok(compare_template(target_state, cache_state))
}
fn is_template(&mut self, source: &Path) -> Result<bool> {
// This is fine because source files are never edited
is_template(source)
}
fn remove_file(&mut self, path: &Path) -> Result<()> {
debug!("Removing file {:?}", path);
self.file_states.insert(path.into(), FileState::Missing);
Ok(())
}
fn read_to_string(&mut self, path: &Path) -> Result<String> {
debug!("Reading contents of file {:?}", path);
match self.get_state(path).context("get file state")? {
FileState::File(s) => Ok(s.context("invalid utf-8 in template source")?),
_ => anyhow::bail!("writing to non-file"),
}
}
fn write(&mut self, path: &Path, content: String) -> Result<()> {
debug!("Writing contents {:?} to file {:?}", content, path);
self.file_states
.insert(path.into(), FileState::File(Some(content)));
Ok(())
}
fn delete_parents(&mut self, path: &Path, _no_ask: bool) -> Result<()> {
debug!(
"Recursively deleting parents of {:?} if they're empty",
path
);
Ok(())
}
fn make_symlink(&mut self, link: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()> {
debug!(
"Making symlink {:?} -> {:?} (owned by {:?})",
link, target, owner
);
self.file_states
.insert(link.into(), FileState::SymbolicLink(target.into()));
Ok(())
}
fn create_dir_all(&mut self, mut path: &Path, owner: &Option<UnixUser>) -> Result<()> {
debug!("Creating directory {:?} (owned by {:?})", path, owner);
self.file_states.insert(path.into(), FileState::Directory);
while path.parent().is_some() {
path = path.parent().unwrap();
self.file_states.insert(path.into(), FileState::Directory);
}
Ok(())
}
fn copy_file(&mut self, source: &Path, target: &Path, owner: &Option<UnixUser>) -> Result<()> {
debug!(
"Copying file {:?} -> {:?} (target owned by {:?})",
source, target, owner
);
match self.get_state(source).context("get state of source file")? {
FileState::File(content) => {
if self
.get_state(target.parent().context("get parent of target")?)
.context("get state of target's parent")?
== FileState::Directory
{
self.file_states
.insert(target.into(), FileState::File(content));
} else {
anyhow::bail!("target's parent is not a directory");
}
Ok(())
}
s @ FileState::SymbolicLink(_) | s @ FileState::Directory | s @ FileState::Missing => {
anyhow::bail!("file is not regular file but is a {:?}", s);
}
}
}
fn set_owner(&mut self, file: &Path, owner: &Option<UnixUser>) -> Result<()> {
debug!("Setting owner of file {:?} to {:?}", file, owner);
Ok(())
}
fn copy_permissions(
&mut self,
source: &Path,
target: &Path,
owner: &Option<UnixUser>,
) -> Result<()> {
debug!(
"Copying permissions on files {:?} -> {:?} (target owned by {:?})",
source, target, owner
);
Ok(())
}
}
// === Comparisons ===
fn get_file_state(path: &Path) -> Result<FileState> {
if let Ok(target) = fs::read_link(&path) {
return Ok(FileState::SymbolicLink(target));
}
if path.is_dir() {
return Ok(FileState::Directory);
}
match fs::read_to_string(path) {
Ok(f) => Ok(FileState::File(Some(f))),
Err(e) if e.kind() == ErrorKind::InvalidData => Ok(FileState::File(None)),
Err(e) if e.kind() == ErrorKind::NotFound => Ok(FileState::Missing),
Err(e) => Err(e).context("read contents of file that isn't symbolic or directory")?,
}
}
#[derive(Debug, PartialEq)]
pub enum SymlinkComparison {
Identical,
OnlySourceExists,
OnlyTargetExists,
TargetNotSymlink,
Changed,
BothMissing,
}
impl std::fmt::Display for SymlinkComparison {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
use self::SymlinkComparison::*;
match self {
Identical => "target points at source",
OnlySourceExists => "target missing",
OnlyTargetExists => "source is missing",
TargetNotSymlink => "target isn't a symlink",
Changed => "target exists and doesn't point at source",
BothMissing => "source and target are missing",
}
.fmt(f)
}
}
fn compare_symlink(
source_path: &Path,
source_state: FileState,
link_state: FileState,
) -> SymlinkComparison {
match (source_state, link_state) {
(FileState::Missing, FileState::SymbolicLink(_)) => SymlinkComparison::OnlyTargetExists,
(_, FileState::SymbolicLink(t)) => {
if t == source_path {
SymlinkComparison::Identical
} else {
SymlinkComparison::Changed
}
}
(FileState::Missing, FileState::Missing) => SymlinkComparison::BothMissing,
(_, FileState::Missing) => SymlinkComparison::OnlySourceExists,
_ => SymlinkComparison::TargetNotSymlink,
}
}
#[derive(Debug, PartialEq)]
pub enum TemplateComparison {
Identical,
OnlyCacheExists,
OnlyTargetExists,
Changed,
TargetNotRegularFile,
BothMissing,
}
impl std::fmt::Display for TemplateComparison {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
use self::TemplateComparison::*;
match self {
Identical => "target and cache's contents are equal",
OnlyCacheExists => "target doesn't exist",
OnlyTargetExists => "cache doesn't exist",
Changed => "target contents were changed",
TargetNotRegularFile => "target is a symbolic link or directory",
BothMissing => "cache and target are missing",
}
.fmt(f)
}
}
fn compare_template(target_state: FileState, cache_state: FileState) -> TemplateComparison {
match (target_state, cache_state) {
(FileState::File(t), FileState::File(c)) => {
if t == c {
TemplateComparison::Identical
} else {
TemplateComparison::Changed
}
}
(FileState::File(_), FileState::Missing) => TemplateComparison::OnlyTargetExists,
(FileState::Missing, FileState::File(_)) => TemplateComparison::OnlyCacheExists,
(FileState::Missing, FileState::Missing) => TemplateComparison::BothMissing,
_ => TemplateComparison::TargetNotRegularFile,
}
}
/// === Utility functions ===
pub fn real_path(path: &Path) -> Result<PathBuf, io::Error> {
let path = std::fs::canonicalize(&path)?;
Ok(platform_dunce(&path))
}
pub fn ask_boolean(prompt: &str) -> bool {
let mut buf = String::from("a"); // enter the loop at least once
while !(buf.to_lowercase().starts_with('y')
|| buf.to_lowercase().starts_with('n')
|| buf.is_empty())
{
eprintln!("{}", prompt);
buf.clear();
io::stdin()
.read_line(&mut buf)
.expect("Failed to read line from stdin");
}
// If empty defaults to no
buf.to_lowercase().starts_with('y')
}
fn is_template(source: &Path) -> Result<bool> {
let mut file = File::open(source).context("open file")?;
let mut buf = String::new();
if file.read_to_string(&mut buf).is_err() {
warn!("File {:?} is not valid UTF-8 - detecting as symlink. Explicitly specify it to silence this message.", source);
Ok(false)
} else {
Ok(buf.contains("{{"))
}
}
#[cfg(windows)]
pub fn symlinks_enabled(test_file_path: &Path) -> Result<bool> {
use std::os::windows::fs;
debug!(
"Testing whether symlinks are enabled on path {:?}",
test_file_path
);
let _ = std::fs::remove_file(&test_file_path);
match fs::symlink_file("test.txt", &test_file_path) {
Ok(()) => {
std::fs::remove_file(&test_file_path)
.context(format!("remove test file {:?}", test_file_path))?;
Ok(true)
}
Err(e) => {
// os error 1314: A required privilege is not held by the client.
if e.raw_os_error() == Some(1314) {
Ok(false)
} else {
Err(e).context(format!("create test symlink at {:?}", test_file_path))
}
}
}
}
#[cfg(unix)]
pub fn symlinks_enabled(_test_file_path: &Path) -> Result<bool> {
Ok(true)
}
#[cfg(windows)]
pub fn platform_dunce(path: &Path) -> PathBuf {
dunce::simplified(&path).into()
}
#[cfg(unix)]
pub fn platform_dunce(path: &Path) -> PathBuf {
path.into()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn simple_remove() {
let mut fs = DryRunFilesystem::new();
fs.remove_file(&PathBuf::from("test")).unwrap();
assert_eq!(
fs.file_states.get(&PathBuf::from("test")),
Some(&FileState::Missing)
);
}
#[test]
fn simple_write_read() {
let mut fs = DryRunFilesystem::new();
fs.write(&PathBuf::from("test"), "hello world!".into())
.unwrap();
assert_eq!(
fs.read_to_string(&PathBuf::from("test")).unwrap(),
"hello world!"
);
}
#[test]
fn simple_create_dir_all() {
let mut fs = DryRunFilesystem::new();
fs.create_dir_all(&PathBuf::from("/home/user/.config"), &None)
.unwrap();
assert_eq!(
fs.get_state(&PathBuf::from("/home")).unwrap(),
FileState::Directory
);
assert_eq!(
fs.get_state(&PathBuf::from("/home/user")).unwrap(),
FileState::Directory
);
assert_eq!(
fs.get_state(&PathBuf::from("/home/user/.config")).unwrap(),
FileState::Directory
);
}
#[test]
fn full_dry_run() {
// Emulate creating new template
let mut fs = DryRunFilesystem::new();
fs.write(&PathBuf::from("source"), "{{name}}".into())
.unwrap();
fs.remove_file(&PathBuf::from("target_dir/target")).unwrap();
assert_eq!(
fs.compare_template(
&PathBuf::from("target_dir/target"),
&PathBuf::from("cache_dir/cache")
)
.unwrap(),
TemplateComparison::BothMissing
);
fs.create_dir_all(&PathBuf::from("target_dir"), &None)
.unwrap();
// perform_template_deploy
assert_eq!(
fs.read_to_string(&PathBuf::from("source")).unwrap(),
"{{name}}"
);
let rendered = String::from("John");
// cache
fs.create_dir_all(&PathBuf::from("cache_dir"), &None)
.unwrap();
fs.write(&PathBuf::from("cache_dir/cache"), rendered)
.unwrap();
// target
fs.copy_file(
&PathBuf::from("cache_dir/cache"),
&PathBuf::from("target_dir/target"),
&None,
)
.unwrap();
fs.copy_permissions(
&PathBuf::from("source"),
&PathBuf::from("target_dir/target"),
&None,
)
.unwrap();
// Verify all actions
assert_eq!(
fs.file_states.get(&PathBuf::from("source")),
Some(&FileState::File(Some("{{name}}".into())))
);
assert_eq!(
fs.file_states.get(&PathBuf::from("cache_dir")),
Some(&FileState::Directory)
);
assert_eq!(
fs.file_states.get(&PathBuf::from("cache_dir/cache")),
Some(&FileState::File(Some("John".into())))
);
assert_eq!(
fs.file_states.get(&PathBuf::from("target_dir")),