# -*- coding: utf-8 -*-""" sphinx.cmdline ~~~~~~~~~~~~~~ sphinx-build command-line handling. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details."""importosimportsysimportgetoptimporttracebackfromosimportpathfromdocutils.utilsimportSystemMessagefromsphinximport__version__fromsphinx.errorsimportSphinxErrorfromsphinx.applicationimportSphinxfromsphinx.utilimportTee,format_exception_cut_frames,save_tracebackfromsphinx.util.consoleimportred,nocolor,color_terminalfromsphinx.util.osutilimportfs_encodingfromsphinx.util.pycompatimportterminal_safe,bytesdefabspath(pathdir):pathdir=path.abspath(pathdir)ifisinstance(pathdir,bytes):pathdir=pathdir.decode(fs_encoding)returnpathdirdefusage(argv,msg=None):ifmsg:print>>sys.stderr,msgprint>>sys.stderrprint>>sys.stderr,"""\Sphinx v%sUsage: %s [options] sourcedir outdir [filenames...]General options^^^^^^^^^^^^^^^-b <builder> builder to use; default is html-a write all files; default is to only write new and changed files-E don't use a saved environment, always read all files-d <path> path for the cached environment and doctree files (default: outdir/.doctrees)Build configuration options^^^^^^^^^^^^^^^^^^^^^^^^^^^-c <path> path where configuration file (conf.py) is located (default: same as sourcedir)-C use no config file at all, only -D options-D <setting=value> override a setting in configuration file-t <tag> define tag: include "only" blocks with <tag>-A <name=value> pass a value into the templates, for HTML builder-n nit-picky mode, warn about all missing referencesConsole output options^^^^^^^^^^^^^^^^^^^^^^-v increase verbosity (can be repeated)-q no output on stdout, just warnings on stderr-Q no output at all, not even warnings-w <file> write warnings (and errors) to given file-W turn warnings into errors-T show full traceback on exception-N do not emit colored output-P run Pdb on exceptionFilename arguments^^^^^^^^^^^^^^^^^^* without -a and without filenames, write new and changed files.* with -a, write all files.* with filenames, write these.Standard options^^^^^^^^^^^^^^^^-h, --help show this help and exit--version show version information and exit"""%(__version__,argv[0])defmain(argv):ifnotcolor_terminal():# Windows' poor cmd box doesn't understand ANSI sequencesnocolor()try:opts,args=getopt.getopt(argv[1:],'ab:t:d:c:CD:A:nNEqQWw:PThv',['help','version'])allopts=set(opt[0]foroptinopts)if'-h'inalloptsor'--help'inallopts:usage(argv)print>>sys.stderrprint>>sys.stderr,'For more information, see '\
'<http://sphinx-doc.org/>.'return0if'--version'inallopts:print'Sphinx (sphinx-build) %s'%__version__return0srcdir=confdir=abspath(args[0])ifnotpath.isdir(srcdir):print>>sys.stderr,'Error: Cannot find source directory `%s\'.'%(srcdir,)return1ifnotpath.isfile(path.join(srcdir,'conf.py'))and \
'-c'notinalloptsand'-C'notinallopts:print>>sys.stderr,('Error: Source directory doesn\'t ''contain conf.py file.')return1outdir=abspath(args[1])exceptgetopt.error,err:usage(argv,'Error: %s'%err)return1exceptIndexError:usage(argv,'Error: Insufficient arguments.')return1filenames=args[2:]err=0forfilenameinfilenames:ifnotpath.isfile(filename):print>>sys.stderr,'Error: Cannot find file %r.'%filenameerr=1iferr:return1# likely encoding used for command-line argumentstry:locale=__import__('locale')# due to submodule of the same namelikely_encoding=locale.getpreferredencoding()exceptException:likely_encoding=Nonebuildername=Noneforce_all=freshenv=warningiserror=use_pdb=Falseshow_traceback=Falseverbosity=0status=sys.stdoutwarning=sys.stderrerror=sys.stderrwarnfile=Noneconfoverrides={}tags=[]doctreedir=path.join(outdir,'.doctrees')foropt,valinopts:ifopt=='-b':buildername=valelifopt=='-a':iffilenames:usage(argv,'Error: Cannot combine -a option and filenames.')return1force_all=Trueelifopt=='-t':tags.append(val)elifopt=='-d':doctreedir=abspath(val)elifopt=='-c':confdir=abspath(val)ifnotpath.isfile(path.join(confdir,'conf.py')):print>>sys.stderr,('Error: Configuration directory ''doesn\'t contain conf.py file.')return1elifopt=='-C':confdir=Noneelifopt=='-D':try:key,val=val.split('=')exceptValueError:print>>sys.stderr,('Error: -D option argument must be ''in the form name=value.')return1try:val=int(val)exceptValueError:iflikely_encodingandisinstance(val,bytes):try:val=val.decode(likely_encoding)exceptUnicodeError:passconfoverrides[key]=valelifopt=='-A':try:key,val=val.split('=')exceptValueError:print>>sys.stderr,('Error: -A option argument must be ''in the form name=value.')return1try:val=int(val)exceptValueError:iflikely_encodingandisinstance(val,bytes):try:val=val.decode(likely_encoding)exceptUnicodeError:passconfoverrides['html_context.%s'%key]=valelifopt=='-n':confoverrides['nitpicky']=Trueelifopt=='-N':nocolor()elifopt=='-E':freshenv=Trueelifopt=='-q':status=Noneelifopt=='-Q':status=Nonewarning=Noneelifopt=='-W':warningiserror=Trueelifopt=='-w':warnfile=valelifopt=='-P':use_pdb=Trueelifopt=='-T':show_traceback=Trueelifopt=='-v':verbosity+=1show_traceback=Trueifwarningandwarnfile:warnfp=open(warnfile,'w')warning=Tee(warning,warnfp)error=warningifnotpath.isdir(outdir):ifstatus:print>>status,'Making output directory...'os.makedirs(outdir)try:app=Sphinx(srcdir,confdir,outdir,doctreedir,buildername,confoverrides,status,warning,freshenv,warningiserror,tags,verbosity)app.build(force_all,filenames)returnapp.statuscodeexcept(Exception,KeyboardInterrupt),err:ifuse_pdb:importpdbprint>>error,red('Exception occurred while building, ''starting debugger:')traceback.print_exc()pdb.post_mortem(sys.exc_info()[2])else:print>>errorifshow_traceback:traceback.print_exc(None,error)print>>errorifisinstance(err,KeyboardInterrupt):print>>error,'interrupted!'elifisinstance(err,SystemMessage):print>>error,red('reST markup error:')print>>error,terminal_safe(err.args[0])elifisinstance(err,SphinxError):print>>error,red('%s:'%err.category)print>>error,terminal_safe(unicode(err))else:print>>error,red('Exception occurred:')print>>error,format_exception_cut_frames().rstrip()tbpath=save_traceback()print>>error,red('The full traceback has been saved ''in %s, if you want to report the ''issue to the developers.'%tbpath)print>>error,('Please also report this if it was a user ''error, so that a better error message ''can be provided next time.')print>>error,('Either send bugs to the mailing list at ''<http://groups.google.com/group/sphinx-users/>,\n''or report them in the tracker at ''<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!')return1