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
/* Copyright (c) 2018 Garrett Berg, vitiral@gmail.com
 *
 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
 * http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
 * http://opensource.org/licenses/MIT>, at your option. This file may not be
 * copied, modified, or distributed except according to those terms.
 */
use std::fs;
use std::fmt;
use std::io;
use std_prelude::*;

use super::{Error, Result};
use super::{FileEdit, FileRead, FileWrite, PathAbs, PathArc};

#[derive(Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
/// a `PathAbs` that was a file at the time of initialization, with associated methods.
pub struct PathFile(pub(crate) PathAbs);

impl PathFile {
    /// Instantiate a new `PathFile`. The file must exist or `io::Error` will be returned.
    ///
    /// Returns `io::ErrorKind::InvalidInput` if the path exists but is not a file.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let lib = PathFile::new("src/lib.rs")?;
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn new<P: AsRef<Path>>(path: P) -> Result<PathFile> {
        let abs = PathAbs::new(path)?;
        PathFile::from_abs(abs)
    }

    /// Consume the `PathAbs` validating that the path is a file and returning `PathFile`. The file
    /// must exist or `io::Error` will be returned.
    ///
    /// If the path is actually a dir returns `io::ErrorKind::InvalidInput`.
    ///
    /// > This does not call [`Path::cannonicalize()`][1], instead trusting that the input is
    /// > already a fully qualified path.
    ///
    /// [1]: https://doc.rust-lang.org/std/path/struct.Path.html?search=#method.canonicalize
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// use path_abs::{PathAbs, PathFile};
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let lib_abs = PathAbs::new("src/lib.rs")?;
    /// let lib_file = PathFile::from_abs(lib_abs)?;
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn from_abs(abs: PathAbs) -> Result<PathFile> {
        if abs.is_file() {
            Ok(PathFile::from_abs_unchecked(abs))
        } else {
            Err(Error::new(
                io::Error::new(io::ErrorKind::InvalidInput, "path is not a file"),
                "resolving",
                abs.into(),
            ))
        }
    }

    #[inline(always)]
    /// Do the conversion _without checking_.
    ///
    /// This is typically used by external libraries when the type is already known
    /// through some other means (to avoid a syscall).
    pub fn from_abs_unchecked(abs: PathAbs) -> PathFile {
        PathFile(abs)
    }

    /// Instantiate a new `PathFile`, creating an empty file if it doesn't exist.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    ///
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    ///
    /// let file = PathFile::create(example)?;
    ///
    /// // It can be done twice with no effect.
    /// let _ = PathFile::create(example)?;
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn create<P: AsRef<Path>>(path: P) -> Result<PathFile> {
        fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(&path)
            .map_err(|err| Error::new(err, "opening", PathArc::new(&path)))?;
        PathFile::new(path)
    }

    /// Read the entire contents of the file into a `String`.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    ///
    /// let expected = "foo\nbar";
    /// file.write_str(expected)?;
    /// assert_eq!(expected, file.read_string()?);
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn read_string(&self) -> Result<String> {
        let mut f = self.read()?;
        f.read_string()
    }

    /// Write the `str` to a file, truncating it first if it exists and creating it otherwise.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    ///
    /// let expected = "foo\nbar";
    /// file.write_str(expected)?;
    /// assert_eq!(expected, file.read_string()?);
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn write_str(&self, s: &str) -> Result<()> {
        let mut options = fs::OpenOptions::new();
        options.create(true);
        options.truncate(true);
        let mut f = FileWrite::open_path(self.clone(), options)?;
        if s.is_empty() {
            return Ok(());
        }
        f.write_str(s)?;
        f.flush()
    }

    /// Append the `str` to a file, creating it if it doesn't exist.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    ///
    /// let expected = "foo\nbar\nbaz";
    /// file.append_str("foo\nbar")?;
    /// file.append_str("\nbaz")?;
    /// assert_eq!(expected, file.read_string()?);
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn append_str(&self, s: &str) -> Result<()> {
        let mut f = self.append()?;
        if s.is_empty() {
            return Ok(());
        }
        f.write_str(s)?;
        f.flush()
    }

