2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Copies test data files or directories into a given output directory."""
13 class WrongNumberOfArgumentsException(Exception):
17 """Returns a path with spaces escaped."""
18 return path.replace(" ", "\\ ")
20 def ListFilesForPath(path):
21 """Returns a list of all the files under a given path."""
23 # Ignore revision control metadata directories.
24 if (os.path.basename(path).startswith('.git') or
25 os.path.basename(path).startswith('.svn')):
28 # Files get returned without modification.
29 if not os.path.isdir(path):
33 # Directories get recursively expanded.
34 contents = os.listdir(path)
36 full_path = os.path.join(path, item)
37 output.extend(ListFilesForPath(full_path))
40 def CalcInputs(inputs):
41 """Computes the full list of input files for a set of command-line arguments.
43 # |inputs| is a list of paths, which may be directories.
46 output.extend(ListFilesForPath(input))
49 def CopyFiles(relative_filenames, output_basedir):
50 """Copies files to the given output directory."""
51 for file in relative_filenames:
52 relative_dirname = os.path.dirname(file)
53 output_dir = os.path.join(output_basedir, relative_dirname)
54 output_filename = os.path.join(output_basedir, file)
56 # In cases where a directory has turned into a file or vice versa, delete it
57 # before copying it below.
58 if os.path.exists(output_dir) and not os.path.isdir(output_dir):
60 if os.path.exists(output_filename) and os.path.isdir(output_filename):
61 shutil.rmtree(output_filename)
63 if not os.path.exists(output_dir):
64 os.makedirs(output_dir)
65 shutil.copy(file, output_filename)
68 parser = optparse.OptionParser()
69 usage = 'Usage: %prog -o <output_dir> [--inputs] [--outputs] <input_files>'
70 parser.set_usage(usage)
71 parser.add_option('-o', dest='output_dir')
72 parser.add_option('--inputs', action='store_true', dest='list_inputs')
73 parser.add_option('--outputs', action='store_true', dest='list_outputs')
74 options, arglist = parser.parse_args(argv)
77 raise WrongNumberOfArgumentsException('<input_files> required.')
79 files_to_copy = CalcInputs(arglist)
80 escaped_files = [EscapePath(x) for x in CalcInputs(arglist)]
81 if options.list_inputs:
82 return '\n'.join(escaped_files)
84 if not options.output_dir:
85 raise WrongNumberOfArgumentsException('-o required.')
87 if options.list_outputs:
88 outputs = [os.path.join(options.output_dir, x) for x in escaped_files]
89 return '\n'.join(outputs)
91 CopyFiles(files_to_copy, options.output_dir)
96 result = DoMain(argv[1:])
97 except WrongNumberOfArgumentsException, e:
104 if __name__ == '__main__':
105 sys.exit(main(sys.argv))