-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathconfig.rs
1507 lines (1269 loc) · 42.8 KB
/
config.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
#![allow(dead_code)]
use std::collections::BTreeMap;
use std::fs::{write, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{env, fs};
use clap::{ArgEnum, Parser};
use clap_complete::Shell;
use color_eyre::eyre::Context;
use color_eyre::eyre::Result;
use etcetera::base_strategy::BaseStrategy;
use merge::Merge;
use regex::Regex;
use regex_split::RegexSplit;
use serde::Deserialize;
use strum::{EnumIter, EnumString, EnumVariantNames, IntoEnumIterator};
use tracing::debug;
use which_crate::which;
use crate::command::CommandExt;
use crate::sudo::SudoKind;
use crate::utils::string_prepend_str;
use super::utils::{editor, hostname};
pub static EXAMPLE_CONFIG: &str = include_str!("../config.example.toml");
#[allow(unused_macros)]
macro_rules! str_value {
($section:ident, $value:ident) => {
pub fn $value(&self) -> Option<&str> {
self.config_file
.$section
.as_ref()
.and_then(|section| section.$value.as_deref())
}
};
}
macro_rules! check_deprecated {
($config:expr, $old:ident, $section:ident, $new:ident) => {
if $config.$old.is_some() {
println!(concat!(
"'",
stringify!($old),
"' configuration option is deprecated. Rename it to '",
stringify!($new),
"' and put it under the section [",
stringify!($section),
"]",
));
}
};
}
/// Get a deprecated option moved from a section to another
macro_rules! get_deprecated_moved_opt {
($old_section:expr, $old:ident, $new_section:expr, $new:ident) => {{
if let Some(old_section) = &$old_section {
if old_section.$old.is_some() {
return &old_section.$old;
}
}
if let Some(new_section) = &$new_section {
return &new_section.$new;
}
return &None;
}};
}
macro_rules! get_deprecated_moved_or_default_to {
($old_section:expr, $old:ident, $new_section:expr, $new:ident, $default_ret:ident) => {{
if let Some(old_section) = &$old_section {
if let Some(old) = old_section.$old {
return old;
}
}
if let Some(new_section) = &$new_section {
if let Some(new) = new_section.$new {
return new;
}
}
return $default_ret;
}};
}
pub type Commands = BTreeMap<String, String>;
#[derive(ArgEnum, EnumString, EnumVariantNames, Debug, Clone, PartialEq, Eq, Deserialize, EnumIter, Copy)]
#[clap(rename_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Step {
AM,
AppMan,
Asdf,
Atom,
Bin,
BrewCask,
BrewFormula,
Bun,
Cargo,
Chezmoi,
Chocolatey,
Choosenim,
Composer,
Conda,
ConfigUpdate,
Containers,
CustomCommands,
DebGet,
Deno,
Distrobox,
DkpPacman,
Dotnet,
Emacs,
Firmware,
Flatpak,
Flutter,
Fossil,
Gcloud,
Gem,
Ghcup,
GithubCliExtensions,
GitRepos,
GnomeShellExtensions,
Go,
Guix,
Haxelib,
Helm,
HomeManager,
Jetpack,
Julia,
Juliaup,
Kakoune,
Helix,
Krew,
Macports,
Mamba,
Mas,
Maza,
Micro,
Myrepos,
Nix,
Node,
Opam,
Pacdef,
Pacstall,
Pearl,
Pip3,
PipReview,
PipReviewLocal,
Pipupgrade,
Pipx,
Pkg,
Pkgin,
Pnpm,
Powershell,
Protonup,
Raco,
Rcm,
Remotes,
Restarts,
Rtcl,
RubyGems,
Rustup,
Scoop,
Sdkman,
Sheldon,
Shell,
Snap,
Sparkle,
Spicetify,
Stack,
Stew,
System,
Tldr,
Tlmgr,
Tmux,
Toolbx,
Vagrant,
Vcpkg,
Vim,
Winget,
Wsl,
WslUpdate,
Yadm,
Yarn,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Include {
#[merge(strategy = merge::vec::append)]
paths: Vec<String>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Git {
max_concurrency: Option<usize>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
repos: Option<Vec<String>>,
pull_predefined: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Vagrant {
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
directories: Option<Vec<String>>,
power_on: Option<bool>,
always_suspend: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Windows {
accept_all_updates: Option<bool>,
self_rename: Option<bool>,
open_remotes_in_new_terminal: Option<bool>,
enable_winget: Option<bool>,
wsl_update_pre_release: Option<bool>,
wsl_update_use_web_download: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Python {
enable_pip_review: Option<bool>,
enable_pip_review_local: Option<bool>,
enable_pipupgrade: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
#[allow(clippy::upper_case_acronyms)]
pub struct Distrobox {
use_root: Option<bool>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
containers: Option<Vec<String>>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
#[allow(clippy::upper_case_acronyms)]
pub struct Yarn {
use_sudo: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
#[allow(clippy::upper_case_acronyms)]
pub struct NPM {
use_sudo: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
#[allow(clippy::upper_case_acronyms)]
pub struct Firmware {
upgrade: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
#[allow(clippy::upper_case_acronyms)]
pub struct Flatpak {
use_sudo: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Brew {
greedy_cask: Option<bool>,
autoremove: Option<bool>,
}
#[derive(Debug, Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ArchPackageManager {
Autodetect,
Aura,
GarudaUpdate,
Pacman,
Pamac,
Paru,
Pikaur,
Trizen,
Yay,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Linux {
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
yay_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
aura_aur_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
aura_pacman_arguments: Option<String>,
arch_package_manager: Option<ArchPackageManager>,
show_arch_news: Option<bool>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
garuda_update_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
trizen_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
pikaur_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
pamac_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
dnf_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
nix_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
apt_arguments: Option<String>,
enable_tlmgr: Option<bool>,
redhat_distro_sync: Option<bool>,
suse_dup: Option<bool>,
rpm_ostree: Option<bool>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
emerge_sync_flags: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
emerge_update_flags: Option<String>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Composer {
self_update: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Vim {
force_plug_update: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
pub struct Misc {
pre_sudo: Option<bool>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
git_repos: Option<Vec<String>>,
predefined_git_repos: Option<bool>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
disable: Option<Vec<Step>>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
ignore_failures: Option<Vec<Step>>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
remote_topgrades: Option<Vec<String>>,
remote_topgrade_path: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
ssh_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
git_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
tmux_arguments: Option<String>,
set_title: Option<bool>,
display_time: Option<bool>,
display_preamble: Option<bool>,
assume_yes: Option<bool>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
yay_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
aura_aur_arguments: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::string_append_opt)]
aura_pacman_arguments: Option<String>,
no_retry: Option<bool>,
run_in_tmux: Option<bool>,
cleanup: Option<bool>,
notify_each_step: Option<bool>,
accept_all_windows_updates: Option<bool>,
skip_notify: Option<bool>,
bashit_branch: Option<String>,
#[merge(strategy = crate::utils::merge_strategies::vec_prepend_opt)]
only: Option<Vec<Step>>,
no_self_update: Option<bool>,
}
#[derive(Deserialize, Default, Debug, Merge)]
#[serde(deny_unknown_fields)]
/// Configuration file
pub struct ConfigFile {
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
include: Option<Include>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
misc: Option<Misc>,
sudo_command: Option<SudoKind>,
#[merge(strategy = crate::utils::merge_strategies::commands_merge_opt)]
pre_commands: Option<Commands>,
#[merge(strategy = crate::utils::merge_strategies::commands_merge_opt)]
post_commands: Option<Commands>,
#[merge(strategy = crate::utils::merge_strategies::commands_merge_opt)]
commands: Option<Commands>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
python: Option<Python>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
composer: Option<Composer>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
brew: Option<Brew>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
linux: Option<Linux>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
git: Option<Git>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
windows: Option<Windows>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
npm: Option<NPM>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
yarn: Option<Yarn>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
vim: Option<Vim>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
firmware: Option<Firmware>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
vagrant: Option<Vagrant>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
flatpak: Option<Flatpak>,
#[merge(strategy = crate::utils::merge_strategies::inner_merge_opt)]
distrobox: Option<Distrobox>,
}
fn config_directory() -> PathBuf {
#[cfg(unix)]
return crate::XDG_DIRS.config_dir();
#[cfg(windows)]
return crate::WINDOWS_DIRS.config_dir();
}
/// The only purpose of this struct is to deserialize only the `include` field of the config file.
#[derive(Deserialize, Default, Debug)]
struct ConfigFileIncludeOnly {
include: Option<Include>,
}
impl ConfigFile {
/// Returns the main config file and any additional config files
/// 0 = main config file
/// 1 = additional config files coming from topgrade.d
fn ensure() -> Result<(PathBuf, Vec<PathBuf>)> {
let mut res = (PathBuf::new(), Vec::new());
let config_directory = config_directory();
let possible_config_paths = vec![
config_directory.join("topgrade.toml"),
config_directory.join("topgrade/topgrade.toml"),
];
// Search for the main config file
for path in possible_config_paths.iter() {
if path.exists() {
debug!("Configuration at {}", path.display());
res.0 = path.clone();
break;
}
}
res.1 = Self::ensure_topgrade_d(&config_directory)?;
// If no config file exists, create a default one in the config directory
if !res.0.exists() && res.1.is_empty() {
debug!("No configuration exists");
write(&res.0, EXAMPLE_CONFIG).map_err(|e| {
debug!(
"Unable to write the example configuration file to {}: {}. Using blank config.",
&res.0.display(),
e
);
e
})?;
}
Ok(res)
}
/// Searches topgrade.d for additional config files
fn ensure_topgrade_d(config_directory: &Path) -> Result<Vec<PathBuf>> {
let mut res = Vec::new();
let dir_to_search = config_directory.join("topgrade.d");
if dir_to_search.exists() {
for entry in fs::read_dir(dir_to_search)? {
let entry = entry?;
if entry.file_type()?.is_file() {
debug!(
"Found additional (directory) configuration file at {}",
entry.path().display()
);
res.push(entry.path());
}
}
res.sort();
} else {
debug!("No additional configuration directory exists, creating one");
fs::create_dir_all(&dir_to_search)?;
}
Ok(res)
}
/// Read the configuration file.
///
/// If the configuration file does not exist, the function returns the default ConfigFile.
fn read(config_path: Option<PathBuf>) -> Result<ConfigFile> {
let mut result = Self::default();
let config_path = if let Some(path) = config_path {
path
} else {
let (path, dir_include) = Self::ensure()?;
/*
The Function was called without a config_path, we need
to read the include directory before returning the main config path
*/
for include in dir_include {
let include_contents = fs::read_to_string(&include).map_err(|e| {
tracing::error!("Unable to read {}", include.display());
e
})?;
let include_contents_parsed = toml::from_str(include_contents.as_str()).map_err(|e| {
tracing::error!("Failed to deserialize {}", include.display());
e
})?;
result.merge(include_contents_parsed);
}
path
};
let mut contents_non_split = fs::read_to_string(&config_path).map_err(|e| {
tracing::error!("Unable to read {}", config_path.display());
e
})?;
Self::ensure_misc_is_present(&mut contents_non_split, &config_path);
// To parse [include] sections in the order as they are written,
// we split the file and parse each part as a separate file
let regex_match_include = Regex::new(r"\[include]").expect("Failed to compile regex");
let contents_split = regex_match_include.split_inclusive_left(contents_non_split.as_str());
for contents in contents_split {
let config_file_include_only: ConfigFileIncludeOnly = toml::from_str(contents).map_err(|e| {
tracing::error!("Failed to deserialize an include section of {}", config_path.display());
e
})?;
if let Some(includes) = &config_file_include_only.include {
// Parses the [include] section present in the slice
for include in includes.paths.iter().rev() {
let include_path = shellexpand::tilde::<&str>(&include.as_ref()).into_owned();
let include_path = PathBuf::from(include_path);
let include_contents = match fs::read_to_string(&include_path) {
Ok(c) => c,
Err(e) => {
tracing::error!("Unable to read {}: {}", include_path.display(), e);
continue;
}
};
match toml::from_str::<Self>(&include_contents) {
Ok(include_parsed) => result.merge(include_parsed),
Err(e) => {
tracing::error!("Failed to deserialize {}: {}", include_path.display(), e);
continue;
}
};
debug!("Configuration include found: {}", include_path.display());
}
}
match toml::from_str::<Self>(contents) {
Ok(contents) => result.merge(contents),
Err(e) => tracing::error!("Failed to deserialize {}: {}", config_path.display(), e),
}
}
if let Some(misc) = &mut result.misc {
if let Some(ref mut paths) = &mut misc.git_repos {
for path in paths.iter_mut() {
let expanded = shellexpand::tilde::<&str>(&path.as_ref()).into_owned();
debug!("Path {} expanded to {}", path, expanded);
*path = expanded;
}
}
}
if let Some(paths) = result.git.as_mut().and_then(|git| git.repos.as_mut()) {
for path in paths.iter_mut() {
let expanded = shellexpand::tilde::<&str>(&path.as_ref()).into_owned();
debug!("Path {} expanded to {}", path, expanded);
*path = expanded;
}
}
debug!("Loaded configuration: {:?}", result);
Ok(result)
}
fn edit() -> Result<()> {
let config_path = Self::ensure()?.0;
let editor = editor();
debug!("Editor: {:?}", editor);
let command = which(&editor[0])?;
let args: Vec<&String> = editor.iter().skip(1).collect();
Command::new(command)
.args(args)
.arg(config_path)
.status_checked()
.context("Failed to open configuration file editor")
}
/// [Misc] was added later, here we check if it is present in the config file and add it if not
fn ensure_misc_is_present(contents: &mut String, path: &PathBuf) {
if !contents.contains("[misc]") {
debug!("Adding [misc] section to {}", path.display());
string_prepend_str(contents, "[misc]\n");
File::create(path)
.and_then(|mut f| f.write_all(contents.as_bytes()))
.expect("Tried to auto-migrate the config file, unable to write to config file.\nPlease add \"[misc]\" section manually to the first line of the file.\nError");
}
}
}
// Command line arguments
#[derive(Parser, Debug)]
#[clap(name = "Topgrade", version)]
pub struct CommandLineArgs {
/// Edit the configuration file
#[clap(long = "edit-config")]
edit_config: bool,
/// Show config reference
#[clap(long = "config-reference")]
show_config_reference: bool,
/// Run inside tmux
#[clap(short = 't', long = "tmux")]
run_in_tmux: bool,
/// Cleanup temporary or old files
#[clap(short = 'c', long = "cleanup")]
cleanup: bool,
/// Print what would be done
#[clap(short = 'n', long = "dry-run")]
dry_run: bool,
/// Do not ask to retry failed steps
#[clap(long = "no-retry")]
no_retry: bool,
/// Do not perform upgrades for the given steps
#[clap(long = "disable", value_name = "STEP", arg_enum, multiple_values = true)]
disable: Vec<Step>,
/// Perform only the specified steps (experimental)
#[clap(long = "only", value_name = "STEP", arg_enum, multiple_values = true)]
only: Vec<Step>,
/// Run only specific custom commands
#[clap(long = "custom-commands", value_name = "NAME", multiple_values = true)]
custom_commands: Vec<String>,
/// Set environment variables
#[clap(long = "env", value_name = "NAME=VALUE", multiple_values = true)]
env: Vec<String>,
/// Output debug logs. Alias for `--log-filter debug`.
#[clap(short = 'v', long = "verbose")]
pub verbose: bool,
/// Prompt for a key before exiting
#[clap(short = 'k', long = "keep")]
keep_at_end: bool,
/// Skip sending a notification at the end of a run
#[clap(long = "skip-notify")]
skip_notify: bool,
/// Say yes to package manager's prompt
#[clap(
short = 'y',
long = "yes",
value_name = "STEP",
arg_enum,
multiple_values = true,
min_values = 0
)]
yes: Option<Vec<Step>>,
/// Don't pull the predefined git repos
#[clap(long = "disable-predefined-git-repos")]
disable_predefined_git_repos: bool,
/// Alternative configuration file
#[clap(long = "config", value_name = "PATH")]
config: Option<PathBuf>,
/// A regular expression for restricting remote host execution
#[clap(long = "remote-host-limit", value_name = "REGEX")]
remote_host_limit: Option<Regex>,
/// Show the reason for skipped steps
#[clap(long = "show-skipped")]
show_skipped: bool,
/// Tracing filter directives.
///
/// See: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/struct.EnvFilter.html
#[clap(long, default_value = "info")]
pub log_filter: String,
/// Print completion script for the given shell and exit
#[clap(long, arg_enum, hide = true)]
pub gen_completion: Option<Shell>,
/// Print roff manpage and exit
#[clap(long, hide = true)]
pub gen_manpage: bool,
/// Don't update Topgrade
#[clap(long = "no-self-update")]
pub no_self_update: bool,
}
impl CommandLineArgs {
pub fn edit_config(&self) -> bool {
self.edit_config
}
pub fn show_config_reference(&self) -> bool {
self.show_config_reference
}
pub fn env_variables(&self) -> &Vec<String> {
&self.env
}
pub fn tracing_filter_directives(&self) -> String {
if self.verbose {
"debug".into()
} else {
self.log_filter.clone()
}
}
}
/// Represents the application configuration
///
/// The struct holds the loaded configuration file, as well as the arguments parsed from the command line.
/// Its provided methods decide the appropriate options based on combining the configuration file and the
/// command line arguments.
pub struct Config {
opt: CommandLineArgs,
config_file: ConfigFile,
allowed_steps: Vec<Step>,
}
impl Config {
/// Load the configuration.
///
/// The function parses the command line arguments and reads the configuration file.
pub fn load(opt: CommandLineArgs) -> Result<Self> {
let config_directory = config_directory();
let config_file = if config_directory.is_dir() {
ConfigFile::read(opt.config.clone()).unwrap_or_else(|e| {
// Inform the user about errors when loading the configuration,
// but fallback to the default config to at least attempt to do something
tracing::error!("failed to load configuration: {}", e);
ConfigFile::default()
})
} else {
debug!("Configuration directory {} does not exist", config_directory.display());
ConfigFile::default()
};
if let Some(misc) = &config_file.misc {
check_deprecated!(misc, git_arguments, git, arguments);
check_deprecated!(misc, git_repos, git, repos);
check_deprecated!(misc, predefined_git_repos, git, pull_predefined);
check_deprecated!(misc, yay_arguments, linux, yay_arguments);
check_deprecated!(misc, accept_all_windows_updates, windows, accept_all_updates);
}
let allowed_steps = Self::allowed_steps(&opt, &config_file);
Ok(Self {
opt,
config_file,
allowed_steps,
})
}
/// Launch an editor to edit the configuration
pub fn edit() -> Result<()> {
ConfigFile::edit()
}
/// The list of commands to run before performing any step.
pub fn pre_commands(&self) -> &Option<Commands> {
&self.config_file.pre_commands
}
/// The list of commands to run at the end of all steps
pub fn post_commands(&self) -> &Option<Commands> {
&self.config_file.post_commands
}
/// The list of custom steps.
pub fn commands(&self) -> &Option<Commands> {
&self.config_file.commands
}
/// The list of additional git repositories to pull.
pub fn git_repos(&self) -> &Option<Vec<String>> {
get_deprecated_moved_opt!(&self.config_file.misc, git_repos, &self.config_file.git, repos)
}
/// Tell whether the specified step should run.
///
/// If the step appears either in the `--disable` command line argument
/// or the `disable` option in the configuration, the function returns false.
pub fn should_run(&self, step: Step) -> bool {
self.allowed_steps.contains(&step)
}
fn allowed_steps(opt: &CommandLineArgs, config_file: &ConfigFile) -> Vec<Step> {
let mut enabled_steps: Vec<Step> = Vec::new();
enabled_steps.extend(&opt.only);
if let Some(misc) = config_file.misc.as_ref() {
if let Some(only) = misc.only.as_ref() {
enabled_steps.extend(only);
}
}
if enabled_steps.is_empty() {
enabled_steps.extend(Step::iter());
}
let mut disabled_steps: Vec<Step> = Vec::new();
disabled_steps.extend(&opt.disable);
if let Some(misc) = config_file.misc.as_ref() {
if let Some(disabled) = misc.disable.as_ref() {
disabled_steps.extend(disabled);
}
}
enabled_steps.retain(|e| !disabled_steps.contains(e) || opt.only.contains(e));
enabled_steps
}
/// Tell whether we should run a self-update.
pub fn no_self_update(&self) -> bool {
self.opt.no_self_update
|| self
.config_file
.misc
.as_ref()
.and_then(|misc| misc.no_self_update)
.unwrap_or(false)
}
/// Tell whether we should run in tmux.
pub fn run_in_tmux(&self) -> bool {
self.opt.run_in_tmux
|| self
.config_file
.misc
.as_ref()
.and_then(|misc| misc.run_in_tmux)
.unwrap_or(false)
}
/// Tell whether we should perform cleanup steps.
pub fn cleanup(&self) -> bool {
self.opt.cleanup
|| self
.config_file
.misc
.as_ref()
.and_then(|misc| misc.cleanup)
.unwrap_or(false)
}
/// Tell whether we are dry-running.
pub fn dry_run(&self) -> bool {
self.opt.dry_run
}
/// Tell whether we should not attempt to retry anything.
pub fn no_retry(&self) -> bool {
self.opt.no_retry
|| self
.config_file
.misc
.as_ref()
.and_then(|misc| misc.no_retry)
.unwrap_or(false)
}
/// List of remote hosts to run Topgrade in
pub fn remote_topgrades(&self) -> Option<&Vec<String>> {
self.config_file
.misc
.as_ref()
.and_then(|misc| misc.remote_topgrades.as_ref())
}
/// Path to Topgrade executable used for all remote hosts
pub fn remote_topgrade_path(&self) -> &str {
self.config_file
.misc
.as_ref()
.and_then(|misc| misc.remote_topgrade_path.as_deref())
.unwrap_or("topgrade")
}
/// Extra SSH arguments
pub fn ssh_arguments(&self) -> Option<&String> {