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
#!/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
33
#import urllib
34 35 36


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

# 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)
121 122
    filenames = [el for el in os.listdir('.') if el.endswith('.tex')]
    filename = (filenames[0] if len(filenames) == 1 else None)
123

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

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

    # move the pdf file
    os.chdir(cwd)

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

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


168
def select_identifier(branch_type):
169
    """Select the identifier to close.
170

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

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

176
    """
177 178

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

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

196 197 198
    return identifier


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

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

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

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


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

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

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

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

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

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


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

    """
    print "Close the hotfix cycle..."
244

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

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

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

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

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

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

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


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

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

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

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


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

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

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


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)


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

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

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

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

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

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


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

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

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

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

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

739 740 741
    if OPT.close_bugfix:
        close_bugfix()

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

769 770 771
    if OPT.start_bugfix:
        start_bugfix()

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

790
    sys.exit(0)