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 13 14 15def main(argv): 16 parser = optparse.OptionParser() 17 parser.add_option('--pattern', default='*', help='File pattern to match.') 18 parser.add_option('--base-dir', help='base directory') 19 parser.add_option('--return-relpath', 20 action='store_true', 21 help='return relative address from base directory') 22 parser.add_option('--follow-symlinks', 23 action='store_true', 24 help='whether to follow links') 25 options, directories = parser.parse_args(argv) 26 27 for d in directories: 28 if not os.path.exists(d): 29 print('%s does not exist' % d) 30 return 1 31 if os.path.isfile(d): 32 if options.return_relpath: 33 if options.base_dir is not None: 34 if fnmatch.filter(d, options.pattern): 35 print(os.path.relpath(d, options.base_dir)) 36 else: 37 print("Please specify the relative base directory") 38 return 1 39 else: 40 if fnmatch.filter(d, options.pattern): 41 print(d) 42 return 0 43 elif not os.path.isdir(d): 44 # if input path is not a directory nor a normal file, return error. 45 print('%s is not a directory or a file' % d) 46 return 1 47 for root, _, files in os.walk(d, followlinks=options.follow_symlinks): 48 for f in fnmatch.filter(files, options.pattern): 49 if options.return_relpath: 50 if options.base_dir is not None: 51 print( 52 os.path.relpath(os.path.join(root, f), 53 options.base_dir)) 54 else: 55 print("Please specify the relative base directory") 56 return 1 57 else: 58 print(os.path.join(root, f)) 59 60 61if __name__ == '__main__': 62 sys.exit(main(sys.argv[1:])) 63