Hal Canary | 11c45d6 | 2019-11-15 10:23:30 -0500 | [diff] [blame] | 1 | #! /usr/bin/env python |
| 2 | # Copyright 2019 Google LLC. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | import os |
| 7 | import shutil |
| 8 | import subprocess |
| 9 | import sys |
| 10 | |
| 11 | def copy_git_directory(src, dst, out=None): |
| 12 | ''' |
| 13 | Makes a copy of `src` directory in `dst` directory. If files already exist |
| 14 | and are identical, do not touch them. If extra files or directories exist, |
| 15 | remove them. Assume that `src` is a git directory so that `git ls-files` can |
| 16 | be used to enumerate files. This has the added benefit of ignoring files |
| 17 | not tracked by git. Also, if out is not None, write summary of actions to out. |
| 18 | If `dst` is a top-level git directory, the `.git` directory will be removed. |
| 19 | ''' |
Hal Canary | 22814db | 2019-11-19 11:58:13 -0500 | [diff] [blame] | 20 | if not os.path.isdir(src): |
| 21 | raise Exception('Directory "%s" does not exist.' % src) |
Hal Canary | 11c45d6 | 2019-11-15 10:23:30 -0500 | [diff] [blame] | 22 | if not os.path.isdir(dst): |
| 23 | os.makedirs(dst) |
| 24 | ls_files = subprocess.check_output(['git', 'ls-files', '-z', '.'], cwd=src) |
| 25 | src_files = set(p for p in ls_files.split('\0') if p) |
| 26 | abs_src = os.path.abspath(src) |
| 27 | cwd = os.getcwd() |
| 28 | try: |
| 29 | os.chdir(dst) |
| 30 | def output(out, sym, dst, path): |
| 31 | if out: |
| 32 | out.write('%s %s%s%s\n' % (sym, dst, os.sep, path)) |
| 33 | for dirpath, dirnames, filenames in os.walk('.', topdown=False): |
| 34 | for filename in filenames: |
| 35 | path = os.path.normpath(os.path.join(dirpath, filename)) |
| 36 | if path not in src_files: |
| 37 | output(out, '-', dst, path) |
| 38 | os.remove(path) |
| 39 | for filename in dirnames: |
| 40 | path = os.path.normpath(os.path.join(dirpath, filename)) |
| 41 | if not os.listdir(path): # Remove empty subfolders. |
| 42 | output(out, '-', dst, path + os.sep) |
| 43 | os.rmdir(path) |
| 44 | for path in src_files: |
| 45 | src_path = os.path.join(abs_src, path) |
| 46 | if os.path.exists(path): |
| 47 | with open(path) as f1: |
| 48 | with open(src_path) as f2: |
| 49 | if f1.read() == f2.read(): |
| 50 | continue |
| 51 | output(out, '+', dst, path) |
| 52 | shutil.copy2(src_path, path) |
| 53 | finally: |
| 54 | os.chdir(cwd) |
| 55 | |
| 56 | if __name__ == '__main__': |
| 57 | if len(sys.argv) != 3: |
| 58 | sys.stderr.write('\nUsage:\n %s SRC_DIR DST_DIR\n\n' % sys.argv[0]) |
| 59 | sys.exit(1) |
| 60 | copy_git_directory(sys.argv[1], sys.argv[2], sys.stdout) |