-
Notifications
You must be signed in to change notification settings - Fork 3
/
mktemp.rs
103 lines (82 loc) · 2.48 KB
/
mktemp.rs
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
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
use uutils_args::{
positional::{Opt, Unpack},
Arguments, Options,
};
#[derive(Clone, Arguments)]
enum Arg {
#[arg("-d", "--directory")]
Directory,
#[arg("-u", "--dry-run")]
DryRun,
#[arg("-q", "--quiet")]
Quiet,
#[arg("--suffix=SUFFIX")]
Suffix(String),
#[arg("-t")]
TreatAsTemplate,
#[arg("-p DIR", "--tmpdir[=DIR]", value = ".".into())]
TmpDir(PathBuf),
}
#[derive(Default)]
struct Settings {
directory: bool,
dry_run: bool,
quiet: bool,
tmp_dir: Option<PathBuf>,
suffix: Option<String>,
treat_as_template: bool,
}
impl Options<Arg> for Settings {
fn apply(&mut self, arg: Arg) {
match arg {
Arg::Directory => self.directory = true,
Arg::DryRun => self.dry_run = true,
Arg::Quiet => self.quiet = true,
Arg::Suffix(s) => self.suffix = Some(s),
Arg::TreatAsTemplate => self.treat_as_template = true,
Arg::TmpDir(dir) => self.tmp_dir = Some(dir),
}
}
}
fn parse<I>(args: I) -> Result<(Settings, Option<OsString>), uutils_args::Error>
where
I: IntoIterator,
I::Item: Into<OsString>,
{
let (s, ops) = Settings::default().parse(args)?;
let file = Opt("FILE").unpack(ops)?;
Ok((s, file))
}
#[test]
fn suffix() {
let (s, _template) = parse(["mktemp", "--suffix=hello"]).unwrap();
assert_eq!(s.suffix.unwrap(), "hello");
let (s, _template) = parse(["mktemp", "--suffix="]).unwrap();
assert_eq!(s.suffix.unwrap(), "");
let (s, _template) = parse(["mktemp", "--suffix="]).unwrap();
assert_eq!(s.suffix.unwrap(), "");
let (s, _template) = parse(["mktemp"]).unwrap();
assert_eq!(s.suffix, None);
}
#[test]
fn tmpdir() {
let (s, _template) = parse(["mktemp", "--tmpdir"]).unwrap();
assert_eq!(s.tmp_dir.unwrap(), Path::new("."));
let (s, _template) = parse(["mktemp", "--tmpdir="]).unwrap();
assert_eq!(s.tmp_dir.unwrap(), Path::new(""));
let (s, _template) = parse(["mktemp", "-p", "foo"]).unwrap();
assert_eq!(s.tmp_dir.unwrap(), Path::new("foo"));
let (s, _template) = parse(["mktemp", "-pfoo"]).unwrap();
assert_eq!(s.tmp_dir.unwrap(), Path::new("foo"));
let (s, _template) = parse(["mktemp", "-p", ""]).unwrap();
assert_eq!(s.tmp_dir.unwrap(), Path::new(""));
assert!(parse(["mktemp", "-p"]).is_err());
}
#[test]
fn too_many_arguments() {
assert!(parse(["mktemp", "foo", "bar"]).is_err());
}