build_version.py 17.4 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 36
#!/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
import urllib


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

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

    if not fn:
        print "\n\tNo latex file !"
        return

    # process the latex file twice
    call([PDFLATEX, fn])
    call([PDFLATEX, fn])

    # move the pdf file
    os.chdir(cwd)

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

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


def close_feature():
    """Close the feature cycle.

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

174 175 176
    identifiers = get_identifiers("feature")
    if not identifiers:
        print "Couldn't find any feature branche to close"
177
        sys.exit(0)
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    
    if len(identifiers) == 1:
        rep = raw_input("Close feature '%s' [y/N]:" % identifiers[0])
        if rep == 'y':
            identifier = identifiers[0]
        else:
            sys.exit(0)
    else:
        print 'List of features in development:'
        print ' ', '\n  '.join(identifiers)
        identifier = raw_input("Select the feature identifier:")
        if not identifier:
            sys.exit(0)
        
    branch = "feature-%s" % identifier
193 194 195 196

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

197
    rep = raw_input("Delete the locale branch %s [y/N]" % branch)
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
    if rep == 'y':
        git("branch -d", branch)


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

    """
    print "Close the hotfix cycle..."
    print "Current branches are:"
    git("branch")

    release = raw_input("Select the hotfix identifier:")
    if not release:
        sys.exit(0)

    branch = "hotfix-%s" % release

    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..."
    print "Current branches are:"
    git("branch")

    release = raw_input("Select the release identifier:")
    if not release:
        sys.exit(0)

    branch = "release-%s" % release

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

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

    """
    fi = tempfile.TemporaryFile()
    git("describe --tags", stdout=fi)
    fi.seek(0)
    return fi.read()


338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
def get_identifiers(branchType):
    """Print out the list of identifiers for the branch type.
    
    Args:
        branchType (str): one of "feature", "hotfix", "release" or "bugfix"
    
    """
    if not os.path.exists(GIT):
        print '\n\tThe application git is missing !'
        sys.exit(-1)

    output = check_output([GIT, "branch", "--list", branchType+"-*"])
    output = output.rstrip().split("\n")
    idx = len(branchType)+3
    return [branch[idx:] for branch in output]


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
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
    fi = tempfile.TemporaryFile()
    git("tag", stdout=fi)

    fi.seek(0)
    if version in fi.read():
        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
    fi = open(CHANGELOG, 'wb')
    fi.write(txt)
    fi.close()
    call(["vim", CHANGELOG])

    # cleaning
    fn = "%s~" % CHANGELOG
    if os.path.exists(fn):
        os.remove(fn)


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)


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

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

    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,
                     close_feature=False,
                     close_hotfix=False,
                     close_release=False,
                     changelog=False,
                     compile=False,
                     jsduck=False,
                     reference_doc=False,
                     reference_pdf=False,
                     release=False,
                     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)

    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)

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

    sys.exit(0)