Skip to content

Commit 1913e1c

Browse files
committed
Support a file name field in license headers
1 parent 6789a1d commit 1913e1c

File tree

3 files changed

+57
-11
lines changed

3 files changed

+57
-11
lines changed

lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ public FormatterStep build() {
142142
throw new IllegalStateException(yearMode.toString());
143143
}
144144
return new Runtime(headerLazy.get(), delimiter, yearSeparator, updateYear, skipLinesMatching);
145-
}, step -> step::format);
145+
}, step -> FormatterFunc.needsFile(step::format));
146146
}
147147

148148
if (contentPattern == null) {
@@ -214,6 +214,8 @@ private static class Runtime implements Serializable {
214214
private final boolean updateYearWithLatest;
215215
private final boolean licenseHeaderWithRange;
216216

217+
private static final Pattern FILENAME_PATTERN = Pattern.compile("\\$FILE");
218+
217219
/** The license that we'd like enforced. */
218220
private Runtime(String licenseHeader, String delimiter, String yearSeparator, boolean updateYearWithLatest, @Nullable String skipLinesMatching) {
219221
if (delimiter.contains("\n")) {
@@ -266,9 +268,9 @@ private static Optional<String> getYearToken(String licenseHeader) {
266268
}
267269

268270
/** Formats the given string. */
269-
private String format(String raw) {
271+
private String format(String raw, File file) {
270272
if (skipLinesMatching == null) {
271-
return addOrUpdateLicenseHeader(raw);
273+
return addOrUpdateLicenseHeader(raw, file);
272274
} else {
273275
String[] lines = raw.split("\n");
274276
StringBuilder skippedLinesBuilder = new StringBuilder();
@@ -287,11 +289,11 @@ private String format(String raw) {
287289
remainingLinesBuilder.append(line).append('\n');
288290
}
289291
}
290-
return skippedLinesBuilder + addOrUpdateLicenseHeader(remainingLinesBuilder.toString());
292+
return skippedLinesBuilder + addOrUpdateLicenseHeader(remainingLinesBuilder.toString(), file);
291293
}
292294
}
293295

294-
private String addOrUpdateLicenseHeader(String raw) {
296+
private String addOrUpdateLicenseHeader(String raw, File file) {
295297
Matcher contentMatcher = delimiterPattern.matcher(raw);
296298
if (!contentMatcher.find()) {
297299
throw new IllegalArgumentException("Unable to find delimiter regex " + delimiterPattern);
@@ -305,13 +307,14 @@ private String addOrUpdateLicenseHeader(String raw) {
305307
return raw;
306308
} else {
307309
// otherwise we'll have to add the header
308-
return yearSepOrFull + content;
310+
return replaceFileName(yearSepOrFull, file) + content;
309311
}
310312
} else {
311313
// the yes year case is a bit harder
312314
int beforeYearIdx = raw.indexOf(beforeYear);
313315
int afterYearIdx = raw.indexOf(afterYear, beforeYearIdx + beforeYear.length() + 1);
314316

317+
String header;
315318
if (beforeYearIdx >= 0 && afterYearIdx >= 0 && afterYearIdx + afterYear.length() <= contentMatcher.start()) {
316319
// and also ends with exactly the right header, so it's easy to parse the existing year
317320
String existingYear = raw.substring(beforeYearIdx + beforeYear.length(), afterYearIdx);
@@ -323,12 +326,13 @@ private String addOrUpdateLicenseHeader(String raw) {
323326
return raw;
324327
}
325328
}
326-
return beforeYear + newYear + afterYear + content;
329+
header = beforeYear + newYear + afterYear;
327330
} else {
328331
String newYear = calculateYearBySearching(raw.substring(0, contentMatcher.start()));
329332
// at worst, we just say that it was made today
330-
return beforeYear + newYear + afterYear + content;
333+
header = beforeYear + newYear + afterYear;
331334
}
335+
return replaceFileName(header, file) + content;
332336
}
333337
}
334338
}
@@ -421,6 +425,10 @@ private String setLicenseHeaderYearsFromGitHistory(String raw, File file) throws
421425
return beforeYear + yearRange + afterYear + raw.substring(contentMatcher.start());
422426
}
423427

428+
private String replaceFileName(String header, File file) {
429+
return FILENAME_PATTERN.matcher(header).replaceAll(file.getName());
430+
}
431+
424432
private static String parseYear(String cmd, File file) throws IOException {
425433
String fullCmd = cmd + " -- " + file.getAbsolutePath();
426434
ProcessBuilder builder = new ProcessBuilder().directory(file.getParentFile());

testlib/src/main/java/com/diffplug/spotless/StepHarness.java

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,22 @@ public static StepHarness forFormatter(Formatter formatter) {
5757

5858
/** Asserts that the given element is transformed as expected, and that the result is idempotent. */
5959
public StepHarness test(String before, String after) {
60-
String actual = formatter.compute(LineEnding.toUnix(before), new File(""));
60+
return test(before, after, "");
61+
}
62+
63+
public StepHarness test(String before, String after, String fileName) {
64+
String actual = formatter.compute(LineEnding.toUnix(before), new File(fileName));
6165
assertEquals(after, actual, "Step application failed");
62-
return testUnaffected(after);
66+
return testUnaffected(after, fileName);
6367
}
6468

6569
/** Asserts that the given element is idempotent w.r.t the step under test. */
6670
public StepHarness testUnaffected(String idempotentElement) {
67-
String actual = formatter.compute(LineEnding.toUnix(idempotentElement), new File(""));
71+
return testUnaffected(idempotentElement, "");
72+
}
73+
74+
public StepHarness testUnaffected(String idempotentElement, String fileName) {
75+
String actual = formatter.compute(LineEnding.toUnix(idempotentElement), new File(fileName));
6876
assertEquals(idempotentElement, actual, "Step is not idempotent");
6977
return this;
7078
}

testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ class LicenseHeaderStepTest extends ResourceHarness {
3535
private static final String package_ = "package ";
3636
private static final String HEADER_WITH_$YEAR = "This is a fake license, $YEAR. ACME corp.";
3737
private static final String HEADER_WITH_RANGE_TO_$YEAR = "This is a fake license with range, 2009-$YEAR. ACME corp.";
38+
private static final String HEADER_WITH_$FILE = "This is a fake license, $FILE. ACME corp.";
39+
private static final String HEADER_WITH_$YEAR_$FILE = "This is a fake license, $FILE, $YEAR. ACME corp.";
3840

3941
@Test
4042
void parseExistingYear() throws Exception {
@@ -163,6 +165,16 @@ private String hasHeaderWithRangeAndWithYearTo(String toYear) throws IOException
163165
return hasHeaderYear(HEADER_WITH_RANGE_TO_$YEAR, toYear);
164166
}
165167

168+
private String hasHeaderFileName(String license, String fileName) throws IOException {
169+
return header(license).replace("$FILE", fileName) + getTestResource(FILE_NO_LICENSE);
170+
}
171+
172+
private String hasHeaderYearFileName(String license, String year, String fileName) throws IOException {
173+
return header(license)
174+
.replace("$YEAR", year)
175+
.replace("$FILE", fileName) + getTestResource(FILE_NO_LICENSE);
176+
}
177+
166178
private static String currentYear() {
167179
return String.valueOf(YearMonth.now().getYear());
168180
}
@@ -250,4 +262,22 @@ void should_preserve_year_for_license_with_address() throws Throwable {
250262
hasHeader(licenceWithAddress().replace("$YEAR", "2015").replace("FooBar Inc. All", "FooBar Inc. All")),
251263
hasHeader(licenceWithAddress().replace("$YEAR", "2015")));
252264
}
265+
266+
@Test
267+
void should_apply_license_containing_filename_token() throws Exception {
268+
FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$FILE), package_).build();
269+
StepHarness.forStep(step)
270+
.test(getTestResource(FILE_NO_LICENSE), hasHeaderFileName(HEADER_WITH_$FILE, "Test.java"), "Test.java");
271+
}
272+
273+
@Test
274+
void should_apply_license_containing_YEAR_filename_token() throws Exception {
275+
FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR_$FILE), package_).build();
276+
StepHarness.forStep(step)
277+
.test(
278+
getTestResource(FILE_NO_LICENSE),
279+
hasHeaderYearFileName(HEADER_WITH_$YEAR_$FILE, currentYear(), "Test.java"),
280+
"Test.java"
281+
);
282+
}
253283
}

0 commit comments

Comments
 (0)