# Path: tldp/utils.py
# def execute(cmd, stdin=None, stdout=None, stderr=None,
#             logdir=None, env=os.environ):
#     '''(yet another) wrapper around subprocess.Popen()
# 
#     The processing tools for handling DocBook SGML, DocBook XML and Linuxdoc
#     all use different conventions for writing outputs.  Some write into the
#     working directory.  Others write to STDOUT.  Others accept the output file
#     as a required option.
# 
#     To allow for automation and flexibility, this wrapper function does what
#     most other synchronous subprocess.Popen() wrappers does, but it adds a
#     feature to record the STDOUT and STDERR of the executable.  This is
#     helpful when trying to diagnose build failures of individual documents.
# 
#     Required:
# 
#       - cmd: (list form only; the paranoid prefer shell=False)
#         this must include the whole command-line
#       - logdir: an existing directory in which temporary log files
#         will be created
# 
#     Optional:
# 
#       - stdin: if not supplied, STDIN (FD 0) will be left as is
#       - stdout: if not supplied, STDOUT (FD 1) will be connected
#         to a named file in the logdir (and left for later inspection)
#       - stderr: if not supplied, STDERR (FD 2) will be connected
#         to a named file in the logdir (and left for later inspection)
#       - env: if not supplied, just use current environment
# 
#     Returns: the numeric exit code of the process
# 
#     Side effects:
# 
#       * will probably create temporary files in logdir
#       * function calls wait(); process execution will intentionally block
#         until the child process terminates
# 
#     Possible exceptions:
# 
#       * if the first element of list cmd does not contain an executable,
#         this function will raise an AssertionError
#       * if logdir is not a directory, this function will raise ValueError or
#         IOError
#       * and, of course, any exceptions passed up from calling subprocess.Popen
# 
#     '''
#     prefix = os.path.basename(cmd[0]) + '.' + str(os.getpid()) + '-'
# 
#     assert isexecutable(cmd[0])
# 
#     if logdir is None:
#         raise ValueError("logdir must be a directory, cannot be None.")
# 
#     if not os.path.isdir(logdir):
#         raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), logdir)
# 
#     # -- not remapping STDIN, because that doesn't make sense here
#     mytfile = functools.partial(mkstemp, prefix=prefix, dir=logdir)
#     if stdout is None:
#         stdout, stdoutname = mytfile(suffix='.stdout')
#     else:
#         stdoutname = None
# 
#     if stderr is None:
#         stderr, stderrname = mytfile(suffix='.stderr')
#     else:
#         stderrname = None
# 
#     logger.debug("About to execute: %r", cmd)
#     proc = subprocess.Popen(cmd, shell=False, close_fds=True,
#                             stdin=stdin, stdout=stdout, stderr=stderr,
#                             env=env, preexec_fn=os.setsid)
#     result = proc.wait()
#     if result != 0:
#         logger.error("Non-zero exit (%s) for process: %r", result, cmd)
#         logger.error("Find STDOUT/STDERR in %s/%s*", logdir, prefix)
#     if isinstance(stdout, int) and stdoutname:
#         os.close(stdout)
#         conditionallogging(result, 'STDOUT', stdoutname)
#     if isinstance(stderr, int) and stderrname:
#         os.close(stderr)
#         conditionallogging(result, 'STDERR', stderrname)
#     return result
# 
# def logtimings(logmethod):
#     def anon(f):
#         @wraps(f)
#         def timing(*args, **kwargs):
#             s = time.time()
#             result = f(*args, **kwargs)
#             e = time.time()
#             logmethod('running %s(%r, %r) took %.3f s',
#                       f.__name__, args, kwargs, e - s)
#             return result
#         return timing
#     return anon
# 
# def writemd5sums(fname, md5s, header=None):
#     '''write an MD5SUM file from [(filename, MD5), ...]'''
#     with codecs.open(fname, 'w', encoding='utf-8') as file:
#         if header:
#             print(header, file=file)
#         for fname, hashval in sorted(md5s.items()):
#             print(hashval + '  ' + fname, file=file)


import os
import sys
import stat
import time
import errno
import codecs
import shutil
import logging
import inspect
import networkx as nx
from tempfile import NamedTemporaryFile as ntf
from functools import wraps
from tldp.utils import execute, logtimings, writemd5sums
        logger.info("%s build SUCCESS  %s.", stem, dirname)
        logger.debug("%s removing logs  %s)", stem, logdir)
        if os.path.isdir(logdir):
            shutil.rmtree(logdir)
        return True

    def hook_build_failure(self):
        pass

    def shellscript(self, script, **kwargs):
        if self.config.build:
            return self.execute_shellscript(script, **kwargs)
        elif self.config.script:
            return self.dump_shellscript(script, **kwargs)
        else:
            etext = '%s in shellscript, neither --build nor --script'
            raise Exception(etext % (self.source.stem,))

    @logtimings(logger.debug)
    def dump_shellscript(self, script, preamble=preamble,
                         postamble=postamble, **kwargs):
        source = self.source
        output = self.output
        config = self.config
        file = kwargs.get('file', sys.stdout)
        s = script.format(output=output, source=source, config=config)
        print('', file=file)
        print(s, file=file)
        return True


