Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d7f5c6f

Browse files
authored
Merge pull request #904 from asottile/clone_uncommitted
Teach pre-commit try-repo to clone uncommitted changes
2 parents e04505a + e4f0b4c commit d7f5c6f

12 files changed

Lines changed: 162 additions & 70 deletions

File tree

pre_commit/commands/run.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,7 @@ def _run_hooks(config, hooks, args, environ):
199199
retval |= _run_single_hook(filenames, hook, args, skips, cols)
200200
if retval and config['fail_fast']:
201201
break
202-
if (
203-
retval and
204-
args.show_diff_on_failure and
205-
subprocess.call(('git', 'diff', '--quiet', '--no-ext-diff')) != 0
206-
):
202+
if retval and args.show_diff_on_failure and git.has_diff():
207203
output.write_line('All changes made by hooks:')
208204
subprocess.call(('git', '--no-pager', 'diff', '--no-ext-diff'))
209205
return retval

pre_commit/commands/try_repo.py

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import unicode_literals
33

44
import collections
5+
import logging
56
import os.path
67

78
from aspy.yaml import ordered_dump
@@ -12,23 +13,50 @@
1213
from pre_commit.clientlib import load_manifest
1314
from pre_commit.commands.run import run
1415
from pre_commit.store import Store
16+
from pre_commit.util import cmd_output
1517
from pre_commit.util import tmpdir
1618

19+
logger = logging.getLogger(__name__)
1720

18-
def try_repo(args):
19-
ref = args.ref or git.head_rev(args.repo)
2021

22+
def _repo_ref(tmpdir, repo, ref):
23+
# if `ref` is explicitly passed, use it
24+
if ref:
25+
return repo, ref
26+
27+
ref = git.head_rev(repo)
28+
# if it exists on disk, we'll try and clone it with the local changes
29+
if os.path.exists(repo) and git.has_diff('HEAD', repo=repo):
30+
logger.warning('Creating temporary repo with uncommitted changes...')
31+
32+
shadow = os.path.join(tmpdir, 'shadow-repo')
33+
cmd_output('git', 'clone', repo, shadow)
34+
cmd_output('git', 'checkout', ref, '-b', '_pc_tmp', cwd=shadow)
35+
idx = git.git_path('index', repo=shadow)
36+
objs = git.git_path('objects', repo=shadow)
37+
env = dict(os.environ, GIT_INDEX_FILE=idx, GIT_OBJECT_DIRECTORY=objs)
38+
cmd_output('git', 'add', '-u', cwd=repo, env=env)
39+
git.commit(repo=shadow)
40+
41+
return shadow, git.head_rev(shadow)
42+
else:
43+
return repo, ref
44+
45+
46+
def try_repo(args):
2147
with tmpdir() as tempdir:
48+
repo, ref = _repo_ref(tempdir, args.repo, args.ref)
49+
2250
store = Store(tempdir)
2351
if args.hook:
2452
hooks = [{'id': args.hook}]
2553
else:
26-
repo_path = store.clone(args.repo, ref)
54+
repo_path = store.clone(repo, ref)
2755
manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE))
2856
manifest = sorted(manifest, key=lambda hook: hook['id'])
2957
hooks = [{'id': hook['id']} for hook in manifest]
3058

31-
items = (('repo', args.repo), ('rev', ref), ('hooks', hooks))
59+
items = (('repo', repo), ('rev', ref), ('hooks', hooks))
3260
config = {'repos': [collections.OrderedDict(items)]}
3361
config_s = ordered_dump(config, **C.YAML_DUMP_KWARGS)
3462

pre_commit/git.py

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,10 @@
44
import os.path
55
import sys
66

7-
from pre_commit.error_handler import FatalError
8-
from pre_commit.util import CalledProcessError
97
from pre_commit.util import cmd_output
108

119

12-
logger = logging.getLogger('pre_commit')
10+
logger = logging.getLogger(__name__)
1311

1412

