]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/find_file_paths
Added the find_file_paths script which utilizes the new find_file_paths function...
[dead/census-tools.git] / bin / find_file_paths
1 #!/usr/bin/env python
2
3 """
4 Find the location of one or more filenames, and output them to
5 stdout. The search can be anchored within a directory using the --root
6 parameter. By default, all matching paths (for all arguments) will be
7 output. However, if the --single flag is set, only the first path
8 found will be output.
9
10 Examples:
11
12 $ ./find_file_paths --root /bin -s mv
13
14 /bin/mv
15
16
17 $ ./find_file_paths --root /bin mv ls
18
19 /bin/mv
20 /bin/ls
21
22 """
23
24 from optparse import OptionParser
25 import os
26 import site
27 import sys
28
29 # Basically, add '../src' to our path.
30 # Needed for the imports that follow.
31 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
32
33 import CLI
34 import ExitCodes
35 import FileUtils
36
37
38 usage = '%prog [options] file1 [file2, file3...]'
39 fmtr = CLI.VerbatimHelpFormatter()
40 parser = OptionParser(usage, formatter=fmtr)
41
42 parser.add_option('-r',
43 '--root',
44 help='The folder under which to search. Defaults to /.',
45 default='/')
46
47 parser.add_option('-s',
48 '--single',
49 action='store_true',
50 help='Return only the first matching path.',
51 default=False)
52
53 # Use this module's docstring as the description.
54 parser.description = __doc__
55
56 (options, args) = parser.parse_args()
57
58
59 if len(args) < 1:
60 print "\nERROR: You must supply at least one filename.\n"
61 parser.print_help()
62 print '' # Print a newline.
63 raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS)
64
65
66 found_paths = []
67
68 # Build a list of found paths, in case there are / we want more than
69 # one.
70 for filename in args:
71 # If --single was passed, we relay it to the find_file_paths
72 # function so that it completes sooner (it doesn't have to keep
73 # looking after the first match).
74 found_paths += FileUtils.find_file_paths(options.root,
75 filename,
76 options.single)
77
78 if options.single and (len(found_paths) > 0):
79 # If we found anything and we only want the first match, just
80 # print it and quit.
81 print found_paths[0]
82 raise SystemExit(ExitCodes.EXIT_SUCCESS)
83
84
85 # If we weren't passed --single, spit out all matches.
86 for fp in found_paths:
87 print fp