robocopyrs 1.0.0

A wrapper for the robocopy command in Windows
Documentation
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Handle for Robocopy file and directory filter options
//! 
//! All filters and exceptions are handled by the Filter struct

use std::{convert::TryInto, ffi::OsString, ops::Add};
use crate::FileAttributes;
use crate::MultipleVariant;

/// Filters out files that match the variant
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum FileExclusionFilter {
    Attributes(FileAttributes),
    PathOrName(Vec<String>),
    CHANGED,
    OLDER,
    NEWER,
    JUNCTION_POINTS,
    _MULTIPLE(Option<FileAttributes>, Vec<String>, [bool; 4])
}

impl Add for FileExclusionFilter {
    type Output = Self;
    
    fn add(self, rhs: Self) -> Self::Output {
        let (mut result_attribs, mut result_path_or_name, mut result_filters) = match self {
            Self::_MULTIPLE(attribs, path_or_name, filters) => (attribs, path_or_name, filters),
            Self::Attributes(attribs) => (Some(attribs), Vec::new(), [false; 4]),
            Self::PathOrName(path_or_name) => (None, path_or_name, [false; 4]),
            filter => {
                let mut val = 2_u8.pow(filter.index_of().unwrap() as u32) + 2_u8; 
                (None, Vec::new(), (0..6).map(|_| { val >>= 1; val == 1 }).collect::<Vec<bool>>().try_into().unwrap())
            }
        };

        match rhs {
            Self::_MULTIPLE(attribs, mut path_or_name, filters) => {
                result_filters = result_filters.iter().zip(filters.iter()).map(|(a, b)| *a && *b).collect::<Vec<bool>>().try_into().unwrap();
                if let Some(attribs) = attribs {
                    result_attribs = match result_attribs {
                        Some(res_attribs) => Some(attribs + res_attribs),
                        None => Some(attribs)
                    };
                }
                result_path_or_name.append(&mut path_or_name);
            },
            Self::Attributes(attribs) => result_attribs = match result_attribs {
                Some(res_attribs) => Some(attribs + res_attribs),
                None => Some(attribs)
            },
            Self::PathOrName(mut path_or_name) => result_path_or_name.append(&mut path_or_name),
            filter => result_filters[filter.index_of().unwrap()] = true
        }

        Self::_MULTIPLE(result_attribs, result_path_or_name, result_filters)
    }
}

impl MultipleVariant for FileExclusionFilter {
    fn single_variants(&self) -> Vec<Self> {
        match self {
            Self::_MULTIPLE(attribs, path_or_name, props) => {
                let mut filters: Vec<FileExclusionFilter> = Self::VARIANTS.iter().zip(props.iter()).filter(|(_, exists)| **exists).map(|(variant, _)| variant.clone() ).collect();
                
                if let Some(attribs) = attribs {
                    filters.push(Self::Attributes(*attribs));
                }

                if !path_or_name.is_empty() {
                    filters.push(Self::PathOrName(path_or_name.clone()))
                }

                filters
            },
            prop => vec![prop.clone()],
        }
    }
}

impl From<&FileExclusionFilter> for Vec<OsString> {
    fn from(fef: &FileExclusionFilter) -> Self {
        let mut res = Vec::new();
        fef.single_variants().iter().for_each(|filter| match filter {
            FileExclusionFilter::Attributes(file_attributes) => res.push(OsString::from(String::from("/xa:") + Into::<OsString>::into(file_attributes).to_str().unwrap())),
            FileExclusionFilter::PathOrName(path_or_name) => {
                res.push(OsString::from("/xf"));
                path_or_name.iter().for_each(|path_or_name| res.push(OsString::from(path_or_name.as_str())));
            },
            FileExclusionFilter::CHANGED => res.push(OsString::from("/xc")),
            FileExclusionFilter::OLDER => res.push(OsString::from("/xo")),
            FileExclusionFilter::NEWER => res.push(OsString::from("/xn")),
            FileExclusionFilter::JUNCTION_POINTS => res.push(OsString::from("/xjf")),
            _ => unreachable!()
        });
        res
    }
}
impl From<FileExclusionFilter> for Vec<OsString> {
    fn from(fef: FileExclusionFilter) -> Self {
        (&fef).into()
    }
}

impl FileExclusionFilter {
    const VARIANTS: [Self; 4] = [
        Self::CHANGED,
        Self::OLDER,
        Self::NEWER,
        Self::JUNCTION_POINTS
    ];

    fn index_of(&self) -> Option<usize>{
        match self {
            Self::CHANGED => Some(0),
            Self::NEWER => Some(2),
            Self::JUNCTION_POINTS => Some(3),
            _ => None,
        }
    }
}

/// Filters out directories that match the variant
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum DirectoryExclusionFilter {
    PathOrName(Vec<String>),
    JUNCTION_POINTS,
    _BOTH(Vec<String>)
}

impl Add for DirectoryExclusionFilter {
    type Output = Self;
    