1513
def zsplit(s):
@@ -20,14 +18,23 @@ def zsplit(s):
2018
return []
2119

2220

21+
def no_git_env():
22+
# Too many bugs dealing with environment variables and GIT:
23+
# https://github.com/pre-commit/pre-commit/issues/300
24+
# In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
25+
# pre-commit hooks
26+
# In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
27+
# while running pre-commit hooks in submodules.
28+
# GIT_DIR: Causes git clone to clone wrong thing
29+
# GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
30+
return {
31+
k: v for k, v in os.environ.items()
32+
if not k.startswith('GIT_') or k in {'GIT_SSH'}
33+
}
34+
35+
2336
def get_root():
24-
try:
25-
return cmd_output('git', 'rev-parse', '--show-toplevel')[1].strip()
26-
except CalledProcessError:
27-
raise FatalError(
28-
'git failed. Is it installed, and are you in a Git repository '
29-
'directory?',
30-
)
37+
return cmd_output('git', 'rev-parse', '--show-toplevel')[1].strip()
3138

3239

3340
def get_git_dir(git_root='.'):
@@ -106,6 +113,27 @@ def head_rev(remote):
106113
return out.split()[0]
107114

108115

116+
def has_diff(*args, **kwargs):
117+
repo = kwargs.pop('repo', '.')
118+
assert not kwargs, kwargs
119+
cmd = ('git', 'diff', '--quiet', '--no-ext-diff') + args
120+
return cmd_output(*cmd, cwd=repo, retcode=None)[0]
121+
122+
123+
def commit(repo='.'):
124+
env = no_git_env()
125+
name, email = 'pre-commit', '[email protected]'
126+
env['GIT_AUTHOR_NAME'] = env['GIT_COMMITTER_NAME'] = name
127+
env['GIT_AUTHOR_EMAIL'] = env['GIT_COMMITTER_EMAIL'] = email
128+
cmd = ('git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
129+
cmd_output(*cmd, cwd=repo, env=env)
130+
131+
132+
def git_path(name, repo='.'):
133+
_, out, _ = cmd_output('git', 'rev-parse', '--git-path', name, cwd=repo)
134+
return os.path.join(repo, out.strip())
135+
136+
109137
def check_for_cygwin_mismatch():
110138
"""See https://github.com/pre-commit/pre-commit/issues/354"""
111139
if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows)

pre_commit/logging_handler.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import unicode_literals
22

3+
import contextlib
34
import logging
45

56
from pre_commit import color
@@ -34,6 +35,12 @@ def emit(self, record):
3435
)
3536

3637

37-
def add_logging_handler(*args, **kwargs):
38-
logger.addHandler(LoggingHandler(*args, **kwargs))
38+
@contextlib.contextmanager
39+
def logging_handler(*args, **kwargs):
40+
handler = LoggingHandler(*args, **kwargs)
41+
logger.addHandler(handler)
3942
logger.setLevel(logging.INFO)
43+
try:
44+
yield
45+
finally:
46+
logger.removeHandler(handler)

pre_commit/main.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,10 @@
1919
from pre_commit.commands.sample_config import sample_config
2020
from pre_commit.commands.try_repo import try_repo
2121
from pre_commit.error_handler import error_handler
22-
from pre_commit.logging_handler import add_logging_handler
22+
from pre_commit.error_handler import FatalError
23+
from pre_commit.logging_handler import logging_handler
2324
from pre_commit.store import Store
25+
from pre_commit.util import CalledProcessError
2426

2527

2628
logger = logging.getLogger('pre_commit')
@@ -97,7 +99,13 @@ def _adjust_args_and_chdir(args):
9799
if args.command == 'try-repo' and os.path.exists(args.repo):
98100
args.repo = os.path.abspath(args.repo)
99101

100-
os.chdir(git.get_root())
102+
try:
103+
os.chdir(git.get_root())
104+
except CalledProcessError:
105+
raise FatalError(
106+
'git failed. Is it installed, and are you in a Git repository '
107+
'directory?',
108+
)
101109

