-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathsnapshotfile.rs
1282 lines (1132 loc) · 38.9 KB
/
snapshotfile.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 std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt::{self, Display},
path::{Path, PathBuf},
str::FromStr,
};
use chrono::{DateTime, Duration, Local};
use derivative::Derivative;
use derive_setters::Setters;
use dunce::canonicalize;
use gethostname::gethostname;
use itertools::Itertools;
use log::info;
use path_dedot::ParseDot;
use serde_derive::{Deserialize, Serialize};
use serde_with::{serde_as, skip_serializing_none, DisplayFromStr};
use crate::{
backend::{decrypt::DecryptReadBackend, FileType, FindInBackend},
error::{RusticError, RusticResult, SnapshotFileErrorKind},
id::Id,
progress::Progress,
repofile::RepoFile,
};
#[cfg(feature = "clap")]
use clap::ValueHint;
/// Options for creating a new [`SnapshotFile`] structure for a new backup snapshot.
///
/// This struct derives [`serde::Deserialize`] allowing to use it in config files.
///
/// # Features
///
/// * With the feature `merge` enabled, this also derives [`merge::Merge`] to allow merging [`SnapshotOptions`] from multiple sources.
/// * With the feature `clap` enabled, this also derives [`clap::Parser`] allowing it to be used as CLI options.
///
/// # Note
///
/// The preferred way is to use [`SnapshotFile::from_options`] to create a SnapshotFile for a new backup.
#[serde_as]
#[cfg_attr(feature = "merge", derive(merge::Merge))]
#[cfg_attr(feature = "clap", derive(clap::Parser))]
#[derive(Deserialize, Serialize, Clone, Default, Debug, Setters)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
#[setters(into)]
#[non_exhaustive]
pub struct SnapshotOptions {
/// Label snapshot with given label
#[cfg_attr(feature = "clap", clap(long, value_name = "LABEL"))]
pub label: Option<String>,
/// Tags to add to snapshot (can be specified multiple times)
#[serde_as(as = "Vec<DisplayFromStr>")]
#[cfg_attr(feature = "clap", clap(long = "tag", value_name = "TAG[,TAG,..]"))]
#[cfg_attr(feature = "merge", merge(strategy = merge::vec::overwrite_empty))]
pub tags: Vec<StringList>,
/// Add description to snapshot
#[cfg_attr(feature = "clap", clap(long, value_name = "DESCRIPTION"))]
pub description: Option<String>,
/// Add description to snapshot from file
#[cfg_attr(
feature = "clap",
clap(long, value_name = "FILE", conflicts_with = "description", value_hint = ValueHint::FilePath)
)]
pub description_from: Option<PathBuf>,
/// Set the backup time manually
#[cfg_attr(feature = "clap", clap(long))]
pub time: Option<DateTime<Local>>,
/// Mark snapshot as uneraseable
#[cfg_attr(feature = "clap", clap(long, conflicts_with = "delete_after"))]
#[cfg_attr(feature = "merge", merge(strategy = merge::bool::overwrite_false))]
pub delete_never: bool,
/// Mark snapshot to be deleted after given duration (e.g. 10d)
#[cfg_attr(feature = "clap", clap(long, value_name = "DURATION"))]
#[serde_as(as = "Option<DisplayFromStr>")]
pub delete_after: Option<humantime::Duration>,
/// Set the host name manually
#[cfg_attr(feature = "clap", clap(long, value_name = "NAME"))]
pub host: Option<String>,
/// Set the backup command manually
#[cfg_attr(feature = "clap", clap(long))]
pub command: Option<String>,
}
impl SnapshotOptions {
/// Add tags to this [`SnapshotOptions`]
///
/// # Arguments
///
/// * `tag` - The tag to add
///
/// # Errors
///
/// * [`SnapshotFileErrorKind::NonUnicodeTag`] - If the tag is not valid unicode
///
/// # Returns
///
/// The modified [`SnapshotOptions`]
///
/// [`SnapshotFileErrorKind::NonUnicodeTag`]: crate::error::SnapshotFileErrorKind::NonUnicodeTag
pub fn add_tags(mut self, tag: &str) -> RusticResult<Self> {
self.tags.push(StringList::from_str(tag)?);
Ok(self)
}
/// Create a new [`SnapshotFile`] using this `SnapshotOption`s
///
/// # Errors
///
/// * [`SnapshotFileErrorKind::NonUnicodeHostname`] - If the hostname is not valid unicode
///
/// # Returns
///
/// The new [`SnapshotFile`]
///
/// [`SnapshotFileErrorKind::NonUnicodeHostname`]: crate::error::SnapshotFileErrorKind::NonUnicodeHostname
pub fn to_snapshot(&self) -> RusticResult<SnapshotFile> {
SnapshotFile::from_options(self)
}
}
/// Summary information about a snapshot.
///
/// This is an extended version of the summaryOutput structure of restic in
/// restic/internal/ui/backup$/json.go
#[derive(Serialize, Deserialize, Debug, Clone, Derivative)]
#[serde(default)]
#[derivative(Default)]
#[non_exhaustive]
pub struct SnapshotSummary {
/// New files compared to the last (i.e. parent) snapshot
pub files_new: u64,
/// Changed files compared to the last (i.e. parent) snapshot
pub files_changed: u64,
/// Unchanged files compared to the last (i.e. parent) snapshot
pub files_unmodified: u64,
/// Total processed files
pub total_files_processed: u64,
/// Total size of all processed files
pub total_bytes_processed: u64,
/// New directories compared to the last (i.e. parent) snapshot
pub dirs_new: u64,
/// Changed directories compared to the last (i.e. parent) snapshot
pub dirs_changed: u64,
/// Unchanged directories compared to the last (i.e. parent) snapshot
pub dirs_unmodified: u64,
/// Total processed directories
pub total_dirs_processed: u64,
/// Total number of data blobs added by this snapshot
pub total_dirsize_processed: u64,
/// Total size of all processed dirs
pub data_blobs: u64,
/// Total number of tree blobs added by this snapshot
pub tree_blobs: u64,
/// Total uncompressed bytes added by this snapshot
pub data_added: u64,
/// Total bytes added to the repository by this snapshot
pub data_added_packed: u64,
/// Total uncompressed bytes (new/changed files) added by this snapshot
pub data_added_files: u64,
/// Total bytes for new/changed files added to the repository by this snapshot
pub data_added_files_packed: u64,
/// Total uncompressed bytes (new/changed directories) added by this snapshot
pub data_added_trees: u64,
/// Total bytes (new/changed directories) added to the repository by this snapshot
pub data_added_trees_packed: u64,
/// The command used to make this backup
pub command: String,
/// Start time of the backup.
///
/// # Note
///
/// This may differ from the snapshot `time`.
#[derivative(Default(value = "Local::now()"))]
pub backup_start: DateTime<Local>,
/// The time that the backup has been finished.
#[derivative(Default(value = "Local::now()"))]
pub backup_end: DateTime<Local>,
/// Total duration of the backup in seconds, i.e. the time between `backup_start` and `backup_end`
pub backup_duration: f64,
/// Total duration that the rustic command ran in seconds
pub total_duration: f64,
}
impl SnapshotSummary {
/// Create a new [`SnapshotSummary`].
///
/// # Arguments
///
/// * `snap_time` - The time of the snapshot
///
/// # Errors
///
/// * [`SnapshotFileErrorKind::OutOfRange`] - If the time is not in the range of `Local::now()`
///
/// [`SnapshotFileErrorKind::OutOfRange`]: crate::error::SnapshotFileErrorKind::OutOfRange
pub(crate) fn finalize(&mut self, snap_time: DateTime<Local>) -> RusticResult<()> {
let end_time = Local::now();
self.backup_duration = (end_time - self.backup_start)
.to_std()
.map_err(SnapshotFileErrorKind::OutOfRange)?
.as_secs_f64();
self.total_duration = (end_time - snap_time)
.to_std()
.map_err(SnapshotFileErrorKind::OutOfRange)?
.as_secs_f64();
self.backup_end = end_time;
Ok(())
}
}
/// Options for deleting snapshots.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Derivative, Copy)]
#[derivative(Default)]
pub enum DeleteOption {
/// No delete option set.
#[derivative(Default)]
NotSet,
/// This snapshot should be never deleted (remove-protection).
Never,
/// Remove this snapshot after the given timestamp, but prevent removing it before.
After(DateTime<Local>),
}
impl DeleteOption {
/// Returns whether the delete option is set to `NotSet`.
const fn is_not_set(&self) -> bool {
matches!(self, Self::NotSet)
}
}
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, Derivative)]
#[derivative(Default)]
/// A [`SnapshotFile`] is the repository representation of the snapshot metadata saved in a repository.
///
/// It is usually saved in the repository under `snapshot/<ID>`
///
/// # Note
///
/// [`SnapshotFile`] implements [`Eq`], [`PartialEq`], [`Ord`], [`PartialOrd`] by comparing only the `time` field.
/// If you need another ordering, you have to implement that yourself.
pub struct SnapshotFile {
#[derivative(Default(value = "Local::now()"))]
/// Timestamp of this snapshot
pub time: DateTime<Local>,
/// Program identifier and its version that have been used to create this snapshot.
#[derivative(Default(
value = "\"rustic \".to_string() + option_env!(\"PROJECT_VERSION\").unwrap_or(env!(\"CARGO_PKG_VERSION\"))"
))]
#[serde(default, skip_serializing_if = "String::is_empty")]
pub program_version: String,
/// The Id of the parent snapshot that this snapshot has been based on
pub parent: Option<Id>,
/// The tree blob id where the contents of this snapshot are stored
pub tree: Id,
/// Label for the snapshot
#[serde(default, skip_serializing_if = "String::is_empty")]
pub label: String,
/// The list of paths contained in this snapshot
pub paths: StringList,
/// The hostname of the device on which the snapshot has been created
#[serde(default)]
pub hostname: String,
/// The username that started the backup run
#[serde(default)]
pub username: String,
/// The uid of the username that started the backup run
#[serde(default)]
pub uid: u32,
/// The gid of the username that started the backup run
#[serde(default)]
pub gid: u32,
/// A list of tags for this snapshot
#[serde(default)]
pub tags: StringList,
/// The original Id of this snapshot. This is stored when the snapshot is modified.
pub original: Option<Id>,
/// Options for deletion of the snapshot
#[serde(default, skip_serializing_if = "DeleteOption::is_not_set")]
pub delete: DeleteOption,
/// Summary information about the backup run
pub summary: Option<SnapshotSummary>,
/// A description of what is contained in this snapshot
pub description: Option<String>,
/// The snapshot Id (not stored within the JSON)
#[serde(default, skip_serializing_if = "Id::is_null")]
pub id: Id,
}
impl RepoFile for SnapshotFile {
/// The file type of a [`SnapshotFile`] is always [`FileType::Snapshot`]
const TYPE: FileType = FileType::Snapshot;
}
impl SnapshotFile {
/// Create a [`SnapshotFile`] from [`SnapshotOptions`].
///
/// # Arguments
///
/// * `opts` - The [`SnapshotOptions`] to use
///
/// # Errors
///
/// * [`SnapshotFileErrorKind::NonUnicodeHostname`] - If the hostname is not valid unicode
/// * [`SnapshotFileErrorKind::OutOfRange`] - If the delete time is not in the range of `Local::now()`
/// * [`SnapshotFileErrorKind::ReadingDescriptionFailed`] - If the description file could not be read
///
/// # Note
///
/// This is the preferred way to create a new [`SnapshotFile`] to be used within [`crate::Repository::backup`].
///
/// [`SnapshotFileErrorKind::NonUnicodeHostname`]: crate::error::SnapshotFileErrorKind::NonUnicodeHostname
/// [`SnapshotFileErrorKind::OutOfRange`]: crate::error::SnapshotFileErrorKind::OutOfRange
/// [`SnapshotFileErrorKind::ReadingDescriptionFailed`]: crate::error::SnapshotFileErrorKind::ReadingDescriptionFailed
pub fn from_options(opts: &SnapshotOptions) -> RusticResult<Self> {
let hostname = if let Some(host) = &opts.host {
host.clone()
} else {
let hostname = gethostname();
hostname
.to_str()
.ok_or_else(|| SnapshotFileErrorKind::NonUnicodeHostname(hostname.clone()))?
.to_string()
};
let time = opts.time.unwrap_or_else(Local::now);
let delete = match (opts.delete_never, opts.delete_after) {
(true, _) => DeleteOption::Never,
(_, Some(d)) => DeleteOption::After(
time + Duration::from_std(*d).map_err(SnapshotFileErrorKind::OutOfRange)?,
),
(false, None) => DeleteOption::NotSet,
};
let command: String = opts.command.as_ref().map_or_else(
|| {
std::env::args_os()
.map(|s| s.to_string_lossy().to_string())
.collect::<Vec<_>>()
.join(" ")
},
Clone::clone,
);
let mut snap = Self {
time,
hostname,
label: opts.label.clone().unwrap_or_default(),
delete,
summary: Some(SnapshotSummary {
command,
..Default::default()
}),
description: opts.description.clone(),
..Default::default()
};
// use description from description file if it is given
if let Some(ref file) = opts.description_from {
snap.description = Some(
std::fs::read_to_string(file)
.map_err(SnapshotFileErrorKind::ReadingDescriptionFailed)?,
);
}
_ = snap.set_tags(opts.tags.clone());
Ok(snap)
}
/// Create a [`SnapshotFile`] from a given [`Id`] and [`RepoFile`].
///
/// # Arguments
///
/// * `tuple` - A tuple of the [`Id`] and the [`RepoFile`] to use
fn set_id(tuple: (Id, Self)) -> Self {
let (id, mut snap) = tuple;
snap.id = id;
_ = snap.original.get_or_insert(id);
snap
}
/// Get a [`SnapshotFile`] from the backend
///
/// # Arguments
///
/// * `be` - The backend to use
/// * `id` - The id of the snapshot
fn from_backend<B: DecryptReadBackend>(be: &B, id: &Id) -> RusticResult<Self> {
Ok(Self::set_id((*id, be.get_file(id)?)))
}
/// Get a [`SnapshotFile`] from the backend by (part of the) Id
///
/// # Arguments
///
/// * `be` - The backend to use
/// * `string` - The (part of the) id of the snapshot
/// * `predicate` - A predicate to filter the snapshots
/// * `p` - A progress bar to use
///
/// # Errors
///
/// * [`IdErrorKind::HexError`] - If the string is not a valid hexadecimal string
/// * [`BackendAccessErrorKind::NoSuitableIdFound`] - If no id could be found.
/// * [`BackendAccessErrorKind::IdNotUnique`] - If the id is not unique.
///
/// [`IdErrorKind::HexError`]: crate::error::IdErrorKind::HexError
/// [`BackendAccessErrorKind::NoSuitableIdFound`]: crate::error::BackendAccessErrorKind::NoSuitableIdFound
/// [`BackendAccessErrorKind::IdNotUnique`]: crate::error::BackendAccessErrorKind::IdNotUnique
pub(crate) fn from_str<B: DecryptReadBackend>(
be: &B,
string: &str,
predicate: impl FnMut(&Self) -> bool + Send + Sync,
p: &impl Progress,
) -> RusticResult<Self> {
match string {
"latest" => Self::latest(be, predicate, p),
_ => Self::from_id(be, string),
}
}
/// Get the latest [`SnapshotFile`] from the backend
///
/// # Arguments
///
/// * `be` - The backend to use
/// * `predicate` - A predicate to filter the snapshots
/// * `p` - A progress bar to use
///
/// # Errors
///
/// * [`SnapshotFileErrorKind::NoSnapshotsFound`] - If no snapshots are found
///
/// [`SnapshotFileErrorKind::NoSnapshotsFound`]: crate::error::SnapshotFileErrorKind::NoSnapshotsFound
pub(crate) fn latest<B: DecryptReadBackend>(
be: &B,
predicate: impl FnMut(&Self) -> bool + Send + Sync,
p: &impl Progress,
) -> RusticResult<Self> {
p.set_title("getting latest snapshot...");
let mut latest: Option<Self> = None;
let mut pred = predicate;
for snap in be.stream_all::<Self>(p)? {
let (id, mut snap) = snap?;
if !pred(&snap) {
continue;
}
snap.id = id;
match &latest {
Some(l) if l.time > snap.time => {}
_ => {
latest = Some(snap);
}
}
}
p.finish();
latest.ok_or_else(|| SnapshotFileErrorKind::NoSnapshotsFound.into())
}
/// Get a [`SnapshotFile`] from the backend by (part of the) id
///
/// # Arguments
///
/// * `be` - The backend to use
/// * `id` - The (part of the) id of the snapshot
///
/// # Errors
/// * [`IdErrorKind::HexError`] - If the string is not a valid hexadecimal string
/// * [`BackendAccessErrorKind::NoSuitableIdFound`] - If no id could be found.
/// * [`BackendAccessErrorKind::IdNotUnique`] - If the id is not unique.
///
/// [`IdErrorKind::HexError`]: crate::error::IdErrorKind::HexError
/// [`BackendAccessErrorKind::NoSuitableIdFound`]: crate::error::BackendAccessErrorKind::NoSuitableIdFound
/// [`BackendAccessErrorKind::IdNotUnique`]: crate::error::BackendAccessErrorKind::IdNotUnique
pub(crate) fn from_id<B: DecryptReadBackend>(be: &B, id: &str) -> RusticResult<Self> {
info!("getting snapshot...");
let id = be.find_id(FileType::Snapshot, id)?;
Self::from_backend(be, &id)
}
/// Get a list of [`SnapshotFile`]s from the backend by supplying a list of/parts of their Ids
///
/// # Arguments
///
/// * `be` - The backend to use
/// * `ids` - The list of (parts of the) ids of the snapshots
/// * `p` - A progress bar to use
///
/// # Errors
///
/// * [`IdErrorKind::HexError`] - If the string is not a valid hexadecimal string
/// * [`BackendAccessErrorKind::NoSuitableIdFound`] - If no id could be found.
/// * [`BackendAccessErrorKind::IdNotUnique`] - If the id is not unique.
///
/// [`IdErrorKind::HexError`]: crate::error::IdErrorKind::HexError
/// [`BackendAccessErrorKind::NoSuitableIdFound`]: crate::error::BackendAccessErrorKind::NoSuitableIdFound
/// [`BackendAccessErrorKind::IdNotUnique`]: crate::error::BackendAccessErrorKind::IdNotUnique
pub(crate) fn from_ids<B: DecryptReadBackend, T: AsRef<str>>(
be: &B,
ids: &[T],
p: &impl Progress,
) -> RusticResult<Vec<Self>> {
let ids = be.find_ids(FileType::Snapshot, ids)?;
let mut list: BTreeMap<_, _> =
be.stream_list::<Self>(&ids, p)?.into_iter().try_collect()?;
// sort back to original order
Ok(ids
.into_iter()
.filter_map(|id| list.remove_entry(&id))
.map(Self::set_id)
.collect())
}
/// Compare two [`SnapshotFile`]s by criteria from [`SnapshotGroupCriterion`].
///
/// # Arguments
///
/// * `crit` - The criteria to use for comparison
/// * `other` - The other [`SnapshotFile`] to compare to
///
/// # Returns
///
/// The ordering of the two [`SnapshotFile`]s
#[must_use]
pub fn cmp_group(&self, crit: SnapshotGroupCriterion, other: &Self) -> Ordering {
if crit.hostname {
self.hostname.cmp(&other.hostname)
} else {
Ordering::Equal
}
.then_with(|| {
if crit.label {
self.label.cmp(&other.label)
} else {
Ordering::Equal
}
})
.then_with(|| {
if crit.paths {
self.paths.cmp(&other.paths)
} else {
Ordering::Equal
}
})
.then_with(|| {
if crit.tags {
self.tags.cmp(&other.tags)
} else {
Ordering::Equal
}
})
}
/// Check if the [`SnapshotFile`] is in the given [`SnapshotGroup`].
///
/// # Arguments
///
/// * `group` - The [`SnapshotGroup`] to check
#[must_use]
pub fn has_group(&self, group: &SnapshotGroup) -> bool {
group
.hostname
.as_ref()
.map_or(true, |val| val == &self.hostname)
&& group.label.as_ref().map_or(true, |val| val == &self.label)
&& group.paths.as_ref().map_or(true, |val| val == &self.paths)
&& group.tags.as_ref().map_or(true, |val| val == &self.tags)
}
/// Get [`SnapshotFile`]s which match the filter grouped by the group criterion
/// from the backend
///
/// # Arguments
///
/// * `be` - The backend to use
/// * `filter` - A filter to filter the snapshots
/// * `crit` - The criteria to use for grouping
/// * `p` - A progress bar to use
pub(crate) fn group_from_backend<B, F>(
be: &B,
filter: F,
crit: SnapshotGroupCriterion,
p: &impl Progress,
) -> RusticResult<Vec<(SnapshotGroup, Vec<Self>)>>
where
B: DecryptReadBackend,
F: FnMut(&Self) -> bool,
{
let mut snaps = Self::all_from_backend(be, filter, p)?;
snaps.sort_unstable_by(|sn1, sn2| sn1.cmp_group(crit, sn2));
let mut result = Vec::new();
for (group, snaps) in &snaps
.into_iter()
.chunk_by(|sn| SnapshotGroup::from_snapshot(sn, crit))
{
result.push((group, snaps.collect()));
}
Ok(result)
}
// TODO: add documentation!
pub(crate) fn all_from_backend<B, F>(
be: &B,
filter: F,
p: &impl Progress,
) -> RusticResult<Vec<Self>>
where
B: DecryptReadBackend,
F: FnMut(&Self) -> bool,
{
be.stream_all::<Self>(p)?
.into_iter()
.map_ok(Self::set_id)
.filter_ok(filter)
.try_collect()
}
/// Add tag lists to snapshot.
///
/// # Arguments
///
/// * `tag_lists` - The tag lists to add
///
/// # Returns
///
/// Returns whether snapshot was changed.
pub fn add_tags(&mut self, tag_lists: Vec<StringList>) -> bool {
let old_tags = self.tags.clone();
self.tags.add_all(tag_lists);
old_tags != self.tags
}
/// Set tag lists to snapshot.
///
/// # Arguments
///
/// * `tag_lists` - The tag lists to set
///
/// # Returns
///
/// Returns whether snapshot was changed.
pub fn set_tags(&mut self, tag_lists: Vec<StringList>) -> bool {
let old_tags = std::mem::take(&mut self.tags);
self.tags.add_all(tag_lists);
old_tags != self.tags
}
/// Remove tag lists from snapshot.
///
/// # Arguments
///
/// * `tag_lists` - The tag lists to remove
///
/// # Returns
///
/// Returns whether snapshot was changed.
pub fn remove_tags(&mut self, tag_lists: &[StringList]) -> bool {
let old_tags = self.tags.clone();
self.tags.remove_all(tag_lists);
old_tags != self.tags
}
/// Returns whether a snapshot must be deleted now
///
/// # Arguments
///
/// * `now` - The current time
#[must_use]
pub fn must_delete(&self, now: DateTime<Local>) -> bool {
matches!(self.delete,DeleteOption::After(time) if time < now)
}
/// Returns whether a snapshot must be kept now
///
/// # Arguments
///
/// * `now` - The current time
#[must_use]
pub fn must_keep(&self, now: DateTime<Local>) -> bool {
match self.delete {
DeleteOption::Never => true,
DeleteOption::After(time) if time >= now => true,
_ => false,
}
}
/// Modifies the snapshot setting/adding/removing tag(s) and modifying [`DeleteOption`]s.
///
/// # Arguments
///
/// * `set` - The tags to set
/// * `add` - The tags to add
/// * `remove` - The tags to remove
/// * `delete` - The delete option to set
///
/// # Returns
///
/// `None` if the snapshot was not changed and
/// `Some(snap)` with a copy of the changed snapshot if it was changed.
pub fn modify_sn(
&mut self,
set: Vec<StringList>,
add: Vec<StringList>,
remove: &[StringList],
delete: &Option<DeleteOption>,
) -> Option<Self> {
let mut changed = false;
if !set.is_empty() {
changed |= self.set_tags(set);
}
changed |= self.add_tags(add);
changed |= self.remove_tags(remove);
if let Some(delete) = delete {
if &self.delete != delete {
self.delete = *delete;
changed = true;
}
}
changed.then_some(self.clone())
}
/// Clear ids which are not saved by the copy command (and not compared when checking if snapshots already exist in the copy target)
///
/// # Arguments
///
/// * `sn` - The snapshot to clear the ids from
#[must_use]
pub(crate) fn clear_ids(mut sn: Self) -> Self {
sn.id = Id::default();
sn.parent = None;
sn
}
}
impl PartialEq<Self> for SnapshotFile {
fn eq(&self, other: &Self) -> bool {
self.time.eq(&other.time)
}
}
impl Eq for SnapshotFile {}
impl PartialOrd for SnapshotFile {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SnapshotFile {
fn cmp(&self, other: &Self) -> Ordering {
self.time.cmp(&other.time)
}
}
/// [`SnapshotGroupCriterion`] determines how to group snapshots.
///
/// `Default` grouping is by hostname, label and paths.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Debug, Copy, Setters)]
#[setters(into)]
#[non_exhaustive]
pub struct SnapshotGroupCriterion {
/// Whether to group by hostnames
pub hostname: bool,
/// Whether to group by labels
pub label: bool,
/// Whether to group by paths
pub paths: bool,
/// Whether to group by tags
pub tags: bool,
}
impl SnapshotGroupCriterion {
/// Create a new empty `SnapshotGroupCriterion`
#[must_use]
pub fn new() -> Self {
Self {
hostname: false,
label: false,
paths: false,
tags: false,
}
}
}
impl Default for SnapshotGroupCriterion {
fn default() -> Self {
Self {
hostname: true,
label: true,
paths: true,
tags: false,
}
}
}
impl FromStr for SnapshotGroupCriterion {
type Err = RusticError;
fn from_str(s: &str) -> RusticResult<Self> {
let mut crit = Self::new();
for val in s.split(',') {
match val {
"host" => crit.hostname = true,
"label" => crit.label = true,
"paths" => crit.paths = true,
"tags" => crit.tags = true,
"" => continue,
v => return Err(SnapshotFileErrorKind::ValueNotAllowed(v.into()).into()),
}
}
Ok(crit)
}
}
impl Display for SnapshotGroupCriterion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut display = Vec::new();
if self.hostname {
display.push("host");
}
if self.label {
display.push("label");
}
if self.paths {
display.push("paths");
}
if self.tags {
display.push("tags");
}
write!(f, "{}", display.join(","))?;
Ok(())
}
}
#[skip_serializing_none]
#[derive(Serialize, Default, Debug, PartialEq, Eq)]
#[non_exhaustive]
/// [`SnapshotGroup`] specifies the group after a grouping using [`SnapshotGroupCriterion`].
pub struct SnapshotGroup {
/// Group hostname, if grouped by hostname
pub hostname: Option<String>,
/// Group label, if grouped by label
pub label: Option<String>,
/// Group paths, if grouped by paths
pub paths: Option<StringList>,
/// Group tags, if grouped by tags
pub tags: Option<StringList>,
}
impl Display for SnapshotGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut out = Vec::new();
if let Some(host) = &self.hostname {
out.push(format!("host [{host}]"));
}
if let Some(label) = &self.label {
out.push(format!("label [{label}]"));
}
if let Some(paths) = &self.paths {
out.push(format!("paths [{paths}]"));
}
if let Some(tags) = &self.tags {
out.push(format!("tags [{tags}]"));
}
write!(f, "({})", out.join(", "))?;
Ok(())
}
}
impl SnapshotGroup {
/// Extracts the suitable [`SnapshotGroup`] from a [`SnapshotFile`] using a given [`SnapshotGroupCriterion`].
///
/// # Arguments
///
/// * `sn` - The [`SnapshotFile`] to extract the [`SnapshotGroup`] from
/// * `crit` - The [`SnapshotGroupCriterion`] to use
#[must_use]
pub fn from_snapshot(sn: &SnapshotFile, crit: SnapshotGroupCriterion) -> Self {
Self {
hostname: crit.hostname.then(|| sn.hostname.clone()),
label: crit.label.then(|| sn.label.clone()),
paths: crit.paths.then(|| sn.paths.clone()),
tags: crit.tags.then(|| sn.tags.clone()),
}
}
/// Returns whether this is an empty group, i.e. no grouping information is contained.
#[must_use]
pub fn is_empty(&self) -> bool {
self == &Self::default()
}
}
/// `StringList` is a rustic-internal list of Strings. It is used within [`SnapshotFile`]
#[derive(Serialize, Deserialize, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct StringList(pub(crate) BTreeSet<String>);
impl FromStr for StringList {
type Err = RusticError;
fn from_str(s: &str) -> RusticResult<Self> {
Ok(Self(s.split(',').map(ToString::to_string).collect()))
}
}
impl Display for StringList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0.iter().join(","))?;
Ok(())
}
}
impl StringList {
/// Returns whether a [`StringList`] contains a given String.
///
/// # Arguments
///
/// * `s` - The String to check
#[must_use]
pub fn contains(&self, s: &str) -> bool {
self.0.contains(s)
}
/// Returns whether a [`StringList`] contains all Strings of another [`StringList`].
///
/// # Arguments
///
/// * `sl` - The [`StringList`] to check
#[must_use]
pub fn contains_all(&self, sl: &Self) -> bool {
sl.0.is_subset(&self.0)
}
/// Returns whether a [`StringList`] matches a list of [`StringList`]s,