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
// License: see LICENSE file at root directory of `master` branch

//! # Paths - extensions for `Args`
//!
//! ## See also
//!
//! - [`Args`][::Args]
//!
//! [::Args]: ../struct.Args.html

use std::{
    fs::{self, File},
    io::{self, Error, ErrorKind},
    path::{Path, PathBuf},
};

use crate::Args;

/// # Path kind
#[derive(Debug, Eq, PartialEq)]
pub enum PathKind {

    /// # Directory
    Directory,

    /// # File
    File,

}

/// # Take option
#[derive(Debug, Eq, PartialEq)]
pub enum TakeOption {

    /// # Must exist
    MustExist,

    /// # Deny existing
    DenyExisting,

    /// # Just take whatever it is
    Take {

        /// # If the path does not exist, and this flag is `true`, make it
        ///
        /// - If [`PathKind::Directory`][::PathKind::Directory] is used, make new directory via
        ///   [`fs::create_dir_all()`][::fs::create_dir_all()].
        /// - If [`PathKind::File`][::PathKind::File] is used, make new empty file via [`File::create()`][::File::create()].
        ///
        /// [::PathKind::Directory]: enum.PathKind.html#variant.Directory
        /// [::PathKind::File]: enum.PathKind.html#variant.File
        /// [::fs::create_dir_all()]: https://doc.rust-lang.org/std/fs/fn.create_dir_all.html
        /// [::File::create()]: https://doc.rust-lang.org/std/fs/struct.File.html#method.create
        make: bool,

    },

}

/// # Gets a path from arguments
///
/// ## Notes
///
/// Error messages are hard-coded. If you want to handle errors, you can get error kinds.
pub fn get_path<S>(args: &Args, keys: &[S], kind: PathKind, option: TakeOption) -> io::Result<Option<PathBuf>> where S: AsRef<str> {
    match args.get::<PathBuf, _>(keys)? {
        Some(path) => handle_path(&path, kind, option).map(|()| Some(path)),
        None => Ok(None),
    }
}

/// # Takes a path from arguments
///
/// ## Notes
///
/// Error messages are hard-coded. If you want to handle errors, you can get error kinds.
///
/// ## Examples
///
/// ```
/// use dia_args::{
///     paths::{self, PathKind, TakeOption},
/// };
///
/// let mut args = dia_args::parse_strings(["--input", file!()].iter()).unwrap();
/// let file = paths::take_path(
///     &mut args, &["--input"], PathKind::File, TakeOption::MustExist,
/// )
///     .unwrap().unwrap();
/// assert!(file.is_file());
/// assert!(args.is_empty());
/// ```
pub fn take_path<S>(args: &mut Args, keys: &[S], kind: PathKind, option: TakeOption) -> io::Result<Option<PathBuf>> where S: AsRef<str> {
    match args.take::<PathBuf, _>(keys)? {
        Some(path) => handle_path(&path, kind, option).map(|()| Some(path)),
        None => Ok(None),
    }
}

/// # Handles path
///
/// This function verifies path kind and handles option. New directory or new file will be made if necessary.
///
/// ## Examples
///
/// ```
/// use dia_args::paths::{self, PathKind, TakeOption};
///
/// paths::handle_path(file!(), PathKind::File, TakeOption::MustExist).unwrap();
/// ```
pub fn handle_path<P>(path: P, kind: PathKind, option: TakeOption) -> io::Result<()> where P: AsRef<Path> {
    let path = path.as_ref();
    if match option {
        TakeOption::MustExist => true,
        TakeOption::Take { .. } if path.exists() => true,
        _ => false,
    } {
        match kind {
            PathKind::Directory => if path.is_dir() == false {
                return Err(Error::new(ErrorKind::InvalidInput, format!("Not a directory: {:?}", path)));
            },
            PathKind::File => if path.is_file() == false {
                return Err(Error::new(ErrorKind::InvalidInput, format!("Not a file: {:?}", path)));
            },
        };
    }
    match option {
        TakeOption::MustExist => if path.exists() == false {
            return Err(Error::new(ErrorKind::NotFound, format!("Not found: {:?}", path)));
        },
        TakeOption::DenyExisting => if path.exists() {
            return Err(Error::new(ErrorKind::AlreadyExists, format!("Already exists: {:?}", path)));
        },
        TakeOption::Take { make } => if make && path.exists() == false {
            match kind {
                PathKind::Directory => fs::create_dir_all(&path)?,
                PathKind::File => drop(File::create(&path)?),
            };
        },
    };
    Ok(())
}

#[test]
fn test_take_path() {
    const KEYS: &[&str] = &["--path"];

    let mut args = crate::parse_strings([&KEYS[0], file!()].iter()).unwrap();
    assert!(take_path(&mut args, KEYS, PathKind::File, TakeOption::MustExist).unwrap().is_some());
    assert!(args.is_empty());

    let mut args = crate::parse_strings([&KEYS[0], file!()].iter()).unwrap();
    assert_eq!(get_path(&mut args, KEYS, PathKind::File, TakeOption::DenyExisting).unwrap_err().kind(), ErrorKind::AlreadyExists);
    assert!(args.is_empty() == false);

    let mut args = crate::parse_strings([&KEYS[0], file!()].iter()).unwrap();
    assert_eq!(take_path(&mut args, KEYS, PathKind::Directory, TakeOption::Take { make: false }).unwrap_err().kind(), ErrorKind::InvalidInput);
    assert!(args.is_empty());
}

#[cfg(unix)]
const INVALID_FILE_NAME_CHARS: &[char] = &[];

#[cfg(not(unix))]
const INVALID_FILE_NAME_CHARS: &[char] = &['^', '?', '%', '*', ':', '|', '"', '<', '>'];

/// # Verifies _non-existing_ file name
///
/// ## Notes
///
/// - Maximum lengths are different across platforms. If you do not provide a value for maximum length, `1024` will be used.
/// - Slashes `\/`, leading/trailing white space(s) and line breaks are _invalid_ characters.
/// - Non-ASCII characters are _allowed_.
/// - This function behaves differently across platforms. For example: on Windows `?` is not allowed, but on Unix it's ok.
///
/// ## References
///
/// - <https://en.wikipedia.org/wiki/Filename>
/// - <https://en.wikipedia.org/wiki/ASCII>
pub fn verify_ne_file_name<S>(name: S, max_len: Option<usize>) -> io::Result<()> where S: AsRef<str> {
    let name = name.as_ref();

    if name.len() > max_len.unwrap_or(1024) {
        return Err(Error::new(ErrorKind::InvalidInput, "File name is too long"));
    }
    if name.is_empty() {
        return Err(Error::new(ErrorKind::InvalidInput, "File name is empty"));
    }
    if name.trim().len() != name.len() {
        return Err(Error::new(ErrorKind::InvalidInput, "File name contains leading or trailing white space(s)"));
    }
    if name.chars().any(|c| match c.is_ascii() {
        true => match c as u8 {
            0...31 | 127 | b'\\' | b'/' => true,
            _ => INVALID_FILE_NAME_CHARS.contains(&c),
        },
        false => false,
    }) {
        return Err(Error::new(ErrorKind::InvalidInput, "File name contains invalid character(s)"));
    }

    Ok(())
}