13
13
14
14
import java .io .File ;
15
15
import java .io .IOException ;
16
+ import java .nio .charset .Charset ;
16
17
import java .nio .file .Files ;
17
18
import java .nio .file .Path ;
19
+ import java .util .ArrayList ;
20
+ import java .util .Arrays ;
21
+ import java .util .List ;
18
22
import java .util .Map ;
19
23
20
24
@ Mojo (name = "install" , defaultPhase = LifecyclePhase .INITIALIZE , threadSafe = true )
21
25
public final class GitHookInstallMojo extends AbstractMojo {
22
26
23
- private static final String SHEBANG = "#!/bin/sh" ;
27
+ private static final String NEW_LINE = System .lineSeparator ();
28
+ private static final String SHEBANG = "#!/bin/sh" + NEW_LINE ;
29
+ private static final List <String > validHooks = Arrays .asList (
30
+ "applypatch-msg" ,
31
+ "pre-applypatch" ,
32
+ "post-applypatch" ,
33
+ "pre-commit" ,
34
+ "prepare-commit-msg" ,
35
+ "commit-msg" ,
36
+ "post-commit" ,
37
+ "pre-rebase" ,
38
+ "post-checkout" ,
39
+ "post-merge" ,
40
+ "pre-receive" ,
41
+ "update" ,
42
+ "post-receive" ,
43
+ "post-update" ,
44
+ "pre-auto-gc" ,
45
+ "post-rewrite" ,
46
+ "pre-push"
47
+ );
24
48
25
49
@ Parameter
26
50
private Map <String , String > hooks ;
@@ -41,18 +65,23 @@ public void execute() throws MojoExecutionException, MojoFailureException {
41
65
42
66
for (Map .Entry <String , String > hook : hooks .entrySet ()) {
43
67
String hookName = hook .getKey ();
44
- String finalScript = SHEBANG + '\n' + hook .getValue ();
68
+ if (!validHooks .contains (hookName )) {
69
+ getLog ().error ( String .format ("`%s` hook is not a valid git-hook name" , hookName ) );
70
+ continue ;
71
+ }
72
+
73
+ String hookScript = hook .getValue ();
74
+ String finalScript = (hookScript .startsWith ("#!" ) ? "" : SHEBANG ) + hookScript + NEW_LINE ;
45
75
try {
46
- getLog ().debug (String .format ("Installing %s hook into %s" , hookName ,
47
- hooksDir .toAbsolutePath ().toString ()));
48
- writeFile (hooksDir .resolve (hookName ), finalScript .getBytes ());
76
+ getLog ().info ( String .format ("Installing %s hook into %s" , hookName , hooksDir .toAbsolutePath ().toString ()) );
77
+ writeFile (hooksDir .resolve (hookName ), finalScript .getBytes (Charset .forName ("UTF-8" )));
49
78
} catch (IOException e ) {
50
79
throw new MojoExecutionException ("Could not write hook with name: " + hookName , e );
51
80
}
52
81
}
53
82
}
54
83
55
- protected synchronized void writeFile (Path path , byte [] bytes ) throws IOException {
84
+ private synchronized void writeFile (Path path , byte [] bytes ) throws IOException {
56
85
File created = Files .write (path , bytes , CREATE , TRUNCATE_EXISTING ).toFile ();
57
86
boolean success = created .setExecutable (true , true )
58
87
&& created .setReadable (true , true )
0 commit comments