1#!/usr/bin/env python3 2# Copyright 2019 The Dawn Authors 3# 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 16import argparse, glob, os, sys 17 18 19def check_in_subdirectory(path, directory): 20 return path.startswith(directory) and not '/' in path[len(directory):] 21 22 23def check_is_allowed(path, allowed_dirs): 24 return any( 25 check_in_subdirectory(path, directory) for directory in allowed_dirs) 26 27 28def get_all_files_in_dir(find_directory): 29 result = [] 30 for (directory, _, files) in os.walk(find_directory): 31 result += [os.path.join(directory, filename) for filename in files] 32 return result 33 34 35def run(): 36 # Parse command line arguments 37 parser = argparse.ArgumentParser( 38 description="Removes stale autogenerated files from gen/ directories.") 39 parser.add_argument( 40 '--root-dir', 41 type=str, 42 help='The root directory, all other paths in files are relative to it.' 43 ) 44 parser.add_argument( 45 '--allowed-output-dirs-file', 46 type=str, 47 help='The file containing a list of allowed directories') 48 parser.add_argument( 49 '--stale-dirs-file', 50 type=str, 51 help= 52 'The file containing a list of directories to check for stale files') 53 parser.add_argument('--stamp', 54 type=str, 55 help='A stamp written once this script completes') 56 args = parser.parse_args() 57 58 root_dir = args.root_dir 59 stamp_file = args.stamp 60 61 # Load the list of allowed and stale directories 62 with open(args.allowed_output_dirs_file) as f: 63 allowed_dirs = set( 64 [os.path.join(root_dir, line.strip()) for line in f.readlines()]) 65 66 for directory in allowed_dirs: 67 if not directory.endswith('/'): 68 print('Allowed directory entry "{}" doesn\'t end with /'.format( 69 directory)) 70 return 1 71 72 with open(args.stale_dirs_file) as f: 73 stale_dirs = set([line.strip() for line in f.readlines()]) 74 75 # Remove all files in stale dirs that aren't in the allowed dirs. 76 for stale_dir in stale_dirs: 77 stale_dir = os.path.join(root_dir, stale_dir) 78 79 for candidate in get_all_files_in_dir(stale_dir): 80 if not check_is_allowed(candidate, allowed_dirs): 81 os.remove(candidate) 82 83 # Finished! Write the stamp file so ninja knows to not run this again. 84 with open(stamp_file, "w") as f: 85 f.write("") 86 87 return 0 88 89 90if __name__ == "__main__": 91 sys.exit(run()) 92