release.py 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
#! /usr/bin/env python
# ==========================================================================
# ctools release manager
#
# Copyright (C) 2016-2021 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import os
import sys
import commands

# Fix Python 2.x.
try:
    input = raw_input
except NameError:
    pass


# ================= #
# Confirm something #
# ================= #
def confirm(text):
    """
    Confirm something

    Parameters
    ----------
    text : str
        Thing to confirm

    Returns
    -------
    flag : bool
        True if something is confirmed
    """
    # Confirmation loop
    waiting = True
    while waiting:
        confirmation = str(input(text+' (y/n): '))
        if confirmation == 'q':
            sys.exit()
        elif confirmation == 'y':
            flag    = True
            waiting = False
        elif confirmation == 'n':
            flag    = False
            waiting = False

    # Return confirmation flag
    return flag


# ============== #
# Commit changes #
# ============== #
def commit(message):
    """
    Commit changes into git repo

    Parameters
    ----------
    message : str
        Commit message
    """
    # Show changes
    print("The following files have been changed:")
    os.system('git status -s')

    # Ask again whether the changes should be committed
    if confirm("Commit all changes?"):

        # Optionally enter a commit message
        if len(message) == 0:
            message = str(input("Please enter a commit message: "))

        # Stage all files
        os.system('git add -u')

        # Commit all changes
        os.system('git commit -m "%s"' % message)
    
    # Return
    return


# ========================== #
# Check if git branch exists #
# ========================== #
def git_branch_exists(branch):
    """
    Check if git branch exists

    Parameters
    ----------
    branch : str
        Branch name

    Returns
    -------
    exists : bool
        True if git branch exists
    """
    # Check if git branch exists
    rc = os.system('git rev-parse --verify %s >/dev/null 2>&1' % branch)

    # Set exists flag
    if rc == 0:
        exists = True
    else:
        exists = False

    # Return flag
    return exists


# ================= #
# Create git branch #
# ================= #
def create_git_branch(branch):
    """
    Create a git branch

    Parameters
    ----------
    branch : str
        Branch name
    """
    # If branch exists already then ask whether it should be deleted
    if git_branch_exists(branch):
        if confirm("Git branch '%s' exists already, do you want to delete "
                   "it?" % branch):
            os.system('git branch -D %s' % branch)

    # If branch exists already then switch to the new branch, otherwise create
    # new branch and switch to it
    if git_branch_exists(branch):
        os.system('git checkout %s' % branch)
    else:
        print("Created new branch '%s'" % branch)
        os.system('git checkout -b %s' % branch)

    # Return
    return


# ======================================= #
# Check whether version string is correct #
# ======================================= #
def check_version(version):
    """
    Check whether version string is correct

    Parameters
    ----------
    version : str
        Version number

    Returns
    -------
    check : bool
        True if version string is correct
    """
    # Initialise check with False
    check = False

    # Split version string
    split = version.split('.')

    # If there are three elements or four elements we may have a valid version
    # string
    if len(split) == 3 or len(split) == 4:

        # If the three first elements are integers we may have a valid version
        # string
        if split[0].isdigit() and split[1].isdigit() and split[2].isdigit():

            # If we have three elements the version is valid and we are done
            if len(split) == 3:
                check = True

            # Otherwise check if the 4th element is of format devn, where n
            # is an integer number
            elif split[3][0:3] == 'dev':
                if split[3][3:].isdigit():
                    check = True
                else:
                    check = True

    # Return check
    return check


# ========================== #
# Get current version number #
# ========================== #
def get_current_version():
    """
    Get current version number

    Returns
    -------
    version : str
        Version number
    """
    # Initialse version number of empty string
    version = ''

    # Open configure.ac file
    f = open('configure.ac', 'r')

    # Read all lines
    for line in f:

        # Search for pattern
        if line.startswith('AC_INIT('):

            # Extract version number
            start   = line.find(',')+1
            stop    = line.find(',', start)
            version = line[start:stop].strip().lstrip('[').rstrip(']')

    # Close file
    f.close()

    # Return version
    return version


# ========================== #
# Get libtool version number #
# ========================== #
def get_libtool_version():
    """
    Get libtools version number

    Returns
    -------
    version : str
        Version number
    """
    # Initialse version number of empty string
    version = ''

    # Open configure.ac file
    f = open('configure.ac', 'r')

    # Read all lines
    for line in f:

        # Search for pattern
        if line.startswith('CTOOLS_LT_VERSION='):

            # Extract version number
            start   = line.find('"')+1
            stop    = line.find('"', start)
            version = line[start:stop].strip()

    # Close file
    f.close()

    # Return version
    return version


