@@ -47,6 +47,25 @@ pub fn work_dir(repo: &Repository) -> &Path {
4747 repo. workdir ( ) . expect ( "unable to query workdir" )
4848}
4949
50+ ///
51+ pub fn get_head ( repo_path : & str ) -> Result < CommitId > {
52+ let repo = repo ( repo_path) ?;
53+ get_head_repo ( & repo)
54+ }
55+
56+ ///
57+ pub fn get_head_repo ( repo : & Repository ) -> Result < CommitId > {
58+ scope_time ! ( "get_head_repo" ) ;
59+
60+ let head = repo. head ( ) ?. target ( ) ;
61+
62+ if let Some ( head_id) = head {
63+ Ok ( CommitId :: new ( head_id) )
64+ } else {
65+ Err ( Error :: NoHead )
66+ }
67+ }
68+
5069/// ditto
5170pub fn commit_new ( repo_path : & str , msg : & str ) -> Result < CommitId > {
5271 commit ( repo_path, msg) . map ( CommitId :: new)
@@ -63,17 +82,8 @@ pub fn commit(repo_path: &str, msg: &str) -> Result<Oid> {
6382 let tree_id = index. write_tree ( ) ?;
6483 let tree = repo. find_tree ( tree_id) ?;
6584
66- //TODO: use NoHead error
67- let parents = if let Ok ( reference) = repo. head ( ) {
68- let parent = repo. find_commit (
69- reference. target ( ) . ok_or_else ( || {
70- Error :: Generic (
71- "failed to get the target for reference"
72- . to_string ( ) ,
73- )
74- } ) ?,
75- ) ?;
76- vec ! [ parent]
85+ let parents = if let Ok ( id) = get_head ( repo_path) {
86+ vec ! [ repo. find_commit( id. into( ) ) ?]
7787 } else {
7888 Vec :: new ( )
7989 } ;
@@ -323,4 +333,26 @@ mod tests {
323333
324334 Ok ( ( ) )
325335 }
336+
337+ #[ test]
338+ fn test_head_empty ( ) -> Result < ( ) > {
339+ let ( _td, repo) = repo_init_empty ( ) ?;
340+ let root = repo. path ( ) . parent ( ) . unwrap ( ) ;
341+ let repo_path = root. as_os_str ( ) . to_str ( ) . unwrap ( ) ;
342+
343+ assert_eq ! ( get_head( repo_path) . is_ok( ) , false ) ;
344+
345+ Ok ( ( ) )
346+ }
347+
348+ #[ test]
349+ fn test_head ( ) -> Result < ( ) > {
350+ let ( _td, repo) = repo_init ( ) ?;
351+ let root = repo. path ( ) . parent ( ) . unwrap ( ) ;
352+ let repo_path = root. as_os_str ( ) . to_str ( ) . unwrap ( ) ;
353+
354+ assert_eq ! ( get_head( repo_path) . is_ok( ) , true ) ;
355+
356+ Ok ( ( ) )
357+ }
326358}
0 commit comments