~whynothugo/dotfiles

ref: 004c9fa5b90e6ccfa6ce9c86b6efcfa9330a81e2 dotfiles/src/main.rs -rw-r--r-- 7.8 KiB
004c9fa5Hugo Osvaldo Barrera clone: simplify call check a year ago
                                                                                
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
use clap::Parser;
use home::home_dir;
use serde::Deserialize;
use std::fmt::Display;
use std::fs::create_dir_all;
use std::fs::remove_file;
use std::os::unix::fs::symlink;
use std::path::Path;
use std::{
    env::set_current_dir,
    fs::File,
    io::{self, BufReader, Read},
    path::PathBuf,
};
use yansi::Color;

#[derive(Deserialize)]
struct Config {
    // TODO: Switch to a different approach.
    // ... The toml file should list directories to link as such.
    // ... All files that are NOT children of this directory are linked directly.
    // ... This would require walking all file in the repo (see TODO below).
    symlinks: Vec<String>,
}

// TODO: show a warning ("unreachable") for any git-tracked file that is not
//       symlinked and does not have a symlinked parent.
impl Config {
    fn read_from_path<P>(path: P) -> io::Result<Config>
    where
        P: AsRef<Path>,
    {
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);

        // This bit can be simplified one this PR is merged:
        // https://github.com/toml-rs/toml/pull/349
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf)?;
        let mut config = toml::de::from_slice::<Config>(&buf)?;

        for i in 0..config.symlinks.len() {
            if let Some(stripped) = config.symlinks[i].strip_suffix('/') {
                config.symlinks[i] = stripped.to_string();
            }
        }

        Ok(config)
    }
}

struct Context {
    /// Home directory.
    home: PathBuf,
    /// Directory containing files that should be linked from $HOME.
    repo: PathBuf,
    /// Current configuration.
    config: Config,
}

impl Context {
    fn new(repo: &Path, home: &Path) -> io::Result<Context> {
        Ok(Context {
            home: home.into(),
            repo: repo.join("home"),
            config: Config::read_from_path(repo.join("dotfiles.toml"))?,
        })
    }

    fn home_path<P>(&self, path: P) -> PathBuf
    where
        P: AsRef<Path>,
    {
        self.home.join(path)
    }

    fn repo_path<P>(&self, path: P) -> PathBuf
    where
        P: AsRef<Path>,
    {
        self.repo.join(path)
    }

    fn get_linked_paths(&self) -> Vec<Link> {
        let mut paths = Vec::new();

        // TODO: walk source directory:
        // if dir && listed -> symlink
        // if dir && !listed -> walk
        // if !dir -> symlink

        for dir in &self.config.symlinks {
            paths.push(Link::new(PathBuf::from(dir), self));
        }

        paths.sort_unstable_by_key(|link| link.path.clone());
        paths
    }

    fn state_for_path<P>(&self, path: P) -> io::Result<PathState>
    where
        P: AsRef<Path>,
    {
        let home_path = self.home_path(&path);

        let state = if home_path.exists() {
            if home_path.canonicalize()? == self.repo.join(path).canonicalize()? {
                PathState::Fine
            } else if home_path.is_symlink() {
                PathState::BadLink
            } else {
                PathState::Conflict
            }
        } else if !home_path.is_symlink() {
            PathState::Missing
        } else {
            PathState::Broken
        };

        Ok(state)
    }
}

#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
enum PathState {
    Fine,     // Link points to dotfiles repo.
    Missing,  // File is missing.
    Broken,   // Link exists and is broken.
    BadLink,  // Link exists and points to another file.
    Conflict, // Not a link.
    Error(String),
}

impl PathState {
    fn colour(&self) -> Color {
        match self {
            PathState::Missing => Color::Cyan,
            PathState::Broken => Color::Yellow,
            PathState::BadLink => Color::Magenta,
            PathState::Conflict => Color::Red,
            PathState::Fine => Color::Green,
            PathState::Error(_) => Color::Red,
        }
    }
}

impl Display for PathState {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_fmt(format_args!("{:?}", self.colour().paint(self),))
    }
}

impl From<io::Result<PathState>> for PathState {
    fn from(item: io::Result<PathState>) -> Self {
        match item {
            Ok(state) => state,
            Err(err) => PathState::Error(err.to_string()),
        }
    }
}

#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
struct Link {
    // Sorting happens based on field sorting from top to bottom.
    state: PathState,
    new_state: Option<PathState>,
    path: PathBuf,
}

impl Display for Link {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.new_state {
            Some(new_state) => formatter.write_fmt(format_args!(
                "{} -> {} {}",
                self.state,
                new_state,
                self.path.to_string_lossy(),
            )),
            None => formatter.write_fmt(format_args!(
                "{} {}",
                self.state,
                self.path.to_string_lossy(),
            )),
        }
    }
}

impl Link {
    fn new(path: PathBuf, context: &Context) -> Link {
        let state = context.state_for_path(&path);

        Link {
            path,
            state: state.into(),
            new_state: None,
        }
    }

    // Creates the link, if possible.
    // Nothing  is returned; the link's internal `state` is mutated.
    fn create_link(&mut self, context: &Context) {
        let link_name = context.home_path(&self.path);
        let parent_dir = link_name
            .parent()
            .expect("symlink file has a parent directory");

        self.new_state = Some(match create_dir_all(parent_dir) {
            Err(err) => PathState::Error(err.to_string()), // Directory creation failed.
            Ok(_) => match symlink(context.repo_path(&self.path), link_name) {
                Ok(()) => PathState::Fine,
                Err(err) => PathState::Error(err.to_string()),
            },
        });
    }

    // Apply necessary changes for this link to be valid.
    fn apply(&mut self, context: &Context) {
        match self.state {
            PathState::Missing => {
                self.create_link(context);
            }
            PathState::Broken | PathState::BadLink => {
                let home_path = context.home_path(&self.path);
                match remove_file(home_path) {
                    Ok(()) => self.create_link(context),
                    Err(err) => self.new_state = Some(PathState::Error(err.to_string())),
                };
            }
            PathState::Conflict => {
                // TODO: Is there anything we CAN do here?
                // TODO: If the files are byte-to-byte identical, then overwriting with a symlink is safe.
                // no-op
            }
            PathState::Fine | PathState::Error(_) => {
                // no-op
            }
        }
    }
}

/// Simple tool that symlinks files from a dotfiles repo into their expected location in $HOME.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct DotSync {
    /// Show plan but don't make any changes.
    #[arg(short, long)]
    dry_run: bool,
}

fn main() {
    let matches = DotSync::parse();

    let cwd = std::env::current_dir().expect("can determine current directory");
    let home = home_dir().expect("could find home dir");
    let context = Context::new(&cwd, &home).expect("context initialised");

    set_current_dir(&context.repo).expect("change directory into $REPO/home.");
    let mut paths = context.get_linked_paths();

    // TODO: Warn about paths that are neither linked, nor children of linked directories.

    if matches.dry_run {
        println!("Dry run: not applying any changes",);
    } else {
        for path in &mut paths {
            path.apply(&context);
        }
    };

    paths.sort();

    for path in &paths {
        println!("{}", path);
    }

    // TODO: print a global results (no-op/dry-run/ok/partial/error).
}