@@ -12,11 +12,11 @@ use std::collections::BinaryHeap;
1212use std:: ffi:: OsStr ;
1313use std:: fs;
1414use std:: io;
15+ use std:: os:: unix:: { self , fs:: PermissionsExt } ;
1516use std:: path:: { Path , PathBuf } ;
1617
1718/// An iterator that recursively walks through a directory structure and yields a tuple `(path,
1819/// dirs, files)` for each directory it visits.
19- ///
2020/// This struct is created by [`walk_dir`]. See its documentation for more.
2121pub struct DirWalk {
2222 /// Queued paths that will be visited next.
@@ -117,3 +117,52 @@ pub fn move_file<S: AsRef<Path>, D: AsRef<Path>>(source: S, destination: D) -> c
117117
118118 Ok ( ( ) )
119119}
120+
121+ /// Set file owner.
122+ #[ cfg( unix) ]
123+ pub fn set_file_permissions < S : AsRef < Path > > (
124+ source : S ,
125+ uid : Option < u32 > ,
126+ gid : Option < u32 > ,
127+ mode : Option < u32 > ,
128+ ) -> crate :: Result < ( ) > {
129+ unix:: fs:: chown ( & source, uid, gid) ?;
130+ match ( uid, gid) {
131+ ( Some ( owner) , Some ( group) ) => {
132+ log:: info!(
133+ "Changed owner/group for {} to {owner}:{group}." ,
134+ source. as_ref( ) . display( )
135+ ) ;
136+ }
137+ ( Some ( owner) , None ) => {
138+ log:: info!(
139+ "Changed owner for {} to {owner}." ,
140+ source. as_ref( ) . display( )
141+ ) ;
142+ }
143+ ( None , Some ( group) ) => {
144+ log:: info!(
145+ "Changed group for {} to {group}." ,
146+ source. as_ref( ) . display( )
147+ ) ;
148+ }
149+ _ => ( ) ,
150+ }
151+
152+ if let Some ( new_mode) = mode {
153+ let file = fs:: File :: open ( & source) ?;
154+ let permissions = file. metadata ( ) ?. permissions ( ) ;
155+ let old_mode = permissions. mode ( ) ;
156+
157+ if permissions. mode ( ) != new_mode {
158+ let permissions = fs:: Permissions :: from_mode ( new_mode) ;
159+ file. set_permissions ( permissions) ?;
160+ log:: info!(
161+ "Permission for {} changed from {old_mode:o} to {new_mode:o}." ,
162+ source. as_ref( ) . display( )
163+ ) ;
164+ }
165+ }
166+
167+ Ok ( ( ) )
168+ }
0 commit comments