blob: b143abee11ca46ac79256429b7099ab01b6f0738 [file] [log] [blame]
Corentin Walleza9a84df2019-09-19 23:30:42 +00001# Copyright 2019 The Dawn Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import argparse, glob, os, sys
16
17def check_in_subdirectory(path, directory):
18 return path.startswith(directory) and not '/' in path[len(directory):]
19
20def check_is_allowed(path, allowed_dirs):
21 return any(check_in_subdirectory(path, directory) for directory in allowed_dirs)
22
23def get_all_files_in_dir(find_directory):
24 result = []
25 for (directory, _, files) in os.walk(find_directory):
26 result += [os.path.join(directory, filename) for filename in files]
27 return result
28
29def run():
30 # Parse command line arguments
31 parser = argparse.ArgumentParser(
32 description = "Removes stale autogenerated files from gen/ directories."
33 )
34 parser.add_argument('--root-dir', type=str, help='The root directory, all other paths in files are relative to it.')
35 parser.add_argument('--allowed-output-dirs-file', type=str, help='The file containing a list of allowed directories')
36 parser.add_argument('--stale-dirs-file', type=str, help='The file containing a list of directories to check for stale files')
37 parser.add_argument('--stamp', type=str, help='A stamp written once this script completes')
38 args = parser.parse_args()
39
40 root_dir = args.root_dir
41 stamp_file = args.stamp
42
43 # Load the list of allowed and stale directories
44 with open(args.allowed_output_dirs_file) as f:
45 allowed_dirs = set([os.path.join(root_dir, line.strip()) for line in f.readlines()])
46
47 for directory in allowed_dirs:
48 if not directory.endswith('/'):
49 print('Allowed directory entry "{}" doesn\'t end with /'.format(directory))
50 return 1
51
52 with open(args.stale_dirs_file) as f:
53 stale_dirs = set([line.strip() for line in f.readlines()])
54
55 # Remove all files in stale dirs that aren't in the allowed dirs.
56 for stale_dir in stale_dirs:
57 stale_dir = os.path.join(root_dir, stale_dir)
58
59 for candidate in get_all_files_in_dir(stale_dir):
60 if not check_is_allowed(candidate, allowed_dirs):
61 os.remove(candidate)
62
63 # Finished! Write the stamp file so ninja knows to not run this again.
64 with open(stamp_file, "w") as f:
65 f.write("")
66
67 return 0
68
69if __name__ == "__main__":
70 sys.exit(run())