1
+ use std:: path:: Path ;
2
+
1
3
/// Common knowledge about the worktree that is needed across most interactions with the work tree
2
4
#[ cfg_attr( feature = "serde1" , derive( serde:: Serialize , serde:: Deserialize ) ) ]
3
5
#[ derive( PartialEq , Eq , Debug , Hash , Ord , PartialOrd , Clone , Copy ) ]
@@ -20,45 +22,40 @@ pub struct Context {
20
22
}
21
23
22
24
impl Context {
23
- /// try to determine all values in this context by probing them in the current working directory, which should be on the file system
24
- /// the git repository is located on.
25
+ /// try to determine all values in this context by probing them in the given ` directory` , which
26
+ /// should be on the file system the git repository is located on.
25
27
///
26
28
/// All errors are ignored and interpreted on top of the default for the platform the binary is compiled for.
27
- pub fn from_probing_cwd ( ) -> Self {
29
+ pub fn probe ( directory : impl AsRef < std:: path:: Path > ) -> Self {
30
+ let root = directory. as_ref ( ) ;
28
31
let ctx = Context :: default ( ) ;
29
32
Context {
30
- symlink : Self :: probe_symlink ( ) . unwrap_or ( ctx. symlink ) ,
33
+ symlink : Self :: probe_symlink ( root ) . unwrap_or ( ctx. symlink ) ,
31
34
..ctx
32
35
}
33
36
}
34
37
35
- fn probe_symlink ( ) -> Option < bool > {
36
- let src_path = "__link_src_file" ;
37
- std:: fs:: File :: options ( )
38
- . create_new ( true )
39
- . write ( true )
40
- . open ( src_path)
41
- . ok ( ) ?;
42
- let link_path = "__file_link" ;
43
- if symlink:: symlink_file ( src_path, link_path) . is_err ( ) {
44
- std:: fs:: remove_file ( src_path) . ok ( ) ;
45
- return None ;
38
+ fn probe_symlink ( root : & Path ) -> std:: io:: Result < bool > {
39
+ let src_path = root. join ( "__link_src_file" ) ;
40
+ std:: fs:: File :: options ( ) . create_new ( true ) . write ( true ) . open ( & src_path) ?;
41
+ let link_path = root. join ( "__file_link" ) ;
42
+ if symlink:: symlink_file ( & src_path, & link_path) . is_err ( ) {
43
+ std:: fs:: remove_file ( & src_path) ?;
44
+ return Ok ( false ) ;
46
45
}
47
46
let cleanup_all = || {
48
- std:: fs:: remove_file ( src_path) . ok ( ) ;
49
- symlink:: remove_symlink_file ( link_path)
50
- . or_else ( |_| std:: fs:: remove_file ( link_path) )
51
- . ok ( ) ;
47
+ let res = std:: fs:: remove_file ( & src_path) ;
48
+ symlink:: remove_symlink_file ( & link_path)
49
+ . or_else ( |_| std:: fs:: remove_file ( & link_path) )
50
+ . and ( res )
52
51
} ;
53
52
54
- let res = Some (
55
- std:: fs:: symlink_metadata ( link_path)
56
- . map_err ( |_| cleanup_all ( ) )
57
- . ok ( ) ?
58
- . is_symlink ( ) ,
59
- ) ;
60
- cleanup_all ( ) ;
61
- res
53
+ let res = std:: fs:: symlink_metadata ( & link_path)
54
+ . or_else ( |err| cleanup_all ( ) . and ( Err ( err) ) ) ?
55
+ . is_symlink ( ) ;
56
+
57
+ cleanup_all ( ) ?;
58
+ Ok ( res)
62
59
}
63
60
}
64
61
0 commit comments