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
use std::fs;
use colored::Colorize;
use log::{debug, error, trace};
use rand::prelude::{SeedableRng, SliceRandom, StdRng};
use std::io;
use std::path::{Path, PathBuf};
use structopt::clap::AppSettings;
use structopt::StructOpt;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum RandSelectError {
#[error(transparent)]
IoError(#[from] io::Error),
}
#[derive(Debug, StructOpt)]
#[structopt(
about,
setting(AppSettings::ColoredHelp),
setting(AppSettings::ColorAuto)
)]
pub struct Args {
#[structopt(name = "IN_DIR", parse(from_os_str))]
pub in_dir: PathBuf,
#[structopt(name = "OUT_DIR", parse(from_os_str))]
pub out_dir: PathBuf,
#[structopt(short, long, default_value = "1")]
pub num_files: usize,
#[structopt(short, long)]
pub move_files: bool,
#[structopt(short, long)]
pub go: bool,
#[structopt(short, long)]
pub seed: Option<u64>,
}
fn get_shuffled_paths(args: &Args) -> Result<Vec<fs::DirEntry>, RandSelectError> {
match fs::read_dir(&args.in_dir) {
Ok(paths) => {
let mut rng: StdRng = match args.seed {
Some(seed) => SeedableRng::seed_from_u64(seed),
None => StdRng::from_entropy(),
};
let mut vec_paths: Vec<_> = paths
.filter_map(|p| match p {
Ok(entry) if entry.file_type().ok()?.is_file() => Some(entry),
_ => None,
})
.collect();
vec_paths.shuffle(&mut rng);
trace! {"Shuffled: {:#?}", vec_paths};
Ok(vec_paths)
}
Err(e) => Err(e.into()),
}
}
fn paths_are_valid(in_dir: &Path, out_dir: &Path) -> Result<(), RandSelectError> {
if !in_dir.is_dir() {
error!("Input directory is not a directory: {}", in_dir.display());
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Input directory is not a directory.",
)
.into());
}
if in_dir == out_dir {
error!(
"The output directory cannot be the same as the input directory.\n{} == {}",
in_dir.display(),
out_dir.display()
);
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Output and input directory were the same.",
)
.into());
}
Ok(())
}
pub fn run(args: &mut Args) -> Result<(), RandSelectError> {
debug!("Input args: {:#?}", args);
paths_are_valid(args.in_dir.as_path(), args.out_dir.as_path())?;
match get_shuffled_paths(args) {
Ok(paths) => {
let selected_files: Vec<&fs::DirEntry> = paths.iter().take(args.num_files).collect();
for file in selected_files {
let dest = format!(
"{}/{}",
args.out_dir.display(),
file.file_name().into_string().unwrap()
);
if args.move_files {
println!("{} {}", "--".red(), file.path().to_str().unwrap().red());
}
println!("{} {}", "++".green(), dest.green());
if args.go {
fs::create_dir_all(&args.out_dir).unwrap();
fs::copy(file.path(), &dest).unwrap();
if args.move_files {
fs::remove_file(file.path()).unwrap();
}
}
}
if !args.go {
println!("Re-run randselect with --go to write these changes to the filesystem.");
}
Ok(())
}
Err(e) => Err(e),
}
}
#[cfg(test)]
mod test {
use super::*;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
#[test]
fn test_valid_paths() {
let rand_path =
String::from_utf8(thread_rng().sample_iter(&Alphanumeric).take(18).collect()).unwrap();
let rand_output = Path::new(&rand_path);
paths_are_valid(Path::new("."), rand_output).expect("Paths are valid.");
}
#[test]
fn test_invalid_paths() {
if let Ok(_) = paths_are_valid(Path::new("."), Path::new(".")) {
panic!("Should have failed with same paths");
}
}
}