1#!/usr/bin/env python 2# 3# Copyright (C) 2022 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import functools 18 19from ninja_syntax import Variable, BuildAction, Rule, Pool, Subninja, Line 20 21 22# TODO: Format the output according to a configurable width variable 23# This will ensure that the generated content fits on a screen and does not 24# require horizontal scrolling 25class Writer: 26 def __init__(self, file, builddir: str = None): 27 self.file = file 28 self.nodes = [] # type Node 29 if builddir: 30 self.add_variable(Variable('builddir', builddir)) 31 32 def add_variable(self, variable: Variable): 33 self.nodes.append(variable) 34 35 @functools.lru_cache(maxsize=None) 36 def add_rule(self, rule: Rule): 37 self.nodes.append(rule) 38 39 @functools.lru_cache(maxsize=None) 40 def add_build_action(self, build_action: BuildAction): 41 self.nodes.append(build_action) 42 43 def add_pool(self, pool: Pool): 44 self.nodes.append(pool) 45 46 def add_comment(self, comment: str): 47 self.nodes.append(Line(value=f"# {comment}")) 48 49 def add_default(self, default: str): 50 self.nodes.append(Line(value=f"default {default}")) 51 52 def add_newline(self): 53 self.nodes.append(Line(value="")) 54 55 def add_subninja(self, subninja: Subninja): 56 self.nodes.append(subninja) 57 58 def add_phony(self, name: str, deps: tuple): 59 self.add_build_action(BuildAction(output=name, rule="phony", inputs=deps)) 60 61 def write(self): 62 for node in self.nodes: 63 for line in node.stream(): 64 print(line, file=self.file) 65