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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Timestamps for files in Rust
//!
//! An enhanced version of [filetime](https://docs.rs/filetime), which can set file creation time on Windows.
//!
//! Internally, this crate use [SetFileTime](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfiletime)
//! Win32 API to set the file creation time on Windows.
//!
//! On other platforms, all functions will just call the corresponding [filetime](https://docs.rs/filetime)'s function, and
//! ignore the file creation time.
//!
//! # Installation
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! filetime_creation = "0.1"
//! ```
//!
//! # Usage
//!
//! ```no_run
//! use std::fs;
//! use filetime_creation::{FileTime, set_file_ctime};
//!
//! let now = FileTime::now();
//!
//! set_file_ctime("test.txt", now);
//! assert_eq!(now, FileTime::from(fs::metadata("test.txt").unwrap().created().unwrap()));
//! ```

pub use filetime::{set_file_atime, set_file_mtime, FileTime};

use std::fs;
use std::io;
use std::path::Path;

cfg_if::cfg_if! {
    if #[cfg(windows)] {
        use fs::OpenOptions;
        use std::ptr;
        use std::os::windows::prelude::*;
        use windows_sys::Win32::Foundation::{FILETIME, HANDLE};
        use windows_sys::Win32::Storage::FileSystem::*;
    }
}

/// Set the last access, modification, and creation times for a file on the filesystem.
#[cfg(windows)]
pub fn set_file_times<P>(p: P, atime: FileTime, mtime: FileTime, ctime: FileTime) -> io::Result<()>
where
    P: AsRef<Path>,
{
    let f = OpenOptions::new()
        .write(true)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
        .open(p)?;
    set_file_handle_times(&f, Some(atime), Some(mtime), Some(ctime))
}

/// Set the creation time for a file on Windows, returning any error encountered.
///
/// # Platform support
///
/// This function is only supported on Windows, other platforms will do nothing
/// and return Err.
#[cfg(windows)]
pub fn set_file_ctime<P>(p: P, ctime: FileTime) -> io::Result<()>
where
    P: AsRef<Path>,
{
    let f = OpenOptions::new()
        .write(true)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
        .open(p)?;
    set_file_handle_times(&f, None, None, Some(ctime))
}

/// Set the last access, modification and creation times for a file handle.
#[cfg(windows)]
pub fn set_file_handle_times(
    f: &fs::File,
    atime: Option<FileTime>,
    mtime: Option<FileTime>,
    ctime: Option<FileTime>,
) -> io::Result<()> {
    let atime = atime.map(to_filetime);
    let mtime = mtime.map(to_filetime);
    let ctime = ctime.map(to_filetime);
    return unsafe {
        let ret = SetFileTime(
            f.as_raw_handle() as HANDLE,
            ctime
                .as_ref()
                .map(|p| p as *const FILETIME)
                .unwrap_or(ptr::null()),
            atime
                .as_ref()
                .map(|p| p as *const FILETIME)
                .unwrap_or(ptr::null()),
            mtime
                .as_ref()
                .map(|p| p as *const FILETIME)
                .unwrap_or(ptr::null()),
        );
        if ret != 0 {
            Ok(())
        } else {
            Err(io::Error::last_os_error())
        }
    };

    fn to_filetime(ft: FileTime) -> FILETIME {
        let intervals = ft.seconds() * (1_000_000_000 / 100) + ((ft.nanoseconds() as i64) / 100);
        FILETIME {
            dwLowDateTime: intervals as u32,
            dwHighDateTime: (intervals >> 32) as u32,
        }
    }
}

