Blame view

obs/re6st/make 9.85 KB
Julien Muchembled committed
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 37 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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
#!/usr/bin/env python
#
# Copyright (C) 2016 Julien Muchembled <jm@nexedi.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
  Very basic Python implementation of a build system similar to the well-known
  'make'. The main concept is the same:
    input files --( recipe )-> output files
  with comparison of timestamps to trigger recipes
  (i.e. no temporary files generated to track the status of the build).
  The main differences are:
  - no parallelism
  - no implicit rule, no predefined rule
  + inputs can be whole directory
  + change time of inputs is also taken into account
  + multiple list of outputs for a recipe
  + dynamic list of outputs
  + no need to care about wrongly/partially written files in case of failure
  + Python...
"""
import argparse, atexit, errno, gzip, os, shutil, subprocess, sys, tarfile
from contextlib import contextmanager

INF = float("inf")
_INF = - INF

class _task(object):

    def __init__(self, *src):
        self.outputs = src

    def __str__(self):
        o = self.outputs
        return repr(o[0]) if len(o) == 1 else str(o)

    @property
    def output(self):
        o, = self.outputs
        return o

    def __call__(self, dry_run):
        run = self._run
        if callable(run):
            self._run = run = run(dry_run)
        return run

    @staticmethod
    def _time(path):
        return os.stat(path).st_mtime

    def _run(self, dry_run=None):
        x = self.outputs
        return max(map(self._time, x)) if x else _INF

class files(_task):

    def __init__(self, *src, **kw):
        if not kw.pop("ctime", True):
            self._time = _task._time
        _task.__init__(self, *src, **kw)

    @staticmethod
    def _time(path):
        s = os.stat(path)
        return max(s.st_ctime, s.st_mtime)

class tree(files):
    """
    e.g. @task(tree("some/folder"), "some/output")
    """

    def __init__(self, root, ignore=None, **kw):
        files.__init__(self, root, **kw)
        self.ignore = ignore

    def __iter__(self):
        root, = self.outputs
        yield root
        ignore = self.ignore
        n = len(root) + 1
        for dirpath, dirs, files in os.walk(root):
            dirpath += os.sep
            if ignore:
                x = dirpath[n:]
                dirs[:] = (name for name in dirs if not ignore(x + name))
            for name in dirs:
                yield dirpath + name
            for name in files:
                x = dirpath + name
                if not (ignore and ignore(x[n:])):
                    yield x

    def _run(self, dry_run=None):
        return max(map(self._time, self))

class task(_task):
    """
    @task(depends, provides)
    def mytask(task):
        # task.inputs
        # task.outputs

    'depends' is a sequence of other tasks or file paths. The order is important
    because it defines the order of task.inputs: not however that paths are
    automatically moved after tasks.

    'provides' is a sequence of callables or file paths. Callables are always
    called to complete task.outputs. Recipe is always called if task.outputs
    is empty.

    For both 'depends' and 'provides', if you have only 1 element, you can pass
    it directly instead of making a 1-size sequence.

    'input' and 'output' properties are shortcut to get the only path.
    'why' is a list of tasks explaining why the recipe is called.
    """

    def __new__(cls, *args, **kw):
        def task_gen(func):
            self = _task.__new__(cls)
            self.__init__(func, *args, **kw)
            return self
        return task_gen

    def __init__(self, run, depends, provides=(),
                 __str_or_task = (basestring, _task)):
        self.run = run
        self.depends = []
        f = []
        for x in (depends,) if isinstance(depends, __str_or_task) else depends:
            (f if isinstance(x, basestring) else self.depends).append(x)
        f and self.depends.append(files(*f))
        self.provides = ((provides,)
            if isinstance(provides, basestring) or callable(provides)
            else provides)
        self.why = self,

    def __str__(self):
        return self.run.__name__

    @property
    def input(self):
        i, = self.inputs
        return i

    def _run(self, dry_run, _otime=INF):
        self.inputs = x = []
        deps = []
        for dep in self.depends:
            deps.append((dep, dep(dry_run)))
            x += dep.outputs
        self.outputs = x = []
        for p in self.provides:
            if callable(p):
                x += p(self)
            else:
                x.append(p)
        if None not in x:
            try:
                _otime = _task._run(self)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            else:
                if deps:
                    self.why = [dep for dep, itime in deps if _otime < itime]
        if self.why:
            print "# Processing %s: %s -> %s" % (self,
                ", ".join(map(str, self.depends)),
                ", ".join("<%s>" % x.__name__ if callable(x) else x
                          for x in self.provides or "?"))
            if not dry_run:
                try:
                    self.run(self)
                except:
                    if _otime is INF:
                        _otime = max(x[1] for x in deps) - 1
                    # Files may still be open due to references in tracebacks.
                    # Make sure they're all closed before reverting mtimes.
                    atexit.register(self._revert, self.outputs, _otime)
                    raise
                return _task._run(self) if self.outputs else INF
        return _otime

    @classmethod
    def _revert(cls, outputs, mtime):
        try:
            for x in outputs:
                if mtime < cls._time(x):
                    os.utime(x, (mtime, mtime))
        except Exception:
            pass

def main():
    parser = argparse.ArgumentParser()
    _ = parser.add_argument
    _("-f", "--file", type=argparse.FileType("r"), default="make.py",
      help="Python script describing how to build the project"
           " (default: make.py).")
    _("-l", "--list", action="store_true",
      help="List defined tasks.")
    _("-n", "--dry-run", action="store_true",
      help="Print the tasks that would be executed.")
    _("task", nargs="*", default=("build",),
      help="Tasks to process (default: build).")
    args = parser.parse_args()

    sys.modules["make"] = sys.modules.pop(__name__)
    f = args.file
    tasks = {"__file__": f.name}
    exec(compile(f.read(), f.name, "exec"), tasks)
    if args.list:
        print " ".join(sorted(k for k, v in tasks.iteritems()
                                if isinstance(v, _task)))
        return
    for t in args.task:
        if not isinstance(tasks.get(t), _task):
            sys.exit("%s is not a valid task." % t)
    for t in args.task:
        tasks[t](args.dry_run)

##
# Helpers
#

class git(tree):

    def __init__(self, root, url=None, ignore=None, **kw):
        _ignore = lambda x: x == ".git" or ignore and ignore(x)
        tree.__init__(self, root, _ignore, **kw)
        self.url = url

    def _run(self, dry_run):
        root, = self.outputs
        if os.path.isdir(root):
            return tree._run(self)
        dry_run or subprocess.check_call(("git", "clone", self.url, root))
        return _INF

def check_output(*args, **kw):
    # BBB: 'input' arg is a backport from Python 3.4
    input = kw.pop("input", None)
    if input is not None:
        kw["stdin"] = subprocess.PIPE
    p = subprocess.Popen(stdout=subprocess.PIPE, *args, **kw)
    out = p.communicate(input)[0]
    if p.returncode:
        raise subprocess.CalledProcessError(p.returncode,
            args[0] if args else kw["args"])
    return out

@contextmanager
def cwd(path):
    p = os.getcwd()
    try:
        os.chdir(path)
        yield p
    finally:
        os.chdir(p)

def mkdir(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno != errno.EEXIST or not os.path.isdir(path):
            raise

def remove(path):
    try:
        os.remove(path)
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise

def rmtree(path):
    if os.path.exists(path):
        shutil.rmtree(path)

@contextmanager
def make_tar_gz(path, mtime, xform=(lambda x: x), **kw):
    # Make reproducible tarball. Otherwise, it's really annoying that we can't
    # rely on 'osc status' to know whether there are real changes or not.
    # BBB: Results differ between Python 2.6 and 2.7 because of tarfile.
    __init__ = gzip.GzipFile.__init__
    listdir = os.listdir
    try:
        if sys.version_info >= (2, 7):
            gzip.GzipFile.__init__ = lambda *args: __init__(mtime=mtime, *args)
        os.listdir = lambda path: sorted(listdir(path))
        t = tarfile.open(path, "w:gz", **kw)
        _gettarinfo = t.gettarinfo
        def gettarinfo(name=None, arcname=None, fileobj=None):
            tarinfo = _gettarinfo(name, xform(arcname or name), fileobj)
            tarinfo.mtime = mtime
            return tarinfo
        t.gettarinfo = gettarinfo
        yield t
    except:
        remove(path)
        raise
    finally:
        gzip.GzipFile.__init__ = __init__
        os.listdir = listdir
        t.close()
    if sys.version_info < (2, 7):
        with open(path, "r+") as t:
            t.seek(4)
            gzip.write32u(t, long(mtime))

if __name__ == "__main__":
    sys.exit(main())