-
-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathAbstractGitFlowMojo.java
1430 lines (1276 loc) · 52.4 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-2024 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.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.TimeZone;
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.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.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingResult;
import org.apache.maven.settings.Settings;
import org.apache.maven.shared.release.policy.version.VersionPolicy;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.Os;
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;
import com.amashchenko.maven.plugin.gitflow.prompter.GitFlowPrompter;
/**
* Abstract git flow mojo.
*
*/
public abstract class AbstractGitFlowMojo extends AbstractMojo {
/** Group and artifact id of the versions-maven-plugin. */
private static final String VERSIONS_MAVEN_PLUGIN = "org.codehaus.mojo:versions-maven-plugin";
/** The versions-maven-plugin set goal. */
private static final String VERSIONS_MAVEN_PLUGIN_SET_GOAL = "set";
/** The versions-maven-plugin set-property goal. */
private static final String VERSIONS_MAVEN_PLUGIN_SET_PROPERTY_GOAL = "set-property";
/** Group and artifact id of the tycho-versions-plugin. */
private static final String TYCHO_VERSIONS_PLUGIN = "org.eclipse.tycho:tycho-versions-plugin";
/** The tycho-versions-plugin set-version goal. */
private static final String TYCHO_VERSIONS_PLUGIN_SET_GOAL = "set-version";
/** Name of the property needed to have reproducible builds. */
private static final String REPRODUCIBLE_BUILDS_PROPERTY = "project.build.outputTimestamp";
/** 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();
/** Whether .gitmodules file exists in project. */
private final boolean gitModulesExists;
/** 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.
*
* @since 1.9.0
*/
@Parameter(property = "gpgSignCommit", defaultValue = "false")
private boolean gpgSignCommit = false;
/**
* Whether to set -DgroupId='*' -DartifactId='*' when calling
* versions-maven-plugin.
*
* @since 1.10.0
*/
@Parameter(property = "versionsForceUpdate", defaultValue = "false")
private boolean versionsForceUpdate = false;
/**
* Property to set version to.
*
* @since 1.13.0
*/
@Parameter(property = "versionProperty")
private String versionProperty;
/**
* Whether to skip updating version. Useful with {@link #versionProperty} to be
* able to update <code>revision</code> property without modifying version tag.
*
* @since 1.13.0
*/
@Parameter(property = "skipUpdateVersion")
private boolean skipUpdateVersion = false;
/**
* Prefix that is applied to commit messages.
*
* @since 1.14.0
*/
@Parameter(property = "commitMessagePrefix")
private String commitMessagePrefix;
/**
* Whether to update the <code>project.build.outputTimestamp</code> property
* automatically or not.
*
* @since 1.17.0
*/
@Parameter(property = "updateOutputTimestamp", defaultValue = "true")
private boolean updateOutputTimestamp = true;
/**
* The role-hint for the
* {@link org.apache.maven.shared.release.policy.version.VersionPolicy}
* implementation used to calculate the project versions. If a policy is set
* other parameters controlling the generation of version are ignored
* (digitsOnlyDevVersion, versionDigitToIncrement).
*
* @since 1.18.0
*/
@Parameter(property = "projectVersionPolicyId")
private String projectVersionPolicyId;
/**
* Version of versions-maven-plugin to use.
*
* @since 1.18.0
*/
@Parameter(property = "versionsMavenPluginVersion", defaultValue = "2.16.0")
private String versionsMavenPluginVersion = "2.16.0";
/**
* Version of tycho-versions-plugin to use.
*
* @since 1.18.0
*/
@Parameter(property = "tychoVersionsPluginVersion", defaultValue = "1.7.0")
private String tychoVersionsPluginVersion = "1.7.0";
/**
* Options to pass to Git push command using <code>--push-option</code>.
* Multiple options can be added separated with a space e.g.
* <code>-DgitPushOptions="merge_request.create merge_request.target=develop
* merge_request.label='Super feature'"</code>
*
* @since 1.18.0
*/
@Parameter(property = "gitPushOptions")
private String gitPushOptions;
/**
* Explicitly enable or disable executing Git submodule update before commit. By
* default plugin tries to automatically determine if update of the Git
* submodules is needed.
*
* @since 1.19.0
*/
@Parameter(property = "updateGitSubmodules")
private Boolean updateGitSubmodules;
/**
* 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)
protected MavenSession mavenSession;
@Component
protected ProjectBuilder projectBuilder;
/** Default prompter. */
@Component
protected GitFlowPrompter prompter;
/** Maven settings. */
@Parameter(defaultValue = "${settings}", readonly = true)
protected Settings settings;
@Component
protected Map<String, VersionPolicy> versionPolicies;
public AbstractGitFlowMojo() {
gitModulesExists = FileUtils.fileExists(".gitmodules");
}
/**
* Initializes command line executables.
*
*/
private void initExecutables() {
if (StringUtils.isBlank(cmdMvn.getExecutable())) {
if (StringUtils.isBlank(mvnExecutable)) {
final String javaCommand = mavenSession.getSystemProperties().getProperty("sun.java.command", "");
final boolean wrapper = javaCommand.startsWith("org.apache.maven.wrapper.MavenWrapperMain");
if (wrapper) {
mvnExecutable = "." + File.separator + "mvnw";
} else {
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
* If current project version cannot be obtained.
*/
protected String getCurrentProjectVersion() throws MojoFailureException {
final MavenProject reloadedProject = reloadProject(mavenSession.getCurrentProject());
if (reloadedProject.getVersion() == null) {
throw new MojoFailureException(
"Cannot get current project version. This plugin should be executed from the parent project.");
}
return reloadedProject.getVersion();
}
/**
* Gets current project {@link #REPRODUCIBLE_BUILDS_PROPERTY} property value
* from pom.xml file.
*
* @return Value of {@link #REPRODUCIBLE_BUILDS_PROPERTY} property.
* @throws MojoFailureException
* If project loading fails.
*/
private String getCurrentProjectOutputTimestamp() throws MojoFailureException {
final MavenProject reloadedProject = reloadProject(mavenSession.getCurrentProject());
return reloadedProject.getProperties().getProperty(REPRODUCIBLE_BUILDS_PROPERTY);
}
/**
* Reloads projects info from file.
*
* @param project
* @return Reloaded Maven projects.
* @throws MojoFailureException
* If project loading fails.
*/
private List<MavenProject> reloadProjects(final MavenProject project) throws MojoFailureException {
try {
List<ProjectBuildingResult> result = projectBuilder.build(
Collections.singletonList(project.getFile()),
true,
mavenSession.getProjectBuildingRequest());
List<MavenProject> projects = new ArrayList<>();
for (ProjectBuildingResult projectBuildingResult : result) {
projects.add(projectBuildingResult.getProject());
}
return projects;
} catch (Exception e) {
throw new MojoFailureException("Error re-loading project info", e);
}
}
/**
* Reloads project info from file.
*
* @param project
* @return Maven project which is the execution root.
* @throws MojoFailureException
* If project loading fails.
*/
private MavenProject reloadProject(final MavenProject project) throws MojoFailureException {
List<MavenProject> projects = reloadProjects(project);
for (MavenProject resultProject : projects) {
if (resultProject.isExecutionRoot()) {
return resultProject;
}
}
throw new NoSuchElementException(
"No reloaded project appears to be the execution root (" + project.getGroupId() + ":" + project.getArtifactId() + ")");
}
/**
* 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
* If there is some uncommitted files.
* @throws CommandLineException
* If command line execution fails.
*/
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<>();
Set<String> builtArtifacts = new HashSet<>();
List<MavenProject> projects = reloadProjects(mavenSession.getCurrentProject());
for (MavenProject project : projects) {
builtArtifacts.add(project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion());
}
for (MavenProject project : projects) {
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);
}
}
MavenProject parent = project.getParent();
if (parent != null) {
String id = parent.getGroupId() + ":" + parent.getArtifactId() + ":" + parent.getVersion();
if (!builtArtifacts.contains(id) && ArtifactUtils.isSnapshot(parent.getVersion())) {
snapshots.add(project + " -> " + parent);
}
}
}
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
* Shouldn't happen, actually.
* @throws CommandLineException
* If command line execution fails.
*/
protected boolean validBranchName(final String branchName) throws MojoFailureException, CommandLineException {
CommandResult res = executeGitCommandExitCode("check-ref-format", "--allow-onelevel", branchName);
return res.getExitCode() == SUCCESS_EXIT_CODE;
}
/**
* Checks if version is valid.
*
* @param version
* Version to validate.
* @return <code>true</code> when version is valid, <code>false</code>
* otherwise.
* @throws MojoFailureException
* Shouldn't happen, actually.
* @throws CommandLineException
* If command line execution fails.
*/
protected boolean validVersion(final String version) throws MojoFailureException, CommandLineException {
boolean valid = "".equals(version) || (GitFlowVersionInfo.isValidVersion(version) && validBranchName(version));
if (!valid) {
getLog().info("The version is not valid.");
}
return valid;
}
/**
* Executes git commands to check for uncommitted changes.
*
* @return <code>true</code> when there are uncommitted changes,
* <code>false</code> otherwise.
* @throws CommandLineException
* If command line execution fails.
* @throws MojoFailureException
* If command line execution returns false code.
*/
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
* Shouldn't happen, actually.
* @throws CommandLineException
* If command line execution fails.
*/
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
* Shouldn't happen, actually.
* @throws CommandLineException
* If command line execution fails.
*/
private void gitSetConfig(final String name, String value) throws MojoFailureException, CommandLineException {
if (value == null || value.isEmpty()) {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
value = "\"\"";
}
else {
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected String gitFindBranches(final String branchName, final boolean firstMatch) throws MojoFailureException, CommandLineException {
return gitFindBranches("refs/heads/", branchName, firstMatch);
}
/**
* Executes git for-each-ref with <code>refname:short</code> format.
*
* @param refs
* Refs to search.
* @param branchName
* Branch name to find.
* @param firstMatch
* Return first match.
* @return Branch names which matches <code>{refs}{branchName}*</code>.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
private String gitFindBranches(final String refs, 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 + branchName + wildcard);
} else {
branches = executeGitCommandReturn("for-each-ref",
"--format=\"%(refname:short)\"", refs + 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);
branches = StringUtils.strip(branches);
return branches;
}
/**
* Executes git for-each-ref to get all tags.
*
* @return Git tags.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected String gitFindLastTag() throws MojoFailureException, CommandLineException {
String tag = executeGitCommandReturn("for-each-ref", "--sort=-version:refname", "--sort=-taggerdate",
"--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) {
return StringUtils.replace(str, "\"", "");
}
/**
* Gets the current branch name.
*
* @return Current branch name.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected String gitCurrentBranch() throws MojoFailureException, CommandLineException {
String name = executeGitCommandReturn("symbolic-ref", "-q", "--short", "HEAD");
name = StringUtils.strip(name);
return name;
}
/**
* 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
* Shouldn't happen, actually.
* @throws CommandLineException
* If command line execution fails.
*/
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
* Shouldn't happen, actually.
* @throws CommandLineException
* If command line execution fails.
*/
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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);
}
/**
* Replaces properties in message.
*
* @param message
* @param map
* Key is a string to replace wrapped in <code>@{...}</code>. Value
* is a string to replace with.
* @return Message with replaced properties.
*/
private String replaceProperties(String message, Map<String, String> map) {
if (map != null) {
for (Entry<String, String> entr : map.entrySet()) {
message = StringUtils.replace(message, "@{" + entr.getKey() + "}", entr.getValue());
}
}
return message;
}
/**
* Executes git commit -a -m.
*
* @param message
* Commit message.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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 messageProperties
* Properties to replace in message.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected void gitCommit(String message, Map<String, String> messageProperties) throws MojoFailureException, CommandLineException {
if ((gitModulesExists && updateGitSubmodules == null) || Boolean.TRUE.equals(updateGitSubmodules)) {
getLog().info("Updating git submodules before commit.");
executeGitCommand("submodule", "update");
}
if (StringUtils.isNotBlank(commitMessagePrefix)) {
message = commitMessagePrefix + message;
}
message = replaceProperties(message, messageProperties);
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.
* @param message
* Merge commit message.
* @param messageProperties
* Properties to replace in message.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected void gitMerge(final String branchName, boolean rebase, boolean noff, boolean ffonly, String message,
Map<String, String> messageProperties)
throws MojoFailureException, CommandLineException {
String sign = null;
if (gpgSignCommit) {
sign = "-S";
}
String msgParam = null;
String msg = null;
if (StringUtils.isNotBlank(message)) {
if (StringUtils.isNotBlank(commitMessagePrefix)) {
message = commitMessagePrefix + message;
}
msgParam = "-m";
msg = replaceProperties(message, messageProperties);
}
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, msgParam, msg);
} else {
getLog().info("Merging '" + branchName + "' branch.");
executeGitCommand("merge", sign, branchName, msgParam, msg);
}
}
/**
* Executes git merge --no-ff.
*
* @param branchName
* Branch name to merge.
* @param message
* Merge commit message.
* @param messageProperties
* Properties to replace in message.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected void gitMergeNoff(final String branchName, final String message, final Map<String, String> messageProperties)
throws MojoFailureException, CommandLineException {
gitMerge(branchName, false, true, false, message, messageProperties);
}
/**
* Executes git merge --squash.
*
* @param branchName
* Branch name to merge.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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.
* @param messageProperties
* Properties to replace in message.
* @throws MojoFailureException
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected void gitTag(final String tagName, String message, boolean gpgSignTag, Map<String, String> messageProperties)
throws MojoFailureException, CommandLineException {
message = replaceProperties(message, messageProperties);
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
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
* If command line execution returns false code.
* @throws CommandLineException
* If command line execution fails.
*/
protected void gitBranchDeleteForce(final String branchName) throws MojoFailureException, CommandLineException {