/// Set the last access, modification and creation times for a file on the filesystem.
/// This function does not follow symlink.
#[cfg(windows)]
pub fn set_symlink_file_times<P>(
    p: P,
    atime: FileTime,
    mtime: FileTime,
    ctime: FileTime,
) -> io::Result<()>
where
    P: AsRef<Path>,
{
    let f = OpenOptions::new()
        .write(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
        .open(p)?;
    set_file_handle_times(&f, Some(atime), Some(mtime), Some(ctime))
}

/// Set the last access, modification, and creation times for a file on the filesystem.
#[cfg(not(windows))]
pub fn set_file_times<P>(p: P, atime: FileTime, mtime: FileTime, _ctime: FileTime) -> io::Result<()>
where
    P: AsRef<Path>,
{
    filetime::set_file_times(p, atime, mtime)
}

/// Set the creation time for a file on Windows, returning any error encountered.
///
/// # Platform support
///
/// This function is only supported on Windows, other platforms will do nothing
/// and return Err.
#[cfg(not(windows))]
pub fn set_file_ctime<P>(_p: P, _ctime: FileTime) -> io::Result<()>
where
    P: AsRef<Path>,
{
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "Platform unsupported",
    ))
}

/// Set the last access, modification and creation times for a file handle.
#[cfg(not(windows))]
pub fn set_file_handle_times(
    f: &fs::File,
    atime: Option<FileTime>,
    mtime: Option<FileTime>,
    _ctime: Option<FileTime>,
) -> io::Result<()> {
    filetime::set_file_handle_times(f, atime, mtime)
}

/// Set the last access, modification and creation times for a file on the filesystem.
/// This function does not follow symlink.
#[cfg(not(windows))]
pub fn set_symlink_file_times<P>(
    p: P,
    atime: FileTime,
    mtime: FileTime,
    _ctime: FileTime,
) -> io::Result<()>
where
    P: AsRef<Path>,
{
    filetime::set_symlink_file_times(p, atime, mtime)
}

