1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3# Copyright 2014 The Chromium Authors. All rights reserved. 4# Use of this source code is governed by a BSD-style license that can be 5# found in the LICENSE file. 6"""Finds files in directories. 7""" 8 9import fnmatch 10import optparse 11import os 12import sys 13from util import build_utils 14 15 16def main(argv): 17 parser = optparse.OptionParser() 18 parser.add_option('--pattern', default='*', help='File pattern to match.') 19 parser.add_option('--base-dir', help='base directory') 20 parser.add_option( 21 '--return-relpath', 22 action='store_true', 23 help='return relative address from base directory') 24 parser.add_option( 25 '--follow-symlinks', action='store_true', help='whether to follow links') 26 options, directories = parser.parse_args(argv) 27 28 for d in directories: 29 if not os.path.exists(d): 30 print('%s does not exist' % d) 31 return 1 32 if os.path.isfile(d): 33 if options.return_relpath: 34 if options.base_dir is not None: 35 if fnmatch.filter(d, options.pattern): 36 print(os.path.relpath(d, options.base_dir)) 37 else: 38 print("Please specify the relative base directory") 39 return 1 40 else: 41 if fnmatch.filter(d, options.pattern): 42 print(d) 43 return 0 44 elif not os.path.isdir(d): 45 # if input path is not a directory nor a normal file, return error. 46 print('%s is not a directory or a file' % d) 47 return 1 48 for root, _, files in os.walk(d, followlinks=options.follow_symlinks): 49 for f in fnmatch.filter(files, options.pattern): 50 if options.return_relpath: 51 if options.base_dir is not None: 52 print(os.path.relpath(os.path.join(root, f), options.base_dir)) 53 else: 54 print("Please specify the relative base directory") 55 return 1 56 else: 57 print(os.path.join(root, f)) 58 59 60if __name__ == '__main__': 61 sys.exit(main(sys.argv[1:])) 62