-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathrepository.rs
2090 lines (1936 loc) · 62.8 KB
/
repository.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
pub(crate) mod command_input;
pub(crate) mod warm_up;
use std::{
cmp::Ordering,
fs::File,
io::{BufRead, BufReader, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
sync::Arc,
};
use bytes::Bytes;
use derive_setters::Setters;
use log::{debug, error, info};
use serde_with::{serde_as, DisplayFromStr};
use crate::{
backend::{
cache::{Cache, CachedBackend},
decrypt::{DecryptBackend, DecryptReadBackend, DecryptWriteBackend},
hotcold::HotColdBackend,
local_destination::LocalDestination,
node::Node,
warm_up::WarmUpAccessBackend,
FileType, ReadBackend, WriteBackend,
},
blob::{
tree::{FindMatches, FindNode, NodeStreamer, TreeId, TreeStreamerOptions as LsOptions},
BlobId, BlobType, PackedId,
},
commands::{
self,
backup::BackupOptions,
check::{check_repository, CheckOptions},
config::ConfigOptions,
copy::CopySnapshot,
forget::{ForgetGroups, KeepOptions},
key::{add_current_key_to_repo, KeyOptions},
prune::{prune_repository, PruneOptions, PrunePlan},
repair::{
index::{index_checked_from_collector, repair_index, RepairIndexOptions},
snapshots::{repair_snapshots, RepairSnapshotsOptions},
},
repoinfo::{IndexInfos, RepoFileInfos},
restore::{collect_and_prepare, restore_repository, RestoreOptions, RestorePlan},
},
crypto::aespoly1305::Key,
error::{ErrorKind, RusticResult},
index::{
binarysorted::{IndexCollector, IndexType},
GlobalIndex, IndexEntry, ReadGlobalIndex, ReadIndex,
},
progress::{NoProgressBars, Progress, ProgressBars},
repofile::{
configfile::ConfigId,
keyfile::find_key_in_backend,
packfile::PackId,
snapshotfile::{SnapshotGroup, SnapshotGroupCriterion, SnapshotId},
ConfigFile, KeyId, PathList, RepoFile, RepoId, SnapshotFile, SnapshotSummary, Tree,
},
repository::{
command_input::CommandInput,
warm_up::{warm_up, warm_up_wait},
},
vfs::OpenFile,
RepositoryBackends, RusticError,
};
#[cfg(feature = "clap")]
use clap::ValueHint;
mod constants {
/// Estimated item capacity used for cache in [`FullIndex`](super::FullIndex)
pub(super) const ESTIMATED_ITEM_CAPACITY: usize = 32;
/// Estimated weight capacity used for cache in [`FullIndex`](super::FullIndex) (in bytes)
pub(super) const WEIGHT_CAPACITY: u64 = 32_000_000;
}
/// Options for using and opening a [`Repository`]
#[serde_as]
#[cfg_attr(feature = "clap", derive(clap::Parser))]
#[cfg_attr(feature = "merge", derive(conflate::Merge))]
#[derive(Clone, Default, Debug, serde::Deserialize, serde::Serialize, Setters)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
#[setters(into, strip_option)]
#[non_exhaustive]
pub struct RepositoryOptions {
/// Password of the repository
///
/// # Warning
///
/// * Using --password can reveal the password in the process list!
#[cfg_attr(
feature = "clap",
clap(long, global = true, env = "RUSTIC_PASSWORD", hide_env_values = true)
)]
// TODO: Security related: use `secrecy` library (#663)
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub password: Option<String>,
/// File to read the password from
#[cfg_attr(
feature = "clap",
clap(
short,
long,
global = true,
env = "RUSTIC_PASSWORD_FILE",
conflicts_with = "password",
value_hint = ValueHint::FilePath,
)
)]
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub password_file: Option<PathBuf>,
/// Command to read the password from. Password is read from stdout
#[cfg_attr(feature = "clap", clap(
long,
global = true,
env = "RUSTIC_PASSWORD_COMMAND",
conflicts_with_all = &["password", "password_file"],
))]
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub password_command: Option<CommandInput>,
/// Don't use a cache.
#[cfg_attr(feature = "clap", clap(long, global = true, env = "RUSTIC_NO_CACHE"))]
#[cfg_attr(feature = "merge", merge(strategy = conflate::bool::overwrite_false))]
pub no_cache: bool,
/// Use this dir as cache dir instead of the standard cache dir
#[cfg_attr(
feature = "clap",
clap(
long,
global = true,
conflicts_with = "no_cache",
env = "RUSTIC_CACHE_DIR",
value_hint = ValueHint::DirPath,
)
)]
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub cache_dir: Option<PathBuf>,
/// Warm up needed data pack files by only requesting them without processing
#[cfg_attr(feature = "clap", clap(long, global = true))]
#[cfg_attr(feature = "merge", merge(strategy = conflate::bool::overwrite_false))]
pub warm_up: bool,
/// Warm up needed data pack files by running the command with %id replaced by pack id
#[cfg_attr(
feature = "clap",
clap(long, global = true, conflicts_with = "warm_up",)
)]
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub warm_up_command: Option<CommandInput>,
/// Wait for end of warm up by running the command with %id replaced by pack id
#[cfg_attr(
feature = "clap",
clap(long, global = true, conflicts_with = "warm_up_wait",)
)]
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub warm_up_wait_command: Option<CommandInput>,
/// Duration (e.g. 10m) to wait after warm up
#[cfg_attr(feature = "clap", clap(long, global = true, value_name = "DURATION"))]
#[serde_as(as = "Option<DisplayFromStr>")]
#[cfg_attr(feature = "merge", merge(strategy = conflate::option::overwrite_none))]
pub warm_up_wait: Option<humantime::Duration>,
}
impl RepositoryOptions {
/// Evaluates the password given by the repository options
///
/// # Errors
///
/// * If opening the password file failed
/// * If reading the password failed
/// * If splitting the password command failed
/// * If executing the password command failed
/// * If reading the password from the command failed
///
/// # Returns
///
/// The password or `None` if no password is given
pub fn evaluate_password(&self) -> RusticResult<Option<String>> {
match (&self.password, &self.password_file, &self.password_command) {
(Some(pwd), _, _) => Ok(Some(pwd.clone())),
(_, Some(file), _) => {
let mut file = BufReader::new(File::open(file).map_err(|err| {
RusticError::with_source(
ErrorKind::Password,
"Opening password file failed. Is the path `{path}` correct?",
err,
)
.attach_context("path", file.display().to_string())
})?);
Ok(Some(read_password_from_reader(&mut file)?))
}
(_, _, Some(command)) if command.is_set() => {
debug!("commands: {command:?}");
let run_command = Command::new(command.command())
.args(command.args())
.stdout(Stdio::piped())
.spawn();
let process = match run_command {
Ok(process) => process,
Err(err) => {
error!("password-command could not be executed: {}", err);
return Err(RusticError::with_source(
ErrorKind::Password,
"Password command `{command}` could not be executed",
err,
)
.attach_context("command", command.to_string()));
}
};
let output = match process.wait_with_output() {
Ok(output) => output,
Err(err) => {
error!("error reading output from password-command: {err}");
return Err(RusticError::with_source(
ErrorKind::Password,
"Error reading output from password command `{command}`",
err,
)
.attach_context("command", command.to_string()));
}
};
if !output.status.success() {
#[allow(clippy::option_if_let_else)]
let s = match output.status.code() {
Some(c) => format!("exited with status code {c}"),
None => "was terminated".into(),
};
error!("password-command {s}");
return Err(RusticError::new(
ErrorKind::Password,
"Password command `{command}` did not exit successfully: `{status}`",
)
.attach_context("command", command.to_string())
.attach_context("status", s));
}
let mut pwd = BufReader::new(&*output.stdout);
Ok(Some(read_password_from_reader(&mut pwd)?))
}
(None, None, _) => Ok(None),
}
}
}
/// Read a password from a reader
///
/// # Arguments
///
/// * `file` - The reader to read the password from
///
/// # Errors
///
/// * If reading the password failed
pub fn read_password_from_reader(file: &mut impl BufRead) -> RusticResult<String> {
let mut password = String::new();
_ = file.read_line(&mut password).map_err(|err| {
RusticError::with_source(
ErrorKind::Password,
"Reading password from reader failed. Is the file empty? Please check the file and the password.",
err
)
.attach_context("password", password.clone())
})?;
// Remove the \n from the line if present
if password.ends_with('\n') {
_ = password.pop();
}
// Remove the \r from the line if present
if password.ends_with('\r') {
_ = password.pop();
}
Ok(password)
}
#[derive(Debug, Clone)]
/// A `Repository` allows all kind of actions to be performed.
///
/// # Type Parameters
///
/// * `P` - The type of the progress bar
/// * `S` - The type of the status
///
/// # Notes
///
/// A repository can be in different states and allows some actions only when in certain state(s).
pub struct Repository<P, S> {
/// The name of the repository
pub name: String,
/// The `HotColdBackend` to use for this repository
pub(crate) be: Arc<dyn WriteBackend>,
/// The Backend to use for hot files
pub(crate) be_hot: Option<Arc<dyn WriteBackend>>,
/// The options used for this repository
opts: RepositoryOptions,
/// The progress bar to use
pub(crate) pb: P,
/// The status
status: S,
}
impl Repository<NoProgressBars, ()> {
/// Create a new repository from the given [`RepositoryOptions`] (without progress bars)
///
/// # Arguments
///
/// * `opts` - The options to use for the repository
/// * `backends` - The backends to create/access a repository on
///
/// # Errors
///
/// * If no repository is given
/// * If the warm-up command does not contain `%id`
/// * If the specified backend cannot be loaded, e.g. is not supported
pub fn new(opts: &RepositoryOptions, backends: &RepositoryBackends) -> RusticResult<Self> {
Self::new_with_progress(opts, backends, NoProgressBars {})
}
}
impl<P> Repository<P, ()> {
/// Create a new repository from the given [`RepositoryOptions`] with given progress bars
///
/// # Type Parameters
///
/// * `P` - The type of the progress bar
///
/// # Arguments
///
/// * `opts` - The options to use for the repository
/// * `backends` - The backends to create/access a repository on
/// * `pb` - The progress bars to use
///
/// # Errors
///
/// * If no repository is given
/// * If the warm-up command does not contain `%id`
/// * If the specified backend cannot be loaded, e.g. is not supported
pub fn new_with_progress(
opts: &RepositoryOptions,
backends: &RepositoryBackends,
pb: P,
) -> RusticResult<Self> {
let mut be = backends.repository();
let be_hot = backends.repo_hot();
if let Some(warm_up) = &opts.warm_up_command {
if warm_up.args().iter().all(|c| !c.contains("%id")) {
return Err(RusticError::new(
ErrorKind::MissingInput,
"No `%id` specified in warm-up command `{command}`. Please specify `%id` in the command.",
)
.attach_context("command", warm_up.to_string()));
}
info!("using warm-up command {warm_up}");
}
if opts.warm_up {
be = WarmUpAccessBackend::new_warm_up(be);
}
let mut name = be.location();
if let Some(be_hot) = &be_hot {
be = Arc::new(HotColdBackend::new(be, be_hot.clone()));
name.push('#');
name.push_str(&be_hot.location());
}
Ok(Self {
name,
be,
be_hot,
opts: opts.clone(),
pb,
status: (),
})
}
}
impl<P, S> Repository<P, S> {
/// Evaluates the password given by the repository options
///
/// # Errors
///
/// * If opening the password file failed
/// * If reading the password failed
/// * If splitting the password command failed
/// * If parsing the password command failed
/// * If reading the password from the command failed
///
/// # Returns
///
/// The password or `None` if no password is given
pub fn password(&self) -> RusticResult<Option<String>> {
self.opts.evaluate_password()
}
/// Returns the Id of the config file
///
/// # Errors
///
/// * If listing the repository config file failed
/// * If there is more than one repository config file
///
/// # Returns
///
/// The id of the config file or `None` if no config file is found
pub fn config_id(&self) -> RusticResult<Option<ConfigId>> {
self.config_id_with_backend(&self.be)
}
/// Returns the Id of the config file corresponding to a specific backend.
///
/// # Errors
///
/// * If listing the repository config file failed
/// * If there is more than one repository config file.
///
/// # Arguments
///
/// * `be` - The backend to use
///
/// # Returns
///
/// The id of the config file or `None` if no config file is found
fn config_id_with_backend(&self, be: &dyn WriteBackend) -> RusticResult<Option<ConfigId>> {
let config_ids = be.list(FileType::Config)?;
match config_ids.len() {
1 => Ok(Some(ConfigId::from(config_ids[0]))),
0 => Ok(None),
_ => Err(RusticError::new(
ErrorKind::Configuration,
"More than one repository found for `{name}`. Please check the config file.",
)
.attach_context("name", self.name.clone())),
}
}
/// Open the repository.
///
/// This gets the decryption key and reads the config file
///
/// # Errors
///
/// * If no password is given
/// * If reading the password failed
/// * If opening the password file failed
/// * If parsing the password command failed
/// * If reading the password from the command failed
/// * If splitting the password command failed
/// * If no repository config file is found
/// * If the keys of the hot and cold backend don't match
/// * If the password is incorrect
/// * If no suitable key is found
/// * If listing the repository config file failed
/// * If there is more than one repository config file
///
/// # Returns
///
/// The open repository
pub fn open(self) -> RusticResult<Repository<P, OpenStatus>> {
let password = self.password()?.ok_or_else(|| {
RusticError::new(
ErrorKind::Password,
"No password given, or Password was empty. Please specify a valid password.",
)
})?;
self.open_with_password(&password)
}
/// Open the repository with a given password.
///
/// This gets the decryption key and reads the config file
///
/// # Arguments
///
/// * `password` - The password to use
///
/// # Errors
///
/// * If no repository config file is found
/// * If the keys of the hot and cold backend don't match
/// * If the password is incorrect
/// * If no suitable key is found
/// * If listing the repository config file failed
/// * If there is more than one repository config file
pub fn open_with_password(self, password: &str) -> RusticResult<Repository<P, OpenStatus>> {
let config_id = self.config_id()?.ok_or_else(|| {
RusticError::new(
ErrorKind::Configuration,
"No repository config file found for `{name}`. Please check the repository.",
)
.attach_context("name", self.name.clone())
})?;
if let Some(be_hot) = &self.be_hot {
let mut keys = self.be.list_with_size(FileType::Key)?;
keys.sort_unstable_by_key(|key| key.0);
let mut hot_keys = be_hot.list_with_size(FileType::Key)?;
hot_keys.sort_unstable_by_key(|key| key.0);
if keys != hot_keys {
return Err(RusticError::new(
ErrorKind::Key,
"Keys of hot and cold repositories don't match for `{name}`. Please check the keys.",
)
.attach_context("name", self.name.clone()));
}
}
let key = find_key_in_backend(&self.be, &password, None)?;
info!("repository {}: password is correct.", self.name);
let dbe = DecryptBackend::new(self.be.clone(), key);
let config: ConfigFile = dbe.get_file(&config_id)?;
self.open_raw(key, config)
}
/// Initialize a new repository with given options using the password defined in `RepositoryOptions`
///
/// This returns an open repository which can be directly used.
///
/// # Type Parameters
///
/// * `P` - The type of the progress bar
///
/// # Arguments
///
/// * `key_opts` - The options to use for the key
/// * `config_opts` - The options to use for the config
///
/// # Errors
///
/// * If no password is given
/// * If reading the password failed
/// * If opening the password file failed
/// * If parsing the password command failed
/// * If reading the password from the command failed
/// * If splitting the password command failed
pub fn init(
self,
key_opts: &KeyOptions,
config_opts: &ConfigOptions,
) -> RusticResult<Repository<P, OpenStatus>> {
let password = self.password()?.ok_or_else(|| {
RusticError::new(
ErrorKind::Password,
"No password given, or Password was empty. Please specify a valid password for `{name}`.",
)
.attach_context("name", self.name.clone())
})?;
self.init_with_password(&password, key_opts, config_opts)
}
/// Initialize a new repository with given password and options.
///
/// This returns an open repository which can be directly used.
///
/// # Type Parameters
///
/// * `P` - The type of the progress bar
///
/// # Arguments
///
/// * `pass` - The password to use
/// * `key_opts` - The options to use for the key
/// * `config_opts` - The options to use for the config
///
/// # Errors
///
/// * If a config file already exists
/// * If listing the repository config file failed
/// * If there is more than one repository config file
pub fn init_with_password(
self,
pass: &str,
key_opts: &KeyOptions,
config_opts: &ConfigOptions,
) -> RusticResult<Repository<P, OpenStatus>> {
let config_exists = self.config_id_with_backend(&self.be)?.is_some();
let hot_config_exists = match self.be_hot {
None => false,
Some(ref be) => self.config_id_with_backend(be)?.is_some(),
};
if config_exists || hot_config_exists {
return Err(RusticError::new(
ErrorKind::Configuration,
"Config file already exists for `{name}`. Please check the repository.",
)
.attach_context("name", self.name));
}
let (key, config) = commands::init::init(&self, pass, key_opts, config_opts)?;
self.open_raw(key, config)
}
/// Initialize a new repository with given password and a ready [`ConfigFile`].
///
/// This returns an open repository which can be directly used.
///
/// # Type Parameters
///
/// * `P` - The type of the progress bar
///
/// # Arguments
///
/// * `password` - The password to use
/// * `key_opts` - The options to use for the key
/// * `config` - The config file to use
///
/// # Errors
///
// TODO: Document errors
pub fn init_with_config(
self,
password: &str,
key_opts: &KeyOptions,
config: ConfigFile,
) -> RusticResult<Repository<P, OpenStatus>> {
let key = commands::init::init_with_config(&self, password, key_opts, &config)?;
info!("repository {} successfully created.", config.id);
self.open_raw(key, config)
}
/// Open the repository with given [`Key`] and [`ConfigFile`].
///
/// # Type Parameters
///
/// * `P` - The type of the progress bar
///
/// # Arguments
///
/// * `key` - The key to use
/// * `config` - The config file to use
///
/// # Errors
///
/// * If the config file has `is_hot` set to `true` but the repository is not hot
/// * If the config file has `is_hot` set to `false` but the repository is hot
fn open_raw(mut self, key: Key, config: ConfigFile) -> RusticResult<Repository<P, OpenStatus>> {
match (config.is_hot == Some(true), self.be_hot.is_some()) {
(true, false) => return Err(
RusticError::new(
ErrorKind::Repository,
"The given repository is a hot repository! Please use `--repo-hot` in combination with the normal repo. Aborting.",
)
),
(false, true) => return Err(
RusticError::new(
ErrorKind::Repository,
"The given repository is not a hot repository! Aborting.",
)
),
_ => {}
}
let cache = (!self.opts.no_cache)
.then(|| Cache::new(config.id, self.opts.cache_dir.clone()).ok())
.flatten();
if let Some(cache) = &cache {
self.be = CachedBackend::new_cache(self.be.clone(), cache.clone());
info!("using cache at {}", cache.location());
} else {
info!("using no cache");
}
let mut dbe = DecryptBackend::new(self.be.clone(), key);
dbe.set_zstd(config.zstd()?);
dbe.set_extra_verify(config.extra_verify());
let open = OpenStatus { cache, dbe, config };
Ok(Repository {
name: self.name,
be: self.be,
be_hot: self.be_hot,
opts: self.opts,
pb: self.pb,
status: open,
})
}
/// List all file [`Id`]s of the given [`FileType`] which are present in the repository
///
/// # Arguments
///
/// * `tpe` - The type of the files to list
///
/// # Errors
///
// TODO: Document errors
pub fn list<T: RepoId>(&self) -> RusticResult<impl Iterator<Item = T>> {
Ok(self.be.list(T::TYPE)?.into_iter().map(Into::into))
}
}
impl<P: ProgressBars, S> Repository<P, S> {
/// Collect information about repository files
///
/// # Errors
///
/// * If files could not be listed.
pub fn infos_files(&self) -> RusticResult<RepoFileInfos> {
commands::repoinfo::collect_file_infos(self)
}
/// Warm up the given pack files without waiting.
///
/// # Arguments
///
/// * `packs` - The pack files to warm up
///
/// # Errors
///
/// * If the command could not be parsed.
/// * If the thread pool could not be created.
///
/// # Returns
///
/// The result of the warm up
pub fn warm_up(&self, packs: impl ExactSizeIterator<Item = PackId>) -> RusticResult<()> {
warm_up(self, packs)
}
/// Warm up the given pack files and wait the configured waiting time.
///
/// # Arguments
///
/// * `packs` - The pack files to warm up
///
/// # Errors
///
/// * If the command could not be parsed.
/// * If the thread pool could not be created.
pub(crate) fn warm_up_wait(
&self,
packs: impl ExactSizeIterator<Item = PackId> + Clone,
) -> RusticResult<()> {
warm_up_wait(self, packs)
}
}
/// A repository which is open, i.e. the password has been checked and the decryption key is available.
pub trait Open {
/// Get the cache
fn cache(&self) -> Option<&Cache>;
/// Get the [`DecryptBackend`]
fn dbe(&self) -> &DecryptBackend<Key>;
/// Get the [`ConfigFile`]
fn config(&self) -> &ConfigFile;
}
impl<P, S: Open> Open for Repository<P, S> {
/// Get the cache
fn cache(&self) -> Option<&Cache> {
self.status.cache()
}
/// Get the [`DecryptBackend`]
fn dbe(&self) -> &DecryptBackend<Key> {
self.status.dbe()
}
/// Get the [`ConfigFile`]
fn config(&self) -> &ConfigFile {
self.status.config()
}
}
/// Open Status: This repository is open, i.e. the password has been checked and the decryption key is available.
#[derive(Debug)]
pub struct OpenStatus {
/// The cache
cache: Option<Cache>,
/// The [`DecryptBackend`]
dbe: DecryptBackend<Key>,
/// The [`ConfigFile`]
config: ConfigFile,
}
impl Open for OpenStatus {
/// Get the cache
fn cache(&self) -> Option<&Cache> {
self.cache.as_ref()
}
/// Get the [`DecryptBackend`]
fn dbe(&self) -> &DecryptBackend<Key> {
&self.dbe
}
/// Get the [`ConfigFile`]
fn config(&self) -> &ConfigFile {
&self.config
}
}
impl<P, S: Open> Repository<P, S> {
/// Get the content of the decrypted repository file given by id and [`FileType`]
///
/// # Arguments
///
/// * `tpe` - The type of the file to get
/// * `id` - The id of the file to get
///
/// # Errors
///
/// * If the string is not a valid hexadecimal string
/// * If no id could be found.
/// * If the id is not unique.
pub fn cat_file(&self, tpe: FileType, id: &str) -> RusticResult<Bytes> {
commands::cat::cat_file(self, tpe, id)
}
/// Add a new key to the repository
///
/// # Arguments
///
/// * `pass` - The password to use for the new key
/// * `opts` - The options to use for the new key
///
/// # Errors
///
/// * If the key could not be serialized.
pub fn add_key(&self, pass: &str, opts: &KeyOptions) -> RusticResult<KeyId> {
add_current_key_to_repo(self, opts, pass)
}
/// Update the repository config by applying the given [`ConfigOptions`]
///
/// # Arguments
///
/// * `opts` - The options to apply
///
/// # Errors
///
/// * If the version is not supported
/// * If the version is lower than the current version
/// * If compression is set for a v1 repo
/// * If the compression level is not supported
/// * If the size is too large
/// * If the min pack size tolerance percent is wrong
/// * If the max pack size tolerance percent is wrong
/// * If the file could not be serialized to json.
pub fn apply_config(&self, opts: &ConfigOptions) -> RusticResult<bool> {
commands::config::apply_config(self, opts)
}
/// Get the repository configuration
pub fn config(&self) -> &ConfigFile {
self.status.config()
}
// TODO: add documentation!
pub(crate) fn dbe(&self) -> &DecryptBackend<Key> {
self.status.dbe()
}
}
impl<P: ProgressBars, S: Open> Repository<P, S> {
/// Get grouped snapshots.
///
/// # Arguments
///
/// * `ids` - The ids of the snapshots to group. If empty, all snapshots are grouped.
/// * `group_by` - The criterion to group by
/// * `filter` - The filter to use
///
/// # Errors
///
// TODO: Document errors
///
/// # Returns
///
/// If `ids` are given, this will try to resolve the ids (or `latest` with respect to the given filter) and return a single group
/// If `ids` is empty, return and group all snapshots respecting the filter.
pub fn get_snapshot_group(
&self,
ids: &[String],
group_by: SnapshotGroupCriterion,
filter: impl FnMut(&SnapshotFile) -> bool,
) -> RusticResult<Vec<(SnapshotGroup, Vec<SnapshotFile>)>> {
commands::snapshots::get_snapshot_group(self, ids, group_by, filter)
}
/// Get a single snapshot
///
/// # Arguments
///
/// * `id` - The id of the snapshot to get
/// * `filter` - The filter to use
///
/// # Errors
///
/// * If the string is not a valid hexadecimal string
/// * If no id could be found.
/// * If the id is not unique.
///
/// # Returns
///
/// If `id` is (part of) an `Id`, return this snapshot.
/// If `id` is "latest", return the latest snapshot respecting the giving filter.
pub fn get_snapshot_from_str(
&self,
id: &str,
filter: impl FnMut(&SnapshotFile) -> bool + Send + Sync,
) -> RusticResult<SnapshotFile> {
let p = self.pb.progress_counter("getting snapshot...");
let snap = SnapshotFile::from_str(self.dbe(), id, filter, &p)?;
p.finish();
Ok(snap)
}
/// Get the given snapshots.
///
/// # Arguments
///
/// * `ids` - The ids of the snapshots to get
///
/// # Notes
///
/// `ids` may contain part of snapshots id which will be resolved.
/// However, "latest" is not supported in this function.
///
/// # Errors
///
// TODO: Document errors
pub fn get_snapshots<T: AsRef<str>>(&self, ids: &[T]) -> RusticResult<Vec<SnapshotFile>> {
self.update_snapshots(Vec::new(), ids)
}
/// Update the given snapshots.
///
/// # Arguments
///
/// * `current` - The existing snapshots
/// * `ids` - The ids of the snapshots to get
///
/// # Notes
///
/// `ids` may contain part of snapshots id which will be resolved.
/// However, "latest" is not supported in this function.
///
/// # Errors
///
// TODO: Document errors
pub fn update_snapshots<T: AsRef<str>>(
&self,
current: Vec<SnapshotFile>,
ids: &[T],
) -> RusticResult<Vec<SnapshotFile>> {
let p = self.pb.progress_counter("getting snapshots...");
let result = SnapshotFile::update_from_ids(self.dbe(), current, ids, &p);
p.finish();
result
}
/// Get all snapshots from the repository
///
/// # Errors
///
// TODO: Document errors
pub fn get_all_snapshots(&self) -> RusticResult<Vec<SnapshotFile>> {
self.get_matching_snapshots(|_| true)
}
/// Update existing snapshots to all from the repository
///
/// # Arguments
///
/// * `current` - The existing snapshots
///
/// # Errors
///