|
| 1 | +import os |
| 2 | +import subprocess |
| 3 | +import tarfile |
| 4 | + |
| 5 | +from .file_finder import scm_find_files |
| 6 | + |
| 7 | + |
| 8 | +def _git_toplevel(path): |
| 9 | + try: |
| 10 | + with open(os.devnull, 'wb') as devnull: |
| 11 | + out = subprocess.check_output([ |
| 12 | + 'git', 'rev-parse', '--show-toplevel', |
| 13 | + ], cwd=(path or '.'), universal_newlines=True, stderr=devnull) |
| 14 | + return os.path.normcase(os.path.realpath(out.strip())) |
| 15 | + except subprocess.CalledProcessError: |
| 16 | + # git returned error, we are not in a git repo |
| 17 | + return None |
| 18 | + except OSError: |
| 19 | + # git command not found, probably |
| 20 | + return None |
| 21 | + |
| 22 | + |
| 23 | +def _git_ls_files_and_dirs(toplevel): |
| 24 | + # use git archive instead of git ls-file to honor |
| 25 | + # export-ignore git attribute |
| 26 | + cmd = ['git', 'archive', '--prefix', toplevel + os.path.sep, 'HEAD'] |
| 27 | + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=toplevel) |
| 28 | + tf = tarfile.open(fileobj=proc.stdout, mode='r|*') |
| 29 | + git_files = set() |
| 30 | + git_dirs = set([toplevel]) |
| 31 | + for member in tf.getmembers(): |
| 32 | + name = os.path.normcase(member.name).replace('/', os.path.sep) |
| 33 | + if member.type == tarfile.DIRTYPE: |
| 34 | + git_dirs.add(name) |
| 35 | + else: |
| 36 | + git_files.add(name) |
| 37 | + return git_files, git_dirs |
| 38 | + |
| 39 | + |
| 40 | +def git_find_files(path=''): |
| 41 | + toplevel = _git_toplevel(path) |
| 42 | + if not toplevel: |
| 43 | + return [] |
| 44 | + git_files, git_dirs = _git_ls_files_and_dirs(toplevel) |
| 45 | + return scm_find_files(path, git_files, git_dirs) |
0 commit comments