1#!/usr/bin/python
2# Copyright (c) 2011 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.
5
6import glob
7import os
8import shutil
9import stat
10import sys
11
12def usage():
13  print("""Usage: squashdir.py <dest-dir> <source-dir> ...
14
15Basic tool to copy a directory heirarchy into a flat space.
16
17This crawls an arbitrarily deep heirarchy of files and directories, and copies
18each file into the destination directory.  The destination file name will
19include the relative path to the source file, with '^^' inserted between each
20directory name.
21
22The resulting directory can then be imported into the file manager test harness,
23which will reconstitute the directory structure.
24
25This is used to work around the fact that the FileList and File objects
26presented by <input type=file multiple> do not allow users to recurse a
27selected directory, nor do they provide information about directory structure.
28""")
29
30def status(msg):
31  sys.stderr.write(msg + '\n')
32
33def scan_path(dest, src, path):
34  abs_src = os.path.join(src, path)
35  statinfo = os.stat(abs_src)
36
37  basename = os.path.basename(path)
38
39  if not stat.S_ISDIR(statinfo.st_mode):
40    newname = os.path.join(dest, path.replace('/', '^^'))
41    status(newname)
42    shutil.copyfile(abs_src, newname)
43  else:
44    for child_path in glob.glob(abs_src + '/*'):
45      scan_path(dest, src, child_path[len(src) + 1:])
46
47if __name__ == '__main__':
48  if len(sys.argv) < 3 or sys.argv[1][0] == '-':
49    usage()
50    return
51
52  dest = sys.argv[1]
53  for src in sys.argv[2:]:
54    abs_src = os.path.abspath(src)
55    path = os.path.basename(abs_src)
56    abs_src = os.path.dirname(abs_src)
57    scan_path(dest, abs_src, path)
58