#[cfg(test)]
mod tests {
    cfg_if::cfg_if! {
        if #[cfg(windows)] {
            use super::*;
            use fs::File;
            use tempfile::Builder;
        }
    }

    #[cfg(windows)]
    fn make_symlink_file<P, Q>(src: P, dst: Q) -> io::Result<()>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        use std::os::windows::fs::symlink_file;
        symlink_file(src, dst)
    }

    #[cfg(windows)]
    fn make_symlink_dir<P, Q>(src: P, dst: Q) -> io::Result<()>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        use std::os::windows::fs::symlink_dir;
        symlink_dir(src, dst)
    }

    #[test]
    #[cfg(windows)]
    fn set_file_times_test() -> io::Result<()> {
        let td = Builder::new().prefix("filetime").tempdir()?;
        let path = td.path().join("foo.txt");
        let mut f = File::create(&path)?;

        let metadata = fs::metadata(&path)?;
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_file_times(&path, atime, mtime, ctime)?;

        let new_ctime = FileTime::from_unix_time(10_000, 0);
        set_file_times(&path, atime, mtime, new_ctime)?;

        let metadata = fs::metadata(&path)?;
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation should be updated");

        // Update just mtime
        let new_mtime = FileTime::from_unix_time(20_000, 0);
        set_file_handle_times(&mut f, None, Some(new_mtime), None)?;
        let metadata = f.metadata()?;
        let mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should be updated");
        let new_atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "accessed time should not be updated");
        let new_ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should not be updated");

        // Update just atime
        let new_atime = FileTime::from_unix_time(30_000, 0);
        set_file_handle_times(&mut f, Some(new_atime), None, None)?;
        let metadata = f.metadata()?;
        let mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should not be updated");
        let atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "accessed time should be updated");
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should not be updated");

        // Update just ctime
        let new_ctime = FileTime::from_unix_time(40_000, 0);
        set_file_handle_times(&mut f, None, None, Some(new_ctime))?;
        let metadata = f.metadata()?;
        let new_mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should not be updated");
        let new_atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "accessed time should not be updated");
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should be updated");

        let spath = td.path().join("bar.txt");
        make_symlink_file(&path, &spath)?;
        let metadata = fs::symlink_metadata(&spath)?;
        let sctime = FileTime::from_creation_time(&metadata).unwrap();

        set_file_times(&spath, atime, mtime, ctime)?;

        let metadata = fs::metadata(&path)?;
        let cur_ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, cur_ctime);

        let metadata = fs::symlink_metadata(&spath)?;
        let cur_ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(sctime, cur_ctime);

        set_file_times(&spath, atime, mtime, new_ctime)?;

        let metadata = fs::metadata(&path)?;
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let metadata = fs::symlink_metadata(&spath)?;
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, sctime);
        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn set_dir_times_test() -> io::Result<()> {
        let td = Builder::new().prefix("filetime").tempdir()?;
        let path = td.path().join("foo");
        fs::create_dir(&path)?;

        let metadata = fs::metadata(&path)?;
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_file_times(&path, atime, mtime, ctime)?;

        let new_ctime = FileTime::from_unix_time(10_000, 0);
        set_file_times(&path, atime, mtime, new_ctime)?;

        let metadata = fs::metadata(&path)?;
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation should be updated");

        // Update just mtime
        let new_mtime = FileTime::from_unix_time(20_000, 0);
        set_file_mtime(&path, new_mtime)?;
        let metadata = fs::metadata(&path)?;
        let mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should be updated");
        let new_atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "accessed time should not be updated");
        let new_ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should not be updated");

        // Update just atime
        let new_atime = FileTime::from_unix_time(30_000, 0);
        set_file_atime(&path, new_atime)?;
        let metadata = fs::metadata(&path)?;
        let mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should not be updated");
        let atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "accessed time should be updated");
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should not be updated");

        // Update just ctime
        let new_ctime = FileTime::from_unix_time(40_000, 0);
        set_file_ctime(&path, new_ctime)?;
        let metadata = fs::metadata(&path)?;
        let new_mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should not be updated");
        let new_atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "accessed time should not be updated");
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should be updated");

        let spath = td.path().join("bar");
        make_symlink_dir(&path, &spath)?;
        let metadata = fs::symlink_metadata(&spath)?;
        let sctime = FileTime::from_creation_time(&metadata).unwrap();

        set_file_times(&spath, atime, mtime, ctime)?;

        let metadata = fs::metadata(&path)?;
        let cur_ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, cur_ctime);

        let metadata = fs::symlink_metadata(&spath)?;
        let cur_ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(sctime, cur_ctime);

        set_file_times(&spath, atime, mtime, new_ctime)?;

        let metadata = fs::metadata(&path)?;
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let metadata = fs::symlink_metadata(&spath)?;
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, sctime);
        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn set_file_times_pre_unix_epoch_test() {
        let td = Builder::new().prefix("filetime").tempdir().unwrap();
        let path = td.path().join("foo.txt");
        File::create(&path).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_file_times(&path, atime, mtime, ctime).unwrap();

        let new_ctime = FileTime::from_unix_time(-10_000, 0);
        set_file_times(&path, atime, mtime, new_ctime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);
    }

    #[test]
    #[cfg(windows)]
    fn set_file_times_pre_windows_epoch_test() {
        let td = Builder::new().prefix("filetime").tempdir().unwrap();
        let path = td.path().join("foo.txt");
        File::create(&path).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_file_times(&path, atime, mtime, ctime).unwrap();

        let new_ctime = FileTime::from_unix_time(-12_000_000_000, 0);
        assert!(set_file_times(&path, atime, mtime, new_ctime).is_err());
    }

    #[test]
    #[cfg(windows)]
    fn set_symlink_file_times_test() {
        let td = Builder::new().prefix("filetime").tempdir().unwrap();
        let path = td.path().join("foo.txt");
        File::create(&path).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_symlink_file_times(&path, atime, mtime, ctime).unwrap();

        let new_ctime = FileTime::from_unix_time(10_000, 0);
        set_symlink_file_times(&path, atime, mtime, new_ctime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let spath = td.path().join("bar.txt");
        make_symlink_file(&path, &spath).unwrap();

        let metadata = fs::symlink_metadata(&spath).unwrap();
        let smtime = FileTime::from_last_modification_time(&metadata);
        let satime = FileTime::from_last_access_time(&metadata);
        let sctime = FileTime::from_creation_time(&metadata).unwrap();
        set_symlink_file_times(&spath, smtime, satime, sctime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let new_sctime = FileTime::from_unix_time(20_000, 0);
        set_symlink_file_times(&spath, atime, mtime, new_sctime).unwrap();

        let metadata = fs::metadata(&spath).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let metadata = fs::symlink_metadata(&spath).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_sctime);
    }

    #[test]
    #[cfg(windows)]
    fn set_symlink_dir_times_test() {
        let td = Builder::new().prefix("filetime").tempdir().unwrap();
        let path = td.path().join("foo");
        fs::create_dir(&path).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_symlink_file_times(&path, atime, mtime, ctime).unwrap();

        let new_ctime = FileTime::from_unix_time(10_000, 0);
        set_symlink_file_times(&path, atime, mtime, new_ctime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let spath = td.path().join("bar");
        make_symlink_dir(&path, &spath).unwrap();

        let metadata = fs::symlink_metadata(&spath).unwrap();
        let smtime = FileTime::from_last_modification_time(&metadata);
        let satime = FileTime::from_last_access_time(&metadata);
        let sctime = FileTime::from_creation_time(&metadata).unwrap();
        set_symlink_file_times(&spath, smtime, satime, sctime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let new_sctime = FileTime::from_unix_time(20_000, 0);
        set_symlink_file_times(&spath, atime, mtime, new_sctime).unwrap();

        let metadata = fs::metadata(&spath).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime);

        let metadata = fs::symlink_metadata(&spath).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_sctime);
    }

    #[test]
    #[cfg(windows)]
    fn set_single_time_test() {
        use super::{set_file_atime, set_file_ctime, set_file_mtime};

        let td = Builder::new().prefix("filetime").tempdir().unwrap();
        let path = td.path().join("foo.txt");
        File::create(&path).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let mtime = FileTime::from_last_modification_time(&metadata);
        let atime = FileTime::from_last_access_time(&metadata);
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        set_file_times(&path, atime, mtime, ctime).unwrap();

        let new_mtime = FileTime::from_unix_time(10_000, 0);
        set_file_mtime(&path, new_mtime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let mtime = FileTime::from_last_modification_time(&metadata);
        assert_eq!(mtime, new_mtime, "modification time should be updated");
        assert_eq!(
            atime,
            FileTime::from_last_access_time(&metadata),
            "access time should not be updated",
        );
        assert_eq!(
            ctime,
            FileTime::from_creation_time(&metadata).unwrap(),
            "creation time should not be updated",
        );

        let new_atime = FileTime::from_unix_time(20_000, 0);
        set_file_atime(&path, new_atime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let atime = FileTime::from_last_access_time(&metadata);
        assert_eq!(atime, new_atime, "access time should be updated");
        assert_eq!(
            mtime,
            FileTime::from_last_modification_time(&metadata),
            "modification time should not be updated"
        );
        assert_eq!(
            ctime,
            FileTime::from_creation_time(&metadata).unwrap(),
            "creation time should not be updated",
        );

        let new_ctime = FileTime::from_unix_time(30_000, 0);
        set_file_ctime(&path, new_ctime).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let ctime = FileTime::from_creation_time(&metadata).unwrap();
        assert_eq!(ctime, new_ctime, "creation time should be updated");
        assert_eq!(
            mtime,
            FileTime::from_last_modification_time(&metadata),
            "modification time should not be updated"
        );
        assert_eq!(
            atime,
            FileTime::from_last_access_time(&metadata),
            "access time should not be updated",
        );
    }
}