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
use crate::paths::Metadata;
use anyhow::Context;
use std::path::Path;
#[derive(Debug, clap::Args)]
pub(crate) struct InstallCmd {
#[arg(short, long)]
/// Don't do anything - just show me what's going to happen.
dry_run: bool,
#[arg(short, long)]
/// Ignore differences in modified time - even if a local file has been
/// updated more recently than the remote file, overwrite it.
force: bool,
#[arg(short, long)]
/// Ignore files that are present in remote, but not present locally. In
/// other words, only _overwrite_ files - do not install any new files.
ignore_missing: bool,
/// Only install this source. Any unique portion of a path in `sources` is
/// valid. E.g. given a list of [ "/home/user/.bashrc", "/home/user/.zshrc" ],
/// ".bashrc" or ".zshrc" may be used as a key.
key: Option<String>,
#[command(subcommand)]
cmd: Option<Commands>,
}
#[derive(Debug, clap::Subcommand)]
enum Commands {
/// Create symlinks in `root` directory (default $HOME/.nedots). This is
/// a little helper tool to quickly enable you to edit all your dots from
/// a single directory through symlinks.
Symlink(Symlink),
}
impl super::Command for InstallCmd {
fn run(
&self,
_: &super::nedots::RootCmd,
config: &crate::config::Config,
) -> anyhow::Result<()> {
if let Some(key) = &self.key {
match config.get_sources_as_hashmap().get(key.as_str()) {
Some(dst) => {
super::backup::backup(
&[dst.to_path_buf()],
&config
.root
.join(&config.backup_dir)
.join(super::backup::get_timestamp()),
true,
)?;
install(
&config.get_dst_from_src(dst)?,
dst,
self.dry_run,
self.force,
self.ignore_missing,
)?;
}
None => {
log::error!("❌ {} not found!", key);
}
}
} else {
super::backup::backup(
&config.sources,
&config
.root
.join(config.backup_dir.join(super::backup::get_timestamp())),
true,
)?;
for dst in &config.sources {
// Joining absolute paths doesn't work - `dots_dir` is replaced with
// `src`. We have to strip the prefix, resulting in a relative path
// being joined instead.
install(
&config.get_dst_from_src(dst)?,
dst,
self.dry_run,
self.force,
self.ignore_missing,
)?
}
}
Ok(())
}
}
fn install(
src: &Path,
dst: &Path,
dry_run: bool,
force: bool,
ignore_missing: bool,
) -> anyhow::Result<()> {
install_file(src, dst, dry_run, force, ignore_missing)?;
log::info!(
"👍 Installed {} -> {}",
console::style(src.display()).green().bold(),
console::style(dst.display()).green().bold()
);
Ok(())
}
fn install_file(
src: &Path,
dst: &Path,
dry_run: bool,
force: bool,
ignore_missing: bool,
) -> anyhow::Result<()> {
log::trace!(
"Installing {} -> {}",
src.file_name().unwrap().to_string_lossy(),
dst.display()
);
if src.is_dir() {
for entry in src.read_dir()? {
let path = entry?.path();
install_file(
&path,
&dst.join(path.file_name().unwrap()),
dry_run,
force,
ignore_missing,
)?;
}
} else {
let src_metadata = src
.get_metadata()
.with_context(|| "Source does not exist - `gather` first!".to_string())?;
let src_modified = src.get_modified()?;
let dst_modified: std::time::SystemTime;
let dst_metadata = match dst.get_metadata() {
Ok(metadata) => {
dst_modified = dst.get_modified()?;
Some(metadata)
}
Err(err) => {
match ignore_missing {
true => dst_modified = std::time::SystemTime::now(),
false => {
dst_modified = std::time::SystemTime::UNIX_EPOCH;
log::error!("{}", err.to_string());
}
};
None
}
};
if !force && dst_modified.gt(&src_modified) {
log::error!(
"{}, {} seconds difference",
console::style("❌ Destination is newer than source")
.red()
.bold(),
(src_modified.elapsed()? - dst_modified.elapsed()?).as_secs(),
);
log::warn!(
"Use `{}` (with caution) to overwrite",
console::style("-f/--force").yellow().bold()
);
log::warn!(
"Use `{}` to only install this file/directory ",
console::style(format!(
"nedots install {}",
src.file_name().unwrap().to_string_lossy()
))
.yellow()
.bold()
);
log::warn!(
"The value must be part of the path defined in `{}`, and {}",
console::style("sources").yellow().italic(),
console::style("unique").yellow().bold()
);
return Ok(());
}
if let Some(dst_metadata) = dst_metadata {
#[cfg(unix)]
{
use std::os::linux::fs::MetadataExt;
if dst_metadata.st_uid().ne(&src_metadata.st_uid()) {
log::warn!("Insufficient permissions ({})", dst.display());
return Ok(());
}
}
if dst_metadata.len().ne(&src_metadata.len()) {
log::debug!(
"{} bytes difference ({})",
dst_metadata.len().abs_diff(src_metadata.len()),
dst.display()
);
}
}
if dry_run {
return Ok(());
} else {
super::gather::gather_file(src, dst)?;
}
}
Ok(())
}
#[derive(Debug, clap::Args)]
struct Symlink;
impl super::Command for Symlink {
fn run(&self, _: &super::nedots::RootCmd, _: &crate::config::Config) -> anyhow::Result<()> {
Ok(())
}
}