symp 0.5.0

symlink farm manager that utilizes configuration files to define symlink mappings
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
use std::io::ErrorKind;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::LazyLock;
use std::{fs, io, path};

use serde::{Deserialize, Serialize};
use symlink::{remove_symlink_auto, symlink_auto};

static ROOT_DIR: LazyLock<AbsPath> = LazyLock::new(|| AbsPath::_new(PathBuf::from("/")));

/// A path that is guaranteed to be absolute.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(transparent)]
pub struct AbsPath {
    path_buf: PathBuf,
}

impl AbsPath {
    /// Create a new [`AbsPath`] (the path will be the root directory of the filesystem).
    pub fn new() -> AbsPath {
        ROOT_DIR.clone()
    }

    /// Turn a path into an [`AbsPath`].
    pub fn from_path(path: &Path) -> io::Result<Self> {
        if path.is_absolute() {
            Ok(AbsPath::_new(path.to_path_buf()))
        } else {
            Ok(AbsPath::_new(path::absolute(path)?))
        }
    }

    /// Convert a path into an [`AbsPath`].
    pub fn from_owned_path(path: PathBuf) -> io::Result<Self> {
        if path.is_absolute() {
            Ok(AbsPath::_new(path))
        } else {
            Ok(AbsPath::_new(path::absolute(path)?))
        }
    }

    /// Returns the relative path to the [`AbsPath`] from
    /// another [`AbsPath`].
    ///
    /// The returned path is guaranteed to _NOT_ be absolute.
    pub fn relative_to(&self, other: &AbsPath) -> PathBuf {
        if other.eq(self) {
            return PathBuf::from_str(".").expect("infallible");
        }
        if other.eq(&ROOT_DIR) {
            return self._relative_to_root().to_path_buf();
        }
        if self.starts_with(other) {
            // unwrap is okay because we know `self` is prefixed by `other`.
            return self.strip_prefix(other).unwrap().to_path_buf();
        }
        let mut relative_path = PathBuf::new();
        let mut current: &Path = other.as_ref();
        let mut parent = other.parent();
        while let Some(path) = parent {
            relative_path.push("..");
            current = path;
            if self.starts_with(current) {
                break;
            }
            parent = path.parent();
        }
        if current.eq(self.as_ref()) {
            relative_path
        } else {
            relative_path.join(self.strip_prefix(current).unwrap())
        }
    }

    /// Helper function for getting the relative path
    /// from the current working directory to this path.
    ///
    /// An error is returned if the current working directory
    /// could not be retrieved.
    pub fn relative_to_cwd(&self) -> io::Result<PathBuf> {
        let cwd = std::env::current_dir()?;
        Ok(self.relative_to(&AbsPath::_new(cwd)))
    }

    /// Returns either the parent of the [`AbsPath`] or (if
    /// the path has no parent) the root directory.
    pub fn parent_or_root(&self) -> AbsPath {
        match self.parent() {
            Some(parent) => AbsPath::_new(parent.to_path_buf()),
            None => ROOT_DIR.clone(),
        }
    }

    fn _new(path_buf: PathBuf) -> Self {
        AbsPath { path_buf }
    }

    fn _relative_to_root(&self) -> &Path {
        self.strip_prefix("/").expect("path is absolute")
    }
}

impl Default for AbsPath {
    /// Returns [`AbsPath`] representing the root directory of the filesystem.
    fn default() -> Self {
        AbsPath::new()
    }
}

impl Deref for AbsPath {
    type Target = Path;

    fn deref(&self) -> &Self::Target {
        &self.path_buf
    }
}

impl AsRef<Path> for AbsPath {
    fn as_ref(&self) -> &Path {
        &self.path_buf
    }
}

impl FromStr for AbsPath {
    type Err = io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        AbsPath::from_path(&PathBuf::from_str(s).expect("infallible"))
    }
}

impl From<AbsPath> for PathBuf {
    fn from(value: AbsPath) -> Self {
        value.path_buf
    }
}

/// Provides function to change the root directory of a path.
pub trait JoinOnRoot {
    /// Attach path to root directory.
    ///
    /// Relative paths are treated as relative to the provided root path
    /// (_NOT_ to the current directory).
    fn join_on_root(&self, root: &AbsPath) -> AbsPath;
}

impl JoinOnRoot for Path {
    fn join_on_root(&self, root: &AbsPath) -> AbsPath {
        // Because root is an absolute path, `path::absolute` cannot return an error for
        // either an empty path nor for `std::env::current_dir` returning an error (this
        // function is only called if the input path is not absolute). So we are okay to unwrap.
        AbsPath::_new(path::absolute(root.join(self.strip_prefix("/").unwrap_or(self))).unwrap())
    }
}

