1+ use std:: fs;
2+ use std:: io:: BufReader ;
3+ use std:: io:: prelude:: * ;
4+ use std:: path:: Path ;
5+ use std:: io:: Result ;
6+ use std:: process:: Command ;
7+
8+ use super :: parsers:: nix_stat_parser;
9+
10+ use serde:: { Deserialize , Serialize } ;
11+
12+ pub struct FileSystem ;
13+
14+ #[ derive( Serialize , Deserialize ) ]
15+ pub struct FileStat {
16+ pub atime : String ,
17+ pub mtime : String ,
18+ pub ctime : String
19+ }
20+
21+ impl FileSystem {
22+ /// Returns stat info of files to parse access/modify timestamps
23+ pub fn file_nix_stat ( file_path : & str ) -> FileStat {
24+ // return file stats from child process
25+ let child_process = Command :: new ( "/bin/stat" )
26+ . arg ( file_path)
27+ . output ( )
28+ . expect ( "failed to execute child process" ) ;
29+
30+ // parse unix timestamp from fs stats
31+ nix_stat_parser (
32+ String :: from_utf8_lossy ( & child_process. stdout )
33+ )
34+ }
35+
36+ /// Apply timestamps to files using the touch utility
37+ #[ inline]
38+ pub fn change_file_timestamp ( file_path : & str , stat : FileStat ) {
39+ Command :: new ( "/usr/bin/touch" )
40+ . args ( [
41+ "-a" , "-t" , & stat. atime ,
42+ "-m" , "-t" , & stat. mtime ,
43+ file_path
44+ ] )
45+ . output ( )
46+ . expect ( "failed to execute child process" ) ;
47+ }
48+
49+ /// Returns if a file path exists or not
50+ #[ inline]
51+ pub fn file_exists ( file_path : & str ) -> bool {
52+ Path :: new ( file_path) . exists ( )
53+ }
54+
55+ /// Read a file into bytes
56+ pub fn read ( file_path : & str ) -> Result < Vec < u8 > > {
57+ let file = fs:: File :: open ( file_path) ?;
58+ let mut buf_reader = BufReader :: new ( file) ;
59+ let mut contents: Vec < u8 > = Vec :: new ( ) ;
60+ buf_reader. read_to_end ( & mut contents) ?;
61+ Ok ( contents)
62+ }
63+
64+ /// Write bytes to a file
65+ pub fn write ( file_path : & str , contents : & [ u8 ] ) -> Result < ( ) > {
66+ let mut file = fs:: File :: create ( file_path) ?;
67+ file. write_all ( contents) ?;
68+ Ok ( ( ) )
69+ }
70+
71+ /// Create a recursive directory
72+ pub fn create_dir ( file_path : & str ) -> Result < ( ) > {
73+ if !Path :: new ( file_path) . exists ( ) {
74+ fs:: create_dir_all ( file_path) ?
75+ }
76+ Ok ( ( ) )
77+ }
78+
79+ /// Remove a directory at absolute path
80+ pub fn remove_dir ( file_path : & str ) -> Result < ( ) > {
81+ if Path :: new ( file_path) . exists ( ) {
82+ fs:: remove_dir_all ( file_path) ?
83+ }
84+ Ok ( ( ) )
85+ }
86+ }
0 commit comments