build_version.py 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/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.

    EXAMPLES

            > build_version -h

    AUTHOR
19
          R. Le Gac, renaud.legac@cppm.in2p3.fr
20 21 22 23

    Copyright (c) 2012-2015 R. Le Gac

"""
24
import argparse
25 26 27 28 29 30 31 32
import datetime
import os
import re
import sys
import tempfile


from os.path import join as opj
33
from subprocess import call
34 35 36 37 38

# constants
APP = os.path.basename(os.getcwd())
API = 'api'
CHANGELOG = 'static/CHANGELOG'
39
DBUISRC = 'static/plugin_dbui/src'
40 41 42 43
DOCS = 'static/docs'
DOCSRC = 'docs'
EXTJSSRC = 'static/plugin_extjs/src'
JSDOC = opj(DOCS, 'jsduck')
44 45
JSLIBDEBUG = 'static/%s-debug.js' % APP
JSLIBMIN = 'static/%s-min.js' % APP
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
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()

71
    for doc in (USER,):
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
        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)
118 119
    filenames = [el for el in os.listdir('.') if el.endswith('.tex')]
    filename = (filenames[0] if len(filenames) == 1 else None)
120

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

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

    # move the pdf file
    os.chdir(cwd)

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

136 137
    fin = filename.replace('.tex', '.pdf')
    fout = "%s_%s.pdf" % (os.path.splitext(filename)[0], doc)
138 139 140 141 142 143 144 145 146
    os.rename(opj(latexdoc, fin), opj(pdfdir, fout))

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

    print "PDF documentation in", PDFDOC


def change_log():
147
    """Commit CHANGELOG.
148 149 150 151 152 153 154 155 156 157 158 159 160

    """
    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'
161
    msg = "Start release %s" % get_version()
162 163 164 165 166
    git("commit -m", msg)


def compile_js():
    """compile_js the javascript code and generate the debug version
167
    as well as the minified version.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

    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

184
    The details documentation can be found:
185 186 187 188 189 190 191 192 193 194
    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

195 196 197 198
    if not os.path.exists(JSLIBSRC):
        print 'No javascript library. Exit.'
        return

199
    # clean previous version
200 201 202 203
    for item in (JSLIBDEBUG, JSLIBMIN):
        if os.path.exists(item):
            os.remove(item)
            print 'Remove old javascript library', item
204 205

    # debug version of the javascript library
206 207 208 209
    cmd = ["sencha", "-sdk", EXTJSSRC,
           "compile", "-classpath", "%s,%s" % (JSLIBSRC, DBUISRC),
           "exclude", "--namespace", "Ext,App",
           "and", "concat", JSLIBDEBUG]
210 211 212 213 214 215

    call(cmd)

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

    # Minified version of the javascript library
216 217 218 219
    cmd = ["sencha", "-sdk", EXTJSSRC,
           "compile", "-classpath", "%s,%s" % (JSLIBSRC, DBUISRC),
           "exclude", "--namespace", "Ext,App",
           "and", "concat", "--yui", JSLIBMIN]
220 221 222 223 224 225 226

    call(cmd)

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


def get_version():
LE GAC Renaud's avatar
LE GAC Renaud committed
227 228 229 230
    """Get the current version identifier in the CHANGELOG

    Returns:
        str: the version number
231 232

    """
LE GAC Renaud's avatar
LE GAC Renaud committed
233 234 235 236 237 238 239
    log = open(CHANGELOG).read()

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

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


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

282 283 284 285
    if not os.path.exists(JSLIBSRC):
        print 'No javascript library. Exit.'
        return

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    # 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):
306
    """Set release identifier in CHANGELOG.
307 308 309 310 311 312 313 314

    Args:
        version (str): release identifier

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

    # check tag in git
315 316
    fichier = tempfile.TemporaryFile()
    git("tag", stdout=fichier)
317

318 319
    fichier.seek(0)
    if version in fichier.read():
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        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
339 340 341
    fichier = open(CHANGELOG, 'wb')
    fichier.write(txt)
    fichier.close()
342 343 344
    call(["vim", CHANGELOG])

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


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_release():
    """Start the release cycle.

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

384 385
    git("checkout", "master")

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    old_release = get_version()
    print "Current release is", old_release

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

    set_version(new_release)
    change_log()
    build()


if __name__ == '__main__':

    # define script options
401
    APS = argparse.ArgumentParser()
402

403 404 405 406 407 408 409
    APS.add_argument("-a", "--api-doc",
                     action="store_true",
                     help="build the API documentation in HTML.")

    APS.add_argument("-A", "--api-pdf",
                     action="store_true",
                     help="build the API documentation in PDF.")
410

411 412 413 414
    APS.add_argument("-b", "--build",
                     action="store_true",
                     help="build the javascript library and the documentation.")

415 416 417
    APS.add_argument("-c", "--compile",
                     action="store_true",
                     help="compile the javascript library.")
418

419 420 421
    APS.add_argument("-C", "--commit-changelog",
                     action="store_true",
                     help="commit CHANGELOG.")
422

423 424 425
    APS.add_argument("-j", "--jsduck",
                     action="store_true",
                     help="build the JavaScript documentation.")
426

427 428 429
    APS.add_argument("-r", "--reference-doc",
                     action="store_true",
                     help="build the reference manual in HTML.")
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
    APS.add_argument("-R", "--reference-pdf",
                     action="store_true",
                     help="build the reference manual in PDF.")

    APS.add_argument("-s", "--start-release",
                     action="store_true",
                     help="start the new release.")

    APS.add_argument("-u", "--user-doc",
                     action="store_true",
                     help="build the user manual in HTML.")

    APS.add_argument("-U", "--user-pdf",
                     action="store_true",
                     help="build the user manual in PDF.")

    APS.add_argument("-v", "--version",
                     action="store_true",
                     help="get the current release identifier.")

    APS.add_argument("-w", "--write-release",
                     action="store_true",
                     help="write the release number in CHANGELOG.")

    ARGS = APS.parse_args()

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

    if ARGS.api_pdf:
        build_pdf(API)

463 464 465
    if ARGS.build:
        build()

466
    if ARGS.compile:
467 468
        compile_js()

469
    if ARGS.commit_changelog:
470 471
        change_log()

472
    if ARGS.jsduck:
473 474
        jsduck()

475
    if ARGS.write_release:
476 477
        set_version(raw_input(MSG_RELEASE))

478
    if ARGS.reference_doc:
479 480
        sphinx("-b html", opj(DOCSRC, REFERENCE), opj(DOCS, REFERENCE))

481
    if ARGS.reference_pdf:
482 483
        build_pdf(REFERENCE)

484
    if ARGS.start_release:
485 486
        start_release()

487
    if ARGS.user_doc:
488 489
        sphinx("-b html", opj(DOCSRC, USER), opj(DOCS, USER))

490
    if ARGS.user_pdf:
491 492
        build_pdf(USER)

493
    if ARGS.version:
494 495
        print "\nThe current release is %s\n" % get_version()

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