# =============================================== #
# Set libtool version number in configure.ac file #
# =============================================== #
def set_libtool_version(library=False, added=False, removed=False, changed=False):
    """
    Set special version numbers in configure.ac file

    Parameters
    ----------
    library : bool, optional
        Library source code changed
    added : bool, optional
        Interfaces added
    removed : bool, optional
        Interfaces removed
    changed : bool, optional
        Interfaces changed
    """
    # Get libtool version number
    old   = get_libtool_version()
    split = old.split(':')

    # Decompose libtool version number
    current  = int(split[0])
    revision = int(split[1])
    age      = int(split[2])

    # If the library source code has changed at all since the last update, then
    # increment revision
    if library:
        revision += 1

    # If any interfaces have been added, removed, or changed since the last
    # update, increment current, and set revision to 0
    if added or removed or changed:
        current  += 1
        revision  = 0

    # If any interfaces have been added since the last public release, then
    # increment age
    if added:
        age += 1

    # If any interfaces have been removed or changed since the last public
    # release, then set age to 0
    if removed or changed:
        age = 0

    # Build new libtool version number
    version = '%d:%d:%d' % (current, revision, age)

    # Set libtool version number
    set_version_in_file('configure.ac', version, old)

    # Return
    return


# ============================== #
# Set version number in one file #
# ============================== #
def set_version_in_file(filename, version, current):
    """
    Set version number in one file

    The function replaces all current version numbers in a file by a new
    version number.

    Parameters
    ----------
    filename : str
        File name
    version : str
        New version number
    current : str
        Current version number
    """
    # Open file in read mode
    f = open(filename, 'r')

    # Read file content
    content = f.read()

    # Close file
    f.close()

    # Replace version number
    new_content = content.replace(current, version)

    # Open file in write mode
    f = open(filename, 'w')

    # Write file content
    f.write(new_content)

    # Close file
    f.close()

    # Return
    return


# ======================= #
# Set the package version #
# ======================= #
def set_package_version(version):
    """
    Set the package version

    Parameters
    ----------
    version : str
        Version number
    """
    # List of all files in which the version numbers should be changed. The
    # file name should include their access paths with respect to the source
    # directory
    filenames = ['configure.ac',
                 'README.md',
                 'sonar-project.properties',
                 'doc/Doxyfile',
                 'doc/source/conf.py']


    # Get the current package version
    current = get_current_version()

    # Set versions by loop over all files
    for filename in filenames:
        set_version_in_file(filename, version, current)

    # Generate current version number
    split = current.split('.')
    cur   = '%s.%s' % (split[0], split[1])

    # Generate new version number
    split = version.split('.')
    ver   = '%s.%s' % (split[0], split[1])

    # Set version number in doc/source/conf.py file
    set_version_in_file('doc/source/conf.py', ver, cur)

    # Return
    return


# ============= #
# Build tarball #
# ============= #
def build_tarball():
    """
    Build tarball using 'make dist'
    """
    # Set base path
    base_path = os.getcwd()

    # Enable/disable logging
    if confirm("Log actions in logfile?"):
        verbosity = ' >> %s/make_dist.log 2>&1' % (base_path)
        os.system('rm -rf make_dist.log >/dev/null 2>&1')
    else:
        verbosity = ' >/dev/null 2>&1'

    # Configure package
    print("Configure package")
    rc = os.system('./configure%s' % verbosity)
    if rc == 0:
        print("Package configuration successful")
    else:
        print("*** Failure in package configuration")

    # Check package
    print("Create tarball")
    rc = os.system('make dist%s' % verbosity)
    if rc == 0:
        print("Tarball creation successful")
    else:
        print("*** Failure in creation of tarball")

    # Return
    return


# ============= #
# Check tarball #
# ============= #
def check_tarball():
    """
    Check tarball using 'make distcheck'

    Parameters
    ----------
    filename : str
        Tarball file name
    """
    # Set base path
    base_path = os.getcwd()

    # Enable/disable logging
    if confirm("Log check in logfile?"):
        verbosity = ' >> %s/make_distcheck.log 2>&1' % (base_path)
        os.system('rm -rf make_distcheck.log >/dev/null 2>&1')
    else:
        verbosity = ' >/dev/null 2>&1'

    # Configure package
    print("Configure package")
    rc = os.system('./configure%s' % verbosity)
    if rc == 0:
        print("Package configuration successful")
    else:
        print("*** Failure in package configuration")

    # Check tarball
    print("Check tarball")
    rc = os.system('make distcheck%s' % verbosity)
    if rc == 0:
        print("Tarball checking successful")
    else:
        print("*** Failure in checking of tarball")

    # Return
    return


