build_version.py 19.2 KB
Newer Older
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
   NAME
          build_version -- build and tag a track_publications version

    SYNOPSIS
          build_version [options]

    DESCRIPTION
          Helper script to build a version of the track_publications.

          Push version number in the CHANGELOG.
          Commit the new version in git and tag it

    EXAMPLES

            > build_version -h

    AUTHOR
          R. Le Gac, renaud.legac@free.fr

    Copyright (c) 2012-2015 R. Le Gac

"""

import datetime
import optparse
import os
import re
import sys
import tempfile


from os.path import join as opj
36
from subprocess import call, check_output
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

# constants
APP = os.path.basename(os.getcwd())
API = 'api'
CHANGELOG = 'static/CHANGELOG'
DOCS = 'static/docs'
DOCSRC = 'docs'
EXTJSSRC = 'static/plugin_extjs/src'
JSDOC = opj(DOCS, 'jsduck')
JSLIBDEBUG = 'static/%s/dbui-debug.js' % APP
JSLIBMIN = 'static/%s/dbui-min.js' % APP
JSLIBSRC = 'static/%s/src' % APP
LATEX = 'latex'
NOW = datetime.datetime.now()
PDF = "pdf"
PDFDOC = opj(DOCS, PDF)
REFERENCE = 'reference'
USER = 'user'

# basic commands
GIT = '/usr/bin/git'
JSDUCK = os.path.expandvars("$HOME/bin/jsduck")
PDFLATEX = '/usr/bin/pdflatex'
SENCHA = os.path.expandvars("$HOME/bin/sencha")
SPHINX = '/usr/bin/sphinx-build'

MSG_RELEASE = 'Enter the new release: '


def build():
    """Compile the javascript code and build documentations.

    """
    compile_js()
    build_html()

    for doc in (API, REFERENCE, USER):
        docsrc = opj(DOCSRC, doc)

        if os.path.exists(docsrc):
            build_pdf(doc)


def build_html():
    """Build HTML documentations.
    The source files are located in the following directory::

        myapp/docs
        myapp/docs/api
        myapp/docs/reference
        myapp/docs/user

    """
    print "Build the HTML documentations..."

    jsduck()

    for doc in (API, REFERENCE, USER):
        docsrc = opj(DOCSRC, doc)

        if os.path.exists(docsrc):
            sphinx("-b html", docsrc, opj(DOCS, doc))


def build_pdf(doc):
    """ Build PDF documentations...

    Args:
        doc (str): sub-directory. Possible values are api, reference, user.

    """
    print "Build the PDF documentations..."

    latexdoc = opj(DOCS, LATEX)

    # generate the latex
    sphinx("-b latex", opj(DOCSRC, doc), latexdoc)

    # the current directory
    cwd = os.getcwd()

    # find the name of the tex file
    os.chdir(latexdoc)
120 121
    filenames = [el for el in os.listdir('.') if el.endswith('.tex')]
    filename = (filenames[0] if len(filenames) == 1 else None)
122

123
    if not filename:
124 125 126 127
        print "\n\tNo latex file !"
        return

    # process the latex file twice
128 129
    call([PDFLATEX, filename])
    call([PDFLATEX, filename])
130 131 132 133 134 135 136 137

    # move the pdf file
    os.chdir(cwd)

    pdfdir = opj(DOCS, PDF)
    if not os.path.exists(pdfdir):
        os.mkdir(pdfdir)

138 139
    fin = filename.replace('.tex', '.pdf')
    fout = "%s_%s.pdf" % (os.path.splitext(filename)[0], doc)
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
    os.rename(opj(latexdoc, fin), opj(pdfdir, fout))

    # remove the latex directory
    call(["rm", "-rf", latexdoc])

    print "PDF documentation in", PDFDOC


def change_log():
    """Commit CHANGELOG and App.js.

    """
    print "Commit CHANGELOG..."
    if not os.path.exists(GIT):
        print '\n\tThe application git is missing !'
        print '\tSkip this step.\n'
        return

    # Commit modified files
    print 'git add', CHANGELOG
    git("add", CHANGELOG)

    print 'git commit'
    msg = "Start release cycle %s" % get_version()
    git("commit -m", msg)


167 168 169 170 171 172 173 174 175
def close_bugfix():
    """Close the bugfix cycle.

    """
    print "Close the bugfix cycle..."

    identifier = select_identifier("bugfix")
    if not identifier:
        sys.exit(0)
176

177 178 179 180 181 182 183 184 185 186
    branch = "bugfix-%s" % identifier

    git("checkout develop")
    git("merge --no-ff", branch)

    rep = raw_input("Delete the locale branch %s [y/N]" % branch)
    if rep == 'y':
        git("branch -d", branch)


187 188 189 190 191 192 193 194 195
def close_feature():
    """Close the feature cycle.

    """
    print "Close the feature cycle..."

    identifier = select_identifier("feature")
    if not identifier:
        sys.exit(0)
196

197
    branch = "feature-%s" % identifier
198 199

    git("checkout develop")
200
    git("merge --no-ff", branch)
201

202
    rep = raw_input("Delete branch %s [y/N]:" % branch)
203
    if rep == 'y':
204
        git("branch -d", branch)
205 206 207 208 209 210 211


def close_hotfix():
    """Close the hotfix cycle.

    """
    print "Close the hotfix cycle..."
212

213
    release = select_identifier("hotfix")
214 215
    if not release:
        sys.exit(0)
216 217

    branch = "hotfix-%s" % release
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

    git("checkout master")
    git("merge --no-ff", branch)

    msg = "Release %s" % release
    git("tag -a", release, "-m", msg)

    git("checkout develop")
    git("merge --no-ff", branch)

    rep = raw_input("Delete branch %s [y/N]:" % branch)
    if rep == "y":
        git("branch -d", branch)

    git("checkout master")
    build()

    print "The hotfix cycle ", release, "is over"


def close_release():
    """Close the release cycle.

    """
    print "Close the release cycle..."
243
    release = select_identifier("release")
244 245
    if not release:
        sys.exit(0)
246 247

    branch = "release-%s" % release
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

    msg = "Release %s" % release
    print msg

    git("checkout develop")
    git("merge --no-ff", branch, "-m", msg)

    git("checkout master")
    git("merge --no-ff", branch, "-m", msg)

    git("tag -a", release, "-m", msg)

    rep = raw_input("Delete branch %s [y/N]:" % branch)
    if rep == "y":
        git("branch -d", branch)

    build()

    print "The release cycle ", release, "is over"


def compile_js():
    """compile_js the javascript code and generate the debug version
    as well as the minified version of the dbui library.

    The compiler verify that the code complied with the class model
    and order the file in the proper way.

    The minified library can be build in several ways, including
    the Ext JS class required by the applications. In the
    current version, the library contains only the dbui classes and
    the Ext JS ones have to be loaded separately. In that sense
    this command is very similar to the yuicompressor one.

    Several compressor can be used yui, closure compiler, ....
    In the current version, the default yui compressor is used?

    This operation relies on the Sencha Cmd:
    http://www.sencha.com/products/sencha-cmd/download

    The details documantation can be found:
    http://docs.sencha.com/extjs/4.2.2/#!/guide/command

    """
    print "Compile the javascript code ..."
    if not os.path.exists(SENCHA):
        print '\n\tThe application sencha is missing !'
        print '\tSee: http://www.sencha.com/products/sencha-cmd/download'
        print '\tSkip this step.\n'
        return

    # clean previous version
300 301 302 303
    for item in (JSLIBDEBUG, JSLIBMIN):
        if os.path.exists(item):
            os.remove(item)
            print 'Remove old javascript library', item
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

    # debug version of the javascript library
    cwd = os.getcwd()

    cmd = ["sencha", "-sdk", opj(cwd, EXTJSSRC),
           "compile", "-class", opj(cwd, JSLIBSRC),
           "exclude", "--namespace", "Ext",
           "and", "concat", opj(cwd, JSLIBDEBUG)]

    call(cmd)

    print 'Debug version of the javascript library', JSLIBDEBUG, 'is ready'

    # Minified version of the javascript library
    cmd = ["sencha", "-sdk", opj(cwd, EXTJSSRC),
           "compile", "-class", opj(cwd, JSLIBSRC),
           "exclude", "--namespace", "Ext",
           "and", "concat", "--yui", opj(cwd, JSLIBMIN)]

    call(cmd)

    print 'Minified version of the javascript library', JSLIBMIN, 'is ready'


def get_version():
LE GAC Renaud's avatar
LE GAC Renaud committed
329 330 331 332
    """Get the current version identifier in the CHANGELOG

    Returns:
        str: the version number
