mksls 2.0.0

Make symlinks specified in files.
Documentation
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
use anyhow::Context;
use crossterm::style::Stylize;
use std::fs;
use std::io::Write;
use std::os::unix;
use std::path::Path;

pub fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}

/// Skips symlink creation when conflict encountered, i.e. when `link`
/// already points to a file.
///
/// Does nothing apart from writing feedback into `writer` in the form of:
///
/// ```text
/// (s) <link> -> <target>
/// ```
///
/// in dark blue.
///
/// # Parameters
///
/// - `writer`: Where to write feeback to.
/// - `target`: Path to the target of the symlink.
/// - `link`: Path to the symlink.
pub fn skip<W: Write>(mut writer: W, target: &Path, link: &Path) -> anyhow::Result<()> {
    writeln!(
        writer,
        "{}",
        format!(
            "(s) {} -> {}",
            link.to_string_lossy(),
            target.to_string_lossy()
        )
        .dark_blue()
    )?;

    Ok(())
}

/// Backs up the existing file at path `link`, then makes the symlink
/// at path `link`, pointing to `target`.
///
/// Finally, writes feeback into `writer` in the form of:
///
/// ```text
/// (b) <link> -> <target>
/// ```
///
/// in dark green.
///
/// # Parameters
///
/// - `writer`: Where to write feedback to.
/// - `backup_dir`: Path to backup directory.
/// - `target`: Path to the target of the symlink.
/// - `link`: Path to the symlink.
///
/// # Errors
///
/// Fails when:
///
/// - The existing file fails to be backed up, i.e. fails to be moved
///   to the backup directory.
/// - The symlink creation fails.
/// - Writing into `writer` fails.
///
/// These are `anyhow` errors, so most of the time, you just want to
/// propagate them.
pub fn backup<W: Write>(
    mut writer: W,
    backup_dir: &Path,
    target: &Path,
    link: &Path,
) -> anyhow::Result<()> {
    let mut new_name;
    match link.file_stem() {
        Some(file_stem) => {
            new_name = format!(
                "{}_backup_{}",
                file_stem.to_string_lossy(),
                chrono::Local::now().to_rfc3339()
            );
            if let Some(extension) = link.extension() {
                new_name.push_str(&format!(".{}", extension.to_string_lossy()));
            }
        }
        None => {
            new_name = String::from(".");
            if let Some(extension) = link.extension() {
                new_name.push_str(&format!(
                    "{}_backup_{}",
                    extension.to_string_lossy(),
                    chrono::Local::now().to_rfc3339()
                ));
            }
        }
    }

    let mut backup = backup_dir.to_path_buf();
    backup.push(new_name);

    fs::rename(link, &backup).with_context(|| {
        format!(
            "Failed to backup! Couldn't move {} to {}",
            link.display(),
            backup.display()
        )
    })?;

    unix::fs::symlink(target, link).with_context(|| {
        format!(
            "Failed to create {} -> {}",
            link.to_string_lossy(),
            target.to_string_lossy()
        )
    })?;

    writeln!(
        writer,
        "{}",
        format!(
            "(b) {} -> {}",
            link.to_string_lossy(),
            target.to_string_lossy()
        )
        .dark_green()
    )?;

    Ok(())
}