# ================ #
# Manage main menu #
# ================ #
def main_menu():
    """
    Manage main menu
    """
    # Print main menu
    print('[1] Make a new release')
    print('[2] Set the package version in current branch')
    print('[3] Set the libtool version in current branch')
    print('[4] Commit changes in current branch')
    print('[5] Create tarball from current branch')
    print('[6] Check tarball')
    print('[q] Quit')

    # Wait for the input
    waiting = True
    while waiting:
        choice = str(input('Enter your choice: '))
        if choice == '1' or choice == '2' or choice == '3' or choice == '4' or \
           choice == '5' or choice == '6' or choice == 'q':
            waiting = False

    # Return choice
    return choice


# ====================== #
# Manage package release #
# ====================== #
def release_menu(branch='release'):
    """
    Manage package release

    Parameters
    ----------
    branch : str, optional
        Release branch name
    """
    # Annonce actions
    print("")
    print("Make a new release")
    print("------------------")

    # Step 1: Create a release branch
    if confirm("Step 1: Do you want to create a '%s' branch?" % branch):
        create_git_branch(branch)
    else:
        if git_branch_exists(branch):
            os.system('git checkout %s' % branch)
        else:
            requested = branch
            branch    = commands.getoutput('git rev-parse --abbrev-ref HEAD')
            print("WARNING: No '%s' branch found, continue working on "
                  "current branch '%s'" % (requested, branch))

    # Get current package version
    current = get_current_version()

    # Step 2: Set package version
    print("")
    if confirm("Step 2: Current ctools version is '%s'. Do you want to "
               "change the package version?" % current):
        package_version_menu()

    # Get current libtool version
    current = get_libtool_version()

    # Step 3: Set libtool version
    print("")
    if confirm("Step 3: Current Libtool version is '%s'. Do you want to "
               "change the libtool version?" % current):
        libtool_version_menu()

    # Step 4: Commit changes
    print("")
    if confirm("Step 4: Commit changes?"):
        package = get_current_version()
        libtool = get_libtool_version()
        message = "ctools package version set to '%s' and libtool version "\
                  "set to '%s'" % (package, libtool)
        commit(message)

    # Step 5: Push branch into git
    print("")
    if confirm("Step 5: Push changes?"):
        os.system('git push origin %s' % branch)

    # Step 6: Build tarball
    print("")
    if confirm("Step 6: Build tarball?"):
        build_tarball()

    # Step 7: Check tarball
    print("")
    if confirm("Step 7: Check tarball?"):
        check_tarball()

    # Print separator
    print("")

    # Return
    return


# ============================== #
# Manage package version setting #
# ============================== #
def package_version_menu():
    """
    Manage package version setting
    """
    # Get the current package version
    current = get_current_version()

    # Looping until the version change is accepted
    looping = True
    while looping:

        # Get package version from input
        waiting = True
        while waiting:
            version = str(input("Current ctools version is '%s'. Please "
                                "enter new ctools version: " % current))
            if version == "q":
                sys.exit()
            if check_version(version) == False:
                print("*** Invalid ctools version. "
                      "Please enter the version in the format x.y.z[.devn]")
            else:
                waiting = False

        # If the version number change is confirmed then do the change
        if confirm("Change version to '%s'?" % version):

            # Set package version
            set_package_version(version)

            # Get new package and libtool versions
            version = get_current_version()

            # Inform about version change
            print("ctools version changed to '%s'" % (version))

            # Signal that we can exit looping
            looping = False

    # Return
    return


# ============================== #
# Manage libtool version setting #
# ============================== #
def libtool_version_menu():
    """
    Manage libtool version setting
    """
    # Get current libtool version
    current = get_libtool_version()

    # Continue only if libtool version should be changed
    if confirm("Current libtool version is '%s'. Do you want to change the "
               "version?" % current):

        # Determine package changes
        library = confirm(" Has the source code changed since last release?")
        added   = confirm(" Have interfaces been added since last release?")
        removed = confirm(" Have interfaces been removed since last release?")
        changed = confirm(" Have interfaces changed since last release?")

        # Set libtool version
        set_libtool_version(library=library, added=added, removed=removed,
                            changed=changed)

        # Get new libtool version
        version = get_libtool_version()

        # Print new libtool version
        print("Libtool version changed to '%s'" % version)

    # Return
    return


# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':

    # Clear console
    os.system('clear')

    # Print header
    print('ctools release manager')
    print('======================')
    print('')
    
    # Enter endless loop
    while True:

        # Show main menu
        choice = main_menu()

        # Dispatch according to choice
        if choice == '1':
            release_menu()
            print('')
        elif choice == '2':
            package_version_menu()
            print('')
        elif choice == '3':
            libtool_version_menu()
            print('')
        elif choice == '4':
            commit('')
            print('')
        elif choice == '5':
            build_tarball()
            print('')
        elif choice == '6':
            check_tarball()
            print('')
        elif choice == 'q':
            break