# Path: tldp/utils.py
# def execute(cmd, stdin=None, stdout=None, stderr=None,
#             logdir=None, env=os.environ):
#     '''(yet another) wrapper around subprocess.Popen()
# 
#     The processing tools for handling DocBook SGML, DocBook XML and Linuxdoc
#     all use different conventions for writing outputs.  Some write into the
#     working directory.  Others write to STDOUT.  Others accept the output file
#     as a required option.
# 
#     To allow for automation and flexibility, this wrapper function does what
#     most other synchronous subprocess.Popen() wrappers does, but it adds a
#     feature to record the STDOUT and STDERR of the executable.  This is
#     helpful when trying to diagnose build failures of individual documents.
# 
#     Required:
# 
#       - cmd: (list form only; the paranoid prefer shell=False)
#         this must include the whole command-line
#       - logdir: an existing directory in which temporary log files
#         will be created
# 
#     Optional:
# 
#       - stdin: if not supplied, STDIN (FD 0) will be left as is
#       - stdout: if not supplied, STDOUT (FD 1) will be connected
#         to a named file in the logdir (and left for later inspection)
#       - stderr: if not supplied, STDERR (FD 2) will be connected
#         to a named file in the logdir (and left for later inspection)
#       - env: if not supplied, just use current environment
# 
#     Returns: the numeric exit code of the process
# 
#     Side effects:
# 
#       * will probably create temporary files in logdir
#       * function calls wait(); process execution will intentionally block
#         until the child process terminates
# 
#     Possible exceptions:
# 
#       * if the first element of list cmd does not contain an executable,
#         this function will raise an AssertionError
#       * if logdir is not a directory, this function will raise ValueError or
#         IOError
#       * and, of course, any exceptions passed up from calling subprocess.Popen
# 
#     '''
#     prefix = os.path.basename(cmd[0]) + '.' + str(os.getpid()) + '-'
# 
#     assert isexecutable(cmd[0])
# 
#     if logdir is None:
#         raise ValueError("logdir must be a directory, cannot be None.")
# 
#     if not os.path.isdir(logdir):
#         raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), logdir)
# 
#     # -- not remapping STDIN, because that doesn't make sense here
#     mytfile = functools.partial(mkstemp, prefix=prefix, dir=logdir)
#     if stdout is None:
#         stdout, stdoutname = mytfile(suffix='.stdout')
#     else:
#         stdoutname = None
# 
#     if stderr is None:
#         stderr, stderrname = mytfile(suffix='.stderr')
#     else:
#         stderrname = None
# 
#     logger.debug("About to execute: %r", cmd)
#     proc = subprocess.Popen(cmd, shell=False, close_fds=True,
#                             stdin=stdin, stdout=stdout, stderr=stderr,
#                             env=env, preexec_fn=os.setsid)
#     result = proc.wait()
#     if result != 0:
#         logger.error("Non-zero exit (%s) for process: %r", result, cmd)
#         logger.error("Find STDOUT/STDERR in %s/%s*", logdir, prefix)
#     if isinstance(stdout, int) and stdoutname:
#         os.close(stdout)
#         conditionallogging(result, 'STDOUT', stdoutname)
#     if isinstance(stderr, int) and stderrname:
#         os.close(stderr)
#         conditionallogging(result, 'STDERR', stderrname)
#     return result
# 
# def logtimings(logmethod):
#     def anon(f):
#         @wraps(f)
#         def timing(*args, **kwargs):
#             s = time.time()
#             result = f(*args, **kwargs)
#             e = time.time()
#             logmethod('running %s(%r, %r) took %.3f s',
#                       f.__name__, args, kwargs, e - s)
#             return result
#         return timing
#     return anon
# 
# def writemd5sums(fname, md5s, header=None):
#     '''write an MD5SUM file from [(filename, MD5), ...]'''
#     with codecs.open(fname, 'w', encoding='utf-8') as file:
#         if header:
#             print(header, file=file)
#         for fname, hashval in sorted(md5s.items()):
#             print(hashval + '  ' + fname, file=file)


# Path: tldp/doctypes/common.py
import os
import sys
import stat
import time
import errno
import codecs
import shutil
import logging
import inspect
import networkx as nx
from tempfile import NamedTemporaryFile as ntf
from functools import wraps
from tldp.utils import execute, logtimings, writemd5sums

        logger.info("%s build SUCCESS  %s.", stem, dirname)
        logger.debug("%s removing logs  %s)", stem, logdir)
        if os.path.isdir(logdir):
            shutil.rmtree(logdir)
        return True

    def hook_build_failure(self):
        pass

    def shellscript(self, script, **kwargs):
        if self.config.build:
            return self.execute_shellscript(script, **kwargs)
        elif self.config.script:
            return self.dump_shellscript(script, **kwargs)
        else:
            etext = '%s in shellscript, neither --build nor --script'
            raise Exception(etext % (self.source.stem,))

    @logtimings(logger.debug)
    def dump_shellscript(self, script, preamble=preamble,
                         postamble=postamble, **kwargs):
        source = self.source
        output = self.output
        config = self.config
        file = kwargs.get('file', sys.stdout)
        s = script.format(output=output, source=source, config=config)
        print('', file=file)
        print(s, file=file)
        return True


    @logtimings(logger.debug)