| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2019 Red Hat, Inc. |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import typing as T |
| 7 |
|
| 8 |
|
| 9 |
def parse(lines: T.Iterable[str]) -> T.List[T.Tuple[T.List[str], T.List[str]]]: |
| 10 |
rules: T.List[T.Tuple[T.List[str], T.List[str]]] = [] |
| 11 |
targets: T.List[str] = [] |
| 12 |
deps: T.List[str] = [] |
| 13 |
in_deps = False |
| 14 |
out = '' |
| 15 |
for line in lines: |
| 16 |
if not line.endswith('\n'): |
| 17 |
line += '\n' |
| 18 |
escape = None |
| 19 |
for c in line: |
| 20 |
if escape: |
| 21 |
if escape == '$' and c != '$': |
| 22 |
out += '$' |
| 23 |
if escape == '\\' and c == '\n': |
| 24 |
continue |
| 25 |
out += c |
| 26 |
escape = None |
| 27 |
continue |
| 28 |
if c in {'\\', '$'}: |
| 29 |
escape = c |
| 30 |
continue |
| 31 |
elif c in {' ', '\n'}: |
| 32 |
if out != '': |
| 33 |
if in_deps: |
| 34 |
deps.append(out) |
| 35 |
else: |
| 36 |
targets.append(out) |
| 37 |
out = '' |
| 38 |
if c == '\n': |
| 39 |
rules.append((targets, deps)) |
| 40 |
targets = [] |
| 41 |
deps = [] |
| 42 |
in_deps = False |
| 43 |
continue |
| 44 |
elif c == ':': |
| 45 |
targets.append(out) |
| 46 |
out = '' |
| 47 |
in_deps = True |
| 48 |
continue |
| 49 |
out += c |
| 50 |
return rules |
| 51 |
|
| 52 |
class Target(T.NamedTuple): |
| 53 |
|
| 54 |
deps: T.Set[str] |
| 55 |
|
| 56 |
|
| 57 |
class DepFile: |
| 58 |
def __init__(self, lines: T.Iterable[str]): |
| 59 |
rules = parse(lines) |
| 60 |
depfile: T.Dict[str, Target] = {} |
| 61 |
for (targets, deps) in rules: |
| 62 |
for target in targets: |
| 63 |
t = depfile.setdefault(target, Target(deps=set())) |
| 64 |
for dep in deps: |
| 65 |
t.deps.add(dep) |
| 66 |
self.depfile = depfile |
| 67 |
|
| 68 |
def get_all_dependencies(self, name: str, visited: T.Optional[T.Set[str]] = None) -> T.List[str]: |
| 69 |
deps: T.Set[str] = set() |
| 70 |
if not visited: |
| 71 |
visited = set() |
| 72 |
if name in visited: |
| 73 |
return [] |
| 74 |
visited.add(name) |
| 75 |
|
| 76 |
target = self.depfile.get(name) |
| 77 |
if not target: |
| 78 |
return [] |
| 79 |
deps.update(target.deps) |
| 80 |
for dep in target.deps: |
| 81 |
deps.update(self.get_all_dependencies(dep, visited)) |
| 82 |
return sorted(deps) |