# HG changeset patch # User cin # Date 2021-06-11 22:35:30 # Node ID 47abdf72678542dc865605a8a02c4e1e9c139fe7 # Parent 0000000000000000000000000000000000000000 Initial coomit, basic hg tasks diff --git a/.hgignore b/.hgignore new file mode 100644 --- /dev/null +++ b/.hgignore @@ -0,0 +1,7 @@ +syntax: glob +.gradle/ +build/ +bin/ +.classpath +.project +.settings/ diff --git a/build.gradle b/build.gradle new file mode 100644 diff --git a/gradlew b/gradlew new file mode 100755 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/mercurial/build.gradle b/mercurial/build.gradle new file mode 100644 --- /dev/null +++ b/mercurial/build.gradle @@ -0,0 +1,17 @@ +plugins { + id "java-gradle-plugin" +} + + +repositories { + mavenCentral() +} + +gradlePlugin { + plugins { + containerPlugin { + id = 'org.implab.gradle-mercurial' + implementationClass = 'org.implab.gradle.mercurial.MercurialPlugin' + } + } +} diff --git a/mercurial/src/main/java/org/implab/gradle/Utils.java b/mercurial/src/main/java/org/implab/gradle/Utils.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/Utils.java @@ -0,0 +1,108 @@ +package org.implab.gradle; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Scanner; + +import org.gradle.api.Action; +import groovy.json.JsonGenerator; +import groovy.json.JsonOutput; +import groovy.json.JsonGenerator.Converter; +import groovy.lang.Closure; + +public final class Utils { + public static void redirectIO(final InputStream src, final Action consumer) { + new Thread(() -> { + try (Scanner sc = new Scanner(src)) { + while (sc.hasNextLine()) { + consumer.execute(sc.nextLine()); + } + } + }).start(); + } + + public static String execCmd(List args, String charset) throws IOException, InterruptedException, Exception { + if (args == null || args.size() == 0) + throw new IllegalArgumentException(); + + ProcessBuilder builder = new ProcessBuilder(args); + + Process p = builder.start(); + + String output = readAll(p.getInputStream(), charset); + + int code = p.waitFor(); + if (code != 0) + throw new Exception(String.format("The process `%s` failed with code: %s", args.get(0), code)); + + return output; + + } + + public static void redirectIO(final InputStream src, final File file) { + new Thread(() -> { + try (OutputStream out = new FileOutputStream(file)) { + src.transferTo(out); + } catch(Exception e) { + // silence! + } + }).start(); + } + + public static String readAll(final InputStream src) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + src.transferTo(out); + return out.toString(); + } + + public static String readAll(final InputStream src, String charset) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + src.transferTo(out); + return out.toString(charset); + } + + public static JsonGenerator createDefaultJsonGenerator() { + return new JsonGenerator.Options() + .excludeNulls() + .addConverter(new Converter() { + public boolean handles(Class type) { + return (File.class == type); + } + public Object convert(Object value, String key) { + return ((File)value).getPath(); + } + }) + .build(); + } + + public static void closeSilent(Closeable handle) { + try { + handle.close(); + } catch(Exception e) { + // silence! + } + } + + public static String toJsonPretty(Object value) { + return JsonOutput.prettyPrint(createDefaultJsonGenerator().toJson(value)); + } + + public static boolean isNullOrEmptyString(String value) { + return (value == null || value.length() == 0); + } + + public static Action wrapClosure(Closure closure) { + return x -> { + closure.setDelegate(x); + closure.setResolveStrategy(Closure.DELEGATE_FIRST); + closure.call(x); + }; + } + +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/MercurialExtension.java b/mercurial/src/main/java/org/implab/gradle/mercurial/MercurialExtension.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/MercurialExtension.java @@ -0,0 +1,115 @@ +package org.implab.gradle.mercurial; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.gradle.api.Project; +import org.implab.gradle.Utils; + +public class MercurialExtension { + private static final String COMMIT_INFO_TEMPLATE = "{latesttag('re:^v') % '{ifeq(tag,'null','',tag)}:{distance}'}:{branch}:{node|short}"; + + private static final Pattern versionPattern = Pattern.compile("^(?:v[\\-_\\.]?)?(.*)"); + + private final Project project; + + private Charset outputCharset = Charset.defaultCharset(); + + private WorkspaceInfo workspaceInfo; + + private String hgCmd = "hg"; + + private SemVersion defaultWorkspaceVersion = new SemVersion(0, 0, 1, "dev", null); + + public MercurialExtension(Project project) { + Objects.requireNonNull(project); + + this.project = project; + } + + public String hg(String... args) throws Exception { + List commandLine = new ArrayList<>(); + commandLine.add(hgCmd); + Collections.addAll(commandLine, args); + + return Utils.execCmd(commandLine, outputCharset.name()); + } + + public Charset getOutputCharset() { + return outputCharset; + } + + public void setOutputCharset(Charset outputCharset) { + this.outputCharset = Optional.ofNullable(outputCharset).orElseGet(Charset::defaultCharset); + } + + public void setOutputCharset(String outputCharset) { + this.outputCharset = Optional.ofNullable(outputCharset).map(x -> Charset.forName(x)) + .orElseGet(Charset::defaultCharset); + } + + public String getHgCmd() { + return hgCmd; + } + + public void setHgCmd(String hgCmd) { + this.hgCmd = hgCmd; + } + + public WorkspaceInfo getWorkspaceInfo() throws Exception { + if (workspaceInfo == null) + workspaceInfo = loadWorkspaceInfo(); + return workspaceInfo; + } + + public SemVersion getWorkspaceVersion() throws Exception { + return tryParseVersion(getWorkspaceInfo().getVersionTag()).orElse(defaultWorkspaceVersion); + } + + public void applyVersioningPolicy() throws Exception { + Object version = project.getVersion(); + if (version == null || version.toString().isBlank() || version.toString().equalsIgnoreCase(Project.DEFAULT_VERSION)) { + int distance = getWorkspaceInfo().getVersionDistance(); + String changeset = getWorkspaceInfo().getChangeset(); + project.setVersion( + distance> 0 ? + getWorkspaceVersion().addPatch(distance).suffix("snapshot").meta(changeset) : + getWorkspaceVersion() + ); + } else { + project.setVersion(SemVersion.toSemVersion(version, false)); + } + } + + String[] queryLogInfo() throws Exception { + return hg("log", "-r", ".", "--template", COMMIT_INFO_TEMPLATE).split(":"); + } + + WorkspaceInfo loadWorkspaceInfo() throws Exception { + boolean isDirty = checkIsDirty(); + String[] info = queryLogInfo(); + return new WorkspaceInfo(info[0], Integer.parseInt(info[1]), info[2], info[3], isDirty); + } + + boolean checkIsDirty() throws Exception { + return !hg("status", "-mard").isBlank(); + } + + Optional tryParseVersion(String version) { + if (version == null) + return Optional.empty(); + + Matcher m = versionPattern.matcher(version); + boolean isMatch = m.matches(); + + return isMatch ? SemVersion.tryParseLax(m.group(1)) : Optional.empty(); + } + + +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/MercurialPlugin.java b/mercurial/src/main/java/org/implab/gradle/mercurial/MercurialPlugin.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/MercurialPlugin.java @@ -0,0 +1,85 @@ +package org.implab.gradle.mercurial; + +import org.codehaus.groovy.runtime.MethodClosure; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.plugins.ExtraPropertiesExtension; +import org.gradle.api.tasks.TaskExecutionException; +import org.gradle.api.tasks.TaskProvider; +import org.implab.gradle.mercurial.tasks.HgBookmark; +import org.implab.gradle.mercurial.tasks.HgTag; +import org.implab.gradle.mercurial.tasks.HgTask; + +public class MercurialPlugin implements Plugin { + + public final String MERCURIAL_EXTENSION_NAME = "mercurial"; + + private MercurialExtension mercurialExtension; + + @Override + public void apply(Project project) { + + mercurialExtension = new MercurialExtension(project); + + project.getExtensions().add(MERCURIAL_EXTENSION_NAME, mercurialExtension); + + ExtraPropertiesExtension extras = project.getExtensions().getExtraProperties(); + extras.set(HgTask.class.getSimpleName(), HgTask.class); + extras.set("semver", new MethodClosure(SemVersion.class, "toSemVersion")); + + project.getTasks().register("printVersion", t -> { + t.doLast(t2 -> { + t2.getLogger().quiet("version: {}", project.getVersion()); + }); + }); + + TaskProvider hgBookmarkTask = project.getTasks().register("hgBookmark", HgBookmark.class, t -> { + t.getInactive().set(true); + t.getForce().set(true); + }); + + TaskProvider hgTagTask = project.getTasks().register("hgTag", HgTag.class, t -> { + t.mustRunAfter(hgBookmarkTask); + }); + + project.getTasks().register("release", t -> { + t.finalizedBy(hgBookmarkTask, hgTagTask); + t.doLast(self -> { + try { + if (mercurialExtension.checkIsDirty()) + throw new Exception("The workspace is dirty, you need to commit changes first"); + + SemVersion version = (SemVersion) project.getVersion(); + SemVersion nextVersion = version.release(); + + self.getLogger().quiet("release {} -> {}", version, nextVersion); + + hgBookmarkTask.get().getBookmarks().add("prod"); + hgTagTask.get().getTags().add("v" + nextVersion.toString()); + } catch (Exception e) { + throw new TaskExecutionException(self, e); + } + }); + }); + + project.getTasks().register("staging", t -> { + t.finalizedBy(hgBookmarkTask, hgTagTask); + t.doLast(self -> { + try { + if (mercurialExtension.checkIsDirty()) + throw new Exception("The workspace is dirty, you need to commit changes first"); + + SemVersion version = (SemVersion) project.getVersion(); + SemVersion nextVersion = version.release().suffix("rc"); + + self.getLogger().quiet("staging {} -> {}", version, nextVersion); + + hgBookmarkTask.get().getBookmarks().add("staging"); + hgTagTask.get().getTags().add("v" + nextVersion.toString()); + } catch (Exception e) { + throw new TaskExecutionException(self, e); + } + }); + }); + } +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/SemVersion.java b/mercurial/src/main/java/org/implab/gradle/mercurial/SemVersion.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/SemVersion.java @@ -0,0 +1,211 @@ +package org.implab.gradle.mercurial; + +import java.io.Serializable; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.annotation.Nonnull; + +public class SemVersion implements Serializable, Comparable { + + private static final long serialVersionUID = 1L; + + private static Pattern semVerPattern = Pattern.compile( + "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); + + private static Pattern semVerLaxPattern = Pattern.compile( + "^(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*))?)?(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); + + private int major; + + private int minor; + + private int patch; + + private String suffix; + + private String meta; + + public SemVersion() { + } + + public SemVersion(int major, int minor, int patch, String suffix, String meta) { + this.major = major; + this.minor = minor; + this.patch = patch; + this.suffix = suffix; + this.meta = meta; + } + + public SemVersion(int major, int minor, int patch) { + this(major, minor, patch, null, null); + } + + public SemVersion(SemVersion src) { + this(src.major, src.minor, src.patch, src.suffix, src.meta); + } + + public int getMajor() { + return major; + } + + public void setMajor(int major) { + this.major = major; + } + + public int getMinor() { + return minor; + } + + public void setMinor(int minor) { + this.minor = minor; + } + + public int getPatch() { + return patch; + } + + public void setPatch(int patch) { + this.patch = patch; + } + + public Optional getSuffix() { + return Optional.ofNullable(suffix); + } + + public void setSuffix(String suffix) { + this.suffix = suffix; + } + + public Optional getMeta() { + return Optional.ofNullable(meta); + } + + public void setMeta(String meta) { + this.meta = meta; + } + + public boolean isRelease() { + return getSuffix().isEmpty(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append(major).append(".").append(minor).append(".").append(patch); + getSuffix().ifPresent(s -> sb.append("-").append(s)); + getMeta().ifPresent(m -> sb.append("+").append(m)); + + return sb.toString(); + } + + @Override + public int compareTo(SemVersion other) { + int res = Integer.compare(major, other.major); + if (res != 0) + return res; + res = Integer.compare(minor, other.minor); + if (res != 0) + return res; + res = Integer.compare(patch, other.patch); + + return getSuffix() + // if we have suffix, chech another suffix, if there is no another suffix + // then another version is bigger: 1.0.0-rc < 1.0.0 + .map(s1 -> other.getSuffix().map(s2 -> s1.compareTo(s2)).orElse(-1)) + // if we don't have the suffix + .orElse(other.getSuffix().isPresent() ? 1 : 0); + + } + + public SemVersion release() { + return new SemVersion(major, minor, patch, null, null); + } + + public SemVersion suffix(String suffix) { + return new SemVersion(major, minor, patch, suffix, meta); + } + + public SemVersion suffix() { + return new SemVersion(major, minor, patch, null, meta); + } + + public SemVersion meta(String meta) { + return new SemVersion(major, minor, patch, suffix, meta); + } + + public SemVersion meta() { + return new SemVersion(major, minor, patch, suffix, null); + } + + public SemVersion patch(int patch) { + return new SemVersion(major, minor, patch, suffix, meta); + } + + public SemVersion minor(int minor) { + return new SemVersion(major, minor, patch, suffix, meta); + } + + public SemVersion major(int major) { + return new SemVersion(major, minor, patch, suffix, meta); + } + + public SemVersion addPatch(int number) { + return new SemVersion(major, minor, patch + number, suffix, meta); + } + + public SemVersion addMinor(int number) { + return new SemVersion(major, minor + number, patch, suffix, meta); + } + + public SemVersion addMajor(int number) { + return new SemVersion(major + number, minor, patch, suffix, meta); + } + + public SemVersion nextMinor() { + return new SemVersion(major, minor + 1, 0, null, meta); + } + + public SemVersion nextMajor() { + return new SemVersion(major + 1, 0, 0, null, meta); + } + + public static Optional tryParse(@Nonnull String str) { + Objects.requireNonNull(str); + + Matcher match = semVerPattern.matcher(str); + + return match.matches() ? Optional.of(new SemVersion(Integer.parseInt(match.group(1)), + Integer.parseInt(match.group(2)), Integer.parseInt(match.group(3)), match.group(4), match.group(5))) + : Optional.empty(); + } + + public static Optional tryParseLax(@Nonnull String str) { + Objects.requireNonNull(str); + + Matcher match = semVerLaxPattern.matcher(str); + + return match.matches() ? Optional.of(new SemVersion(Integer.parseInt(match.group(1)), + Integer.parseInt(Optional.ofNullable(match.group(2)).orElse("0")), + Integer.parseInt(Optional.ofNullable(match.group(3)).orElse("0")), match.group(4), match.group(5))) + : Optional.empty(); + } + + public static SemVersion toSemVersion(Object value, boolean strict) { + if (value == null) { + return new SemVersion(); + } else if (value instanceof SemVersion) { + return new SemVersion((SemVersion) value); + } else { + Optional semver = strict ? tryParse(value.toString()) : tryParseLax(value.toString()); + return semver.orElseThrow(() -> new IllegalArgumentException(String.format("Failed to parse semver '%s', strict=%s", value, strict))); + } + } + + public static SemVersion toSemVersion(Object value) { + return toSemVersion(value, false); + } +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/WorkspaceInfo.java b/mercurial/src/main/java/org/implab/gradle/mercurial/WorkspaceInfo.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/WorkspaceInfo.java @@ -0,0 +1,51 @@ +package org.implab.gradle.mercurial; + +import java.util.Objects; + +public class WorkspaceInfo { + private final String versionTag; + + private final int versionDistance; + + private final String branch; + + private final String changeset; + + private final boolean isDirty; + + public WorkspaceInfo(String versionTag, int versionDistance, String branch, String changeset, boolean isDirty) { + this.versionTag = versionTag; + this.versionDistance = versionDistance; + this.branch = Objects.requireNonNull(branch); + this.changeset = Objects.requireNonNull(changeset); + this.isDirty = isDirty; + } + + public String getChangeset() { + return changeset; + } + + public String getVersionTag() { + return versionTag; + } + + public int getVersionDistance() { + return versionDistance; + } + + public String getBranch() { + return branch; + } + + public boolean getIsDirty() { + return isDirty; + } + + + @Override + public String toString() { + return String.format("{ changeset=%s, branch=%s, versionTag=%s, distance=%s, isDirty=%s}", changeset, branch, + versionTag, versionDistance, isDirty); + } + +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgBookmark.java b/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgBookmark.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgBookmark.java @@ -0,0 +1,84 @@ +package org.implab.gradle.mercurial.tasks; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.gradle.api.DefaultTask; +import org.gradle.api.model.ObjectFactory; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.TaskAction; +import org.implab.gradle.Utils; +import org.implab.gradle.mercurial.MercurialExtension; + +import groovy.transform.Internal; + +public class HgBookmark extends DefaultTask { + + private final Property cliCmd; + + private final Property inactive; + + private final Property force; + + private final ListProperty bookmarks; + + private String commandOutput; + + protected MercurialExtension getMercurialExtension() { + return getProject().getExtensions().getByType(MercurialExtension.class); + } + + @Inject + public HgBookmark(ObjectFactory factory) { + cliCmd = factory.property(String.class); + inactive = factory.property(Boolean.class); + force = factory.property(Boolean.class); + bookmarks = factory.listProperty(String.class); + cliCmd.convention(getMercurialExtension().getHgCmd()); + + onlyIf(t -> !getBookmarks().get().isEmpty()); + } + + @Internal + public Property getInactive() { + return inactive; + } + + @Internal + public Property getForce() { + return force; + } + + @Internal + public String getCommandOutput() { + return commandOutput; + } + + @Internal + public ListProperty getBookmarks() { + return bookmarks; + } + + @TaskAction + public void Run() throws IOException, InterruptedException, Exception { + List commandLine = new ArrayList<>(); + + commandLine.add(cliCmd.get()); + commandLine.add("bookmark"); + if(inactive.isPresent()) + commandLine.add("-i"); + if(force.isPresent()) + commandLine.add("-f"); + + commandLine.addAll(bookmarks.get()); + + getLogger().info("Starting: {}", commandLine); + + commandOutput = Utils.execCmd(commandLine, getMercurialExtension().getOutputCharset().name()); + } + +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgTag.java b/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgTag.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgTag.java @@ -0,0 +1,79 @@ +package org.implab.gradle.mercurial.tasks; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.gradle.api.DefaultTask; +import org.gradle.api.model.ObjectFactory; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.SkipWhenEmpty; +import org.gradle.api.tasks.TaskAction; +import org.implab.gradle.Utils; +import org.implab.gradle.mercurial.MercurialExtension; + +import groovy.transform.Internal; + +public class HgTag extends DefaultTask { + + private final Property cliCmd; + + private final Property force; + + private final ListProperty tags; + + private String commandOutput; + + protected MercurialExtension getMercurialExtension() { + return getProject().getExtensions().getByType(MercurialExtension.class); + } + + @Inject + public HgTag(ObjectFactory factory) { + cliCmd = factory.property(String.class); + force = factory.property(Boolean.class); + tags = factory.listProperty(String.class); + cliCmd.convention(getMercurialExtension().getHgCmd()); + + onlyIf(t -> !getTags().get().isEmpty()); + } + + @Internal + public Property getForce() { + return force; + } + + @Internal + public String getCommandOutput() { + return commandOutput; + } + + @Input + @SkipWhenEmpty + public ListProperty getTags() { + return tags; + } + + @TaskAction + public void Run() throws IOException, InterruptedException, Exception { + List commandLine = new ArrayList<>(); + + commandLine.add(cliCmd.get()); + + commandLine.add("tag"); + + if(force.isPresent()) + commandLine.add("-f"); + + commandLine.addAll(tags.get()); + + getLogger().info("Starting: {}", commandLine); + + commandOutput = Utils.execCmd(commandLine, getMercurialExtension().getOutputCharset().name()); + } + +} diff --git a/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgTask.java b/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgTask.java new file mode 100644 --- /dev/null +++ b/mercurial/src/main/java/org/implab/gradle/mercurial/tasks/HgTask.java @@ -0,0 +1,67 @@ +package org.implab.gradle.mercurial.tasks; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.gradle.api.DefaultTask; +import org.gradle.api.provider.Property; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.TaskAction; +import org.implab.gradle.Utils; +import org.implab.gradle.mercurial.MercurialExtension; + +public class HgTask extends DefaultTask { + + private final Property cliCmd; + + private List> commandArgs; + + private String commandOutput; + + protected MercurialExtension getMercurialExtension() { + return getProject().getExtensions().getByType(MercurialExtension.class); + } + + public HgTask() { + cliCmd = getProject().getObjects().property(String.class); + cliCmd.convention(getMercurialExtension().getHgCmd()); + + } + + public String getCommandOutput() { + return commandOutput; + } + + public void clearCommandArgs() { + commandArgs.clear(); + } + + public void commandArgs(Object... args) { + for (Object arg : args) { + if (arg == null) + continue; + if (arg instanceof Provider) + commandArgs.add(((Provider) arg).map(x -> x.toString())); + else + commandArgs.add(getProject().getProviders().provider(() -> arg.toString())); + } + } + + @TaskAction + public void Run() throws IOException, InterruptedException, Exception { + List commandLine = new ArrayList<>(); + + commandLine.add(cliCmd.get()); + + for (Provider arg : commandArgs) { + if (arg.isPresent()) + commandLine.add(arg.get()); + } + + getLogger().info("Starting: ", commandLine); + + commandOutput = Utils.execCmd(commandLine, getMercurialExtension().getOutputCharset().name()); + } + +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,13 @@ +/* + * This settings file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/3.5/userguide/multi_project_builds.html + */ + +rootProject.name = 'plugins' + +include 'mercurial'