19
19
20
20
package org .commonwl .view .git ;
21
21
22
+ import org .apache .commons .codec .digest .DigestUtils ;
22
23
import org .eclipse .jgit .api .Git ;
23
24
import org .eclipse .jgit .api .errors .GitAPIException ;
25
+ import org .slf4j .Logger ;
26
+ import org .slf4j .LoggerFactory ;
24
27
import org .springframework .beans .factory .annotation .Autowired ;
25
28
import org .springframework .beans .factory .annotation .Value ;
26
29
import org .springframework .stereotype .Service ;
27
30
31
+ import java .io .File ;
32
+ import java .io .IOException ;
28
33
import java .nio .file .Path ;
29
34
30
- import static java .util .Collections .singleton ;
31
- import static org .apache .jena .ext .com .google .common .io .Files .createTempDir ;
32
-
33
35
/**
34
36
* Handles Git related functionality
35
37
*/
36
38
@ Service
37
39
public class GitService {
38
40
41
+ private final Logger logger = LoggerFactory .getLogger (this .getClass ());
42
+
39
43
// Location to check out git repositories into
40
44
private Path gitStorage ;
41
45
@@ -55,13 +59,44 @@ public GitService(@Value("${gitStorage}") Path gitStorage,
55
59
*/
56
60
public Git cloneRepository (GitDetails gitDetails )
57
61
throws GitAPIException {
58
- return Git .cloneRepository ()
59
- .setCloneSubmodules (cloneSubmodules )
60
- .setURI (gitDetails .getRepoUrl ())
61
- .setDirectory (createTempDir ())
62
- .setBranchesToClone (singleton ("refs/heads/" + gitDetails .getBranch ()))
63
- .setBranch ("refs/heads/" + gitDetails .getBranch ())
64
- .call ();
62
+ Git repo = null ;
63
+ try {
64
+ // Get base directory based on configuration
65
+ File baseDir = new File (gitStorage .toString ());
66
+ String baseName = DigestUtils .shaHex (GitDetails .normaliseUrl (gitDetails .getRepoUrl ()));
67
+
68
+ // Check if folder already exists
69
+ File repoDir = new File (baseDir , baseName );
70
+ if (repoDir .exists () && repoDir .isDirectory ()) {
71
+ repo = Git .open (repoDir );
72
+ repo .fetch ().call ();
73
+ } else {
74
+ // Create a folder and clone repository into it
75
+ if (repoDir .mkdir ()) {
76
+ repo = Git .cloneRepository ()
77
+ .setCloneSubmodules (cloneSubmodules )
78
+ .setURI (gitDetails .getRepoUrl ())
79
+ .setDirectory (repoDir )
80
+ .setCloneAllBranches (true )
81
+ .call ();
82
+ }
83
+ }
84
+
85
+ // Checkout the specific branch or commit ID
86
+ if (repo != null ) {
87
+ repo .checkout ()
88
+ .setName (gitDetails .getBranch ())
89
+ .call ();
90
+ if (repo .getRepository ().getFullBranch () != null ) {
91
+ repo .pull ().call ();
92
+ }
93
+ }
94
+ } catch (IOException ex ) {
95
+ logger .error ("Could not open existing Git repository for '"
96
+ + gitDetails .getRepoUrl () + "'" , ex );
97
+ }
98
+
99
+ return repo ;
65
100
}
66
101
67
102
0 commit comments