-
-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathAbstractGitFlowMojo.java
1065 lines (953 loc) · 35.5 KB
/
AbstractGitFlowMojo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014-2017 Aleksandr Mashchenko.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amashchenko.maven.plugin.gitflow;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.components.interactivity.Prompter;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
/**
* Abstract git flow mojo.
*
*/
public abstract class AbstractGitFlowMojo extends AbstractMojo {
/** A full name of the versions-maven-plugin set goal. */
private static final String VERSIONS_MAVEN_PLUGIN_SET_GOAL = "org.codehaus.mojo:versions-maven-plugin:2.1:set";
/** Name of the tycho-versions-plugin set-version goal. */
private static final String TYCHO_VERSIONS_PLUGIN_SET_GOAL = "org.eclipse.tycho:tycho-versions-plugin:set-version";
/** System line separator. */
protected static final String LS = System.getProperty("line.separator");
/** Success exit code. */
private static final int SUCCESS_EXIT_CODE = 0;
/** Pattern of disallowed characters in Maven commands. */
private static final Pattern MAVEN_DISALLOWED_PATTERN = Pattern
.compile("[&|;]");
/** Command line for Git executable. */
private final Commandline cmdGit = new Commandline();
/** Command line for Maven executable. */
private final Commandline cmdMvn = new Commandline();
/** Git flow configuration. */
@Parameter(defaultValue = "${gitFlowConfig}")
protected GitFlowConfig gitFlowConfig;
/**
* Git commit messages.
*
* @since 1.2.1
*/
@Parameter(defaultValue = "${commitMessages}")
protected CommitMessages commitMessages;
/**
* Whether this is Tycho build.
*
* @since 1.1.0
*/
@Parameter(defaultValue = "false")
protected boolean tychoBuild;
/**
* Whether to call Maven install goal during the mojo execution.
*
* @since 1.0.5
*/
@Parameter(property = "installProject", defaultValue = "false")
protected boolean installProject = false;
/**
* Whether to fetch remote branch and compare it with the local one.
*
* @since 1.3.0
*/
@Parameter(property = "fetchRemote", defaultValue = "true")
protected boolean fetchRemote;
/**
* Whether to print commands output into the console.
*
* @since 1.0.7
*/
@Parameter(property = "verbose", defaultValue = "false")
private boolean verbose = false;
/**
* Command line arguments to pass to the underlying Maven commands.
*
* @since 1.8.0
*/
@Parameter(property = "argLine")
private String argLine;
/**
* Whether to make a GPG-signed commit.
*
*/
@Parameter(property = "gpgSignCommit", defaultValue = "false")
private boolean gpgSignCommit = false;
/**
* The path to the Maven executable. Defaults to "mvn".
*/
@Parameter(property = "mvnExecutable")
private String mvnExecutable;
/**
* The path to the Git executable. Defaults to "git".
*/
@Parameter(property = "gitExecutable")
private String gitExecutable;
/** Maven session. */
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
/** Default prompter. */
@Component
protected Prompter prompter;
/** Maven settings. */
@Parameter(defaultValue = "${settings}", readonly = true)
protected Settings settings;
/**
* Initializes command line executables.
*
*/
private void initExecutables() {
if (StringUtils.isBlank(cmdMvn.getExecutable())) {
if (StringUtils.isBlank(mvnExecutable)) {
mvnExecutable = "mvn";
}
cmdMvn.setExecutable(mvnExecutable);
}
if (StringUtils.isBlank(cmdGit.getExecutable())) {
if (StringUtils.isBlank(gitExecutable)) {
gitExecutable = "git";
}
cmdGit.setExecutable(gitExecutable);
}
}
/**
* Validates plugin configuration. Throws exception if configuration is not
* valid.
*
* @param params
* Configuration parameters to validate.
* @throws MojoFailureException
* If configuration is not valid.
*/
protected void validateConfiguration(String... params)
throws MojoFailureException {
if (StringUtils.isNotBlank(argLine)
&& MAVEN_DISALLOWED_PATTERN.matcher(argLine).find()) {
throw new MojoFailureException(
"The argLine doesn't match allowed pattern.");
}
if (params != null && params.length > 0) {
for (String p : params) {
if (StringUtils.isNotBlank(p)
&& MAVEN_DISALLOWED_PATTERN.matcher(p).find()) {
throw new MojoFailureException("The '" + p
+ "' value doesn't match allowed pattern.");
}
}
}
}
/**
* Gets current project version from pom.xml file.
*
* @return Current project version.
* @throws MojoFailureException
*/
protected String getCurrentProjectVersion() throws MojoFailureException {
try {
// read pom.xml
final MavenXpp3Reader mavenReader = new MavenXpp3Reader();
final FileReader fileReader = new FileReader(mavenSession
.getCurrentProject().getFile().getAbsoluteFile());
try {
final Model model = mavenReader.read(fileReader);
if (model.getVersion() == null) {
throw new MojoFailureException(
"Cannot get current project version. This plugin should be executed from the parent project.");
}
return model.getVersion();
} finally {
if (fileReader != null) {
fileReader.close();
}
}
} catch (Exception e) {
throw new MojoFailureException("", e);
}
}
/**
* Compares the production branch name with the development branch name.
*
* @return <code>true</code> if the production branch name is different from
* the development branch name, <code>false</code> otherwise.
*/
protected boolean notSameProdDevName() {
return !gitFlowConfig.getProductionBranch().equals(
gitFlowConfig.getDevelopmentBranch());
}
/**
* Checks uncommitted changes.
*
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void checkUncommittedChanges() throws MojoFailureException,
CommandLineException {
getLog().info("Checking for uncommitted changes.");
if (executeGitHasUncommitted()) {
throw new MojoFailureException(
"You have some uncommitted files. Commit or discard local changes in order to proceed.");
}
}
protected void checkSnapshotDependencies() throws MojoFailureException {
getLog().info("Checking for SNAPSHOT versions in dependencies.");
List<String> snapshots = new ArrayList<String>();
List<String> builtArtifacts = new ArrayList<String>();
List<MavenProject> projects = mavenSession.getProjects();
for (MavenProject project : projects) {
builtArtifacts.add(project.getGroupId() + ":"
+ project.getArtifactId() + ":" + project.getVersion());
List<Dependency> dependencies = project.getDependencies();
for (Dependency d : dependencies) {
String id = d.getGroupId() + ":" + d.getArtifactId() + ":"
+ d.getVersion();
if (!builtArtifacts.contains(id)
&& ArtifactUtils.isSnapshot(d.getVersion())) {
snapshots.add(project + " -> " + d);
}
}
}
if (!snapshots.isEmpty()) {
for (String s : snapshots) {
getLog().warn(s);
}
throw new MojoFailureException(
"There is some SNAPSHOT dependencies in the project, see warnings above. Change them or ignore with `allowSnapshots` property.");
}
}
/**
* Checks if branch name is acceptable.
*
* @param branchName
* Branch name to check.
* @return <code>true</code> when name is valid, <code>false</code>
* otherwise.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected boolean validBranchName(final String branchName)
throws MojoFailureException, CommandLineException {
CommandResult r = executeGitCommandExitCode("check-ref-format",
"--allow-onelevel", branchName);
return r.getExitCode() == SUCCESS_EXIT_CODE;
}
/**
* Executes git commands to check for uncommitted changes.
*
* @return <code>true</code> when there are uncommitted changes,
* <code>false</code> otherwise.
* @throws CommandLineException
* @throws MojoFailureException
*/
private boolean executeGitHasUncommitted() throws MojoFailureException,
CommandLineException {
boolean uncommited = false;
// 1 if there were differences and 0 means no differences
// git diff --no-ext-diff --ignore-submodules --quiet --exit-code
final CommandResult diffCommandResult = executeGitCommandExitCode(
"diff", "--no-ext-diff", "--ignore-submodules", "--quiet",
"--exit-code");
String error = null;
if (diffCommandResult.getExitCode() == SUCCESS_EXIT_CODE) {
// git diff-index --cached --quiet --ignore-submodules HEAD --
final CommandResult diffIndexCommandResult = executeGitCommandExitCode(
"diff-index", "--cached", "--quiet", "--ignore-submodules",
"HEAD", "--");
if (diffIndexCommandResult.getExitCode() != SUCCESS_EXIT_CODE) {
error = diffIndexCommandResult.getError();
uncommited = true;
}
} else {
error = diffCommandResult.getError();
uncommited = true;
}
if (StringUtils.isNotBlank(error)) {
throw new MojoFailureException(error);
}
return uncommited;
}
/**
* Executes git config commands to set Git Flow configuration.
*
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void initGitFlowConfig() throws MojoFailureException,
CommandLineException {
gitSetConfig("gitflow.branch.master",
gitFlowConfig.getProductionBranch());
gitSetConfig("gitflow.branch.develop",
gitFlowConfig.getDevelopmentBranch());
gitSetConfig("gitflow.prefix.feature",
gitFlowConfig.getFeatureBranchPrefix());
gitSetConfig("gitflow.prefix.release",
gitFlowConfig.getReleaseBranchPrefix());
gitSetConfig("gitflow.prefix.hotfix",
gitFlowConfig.getHotfixBranchPrefix());
gitSetConfig("gitflow.prefix.support",
gitFlowConfig.getSupportBranchPrefix());
gitSetConfig("gitflow.prefix.versiontag",
gitFlowConfig.getVersionTagPrefix());
gitSetConfig("gitflow.origin", gitFlowConfig.getOrigin());
}
/**
* Executes git config command.
*
* @param name
* Option name.
* @param value
* Option value.
* @throws MojoFailureException
* @throws CommandLineException
*/
private void gitSetConfig(final String name, String value)
throws MojoFailureException, CommandLineException {
if (value == null || value.isEmpty()) {
value = "\"\"";
}
// ignore error exit codes
executeGitCommandExitCode("config", name, value);
}
/**
* Executes git for-each-ref with <code>refname:short</code> format.
*
* @param branchName
* Branch name to find.
* @param firstMatch
* Return first match.
* @return Branch names which matches <code>refs/heads/{branchName}*</code>.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected String gitFindBranches(final String branchName,
final boolean firstMatch) throws MojoFailureException,
CommandLineException {
String wildcard = "*";
if (branchName.endsWith("/")) {
wildcard = "**";
}
String branches;
if (firstMatch) {
branches = executeGitCommandReturn("for-each-ref", "--count=1",
"--format=\"%(refname:short)\"", "refs/heads/" + branchName
+ wildcard);
} else {
branches = executeGitCommandReturn("for-each-ref",
"--format=\"%(refname:short)\"", "refs/heads/" + branchName
+ wildcard);
}
// on *nix systems return values from git for-each-ref are wrapped in
// quotes
// https://github.com/aleksandr-m/gitflow-maven-plugin/issues/3
branches = removeQuotes(branches);
return branches;
}
/**
* Executes git for-each-ref to get all tags.
*
* @return Git tags.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected String gitFindTags() throws MojoFailureException, CommandLineException {
String tags = executeGitCommandReturn("for-each-ref", "--sort=*authordate", "--format=\"%(refname:short)\"",
"refs/tags/");
// https://github.com/aleksandr-m/gitflow-maven-plugin/issues/3
tags = removeQuotes(tags);
return tags;
}
/**
* Executes git for-each-ref to get the last tag.
*
* @return Last tag.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected String gitFindLastTag() throws MojoFailureException, CommandLineException {
String tag = executeGitCommandReturn("for-each-ref", "--sort=-*authordate", "--count=1",
"--format=\"%(refname:short)\"", "refs/tags/");
// https://github.com/aleksandr-m/gitflow-maven-plugin/issues/3
tag = removeQuotes(tag);
tag = tag.replaceAll("\\r?\\n", "");
return tag;
}
/**
* Removes double quotes from the string.
*
* @param str
* String to remove quotes from.
* @return String without quotes.
*/
private String removeQuotes(String str) {
if (str != null && !str.isEmpty()) {
str = str.replaceAll("\"", "");
}
return str;
}
/**
* Checks if local branch with given name exists.
*
* @param branchName
* Name of the branch to check.
* @return <code>true</code> if local branch exists, <code>false</code>
* otherwise.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected boolean gitCheckBranchExists(final String branchName)
throws MojoFailureException, CommandLineException {
CommandResult commandResult = executeGitCommandExitCode("show-ref",
"--verify", "--quiet", "refs/heads/" + branchName);
return commandResult.getExitCode() == SUCCESS_EXIT_CODE;
}
/**
* Checks if local tag with given name exists.
*
* @param tagName
* Name of the tag to check.
* @return <code>true</code> if local tag exists, <code>false</code> otherwise.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected boolean gitCheckTagExists(final String tagName) throws MojoFailureException, CommandLineException {
CommandResult commandResult = executeGitCommandExitCode("show-ref", "--verify", "--quiet",
"refs/tags/" + tagName);
return commandResult.getExitCode() == SUCCESS_EXIT_CODE;
}
/**
* Executes git checkout.
*
* @param branchName
* Branch name to checkout.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitCheckout(final String branchName)
throws MojoFailureException, CommandLineException {
getLog().info("Checking out '" + branchName + "' branch.");
executeGitCommand("checkout", branchName);
}
/**
* Executes git checkout -b.
*
* @param newBranchName
* Create branch with this name.
* @param fromBranchName
* Create branch from this branch.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitCreateAndCheckout(final String newBranchName,
final String fromBranchName) throws MojoFailureException,
CommandLineException {
getLog().info(
"Creating a new branch '" + newBranchName + "' from '"
+ fromBranchName + "' and checking it out.");
executeGitCommand("checkout", "-b", newBranchName, fromBranchName);
}
/**
* Executes git branch.
*
* @param newBranchName
* Create branch with this name.
* @param fromBranchName
* Create branch from this branch.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitCreateBranch(final String newBranchName, final String fromBranchName)
throws MojoFailureException, CommandLineException {
getLog().info(
"Creating a new branch '" + newBranchName + "' from '"
+ fromBranchName + "'.");
executeGitCommand("branch", newBranchName, fromBranchName);
}
/**
* Executes git commit -a -m.
*
* @param message
* Commit message.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitCommit(final String message) throws MojoFailureException,
CommandLineException {
gitCommit(message, null);
}
/**
* Executes git commit -a -m, replacing <code>@{map.key}</code> with
* <code>map.value</code>.
*
* @param message
* Commit message.
* @param map
* Key is a string to replace wrapped in <code>@{...}</code>.
* Value is a string to replace with.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitCommit(String message, Map<String, String> map)
throws MojoFailureException, CommandLineException {
if (map != null) {
for (Entry<String, String> entr : map.entrySet()) {
message = StringUtils.replace(message, "@{" + entr.getKey()
+ "}", entr.getValue());
}
}
if (gpgSignCommit) {
getLog().info("Committing changes. GPG-signed.");
executeGitCommand("commit", "-a", "-S", "-m", message);
} else {
getLog().info("Committing changes.");
executeGitCommand("commit", "-a", "-m", message);
}
}
/**
* Executes git rebase or git merge --ff-only or git merge --no-ff or git merge.
*
* @param branchName
* Branch name to merge.
* @param rebase
* Do rebase.
* @param noff
* Merge with --no-ff.
* @param ffonly
* Merge with --ff-only.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitMerge(final String branchName, boolean rebase, boolean noff, boolean ffonly)
throws MojoFailureException, CommandLineException {
String sign = "";
if (gpgSignCommit) {
sign = "-S";
}
if (rebase) {
getLog().info("Rebasing '" + branchName + "' branch.");
executeGitCommand("rebase", sign, branchName);
} else if (ffonly) {
getLog().info("Merging (--ff-only) '" + branchName + "' branch.");
executeGitCommand("merge", "--ff-only", sign, branchName);
} else if (noff) {
getLog().info("Merging (--no-ff) '" + branchName + "' branch.");
executeGitCommand("merge", "--no-ff", sign, branchName);
} else {
getLog().info("Merging '" + branchName + "' branch.");
executeGitCommand("merge", sign, branchName);
}
}
/**
* Executes git merge --no-ff.
*
* @param branchName
* Branch name to merge.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitMergeNoff(final String branchName)
throws MojoFailureException, CommandLineException {
gitMerge(branchName, false, true, false);
}
/**
* Executes git merge --squash.
*
* @param branchName
* Branch name to merge.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitMergeSquash(final String branchName)
throws MojoFailureException, CommandLineException {
getLog().info("Squashing '" + branchName + "' branch.");
executeGitCommand("merge", "--squash", branchName);
}
/**
* Executes git tag -a [-s] -m.
*
* @param tagName
* Name of the tag.
* @param message
* Tag message.
* @param gpgSignTag
* Make a GPG-signed tag.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitTag(final String tagName, final String message, boolean gpgSignTag)
throws MojoFailureException, CommandLineException {
if (gpgSignTag) {
getLog().info("Creating GPG-signed '" + tagName + "' tag.");
executeGitCommand("tag", "-a", "-s", tagName, "-m", message);
} else {
getLog().info("Creating '" + tagName + "' tag.");
executeGitCommand("tag", "-a", tagName, "-m", message);
}
}
/**
* Executes git branch -d.
*
* @param branchName
* Branch name to delete.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitBranchDelete(final String branchName)
throws MojoFailureException, CommandLineException {
getLog().info("Deleting '" + branchName + "' branch.");
executeGitCommand("branch", "-d", branchName);
}
/**
* Executes git branch -D.
*
* @param branchName
* Branch name to delete.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitBranchDeleteForce(final String branchName)
throws MojoFailureException, CommandLineException {
getLog().info("Deleting (-D) '" + branchName + "' branch.");
executeGitCommand("branch", "-D", branchName);
}
/**
* Fetches and checkouts from remote if local branch doesn't exist.
*
* @param branchName
* Branch name to check.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitFetchRemoteAndCreate(final String branchName)
throws MojoFailureException, CommandLineException {
if (!gitCheckBranchExists(branchName)) {
getLog().info(
"Local branch '"
+ branchName
+ "' doesn't exist. Trying to fetch and check it out from '"
+ gitFlowConfig.getOrigin() + "'.");
gitFetchRemote(branchName);
gitCreateAndCheckout(branchName, gitFlowConfig.getOrigin() + "/"
+ branchName);
}
}
/**
* Executes git fetch and compares local branch with the remote.
*
* @param branchName
* Branch name to fetch and compare.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitFetchRemoteAndCompare(final String branchName)
throws MojoFailureException, CommandLineException {
if (gitFetchRemote(branchName)) {
getLog().info(
"Comparing local branch '" + branchName + "' with remote '"
+ gitFlowConfig.getOrigin() + "/" + branchName
+ "'.");
String revlistout = executeGitCommandReturn("rev-list",
"--left-right", "--count", branchName + "..."
+ gitFlowConfig.getOrigin() + "/" + branchName);
String[] counts = org.apache.commons.lang3.StringUtils.split(
revlistout, '\t');
if (counts != null && counts.length > 1) {
if (!"0".equals(org.apache.commons.lang3.StringUtils
.deleteWhitespace(counts[1]))) {
throw new MojoFailureException("Remote branch '"
+ gitFlowConfig.getOrigin() + "/" + branchName
+ "' is ahead of the local branch '" + branchName
+ "'. Execute git pull.");
}
}
}
}
/**
* Executes git fetch.
*
* @param branchName
* Branch name to fetch.
* @return <code>true</code> if git fetch returned success exit code,
* <code>false</code> otherwise.
* @throws MojoFailureException
* @throws CommandLineException
*/
private boolean gitFetchRemote(final String branchName)
throws MojoFailureException, CommandLineException {
getLog().info(
"Fetching remote branch '" + gitFlowConfig.getOrigin() + " "
+ branchName + "'.");
CommandResult result = executeGitCommandExitCode("fetch", "--quiet",
gitFlowConfig.getOrigin(), branchName);
boolean success = result.getExitCode() == SUCCESS_EXIT_CODE;
if (!success) {
getLog().warn(
"There were some problems fetching remote branch '"
+ gitFlowConfig.getOrigin()
+ " "
+ branchName
+ "'. You can turn off remote branch fetching by setting the 'fetchRemote' parameter to false.");
}
return success;
}
/**
* Executes git push, optionally with the <code>--follow-tags</code>
* argument.
*
* @param branchName
* Branch name to push.
* @param pushTags
* If <code>true</code> adds <code>--follow-tags</code> argument
* to the git <code>push</code> command.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitPush(final String branchName, boolean pushTags)
throws MojoFailureException, CommandLineException {
getLog().info(
"Pushing '" + branchName + "' branch" + " to '"
+ gitFlowConfig.getOrigin() + "'.");
if (pushTags) {
executeGitCommand("push", "--quiet", "-u", "--follow-tags",
gitFlowConfig.getOrigin(), branchName);
} else {
executeGitCommand("push", "--quiet", "-u",
gitFlowConfig.getOrigin(), branchName);
}
}
protected void gitPushDelete(final String branchName)
throws MojoFailureException, CommandLineException {
getLog().info(
"Deleting remote branch '" + branchName + "' from '"
+ gitFlowConfig.getOrigin() + "'.");
CommandResult result = executeGitCommandExitCode("push", "--delete",
gitFlowConfig.getOrigin(), branchName);
if (result.getExitCode() != SUCCESS_EXIT_CODE) {
getLog().warn(
"There were some problems deleting remote branch '"
+ branchName + "' from '"
+ gitFlowConfig.getOrigin() + "'.");
}
}
/**
* Executes 'set' goal of versions-maven-plugin or 'set-version' of
* tycho-versions-plugin in case it is tycho build.
*
* @param version
* New version to set.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void mvnSetVersions(final String version)
throws MojoFailureException, CommandLineException {
getLog().info("Updating version(s) to '" + version + "'.");
if (tychoBuild) {
executeMvnCommand(TYCHO_VERSIONS_PLUGIN_SET_GOAL, "-DnewVersion="
+ version, "-Dtycho.mode=maven");
} else {
executeMvnCommand(VERSIONS_MAVEN_PLUGIN_SET_GOAL, "-DnewVersion="
+ version, "-DgenerateBackupPoms=false");
}
}
/**
* Executes mvn clean test.
*
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void mvnCleanTest() throws MojoFailureException,
CommandLineException {
getLog().info("Cleaning and testing the project.");
if (tychoBuild) {
executeMvnCommand("clean", "verify");
} else {
executeMvnCommand("clean", "test");
}
}
/**
* Executes mvn clean install.
*
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void mvnCleanInstall() throws MojoFailureException,
CommandLineException {
getLog().info("Cleaning and installing the project.");
executeMvnCommand("clean", "install");
}
/**
* Executes Maven goals.
*
* @param goals
* The goals to execute.
* @throws Exception
*/
protected void mvnRun(final String goals) throws Exception {
getLog().info("Running Maven goals: " + goals);
executeMvnCommand(CommandLineUtils.translateCommandline(goals));
}
/**
* Executes Git command and returns output.
*
* @param args
* Git command line arguments.
* @return Command output.
* @throws CommandLineException
* @throws MojoFailureException
*/
private String executeGitCommandReturn(final String... args)
throws CommandLineException, MojoFailureException {
return executeCommand(cmdGit, true, null, args).getOut();
}
/**
* Executes Git command without failing on non successful exit code.
*
* @param args
* Git command line arguments.
* @return Command result.
* @throws CommandLineException
* @throws MojoFailureException
*/
private CommandResult executeGitCommandExitCode(final String... args)
throws CommandLineException, MojoFailureException {
return executeCommand(cmdGit, false, null, args);
}
/**
* Executes Git command.
*
* @param args
* Git command line arguments.
* @throws CommandLineException
* @throws MojoFailureException
*/
private void executeGitCommand(final String... args)
throws CommandLineException, MojoFailureException {
executeCommand(cmdGit, true, null, args);
}
/**
* Executes Maven command.
*
* @param args
* Maven command line arguments.
* @throws CommandLineException
* @throws MojoFailureException
*/
private void executeMvnCommand(final String... args)
throws CommandLineException, MojoFailureException {
executeCommand(cmdMvn, true, argLine, args);
}
/**
* Executes command line.
*
* @param cmd
* Command line.
* @param failOnError
* Whether to throw exception on NOT success exit code.
* @param argStr
* Command line arguments as a string.
* @param args
* Command line arguments.
* @return {@link CommandResult} instance holding command exit code, output
* and error if any.
* @throws CommandLineException
* @throws MojoFailureException
* If <code>failOnError</code> is <code>true</code> and command
* exit code is NOT equals to 0.
*/
private CommandResult executeCommand(final Commandline cmd,
final boolean failOnError, final String argStr,
final String... args) throws CommandLineException,
MojoFailureException {
// initialize executables
initExecutables();
if (getLog().isDebugEnabled()) {
getLog().debug(
cmd.getExecutable() + " " + StringUtils.join(args, " ")
+ (argStr == null ? "" : " " + argStr));
}
cmd.clearArgs();
cmd.addArguments(args);