更新依赖项中的版本时更新模块版本(多模块maven)

时间:2018-01-06 14:15:52

标签: java maven versions-maven-plugin

我的问题:versions-maven-plugin帮助我在我的多模块maven项目中升级某个模块中的版本(我们称之为 A )。

此项目中的某些模块(我们称之为 B C )具有依赖模块 A 。我也需要为这个模块升级版本( B C )。有时,我还需要在依赖项中 B (或 C )的其他模块( B-parent )中升级版本( A 版本升级 - > B 版本升级 - > B-parent 升级版本)。其他问题是模块可以处于不同的嵌套级别。

示例:

root:
  ---B-parent: 
       ---B (A in dependencies)
  ---C-parent
       ---C (A in dependencies)
  ---A-parent: 
       ---A

流程: A 版本升级 - > A-parent 版本向上, C 版本升级 - > C-parent 版本升级, B 版本升级 - > B-parent 版本。

此插件无法执行此操作。

有什么想法可以做到这一点吗? 或者我更新版本的策略不够好?

1 个答案:

答案 0 :(得分:1)

我已经制作了一个脚本,用于使用versions-maven-plugin以递归方式增加所有相关模块中的版本号。

算法如下:

  1. 运行版本:在目标模块中设置
  2. 运行版本:在所有已按版本更新的模块中设置:从上一步设置。如果模块已经处理过 - 请跳过它。
  3. 重复步骤2
  4. Python 2.7代码

    #!/usr/bin/env python
    # -*- coding: utf-8 -*- #
    
    # How To
    #
    # Run script and pass module path as a first argument.
    # Or run it without arguments in module dir.
    #
    # Script will request the new version number for each module.
    # If no version provided - last digit will be incremented (1.0.0 -> 1.0.1).
    # cd <module-path>
    # <project-dir>/increment-version.py
    # ...
    # review changes and commit
    
    from subprocess import call, Popen, PIPE, check_output
    import os
    import re
    import sys
    
    getVersionCommand = "mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate " \
                        "-Dexpression=project.version 2>/dev/null | grep -v '\['"
    
    
    def getCurrentModuleVersion():
        return check_output(getVersionCommand, shell=True).decode("utf-8").split("\n")[0]
    
    
    def incrementLastDigit(version):
        digits = version.split(".")
        lastDigit = int(digits[-1])
        digits[-1] = str(lastDigit+1)
        return ".".join(digits)
    
    
    def isUpdatedVersionInFile(version, file):
        return "<version>" + version + "</version>" in \
               check_output("git diff HEAD --no-ext-diff --unified=0 --exit-code -a --no-prefix {} "
                            "| egrep \"^\\+\"".format(file), shell=True).decode("utf-8")
    
    
    def runVersionSet(version):
        process = Popen(["mvn", "versions:set", "-DnewVersion="+version, "-DgenerateBackupPoms=false"], stdout=PIPE)
        (output, err) = process.communicate()
        exitCode = process.wait()
        if exitCode is not 0:
            print "Error setting the version"
            exit(1)
        return output, err, exitCode
    
    
    def addChangedPoms(version, dirsToVisit, visitedDirs):
        changedFiles = check_output(["git", "ls-files", "-m"]) \
            .decode("utf-8").split("\n")
        changedPoms = [f for f in changedFiles if f.endswith("pom.xml")]
        changedDirs = [os.path.dirname(os.path.abspath(f)) for f in changedPoms if isUpdatedVersionInFile(version, f)]
        changedDirs = [d for d in changedDirs if d not in visitedDirs and d not in dirsToVisit]
        print "New dirs to visit:", changedDirs
        return changedDirs
    
    
    if __name__ == "__main__":
        visitedDirs = []
        dirsToVisit = []
    
        if len(sys.argv) > 1:
            if os.path.exists(os.path.join(sys.argv[1], "pom.xml")):
                dirsToVisit.append(os.path.abspath(sys.argv[1]))
            else:
                print "Error. No pom.xml file in dir", sys.argv[1]
                exit(1)
        else:
            dirsToVisit.append(os.path.abspath(os.getcwd()))
    
        pattern = re.compile("aggregation root: (.*)")
        while len(dirsToVisit) > 0:
            dirToVisit = dirsToVisit.pop()
            print "Visiting dir", dirToVisit
            os.chdir(dirToVisit)
            currentVersion = getCurrentModuleVersion()
            defaultVersion = incrementLastDigit(currentVersion)
            version = raw_input("New version for {}:{} ({}):".format(dirToVisit, currentVersion, defaultVersion))
            if not version.strip():
                version = defaultVersion
            print "New version:", version
            output, err, exitcode = runVersionSet(version)
            rootDir = pattern.search(output).group(1)
            visitedDirs = visitedDirs + [dirToVisit]
            os.chdir(rootDir)
            print "Adding new dirs to visit"
            dirsToVisit = dirsToVisit + addChangedPoms(version, dirsToVisit, visitedDirs)