/// Overwrites existing file at path `link` by making a symlink
/// at path `link` (pointing to `target`) without backup.
///
/// Finally, writes feeback into `writer` in the form of:
///
/// ```text
/// (o) <link> -> <target>
/// ```
///
/// in dark red.
///
/// # Parameters
///
/// - `writer`: Where to write feedback to.
/// - `target`: Path to the target of the symlink.
/// - `link`: Path to the symlink.
///
/// # Errors
///
/// Fails when:
///
/// - The existing file fails to be removed.
/// - The symlink creation fails.
/// - Writing into `writer` fails.
///
/// These are `anyhow` errors, so most of the time, you just want to
/// propagate them.
pub fn overwrite<W: Write>(mut writer: W, target: &Path, link: &Path) -> anyhow::Result<()> {
    if link.is_dir() {
        fs::remove_dir_all(link)
            .with_context(|| format!("Failed to remove current directory {} to then make the symlink with the same path.", link.to_string_lossy()))?;
    } else {
        fs::remove_file(link).with_context(|| {
            format!(
                "Failed to remove current file {} to then make the symlink with the same path.",
                link.to_string_lossy()
            )
        })?;
    }

    unix::fs::symlink(target, link).with_context(|| {
        format!(
            "Failed to create {} -> {}",
            link.to_string_lossy(),
            target.to_string_lossy()
        )
    })?;

    writeln!(
        writer,
        "{}",
        format!(
            "(o) {} -> {}",
            link.to_string_lossy(),
            target.to_string_lossy()
        )
        .dark_red()
    )?;

    Ok(())
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use crate::dir::Dir;
    use assert_fs::fixture::NamedTempFile;
    use assert_fs::fixture::TempDir;
    use assert_fs::prelude::*;
    use predicates::prelude::*;
    use std::path::PathBuf;
    use std::str;

    pub fn vec_are_equal<T: Eq>(v1: &Vec<T>, v2: &Vec<T>) -> bool {
        v1.len() == v2.len() && v1.iter().fold(true, |acc, el| acc && v2.contains(el))
    }

    #[test]
    fn skip_feedback_has_right_format() {
        let mut feedback = vec![];
        let target = PathBuf::from("/target");
        let link = PathBuf::from("/link");

        skip(&mut feedback, &target, &link).expect("Expected to be able to write into `feedback`.");
        let feedback = str::from_utf8(&feedback[..]).expect("Should be valid utf-8 characters.");

        let expected_feedback = format!(
            "(s) {} -> {}",
            link.to_string_lossy(),
            target.to_string_lossy()
        )
        .dark_blue()
        .to_string();

        assert!(
            feedback.contains(&expected_feedback[..]),
            "Expected '{}' to contain '{}'.",
            feedback,
            expected_feedback,
        );
    }

    #[test]
    fn backup_feedback_has_right_format() -> Result<(), Box<dyn std::error::Error>> {
        let mut feedback = vec![];
        let backup_dir = TempDir::new()?;
        let target = NamedTempFile::new("target")?;
        target.touch()?;
        let conflicting_file = NamedTempFile::new("conflicting_file")?;
        conflicting_file.write_str("Contents of conflicting file.")?;

        backup(&mut feedback, &backup_dir, &target, &conflicting_file)?;
        let feedback = str::from_utf8(&feedback[..]).expect("Should be valid utf-8 characters.");

        let expected_feedback = format!(
            "(b) {} -> {}",
            conflicting_file.to_string_lossy(),
            target.to_string_lossy()
        )
        .dark_green()
        .to_string();

        assert!(
            feedback.contains(&expected_feedback[..]),
            "Expected '{}' to contain '{}'.",
            feedback,
            expected_feedback,
        );

        // Ensure deletion happens.
        backup_dir.close()?;
        target.close()?;
        conflicting_file.close()?;

        Ok(())
    }

    #[test]
    fn backup_backs_up_file_as_expected() -> Result<(), Box<dyn std::error::Error>> {
        let mut feedback = vec![];
        let backup_dir = TempDir::new()?;
        let dir = TempDir::new()?;
        let conflicting_file_name = "link";
        let conflicting_file = dir.child(conflicting_file_name);
        let conflicting_file_contents = "Contents of conflicting file.";
        conflicting_file.write_str(conflicting_file_contents)?;
        let target = NamedTempFile::new("target")?;
        target.touch()?;

        backup(&mut feedback, &backup_dir, &target, &conflicting_file)?;

        // Check that a file containing the name of `conflicting_file` exists in `backup_dir`.
        let d = Dir::build(backup_dir.to_path_buf())
            .expect("Path of `backup_dir` should be valid at this point.");
        let mut at_least_one_file_containing_conflicting_file_name = false;
        let mut backup_file: Option<PathBuf> = None;
        for file in d.iter_on_files() {
            if file
                .file_name()
                .unwrap()
                .to_string_lossy()
                .contains(conflicting_file_name)
            {
                backup_file = Some(file.clone());
                at_least_one_file_containing_conflicting_file_name = true;
            }
        }
        assert!(at_least_one_file_containing_conflicting_file_name);

        // Check that `backup_file` has the contents of the conflicting file.
        let backup_file = backup_file.expect(
            "Should have found a file containing the name of `conflicting_file` in `backup_dir`.",
        );
        let backup_file_contents = std::fs::read_to_string(backup_file)?;
        assert_eq!(backup_file_contents, conflicting_file_contents);

        // Ensure deletion happens.
        backup_dir.close()?;
        dir.close()?;
        target.close()?;

        Ok(())
    }

    #[test]
    fn backup_fails_when_no_conflicting_file() -> Result<(), Box<dyn std::error::Error>> {
        let mut feedback = vec![];
        let backup_dir = TempDir::new()?;
        // Do not touch or write to `conflicting_file` so that it doesn't actually exist in the file system.
        let conflicting_file = NamedTempFile::new("conflicting_file")?;
        let target = NamedTempFile::new("target")?;

        assert!(backup(&mut feedback, &backup_dir, &target, &conflicting_file).is_err());

        // Ensure deletion happens.
        backup_dir.close()?;
        target.close()?;

        Ok(())
    }

    #[test]
    fn overwrite_feedback_has_right_format() -> Result<(), Box<dyn std::error::Error>> {
        let mut feedback = vec![];
        let backup_dir = TempDir::new()?;
        let target = NamedTempFile::new("target")?;
        target.touch()?;
        let conflicting_file = NamedTempFile::new("conflicting_file")?;
        conflicting_file.write_str("Contents of conflicting file.")?;

        overwrite(&mut feedback, &target, &conflicting_file)?;
        let feedback = str::from_utf8(&feedback[..]).expect("Should be valid utf-8 characters.");

        let expected_feedback = format!(
            "(o) {} -> {}",
            conflicting_file.to_string_lossy(),
            target.to_string_lossy()
        )
        .dark_red()
        .to_string();

        assert!(
            feedback.contains(&expected_feedback[..]),
            "Expected '{}' to contain '{}'.",
            feedback,
            expected_feedback,
        );

        // Ensure deletion happens.
        backup_dir.close()?;
        target.close()?;
        conflicting_file.close()?;

        Ok(())
    }

    #[test]
    fn overwrite_overwrites_file_as_expected() -> Result<(), Box<dyn std::error::Error>> {
        let mut feedback = vec![];
        let conflicting_file_name = "link";
        let conflicting_file = NamedTempFile::new(conflicting_file_name)?;
        let conflicting_file_contents = "Contents of conflicting file.";
        conflicting_file.write_str(conflicting_file_contents)?;
        let target = NamedTempFile::new("target")?;
        target.touch()?;

        overwrite(&mut feedback, &target, &conflicting_file)?;

        // Check that a symlink to `target` exists in place of `conflicting_file`.
        assert!(predicate::path::is_symlink().eval(&conflicting_file));
        assert_eq!(
            std::fs::canonicalize(&conflicting_file).unwrap(),
            target.path()
        );

        // Ensure deletion happens.
        target.close()?;
        conflicting_file.close()?;

        Ok(())
    }

    #[test]
    fn overwrite_fails_when_no_conflicting_file() -> Result<(), Box<dyn std::error::Error>> {
        let mut feedback = vec![];
        // Do not touch or write to `conflicting_file` so that it doesn't actually exist in the file system.
        let conflicting_file = NamedTempFile::new("conflicting_file")?;
        let target = NamedTempFile::new("target")?;
        target.touch()?;

        assert!(overwrite(&mut feedback, &target, &conflicting_file).is_err());

        // Ensure deletion happens.
        conflicting_file.close()?;
        target.close()?;

        Ok(())
    }
}