333 334

    """
LE GAC Renaud's avatar
LE GAC Renaud committed
335 336 337 338 339 340 341
    log = open(CHANGELOG).read()

    match = re.search(r"(\d+\.\d+(\.\d+)*)", log)
    if match:
        return match.group(1)

    return ""
342 343


344
def get_identifiers(branch_type):
345
    """Return the list of identifiers for the branch of type branch_type.
346

347 348
    Args:
        branchType (str): one of "feature", "hotfix", "release" or "bugfix"
LE GAC Renaud's avatar
LE GAC Renaud committed
349

350
    Return (str): a list of branch identifiers of type branch_type
351

352 353 354 355 356
    """
    if not os.path.exists(GIT):
        print '\n\tThe application git is missing !'
        sys.exit(-1)

LE GAC Renaud's avatar
LE GAC Renaud committed
357
    output = check_output([GIT, "branch", "--list", branch_type + "-*"])
358
    output = output.rstrip().split("\n")
LE GAC Renaud's avatar
LE GAC Renaud committed
359
    idx = len(branch_type) + 3
360 361 362
    return [branch[idx:] for branch in output]


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
def git(*args, **kwargs):
    """run any git instruction:

    Args:
        *args: list of variable arguments containing git command
            and their options

         **kwargs: keyword argument of the function ``subprocess.call``.

    Examples:
            git("add CHANGELOG foo.txt")
            git("add", CHANGELOG, "foo.txt")
            git("commit", stdout=fi)

    """
    if not os.path.exists(GIT):
        print '\n\tThe application git is missing !'
        print '\tSkip this step.\n'
        return

    cmd = [GIT]
    cmd.extend(args[0].split())

    if len(args) > 1:
        cmd.extend(args[1:])

    call(cmd, **kwargs)


def jsduck():
    """Generate the JavaScript documentation.
    The HTML files are located in static/plugin_dbui/docs/jsduck

    """
    print "Build the javascript documentation..."
    if not os.path.exists(JSDUCK):
        print '\n\tThe application jsduck is missing !'
        print '\tSkip this step.\n'
        return

    # create the directory
    if not os.path.exists(JSDOC):
        os.makedirs(JSDOC)

    # clean the directory
    cmd = ["rm", "-rf", JSDOC]
    call(cmd)

    # run JsDuck
    cmd = ["jsduck", EXTJSSRC, JSLIBSRC, \
           "--output", JSDOC, \
           "--title", "plugin_dbui %s" % get_version(), \
           "--warnings=-all:" + EXTJSSRC]

    call(cmd)

    print "JavaScript documentation in", JSDOC


LE GAC Renaud's avatar
LE GAC Renaud committed
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
def select_identifier(branch_type):
    """Select the identifier to close.

    Args:
        branch_type (str): one of "feature", "hotfix", "release" or "bugfix"

    Returns:
        str: the selected identifier or an empty string if none is selected

    """

    identifiers = get_identifiers(branch_type)
    if not identifiers:
        print "Couldn't find any %s branch" % branch_type
        return ""

    if len(identifiers) == 1:
        rep = raw_input("Close %s '%s' [y/N]:" % (branch_type, identifiers[0]))
        if rep == 'y':
            identifier = identifiers[0]
        else:
            return ""
    else:
        print '%s identifiers:' % branch_type
        print ' ', '\n  '.join(identifiers)
        identifier = raw_input("Select the %s identifier:" % branch_type)
        if not identifier in identifiers:
            return ""

    return identifier


454 455 456 457 458 459 460 461 462 463
def set_version(version):
    """Set release identifier in CHANGELOG and App.js

    Args:
        version (str): release identifier

    """
    print "Update CHANGELOG with the release", version, "..."

    # check tag in git
464 465
    fichier = tempfile.TemporaryFile()
    git("tag", stdout=fichier)
466

467 468
    fichier.seek(0)
    if version in fichier.read():
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        print "\n\tRelease %s already exit in git" % version
        sys.exit(1)

    # look for a pattern HEAD in the CHANGELOG
    # split the the string in 2 parts (pre HEAD, post HEAD)
    print 'Set release', version, 'in', CHANGELOG
    txt = open(CHANGELOG, 'rb').read()

    match = re.match("(.+HEAD\n)(.*)", txt, re.DOTALL)

    if match == None:
        print '\n\tNo HEAD tag in the CHANGELOG!\n'
        rep = raw_input('\tDo you want to continue [n]?')
        if rep not in ('y', 'yes'):
            sys.exit(1)

    # update the version and edit the CHANGELOG
    tpl = (match.group(1), version, NOW.strftime('%b %Y'), match.group(2))
    txt = '%s\n%s (%s)\n%s' % tpl
488 489 490
    fichier = open(CHANGELOG, 'wb')
    fichier.write(txt)
    fichier.close()
491 492 493
    call(["vim", CHANGELOG])

    # cleaning
494 495 496
    filename = "%s~" % CHANGELOG
    if os.path.exists(filename):
        os.remove(filename)
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


def sphinx(*args, **kwargs):
    """run the sphinx-build:

    Args:
        *args: list of variable arguments containing the sphinx-build options.

         **kwargs: keyword argument of the function ``subprocess.call``.

    Examples:

            sphinx("-b html sourcedir outdir")
            sphinx("-b html", sourcedir, outdir)

    """
    if not os.path.exists(SPHINX):
        print '\n\tThe application sphinx is missing !'
        print '\tSkip this step.\n'
        return

    cmd = [SPHINX]
    cmd.extend(args[0].split())

    if len(args) > 1:
        cmd.extend(args[1:])

    call(cmd, **kwargs)


527 528 529 530 531 532
def start_bugfix():
    """Start the bugfix cycle.

    """
    print "Start the bugfix cycle..."

533 534
    issue_number = raw_input("Enter the bugfix issue number [None]:")
    if issue_number and not issue_number.isdigit():
535 536
        print "The issue number must be a number"
        sys.exit(-1)
537

538 539 540 541
    rep = raw_input("Enter the bugfix identifier:")
    if not rep:
        sys.exit(0)

542
    if not issue_number:
543
        branch = "bugfix-%s" % rep
544 545 546
    else:
        branch = "bugfix-%s-%s" % (issue_number, rep)

547 548 549
    git("checkout -b", branch, "develop")


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
def start_feature():
    """Start the feature cycle.

    """
    print "Start the feature cycle..."

    rep = raw_input("Enter the feature identifier:")
    if not rep:
        sys.exit(0)

    branch = "feature-%s" % rep
    git("checkout -b", branch, "develop")


def start_hotfix():
    """Start the hotfix cycle.

    """
    print "Start the hotfix cycle..."
    print "The current release is", get_version()

    rep = raw_input("Enter the hotfix release identifer:")
    if not rep:
        sys.exit(0)

    branch = "hotfix-%s" % rep
    git("checkout -b", branch, "master")

    set_version(rep)
    change_log()


def start_release():
    """Start the release cycle.

    """
    print "Start the release cycle..."

    old_release = get_version()
    print "Current release is", old_release

    new_release = raw_input(MSG_RELEASE)
    if not new_release:
        sys.exit(0)

    branch = "release-%s" % new_release
    git("checkout", "-b", branch, "develop")

    set_version(new_release)
    change_log()
    build()


if __name__ == '__main__':

    # define script options
    OPS = optparse.OptionParser()

    OPS.add_option("-a", "--api-doc",
                   action="store_true",
                   dest="api_doc",
                   help="build the API documentation in HTML.")

    OPS.add_option("--api-pdf",
                   action="store_true",
                   dest="api_pdf",
                   help="build the API documentation in PDF.")

618 619 620 621 622
    OPS.add_option("--start-bugfix",
                   action="store_true",
                   dest="start_bugfix",
                   help="start the bugfix cycle.")

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
    OPS.add_option("--start-feature",
                   action="store_true",
                   dest="start_feature",
                   help="start the feature cycle.")

    OPS.add_option("--start-hotfix",
                   action="store_true",
                   dest="start_hotfix",
                   help="start the hotfix cycle.")

    OPS.add_option("--start-release",
                   action="store_true",
                   dest="start_release",
                   help="start the new release branch cycle.")

    OPS.add_option("--close-hotfix",
                   action="store_true",
                   dest="close_hotfix",
                   help="close the hotfix branch cycle.")

    OPS.add_option("--close-feature",
                   action="store_true",
                   dest="close_feature",
                   help="close the feature branch cycle.")

648 649 650 651 652
    OPS.add_option("--close-bugfix",
                   action="store_true",
                   dest="close_bugfix",
                   help="close the bugfix branch cycle.")

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
    OPS.add_option("--close-release",
                   action="store_true",
                   dest="close_release",
                   help="close the release branch cycle.")

    OPS.add_option("-c", "--compile",
                   action="store_true",
                   dest="compile",
                   help="compile the javascript library.")

    OPS.add_option("--commit-changelog",
                   action="store_true",
                   dest="changelog",
                   help="commit CHANGELOG and App.js.")

    OPS.add_option("-j", "--jsduck",
                   action="store_true",
                   dest="jsduck",
                   help="build the JavaScript documentation.")

    OPS.add_option("-r", "--reference-doc",
                   action="store_true",
                   dest="reference_doc",
                   help="build the reference manual in HTML.")

    OPS.add_option("--reference-pdf",
                   action="store_true",
                   dest="reference_pdf",
                   help="build the reference manual in PDF.")

    OPS.add_option("--write-release",
                   action="store_true",
                   dest="release",
                   help="write the release number in CHANGELOG and App.js.")

    OPS.add_option("-u", "--user-doc",
                   action="store_true",
                   dest="user_doc",
                   help="build the user manual in HTML.")

    OPS.add_option("--user-pdf",
                   action="store_true",
                   dest="user_pdf",
                   help="build the user manual in PDF.")

    OPS.add_option("-v", "--version",
                   action="store_true",
                   dest="version",
                   help="get the current release identifier.")

    OPS.set_defaults(api_doc=False,
                     api_pdf=False,
705
                     close_bugfix=False,
706 707 708 709 710 711 712 713 714
                     close_feature=False,
                     close_hotfix=False,
                     close_release=False,
                     changelog=False,
                     compile=False,
                     jsduck=False,
                     reference_doc=False,
                     reference_pdf=False,
                     release=False,
715
                     start_bugfix=False,
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
                     start_feature=False,
                     start_hotfix=False,
                     start_release=False,
                     user_doc=False,
                     user_pdf=False,
                     version=False)

    (OPT, ARGS) = OPS.parse_args()

    if OPT.api_doc:
        sphinx("-b html", opj(DOCSRC, API), opj(DOCS, API))

    if OPT.api_pdf:
        build_pdf(API)

731 732 733
    if OPT.close_bugfix:
        close_bugfix()

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
    if OPT.close_feature:
        close_feature()

    if OPT.close_hotfix:
        close_hotfix()

    if OPT.close_release:
        close_release()

    if OPT.compile:
        compile_js()

    if OPT.changelog:
        change_log()

    if OPT.jsduck:
        jsduck()

    if OPT.release:
        set_version(raw_input(MSG_RELEASE))

    if OPT.reference_doc:
        sphinx("-b html", opj(DOCSRC, REFERENCE), opj(DOCS, REFERENCE))

    if OPT.reference_pdf:
        build_pdf(REFERENCE)

761 762 763
    if OPT.start_bugfix:
        start_bugfix()

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    if OPT.start_feature:
        start_feature()

    if OPT.start_hotfix:
        start_hotfix()

    if OPT.start_release:
        start_release()

    if OPT.user_doc:
        sphinx("-b html", opj(DOCSRC, USER), opj(DOCS, USER))

    if OPT.user_pdf:
        build_pdf(USER)

    if OPT.version:
        print "\nThe current release is %s\n" % get_version()

LE GAC Renaud's avatar
LE GAC Renaud committed
782
    sys.exit(0)