impl JoinOnRoot for AbsPath {
    fn join_on_root(&self, root: &AbsPath) -> AbsPath {
        // Because root is an absolute path, `path::absolute` cannot return an error for
        // either an empty path nor for `std::env::current_dir` returning an error (this
        // function is only called if the input path is not absolute). So we are okay to unwrap.
        AbsPath::_new(path::absolute(root.join(self._relative_to_root())).unwrap())
    }
}

/// Representation of a symlink on the filesystem.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct Symlink {
    pub source: AbsPath,
    pub destination: AbsPath,
}

impl Symlink {
    pub fn new(source: AbsPath, destination: AbsPath) -> Self {
        Symlink {
            source,
            destination,
        }
    }

    /// Whether the symlink exists.
    pub fn exists(&self) -> bool {
        matches!(self.status(), SymlinkStatus::Exists)
    }

    /// Whether the symlink is broken.
    pub fn is_broken(&self) -> bool {
        matches!(self.status(), SymlinkStatus::Broken)
    }

    /// Status (Exists, Broken, NoSymlink) of the symlink.
    pub fn status(&self) -> SymlinkStatus {
        if self.destination.is_symlink() {
            return if let Ok(source) = self.destination.read_link()
                && source.eq(&self.source.path_buf)
                && source.exists()
            {
                SymlinkStatus::Exists
            } else {
                SymlinkStatus::Broken
            };
        }
        SymlinkStatus::NoSymlink
    }

    /// Create the symlink on the filesystem.
    ///
    /// Returns [`Ok(())`] if the symlink already exists or was successfully created.
    /// Otherwise, an error is returned.
    pub fn create(&self) -> io::Result<()> {
        if !self.source.exists() {
            Err(io::Error::new(
                ErrorKind::NotFound,
                format!("Source does not exist: {}", self.source.display()),
            ))
        } else if self.exists() {
            Ok(())
        } else {
            if let Some(parent) = self.destination.parent()
                && !parent.exists()
            {
                fs::create_dir_all(parent)?;
            }
            symlink_auto(&self.source, &self.destination)?;
            Ok(())
        }
    }

    /// Remove the symlink on the filesystem.
    ///
    /// Returns [`Ok(())`] if the symlink did not exist or was removed.
    /// Otherwise, an error is returned.
    pub fn remove(&self) -> io::Result<()> {
        match self.status() {
            SymlinkStatus::NoSymlink => {}
            _ => remove_symlink_auto(&self.destination)?,
        }
        Ok(())
    }
}

/// Representation of the symlink's status on the filesystem.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymlinkStatus {
    Exists,
    Broken,
    NoSymlink,
}

/// Create absolute path after resolving '~' and environment variables in string.
pub fn expand_to_path(s: &str) -> io::Result<PathBuf> {
    Ok(PathBuf::from_str(
        shellexpand::full(s)
            .map_err(|err| io::Error::new(ErrorKind::NotFound, err))?
            .to_string()
            .as_str(),
    )
    .expect("infallible"))
}

