1
1
package org .ajoberstar .grgit .gradle ;
2
2
3
3
import java .io .File ;
4
+ import java .util .Optional ;
4
5
5
6
import javax .inject .Inject ;
6
7
9
10
import org .gradle .api .logging .Logger ;
10
11
import org .gradle .api .logging .Logging ;
11
12
import org .gradle .api .provider .Property ;
13
+ import org .gradle .api .provider .ProviderFactory ;
12
14
import org .gradle .api .services .BuildService ;
13
15
import org .gradle .api .services .BuildServiceParameters ;
14
16
@@ -23,39 +25,55 @@ public interface Params extends BuildServiceParameters {
23
25
Property <Boolean > getInitIfNotExists ();
24
26
}
25
27
26
- private final Grgit grgit ;
27
-
28
28
@ Inject
29
- public GrgitService () {
29
+ public GrgitService (ProviderFactory providers ) {
30
+ getGrgitProperty ().set (providers .provider (this ::makeGrgit ));
31
+ getGrgitProperty ().disallowChanges ();
32
+ getGrgitProperty ().finalizeValueOnRead ();
33
+ }
34
+
35
+ protected abstract Property <Grgit > getGrgitProperty ();
36
+
37
+ public Grgit getGrgit () {
38
+ return getGrgitProperty ().get ();
39
+ }
40
+
41
+ public Optional <Grgit > findGrgit () {
42
+ try {
43
+ return Optional .of (getGrgit ());
44
+ } catch (Exception e ) {
45
+ logger .info ("Failed to make grgit service." , e );
46
+ return Optional .empty ();
47
+ }
48
+ }
49
+
50
+ @ Override
51
+ public void close () throws Exception {
52
+ findGrgit ().ifPresent (grgit -> {
53
+ logger .info ("Closing Git repo: {}" , grgit .getRepository ().getRootDir ());
54
+ grgit .close ();
55
+ });
56
+ }
57
+
58
+ private Grgit makeGrgit () {
30
59
if (getParameters ().getCurrentDirectory ().isPresent ()) {
31
- this . grgit = Grgit .open (op -> {
60
+ return Grgit .open (op -> {
32
61
op .setCurrentDir (getParameters ().getCurrentDirectory ().get ().getAsFile ());
33
62
});
34
- return ;
35
63
}
36
64
37
65
var dir = getParameters ().getDirectory ().get ().getAsFile ();
38
66
var gitDir = new File (dir , ".git" );
39
67
if (gitDir .exists ()) {
40
- this . grgit = Grgit .open (op -> {
68
+ return Grgit .open (op -> {
41
69
op .setDir (dir );
42
70
});
43
71
} else if (getParameters ().getInitIfNotExists ().getOrElse (false )) {
44
- this . grgit = Grgit .init (op -> {
72
+ return Grgit .init (op -> {
45
73
op .setDir (dir );
46
74
});
47
75
} else {
48
76
throw new IllegalStateException ("No Git repo exists at " + dir + " and initIfNotExists is false. Cannot proceed." );
49
77
}
50
78
}
51
-
52
- public Grgit getGrgit () {
53
- return grgit ;
54
- }
55
-
56
- @ Override
57
- public void close () throws Exception {
58
- logger .info ("Closing Git repo: {}" , grgit .getRepository ().getRootDir ());
59
- grgit .close ();
60
- }
61
79
}
0 commit comments