├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitattributes ├── .travis.yml ├── LICENSE ├── src ├── main │ └── groovy │ │ └── org │ │ └── cadixdev │ │ └── gradle │ │ └── licenser │ │ ├── header │ │ ├── HeaderFormat.java │ │ ├── PreparedHeader.java │ │ ├── HeaderFormatRegistry.groovy │ │ ├── HeaderStyle.groovy │ │ ├── CommentHeaderFormat.groovy │ │ ├── Header.groovy │ │ └── PreparedCommentHeader.groovy │ │ ├── LicenseViolationException.java │ │ ├── util │ │ ├── CaseInsensitiveMap.groovy │ │ └── HeaderHelper.java │ │ ├── LicenseTaskProperties.groovy │ │ ├── tasks │ │ ├── LicenseCheck.groovy │ │ ├── LicenseUpdate.groovy │ │ └── LicenseTask.groovy │ │ ├── LicenseProperties.groovy │ │ ├── Licenser.groovy │ │ └── LicenseExtension.groovy ├── test │ └── groovy │ │ └── org │ │ └── cadixdev │ │ └── gradle │ │ └── licenser │ │ ├── header │ │ └── HeaderFormatRegistryTest.groovy │ │ ├── LicenserPluginTest.groovy │ │ ├── LicenseExtensionTest.groovy │ │ └── util │ │ └── HeaderHelperTest.groovy └── functionalTest │ └── groovy │ └── org │ └── cadixdev │ └── gradle │ └── licenser │ └── LicenserPluginFunctionalTest.groovy ├── gradlew.bat ├── .gitignore ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'licenser' 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CadixDev/licenser/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | *.bat text eol=crlf 3 | gradlew text eol=lf 4 | *.sh text eol=lf 5 | 6 | ################# 7 | ## Java 8 | ################# 9 | *.java text 10 | *.java diff=java 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | dist: trusty 3 | 4 | language: groovy 5 | jdk: 6 | - openjdk8 7 | - oraclejdk8 8 | 9 | install: true 10 | script: ./gradlew build 11 | 12 | notifications: 13 | email: false 14 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015, Minecrell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/HeaderFormat.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header; 26 | 27 | public interface HeaderFormat { 28 | 29 | String getName(); 30 | 31 | PreparedHeader prepare(Header header, String text); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/PreparedHeader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header; 26 | 27 | import java.io.File; 28 | import java.io.IOException; 29 | 30 | public interface PreparedHeader { 31 | 32 | boolean check(File file, String charset, boolean skipExistingHeaders) throws IOException; 33 | 34 | boolean update(File file, String charset, String lineSeparator, boolean skipExistingHeaders, Runnable callback) throws IOException; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/test/groovy/org/cadixdev/gradle/licenser/header/HeaderFormatRegistryTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header 26 | 27 | import spock.lang.Specification 28 | 29 | class HeaderFormatRegistryTest extends Specification { 30 | def "registry contains default properties"() { 31 | when: 32 | def registry = new HeaderFormatRegistry() 33 | 34 | then: 35 | registry.keySet().containsAll(["java", "js", "kt", "groovy", "yml", "xml", "html"]) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/LicenseViolationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser; 26 | 27 | import org.gradle.api.GradleException; 28 | 29 | /** 30 | * Thrown if a license violation was found. 31 | */ 32 | public class LicenseViolationException extends GradleException { 33 | 34 | /** 35 | * Constructs a new {@link LicenseViolationException} with the specified 36 | * message. 37 | * 38 | * @param message The exception message 39 | */ 40 | public LicenseViolationException(String message) { 41 | super(message); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/groovy/org/cadixdev/gradle/licenser/LicenserPluginTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import org.gradle.testfixtures.ProjectBuilder 28 | import spock.lang.Specification 29 | 30 | class LicenserPluginTest extends Specification { 31 | def "plugin registers tasks"() { 32 | given: 33 | def project = ProjectBuilder.builder().build() 34 | 35 | when: 36 | project.plugins.apply("org.cadixdev.licenser") 37 | 38 | then: 39 | ["licenseCheck", "licenseFormat", "checkLicenses", "updateLicenses"].each { 40 | assert project.tasks.findByName(it) != null 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/groovy/org/cadixdev/gradle/licenser/LicenseExtensionTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import org.cadixdev.gradle.licenser.header.HeaderStyle 28 | import org.gradle.testfixtures.ProjectBuilder 29 | import spock.lang.Specification 30 | 31 | class LicenseExtensionTest extends Specification { 32 | def "style closure registers header style"() { 33 | given: 34 | def project = ProjectBuilder.builder().build() 35 | def licenseExtension = new LicenseExtension(project.objects, project) 36 | 37 | when: 38 | licenseExtension.style { 39 | ext = 'BLOCK_COMMENT' 40 | } 41 | 42 | then: 43 | licenseExtension.style.getProperty("ext") == HeaderStyle.BLOCK_COMMENT.format 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/util/CaseInsensitiveMap.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.util 26 | 27 | class CaseInsensitiveMap { 28 | @Delegate(includes = ["size", "isEmpty", "containsValue", "clear", "keySet", "values", "entrySet", "equals", "hashCode"]) 29 | private final Map map = new HashMap<>(); 30 | 31 | private static String normalizeKey(Object key) { 32 | return key.toString().toLowerCase(Locale.ROOT) 33 | } 34 | 35 | boolean containsKey(Object key) { 36 | return map.containsKey(normalizeKey(key)) 37 | } 38 | 39 | V get(Object key) { 40 | return map.get(normalizeKey(key)) 41 | } 42 | 43 | V put(String key, V value) { 44 | return map.put(normalizeKey(key), value) 45 | } 46 | 47 | V remove(Object key) { 48 | return map.remove(normalizeKey(key)) 49 | } 50 | 51 | void putAll(Map m) { 52 | m.each this.&put 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/HeaderFormatRegistry.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header 26 | 27 | import org.cadixdev.gradle.licenser.util.CaseInsensitiveMap 28 | 29 | class HeaderFormatRegistry extends CaseInsensitiveMap { 30 | 31 | HeaderFormatRegistry() { 32 | for (HeaderStyle style : HeaderStyle.values()) { 33 | style.register(this) 34 | } 35 | } 36 | 37 | // Note: This is Groovy magic 38 | 39 | HeaderFormat put(String key, HeaderStyle value) { 40 | return put(key, value.format) 41 | } 42 | 43 | HeaderFormat put(String key, String value) { 44 | return put(key, value as HeaderStyle) 45 | } 46 | 47 | HeaderFormat putAt(String key, HeaderStyle value) { 48 | return put(key, value) 49 | } 50 | 51 | HeaderFormat putAt(String key, String value) { 52 | return put(key, value) 53 | } 54 | 55 | @Override 56 | Object getProperty(String key) { 57 | return get(key) 58 | } 59 | 60 | @Override 61 | void setProperty(String key, Object value) { 62 | put(key, value) 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/LicenseTaskProperties.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import groovy.transform.PackageScope 28 | import org.gradle.api.Incubating 29 | import org.gradle.api.file.ConfigurableFileCollection 30 | import org.gradle.api.model.ObjectFactory 31 | import org.gradle.api.provider.Property 32 | import org.gradle.api.resources.TextResourceFactory 33 | import org.gradle.api.tasks.util.PatternSet 34 | 35 | /** 36 | * Represents a custom license task that operates on a number of files 37 | * defined by {@link #files}. 38 | */ 39 | @Incubating 40 | class LicenseTaskProperties extends LicenseProperties { 41 | 42 | /** 43 | * The name of this custom task. This is set automatically in the container. 44 | */ 45 | final String name 46 | 47 | /** 48 | * The set of files to operate on. 49 | */ 50 | final ConfigurableFileCollection files 51 | 52 | @PackageScope 53 | LicenseTaskProperties(PatternSet filter, String name, ObjectFactory objects, TextResourceFactory text, Property charset) { 54 | super(filter, objects, text, charset) 55 | this.name = name 56 | this.files = objects.fileCollection() 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/HeaderStyle.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header 26 | 27 | import javax.annotation.Nullable 28 | import java.util.regex.Pattern 29 | 30 | enum HeaderStyle { 31 | BLOCK_COMMENT(~/^\s*\/\*(?:[^*].*)?$/, ~/\*\/\s*(.*?)$/, null, '/*', ' *', ' */', 32 | 'java', 'groovy', 'scala', 'kt', 'kts', 'gradle', 'css', 'js'), 33 | JAVADOC(~/^\s*\/\*\*(?:[^*].*)?$/, ~/\*\/\s*(.*?)$/, null, '/**', ' *', ' */'), 34 | HASH(~/^\s*#/, null, ~/^\s*#!/, '#', '#', '#', 'properties', 'yml', 'yaml', 'sh'), 35 | XML(~/^\s*\s*(.*?)$/, ~/^\s*<(?:\?xml .*\?|!DOCTYPE .*)>\s*$/, '', 36 | 'xml', 'xsd', 'xsl', 'fxml', 'dtd', 'html', 'xhtml'), 37 | DOUBLE_SLASH(~/^\s*\/\//, null, null, '//', '//', '//') 38 | 39 | final CommentHeaderFormat format 40 | private final String[] extensions 41 | 42 | HeaderStyle(Pattern start, @Nullable Pattern end, @Nullable Pattern skipLine, 43 | String firstLine, String prefix, String lastLine, String... extensions) { 44 | this.format = new CommentHeaderFormat(this.name(), start, end, skipLine, firstLine, prefix, lastLine) 45 | this.extensions = extensions 46 | } 47 | 48 | void register(HeaderFormatRegistry registry) { 49 | extensions.each { registry[it] = this } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/CommentHeaderFormat.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header 26 | 27 | import groovy.transform.EqualsAndHashCode 28 | import groovy.transform.PackageScope 29 | import org.cadixdev.gradle.licenser.util.HeaderHelper 30 | 31 | import javax.annotation.Nullable 32 | import java.util.regex.Pattern 33 | 34 | @EqualsAndHashCode 35 | class CommentHeaderFormat implements HeaderFormat { 36 | 37 | final String name 38 | 39 | final Pattern start 40 | @Nullable 41 | final Pattern end 42 | @Nullable 43 | final Pattern skipLine 44 | 45 | final String firstLine 46 | final String prefix 47 | final String lastLine 48 | 49 | @PackageScope 50 | CommentHeaderFormat(String name, Pattern start, @Nullable Pattern end, @Nullable Pattern skipLine, 51 | String firstLine, String prefix, String lastLine) { 52 | this.name = name 53 | this.start = start 54 | this.end = end 55 | this.skipLine = skipLine 56 | this.firstLine = firstLine 57 | this.prefix = prefix 58 | this.lastLine = lastLine 59 | } 60 | 61 | protected List format(String text) { 62 | ensureAbsent(text, firstLine) 63 | ensureAbsent(text, lastLine) 64 | 65 | List result = [firstLine] 66 | 67 | text.eachLine { 68 | result << HeaderHelper.stripTrailingIndent("$prefix $it") 69 | } 70 | 71 | result << lastLine 72 | return result 73 | } 74 | 75 | private static void ensureAbsent(String s, String search) { 76 | if (s.contains(search)) { 77 | throw new IllegalArgumentException("Header contains unsupported characters $search") 78 | } 79 | } 80 | 81 | @Override 82 | PreparedHeader prepare(Header header, String text) { 83 | return new PreparedCommentHeader(header, this, format(text)) 84 | } 85 | 86 | @Override 87 | String toString() { 88 | return name 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/tasks/LicenseCheck.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.tasks 26 | 27 | import org.cadixdev.gradle.licenser.LicenseViolationException 28 | import org.gradle.api.file.FileVisitDetails 29 | import org.gradle.api.provider.Property 30 | import org.gradle.api.tasks.Input 31 | import org.gradle.api.tasks.TaskAction 32 | import org.gradle.api.tasks.VerificationTask 33 | 34 | abstract class LicenseCheck extends LicenseTask { 35 | 36 | @Input 37 | abstract Property getIgnoreFailures() 38 | 39 | void ignoreFailures(final boolean ignoreFailures) { 40 | this.ignoreFailures.set(ignoreFailures) 41 | } 42 | 43 | @TaskAction 44 | void checkFiles() { 45 | didWork = false 46 | 47 | def headers = this.headers.get() 48 | if (headers.size() == 1 && headers.first().text.empty) { 49 | return 50 | } 51 | 52 | Set violations = [] 53 | def charset = charset.get() 54 | def skipExistingHeaders = skipExistingHeaders.get() 55 | matchingFiles.visit { FileVisitDetails details -> 56 | if (!details.directory) { 57 | didWork = true 58 | def file = details.file 59 | 60 | try { 61 | def prepared = prepareMatchingHeader(details, file) 62 | if (prepared == null) { 63 | return 64 | } 65 | 66 | if (!prepared.check(file, charset, skipExistingHeaders)) { 67 | violations.add(file) 68 | } 69 | } catch (Exception e) { 70 | violations.add(file) 71 | logger.error("Failed to check license header of ${getSimplifiedPath(file)}", e) 72 | } 73 | } 74 | } 75 | 76 | if (!violations.isEmpty()) { 77 | String violators = violations.collect { getSimplifiedPath(it) }.join(', ') 78 | 79 | final def message = "License violations were found: $violators" 80 | if (this.ignoreFailures.get()) { 81 | logger.warn(message) 82 | } else { 83 | throw new LicenseViolationException(message) 84 | } 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/Header.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header 26 | 27 | import org.cadixdev.gradle.licenser.util.HeaderHelper 28 | import org.gradle.api.file.FileTreeElement 29 | import org.gradle.api.provider.ListProperty 30 | import org.gradle.api.provider.Provider 31 | import org.gradle.api.specs.Spec 32 | import org.gradle.api.specs.Specs 33 | import org.gradle.api.tasks.Input 34 | import org.gradle.api.tasks.Internal 35 | import org.gradle.api.tasks.util.PatternSet 36 | 37 | class Header { 38 | 39 | @Internal 40 | final HeaderFormatRegistry registry 41 | 42 | @Input 43 | final Provider> keywords 44 | 45 | private final Provider loader 46 | 47 | @Input 48 | final Spec filter 49 | 50 | @Input 51 | final Provider newLine 52 | 53 | private String text 54 | 55 | private final Map formatted = new HashMap<>() 56 | 57 | Header(HeaderFormatRegistry registry, ListProperty keywords, Provider loader, PatternSet filter, Provider newLine) { 58 | this.registry = registry 59 | this.keywords = keywords.map { it*.toLowerCase() } 60 | this.loader = loader 61 | this.filter = filter?.asSpec ?: Specs.satisfyAll() 62 | this.newLine = newLine 63 | } 64 | 65 | @Input 66 | String getText() { 67 | if (this.text == null) { 68 | this.text = this.loader.get() 69 | if (!containsKeyword(this.text)) { 70 | throw new IllegalArgumentException("Header does not contain any of the required keywords: $keywords") 71 | } 72 | } 73 | 74 | return this.text 75 | } 76 | 77 | boolean containsKeyword(String s) { 78 | s = s.toLowerCase() 79 | return keywords.get().any(s.&contains) 80 | } 81 | 82 | PreparedHeader prepare(HeaderFormat format) { 83 | if (format == null) { 84 | return null 85 | } 86 | 87 | PreparedHeader result = formatted[format] 88 | if (result == null) { 89 | result = format.prepare(this, getText()) 90 | formatted[format] = result 91 | } 92 | return result 93 | } 94 | 95 | PreparedHeader prepare(String path) { 96 | return prepare(registry[HeaderHelper.getExtension(path)]) 97 | } 98 | 99 | PreparedHeader prepare(File file) { 100 | return prepare(file.path) 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/LicenseProperties.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import org.gradle.api.model.ObjectFactory 28 | import org.gradle.api.provider.Property 29 | import org.gradle.api.resources.TextResource 30 | import org.gradle.api.resources.TextResourceFactory 31 | import org.gradle.api.tasks.util.PatternFilterable 32 | import org.gradle.api.tasks.util.PatternSet 33 | 34 | import javax.inject.Inject 35 | 36 | /** 37 | * Specifies how to format the license header of a subset of the files, defined 38 | * by the {@link #filter}. 39 | */ 40 | class LicenseProperties implements PatternFilterable { 41 | 42 | /** 43 | * The filter to apply to the source files. 44 | * By default this only includes a few excludes for binary files or files 45 | * without standardized comment formats. 46 | */ 47 | @Delegate 48 | PatternFilterable filter 49 | 50 | /** 51 | * The path to the file containing the license header. 52 | * By default this is the {@code LICENSE} file in the project directory. 53 | */ 54 | final Property header 55 | 56 | /** 57 | * Whether to insert an empty line after the license header. 58 | * By default this is {@code true}. 59 | */ 60 | final Property newLine 61 | 62 | protected final Property charset 63 | private final TextResourceFactory resources 64 | 65 | @Inject 66 | LicenseProperties(PatternSet filter, ObjectFactory objects, TextResourceFactory resources) { 67 | this.filter = filter 68 | this.charset = objects.property(String) 69 | this.header = objects.property(TextResource) 70 | this.newLine = objects.property(Boolean) 71 | this.resources = resources 72 | } 73 | 74 | @Inject 75 | LicenseProperties(PatternSet filter, ObjectFactory objects, TextResourceFactory resources, Property charset) { 76 | this(filter, objects, resources) 77 | this.charset.set(charset) 78 | } 79 | 80 | /** 81 | * @see #header 82 | * @param header the new header 83 | */ 84 | void header(final TextResource header) { 85 | this.header.set(header) 86 | } 87 | 88 | // kotlin + from other plugins 89 | /** 90 | * Set the header to the contents of a file. 91 | * 92 | * @param header anything accepted in {@link org.gradle.api.Project#file(Object)} 93 | * @see #header 94 | */ 95 | void header(final Object header) { 96 | this.header.set(this.charset.map { this.resources.fromFile(header, it) }) 97 | } 98 | 99 | // groovy 100 | void setHeader(final File header) { 101 | this.header.set(this.charset.map { this.resources.fromFile(header, it) }) 102 | } 103 | 104 | void newLine(final Boolean newLine) { 105 | this.newLine.set(newLine) 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/tasks/LicenseUpdate.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.tasks 26 | 27 | import org.gradle.api.GradleException 28 | import org.gradle.api.file.FileVisitDetails 29 | import org.gradle.api.provider.Property 30 | import org.gradle.api.tasks.Input 31 | import org.gradle.api.tasks.TaskAction 32 | 33 | import javax.annotation.Nullable 34 | 35 | abstract class LicenseUpdate extends LicenseTask { 36 | 37 | /** 38 | * Get the line separator to use when writing license files. 39 | * 40 | * @return the file line separator 41 | */ 42 | @Input 43 | abstract Property getLineEnding() 44 | 45 | void lineEnding(final @Nullable String lineEnding) { 46 | this.lineEnding.set(lineEnding) 47 | } 48 | 49 | @TaskAction 50 | void formatFiles() { 51 | didWork = false 52 | 53 | this.headers.finalizeValue() 54 | def headers = this.headers.get() 55 | if (headers.size() == 1 && headers.first().text.empty) { 56 | return 57 | } 58 | 59 | // Backup files before modifying them 60 | def original = new File(temporaryDir, 'original') 61 | def updated = 0 62 | def failed = false 63 | 64 | matchingFiles.visit { FileVisitDetails details -> 65 | if (!details.directory) { 66 | def file = details.file 67 | 68 | try { 69 | def prepared = prepareMatchingHeader(details, file) 70 | if (prepared == null) { 71 | return 72 | } 73 | 74 | if (prepared.update(file, charset.get(), lineEnding.get(), skipExistingHeaders.get(), { 75 | def backup = details.relativePath.getFile(original) 76 | if (backup.exists()) { 77 | assert backup.delete(), "Failed to delete backup file: $backup" 78 | } else { 79 | backup.parentFile.mkdirs() 80 | } 81 | 82 | assert file.renameTo(backup), "Failed to backup file $file to $backup" 83 | assert file.createNewFile(), "Failed to recreate source file: $file" 84 | })) { 85 | updated++ 86 | logger.lifecycle('Updating license header in {}', getSimplifiedPath(file)) 87 | didWork = true 88 | } 89 | } catch (Exception e) { 90 | logger.error("Failed to update license header in ${getSimplifiedPath(file)}", e) 91 | failed = true 92 | } 93 | } 94 | } 95 | 96 | if (updated > 0) { 97 | logger.lifecycle('{} license header(s) updated. A backup of the original file(s) was created in {}', updated, getSimplifiedPath(original)) 98 | } 99 | 100 | if (failed) { 101 | throw new GradleException('One or more license headers could not be successfully updated') 102 | } 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/tasks/LicenseTask.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.tasks 26 | 27 | import org.cadixdev.gradle.licenser.header.Header 28 | import org.cadixdev.gradle.licenser.header.PreparedHeader 29 | import org.gradle.api.Action 30 | import org.gradle.api.DefaultTask 31 | import org.gradle.api.file.FileCollection 32 | import org.gradle.api.file.FileTree 33 | import org.gradle.api.file.FileTreeElement 34 | import org.gradle.api.file.ProjectLayout 35 | import org.gradle.api.provider.ListProperty 36 | import org.gradle.api.provider.Property 37 | import org.gradle.api.tasks.IgnoreEmptyDirectories; 38 | import org.gradle.api.tasks.Input 39 | import org.gradle.api.tasks.InputFiles 40 | import org.gradle.api.tasks.Internal 41 | import org.gradle.api.tasks.Nested 42 | import org.gradle.api.tasks.PathSensitive 43 | import org.gradle.api.tasks.PathSensitivity 44 | import org.gradle.api.tasks.SkipWhenEmpty 45 | import org.gradle.api.tasks.util.PatternFilterable 46 | 47 | import javax.inject.Inject 48 | 49 | abstract class LicenseTask extends DefaultTask { 50 | 51 | @Nested 52 | abstract ListProperty
getHeaders() 53 | 54 | @Internal 55 | FileCollection files 56 | 57 | @Input 58 | PatternFilterable filter 59 | 60 | @Input 61 | abstract Property getCharset() 62 | 63 | @Input 64 | abstract Property getSkipExistingHeaders() 65 | 66 | @InputFiles 67 | @SkipWhenEmpty 68 | @IgnoreEmptyDirectories 69 | @PathSensitive(PathSensitivity.ABSOLUTE) 70 | FileTree getMatchingFiles() { 71 | def tree = this.files.asFileTree 72 | return filter != null ? tree.matching(filter) : tree 73 | } 74 | 75 | void headers(Header... headers) { 76 | this.headers.addAll(headers) 77 | } 78 | 79 | void headers(final Action> headers) { 80 | headers.execute(this.headers) 81 | } 82 | 83 | void charset(final String charset) { 84 | this.charset.set(charset) 85 | } 86 | 87 | void skipExistingHeaders(final Boolean skip) { 88 | this.skipExistingHeaders.set(skip) 89 | } 90 | 91 | @Inject 92 | protected abstract ProjectLayout getLayout() 93 | 94 | protected PreparedHeader prepareMatchingHeader(FileTreeElement element, File file) { 95 | def header = getMatchingHeader(element) 96 | if (header == null) { 97 | logger.info("No matching header found for {}", getSimplifiedPath(file)) 98 | return null 99 | } 100 | 101 | if (header.text.empty) { 102 | return null 103 | } 104 | 105 | def prepared = header.prepare(file) 106 | if (prepared == null) { 107 | logger.info("No matching header format found for {}", getSimplifiedPath(file)) 108 | return null 109 | } 110 | 111 | return prepared 112 | } 113 | 114 | protected Header getMatchingHeader(FileTreeElement element) { 115 | return getHeaders().get().find { it.filter.isSatisfiedBy(element) } 116 | } 117 | 118 | private String projectPath 119 | 120 | protected String getSimplifiedPath(File file) { 121 | if (projectPath == null) { 122 | projectPath = layout.projectDirectory.asFile.canonicalPath 123 | } 124 | 125 | def path = file.canonicalPath 126 | return path.startsWith(projectPath) ? path[projectPath.length()+1..-1] : path 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ########################## 2 | #### General 3 | ########################## 4 | # https://gist.github.com/octocat/9257657 5 | 6 | *.log 7 | *.bak 8 | 9 | ################# 10 | ## Compiled source 11 | ################# 12 | *.com 13 | *.class 14 | *.dll 15 | *.exe 16 | *.o 17 | *.so 18 | 19 | ################# 20 | ## Archives 21 | ################# 22 | # https://github.com/github/gitignore/blob/master/Global/Archives.gitignore 23 | 24 | # It's better to unpack these files and commit the raw source because 25 | # git has its own built in compression methods. 26 | *.7z 27 | *.jar 28 | *.rar 29 | *.zip 30 | *.gz 31 | *.bzip 32 | *.bz2 33 | *.xz 34 | *.lzma 35 | *.cab 36 | 37 | #packing-only formats 38 | *.iso 39 | *.tar 40 | 41 | #package management formats 42 | *.dmg 43 | *.xpi 44 | *.gem 45 | *.egg 46 | *.deb 47 | *.rpm 48 | *.msi 49 | *.msm 50 | *.msp 51 | 52 | ########################## 53 | #### Operating Systems 54 | ########################## 55 | 56 | ################# 57 | ## Windows 58 | ################# 59 | # https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 60 | 61 | # Windows image file caches 62 | Thumbs.db 63 | ehthumbs.db 64 | 65 | # Folder config file 66 | Desktop.ini 67 | 68 | # Recycle Bin used on file shares 69 | $RECYCLE.BIN/ 70 | 71 | # Windows Installer files 72 | *.cab 73 | *.msi 74 | *.msm 75 | *.msp 76 | 77 | # Windows shortcuts 78 | *.lnk 79 | 80 | ################# 81 | ## OSX 82 | ################# 83 | # https://github.com/github/gitignore/blob/master/Global/OSX.gitignore 84 | 85 | .DS_Store 86 | .AppleDouble 87 | .LSOverride 88 | 89 | # Icon must end with two \r 90 | Icon 91 | 92 | 93 | # Thumbnails 94 | ._* 95 | 96 | # Files that might appear on external disk 97 | .Spotlight-V100 98 | .Trashes 99 | 100 | # Directories potentially created on remote AFP share 101 | .AppleDB 102 | .AppleDesktop 103 | Network Trash Folder 104 | Temporary Items 105 | .apdisk 106 | 107 | ################# 108 | ## Linux 109 | ################# 110 | # https://github.com/github/gitignore/blob/master/Global/Linux.gitignore 111 | 112 | *~ 113 | 114 | # KDE directory preferences 115 | .directory 116 | 117 | ########################## 118 | #### IDE 119 | ########################## 120 | 121 | ################# 122 | ## Eclipse 123 | ################# 124 | # https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore 125 | 126 | # Don't commit project files 127 | .classpath 128 | .project 129 | 130 | *.pydevproject 131 | .metadata 132 | .gradle 133 | bin/ 134 | tmp/ 135 | *.tmp 136 | *.bak 137 | *.swp 138 | *~.nib 139 | local.properties 140 | .settings/ 141 | .loadpath 142 | 143 | # External tool builders 144 | .externalToolBuilders/ 145 | 146 | # Locally stored "Eclipse launch configurations" 147 | *.launch 148 | 149 | # CDT-specific 150 | .cproject 151 | 152 | # PDT-specific 153 | .buildpath 154 | 155 | # sbteclipse plugin 156 | .target 157 | 158 | # TeXlipse plugin 159 | .texlipse 160 | 161 | ################# 162 | ## NetBeans 163 | ################# 164 | # https://github.com/github/gitignore/blob/master/Global/NetBeans.gitignore 165 | 166 | nbproject/private/ 167 | build/ 168 | nbbuild/ 169 | dist/ 170 | nbdist/ 171 | nbactions.xml 172 | nb-configuration.xml 173 | 174 | ################# 175 | ## JetBrains 176 | ################# 177 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 178 | 179 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 180 | 181 | *.iml 182 | 183 | ## Directory-based project format: 184 | .idea/ 185 | # if you remove the above rule, at least ignore the following: 186 | 187 | # User-specific stuff: 188 | # .idea/workspace.xml 189 | # .idea/tasks.xml 190 | # .idea/dictionaries 191 | 192 | # Sensitive or high-churn files: 193 | # .idea/dataSources.ids 194 | # .idea/dataSources.xml 195 | # .idea/sqlDataSources.xml 196 | # .idea/dynamic.xml 197 | # .idea/uiDesigner.xml 198 | 199 | # Gradle: 200 | # .idea/gradle.xml 201 | # .idea/libraries 202 | 203 | # Mongo Explorer plugin: 204 | # .idea/mongoSettings.xml 205 | 206 | ## File-based project format: 207 | *.ipr 208 | *.iws 209 | 210 | ## Plugin-specific files: 211 | 212 | # IntelliJ 213 | out/ 214 | 215 | # mpeltonen/sbt-idea plugin 216 | .idea_modules/ 217 | 218 | # JIRA plugin 219 | atlassian-ide-plugin.xml 220 | 221 | # Crashlytics plugin (for Android Studio and IntelliJ) 222 | com_crashlytics_export_strings.xml 223 | 224 | ########################## 225 | #### Project 226 | ########################## 227 | 228 | ################# 229 | ## Java 230 | ################# 231 | # https://github.com/github/gitignore/blob/master/Java.gitignore 232 | 233 | *.class 234 | 235 | # Mobile Tools for Java (J2ME) 236 | .mtj.tmp/ 237 | 238 | # Package Files # 239 | *.jar 240 | *.war 241 | *.ear 242 | 243 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 244 | hs_err_pid* 245 | 246 | ################# 247 | ## Gradle 248 | ################# 249 | # https://github.com/github/gitignore/blob/master/Gradle.gitignore 250 | 251 | .gradle 252 | build/ 253 | 254 | # Ignore Gradle GUI config 255 | gradle-app.setting 256 | 257 | # Allow the Gradle wrapper 258 | !gradle-wrapper.jar 259 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # licenser 2 | licenser is a simple license header manager for Gradle. It can automatically ensure that the source files contain a predefined license header and optionally generate them automatically using a Gradle task. It provides several options as configuration (e.g. variables in the license header, included file types, style of license header) so it can be customized for each project. 3 | 4 | ## Features 5 | - Apply pre-defined license header in a file to the source files of the source sets or any other set of files (configurable) 6 | - Variable substitution in the license header file 7 | - Apply license header only to certain files (include/exclude possible) 8 | - Apply special license headers to matching files 9 | - Support for Android projects 10 | 11 | ## Usage 12 | For a simple project you only need to apply the licenser plugin to your project: 13 | 14 | ```gradle 15 | plugins { 16 | id 'org.cadixdev.licenser' version '0.6.1' 17 | } 18 | ``` 19 | 20 | This will apply the `LICENSE` file found in the project directory to all common source file types known to licenser. 21 | 22 | 23 | ## Tasks 24 | |Name|Description| 25 | |----|-----------| 26 | |`checkLicenses`|Verifies the license headers for the selected source files.| 27 | |`updateLicenses`|Updates the license headers in the selected source files. Will create a backup in `build/tmp/updateLicense/original`.| 28 | |`checkLicense`|Verifies the license headers for the specified source set.| 29 | |`updateLicense`|Updates the license headers in the specified source set. Will create a backup in `build/tmp/updateLicense/original`.| 30 | |`checkLicenseAndroid`|Same as `checkLicense`, but for Android source sets.| 31 | |`updateLicenseAndroid`|Same as `updateLicense`, but for Android source sets.| 32 | |`checkLicenseCustom`|Same as `checkLicense`, but for custom tasks.| 33 | |`updateLicenseCustom`|Same as `updateLicense`, but for custom tasks.| 34 | |`licenseCheck`|Alias for `checkLicenses`| 35 | |`licenseFormat`|Alias for `updateLicenses`| 36 | 37 | ## Configuration 38 | The plugin can be configured using the `license` extension on the project. 39 | 40 | - **Custom header file source:** (Default: `LICENSE` in project directory) 41 | 42 | ```gradle 43 | license { 44 | header = project.file('HEADER.txt') 45 | } 46 | ``` 47 | 48 | - **Variable substitution in the license header:** 49 | 50 | ```gradle 51 | license { 52 | header = project.file('HEADER.txt') 53 | properties { 54 | name = 'Company' 55 | year = 2018 56 | } 57 | 58 | // Example license header: Copyright (C) ${year} ${name} 59 | } 60 | ``` 61 | 62 | - **Toggle new empty line after the license header:** (Default: true) 63 | 64 | ```gradle 65 | license { 66 | newLine = false // Disables the new line 67 | } 68 | ``` 69 | - **Ignore existing license headers:** (Default: false) 70 | 71 | ```gradle 72 | license { 73 | skipExistingHeaders = true // Ignore existing license headers on files 74 | } 75 | ``` 76 | - **Exclude/include certain file types:** (Default: Excludes files without standard comment format and binary files) 77 | 78 | ```gradle 79 | license { 80 | include '**/*.java' // Apply license header ONLY to Java files 81 | // OR 82 | exclude '**/*.properties' // Apply license header NOT to properties files 83 | } 84 | ``` 85 | - **Apply special license header to some matching files:** 86 | 87 | ```gradle 88 | license { 89 | // Apply special license header to one source file 90 | matching('**/ThirdPartyLibrary.java') { 91 | header = file('THIRDPARTY-LICENSE.txt') 92 | } 93 | 94 | // Apply special license header to matching source files 95 | matching(includes: ['**/thirdpartylibrary/**', '**/ThirdPartyLibrary.java']) { 96 | header = file('THIRDPARTY-LICENSE.txt') 97 | } 98 | } 99 | ``` 100 | - **Custom tasks: Apply license header to files outside of source set:** 101 | 102 | ```gradle 103 | license { 104 | tasks { 105 | gradle { 106 | files.from('build.gradle.kts', 'settings.gradle.kts', 'gradle.properties') 107 | // header = ... (optional) 108 | } 109 | directory { 110 | files.from('path/to/directory') 111 | // include/exclude ... (optional) 112 | } 113 | } 114 | } 115 | ``` 116 | 117 | - **Manage file extension to license header styles:** 118 | 119 | ```gradle 120 | license { 121 | style { 122 | java = 'JAVADOC' // Sets Java license header style to JAVADOC (/**) 123 | } 124 | } 125 | ``` 126 | - **Other options:** 127 | 128 | ```gradle 129 | license { 130 | // Ignore failures and only print a warning on license violations 131 | ignoreFailures = true 132 | 133 | // Read/write files with platform charset (Default: UTF-8) 134 | charset = Charset.defaultCharset().name() 135 | 136 | // Override the line ending used for license files (Default: system line ending) 137 | lineEnding = '\n' 138 | } 139 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/util/HeaderHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.util; 26 | 27 | import org.cadixdev.gradle.licenser.header.CommentHeaderFormat; 28 | 29 | import javax.annotation.Nullable; 30 | import java.io.BufferedReader; 31 | import java.io.IOException; 32 | import java.util.Iterator; 33 | import java.util.regex.Pattern; 34 | 35 | public final class HeaderHelper { 36 | 37 | private HeaderHelper() { 38 | } 39 | 40 | public static String getExtension(String s) { 41 | final int pos = s.lastIndexOf('.'); 42 | return pos >= 0 ? s.substring(pos + 1) : null; 43 | } 44 | 45 | public static String stripIndent(String s) { 46 | if (s.isEmpty()) { 47 | return s; 48 | } 49 | 50 | final int len = s.length(); 51 | for (int i = 0; i < len; i++) { 52 | if (!Character.isWhitespace(s.charAt(i))) { 53 | return i == 0 ? s : s.substring(i); 54 | } 55 | } 56 | 57 | return ""; 58 | } 59 | 60 | public static String stripTrailingIndent(String s) { 61 | if (s.isEmpty()) { 62 | return s; 63 | } 64 | 65 | final int last = s.length() - 1; 66 | for (int i = last; i >= 0; i--) { 67 | if (!Character.isWhitespace(s.charAt(i))) { 68 | return i == last ? s : s.substring(0, i + 1); 69 | } 70 | } 71 | 72 | return ""; 73 | } 74 | 75 | public static boolean contentStartsWith(BufferedReader reader, Iterator itr, Pattern ignored) throws IOException { 76 | String line; 77 | while (itr.hasNext() && (line = reader.readLine()) != null) { 78 | if (ignored != null && ignored.matcher(line).find()) { 79 | continue; 80 | } 81 | 82 | if (!line.equals(itr.next())) { 83 | return false; 84 | } 85 | } 86 | 87 | return !itr.hasNext(); 88 | } 89 | 90 | public static boolean contentStartsWithValidHeaderFormat(BufferedReader reader, CommentHeaderFormat format) throws IOException { 91 | String firstLine; 92 | while ((firstLine = skipEmptyLines(reader)) != null && findPattern(firstLine, format.getSkipLine())) { 93 | // skip ignored lines 94 | } 95 | if (firstLine == null) { 96 | return false; 97 | } 98 | final boolean firstLineMatches = format.getStart().matcher(firstLine).find(); 99 | boolean lastLineMatches = format.getEnd() == null; 100 | boolean contentLinesMatch = true; 101 | 102 | String line; 103 | while ((line = reader.readLine()) != null) { 104 | // skip ignored lines 105 | if (findPattern(line, format.getSkipLine())) { 106 | continue; 107 | } 108 | 109 | if (findPattern(line, format.getEnd())) { 110 | lastLineMatches = true; 111 | break; 112 | } else if (format.getEnd() == null) { 113 | break; 114 | } 115 | // If the current line doesn't match and there's no end marker, assume the header is complete 116 | contentLinesMatch = contentLinesMatch && (line.startsWith(format.getPrefix()) || format.getEnd() == null); 117 | } 118 | 119 | return firstLineMatches && contentLinesMatch && lastLineMatches; 120 | } 121 | 122 | private static boolean findPattern(CharSequence line, @Nullable Pattern pattern) { 123 | if (pattern == null) { 124 | return false; 125 | } else { 126 | return pattern.matcher(line).find(); 127 | } 128 | } 129 | 130 | public static boolean isBlank(String s) { 131 | return stripIndent(s).isEmpty(); 132 | } 133 | 134 | public static String skipEmptyLines(BufferedReader reader) throws IOException { 135 | String line; 136 | while ((line = reader.readLine()) != null) { 137 | if (!isBlank(line)) { 138 | return line; 139 | } 140 | } 141 | 142 | return null; 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /src/test/groovy/org/cadixdev/gradle/licenser/util/HeaderHelperTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.util 26 | 27 | 28 | import org.cadixdev.gradle.licenser.header.HeaderStyle 29 | import spock.lang.Specification 30 | 31 | class HeaderHelperTest extends Specification { 32 | def "contentStartsWithValidHeaderFormat returns false with empty input"() { 33 | given: 34 | def inputString = "" 35 | def stringReader = new StringReader(inputString) 36 | def reader = new BufferedReader(stringReader) 37 | 38 | when: 39 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.BLOCK_COMMENT.format) 40 | 41 | then: 42 | !result 43 | } 44 | 45 | def "contentStartsWithValidHeaderFormat returns false with non-matching input"() { 46 | given: 47 | def inputString = "Not a copyright header" 48 | def stringReader = new StringReader(inputString) 49 | def reader = new BufferedReader(stringReader) 50 | 51 | when: 52 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.BLOCK_COMMENT.format) 53 | 54 | then: 55 | !result 56 | } 57 | 58 | def "contentStartsWithValidHeaderFormat returns true with valid non-empty header"() { 59 | given: 60 | def inputString = """\ 61 | /* 62 | * Some copyright header 63 | */ 64 | My Content 65 | """.stripIndent() 66 | def stringReader = new StringReader(inputString) 67 | def reader = new BufferedReader(stringReader) 68 | 69 | when: 70 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.BLOCK_COMMENT.format) 71 | 72 | then: 73 | result 74 | } 75 | 76 | def "contentStartsWithValidHeaderFormat returns false with invalid non-empty header"() { 77 | given: 78 | def inputString = """\ 79 | /** 80 | * Some copyright header 81 | */ 82 | My Content 83 | """.stripIndent() 84 | def stringReader = new StringReader(inputString) 85 | def reader = new BufferedReader(stringReader) 86 | 87 | when: 88 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.BLOCK_COMMENT.format) 89 | 90 | then: 91 | !result 92 | } 93 | 94 | def "contentStartsWithValidHeaderFormat returns true with valid empty header"() { 95 | given: 96 | def inputString = """\ 97 | /* 98 | */ 99 | My Content 100 | """.stripIndent() 101 | def stringReader = new StringReader(inputString) 102 | def reader = new BufferedReader(stringReader) 103 | 104 | when: 105 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.BLOCK_COMMENT.format) 106 | 107 | then: 108 | result 109 | } 110 | 111 | def "contentStartsWithValidHeaderFormat returns false with incomplete header"() { 112 | given: 113 | def inputString = """\ 114 | /* 115 | * Incomplete copyright header 116 | My Content 117 | """.stripIndent() 118 | def stringReader = new StringReader(inputString) 119 | def reader = new BufferedReader(stringReader) 120 | 121 | when: 122 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.BLOCK_COMMENT.format) 123 | 124 | then: 125 | !result 126 | } 127 | 128 | def "contentStartsWithValidHeaderFormat returns true with valid header with ignored lines"() { 129 | given: 130 | def inputString = """\ 131 | #!/bin/bash 132 | # Some header 133 | My Content 134 | """.stripIndent() 135 | def stringReader = new StringReader(inputString) 136 | def reader = new BufferedReader(stringReader) 137 | 138 | when: 139 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.HASH.format) 140 | 141 | then: 142 | result 143 | } 144 | 145 | def "contentStartsWithValidHeaderFormat returns true with valid header with XML"() { 146 | given: 147 | def inputString = """\ 148 | 149 | 152 | 153 | 154 | """.stripIndent() 155 | def stringReader = new StringReader(inputString) 156 | def reader = new BufferedReader(stringReader) 157 | 158 | when: 159 | def result = HeaderHelper.contentStartsWithValidHeaderFormat(reader, HeaderStyle.XML.format) 160 | 161 | then: 162 | result 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/Licenser.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import groovy.text.SimpleTemplateEngine 28 | import org.cadixdev.gradle.licenser.header.Header 29 | import org.cadixdev.gradle.licenser.tasks.LicenseCheck 30 | import org.cadixdev.gradle.licenser.tasks.LicenseTask 31 | import org.cadixdev.gradle.licenser.tasks.LicenseUpdate 32 | import org.gradle.api.Plugin 33 | import org.gradle.api.Project 34 | import org.gradle.api.file.FileCollection 35 | import org.gradle.api.plugins.JavaBasePlugin 36 | import org.gradle.api.provider.ListProperty 37 | import org.gradle.api.resources.ResourceException 38 | import org.gradle.api.resources.TextResource 39 | import org.gradle.api.tasks.SourceSet 40 | import org.gradle.api.tasks.TaskProvider 41 | import org.gradle.api.tasks.util.PatternSet 42 | import org.gradle.language.base.plugins.LifecycleBasePlugin 43 | import org.gradle.util.ConfigureUtil 44 | 45 | class Licenser implements Plugin { 46 | 47 | private static final String CHECK_TASK = 'checkLicense' 48 | private static final String FORMAT_TASK = 'updateLicense' 49 | private static final String ANDROID_TASK = 'Android' 50 | private static final String CUSTOM_TASK = 'Custom' 51 | private static final String FORMATTING_GROUP = 'formatting' 52 | 53 | private Project project 54 | private LicenseExtension extension 55 | 56 | @Override 57 | void apply(Project project) { 58 | this.project = project 59 | this.extension = project.extensions.create('license', LicenseExtension, project.objects, project) 60 | this.extension.header.set(extension.charset.map { charset -> project.resources.text.fromFile('LICENSE', charset) }) 61 | 62 | def headers = project.objects.listProperty(Header) 63 | // TODO: finalizeValueOnRead is not supported on Gradle 5, remove when dropping support 64 | try { 65 | extension.conditionalProperties.finalizeValueOnRead() 66 | headers.finalizeValueOnRead() 67 | } catch (final MissingMethodException ignored) { 68 | // no method 69 | } 70 | headers.set(extension.conditionalProperties.map { 71 | def built = [] 72 | it.reverseEach { props -> 73 | built << prepareHeader(extension, props) 74 | } 75 | built << prepareHeader(extension, extension) 76 | return built 77 | }) 78 | 79 | def plugins = project.plugins 80 | def tasks = project.tasks 81 | 82 | // Configure tasks from different sources 83 | plugins.withType(JavaBasePlugin) { 84 | project.sourceSets.all { SourceSet set -> 85 | def extensionIgnoreFailures = extension.ignoreFailures 86 | def extensionLineEnding = extension.lineEnding 87 | createTask(CHECK_TASK, LicenseCheck, headers, set) { 88 | ignoreFailures.set(extensionIgnoreFailures) 89 | } 90 | createTask(FORMAT_TASK, LicenseUpdate, headers, set) { 91 | lineEnding.set(extensionLineEnding) 92 | } 93 | } 94 | } 95 | 96 | ['com.android.library', 'com.android.application'].each { 97 | plugins.withId(it) { 98 | project.android.sourceSets.all { set -> 99 | def extensionIgnoreFailures = extension.ignoreFailures 100 | def extensionLineEnding = extension.lineEnding 101 | createAndroidTask(CHECK_TASK, LicenseCheck, headers, set) { 102 | ignoreFailures.set(extensionIgnoreFailures) 103 | } 104 | createAndroidTask(FORMAT_TASK, LicenseUpdate, headers, set) { 105 | lineEnding.set(extensionLineEnding) 106 | } 107 | } 108 | } 109 | } 110 | 111 | extension.tasks.all { LicenseTaskProperties props -> 112 | def extensionIgnoreFailures = extension.ignoreFailures 113 | def extensionLineEnding = extension.lineEnding 114 | createCustomTask(CHECK_TASK, LicenseCheck, props) { 115 | ignoreFailures.set(extensionIgnoreFailures) 116 | } 117 | createCustomTask(FORMAT_TASK, LicenseUpdate, props) { 118 | lineEnding.set(extensionLineEnding) 119 | } 120 | } 121 | 122 | // Then configure catch-all tasks 123 | def globalCheck = tasks.register(CHECK_TASK + 's') { 124 | dependsOn(tasks.withType(LicenseCheck)) 125 | } 126 | tasks.register('licenseCheck') { 127 | dependsOn(globalCheck) 128 | } 129 | def globalFormat = tasks.register(FORMAT_TASK + 's') { 130 | dependsOn(tasks.withType(LicenseUpdate)) 131 | } 132 | tasks.register('licenseFormat') { 133 | group = FORMATTING_GROUP 134 | dependsOn(globalFormat) 135 | } 136 | 137 | plugins.withType(LifecycleBasePlugin) { 138 | tasks.named(LifecycleBasePlugin.CHECK_TASK_NAME).configure { 139 | dependsOn(globalCheck) 140 | } 141 | } 142 | } 143 | 144 | private static Header prepareHeader(LicenseExtension extension, LicenseProperties properties) { 145 | def headerResource = properties.header.orElse(extension.header) 146 | def extraProperties = extension.ext 147 | extension.keywords.disallowChanges() 148 | properties.newLine.disallowChanges() 149 | return new Header(extension.style, extension.keywords, extension.providers.provider { 150 | TextResource header = headerResource.getOrNull() 151 | if (header != null) { 152 | def text 153 | try { 154 | text = header.asString() 155 | } catch (ResourceException ignored) { 156 | return "" 157 | } 158 | 159 | Map props = extraProperties.properties 160 | if (props) { 161 | def engine = new SimpleTemplateEngine() 162 | def template = engine.createTemplate(text).make(props) 163 | text = template.toString() 164 | } 165 | 166 | return text 167 | } 168 | 169 | return "" 170 | }, (PatternSet) properties.filter, properties.newLine.orElse(extension.newLine),) 171 | } 172 | 173 | private TaskProvider createTask( 174 | String name, 175 | @DelegatesTo.Target Class type, 176 | ListProperty
headers, 177 | SourceSet sourceSet, 178 | @DelegatesTo(strategy = Closure.DELEGATE_FIRST) Closure target = null 179 | ) { 180 | return makeTask(sourceSet.getTaskName(name, null), type, headers, sourceSet.allSource, target) 181 | } 182 | 183 | private TaskProvider createAndroidTask( 184 | String name, 185 | @DelegatesTo.Target Class type, 186 | ListProperty
headers, 187 | Object sourceSet, 188 | @DelegatesTo(strategy = Closure.DELEGATE_FIRST) Closure target = null 189 | ) { 190 | return makeTask(name + ANDROID_TASK + sourceSet.name.capitalize(), type, headers, 191 | project.files(sourceSet.java.sourceFiles, sourceSet.res.sourceFiles, sourceSet.manifest.srcFile), target) 192 | } 193 | 194 | private TaskProvider createCustomTask( 195 | String name, 196 | @DelegatesTo.Target Class type, 197 | LicenseTaskProperties properties, 198 | @DelegatesTo(strategy = Closure.DELEGATE_FIRST) Closure target = null 199 | ) { 200 | def headers = project.objects.listProperty(Header) 201 | headers.add(prepareHeader(extension, properties)) 202 | def task = makeTask(name + CUSTOM_TASK + properties.name.capitalize(), type, headers, properties.files, target) 203 | task.configure { 204 | filter = properties.filter 205 | } 206 | return task 207 | } 208 | 209 | private TaskProvider makeTask( 210 | String name, 211 | Class type, 212 | ListProperty
headers, 213 | FileCollection files, 214 | Closure target = null 215 | ) { 216 | def charset = extension.charset 217 | def skipExisting = extension.skipExistingHeaders 218 | return project.tasks.register(name, type) { T task -> 219 | task.headers.set(headers) 220 | task.files = files 221 | task.filter = extension.filter 222 | task.charset.set(charset) 223 | task.skipExistingHeaders.set(skipExisting) 224 | if (target != null) { 225 | ConfigureUtil.configure(target, task) 226 | } 227 | } 228 | } 229 | 230 | } 231 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/LicenseExtension.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import groovy.transform.PackageScope 28 | import org.cadixdev.gradle.licenser.header.HeaderFormatRegistry 29 | import org.gradle.api.Action 30 | import org.gradle.api.Incubating 31 | import org.gradle.api.NamedDomainObjectContainer 32 | import org.gradle.api.Project 33 | import org.gradle.api.model.ObjectFactory 34 | import org.gradle.api.plugins.ExtraPropertiesExtension 35 | import org.gradle.api.provider.ListProperty 36 | import org.gradle.api.provider.Property 37 | import org.gradle.api.provider.ProviderFactory 38 | import org.gradle.api.resources.TextResourceFactory 39 | import org.gradle.api.tasks.util.PatternFilterable 40 | import org.gradle.api.tasks.util.PatternSet 41 | import org.gradle.util.ConfigureUtil 42 | 43 | import javax.inject.Inject 44 | 45 | /** 46 | * Represents the Gradle extension for configuring the settings for the 47 | * {@link Licenser} plugin. 48 | */ 49 | class LicenseExtension extends LicenseProperties { 50 | 51 | /** 52 | * The charset to read/write the files with. 53 | * By default this is {@code UTF-8}. 54 | */ 55 | Property getCharset() { 56 | return super.charset // groovy has no distinction between methods and fields... 57 | } 58 | 59 | /** 60 | * Whether to ignore failures and only warn about license violations 61 | * instead of failing the build. 62 | * By default this is {@code false}. 63 | */ 64 | final Property ignoreFailures 65 | 66 | /** 67 | * Whether to skip existing license headers instead of failing the build or 68 | * updating the license headers. 69 | * By default this is {@code false}. 70 | */ 71 | final Property skipExistingHeaders 72 | 73 | /** 74 | * The line ending to use within license headers. 75 | * 76 | * By default this is {@link System#lineSeparator()} 77 | */ 78 | final Property lineEnding 79 | 80 | /** 81 | * The style mappings from file extension to the type of style of the 82 | * comment header for the license header. 83 | * By default this includes mappings and styles for the most common file 84 | * types. 85 | */ 86 | HeaderFormatRegistry style = new HeaderFormatRegistry() 87 | 88 | /** 89 | * The (case-insensitive) keywords that identify a comment as license 90 | * header. 91 | * By default this includes only the words "Copyright" and "License". 92 | */ 93 | final ListProperty keywords 94 | 95 | /** 96 | * Additional conditional {@link LicenseProperties} matching a subset of 97 | * the files in the project's source sets. 98 | */ 99 | final ListProperty conditionalProperties 100 | 101 | /** 102 | * Additional custom license tasks that operate on a listed set of files 103 | * (not necessarily source sets). Can be used to apply license headers to 104 | * sources outside of source sets. 105 | */ 106 | @Incubating 107 | final NamedDomainObjectContainer tasks 108 | 109 | @PackageScope final ObjectFactory objects 110 | @PackageScope final TextResourceFactory textResources 111 | @PackageScope final ProviderFactory providers 112 | 113 | @Inject 114 | LicenseExtension(final ObjectFactory objects, final Project project) { 115 | super(new PatternSet(), objects, project.resources.text) 116 | 117 | this.objects = objects 118 | this.textResources = project.resources.text 119 | this.providers = project.providers 120 | this.tasks = objects.domainObjectContainer(LicenseTaskProperties) { String name -> 121 | new LicenseTaskProperties((filter as PatternSet).intersect(), name, objects, textResources, charset) 122 | } 123 | this.conditionalProperties = objects.listProperty(LicenseProperties) 124 | 125 | // Defaults 126 | this.keywords = objects.listProperty(String).convention(['Copyright', 'License']) 127 | this.ignoreFailures = objects.property(Boolean).convention(false) 128 | this.skipExistingHeaders = objects.property(Boolean).convention(false) 129 | this.charset.convention('UTF-8') 130 | 131 | def defaultLineEnding 132 | try { 133 | // Gradle 6+ 134 | defaultLineEnding = project.providers.systemProperty("line.separator") 135 | } catch (final MissingMethodException ex) { 136 | // Gradle 5.x TODO @ 0.7: remove this 137 | defaultLineEnding = project.provider { System.lineSeparator() } 138 | } 139 | this.lineEnding = objects.property(String).convention(defaultLineEnding) 140 | this.newLine.convention(true) 141 | 142 | // Files without standard comment format 143 | exclude '**/*.txt' 144 | exclude '**/*.json' 145 | exclude '**/*.md' 146 | 147 | // Image files 148 | exclude '**/*.jpg' 149 | exclude '**/*.png' 150 | exclude '**/*.gif' 151 | exclude '**/*.bmp' 152 | exclude '**/*.ico' 153 | 154 | // Binary files 155 | exclude '**/*.zip' 156 | exclude '**/*.jar' 157 | exclude '**/*.class' 158 | exclude '**/*.bin' 159 | 160 | // Manifest 161 | exclude '**/MANIFEST.MF' 162 | exclude '**/META-INF/services/**' 163 | } 164 | 165 | /** 166 | * @see #charset 167 | */ 168 | void charset(final String charset) { 169 | this.charset.set(charset) 170 | } 171 | 172 | /** 173 | * @see #ignoreFailures 174 | */ 175 | void ignoreFailures(final boolean ignoreFailures) { 176 | this.ignoreFailures.set(ignoreFailures) 177 | } 178 | 179 | /** 180 | * @see #skipExistingHeaders 181 | */ 182 | void skipExistingHeaders(final boolean skipExistingHeaders) { 183 | this.skipExistingHeaders.set(skipExistingHeaders) 184 | } 185 | 186 | /** 187 | * @see #lineEnding 188 | */ 189 | void lineEnding(final String lineEnding) { 190 | this.lineEnding.set(lineEnding) 191 | } 192 | 193 | /** 194 | * Adds a new conditional license header that will be applied to all matching files. 195 | * 196 | * @param include A single include pattern 197 | * @param closure The closure that configures the license header 198 | */ 199 | void matching(String include, @DelegatesTo(LicenseProperties) Closure closure) { 200 | matching(new PatternSet().include(include), closure) 201 | } 202 | 203 | /** 204 | * Adds a new conditional license header that will be applied to all matching files. 205 | * 206 | * @param args A map definition of the pattern, similar to {@link Project#fileTree(Map)} 207 | * @param closure The closure that configures the license header 208 | */ 209 | void matching(Map args, @DelegatesTo(LicenseProperties) Closure closure) { 210 | matching(ConfigureUtil.configureByMap(args, new PatternSet()), closure) 211 | } 212 | 213 | /** 214 | * Adds a new conditional license header that will be applied to all matching files. 215 | * 216 | * @param patternClosure A closure that configures the {@link PatternFilterable} 217 | * @param configureClosure The closure that configures the license header 218 | */ 219 | void matching(@DelegatesTo(PatternFilterable) Closure patternClosure, @DelegatesTo(LicenseProperties) Closure configureClosure) { 220 | matching(ConfigureUtil.configure(patternClosure, new PatternSet()), configureClosure) 221 | } 222 | 223 | /** 224 | * Adds a new conditional license header that will be applied to all matching files. 225 | * 226 | * @param pattern The pattern that matches the files 227 | * @param closure The closure that configures the license header 228 | */ 229 | void matching(PatternSet pattern, @DelegatesTo(LicenseProperties) Closure closure) { 230 | conditionalProperties.add(ConfigureUtil.configure(closure, new LicenseProperties(pattern, this.objects, this.textResources, this.charset))) 231 | } 232 | 233 | /** 234 | * Configures the license styles using the specified {@link Closure}. 235 | * 236 | * @param closure The closure to apply to the style 237 | */ 238 | void style(@DelegatesTo(HeaderFormatRegistry) Closure closure) { 239 | style.with(closure) 240 | } 241 | 242 | /** 243 | * Configures the custom tasks using the specified {@link Closure}. 244 | * 245 | * @param closure The closure to apply to the custom tasks 246 | */ 247 | @Incubating 248 | void tasks(Closure closure) { 249 | this.tasks.configure(closure) 250 | } 251 | 252 | /** 253 | * Add additional keywords that indicate a license header. 254 | * 255 | * @param keywords the extra keywords 256 | */ 257 | void keywords(final String... keywords) { 258 | this.keywords.addAll(keywords); 259 | } 260 | 261 | /** 262 | * Configure the extra properties that can be used in the license plugin. 263 | * 264 | *

This is mostly useful for Kotlin buildscripts which have scope issues 265 | * for the normal way of working with extra properties.

266 | * 267 | * @param action the action to perform 268 | */ 269 | void properties(final Action action) { 270 | ExtraPropertiesExtension extra = this.ext 271 | action.execute(extra) 272 | } 273 | 274 | // kotlin + from other plugins 275 | /** 276 | * Set the header to the contents of a file. 277 | * 278 | * @param header anything accepted in {@link org.gradle.api.Project#file(Object)} 279 | * @see #header 280 | */ 281 | @Override 282 | void header(final Object header) { 283 | this.header.set(this.charset.map { this.textResources.fromFile(header, it) }) 284 | } 285 | 286 | // groovy 287 | @Override 288 | void setHeader(final File header) { 289 | this.header.set(this.charset.map { this.textResources.fromFile(header, it) }) 290 | } 291 | 292 | } 293 | -------------------------------------------------------------------------------- /src/main/groovy/org/cadixdev/gradle/licenser/header/PreparedCommentHeader.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser.header 26 | 27 | import groovy.transform.PackageScope 28 | import org.cadixdev.gradle.licenser.util.HeaderHelper 29 | 30 | @PackageScope 31 | class PreparedCommentHeader implements PreparedHeader { 32 | 33 | final Header header 34 | final CommentHeaderFormat format 35 | final List lines 36 | 37 | PreparedCommentHeader(Header header, CommentHeaderFormat format, List lines) { 38 | this.header = header 39 | this.format = format 40 | this.lines = lines 41 | } 42 | 43 | @Override 44 | boolean check(File file, String charset, boolean skipExistingHeaders) throws IOException { 45 | return file.withReader(charset) { BufferedReader reader -> 46 | boolean result = skipExistingHeaders ? 47 | HeaderHelper.contentStartsWithValidHeaderFormat(reader, format) : 48 | HeaderHelper.contentStartsWith(reader, this.lines.iterator(), format.skipLine) 49 | if (result) { 50 | def line = reader.readLine() 51 | if (header.newLine.get()) { 52 | result = line != null && line.isEmpty() 53 | } else if (line != null) { 54 | result = !line.isEmpty() 55 | } 56 | } 57 | return result 58 | } 59 | } 60 | 61 | @Override 62 | boolean update(File file, String charset, String lineSeparator, boolean skipExistingHeaders, Runnable callback) throws IOException { 63 | boolean valid = false 64 | // The lines skipped before the license header 65 | List before = [] 66 | // The comment lines we've read. Important if the comment does not contain 67 | // any of the keywords, then we need to write it back to the file. 68 | List comment = null 69 | // The last line we've looked at 70 | String last = null 71 | // The remaining text to write back to the file 72 | String text = null 73 | 74 | // Open file for verifying the license header and reading the text we 75 | // need to append after it 76 | file.withReader(charset) { BufferedReader reader -> 77 | if (skipExistingHeaders) { 78 | reader.mark(2048) 79 | def startsWithValidHeader = HeaderHelper.contentStartsWithValidHeaderFormat(reader, format) 80 | if (startsWithValidHeader) { 81 | valid = true 82 | return 83 | } else { 84 | reader.reset() 85 | } 86 | } 87 | 88 | String line 89 | while (true) { 90 | // Find first non-empty line 91 | line = HeaderHelper.skipEmptyLines(reader) 92 | if (line == null) { 93 | return // EOF, invalid and done 94 | } 95 | 96 | // Unless the line is requested to be skipped by the header we're done 97 | // However, some header formats have certain lines that need to be skipped 98 | // E.g. for XML the XML document declaration 99 | if (!format.skipLine || !(line =~ format.skipLine)) { 100 | break 101 | } 102 | 103 | // Append the lines we've skipped so we can add them back to the file later 104 | before << line 105 | } 106 | 107 | // If the first line doesn't match the comment start we're done 108 | // and the file doesn't have a license header yet 109 | if (!(line =~ format.start) || (format.end && line =~ format.end)) { 110 | last = line 111 | text = reader.text 112 | return 113 | } 114 | 115 | // If the first line does not contain one of our license header 116 | // keywords, we need to start collecting all comment lines we've read 117 | if (!header.containsKeyword(line)) { 118 | comment = [line] 119 | } 120 | 121 | // Now go through the license header and verify it 122 | valid = true 123 | def itr = this.lines.iterator() 124 | while (true) { 125 | // No lines left in our expected license header; this comment is invalid 126 | if (!itr.hasNext()) { 127 | valid = false 128 | } 129 | 130 | // Still valid, but next lines doesn't match; invalid comment 131 | if (valid && itr.next() != line) { 132 | valid = false 133 | } 134 | 135 | // Read the next line from the file 136 | line = reader.readLine() 137 | if (line == null) { 138 | // EOF, but the end comment was yet found 139 | if (format.end) { 140 | // Failed to find end of comment. This often means the end 141 | // of comment was simply removed, so instead of wiping the 142 | // whole file simply throw an exception 143 | throw new IllegalStateException("Failed to find end of block comment in $file") 144 | } 145 | 146 | // Nothing needed to end a comment: Invalid but fine to continue 147 | valid = false 148 | return 149 | } 150 | 151 | // Only some comment formats have specific patterns for the end of a comment 152 | if (format.end) { 153 | // Multi-line 154 | def matcher = line =~ format.end 155 | if (matcher) { 156 | // Append comment to buffer if it doesn't contain keyword 157 | if (comment != null) { 158 | if (header.containsKeyword(line)) { 159 | comment = null 160 | } else { 161 | comment << line 162 | } 163 | } 164 | 165 | // Check for remaining stuff on the comment line 166 | // (We don't want to wipe lines from the file) 167 | if (matcher.hasGroup()) { 168 | def group = matcher.group(1) 169 | if (!group.isEmpty()) { 170 | // There is stuff after the comment has ended, never valid 171 | valid = false 172 | if (!comment) { 173 | last = group 174 | } 175 | break 176 | } 177 | } 178 | 179 | // Check if really, really valid 180 | if (valid) { 181 | valid = line == itr.next() 182 | // There are still lines left that would need to come, invalid header 183 | if (itr.hasNext()) { 184 | valid = false 185 | } 186 | } 187 | 188 | // Read one more line so we can check for new lines 189 | last = reader.readLine() 190 | break 191 | } 192 | } else if (!(line =~ format.start)) { 193 | // There are still lines left that would need to come, invalid header 194 | if (itr.hasNext()) { 195 | valid = false 196 | } 197 | 198 | // The next line is actually the current one, because it is no longer 199 | // part of the comment 200 | last = line 201 | break 202 | } 203 | 204 | // Append comment to buffer if it doesn't contain keyword 205 | if (comment != null) { 206 | if (header.containsKeyword(line)) { 207 | comment = null 208 | } else { 209 | comment << line 210 | } 211 | } 212 | } 213 | 214 | // Look more carefully at the new lines 215 | if (valid) { 216 | if (header.newLine.get()) { 217 | // Only valid if next line is empty 218 | valid = last != null && last.isEmpty() 219 | } else if (last != null) { 220 | // Only valid if next line is NOT empty 221 | valid = !HeaderHelper.isBlank(last) 222 | } 223 | } 224 | 225 | if (last != null && HeaderHelper.isBlank(last)) { 226 | // Skip empty lines 227 | while ((last = reader.readLine()) != null && HeaderHelper.isBlank(last)) { 228 | // Duplicate new lines, NEVER valid 229 | valid = false 230 | } 231 | } 232 | 233 | if (last != null) { 234 | // Read the remaining text from the file so we can add it back later 235 | text = reader.text 236 | } 237 | return 238 | } 239 | 240 | // License header is valid, nothing to do 241 | if (valid) { 242 | return false 243 | } 244 | 245 | // Run callback (used for creating a backup of the files) 246 | callback.run() 247 | 248 | // Open file for updating license header 249 | file.withWriter(charset) { BufferedWriter writer -> 250 | // Write lines that were skipped before the header 251 | before.each { 252 | writer.write(it) 253 | writer.write(lineSeparator) 254 | } 255 | 256 | // Write actual license header 257 | this.lines.each { 258 | writer.write(it) 259 | writer.write(lineSeparator) 260 | } 261 | 262 | // Add new line if requested 263 | if (header.newLine.get()) { 264 | writer.write(lineSeparator) 265 | } 266 | 267 | // Add comment that was collected but did not match a valid license header 268 | // (Did not contain any of the defined keywords) 269 | if (comment != null) { 270 | comment.each { 271 | writer.write(it) 272 | writer.write(lineSeparator) 273 | } 274 | } 275 | 276 | // Write the last line we have looked at additionally 277 | // (Only if we have a captured (non-license header) comment before this 278 | // or it is not empty, we handle the new lines for license header ourselves) 279 | if (last != null && (comment != null || !last.isEmpty())) { 280 | writer.write(last) 281 | writer.write(lineSeparator) 282 | } 283 | 284 | // Write the remaining file 285 | if (text != null) { 286 | writer.write(text) 287 | } 288 | } 289 | 290 | return true 291 | } 292 | 293 | } 294 | -------------------------------------------------------------------------------- /src/functionalTest/groovy/org/cadixdev/gradle/licenser/LicenserPluginFunctionalTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015, Minecrell 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.cadixdev.gradle.licenser 26 | 27 | import org.gradle.testkit.runner.GradleRunner 28 | import org.gradle.testkit.runner.TaskOutcome 29 | import org.junit.Rule 30 | import org.junit.rules.TemporaryFolder 31 | import spock.lang.Specification 32 | import spock.lang.Unroll 33 | 34 | import java.nio.file.Paths 35 | 36 | class LicenserPluginFunctionalTest extends Specification { 37 | @Rule 38 | TemporaryFolder temporaryFolder = new TemporaryFolder() 39 | 40 | static final def standardArguments = ["--warning-mode", "fail", "--stacktrace"].asImmutable() 41 | 42 | static final def configurationCacheTestMatrix = [ 43 | // TODO: restore android plugin once versions that support configuration cache are available 44 | /* gradleVersion | androidVersion | extraArgs */ 45 | [ "6.8.3", null, ["--configuration-cache"] ], 46 | [ "6.9", null, ["--configuration-cache"] ], 47 | [ "7.0.2", null, ["--configuration-cache"] ], 48 | [ "7.1", null, ["--configuration-cache"] ], 49 | ].asImmutable() 50 | 51 | static final def testMatrix = ([ 52 | /* gradleVersion | androidVersion | extraArgs */ 53 | [ "5.6.4", "3.6.4", [] ], 54 | [ "6.8.3", "4.1.0", [] ], 55 | ] + configurationCacheTestMatrix).asImmutable() 56 | 57 | GradleRunner runner(File projectDir, gradleVersion, args) { 58 | return GradleRunner.create() 59 | .forwardOutput() 60 | .withPluginClasspath() 61 | .withGradleVersion(gradleVersion) 62 | .withArguments(standardArguments + args) 63 | .withProjectDir(projectDir) 64 | } 65 | 66 | @Unroll 67 | def "can run licenseCheck task (gradle #gradleVersion)"() { 68 | given: 69 | def projectDir = temporaryFolder.newFolder() 70 | new File(projectDir, "settings.gradle") << "" 71 | new File(projectDir, "build.gradle") << """ 72 | plugins { 73 | id('org.cadixdev.licenser') 74 | } 75 | """.stripIndent() 76 | 77 | when: 78 | def result = runner(projectDir, gradleVersion, extraArgs + "licenseCheck").build() 79 | 80 | then: 81 | result.task(":checkLicenses").outcome == TaskOutcome.UP_TO_DATE 82 | result.task(":licenseCheck").outcome == TaskOutcome.UP_TO_DATE 83 | 84 | where: 85 | [gradleVersion, _, extraArgs] << testMatrix 86 | } 87 | 88 | @Unroll 89 | def "skips existing headers in checkLicenses task (gradle #gradleVersion)"() { 90 | given: 91 | def projectDir = temporaryFolder.newFolder() 92 | def sourceDir = projectDir.toPath().resolve(Paths.get("src", "main", "java", "com", "example")).toFile() 93 | sourceDir.mkdirs() 94 | new File(projectDir, "header.txt") << "New copyright header" 95 | new File(projectDir, "settings.gradle") << "" 96 | new File(projectDir, "build.gradle") << """ 97 | plugins { 98 | id('java') 99 | id('org.cadixdev.licenser') 100 | } 101 | 102 | license { 103 | lineEnding = '\\n' 104 | header = project.file('header.txt') 105 | skipExistingHeaders = true 106 | } 107 | """.stripIndent() 108 | new File(sourceDir, "MyClass.java") << """ 109 | /* 110 | * Existing copyright header 111 | */ 112 | 113 | package com.example; 114 | 115 | class MyClass {} 116 | """.stripIndent() 117 | 118 | when: 119 | // Run twice to make sure that we can read the configuration cache 120 | def firstResult = runner(projectDir, gradleVersion, extraArgs + "checkLicenses").build() 121 | def secondResult = runner(projectDir, gradleVersion, extraArgs + "checkLicenses").build() 122 | 123 | then: 124 | firstResult.task(":checkLicenses").outcome == TaskOutcome.SUCCESS 125 | secondResult.task(":checkLicenses").outcome == TaskOutcome.SUCCESS 126 | 127 | where: 128 | [gradleVersion, _, extraArgs] << testMatrix 129 | } 130 | 131 | @Unroll 132 | def "skips existing headers in updateLicenses task (gradle #gradleVersion)"() { 133 | given: 134 | def projectDir = temporaryFolder.newFolder() 135 | def sourceDir = projectDir.toPath().resolve(Paths.get("src", "main", "java", "com", "example")).toFile() 136 | sourceDir.mkdirs() 137 | new File(projectDir, "header.txt") << "New copyright header" 138 | new File(projectDir, "settings.gradle") << "" 139 | new File(projectDir, "build.gradle") << """ 140 | plugins { 141 | id('java') 142 | id('org.cadixdev.licenser') 143 | } 144 | 145 | license { 146 | lineEnding = '\\n' 147 | header = project.file('header.txt') 148 | skipExistingHeaders = true 149 | } 150 | """.stripIndent() 151 | def sourceFileContent = """\ 152 | /* 153 | * Existing copyright header 154 | */ 155 | 156 | package com.example; 157 | 158 | class MyClass {} 159 | """.stripIndent() 160 | def sourceFile = new File(sourceDir, "MyClass.java") << sourceFileContent 161 | 162 | when: 163 | def result = runner(projectDir, gradleVersion, extraArgs + "updateLicenses").build() 164 | 165 | then: 166 | result.task(":updateLicenses").outcome == TaskOutcome.UP_TO_DATE 167 | sourceFile.text == sourceFileContent 168 | 169 | where: 170 | [gradleVersion, _, extraArgs] << testMatrix 171 | } 172 | 173 | @Unroll 174 | def "updates invalid headers in updateLicenses task when skipExistingHeaders=true (gradle #gradleVersion)"() { 175 | given: 176 | def projectDir = temporaryFolder.newFolder() 177 | def sourceDir = projectDir.toPath().resolve(Paths.get("src", "main", "java", "com", "example")).toFile() 178 | sourceDir.mkdirs() 179 | new File(projectDir, "header.txt") << "New copyright header" 180 | new File(projectDir, "settings.gradle") << "" 181 | new File(projectDir, "build.gradle") << """ 182 | plugins { 183 | id('java') 184 | id('org.cadixdev.licenser') 185 | } 186 | 187 | license { 188 | lineEnding = '\\n' 189 | header = project.file('header.txt') 190 | skipExistingHeaders = true 191 | } 192 | """.stripIndent() 193 | def sourceFileContent = """\ 194 | // 195 | // Existing copyright header 196 | // 197 | 198 | package com.example; 199 | 200 | class MyClass {} 201 | """.stripIndent() 202 | def sourceFile = new File(sourceDir, "MyClass.java") << sourceFileContent 203 | 204 | when: 205 | def runner = runner(projectDir, gradleVersion, extraArgs + "updateLicenses") 206 | runner.debug = true 207 | def result = runner.build() 208 | 209 | then: 210 | result.task(":updateLicenses").outcome == TaskOutcome.SUCCESS 211 | sourceFile.text == """\ 212 | /* 213 | * New copyright header 214 | */ 215 | 216 | // 217 | // Existing copyright header 218 | // 219 | 220 | package com.example; 221 | 222 | class MyClass {} 223 | """.stripIndent() 224 | 225 | where: 226 | [gradleVersion, _, extraArgs] << testMatrix 227 | } 228 | 229 | @Unroll 230 | def "can run licenseFormat task (gradle #gradleVersion)"() { 231 | given: 232 | def projectDir = temporaryFolder.newFolder() 233 | new File(projectDir, "settings.gradle") << "" 234 | new File(projectDir, "build.gradle") << """ 235 | plugins { 236 | id('org.cadixdev.licenser') 237 | } 238 | """.stripIndent() 239 | 240 | when: 241 | def result = runner(projectDir, gradleVersion, extraArgs + "licenseFormat").build() 242 | 243 | then: 244 | result.output.contains("Task :updateLicenses UP-TO-DATE") 245 | result.output.contains("Task :licenseFormat UP-TO-DATE") 246 | result.task(":updateLicenses").outcome == TaskOutcome.UP_TO_DATE 247 | result.task(":licenseFormat").outcome == TaskOutcome.UP_TO_DATE 248 | 249 | where: 250 | [gradleVersion, _, extraArgs] << testMatrix 251 | } 252 | 253 | @Unroll 254 | def "supports custom source sets task (gradle #gradleVersion)"() { 255 | given: 256 | def projectDir = temporaryFolder.newFolder() 257 | new File(projectDir, "settings.gradle") << "" 258 | new File(projectDir, "build.gradle") << """ 259 | plugins { 260 | id('org.cadixdev.licenser') 261 | id('java') 262 | } 263 | sourceSets { 264 | mySourceSet {} 265 | } 266 | """.stripIndent() 267 | 268 | when: 269 | def result = runner(projectDir, gradleVersion, extraArgs + "licenseCheck").build() 270 | 271 | then: 272 | result.task(":checkLicenseMySourceSet").outcome == TaskOutcome.NO_SOURCE 273 | 274 | where: 275 | [gradleVersion, _, extraArgs] << testMatrix 276 | } 277 | 278 | @Unroll 279 | def "supports custom style (gradle #gradleVersion)"() { 280 | given: 281 | def projectDir = temporaryFolder.newFolder() 282 | def sourcesDir = new File(projectDir, "sources") 283 | sourcesDir.mkdirs() 284 | new File(projectDir, "settings.gradle") << "" 285 | new File(projectDir, "header.txt") << "Copyright header" 286 | def sourceFile = new File(sourcesDir, "source.c") << "TEST" 287 | new File(projectDir, "build.gradle") << """ 288 | plugins { 289 | id('org.cadixdev.licenser') 290 | } 291 | 292 | license { 293 | lineEnding = '\\n' 294 | header = project.file("header.txt") 295 | newLine = false 296 | style { 297 | c = 'BLOCK_COMMENT' 298 | } 299 | tasks { 300 | sources { 301 | files.from("sources") 302 | include("**/*.c") 303 | } 304 | } 305 | } 306 | """.stripIndent() 307 | 308 | when: 309 | def runner = runner(projectDir, gradleVersion, extraArgs + "updateLicenses") 310 | runner.debug = true 311 | def result = runner.build() 312 | 313 | then: 314 | result.task(":updateLicenseCustomSources").outcome == TaskOutcome.SUCCESS 315 | sourceFile.text == """\ 316 | /* 317 | * Copyright header 318 | */ 319 | TEST 320 | """.stripIndent() 321 | 322 | where: 323 | [gradleVersion, _, extraArgs] << testMatrix 324 | } 325 | 326 | @Unroll 327 | def "license formatting configuration is configuration-cacheable (gradle #gradleVersion)"() { 328 | given: 329 | def projectDir = temporaryFolder.newFolder() 330 | new File(projectDir, "settings.gradle") << "" 331 | new File(projectDir, "build.gradle") << """ 332 | plugins { 333 | id('org.cadixdev.licenser') 334 | } 335 | """.stripIndent() 336 | 337 | when: 338 | def result = runner(projectDir, gradleVersion, extraArgs + "licenseFormat").build() 339 | 340 | then: 341 | result.output.contains("Configuration cache entry stored") 342 | 343 | when: 344 | def resultCached = runner(projectDir, gradleVersion, extraArgs + "licenseFormat").build() 345 | 346 | then: 347 | resultCached.output.contains("Reusing configuration cache") 348 | resultCached.task(":licenseFormat").outcome == TaskOutcome.UP_TO_DATE 349 | 350 | 351 | where: 352 | [gradleVersion, _, extraArgs] << configurationCacheTestMatrix 353 | } 354 | 355 | @Unroll 356 | def "supports Android source sets (gradle #gradleVersion)"() { 357 | given: 358 | def projectDir = temporaryFolder.newFolder() 359 | new File(projectDir, "settings.gradle") << "" 360 | new File(projectDir, "build.gradle") << """ 361 | buildscript { 362 | repositories { 363 | google() 364 | } 365 | 366 | dependencies { 367 | classpath 'com.android.tools.build:gradle:$androidVersion' 368 | } 369 | } 370 | 371 | plugins { 372 | id('org.cadixdev.licenser') 373 | } 374 | apply plugin: 'com.android.application' 375 | 376 | android { 377 | compileSdkVersion 30 378 | buildToolsVersion '30.0.1' 379 | defaultConfig { 380 | applicationId 'org.gradle.samples' 381 | minSdkVersion 16 382 | targetSdkVersion 30 383 | versionCode 1 384 | versionName '1.0' 385 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 386 | } 387 | } 388 | """.stripIndent() 389 | 390 | when: 391 | def result = runner(projectDir, gradleVersion, extraArgs + "licenseCheck").build() 392 | 393 | then: 394 | result.task(":checkLicenseAndroidMain").outcome == TaskOutcome.NO_SOURCE 395 | result.task(":checkLicenseAndroidRelease").outcome == TaskOutcome.NO_SOURCE 396 | result.task(":checkLicenseAndroidTest").outcome == TaskOutcome.NO_SOURCE 397 | 398 | where: 399 | [gradleVersion, androidVersion, extraArgs] << testMatrix.findAll { it[1 /* androidVersion */] != null } 400 | } 401 | 402 | @Unroll 403 | def "supports Kotlin buildscripts (gradle #gradleVersion)"() { 404 | given: 405 | def projectDir = temporaryFolder.newFolder() 406 | def sourceDir = projectDir.toPath().resolve(Paths.get("src", "main", "java", "com", "example")).toFile() 407 | sourceDir.mkdirs() 408 | new File(projectDir, "header.txt") << 'New copyright header for ${project}' 409 | new File(projectDir, "settings.gradle.kts") << "" 410 | new File(projectDir, "build.gradle.kts") << """ 411 | plugins { 412 | java 413 | id("org.cadixdev.licenser") 414 | } 415 | 416 | license { 417 | lineEnding("\\n") 418 | header("header.txt") 419 | properties { 420 | this["project"] = "AirhornPowered" 421 | } 422 | } 423 | """.stripIndent() 424 | def sourceFileContent = """\ 425 | package com.example; 426 | 427 | class MyClass {} 428 | """.stripIndent() 429 | def sourceFile = new File(sourceDir, "MyClass.java") << sourceFileContent 430 | 431 | when: 432 | def runner = runner(projectDir, gradleVersion, extraArgs + "updateLicenses") 433 | runner.debug = true 434 | def result = runner.build() 435 | 436 | then: 437 | result.task(":updateLicenses").outcome == TaskOutcome.SUCCESS 438 | sourceFile.text == """\ 439 | /* 440 | * New copyright header for AirhornPowered 441 | */ 442 | 443 | package com.example; 444 | 445 | class MyClass {} 446 | """.stripIndent() 447 | 448 | where: 449 | [gradleVersion, _, extraArgs] << testMatrix 450 | 451 | } 452 | } 453 | --------------------------------------------------------------------------------