    fn add(self, rhs: Self) -> Self::Output {
        let mut junction_pts = false;

        let mut result_path_or_name = match self {
            Self::PathOrName(attribs) | Self::_BOTH(attribs) => attribs,
            Self::JUNCTION_POINTS => { junction_pts = true; Vec::new() }
        };

        match rhs {
            Self::PathOrName(mut attribs) | Self::_BOTH(mut attribs) => result_path_or_name.append(&mut attribs),
            _ => junction_pts = true
        };

        if junction_pts {
            Self::_BOTH(result_path_or_name)
        } else {
            Self::PathOrName(result_path_or_name)
        }
    }
}

impl From<&DirectoryExclusionFilter> for Vec<OsString> {
    fn from(def: &DirectoryExclusionFilter) -> Self {
        let mut res = Vec::new();
        def.single_variants().iter().for_each(|filter| match filter {
            DirectoryExclusionFilter::PathOrName(path_or_name) => {
                res.push(OsString::from("/xd"));
                path_or_name.iter().for_each(|path_or_name| res.push(OsString::from(path_or_name.as_str())));
            },
            DirectoryExclusionFilter::JUNCTION_POINTS => res.push(OsString::from("/xjd")),
            _ => unreachable!()
        });
        res
    }
}
impl From<DirectoryExclusionFilter> for Vec<OsString> {
    fn from(def: DirectoryExclusionFilter) -> Self {
        (&def).into()
    }
}

impl MultipleVariant for DirectoryExclusionFilter {
    fn single_variants(&self) -> Vec<Self> {
        match self {
            Self::_BOTH(path_or_name) => vec![Self::JUNCTION_POINTS, Self::PathOrName(path_or_name.clone())],
            Self::JUNCTION_POINTS => vec![Self::JUNCTION_POINTS],
            Self::PathOrName(path_or_name) => vec![Self::PathOrName(path_or_name.clone())]
        }
    }
}


/// Filters out files and directories that match the variant
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)]
pub enum FileAndDirectoryExclusionFilter {
    EXTRA,
    LONELY,
    JUNCTION_POINTS,
    _MULTIPLE([bool; 3])
}

impl Add for FileAndDirectoryExclusionFilter {
    type Output = Self;
    
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn add(self, rhs: Self) -> Self::Output {
        let mut result_filters = match self {
            Self::_MULTIPLE(filters) => filters,
            filter => {
                let mut val = 2_u8.pow(filter.index_of().unwrap() as u32) + 2_u8; 
                (0..6).map(|_| { val >>= 1; val == 1 }).collect::<Vec<bool>>().try_into().unwrap()
            }
        };

        match rhs {
            Self::_MULTIPLE(filters) => result_filters = result_filters.iter().zip(filters.iter()).map(|(a, b)| *a && *b).collect::<Vec<bool>>().try_into().unwrap(),
            filter => result_filters[filter.index_of().unwrap()] = true
        }

        Self::_MULTIPLE(result_filters)
    }
}

impl From<&FileAndDirectoryExclusionFilter> for Vec<OsString> {
    fn from(fadef: &FileAndDirectoryExclusionFilter) -> Self {
        let mut res = Vec::new();
        fadef.single_variants().iter().for_each(|filter| match filter {
            FileAndDirectoryExclusionFilter::EXTRA => res.push(OsString::from("/xx")),
            FileAndDirectoryExclusionFilter::LONELY => res.push(OsString::from("/xl")),
            FileAndDirectoryExclusionFilter::JUNCTION_POINTS => res.push(OsString::from("/xj")),
            _ => unreachable!()
        });
        res
    }
}
impl From<FileAndDirectoryExclusionFilter> for Vec<OsString> {
    fn from(fadef: FileAndDirectoryExclusionFilter) -> Self {
        (&fadef).into()
    }
}

impl MultipleVariant for FileAndDirectoryExclusionFilter {
    fn single_variants(&self) -> Vec<Self> {
        match self {
            Self::_MULTIPLE(filters) => {
                Self::VARIANTS.iter().zip(filters.iter()).filter(|(_, exists)| **exists).into_iter().unzip::<&Self, &bool, Vec<Self>, Vec<bool>>().0
            },
            attrib => vec![*attrib],
        }
    }
}

impl FileAndDirectoryExclusionFilter {
    const VARIANTS: [Self; 3] = [
        Self::EXTRA,
        Self::LONELY,
        Self::JUNCTION_POINTS
    ];

    fn index_of(&self) -> Option<usize>{
        match self {
            Self::EXTRA => Some(0),
            Self::LONELY => Some(1),
            Self::JUNCTION_POINTS => Some(2),
            _ => None,
        }
    }
}

/// Includes files despite the filters that match the variant
#[derive(Debug, Copy, Clone)]
pub enum FileExclusionFilterException {
    MODIFIED,
    SAME,
    TWEAKED,
    _MULTIPLE([bool; 3])
}