102110
args.config = os.path.relpath(args.config)
103111
if args.command in {'run', 'try-repo'}:
@@ -240,9 +248,7 @@ def main(argv=None):
240248
elif args.command == 'help':
241249
parser.parse_args(['--help'])
242250

243-
with error_handler():
244-
add_logging_handler(args.color)
245-
251+
with error_handler(), logging_handler(args.color):
246252
_adjust_args_and_chdir(args)
247253

248254
store = Store()

pre_commit/store.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99

1010
import pre_commit.constants as C
1111
from pre_commit import file_lock
12+
from pre_commit import git
1213
from pre_commit.util import clean_path_on_failure
1314
from pre_commit.util import cmd_output
14-
from pre_commit.util import no_git_env
1515
from pre_commit.util import resource_text
1616

1717

@@ -135,7 +135,7 @@ def _get_result():
135135
def clone(self, repo, ref, deps=()):
136136
"""Clone the given url and checkout the specific ref."""
137137
def clone_strategy(directory):
138-
env = no_git_env()
138+
env = git.no_git_env()
139139

140140
cmd = ('git', 'clone', '--no-checkout', repo, directory)
141141
cmd_output(*cmd, env=env)
@@ -160,10 +160,7 @@ def make_local_strategy(directory):
160160
with io.open(os.path.join(directory, resource), 'w') as f:
161161
f.write(contents)
162162

163-
env = no_git_env()
164-
name, email = 'pre-commit', '[email protected]'
165-
env['GIT_AUTHOR_NAME'] = env['GIT_COMMITTER_NAME'] = name
166-
env['GIT_AUTHOR_EMAIL'] = env['GIT_COMMITTER_EMAIL'] = email
163+
env = git.no_git_env()
167164

168165
# initialize the git repository so it looks more like cloned repos
169166
def _git_cmd(*args):
@@ -172,7 +169,7 @@ def _git_cmd(*args):
172169
_git_cmd('init', '.')
173170
_git_cmd('config', 'remote.origin.url', '<<unknown>>')
174171
_git_cmd('add', '.')
175-
_git_cmd('commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
172+
git.commit(repo=directory)
176173

177174
return self._new_repo(
178175
'local', C.LOCAL_REPO_VERSION, deps, make_local_strategy,

pre_commit/util.py

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -64,21 +64,6 @@ def noop_context():
6464
yield
6565

6666

67-
def no_git_env():
68-
# Too many bugs dealing with environment variables and GIT:
69-
# https://github.com/pre-commit/pre-commit/issues/300
70-
# In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
71-
# pre-commit hooks
72-
# In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
73-
# while running pre-commit hooks in submodules.
74-
# GIT_DIR: Causes git clone to clone wrong thing
75-
# GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
76-
return {
77-
k: v for k, v in os.environ.items()
78-
if not k.startswith('GIT_') or k in {'GIT_SSH'}
79-
}
80-
81-
8267
@contextlib.contextmanager
8368
def tmpdir():
8469
"""Contextmanager to create a temporary directory. It will be cleaned up

testing/fixtures.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def make_repo(tempdir_factory, repo_source):
5353

5454

5555
@contextlib.contextmanager
56-
def modify_manifest(path):
56+
def modify_manifest(path, commit=True):
5757
"""Modify the manifest yielded by this context to write to
5858
.pre-commit-hooks.yaml.
5959
"""
@@ -63,7 +63,8 @@ def modify_manifest(path):
6363
yield manifest
6464
with io.open(manifest_path, 'w') as manifest_file:
6565
manifest_file.write(ordered_dump(manifest, **C.YAML_DUMP_KWARGS))
66-
git_commit(msg=modify_manifest.__name__, cwd=path)
66+
if commit:
67+
git_commit(msg=modify_manifest.__name__, cwd=path)
6768

6869

6970
@contextlib.contextmanager

0 commit comments

Comments
 (0)