build_version.py 12 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 39 40 41 42

# 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')
43 44
JSLIBDEBUG = 'static/%s-debug.js' % APP
JSLIBMIN = 'static/%s-min.js' % APP
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
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)
117 118
    filenames = [el for el in os.listdir('.') if el.endswith('.tex')]
    filename = (filenames[0] if len(filenames) == 1 else None)
119

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

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

    # move the pdf file
    os.chdir(cwd)

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

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

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

    print "PDF documentation in", PDFDOC


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

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


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

    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

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

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

198
    # clean previous version
199 200 201 202
    for item in (JSLIBDEBUG, JSLIBMIN):
        if os.path.exists(item):
            os.remove(item)
            print 'Remove old javascript library', item
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

    # 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
228 229 230 231
    """Get the current version identifier in the CHANGELOG

    Returns:
        str: the version number
232 233

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

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

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


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

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

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

    Args:
        version (str): release identifier

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

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

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

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


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

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

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    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
402
    APS = argparse.ArgumentParser()
403

404 405 406 407 408 409 410
    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.")
411

412 413 414
    APS.add_argument("-c", "--compile",
                     action="store_true",
                     help="compile the javascript library.")
415

416 417 418
    APS.add_argument("-C", "--commit-changelog",
                     action="store_true",
                     help="commit CHANGELOG.")
419

420 421 422
    APS.add_argument("-j", "--jsduck",
                     action="store_true",
                     help="build the JavaScript documentation.")
423

424 425 426
    APS.add_argument("-r", "--reference-doc",
                     action="store_true",
                     help="build the reference manual in HTML.")
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
    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)

    if ARGS.compile:
461 462
        compile_js()

463
    if ARGS.commit_changelog:
464 465
        change_log()

466
    if ARGS.jsduck:
467 468
        jsduck()

469
    if ARGS.write_release:
470 471
        set_version(raw_input(MSG_RELEASE))

472
    if ARGS.reference_doc:
473 474
        sphinx("-b html", opj(DOCSRC, REFERENCE), opj(DOCS, REFERENCE))

475
    if ARGS.reference_pdf:
476 477
        build_pdf(REFERENCE)

478
    if ARGS.start_release:
479 480
        start_release()

481
    if ARGS.user_doc:
482 483
        sphinx("-b html", opj(DOCSRC, USER), opj(DOCS, USER))

484
    if ARGS.user_pdf:
485 486
        build_pdf(USER)

487
    if ARGS.version:
488 489
        print "\nThe current release is %s\n" % get_version()

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