impl Add for FileExclusionFilterException {
    type Output = Self;
    
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn add(self, rhs: Self) -> Self::Output {
        let mut result_filters = match self {
            Self::_MULTIPLE(filters) => filters,
            filter => {
                let mut val = 2_u8.pow(filter.index_of().unwrap() as u32) + 2_u8; 
                (0..6).map(|_| { val >>= 1; val == 1 }).collect::<Vec<bool>>().try_into().unwrap()
            }
        };

        match rhs {
            Self::_MULTIPLE(filters) => result_filters = result_filters.iter().zip(filters.iter()).map(|(a, b)| *a && *b).collect::<Vec<bool>>().try_into().unwrap(),
            filter => result_filters[filter.index_of().unwrap()] = true
        }

        Self::_MULTIPLE(result_filters)
    }
}

impl From<&FileExclusionFilterException> for Vec<OsString> {
    fn from(fefe: &FileExclusionFilterException) -> Self {
        let mut res = Vec::new();
        fefe.single_variants().iter().for_each(|filter| match filter {
            FileExclusionFilterException::MODIFIED => res.push(OsString::from("/im")),
            FileExclusionFilterException::SAME => res.push(OsString::from("/is")),
            FileExclusionFilterException::TWEAKED => res.push(OsString::from("/it")),
            _ => unreachable!()
        });
        res
    }
}
impl From<FileExclusionFilterException> for Vec<OsString> {
    fn from(fefe: FileExclusionFilterException) -> Self {
        (&fefe).into()
    }
}

impl MultipleVariant for FileExclusionFilterException {
    fn single_variants(&self) -> Vec<Self> {
        match self {
            Self::_MULTIPLE(filters) => {
                Self::VARIANTS.iter().zip(filters.iter()).filter(|(_, exists)| **exists).into_iter().unzip::<&Self, &bool, Vec<Self>, Vec<bool>>().0
            },
            attrib => vec![*attrib],
        }
    }
}

impl FileExclusionFilterException {
    const VARIANTS: [Self; 3] = [
        Self::MODIFIED,
        Self::SAME,
        Self::TWEAKED
    ];

    /// Returns the index of the variant in a 
    /// FileExclusionFilterException::_MULTIPLE variant
    /// and the Self::VARIANTS array
    fn index_of(&self) -> Option<usize>{
        match self {
            Self::MODIFIED => Some(0),
            Self::SAME => Some(1),
            Self::TWEAKED => Some(2),
            _ => None,
        }
    }
}

/// Handles all filter attributes supported by Robocopy
#[derive(Debug, Clone, Default)]
pub struct Filter<'a> {
    pub handle_archive_and_reset: bool,
    pub include_only_files_with_any_of_these_attribs: Option<FileAttributes>,
    
    pub file_exclusion_filter: Option<FileExclusionFilter>,
    pub directory_exclusion_filter: Option<DirectoryExclusionFilter>,
    pub file_and_directory_exclusion_filter: Option<FileAndDirectoryExclusionFilter>,

    pub file_exclusion_filter_exceptions: Option<FileExclusionFilterException>,
    
    pub max_size: Option<u128>,
    pub min_size: Option<u128>,

    pub max_age: Option<&'a str>,
    pub min_age: Option<&'a str>,
    
    pub max_last_access_date: Option<&'a str>,
    pub min_last_access_date: Option<&'a str>,
}

impl<'a> From<&'a Filter<'a>> for Vec<OsString> {
    fn from(filter: &'a Filter<'a>) -> Self {
        let mut res = Vec::new();
        
        if filter.handle_archive_and_reset {
            res.push(OsString::from("/m"));
        }
        if let Some(attribs) = filter.include_only_files_with_any_of_these_attribs {
            res.push(OsString::from(String::from("/ia:") + Into::<OsString>::into(attribs).to_str().unwrap()));
        }

        if let Some(filter) = filter.file_exclusion_filter.clone() {
            res.append(&mut filter.into());
        }
        if let Some(filter) = filter.directory_exclusion_filter.clone() {
            res.append(&mut filter.into());
        }
        if let Some(filter) = filter.file_and_directory_exclusion_filter {
            res.append(&mut filter.into());
        }

        if let Some(filter) = filter.file_exclusion_filter_exceptions {
            res.append(&mut filter.into());
        }

        if let Some(max_size) = filter.max_size {
            res.push(OsString::from(format!("/max:{}", max_size)));
        }
        if let Some(min_size) = filter.min_size {
            res.push(OsString::from(format!("/min:{}", min_size)));
        }
        
        if let Some(max_age) = filter.max_age {
            res.push(OsString::from(format!("/maxage:{}", max_age)));
        }
        if let Some(min_age) = filter.min_age {
            res.push(OsString::from(format!("/minage:{}", min_age)));
        }

        if let Some(max_lad) = filter.max_last_access_date {
            res.push(OsString::from(format!("/maxlad:{}", max_lad)));
        }
        if let Some(min_lad) = filter.min_last_access_date {
            res.push(OsString::from(format!("/minlad:{}", min_lad)));
        }

        res
    }
}
impl<'a> From<Filter<'a>> for Vec<OsString> {
    fn from(filter: Filter<'a>) -> Self {
        (&filter).into()
    }
}