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
//! `bak` is a Rust library for safely moving files out of the way.
//!
//! The API has a few methods, but the one to start with is
//! `bak::move_aside(PATH)`.
//!
//! `move_aside("foo")` will move the file or directory "foo" to
//! "foo.bak", if there isn't already something there. If there is
//! already a file called "foo.bak", it will move it to "foo.bak.0", and
//! so on.
//!
//! `move_aside()` returns an `io::Result<PathBuf>` containing the path
//! to the renamed file.
//!
//! You can call `move_aside_with_extension(PATH, EXTENSION)` if you'd
//! like to use an extension other than "bak". To see where a file would
//! be moved without actually moving it, call `destination_path(PATH)`
//! or `destination_with_extension(PATH, EXTENSION)`.
//!
//! ## caveats
//!
//! - If `bak` is in the middle of renaming a file from `foo` to
//!   `foo.bak`, and another process or thread concurrently creates a
//!   file called `foo.bak`, `bak` will silently overwrite the newly
//!   created `foo.bak` with `foo`. This is because `bak` uses
//!   `std::fs::rename`, which clobbers destination files.
#![deny(missing_docs)]

mod common;
mod error;
mod template;

#[cfg(test)]
mod testing;

const DEFAULT_EXTENSION: &str = "bak";

use crate::common::*;

/// Move aside `path` using the default extension, "bak".
pub fn move_aside(path: impl AsRef<Path>) -> io::Result<PathBuf> {
  move_aside_with_extension(path, DEFAULT_EXTENSION)
}

/// Move aside `path` using `extension`.
pub fn move_aside_with_extension(
  path: impl AsRef<Path>,
  extension: impl AsRef<OsStr>,
) -> io::Result<PathBuf> {
  let template = Template::new(path.as_ref())?;

  let source = template.source();

  let destination = template.destination(extension.as_ref())?;

  fs::rename(source, &destination)?;

  Ok(destination)
}

/// Get the destination that `path` would be moved to by `move_aside(path)`
/// without actually moving it.
pub fn destination(path: impl AsRef<Path>) -> io::Result<PathBuf> {
  destination_with_extension(path, DEFAULT_EXTENSION)
}

/// Get the destination that `path` would be moved to by
/// `move_aside(path, extension)` without actually moving it.
pub fn destination_with_extension(
  path: impl AsRef<Path>,
  extension: impl AsRef<OsStr>,
) -> io::Result<PathBuf> {
  Template::new(path.as_ref())?.destination(extension.as_ref())
}

#[cfg(test)]
mod tests {
  use super::*;

  use std::fs::File;

  macro_rules! test {
    {
      name:        $name:ident,
      files:       [$($file:expr),*],
      source:      $source:expr,
      extension:   $extension:expr,
      destination: $destination:expr,
    } => {
      #[test]
      fn $name() -> io::Result<()> {
        let mut files = Vec::new();
        $(
          {
            files.push(PathBuf::from($file));
          }
        )*;

        let source = PathBuf::from($source);

        let extension: Option<&OsStr> = $extension.map(|extension: &str| extension.as_ref());

        let desired_destination = PathBuf::from($destination);

        let tempdir = tempfile::tempdir()?;

        let base = tempdir.path();

        for file in &files {
          File::create(base.join(file))?;
        }

        let planned_destination = match extension {
          Some(extension) => destination_with_extension(base.join(&source), extension)?,
          None => destination(base.join(&source))?,
        };

        let planned_destination = planned_destination.strip_prefix(base.canonicalize()?).unwrap();

        assert_eq!(planned_destination, desired_destination);

        let actual_destination = match extension {
          Some(extension) => move_aside_with_extension(base.join(&source), extension)?,
          None => move_aside(base.join(&source))?,
        };

        let actual_destination = actual_destination.strip_prefix(base.canonicalize()?).unwrap();

        assert_eq!(actual_destination, desired_destination);

        let mut want = files.clone();
        want.retain(|file| file != &source);
        want.push(desired_destination);
        want.sort();

        let mut have = tempdir.path()
          .read_dir()?
          .map(|result| result.map(|entry| PathBuf::from(entry.file_name())))
          .collect::<io::Result<Vec<PathBuf>>>()?;
        have.sort();

        assert_eq!(have, want, "{:?} != {:?}", have, want);

        Ok(())
      }
    }
  }

  test! {
    name:        no_conflicts,
    files:       ["foo"],
    source:      "foo",
    extension:   None,
    destination: "foo.bak",
  }

  test! {
    name:        one_conflict,
    files:       ["foo", "foo.bak"],
    source:      "foo",
    extension:   None,
    destination: "foo.bak.0",
  }

  test! {
    name:        two_conflicts,
    files:       ["foo", "foo.bak", "foo.bak.0"],
    source:      "foo",
    extension:   None,
    destination: "foo.bak.1",
  }

  test! {
    name:        three_conflicts,
    files:       ["foo", "foo.bak", "foo.bak.0", "foo.bak.1"],
    source:      "foo",
    extension:   None,
    destination: "foo.bak.2",
  }

  test! {
    name:        no_conflicts_ext,
    files:       ["foo"],
    source:      "foo",
    extension:   Some("bar"),
    destination: "foo.bar",
  }

  test! {
    name:        one_conflict_ext,
    files:       ["foo", "foo.bar"],
    source:      "foo",
    extension:   Some("bar"),
    destination: "foo.bar.0",
  }

  test! {
    name:        two_conflicts_ext,
    files:       ["foo", "foo.bar", "foo.bar.0"],
    source:      "foo",
    extension:   Some("bar"),
    destination: "foo.bar.1",
  }

  test! {
    name:        three_conflicts_ext,
    files:       ["foo", "foo.bar", "foo.bar.0", "foo.bar.1"],
    source:      "foo",
    extension:   Some("bar"),
    destination: "foo.bar.2",
  }
}