pub fn move_to_backup(path: &AbsPath) -> io::Result<()> {
    let mut i: u8 = 0;
    let mut backup_path = path.with_added_extension(format!("bkp-{i}"));
    while backup_path.exists() && i < 100 {
        i += 1;
        backup_path = path.with_added_extension(format!("bkp-{i}"));
    }
    if i >= 50 {
        return Err(io::Error::other(format!(
            "Too many backups for {}",
            path.display()
        )));
    }
    if path.is_symlink() {
        let source = path.read_link()?;
        symlink::remove_symlink_auto(path)?;
        symlink::symlink_auto(&source, backup_path)?;
    } else {
        fs::rename(path, backup_path)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs::File;
    use std::io::Write;

    use anyhow;
    use tempfile::tempdir;

    use super::*;

    #[test]
    fn relative_to() {
        let a = AbsPath::from_str("/hello").unwrap();
        let b = AbsPath::from_str("/hello/kitty").unwrap();
        let c = AbsPath::from_str("/hello/kitty/cat").unwrap();
        let d = AbsPath::from_str("/hello/world").unwrap();
        let e = AbsPath::from_str("/goodbye/eri").unwrap();

        // test same path produces "."
        assert_eq!(a.relative_to(&a), PathBuf::from_str(".").unwrap());
        assert_eq!(c.relative_to(&c), PathBuf::from_str(".").unwrap());

        // test child relative to parent
        assert_eq!(b.relative_to(&a), PathBuf::from_str("kitty").unwrap());
        assert_eq!(c.relative_to(&a), PathBuf::from_str("kitty/cat").unwrap());

        // test parent relative to child
        assert_eq!(a.relative_to(&b), PathBuf::from_str("..").unwrap());
        assert_eq!(a.relative_to(&c), PathBuf::from_str("../..").unwrap());

        // test common parent
        assert_eq!(
            c.relative_to(&d),
            PathBuf::from_str("../kitty/cat").unwrap()
        );
        assert_eq!(d.relative_to(&c), PathBuf::from_str("../../world").unwrap());

        // test no common parent (except root dir)
        assert_eq!(
            c.relative_to(&e),
            PathBuf::from_str("../../hello/kitty/cat").unwrap()
        );
        assert_eq!(
            e.relative_to(&c),
            PathBuf::from_str("../../../goodbye/eri").unwrap()
        );
    }

    #[test]
    fn symlink_file() -> anyhow::Result<()> {
        let tmp = tempdir()?;
        let source = AbsPath::from_path(&tmp.path().join("s"))?;
        let destination = AbsPath::from_path(&tmp.path().join("t"))?;
        let symlink = Symlink::new(source.clone(), destination.clone());

        assert!(!symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::NoSymlink);

        let mut file = File::create(&source)?;
        file.write_all(b"Trans rights!")?;
        file.sync_all()?;

        assert!(!symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::NoSymlink);

        symlink.create()?;

        assert!(destination.is_symlink());
        assert_eq!(destination.read_link()?, source.to_path_buf());
        assert_eq!(fs::read_to_string(&destination)?, "Trans rights!");
        assert!(symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::Exists);

        fs::remove_file(&source)?;

        assert!(!symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::Broken);

        tmp.close()?;
        Ok(())
    }

    #[test]
    fn symlink_dir() -> anyhow::Result<()> {
        let tmp = tempdir()?;
        let source = AbsPath::from_path(&tmp.path().join("s"))?;
        let destination = AbsPath::from_path(&tmp.path().join("t"))?;
        let symlink = Symlink::new(source.clone(), destination.clone());

        assert!(!symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::NoSymlink);

        fs::create_dir(&source)?;

        assert!(!symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::NoSymlink);

        symlink.create()?;

        assert!(destination.is_symlink());
        assert_eq!(destination.read_link()?, source.to_path_buf());
        assert!(symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::Exists);

        fs::remove_dir(&source)?;

        assert!(!symlink.exists());
        assert_eq!(symlink.status(), SymlinkStatus::Broken);

        tmp.close()?;
        Ok(())
    }

    #[test]
    fn backup_file() -> anyhow::Result<()> {
        let tmp = tempdir()?;
        let orig = AbsPath::from_owned_path(tmp.path().join("orig_file"))?;

        let mut file = File::create(&orig)?;
        file.write_all(b"This memorial dedicated to those Who perished on the climb")?;
        file.sync_all()?;

        assert!(orig.exists());

        move_to_backup(&orig)?;

        assert!(!orig.exists());
        assert!(orig.with_added_extension("bkp-0").exists());
        assert_eq!(
            fs::read_to_string(orig.with_added_extension("bkp-0"))?,
            "This memorial dedicated to those Who perished on the climb"
        );

        fs::remove_file(orig.with_added_extension("bkp-0"))?;

        let mut file = File::create(&orig)?;
        file.write_all(b"This memorial dedicated to those Who perished on the climb")?;
        file.sync_all()?;
        for i in 0..3 {
            File::create(orig.with_added_extension(format!("bkp-{i}")))?;
        }
        move_to_backup(&orig)?;

        assert!(!orig.exists());
        assert!(orig.with_added_extension("bkp-3").exists());
        assert_eq!(
            fs::read_to_string(orig.with_added_extension("bkp-3"))?,
            "This memorial dedicated to those Who perished on the climb"
        );

        tmp.close()?;
        Ok(())
    }

    #[test]
    fn backup_dir() -> anyhow::Result<()> {
        let tmp = tempdir()?;
        let orig = AbsPath::from_owned_path(tmp.path().join("orig_dir"))?;

        fs::create_dir(&orig)?;

        assert!(orig.exists());

        move_to_backup(&orig)?;

        assert!(!orig.exists());
        assert!(orig.with_added_extension("bkp-0").exists());

        fs::remove_dir(orig.with_added_extension("bkp-0"))?;

        fs::create_dir(&orig)?;
        for i in 0..3 {
            fs::create_dir(orig.with_added_extension(format!("bkp-{i}")))?;
        }
        move_to_backup(&orig)?;

        assert!(!orig.exists());
        assert!(orig.with_added_extension("bkp-3").exists());

        tmp.close()?;
        Ok(())
    }

    #[test]
    fn expand_path() -> anyhow::Result<()> {
        // this is okay because we are (1) running single threaded, where set_var
        // is safe, and (2) this is in a test case.
        unsafe {
            std::env::set_var("SYMP_TEST_VAR", "/tmp");
        }
        assert_eq!(
            expand_to_path("$SYMP_TEST_VAR/howdy")?,
            PathBuf::from_str("/tmp/howdy")?
        );

        assert_eq!(
            expand_to_path("~/blåhaj")?,
            PathBuf::from_str(
                format!("{}/blåhaj", std::env::home_dir().unwrap().display()).as_str()
            )?
        );
        Ok(())
    }
}