dotr 0.4.0

Very simple dotfile manager
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
//! `dotr` is a very simple dotfile manager
//!
//! It supports `link` and `unlink` operations and couple
//! of basic flags like `force`.
//!
//! I wrote it for myself, so it's in Rust and does exactly what I want, so I
//! can fix/customize if I need something. But hey, maybe it also does
//! exactly what you want too!
//!
//! ### Installation:
//!
//! * [Install Rust](https://www.rustup.rs/)
//!
//! ```norust
//! cargo install dotr
//! ```
//!
//! ### Usage:
//!
//! ```norust
//! dotr help
//! ```
//!
//! ### TODO:
//!
//! * Make it a separate library + binary

#[macro_use]
extern crate clap;
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_term;
extern crate walkdir;


use walkdir::{WalkDir, WalkDirIterator};
use std::path::{Path, PathBuf};
use std::{env, fs, io, process};
use slog::Drain;

fn create_logger(verbosity: Option<u32>) -> slog::Logger {
    match verbosity {
        None => slog::Logger::root(slog::Discard, o!()),
        Some(v) => {
            let level = match v {
                0 => slog::Level::Warning,
                1 => slog::Level::Info,
                2 => slog::Level::Debug,
                _ => slog::Level::Trace,
            };
            let drain = slog_term::term_compact();
            let drain = std::sync::Mutex::new(drain);
            let drain = slog::LevelFilter(drain, level);
            slog::Logger::root(drain.fuse(), o!())
        }
    }
}

fn should_traverse(de: &walkdir::DirEntry) -> bool {
    if !de.path().is_dir() {
        return true
    }

    if de.path().file_name().and_then(|s| s.to_str()) == Some(".git") {
        return false
    }

    return true
}

struct Dotr {
    force: bool,
    dry_run: bool,
    log: slog::Logger,
}

impl Dotr {
    fn new() -> Self {
        Dotr {
            force: false,
            dry_run: false,
            log: slog::Logger::root(slog::Discard, o!()),
        }
    }

    fn set_dry_run(&mut self) -> &mut Self {
        self.dry_run = true;
        self
    }

    fn set_force(&mut self) -> &mut Self {
        self.force = true;
        self
    }

    fn set_log(&mut self, log: slog::Logger) -> &mut Self {
        self.log = log;
        self
    }

