summaryrefslogtreecommitdiff
path: root/synchronize_owners
blob: e96009d1a286cc6435a12cbb37c885fdc936e46b (plain)
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
#!/usr/bin/env python3
#
# Copyright (C) 2021 The Android Open main Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import argparse
import os
import pathlib
import sys


def process_owners(main_dir, main_branch, tracking_dirs):
  # walk the tree ...
  for subdir, _, files in os.walk(main_dir):
    for file in files:
      # ... and for each OWNERS file in the main ...
      if file == 'OWNERS':
        rel_dir = pathlib.Path(subdir[len(main_dir.name) + 1:])
        owners = rel_dir / file

        for tracking_dir in tracking_dirs:
          target = tracking_dir / owners
          comment_line = (f'# include OWNERS from the authoritative '
                          f'{main_branch} branch\n')
          include_line = f'include kernel/common:{main_branch}:/{owners}\n'

          # ... either add a new file with include directive ...
          if not target.is_file():
            with open(target, 'w') as file:
              file.writelines([comment_line, include_line])

          # ... or ensure the include directive is in the file
          else:
            with open(target) as file:
              contents = file.readlines()
            if include_line not in contents:
              with open(target, 'w') as file:
                file.writelines([comment_line, include_line, '\n'] + contents)


def is_dir(dirname):
  result = pathlib.Path(dirname)
  if not result.is_dir():
    raise argparse.ArgumentTypeError(f'{dirname} is not a directory')
  else:
    return result


def main():
  parser = argparse.ArgumentParser()

  parser.add_argument(
      'main_dir', type=is_dir, help='main directory to synchronize from')
  parser.add_argument('main_branch', help='main branch name'),
  parser.add_argument(
      'tracking_dir', type=is_dir, nargs='+', help='tracking directory to synchronize to')

  args = parser.parse_args()

  process_owners(args.main_dir, args.main_branch, args.tracking_dir)


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