1#!/usr/bin/env ruby
2
3# Copyright (c) 2021-2024 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
17class Output
18  @@indent = 0
19  @@indent_str = ""
20  @@file = nil
21  STEP = 4
22
23  def self.setup(file = nil)
24    @@file = file.nil? ? $stdout : File.open(file, 'w')
25  end
26
27  def self.write(line)
28    @@file.write line
29  end
30
31  def self.println(line)
32    @@file.write @@indent_str
33    @@file.puts line
34  end
35
36  def self.puts(line = '')
37    println(line)
38  end
39
40  def self.<<(line)
41    println(line)
42    self
43  end
44
45  def self.printlni(line)
46    println line
47    indent_up
48  end
49
50  def self.printlnd(line)
51    indent_down
52    println line
53  end
54
55  def self.scoped_puts(start_line, end_line = '}')
56    puts start_line
57    indent_up
58    yield
59    indent_down
60    puts end_line
61  end
62
63  def self.indent_up
64    change_indent(STEP)
65  end
66  def self.indent_down
67    change_indent(-STEP)
68  end
69
70private
71  def self.change_indent(step = 4)
72    @@indent += step
73    raise "Wrong indent" if @@indent < 0
74    @@indent_str = " " * @@indent
75  end
76end
77