    fn link(&self, src_base: &Path, dst_base: &Path) -> io::Result<()> {
        info!(self.log, "Starting link operation"; "src" => src_base.display(), "dst" => dst_base.display());

        if !dst_base.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Destination doesn't exist",
            ));
        }

        if !dst_base.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "Destination is not a directory",
            ));
        }

        let dst_base = dst_base.canonicalize()?;
        let src_base = src_base.canonicalize()?;

        assert!(dst_base.is_absolute());
        assert!(src_base.is_absolute());

        for src in WalkDir::new(&src_base)
            .into_iter()
            .filter_entry(should_traverse)
            .filter_map(|e| e.ok())
        {
            trace!(self.log, "Walking path"; "path" => src.path().display());

            let src = src.path();
            let src_rel = src.strip_prefix(&src_base).unwrap();
            let dst = dst_base.join(src_rel);
            let dst_metadata = dst.symlink_metadata().ok();
            let dst_type = dst_metadata.map(|m| m.file_type());


            let src_metadata = src.symlink_metadata()?;
            let src_type = src_metadata.file_type();

            let log = self.log.new(
                o!("src" => format!("{}", src.display()), "dst" => format!("{}", dst.display())),
            );

            if src_type.is_dir() {
                continue;
            } else if src_type.is_file() {
                trace!(log, "Source is a file"; );
                if dst.exists() || dst.symlink_metadata().is_ok() {
                    if self.force {
                        if !self.dry_run {
                            debug!(log, "Force removing destination");
                            fs::remove_file(&dst)?;
                        } else {
                            debug!(log, "Force removing destination (dry-run)");
                        }
                    } else {
                        if dst_type.map(|t| t.is_symlink()).unwrap_or(false) {
                            let dst_link_dst = dst.read_link()?;
                            if *dst_link_dst == *src {
                                debug!(log, "Destination already points to the source");
                                continue;
                            } else {
                                warn!(log, "Destination already exists and points elsewhere";
                                      "dst_dst" => %dst_link_dst.display());
                            }
                        } else {
                            warn!(log, "Destination already exists and is not a symlink");
                        }
                        continue;
                    }
                } else {
                    if !self.dry_run {
                        trace!(log, "Creating a base directory (if doesn't exist)");
                        fs::create_dir_all(dst.parent().unwrap())?;
                    }
                }

                if !self.dry_run {
                    trace!(log, "Creating symlink to a src file");
                    std::os::unix::fs::symlink(&src, &dst)?;
                }
            } else if src_type.is_symlink() {
                let src_link = src.read_link()?;
                trace!(log, "Source is a symlink"; "src-link" => &src_link.display());
                if dst.exists() || dst.symlink_metadata().is_ok() {
                    if self.force {
                        if !self.dry_run {
                            debug!(log, "Force removing destination");
                            fs::remove_file(&dst)?;
                        } else {
                            debug!(log, "Force removing destination (dry-run)");
                        }
                    } else if Some(src_link.clone()) == dst.read_link().ok() {
                        debug!(log, "Destination already points to the source (symlink source)");
                        continue;
                    } else {
                        warn!(log, "Destination already exists");
                        continue;
                    }
                } else {
                    if !self.dry_run {
                        trace!(log, "Creating a base directory (if doesn't exist)");
                        fs::create_dir_all(dst.parent().unwrap())?;
                    }
                }
                if !self.dry_run {
                    trace!(log, "Duplicating symlink"; "src-link" => src_link.display());
                    std::os::unix::fs::symlink(&src_link, &dst)?;
                }
            } else {
                warn!(log, "Skipping unknown source file type");
            }
        }

        Ok(())
    }
    fn unlink(&self, src_base: &Path, dst_base: &Path) -> io::Result<()> {
        info!(self.log, "Starting unlink operation"; "src" => src_base.display(), "dst" => dst_base.display());

        let dst_base = dst_base.canonicalize()?;
        let src_base = src_base.canonicalize()?;

        assert!(dst_base.is_absolute());
        assert!(src_base.is_absolute());

        for src in WalkDir::new(&src_base)
            .into_iter()
            .filter_entry(should_traverse)
            .filter_map(|e| e.ok())
        {
            trace!(self.log, "Walking path"; "path" => src.path().display());

            let src = src.path();
            let src_rel = src.strip_prefix(&src_base).unwrap();
            let dst = dst_base.join(src_rel);

            let src_metadata = src.symlink_metadata()?;
            let src_type = src_metadata.file_type();

            let log = self.log.new(
                o!("src" => format!("{}", src.display()), "dst" => format!("{}", dst.display())),
            );
            if src_type.is_dir() {
                continue;
            } else if src_type.is_file() {
                trace!(log, "Unlink a file");
                let dst_metadata = dst.symlink_metadata();
                // exists follows symlinks :/
                if dst.exists() || dst_metadata.is_ok() {
                    let dst_metadata = dst_metadata?;
                    if self.force {
                        if !self.dry_run {
                            debug!(log, "Force removing");
                            fs::remove_file(&dst)?;
                            continue;
                        } else {
                            debug!(log, "Force removing (dry run)");
                        }
                    } else {
                        if dst_metadata.file_type().is_file() {
                            warn!(log, "Destination already exists and is a file");
                            continue;
                        } else if dst_metadata.file_type().is_dir() {
                            warn!(log, "Destination already exists and is a directory");
                            continue;
                        } else if dst_metadata.file_type().is_symlink() {
                            let dst_link = dst.read_link()?;
                            if dst_link != src {
                                warn!(
                                    log,
                                    "Destination already exists and is a symlink pointing to something else"
                                );
                                continue;
                            } else {
                                if !self.dry_run {
                                    fs::remove_file(&dst)?;
                                }
                            }
                        } else {
                            warn!(log, "Destination exists and is of unknown file type");
                        }
                    }
                } else {
                    debug!(log, "Destination doesn't exist - nothing to unlink");
                    continue;
                }
            } else if src_type.is_symlink() {
                let src_link = src.read_link()?;
                trace!(log, "Unlink a symlink");
                let dst_metadata = dst.symlink_metadata();
                // exists follows symlinks :/
                if dst.exists() || dst_metadata.is_ok() {
                    let dst_metadata = dst_metadata?;
                    if self.force {
                        if !self.dry_run {
                            fs::remove_file(&dst)?;
                            continue;
                        }
                    } else {
                        if dst_metadata.file_type().is_file() {
                            warn!(log, "Destination already exists and is a file");
                            continue;
                        } else if dst_metadata.file_type().is_dir() {
                            warn!(log, "Destination already exists and is a directory");
                            continue;
                        } else if dst_metadata.file_type().is_symlink() {
                            let dst_link = dst.read_link()?;
                            if dst_link != src_link {
                                warn!(log,
                                      "Destination already exists and is a symlink pointing to something else";
                                      "dst-link" => dst_link.display(),
                                      "src-link" => src_link.display(),
                                      );
                                continue;
                            } else {
                                if !self.dry_run {
                                    fs::remove_file(&dst)?;
                                }
                            }
                        } else {
                            warn!(log, "Destination exists and is of unknown file type");
                        }
                    }
                } else {
                    debug!(log, "Destination doesn't exist - nothing to unlink");
                    continue;
                }
            } else {
                warn!(log, "Skipping unknown source file type");
            }
        }

        Ok(())
    }
}
#[derive(Copy, Clone)]
enum Command {
    Link,
    Unlink,
}

