├── .gitignore ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── scripts │ ├── gradle_publish_buildscript.gradle │ ├── gradle_publish.gradle │ └── maven_publish.gradle ├── src └── main │ ├── resources │ └── META-INF │ │ └── gradle-plugins │ │ └── com.alexvasilkov.git-dependencies.properties │ └── groovy │ └── com │ └── alexvasilkov │ └── gradle │ └── git │ ├── EmptyExtension.groovy │ ├── utils │ ├── Log.groovy │ ├── SshSystemReader.groovy │ ├── IdeaUtils.groovy │ └── GitUtils.groovy │ ├── Dependencies.groovy │ ├── SettingsExtension.groovy │ ├── Credentials.groovy │ ├── GitDependency.groovy │ └── SettingsPlugin.groovy ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | *.iml 5 | local.properties -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexvasilkov/GradleGitDependenciesPlugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/META-INF/gradle-plugins/com.alexvasilkov.git-dependencies.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.alexvasilkov.gradle.git.SettingsPlugin 2 | -------------------------------------------------------------------------------- /gradle/scripts/gradle_publish_buildscript.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | maven { url 'https://plugins.gradle.org/m2/' } 3 | } 4 | dependencies { 5 | classpath 'com.gradle.publish:plugin-publish-plugin:0.11.0' 6 | } 7 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/EmptyExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git 2 | 3 | class EmptyExtension { 4 | // Ignoring all method calls 5 | def methodMissing(String name, def args) {} 6 | } 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip 6 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/utils/Log.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git.utils 2 | 3 | import org.gradle.api.logging.Logger 4 | import org.gradle.api.logging.Logging 5 | 6 | class Log { 7 | 8 | private static final Logger logger = Logging.getLogger("git-dependencies-plugin") 9 | 10 | private Log() {} 11 | 12 | static void info(String msg) { 13 | logger.lifecycle("Git dependency: $msg") 14 | } 15 | 16 | static void warn(String msg) { 17 | logger.warn("Git dependency: $msg") 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /gradle/scripts/gradle_publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.gradle.plugin-publish' 2 | 3 | pluginBundle { 4 | website = project.ext.github 5 | vcsUrl = project.ext.github 6 | 7 | plugins { 8 | gitDependencies { 9 | id = 'com.alexvasilkov.git-dependencies' 10 | version = project.ext.version 11 | displayName = project.ext.name 12 | description = project.ext.description 13 | tags = ['git', 'dependency'] 14 | } 15 | } 16 | 17 | mavenCoordinates { 18 | groupId = project.ext.group 19 | artifactId = project.ext.artifactId 20 | version = project.ext.version 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/Dependencies.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git 2 | 3 | import com.alexvasilkov.gradle.git.utils.GitUtils 4 | import com.alexvasilkov.gradle.git.utils.Log 5 | 6 | class Dependencies { 7 | 8 | private final Map byName = new HashMap<>() 9 | private final Map> byProject = new HashMap<>() 10 | 11 | void add(String projectName, GitDependency dependency) { 12 | // Checking if there are no dependencies with same name, 13 | // or if existing dependency is completely the same 14 | GitDependency existing = byName.get(dependency.name) 15 | 16 | if (existing != null) { 17 | existing.checkEquals(dependency) 18 | } else { 19 | byName.put(dependency.name, dependency) 20 | } 21 | 22 | if (projectName == null) { 23 | Log.info "Added '${dependency.name}'" 24 | } else { 25 | // Adding per-project dependency 26 | List list = byProject.get(projectName) 27 | if (list == null) { 28 | list = new ArrayList() 29 | byProject.put(projectName, list) 30 | } 31 | list.add(dependency) 32 | 33 | Log.info "Added '${dependency.name}' for '$projectName'" 34 | } 35 | 36 | GitUtils.init(dependency) 37 | } 38 | 39 | List get(String projectName) { 40 | return byProject.get(projectName) ?: Collections.EMPTY_LIST 41 | } 42 | 43 | Collection all() { 44 | return byName.values() 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/SettingsExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git 2 | 3 | import org.gradle.api.initialization.Settings 4 | 5 | class SettingsExtension { 6 | 7 | private final Closure dependencyAction 8 | final File rootDir 9 | 10 | File dir 11 | String defaultAuthGroup 12 | boolean cleanup 13 | boolean cleanupIdeaModules 14 | 15 | SettingsExtension(Settings settings, Closure dependencyAction) { 16 | this.dependencyAction = dependencyAction 17 | this.rootDir = settings.rootDir 18 | // Setting default values: 19 | this.dir = new File(settings.rootDir, 'libs') 20 | this.defaultAuthGroup = null 21 | this.cleanup = true 22 | this.cleanupIdeaModules = true 23 | } 24 | 25 | void apply(Closure closure) { 26 | final Collector collector = new Collector() 27 | closure.rehydrate(collector, collector, collector).call() 28 | } 29 | 30 | @SuppressWarnings("unused") 31 | class Collector { 32 | void dir(def dir) { 33 | if (!dir) throw new NullPointerException("Git dependency: 'dir' cannot be null") 34 | SettingsExtension.this.dir = dir as File 35 | } 36 | 37 | void defaultAuthGroup(String authGroup) { 38 | SettingsExtension.this.defaultAuthGroup = authGroup 39 | } 40 | 41 | void cleanup(boolean cleanup) { 42 | SettingsExtension.this.cleanup = cleanup 43 | } 44 | 45 | void cleanupIdeaModules(boolean cleanup) { 46 | SettingsExtension.this.cleanupIdeaModules = cleanup 47 | } 48 | 49 | void fetch(String url, Closure closure = null) { 50 | dependencyAction(url, closure) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/utils/SshSystemReader.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git.utils 2 | 3 | import org.eclipse.jgit.util.SystemReader 4 | 5 | import java.nio.file.Files 6 | import java.nio.file.Path 7 | import java.nio.file.Paths 8 | import java.util.regex.Pattern 9 | 10 | // Based on https://github.com/ajoberstar/grgit/blob/1a1c6b7/grgit-core/src/main/groovy/org/ajoberstar/grgit/auth/GrgitSystemReader.java 11 | class SshSystemReader extends SystemReader { 12 | 13 | @Delegate 14 | private final SystemReader delegate 15 | 16 | private final String gitSsh 17 | 18 | private SshSystemReader(SystemReader delegate, String gitSsh) { 19 | this.delegate = delegate 20 | this.gitSsh = gitSsh 21 | } 22 | 23 | @Override 24 | String getenv(String variable) { 25 | String value = delegate.getenv(variable) 26 | if ('GIT_SSH' == variable && value == null) { 27 | return gitSsh 28 | } else { 29 | return value 30 | } 31 | } 32 | 33 | static void install() { 34 | final SystemReader current = instance 35 | if (current instanceof SshSystemReader) return 36 | 37 | final String gitSsh = findExecutable("ssh") ?: findExecutable("plink") 38 | instance = new SshSystemReader(current, gitSsh) 39 | } 40 | 41 | private static String findExecutable(String exe) { 42 | final String path = System.getenv('PATH') ?: '' 43 | final String pathExt = System.getenv('PATHEXT') ?: '' 44 | final Pattern splitter = Pattern.compile(Pattern.quote(File.pathSeparator)) 45 | 46 | final String[] extensions = splitter.split(pathExt) 47 | final List withExt = 48 | extensions.length == 0 ? [exe] : extensions.collect { ext -> exe + ext } 49 | 50 | return splitter.split(path).findResult { 51 | final Path dir = Paths.get(it) 52 | withExt.findResult { 53 | final Path exePath = dir.resolve(it) 54 | Files.isExecutable(exePath) ? exePath.toAbsolutePath().toString() : null 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /gradle/scripts/maven_publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | apply plugin: 'signing' 3 | 4 | task pluginGroovydoc(type: Groovydoc) { 5 | source = sourceSets.main.groovy.srcDirs 6 | classpath = sourceSets.main.compileClasspath 7 | } 8 | 9 | task pluginGroovydocJar(type: Jar, dependsOn: pluginGroovydoc) { 10 | archiveClassifier.set('javadoc') // Required to be named 'javadoc' for Maven Central 11 | from pluginGroovydoc.destinationDir 12 | } 13 | 14 | task pluginSourcesJar(type: Jar) { 15 | archiveClassifier.set('sources') 16 | from sourceSets.main.allGroovy 17 | } 18 | 19 | publishing { 20 | publications { 21 | mavenJava(MavenPublication) { 22 | from components.java 23 | artifact source: pluginGroovydocJar, classifier: 'javadoc' 24 | artifact source: pluginSourcesJar, classifier: 'sources' 25 | 26 | groupId = project.ext.group 27 | artifactId = project.ext.artifactId 28 | version = project.ext.version 29 | 30 | pom { 31 | name = project.ext.name 32 | description = project.ext.description 33 | packaging = 'jar' 34 | url = project.ext.github 35 | licenses { 36 | license { 37 | name = 'The Apache License, Version 2.0' 38 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 39 | } 40 | } 41 | developers { 42 | developer { 43 | id = 'alexvasilkov' 44 | name = 'Alex Vasilkov' 45 | } 46 | } 47 | scm { 48 | connection = project.ext.githubScm 49 | developerConnection = project.ext.githubScm 50 | url = project.ext.github 51 | } 52 | } 53 | } 54 | } 55 | repositories { 56 | maven { 57 | def releasesRepoUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/' 58 | def snapshotsRepoUrl = 'https://oss.sonatype.org/content/repositories/snapshots/' 59 | url = project.ext.version.contains('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 60 | credentials { 61 | username = findProperty('maven.alexvasilkov.username') 62 | password = findProperty('maven.alexvasilkov.password') 63 | } 64 | } 65 | } 66 | } 67 | 68 | signing { 69 | required { gradle.taskGraph.hasTask('publish') } 70 | 71 | sign publishing.publications.mavenJava 72 | 73 | // We need to re-map singing properties to be able to mix properties for different projects 74 | project.ext.'signing.keyId' = findProperty('signing.alexvasilkov.keyId') 75 | project.ext.'signing.password' = findProperty('signing.alexvasilkov.password') 76 | } 77 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/Credentials.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git 2 | 3 | class Credentials { 4 | 5 | private static final USERNAME = 'username' 6 | private static final PASSWORD = 'password' 7 | 8 | private final File userDir 9 | private Properties gradleProps 10 | private Properties gradleUserProps 11 | private Properties localProps 12 | 13 | Credentials(File gradleUserHomeDir) { 14 | userDir = gradleUserHomeDir 15 | 16 | File gradleFile = new File('gradle.properties') 17 | if (gradleFile.exists()) { 18 | gradleProps = new Properties() 19 | gradleFile.withInputStream { stream -> gradleProps.load(stream) } 20 | } 21 | 22 | File gradleUserFile = new File(userDir, 'gradle.properties') 23 | if (gradleUserFile.exists()) { 24 | gradleUserProps = new Properties() 25 | gradleUserFile.withInputStream { stream -> gradleUserProps.load(stream) } 26 | } 27 | 28 | File localFile = new File('local.properties') 29 | if (localFile.exists()) { 30 | localProps = new Properties() 31 | localFile.withInputStream { stream -> localProps.load(stream) } 32 | } 33 | } 34 | 35 | private static String name(String authGroup, String suffix) { 36 | return "git.$authGroup.$suffix" 37 | } 38 | 39 | String username(String authGroup) { 40 | return get(authGroup, USERNAME) 41 | } 42 | 43 | String password(String authGroup) { 44 | return get(authGroup, PASSWORD) 45 | } 46 | 47 | private String get(String authGroup, String suffix) { 48 | if (!authGroup) return null 49 | String name = name(authGroup, suffix) 50 | return System.getProperty(name) ?: 51 | gradleProps?.getProperty(name) ?: 52 | localProps?.getProperty(name) ?: 53 | gradleUserProps?.getProperty(name) ?: 54 | System.getenv().get(name.replace('.', '_').toUpperCase()) 55 | } 56 | 57 | String usernameHelp(String authGroup) { 58 | return help(authGroup, USERNAME) 59 | } 60 | 61 | String passwordHelp(String authGroup) { 62 | return help(authGroup, PASSWORD) 63 | } 64 | 65 | private String help(String authGroup, String suffix) { 66 | if (authGroup == null) { 67 | return "" 68 | } else { 69 | String name = name(authGroup, suffix) 70 | return "You should provide '$name'" + 71 | " as command line argument (-D$name=...) OR" + 72 | " in gradle.properties OR" + 73 | " in local.properties OR" + 74 | " in ${userDir.absolutePath}/gradle.properties OR" + 75 | " as environment variable (${name.replace('.', '_').toUpperCase()})." 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/utils/IdeaUtils.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git.utils 2 | 3 | import com.alexvasilkov.gradle.git.Dependencies 4 | import com.alexvasilkov.gradle.git.GitDependency 5 | 6 | import java.nio.file.Paths 7 | import java.util.regex.Matcher 8 | import java.util.regex.Pattern 9 | 10 | class IdeaUtils { 11 | 12 | private IdeaUtils() {} 13 | 14 | static void cleanModules(File rootDir, Dependencies dependencies) { 15 | try { 16 | cleanModulesInternal(rootDir, dependencies) 17 | } catch (Exception ex) { 18 | Log.warn "Cannot clean up .idea/modules.xml file. ${ex.message}" 19 | } 20 | } 21 | 22 | private static void cleanModulesInternal(File rootDir, Dependencies dependencies) { 23 | final File modules = new File(new File(rootDir, '.idea'), 'modules.xml') 24 | if (!modules.exists() || !modules.isFile()) return 25 | 26 | final List modulesLines = modules.readLines() 27 | 28 | // Finding module entries and reading module path and .iml file name 29 | final Pattern pattern = Pattern.compile( 30 | '\\s* 64 | File file = new File(dep.projectDir, fileName) 65 | if (file.exists()) { 66 | Log.info "Deleting file $path/$fileName" 67 | file.delete() 68 | } 69 | } 70 | pathsToDelete.add(path) 71 | } 72 | } 73 | } 74 | 75 | // Rewriting modules file excluding invalid modules detected above 76 | if (!pathsToDelete.isEmpty()) { 77 | modules.withWriter { BufferedWriter writer -> 78 | modulesLines.eachWithIndex { String line, int pos -> 79 | String path = moduleLinesPaths[pos] 80 | boolean writeLine = path == null || !pathsToDelete.contains(path) 81 | if (writeLine) writer.writeLine(line) 82 | } 83 | } 84 | } 85 | } 86 | 87 | private static String getRelativePath(File root, File dir) { 88 | return Paths.get(root.absolutePath).relativize(Paths.get(dir.absolutePath)).toString() 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/GitDependency.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git 2 | 3 | import org.gradle.api.GradleException 4 | 5 | import java.util.regex.Matcher 6 | 7 | class GitDependency { 8 | 9 | final String configName 10 | final String url 11 | final String name 12 | final String commit 13 | final String projectPath 14 | final File dir 15 | final String authGroup 16 | final boolean needsAuth 17 | final String username 18 | final String password 19 | final boolean keepUpdated 20 | 21 | final String projectName 22 | final File projectDir 23 | 24 | GitDependency(SettingsExtension props, Credentials credentials, Builder builder) { 25 | configName = builder.configName 26 | url = builder.url 27 | name = builder.name ?: getNameFromUrl(url) 28 | commit = builder.commit ?: 'master' 29 | projectPath = builder.projectPath 30 | dir = builder.dir ?: (name != null ? new File(props.dir, name) : null) 31 | authGroup = builder.authGroup ?: props.defaultAuthGroup 32 | needsAuth = authGroup || builder.username || builder.password 33 | username = needsAuth ? (builder.username ?: credentials.username(authGroup)) : null 34 | password = needsAuth ? (builder.password ?: credentials.password(authGroup)) : null 35 | keepUpdated = builder.keepUpdated == null ? true : builder.keepUpdated 36 | 37 | projectName = ":$name" 38 | projectDir = projectPath == null || dir == null ? dir : new File(dir, projectPath) 39 | 40 | if (!url) { 41 | throw new GradleException("Git dependency: 'url' is not specified") 42 | } 43 | if (!name) { 44 | throw new GradleException("Git dependency: 'name' is not specified") 45 | } 46 | if (dir.exists() && !dir.isDirectory()) { 47 | throw new GradleException("Git dependency: 'dir' is not a directory '${dir.path}'") 48 | } 49 | if (needsAuth && !username) { 50 | throw new GradleException("Git dependency: 'username' is not specified for '${name}'." + 51 | "\n${credentials.usernameHelp(authGroup)}") 52 | } 53 | if (needsAuth && !password) { 54 | throw new GradleException("Git dependency: 'password' is not specified for '${name}'." + 55 | "\n${credentials.passwordHelp(authGroup)}") 56 | } 57 | } 58 | 59 | private static String getNameFromUrl(String url) { 60 | if (url == null) return null 61 | // Splitting last url's part before ".git" suffix 62 | Matcher matcher = url =~ /([^\/]+)\.git$/ 63 | return matcher.find() ? matcher[0][1] : null 64 | } 65 | 66 | void checkEquals(GitDependency dep) { 67 | if (dep.url != url) throwEqualCheckFail('url', url, dep.url) 68 | if (dep.name != name) throwEqualCheckFail('name', name, dep.name) 69 | if (dep.commit != commit) throwEqualCheckFail('commit', commit, dep.commit) 70 | if (dep.projectPath != projectPath) throwEqualCheckFail('path', projectPath, s.projectPath) 71 | if (!Objects.equals(dep.dir, dir)) throwEqualCheckFail('dir', dir.path, dep.dir.path) 72 | if (dep.username != username) throwEqualCheckFail('username', username, dep.username) 73 | if (dep.password != password) throwEqualCheckFail('passwords', '***', '***') 74 | } 75 | 76 | private void throwEqualCheckFail(String paramName, Object val1, Object val2) { 77 | throw new GradleException("Git dependency: Found 2 incompatible '$name' dependencies" + 78 | " with different '$paramName' values: '$val1' and '$val2'") 79 | } 80 | 81 | @SuppressWarnings("unused") 82 | static class Builder { 83 | private final String configName 84 | private final String url 85 | 86 | private String name 87 | private String commit 88 | private String projectPath 89 | private File dir 90 | private String authGroup 91 | private String username 92 | private String password 93 | private Boolean keepUpdated 94 | 95 | Builder(String configName, String url) { 96 | this.configName = configName 97 | this.url = url 98 | } 99 | 100 | void name(String name) { 101 | this.name = name 102 | } 103 | 104 | void commit(String commit) { 105 | this.commit = commit 106 | } 107 | 108 | void branch(String branch) { 109 | this.commit = branch 110 | } 111 | 112 | void tag(String tag) { 113 | this.commit = tag 114 | } 115 | 116 | void projectPath(String path) { 117 | this.projectPath = path 118 | } 119 | 120 | void dir(def dir) { 121 | this.dir = dir as File 122 | } 123 | 124 | void authGroup(String authGroup) { 125 | this.authGroup = authGroup 126 | } 127 | 128 | void username(String username) { 129 | this.username = username 130 | } 131 | 132 | void password(String password) { 133 | this.password = password 134 | } 135 | 136 | void keepUpdated(boolean keepUpdated) { 137 | this.keepUpdated = keepUpdated 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/utils/GitUtils.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git.utils 2 | 3 | import com.alexvasilkov.gradle.git.GitDependency 4 | import org.eclipse.jgit.api.Git 5 | import org.eclipse.jgit.api.Status 6 | import org.eclipse.jgit.errors.RepositoryNotFoundException 7 | import org.eclipse.jgit.lib.Constants 8 | import org.eclipse.jgit.lib.ObjectId 9 | import org.eclipse.jgit.lib.Ref 10 | import org.eclipse.jgit.transport.CredentialsProvider 11 | import org.eclipse.jgit.transport.JschConfigSessionFactory 12 | import org.eclipse.jgit.transport.SshSessionFactory 13 | import org.eclipse.jgit.transport.TagOpt 14 | import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider 15 | import org.gradle.api.GradleException 16 | 17 | class GitUtils { 18 | 19 | private GitUtils() {} 20 | 21 | static void init(GitDependency dep) { 22 | // For SSH to work with JGit 5.8+ we have to manually set the SSH factory because default 23 | // ServiceLoader mechanism does not seem to work with Gradle plugins. 24 | SshSessionFactory.instance = new JschConfigSessionFactory() 25 | 26 | // Jsch does not really work well so we'd better rely on system "ssh" command. 27 | // To do so we'll manually try to find "ssh" in local PATH and set it as "GIT_SSH" for Jgit. 28 | SshSystemReader.install() 29 | 30 | final Git git = openGit(dep) 31 | 32 | if (git != null) { 33 | final String remoteUrl = remoteUrl(git) 34 | 35 | if (remoteUrl == null || remoteUrl != dep.url) { 36 | throw new GradleException("Git cannot update from ${remoteUrl} to ${dep.url}.\n" + 37 | "Delete directory '${dep.dir}' and try again.") 38 | } 39 | 40 | final String targetCommit = dep.commit 41 | 42 | if (dep.keepUpdated && !isLocalCommit(git, targetCommit)) { 43 | final String localCommit = head(git).substring(0, 7) 44 | Log.warn "Local version '${localCommit}' is not equal to target " + 45 | "'${targetCommit}' for '${dep.dir}'" 46 | 47 | if (hasLocalChanges(git)) { 48 | throw new GradleException("Git repo cannot be updated to '${targetCommit}', " + 49 | "'${dep.dir}' contains local changes.\n" + 50 | "Commit or revert all changes manually.") 51 | } else { 52 | Log.warn "Updating to version '${targetCommit}' for '${dep.dir}'" 53 | update(git, dep) 54 | } 55 | } 56 | } else { 57 | clone(dep) 58 | } 59 | } 60 | 61 | private static Git openGit(GitDependency dep) { 62 | try { 63 | return Git.open(dep.dir) 64 | } catch (RepositoryNotFoundException ignored) { 65 | return null 66 | } 67 | } 68 | 69 | private static String remoteUrl(Git git) { 70 | return git.repository.config.getString('remote', Constants.DEFAULT_REMOTE_NAME, 'url') 71 | } 72 | 73 | private static String head(Git git) { 74 | return ObjectId.toString(git.repository.resolve('HEAD')) 75 | } 76 | 77 | private static boolean isLocalCommit(Git git, String targetId) { 78 | // Checking if local commit is equal to (starts with) requested one. 79 | final String headId = head(git) 80 | if (headId.startsWith(targetId)) return true 81 | 82 | // If not then we should check if there is a tag with given name pointing to current head. 83 | final Ref tag = git.repository.refDatabase.exactRef(Constants.R_TAGS + targetId) 84 | // Annotated tags need extra effort 85 | final Ref peeledTag = tag == null ? null : git.repository.refDatabase.peel(tag) 86 | final tagObjectId = peeledTag?.peeledObjectId ?: tag?.objectId 87 | 88 | final String tagId = ObjectId.toString(tagObjectId) 89 | return tagId == headId 90 | } 91 | 92 | private static boolean hasLocalChanges(Git git) { 93 | final Status status = git.status().call() 94 | final List changes = new ArrayList<>() 95 | changes.addAll(status.added) 96 | changes.addAll(status.changed) 97 | changes.addAll(status.removed) 98 | changes.addAll(status.untracked) 99 | changes.addAll(status.modified) 100 | changes.addAll(status.missing) 101 | return !changes.isEmpty() 102 | } 103 | 104 | static boolean hasLocalChangesInDir(File dir) { 105 | try { 106 | return hasLocalChanges(Git.open(dir)) 107 | } catch (RepositoryNotFoundException ignored) { 108 | return false 109 | } 110 | } 111 | 112 | private static void update(Git git, GitDependency dep) { 113 | final long start = System.currentTimeMillis() 114 | Log.info "Update started '${dep.url}' at version '${dep.commit}'" 115 | 116 | git.fetch() 117 | .setTagOpt(TagOpt.FETCH_TAGS) 118 | .setCredentialsProvider(creds(dep)) 119 | .call() 120 | 121 | git.checkout().setName(dep.commit).call() 122 | 123 | final long spent = System.currentTimeMillis() - start 124 | Log.info "Update finished ($spent ms)" 125 | } 126 | 127 | private static void clone(GitDependency dep) { 128 | final long start = System.currentTimeMillis() 129 | Log.info "Clone started '${dep.url}' at version '${dep.commit}'" 130 | 131 | final Git git = Git.cloneRepository() 132 | .setDirectory(dep.dir) 133 | .setURI(dep.url) 134 | .setRemote('origin') 135 | .setNoCheckout(true) 136 | .setCredentialsProvider(creds(dep)) 137 | .call() 138 | 139 | git.checkout().setName(dep.commit).call() 140 | 141 | final long spent = System.currentTimeMillis() - start 142 | Log.info "Clone finished ($spent ms)" 143 | } 144 | 145 | private static CredentialsProvider creds(GitDependency dep) { 146 | return dep.needsAuth 147 | ? new UsernamePasswordCredentialsProvider(dep.username, dep.password) : null 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GradleGitDependencies 2 | ===================== 3 | 4 | [![Maven Central][mvn-img]][mvn-url] 5 | 6 | Gradle plugin to add external git repositories as dependencies. 7 | 8 | ### Setup ### 9 | 10 | In `settings.gradle` file add the following lines: 11 | 12 | * If using Gradle 6.x.x 13 | 14 | ``` 15 | plugins { 16 | id 'com.alexvasilkov.git-dependencies' version '2.0.4' 17 | } 18 | ``` 19 | 20 | * If using older Gradle version 21 | 22 | ``` 23 | buildscript { 24 | repositories { 25 | mavenCentral() 26 | } 27 | dependencies { 28 | classpath 'com.alexvasilkov:gradle-git-dependencies:2.0.4' 29 | } 30 | } 31 | 32 | apply plugin: 'com.alexvasilkov.git-dependencies' 33 | ``` 34 | 35 | Optionally you can provide settings next in `settings.gradle`: 36 | 37 | ``` 38 | git { 39 | dir 'libs' // Directory in which to store git repositories, 'libs' by default 40 | cleanup true // Whether to cleanup unused dirs inside 'libs' dir, true by default 41 | defaultAuthGroup 'group name' // Default auth group to be used for all repos. See `Credentials` section below. 42 | } 43 | ``` 44 | 45 | ### Usage ### 46 | 47 | **Note that the plugin only works with Groovy scripts, no Kotlin DSL support is available yet.** 48 | 49 | Now in module's `build.gradle` add the following: 50 | 51 | ``` 52 | git { 53 | implementation 'https://example.com/repository.git', { 54 | name 'DependencyName' 55 | commit '12345678abcdefgh' 56 | } 57 | } 58 | ``` 59 | 60 | Where `implementation` is a configuration name, similar as used for regular gradle dependencies. 61 | Can be any valid configuration name. 62 | 63 | #### Supported parameters #### 64 | 65 | | Parameter | Description | 66 | | --------------- | ----------- | 67 | | name | Dependency name. Will be used as gradle project name and as repo directory name. If the name is not set then it will be taken from url. | 68 | | commit | Git commit id of any length, tag name or full branch name. For example `e628b205`, `v1.2.3`, `origin/master`. | 69 | | tag | Same as `commit`, see above. | 70 | | branch | Same as `commit`, see above. | 71 | | dir | Directory for cloned repository. Used to override default directory as defined in `settings.gradle`. | 72 | | projectPath | Path within repository which should be added as gradle project. By default repo's root directory is added as project. | 73 | | username | Username to access repository. See `Credentials` section below. | 74 | | password | Password to access repository. See `Credentials` section below. | 75 | | authGroup | Group name used when looking for credentials. See `Credentials` section below. | 76 | | keepUpdated | Whether to update this repository automatically or not. Default is `true`. | 77 | 78 | Note that using `master` or any other branch name as git commit is not recommended, 79 | use explicit commit or tag instead. 80 | 81 | 82 | You can also specify git repos in `settings.gradle` similar as it is done in `build.gradle` 83 | but use `fetch` instead of configuration name: 84 | 85 | ``` 86 | git { 87 | fetch 'https://example.com/repository.git', { 88 | dir "$rootDir/gradle/scripts" 89 | tag 'v1.2.3' 90 | } 91 | } 92 | ``` 93 | 94 | Such repositories will be downloaded but not added as dependencies. 95 | This can be useful, for example, if you want to pre-fetch build scripts. 96 | 97 | ### Examples ### 98 | 99 | ``` 100 | git { 101 | implementation 'git@github.com:alexvasilkov/GestureViews.git' 102 | 103 | api 'https://github.com/alexvasilkov/GestureViews.git', { 104 | name 'GestureViews' 105 | tag 'v2.6.0' 106 | projectPath '/library' 107 | } 108 | } 109 | ``` 110 | 111 | ### How it works ### 112 | 113 | 1. You're providing git repository URL and other optional details in `build.gradle` file. 114 | 2. The plugin clones repository to `libs/[name]` directory (both name and directory can be changed) 115 | at specified commit, tag or branch. 116 | 3. Cloned repo will be included as sub-project and defined as dependency of original project. 117 | 4. Dependencies are resolved recursively, i.e. your git dependency can have other git dependencies. 118 | 5. If several projects have dependencies with same name then all other details (url, commit, etc) 119 | should be completely the same, otherwise build process will fail. 120 | 6. The plugin automatically updates repository if `commit` doesn't much local commit. If there're any 121 | uncommited changes in local repo then build process will fail until you manually resolve conflicts. 122 | 7. Removed dependencies will be automatically cleaned from `libs` directory. 123 | 124 | ### Credentials ### 125 | 126 | If git repo is using SSH url (starts with `git@`) then the plugin will automatically try to use 127 | local SSH key. But you need to ensure your SSH key is correctly setup, see instructions for 128 | [GitHub](https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh) 129 | or [Bitbucket](https://confluence.atlassian.com/bitbucket/ssh-keys-935365775.html) 130 | 131 | If git repo is using HTTPS url then there are two options how you can define credentials: 132 | 133 | * Using `username` and `password` options directly in `build.gradle`. 134 | * Using `authGroup` option and providing credentials as specified below. 135 | 136 | If `authGroup` is provided then the plugin will search for `git.[authGroup].username` and 137 | `git.[authGroup].password` params in: 138 | 139 | * command line arguments (e.g. `-Dgit.github.username=email@test.com`) 140 | * gradle.properties 141 | * local.properties 142 | * ~/.gradle/gradle.properties 143 | * environment variables, in uppercase and with `_` instead of `.`, e.g. `GIT_GITHUB_USERNAME` 144 | 145 | If `defaultAuthGroup` is provided in `settings.gradle` then it will be used for all repos 146 | unless `authGroup` is explicitly set. 147 | 148 | ### Migration from v1.x.x ### 149 | 150 | There were several breaking changes since version 1.x.x: 151 | 152 | * Default directory is changed from `libraries` to `libs`. 153 | * Instead of defining `def vcs() { ... }` method you can use simpler `git { ... }` 154 | * Git dependencies declaration is reimplemented to mimic default gradle dependencies section. 155 | * Credentials properties names are changed, e.g. was `GIT_AUTHGROUP_USERNAME`, 156 | become `git.authGroup.username`. 157 | * Dropped SVN support. 158 | 159 | #### License #### 160 | 161 | Licensed under the Apache License, Version 2.0 (the "License"); 162 | you may not use this file except in compliance with the License. 163 | You may obtain a copy of the License at 164 | 165 | http://www.apache.org/licenses/LICENSE-2.0 166 | 167 | Unless required by applicable law or agreed to in writing, software 168 | distributed under the License is distributed on an "AS IS" BASIS, 169 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 170 | See the License for the specific language governing permissions and 171 | limitations under the License. 172 | 173 | [mvn-url]: https://maven-badges.herokuapp.com/maven-central/com.alexvasilkov/gradle-git-dependencies 174 | [mvn-img]: https://img.shields.io/maven-central/v/com.alexvasilkov/gradle-git-dependencies.svg?style=flat-square 175 | -------------------------------------------------------------------------------- /src/main/groovy/com/alexvasilkov/gradle/git/SettingsPlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.alexvasilkov.gradle.git 2 | 3 | import com.alexvasilkov.gradle.git.utils.GitUtils 4 | import com.alexvasilkov.gradle.git.utils.IdeaUtils 5 | import com.alexvasilkov.gradle.git.utils.Log 6 | import org.gradle.api.Plugin 7 | import org.gradle.api.Project 8 | import org.gradle.api.initialization.ProjectDescriptor 9 | import org.gradle.api.initialization.Settings 10 | 11 | import java.nio.file.Paths 12 | import java.util.regex.Matcher 13 | 14 | class SettingsPlugin implements Plugin { 15 | 16 | private static final EXTENSION_NAME = 'git' 17 | 18 | private Settings settings 19 | private SettingsExtension props 20 | private Credentials credentials 21 | private final Dependencies dependencies = new Dependencies() 22 | private final GroovyShell shell = new GroovyShell() 23 | private final Set projectsWithExtension = new HashSet<>() 24 | 25 | void apply(Settings settings) { 26 | this.settings = settings 27 | this.props = new SettingsExtension(settings, { url, closure -> 28 | GitDependency dep = buildDependency(settings, null, url, closure) 29 | dependencies.add(null, dep) 30 | }) 31 | this.credentials = new Credentials(settings.gradle.gradleUserHomeDir) 32 | 33 | // Adding configuration method to collect plugin settings 34 | settings.metaClass."$EXTENSION_NAME" = props.&apply 35 | 36 | settings.gradle.settingsEvaluated { 37 | resolveDependenciesRecursively(settings.projectDescriptorRegistry.allProjects) 38 | cleanup() 39 | } 40 | 41 | // Registering special extension that will ignore our fake extension (which was already 42 | // handled as part of `Settings` evaluation process above) 43 | settings.gradle.beforeProject { Project project -> 44 | // Only adding `empty` extension for the projects where we successfully handled 45 | // the extension during settings evaluation. 46 | if (projectsWithExtension.contains(project.name)) { 47 | project.extensions.create(EXTENSION_NAME, EmptyExtension) 48 | } 49 | } 50 | 51 | // Adding projects dependencies for each project 52 | settings.gradle.afterProject { Project project -> 53 | dependencies.get(project.name).each { GitDependency dep -> 54 | project.dependencies.add(dep.configName, project.project(dep.projectName)) 55 | } 56 | } 57 | } 58 | 59 | void resolveDependenciesRecursively(Set projects) { 60 | Set newlyAddedProjects = new HashSet<>() 61 | 62 | // Building git dependencies list by invoking extension method for each project 63 | projects.each { ProjectDescriptor project -> 64 | Script script = parseBuildScript(project.buildFile) 65 | 66 | if (script != null) { 67 | projectsWithExtension.add(project.name) 68 | 69 | // Defining extra properties to be available in extension script 70 | script.metaClass.project = project 71 | script.metaClass.gradle = settings.gradle 72 | 73 | // Adding method to handle configuration names dynamically 74 | script.metaClass.methodMissing { methodName, args -> 75 | GitDependency dep = buildDependency(script, methodName, args) 76 | dependencies.add(project.name, dep) 77 | } 78 | 79 | // Calling (fake) extension method 80 | script."$EXTENSION_NAME"() 81 | 82 | // Registering new projects 83 | dependencies.get(project.name).each { GitDependency dep -> 84 | if (!settings.findProject(dep.projectName)) { 85 | settings.include(dep.projectName) 86 | ProjectDescriptor depProject = settings.project(dep.projectName) 87 | depProject.projectDir = dep.projectDir 88 | newlyAddedProjects.add(depProject) 89 | } 90 | } 91 | } 92 | } 93 | 94 | // If we have new projects we should process them too 95 | if (newlyAddedProjects) resolveDependenciesRecursively(newlyAddedProjects) 96 | } 97 | 98 | private Script parseBuildScript(File buildFile) { 99 | // We want our extension to appear as regular DSL but at the same time we cannot use 100 | // Gradle's native extensions mechanism because project extensions are handled after 101 | // `Settings` was configured so we won't be able to add dynamic projects anymore. 102 | // Instead we are going to parse projects build scripts manually during settings 103 | // configuration phase. When manually parsing scripts we cannot run regular DSL, like 104 | // `android { ... }`, but we can run methods defined like `def android() {...}`. 105 | // So we have to use a hack: transform DSL call to a method reference directly in sources. 106 | 107 | if (buildFile == null || !buildFile.exists()) return null 108 | 109 | // Reading original script 110 | GroovyCodeSource orig = new GroovyCodeSource(buildFile, 'UTF-8') 111 | 112 | // Checking if we have our extension defined 113 | Matcher matcher = orig.scriptText =~ /(^|\n)([\s\t\n\r]*)($EXTENSION_NAME)([\s\t\n\r]*\{)/ 114 | if (!matcher.find()) return null 115 | 116 | // Replacing extension with method declaration 117 | String fixedScript = matcher.replaceFirst('$1$2def $3()$4') 118 | 119 | // Parsing fixed script 120 | String codeBase = buildFile.toURI().toString() 121 | GroovyCodeSource fixedSource = new GroovyCodeSource(fixedScript, orig.name, codeBase) 122 | Script script = shell.parse(fixedSource) 123 | 124 | // Returning parsed script if it contains expected method 125 | if (script.metaClass.respondsTo(script, EXTENSION_NAME)) { 126 | return script 127 | } else { 128 | return null 129 | } 130 | } 131 | 132 | private GitDependency buildDependency(Object owner, String configName, def args) { 133 | // Handling calls like `implementation 'git url', { dependency config closure }` 134 | 135 | String url 136 | Closure closure = null 137 | 138 | if (args != null && args.length > 0 && args[0] instanceof String) { 139 | url = args[0] 140 | } else { 141 | throw new IllegalArgumentException('Git dependency: Missing git repo URL') 142 | } 143 | 144 | if (args.length > 1) { 145 | if (args[1] instanceof Closure) { 146 | closure = args[1] 147 | } else { 148 | throw new IllegalArgumentException("Git dependency: Config closure is invalid") 149 | } 150 | } 151 | 152 | return buildDependency(owner, configName, url, closure) 153 | } 154 | 155 | private GitDependency buildDependency( 156 | Object owner, String configName, String url, Closure closure 157 | ) { 158 | final GitDependency.Builder builder = new GitDependency.Builder(configName, url) 159 | 160 | if (closure != null) { 161 | // Passing `builder` as delegate and `owner` as owner, to have access to extra 162 | // properties from extension scripts 163 | closure.rehydrate(builder, owner, builder).call() 164 | } 165 | 166 | return new GitDependency(props, credentials, builder) 167 | } 168 | 169 | private void cleanup() { 170 | if (props.cleanup) { 171 | // Cleaning up unused directories 172 | final File libsDir = props.dir 173 | 174 | // Deleting dirs if they're not declared as dependency and don't contain local changes 175 | dirLoop: 176 | for (File dir in libsDir.listFiles()) { 177 | if (!dir.isDirectory()) continue 178 | 179 | for (GitDependency dep in dependencies.all()) { 180 | if (dir == dep.dir) continue dirLoop 181 | } 182 | 183 | String relativePath = Paths.get(libsDir.absolutePath) 184 | .relativize(Paths.get(dir.absolutePath)) 185 | .toString() 186 | 187 | if (GitUtils.hasLocalChangesInDir(dir)) { 188 | Log.warn "Skipping directory deletion for $relativePath" 189 | } else { 190 | Log.warn "Deleting unknown directory $relativePath" 191 | dir.deleteDir() 192 | } 193 | } 194 | 195 | // Removing libs directory if it's empty 196 | if (!libsDir.list()) libsDir.deleteDir() 197 | } 198 | 199 | if (props.cleanupIdeaModules) { 200 | IdeaUtils.cleanModules(settings.rootDir, dependencies) 201 | } 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------