-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathGitChangelogApi.java
843 lines (747 loc) · 29.9 KB
/
GitChangelogApi.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
package se.bjurr.gitchangelog.api;
import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.REF_HEAD;
import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.REF_MASTER;
import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.ZERO_COMMIT;
import static se.bjurr.gitchangelog.internal.git.GitRepoDataHelper.removeCommitsWithoutIssue;
import static se.bjurr.gitchangelog.internal.settings.Settings.fromFile;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.helper.StringHelpers;
import com.github.jknack.handlebars.io.FileTemplateLoader;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.eclipse.jgit.lib.ObjectId;
import se.bjurr.gitchangelog.api.exceptions.GitChangelogRepositoryException;
import se.bjurr.gitchangelog.api.helpers.Helpers;
import se.bjurr.gitchangelog.api.model.Changelog;
import se.bjurr.gitchangelog.api.model.Issue;
import se.bjurr.gitchangelog.internal.git.GitRepo;
import se.bjurr.gitchangelog.internal.git.GitRepoData;
import se.bjurr.gitchangelog.internal.git.RevisionBoundary;
import se.bjurr.gitchangelog.internal.git.model.GitCommit;
import se.bjurr.gitchangelog.internal.git.model.GitTag;
import se.bjurr.gitchangelog.internal.issues.IssueParser;
import se.bjurr.gitchangelog.internal.model.ParsedIssue;
import se.bjurr.gitchangelog.internal.model.Transformer;
import se.bjurr.gitchangelog.internal.semantic.SemanticVersion;
import se.bjurr.gitchangelog.internal.semantic.SemanticVersioning;
import se.bjurr.gitchangelog.internal.settings.Settings;
import se.bjurr.gitchangelog.internal.settings.SettingsIssue;
import se.bjurr.gitchangelog.internal.util.ResourceLoader;
@SuppressFBWarnings("PATH_TRAVERSAL_IN")
public final class GitChangelogApi {
private Settings settings;
private String templateContent;
private Handlebars handlebars;
private final AtomicInteger helperCounter = new AtomicInteger();
public static GitChangelogApi gitChangelogApiBuilder() {
return new GitChangelogApi();
}
private GitChangelogApi() {
this.settings = new Settings();
this.handlebars = new Handlebars();
this.handlebars.setPrettyPrint(true);
this.handlebars.registerHelpers(StringHelpers.class);
for (final Entry<String, Helper<?>> helper : Helpers.getAll().entrySet()) {
this.handlebars.registerHelper(helper.getKey(), helper.getValue());
}
}
private GitChangelogApi(final Settings settings) {
this.settings = settings;
}
/**
* Get the changelog as data object.
*
* @throws GitChangelogRepositoryException
*/
public Changelog getChangelog() throws GitChangelogRepositoryException {
return this.getChangelog(true);
}
private Changelog getChangelog(final boolean useIntegrations)
throws GitChangelogRepositoryException {
try (GitRepo gitRepo = new GitRepo(new File(this.settings.getFromRepo()))) {
return this.getChangelog(gitRepo, useIntegrations);
} catch (final IOException e) {
throw new GitChangelogRepositoryException("", e);
}
}
public Settings getSettings() {
return this.settings;
}
/**
* Get the changelog.
*
* @param prepend
* @throws GitChangelogRepositoryException
*/
public void render(final Writer writer, final boolean prepend)
throws GitChangelogRepositoryException {
final String templateString = this.getTemplateString(prepend);
if (this.settings.getTemplateBaseDir() != null) {
this.handlebars.with(
new FileTemplateLoader(
this.settings.getTemplateBaseDir(), this.settings.getTemplateSuffix()));
}
Template template;
try {
template = this.handlebars.compileInline(templateString);
} catch (final IOException e) {
throw new RuntimeException("Cannot render:\n\n" + templateString, e);
}
try {
final Map<String, Object> extendedVariables = this.settings.getExtendedVariables();
if (extendedVariables == null) {
throw new IllegalStateException("extendedVariables cannot be null");
}
final Changelog changelog = this.getChangelog(this.settings.isUseIntegrations());
final Context changelogContext = Context.newContext(changelog).combine(extendedVariables);
template.apply(changelogContext, writer);
} catch (final IOException e) {
// Should be impossible!
throw new GitChangelogRepositoryException("", e);
}
}
public String getTemplateString() {
return this.getTemplateString(false);
}
public String getTemplateString(final boolean prepend) {
if (this.templateContent != null) {
return this.templateContent;
}
final String resourceName =
prepend ? this.settings.getPrependTemplatePath() : this.settings.getTemplatePath();
return ResourceLoader.getResourceOrFile(resourceName, this.settings.getEncoding());
}
/** Get the changelog. */
@SuppressFBWarnings("PATH_TRAVERSAL_IN")
public String render() throws GitChangelogRepositoryException {
return this.render(false);
}
/**
* Get the changelog. There is a different default changelog when prepending which is why it can
* be supplied
*/
@SuppressFBWarnings("PATH_TRAVERSAL_IN")
public String render(final boolean prepend) throws GitChangelogRepositoryException {
final Writer writer = new StringWriter();
this.render(writer, prepend);
return writer.toString();
}
/**
* Write changelog to file.
*
* @throws GitChangelogRepositoryException
* @throws IOException When file cannot be written.
*/
public void toFile(final File file) throws GitChangelogRepositoryException, IOException {
final File parentFile = file.getParentFile();
if (parentFile != null) {
final boolean folderExists = parentFile.exists() || parentFile.mkdirs();
if (!folderExists) {
throw new RuntimeException("Folder " + parentFile.getAbsolutePath() + " cannot be created");
}
}
Files.write(file.toPath(), this.render().getBytes(this.settings.getEncoding()));
}
/** Prepend the changelog to the given file. */
public void prependToFile(final File file) throws GitChangelogRepositoryException, IOException {
if (!file.exists()) {
this.toFile(file);
return;
}
final byte[] bytesToPrepend = this.render(true).getBytes(this.settings.getEncoding());
final byte[] originalBytes = Files.readAllBytes(file.toPath());
try (final OutputStream outputStream = Files.newOutputStream(file.toPath())) {
outputStream.write(bytesToPrepend);
outputStream.write(originalBytes);
}
}
/**
* Get next semantic version. This requires version-pattern and major/minor/patch patterns to have
* been configured.
*/
public SemanticVersion getNextSemanticVersion() throws GitChangelogRepositoryException {
final GitChangelogApi api = GitChangelogApi.gitChangelogApiBuilder();
api.settings = this.settings.copy();
final boolean fromGiven = api.getSettings().getFromRevision().isPresent();
final SemanticVersion highestSemanticVersion = api.getHighestSemanticVersion();
if (!fromGiven) {
final Optional<String> tag = highestSemanticVersion.findTag();
if (tag.isPresent()) {
api.withFromRevision(tag.get());
}
}
final Changelog changelog = api.getChangelog(false);
api.getTagsAsStrings(changelog);
final List<String> commits = api.getCommitMessages(changelog);
final String majorVersionPattern = api.settings.getSemanticMajorPattern().orElse(null);
final String minorVersionPattern = api.settings.getSemanticMinorPattern();
final String patchVersionPattern = api.settings.getSemanticPatchPattern();
final SemanticVersioning semanticVersioning =
new SemanticVersioning(
commits, majorVersionPattern, minorVersionPattern, patchVersionPattern);
return semanticVersioning.getNextVersion(highestSemanticVersion);
}
public SemanticVersion getHighestSemanticVersion() throws GitChangelogRepositoryException {
final Changelog changelog = this.getChangelog(false);
final List<String> tags = this.getTagsAsStrings(changelog);
return SemanticVersioning.getHighestVersion(tags);
}
public SemanticVersion getCurrentSemanticVersion() throws Exception {
try (GitRepo gitRepo = new GitRepo(new File(this.settings.getFromRepo()))) {
final RevisionBoundary<ObjectId> from = this.getFrom(gitRepo, this.settings);
final RevisionBoundary<ObjectId> to = this.getTo(gitRepo, this.settings);
final List<String> tags =
gitRepo.getTags(from, to).stream()
.map(it -> Transformer.toReadableTagName(it, this.settings.getReadableTagName()))
.collect(Collectors.toList());
if (!tags.isEmpty()) {
return SemanticVersioning.getHighestVersion(tags);
}
} catch (final IOException e) {
throw new GitChangelogRepositoryException("", e);
}
return this.getNextSemanticVersion();
}
private List<String> getCommitMessages(final Changelog changelog) {
return changelog.getCommits().stream()
.map((it) -> it.getMessage())
.collect(Collectors.toList());
}
private List<String> getTagsAsStrings(final Changelog changelog) {
return changelog.getTags().stream().map((it) -> it.getName()).collect(Collectors.toList());
}
/** Will be used to determine next semantic version. */
public GitChangelogApi withSemanticMajorVersionPattern(final String major)
throws GitChangelogRepositoryException {
this.settings.setSemanticMajorPattern(major);
return this;
}
/** Will be used to determine next semantic version. */
public GitChangelogApi withSemanticMinorVersionPattern(final String minor)
throws GitChangelogRepositoryException {
this.settings.setSemanticMinorPattern(minor);
return this;
}
/** Will be used to determine next semantic version. */
public GitChangelogApi withSemanticPatchVersionPattern(final String patch)
throws GitChangelogRepositoryException {
this.settings.setSemanticPatchPattern(patch);
return this;
}
/**
* Registers (Javscript) Handlebars helper to use in template.
*
* @see https://github.com/jknack/handlebars.java/tree/master#with-plain-javascript
*/
public GitChangelogApi withHandlebarsHelper(final String javascriptHelper)
throws GitChangelogRepositoryException, IOException {
final int helperIndex = this.helperCounter.getAndIncrement();
this.handlebars.registerHelpers("helper-" + helperIndex, javascriptHelper);
return this;
}
/**
* Registers (Java) Handlebars helper to use in template.
*
* @return
* @see https://github.com/jknack/handlebars.java/tree/master#with-plain-javascript
*/
public GitChangelogApi withHandlebarsHelper(final String name, final Helper<?> helper)
throws GitChangelogRepositoryException, IOException {
this.handlebars.registerHelper(name, helper);
return this;
}
/**
* Custom issues are added to support any kind of issue management, perhaps something that is
* internal to your project. See {@link SettingsIssue}.
*/
public GitChangelogApi withCustomIssue( // NOPMD
final String name, final String pattern, final String link, final String title) {
this.settings.addCustomIssue(new SettingsIssue(name, pattern, link, title));
return this;
}
/** Format of dates, see {@link SimpleDateFormat}. */
public GitChangelogApi withDateFormat(final String dateFormat) {
this.settings.setDateFormat(dateFormat);
return this;
}
/**
* Extended variables is simply a key-value mapping of variables that are made available in the
* template. Is used, for example, by the Bitbucket plugin to supply some internal variables to
* the changelog context.
*/
public GitChangelogApi withExtendedVariables(final Map<String, Object> extendedVariables) {
this.settings.setExtendedVariables(extendedVariables);
return this;
}
/**
* Extended headers is simply a key-value mapping of headers that will be passed to REST request.
* Is used, for example, to bypass 2-factor authentication.
*/
public GitChangelogApi withExtendedHeaders(final Map<String, String> extendedHeaders) {
this.settings.setExtendedRestHeaders(extendedHeaders);
return this;
}
/**
* Include all commits from here. Any tag or branch name or commit hash. There is a constant
* pointing at the first commit here: reference{GitChangelogApiConstants#ZERO_COMMIT}.
*/
public GitChangelogApi withFromRevision(
final String revision, final InclusivenessStrategy strategy) {
this.settings.setFromRevision(revision);
this.settings.setFromRevisionStrategy(strategy);
return this;
}
/**
* Include all commits from here. Any tag or branch name or commit hash. There is a constant
* pointing at the first commit here: reference{GitChangelogApiConstants#ZERO_COMMIT}.
*/
public GitChangelogApi withFromRevision(final String fromRevision) {
return this.withFromRevision(fromRevision, InclusivenessStrategy.DEFAULT);
}
/**
* Include all commits from here. Any commit hash. There is a constant pointing at the first
* commit here: reference{GitChangelogApiConstants#ZERO_COMMIT}.
*
* @deprecated Use {@link #withFromRevision(String)} instead
*/
@Deprecated
public GitChangelogApi withFromCommit(final String fromCommit) {
return this.withFromRevision(fromCommit);
}
/**
* Include all commits from here. Any tag or branch name.
*
* @deprecated Use {@link #withFromRevision(String)} instead
*/
@Deprecated
public GitChangelogApi withFromRef(final String fromBranch) {
return this.withFromRevision(fromBranch);
}
/** Folder where repo lives. */
public GitChangelogApi withFromRepo(final String fromRepo) {
this.settings.setFromRepo(fromRepo);
return this;
}
public GitChangelogApi withFromRepo(final File fromRepo) {
this.settings.setFromRepo(fromRepo.getAbsolutePath());
return this;
}
/**
* URL pointing at GitHub API. When configured, the {@link Issue#getTitle()} will be populated
* with title from GitHub.<br>
* <code>https://api.github.com/repos/tomasbjerre/git-changelog-lib</code>
*/
public GitChangelogApi withGitHubApi(final String gitHubApi) {
this.settings.setGitHubApi(gitHubApi);
return this;
}
/** Pattern to recognize GitHub:s. <code>#([0-9]+)</code> */
public GitChangelogApi withGitHubIssuePattern(final String gitHubIssuePattern) {
this.settings.setGitHubIssuePattern(gitHubIssuePattern);
return this;
}
/**
* GitHub authentication token. Configure to avoid low rate limits imposed by GitHub in case you
* have a lot of issues and/or pull requests.<br>
* <br>
* You can get one like this:<br>
* <code>
* curl -u 'yourgithubuser' -d '{"note":"Git Changelog Lib"}' https://api.github.com/authorizations
* </code>
*/
public GitChangelogApi withGitHubToken(final String gitHubToken) {
this.settings.setGitHubToken(gitHubToken);
return this;
}
/** Pattern to recognize GitHub:s. <code>#([0-9]+)</code> */
public GitChangelogApi withGitLabIssuePattern(final String gitLabIssuePattern) {
this.settings.setGitLabIssuePattern(gitLabIssuePattern);
return this;
}
/**
* In this URL: <code>https://gitlab.com/tomas.bjerre85/violations-test/issues</code> it would be
* <code>violations-test</code>.
*/
public GitChangelogApi withGitLabProjectName(final String gitLabProjectName) {
this.settings.setGitLabProjectName(gitLabProjectName);
return this;
}
/** Example: https://gitlab.com/ */
public GitChangelogApi withGitLabServer(final String gitLabServer) {
this.settings.setGitLabServer(gitLabServer);
return this;
}
/** You can create it in the project settings page. */
public GitChangelogApi withGitLabToken(final String gitLabToken) {
this.settings.setGitLabToken(gitLabToken);
return this;
}
/**
* A regular expression that is evaluated on the commit message of each commit. If it matches, the
* commit will be filtered out and not included in the changelog.<br>
* <br>
* To ignore tags creted by Maven and Gradle release plugins, perhaps you want this: <br>
* <code>
* ^\[maven-release-plugin\].*|^\[Gradle Release Plugin\].*|^Merge.*
* </code><br>
* <br>
* Remember to escape it, if added to the json-file it would look like this:<br>
* <code>
* ^\\[maven-release-plugin\\].*|^\\[Gradle Release Plugin\\].*|^Merge.*
* </code>
*/
public GitChangelogApi withIgnoreCommitsWithMessage(final String ignoreCommitsIfMessageMatches) {
this.settings.setIgnoreCommitsIfMessageMatches(ignoreCommitsIfMessageMatches);
return this;
}
/**
* A date that is evaluated on the author date of each commit. If the commit is older than the
* point in time given, then it will be filtered out and not included in the changelog. <br>
* See {@link SimpleDateFormat}.
*/
public GitChangelogApi withIgnoreCommitsOlderThan(final Date ignoreCommitsIfOlderThan) {
this.settings.setIgnoreCommitsIfOlderThan(ignoreCommitsIfOlderThan);
return this;
}
/**
* If a commit cannot be mapped to any issue, it can be added to the virtual " {@link
* GitChangelogApi#withNoIssueName no issue}"-issue.<br>
* <br>
* True means that this issue will be created and populated.<br>
* <br>
* False means that it will not be created and commits that cannot be mapped to any issue will not
* be included in the changelog.
*/
public GitChangelogApi withIgnoreCommitsWithoutIssue(final boolean ignoreCommitsWithoutIssue) {
this.settings.setIgnoreCommitsWithoutIssue(ignoreCommitsWithoutIssue);
return this;
}
/**
* A regular expression that is evaluated on each tag. If it matches, the tag will be filtered out
* and not included in the changelog.
*/
public GitChangelogApi withIgnoreTagsIfNameMatches(final String ignoreTagsIfNameMatches) {
this.settings.setIgnoreTagsIfNameMatches(ignoreTagsIfNameMatches);
return this;
}
/**
* Pattern to recognize JIRA:s. <code>\b[a-zA-Z]([a-zA-Z]+)-([0-9]+)\b</code><br>
* <br>
* Or escaped if added to json-file:<br>
* <code>\\b[a-zA-Z]([a-zA-Z]+)-([0-9]+)\\b</code>
*/
public GitChangelogApi withJiraIssuePattern(final String jiraIssuePattern) {
this.settings.setJiraIssuePattern(jiraIssuePattern);
return this;
}
/** Authenticate to JIRA. */
public GitChangelogApi withJiraPassword(final String string) {
this.settings.setJiraPassword(string);
return this;
}
/** Authenticate to JIRA. */
public GitChangelogApi withJiraBasicAuthString(final String string) {
this.settings.setJiraToken(string);
return this;
}
/** Authenticate to JIRA. */
public GitChangelogApi withJiraBearer(final String string) {
this.settings.setJiraBearer(string);
return this;
}
/**
* URL pointing at your JIRA server. When configured, the {@link Issue#getTitle()} will be
* populated with title from JIRA.<br>
* <code>https://jiraserver/jira</code>
*/
public GitChangelogApi withJiraServer(final String jiraServer) {
this.settings.setJiraServer(jiraServer);
return this;
}
/** Authenticate to JIRA. */
public GitChangelogApi withJiraUsername(final String string) {
this.settings.setJiraUsername(string);
return this;
}
/** Pattern to recognize Redmine:s. <code>#([0-9]+)</code> */
public GitChangelogApi withRedmineIssuePattern(final String redmineIssuePattern) {
this.settings.setRedmineIssuePattern(redmineIssuePattern);
return this;
}
/** Authenticate to Redmine. */
public GitChangelogApi withRedminePassword(final String string) {
this.settings.setRedminePassword(string);
return this;
}
/** Authenticate to Redmine with API_KEY */
public GitChangelogApi withRedmineToken(final String string) {
this.settings.setRedmineToken(string);
return this;
}
/**
* URL pointing at your Redmine server. When configured, the {@link Issue#getTitle()} will be
* populated with title from Redmine.<br>
* <code>https://redmineserver/</code>
*/
public GitChangelogApi withRedmineServer(final String redmineServer) {
this.settings.setRedmineServer(redmineServer);
return this;
}
/** Authenticate to Redmine. */
public GitChangelogApi withRedmineUsername(final String string) {
this.settings.setRedmineUsername(string);
return this;
}
/**
* Additional Fields for Jira. When configured, we will return from Jira the results of these
* fields, if they exist.<br>
* <code>"customfield_10000"</code><br>
* <br>
* <code>
* /rest/api/2/issue/JIR-1234?fields=parent,summary,issuetype,labels,description,issuelinks,customfield_10000
* </code>
*/
public GitChangelogApi withJiraIssueAdditionalField(final String field) {
this.settings.addJiraIssueAdditionalField(field);
return this;
}
/**
* This is a "virtual issue" that is added to {@link Changelog#getIssues()}. It contains all
* commits that has no issue in the commit comment. This could be used as a "wall of shame"
* listing commiters that did not tag there commits with an issue.
*/
public GitChangelogApi withNoIssueName(final String noIssueName) {
this.settings.setNoIssueName(noIssueName);
return this;
}
/**
* Your tags may look something like <code>git-changelog-maven-plugin-1.6</code>. But in the
* changelog you just want <code>1.6</code>. With this regular expression, the numbering can be
* extracted from the tag name.<br>
* <code>/([^/]+?)$</code>
*/
public GitChangelogApi withReadableTagName(final String readableTagName) {
this.settings.setReadableTagName(readableTagName);
return this;
}
/**
* If true, the changelog will not contain the issue in the commit comment. If your changelog is
* grouped by issues, you may want this to be true. If not grouped by issue, perhaps false.
*/
public GitChangelogApi withRemoveIssueFromMessageArgument(final boolean removeIssueFromMessage) {
this.settings.setRemoveIssueFromMessage(removeIssueFromMessage);
return this;
}
/** {@link Settings}. */
public GitChangelogApi withSettings(final URL url) {
this.settings = fromFile(url);
return this;
}
/** Use string as template. {@link #withTemplatePath}. */
public GitChangelogApi withTemplateContent(final String templateContent) {
this.templateContent = templateContent;
return this;
}
/**
* Path of template-file to use. It is a Mustache (https://mustache.github.io/) template. Supplied
* with the context of {@link Changelog}.
*/
public GitChangelogApi withTemplatePath(final String templatePath) {
this.settings.setTemplatePath(templatePath);
return this;
}
/**
* Path of template-file to use when prepending. It is a Mustache (https://mustache.github.io/)
* template. Supplied with the context of {@link Changelog}.
*/
public GitChangelogApi withPrependTemplatePath(final String templatePath) {
this.settings.setPrependTemplatePath(templatePath);
return this;
}
/** Path to the base directory for template partial files */
public GitChangelogApi withTemplateBaseDir(final String templateBaseDir) {
this.settings.setTemplateBaseDir(templateBaseDir);
return this;
}
/** Suffix of the template partial files */
public GitChangelogApi withTemplateSuffix(final String templateSuffix) {
this.settings.setTemplateSuffix(templateSuffix);
return this;
}
public GitChangelogApi withUseIntegrations(final boolean useIntegrations) {
this.settings.setUseIntegrations(useIntegrations);
return this;
}
/**
* When date of commits are translated to a string, this timezone is used.<br>
* <code>UTC</code>
*/
public GitChangelogApi withTimeZone(final String timeZone) {
this.settings.setTimeZone(timeZone);
return this;
}
/**
* Include all commits to this revision. Any tag or branch name or commit hash. There is a
* constant for master here: reference{GitChangelogApiConstants#REF_MASTER}.
*/
public GitChangelogApi withToRevision(
final String revision, final InclusivenessStrategy strategy) {
this.settings.setToRevision(revision);
this.settings.setToRevisionStrategy(strategy);
return this;
}
/**
* Include all commits to this revision. Any tag or branch name or commit hash. There is a
* constant for master here: reference{GitChangelogApiConstants#REF_MASTER}.
*/
public GitChangelogApi withToRevision(final String toRevision) {
return this.withToRevision(toRevision, InclusivenessStrategy.DEFAULT);
}
/**
* Include all commits to here. Any commit hash.
*
* @deprecated Use {@link #withToRevision(String)} instead
*/
@Deprecated
public GitChangelogApi withToCommit(final String toCommit) {
return this.withToRevision(toCommit);
}
/**
* Include all commits to this reference. Any tag or branch name. There is a constant for master
* here: reference{GitChangelogApiConstants#REF_MASTER}.
*
* @deprecated Use {@link #withToRevision(String)} instead
*/
@Deprecated
public GitChangelogApi withToRef(final String toBranch) {
return this.withToRevision(toBranch);
}
/**
* Filter commits using the provided path filters, analogous to using the cli command git log --
* git log <path>...
*
* @param pathFilters the path filters to be used for filtering.
*/
public GitChangelogApi withPathFilters(final String... pathFilters) {
this.settings.setPathFilters(Arrays.asList(pathFilters));
return this;
}
/**
* Some commits may not be included in any tag. Commits that not released yet may not be tagged.
* This is a "virtual tag", added to {@link Changelog#getTags()}, that includes those commits. A
* fitting value may be "Next release".
*/
public GitChangelogApi withUntaggedName(final String untaggedName) {
this.settings.setUntaggedName(untaggedName);
return this;
}
private Changelog getChangelog(final GitRepo gitRepo, final boolean useIntegrations)
throws GitChangelogRepositoryException {
gitRepo.setPathFilters(this.settings.getPathFilters());
final RevisionBoundary<ObjectId> fromId = this.getFrom(gitRepo, this.settings);
final RevisionBoundary<ObjectId> toId = this.getTo(gitRepo, this.settings);
GitRepoData gitRepoData =
gitRepo.getGitRepoData(
fromId,
toId,
this.settings.getUntaggedName(),
this.settings.getIgnoreTagsIfNameMatches());
if (!this.settings.getGitHubApi().isPresent()) {
this.settings.setGitHubApi(gitRepoData.findGitHubApi().orElse(null));
}
if (!this.settings.getGitLabServer().isPresent()) {
this.settings.setGitLabServer(gitRepoData.findGitLabServer().orElse(null));
this.settings.setGitLabProjectName(gitRepoData.findOwnerName().orElse(null));
}
List<GitCommit> diff = gitRepoData.getGitCommits();
final List<ParsedIssue> issues =
new IssueParser(this.settings, diff).parseForIssues(useIntegrations);
if (this.settings.ignoreCommitsWithoutIssue()) {
gitRepoData = removeCommitsWithoutIssue(issues, gitRepoData);
diff = gitRepoData.getGitCommits();
}
final List<GitTag> tags = gitRepoData.getGitTags();
final Transformer transformer = new Transformer(this.settings);
return new Changelog( //
transformer.toCommits(diff), //
transformer.toTags(tags, issues), //
transformer.toAuthors(diff), //
transformer.toIssues(issues), //
transformer.toIssueTypes(issues), //
gitRepoData.findOwnerName().orElse(null), //
gitRepoData.findRepoName().orElse(null),
gitRepoData.getUrlPartsList());
}
private RevisionBoundary<ObjectId> getTo(final GitRepo gitRepo, final Settings settings)
throws GitChangelogRepositoryException {
final Optional<RevisionBoundary<ObjectId>> toIdOpt =
this.getId(gitRepo, settings.getToRevision(), settings.getToRevisionStrategy());
if (toIdOpt.isPresent()) {
return toIdOpt.get();
} else {
final Optional<ObjectId> headOpt = gitRepo.findRef(REF_HEAD);
if (headOpt.isPresent()) {
return new RevisionBoundary<ObjectId>(headOpt.get(), InclusivenessStrategy.INCLUSIVE);
} else {
return new RevisionBoundary<ObjectId>(
gitRepo.getRef(REF_MASTER), InclusivenessStrategy.INCLUSIVE);
}
}
}
private RevisionBoundary<ObjectId> getFrom(final GitRepo gitRepo, final Settings settings)
throws GitChangelogRepositoryException {
return this.getId(gitRepo, settings.getFromRevision(), settings.getFromRevisionStrategy()) //
.orElse(
new RevisionBoundary<ObjectId>(
gitRepo.getCommit(ZERO_COMMIT), InclusivenessStrategy.INCLUSIVE));
}
private Optional<RevisionBoundary<ObjectId>> getId(
final GitRepo gitRepo,
final Optional<String> revision,
final InclusivenessStrategy inclusivenessStrategy)
throws GitChangelogRepositoryException {
if (!revision.isPresent()) {
return Optional.empty();
}
return gitRepo.findObjectId(revision.get(), inclusivenessStrategy);
}
public GitChangelogApi withJiraEnabled(final boolean b) {
this.settings.setJiraEnabled(b);
return this;
}
public GitChangelogApi withGitLabEnabled(final boolean b) {
this.settings.setGitLabEnabled(b);
return this;
}
public GitChangelogApi withGitHubEnabled(final boolean b) {
this.settings.setGitHubEnabled(b);
return this;
}
public GitChangelogApi withRedmineEnabled(final boolean b) {
this.settings.setRedmineEnabled(b);
return this;
}
public GitChangelogApi withEncoding(final Charset encoding) {
this.settings.setEncoding(encoding);
return this;
}
}