#[derive(Clone)]
struct Options {
    dst_dir: PathBuf,
    src_dir: PathBuf,
    command: Command,
    log: slog::Logger,
    dry_run: bool,
    force: bool,
}

impl Options {
    fn from_clap() -> io::Result<Options> {
        let mut dst_dir: Option<PathBuf> = None;
        let mut src_dir: PathBuf = PathBuf::from(".");
        let command;
        let mut dry_run = false;
        let mut force = false;
        //let mut command : Option<Command> = None;

        let matches = clap_app!(
            dotr =>
            (version: env!("CARGO_PKG_VERSION"))
            (author: "Dawid Ciężarkiewicz <dpc@dpc.pw>")
            (about: "Simple dotfile manager")
            (@arg DST_DIR: -d --dst +takes_value "Path to destination. Default: $HOME")
            (@arg SRC_DIR: -s --src +takes_value "Path to source. Default: .")
            (@arg VERBOSE: -v ... "Increase debugging level")
            (@arg DRY_RUN: --dry... "Dry run")
            (@arg FORCE: --force ... "Force overwrite/delete")
            (@subcommand link =>
             (about: "Link to files from SRC_DIR in DST_DIR")
            )
            (@subcommand unlink =>
             (about: "Remove links created by `link`")
            )
            ).setting(clap::AppSettings::SubcommandRequiredElseHelp)
            .get_matches();


        if let Some(dir) = matches.value_of_os("DST_DIR") {
            dst_dir = Some(dir.into());
        }

        if let Some(dir) = matches.value_of_os("SRC_DIR") {
            src_dir = Path::new(&dir).into();
        }

        if matches.is_present("DRY_RUN") {
            dry_run = true;
        }

        if matches.is_present("FORCE") {
            force = true;
        }

        let log = create_logger(Some(matches.occurrences_of("VERBOSE") as u32));

        match matches.subcommand() {
            ("link", _) => {
                command = Some(Command::Link);
            }
            ("unlink", _) => {
                command = Some(Command::Unlink);
            }
            _ => panic!("Unrecognized subcommand"),
        }

        let dst_dir = if let Some(dir) = dst_dir {
            dir
        } else {
            if let Some(home) = env::var_os("HOME") {
                Path::new(&home).into()
            } else {
                return Err(io::Error::new(io::ErrorKind::NotFound, "$HOME not set"));
            }
        };

        Ok(Options {
            dst_dir: dst_dir,
            src_dir: src_dir,
            command: command.unwrap(),
            dry_run: dry_run,
            force: force,
            log: log,
        })
    }
}

fn run() -> io::Result<()> {
    let options = Options::from_clap()?;

    let mut dotr = Dotr::new();

    dotr.set_log(options.log);

    if options.dry_run {
        dotr.set_dry_run();
    }

    if options.force {
        dotr.set_force();
    }

    match options.command {
        Command::Link => dotr.link(&options.src_dir, &options.dst_dir)?,
        Command::Unlink => dotr.unlink(&options.src_dir, &options.dst_dir)?,
    }

    Ok(())
}

fn main() {
    if let Err(e) = run() {
        eprintln!("Error: {}", e);
        process::exit(-1);
    }
}