    /// Open the file as read-only.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use std::io::Read;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    ///
    /// let expected = "foo\nbar";
    /// file.write_str(expected)?;
    ///
    /// let mut read = file.read()?;
    /// let mut s = String::new();
    /// read.read_to_string(&mut s)?;
    /// assert_eq!(expected, s);
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn read(&self) -> Result<FileRead> {
        FileRead::read_path(self.clone())
    }

    /// Open the file as write-only in append mode.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use std::io::Write;
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    ///
    /// let expected = "foo\nbar\n";
    /// file.write_str("foo\n")?;
    ///
    /// let mut append = file.append()?;
    /// append.write_all(b"bar\n")?;
    /// append.flush();
    /// assert_eq!(expected, file.read_string()?);
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn append(&self) -> Result<FileWrite> {
        let mut options = fs::OpenOptions::new();
        options.append(true);
        FileWrite::open_path(self.clone(), options)
    }

    /// Open the file for editing (reading and writing).
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use std::io::{Read, Seek, Write, SeekFrom};
    /// use path_abs::PathFile;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    ///
    /// let expected = "foo\nbar";
    ///
    /// let mut edit = file.edit()?;
    /// let mut s = String::new();
    ///
    /// edit.write_all(expected.as_bytes())?;
    /// edit.seek(SeekFrom::Start(0))?;
    /// edit.read_to_string(&mut s)?;
    /// assert_eq!(expected, s);
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn edit(&self) -> Result<FileEdit> {
        FileEdit::open_path(self.clone(), fs::OpenOptions::new())
    }

    /// Remove (delete) the file from the filesystem, consuming self.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate path_abs;
    /// # extern crate tempdir;
    /// use path_abs::PathFile;
    /// use std::path::Path;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let example = "example.txt";
    /// # let tmp = tempdir::TempDir::new("ex")?;
    /// # let example = &tmp.path().join(example);
    /// let file = PathFile::create(example)?;
    /// assert!(file.exists());
    /// file.remove()?;
    ///
    /// // file.exists() <--- COMPILER ERROR, `file` was consumed
    ///
    /// assert!(!Path::new(example).exists());
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    pub fn remove(self) -> Result<()> {
        fs::remove_file(&self).map_err(|err| Error::new(err, "removing", self.into()))
    }

    /// Return a reference to a basic `std::path::Path`
    pub fn as_path(&self) -> &Path {
        self.as_ref()
    }

    /// Create a mock file type. *For use in tests only*.
    ///
    /// See the docs for [`PathAbs::mock`](struct.PathAbs.html#method.mock)
    pub fn mock<P: AsRef<Path>>(path: P) -> PathFile {
        PathFile(PathAbs::mock(path))
    }
}

impl fmt::Debug for PathFile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl AsRef<PathAbs> for PathFile {
    fn as_ref(&self) -> &PathAbs {
        &self.0
    }
}

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

impl AsRef<PathBuf> for PathFile {
    fn as_ref(&self) -> &PathBuf {
        self.0.as_ref()
    }
}

impl Deref for PathFile {
    type Target = PathAbs;

    fn deref(&self) -> &PathAbs {
        &self.0
    }
}

impl Into<PathAbs> for PathFile {
    /// Downgrades the `PathFile` into a `PathAbs`
    ///
    /// # Examples
    /// ```
    /// # extern crate path_abs;
    /// use std::path::PathBuf;
    /// use path_abs::{PathFile, PathAbs};
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let file = PathFile::new("src/lib.rs")?;
    /// let abs: PathAbs = file.clone().into();
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    fn into(self) -> PathAbs {
        self.0
    }
}

impl Into<PathArc> for PathFile {
    /// Downgrades the `PathFile` into a `PathArc`
    fn into(self) -> PathArc {
        (self.0).0
    }
}

impl Into<PathBuf> for PathFile {
    /// Downgrades the `PathFile` into a `PathBuf`. Avoids a clone if this is the only reference.
    ///
    /// # Examples
    /// ```
    /// # extern crate path_abs;
    /// use path_abs::PathFile;
    /// use std::path::PathBuf;
    ///
    /// # fn try_main() -> ::std::io::Result<()> {
    /// let file = PathFile::new("src/lib.rs")?;
    /// let buf: PathBuf = file.into();
    /// # Ok(()) } fn main() { try_main().unwrap() }
    /// ```
    fn into(self) -> PathBuf {
        let arc: PathArc = self.into();
        arc.into()
    }
}