build_version.py 19.3 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
def select_identifier(branch_type):
168
    """Select the identifier to close.
169

170
    Args:
171 172 173 174
        branch_type (str): one of "feature", "hotfix", "release" or "bugfix"

    Return (str): the selected identifier or an empty string if none is selected

175
    """
176 177

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

182
    if len(identifiers) == 1:
183
        rep = raw_input("Close %s '%s' [y/N]:" % (branch_type, identifiers[0]))
184 185 186
        if rep == 'y':
            identifier = identifiers[0]
        else:
187
            return ""
188
    else:
189
        print '%s identifiers:' % branch_type
190
        print ' ', '\n  '.join(identifiers)
191
        identifier = raw_input("Select the %s identifier:" % branch_type)
192 193
        if not identifier in identifiers:
            return ""
194

195 196 197
    return identifier


198 199 200 201 202 203 204 205 206
def close_bugfix():
    """Close the bugfix cycle.

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

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

208 209 210 211 212 213 214 215 216 217
    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)


218 219 220 221 222 223 224 225 226
def close_feature():
    """Close the feature cycle.

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

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

228
    branch = "feature-%s" % identifier
229 230

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

233
    rep = raw_input("Delete branch %s [y/N]:" % branch)
234
    if rep == 'y':
235
        git("branch -d", branch)
236 237 238 239 240 241 242


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

    """
    print "Close the hotfix cycle..."
243

244
    release = select_identifier("hotfix")
245 246
    if not release:
        sys.exit(0)
247 248

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

    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..."
274
    release = select_identifier("release")
275 276
    if not release:
        sys.exit(0)
277 278

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

    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
331 332 333 334
    for item in (JSLIBDEBUG, JSLIBMIN):
        if os.path.exists(item):
            os.remove(item)
            print 'Remove old javascript library', item
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

    # 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():
    """Get the current version identifier.

    """
363 364 365 366
    fichier = tempfile.TemporaryFile()
    git("describe --tags", stdout=fichier)
    fichier.seek(0)
    return fichier.read()
367 368


369
def get_identifiers(branch_type):
370
    """Return the list of identifiers for the branch of type branch_type.
371

372 373
    Args:
        branchType (str): one of "feature", "hotfix", "release" or "bugfix"
374 375
        
    Return (str): a list of branch identifiers of type branch_type
376

377 378 379 380 381
    """
    if not os.path.exists(GIT):
        print '\n\tThe application git is missing !'
        sys.exit(-1)

382
    output = check_output([GIT, "branch", "--list", branch_type+"-*"])
383
    output = output.rstrip().split("\n")
384
    idx = len(branch_type)+3
385 386 387
    return [branch[idx:] for branch in output]


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
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


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
457 458
    fichier = tempfile.TemporaryFile()
    git("tag", stdout=fichier)
459

460 461
    fichier.seek(0)
    if version in fichier.read():
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        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
481 482 483
    fichier = open(CHANGELOG, 'wb')
    fichier.write(txt)
    fichier.close()
484 485 486
    call(["vim", CHANGELOG])

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


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)


520 521 522 523 524 525
def start_bugfix():
    """Start the bugfix cycle.

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

526 527
    issue_number = raw_input("Enter the bugfix issue number [None]:")
    if issue_number and not issue_number.isdigit():
528 529
        print "The issue number must be a number"
        sys.exit(-1)
530

531 532 533 534
    rep = raw_input("Enter the bugfix identifier:")
    if not rep:
        sys.exit(0)

535
    if not issue_number:
536
        branch = "bugfix-%s" % rep
537 538 539
    else:
        branch = "bugfix-%s-%s" % (issue_number, rep)

540 541 542
    git("checkout -b", branch, "develop")


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
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()


def tag():
    """Tag the current release in git.

    """
    print "Tag the release...",

    version = get_version()
    msg = "Tag %s" % version

    # annotated tag
    print 'git tag', version
    git("tag", "-a", version, "-m", msg)


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.")

625 626 627 628 629
    OPS.add_option("--start-bugfix",
                   action="store_true",
                   dest="start_bugfix",
                   help="start the bugfix cycle.")

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
    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.")

655 656 657 658 659
    OPS.add_option("--close-bugfix",
                   action="store_true",
                   dest="close_bugfix",
                   help="close the bugfix branch cycle.")

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
    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,
712
                     close_bugfix=False,
713 714 715 716 717 718 719 720 721
                     close_feature=False,
                     close_hotfix=False,
                     close_release=False,
                     changelog=False,
                     compile=False,
                     jsduck=False,
                     reference_doc=False,
                     reference_pdf=False,
                     release=False,
722
                     start_bugfix=False,
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                     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)

738 739 740
    if OPT.close_bugfix:
        close_bugfix()

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    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)

768 769 770
    if OPT.start_bugfix:
        start_bugfix()

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    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()

789
    sys.exit(0)