Skip to content

Commit 7b1b72e

Browse files
committed
Consolidated some code.
1 parent 33f5bad commit 7b1b72e

2 files changed

Lines changed: 22 additions & 23 deletions

File tree

pre_commit/git.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1+
import functools
12
import os
2-
import re
33
import pkg_resources
4+
import re
45
from plumbum import local
56

67
from pre_commit.util import memoize_by_cwd
78

89

9-
def _get_root_original():
10-
return local['git']['rev-parse', '--show-toplevel']().strip()
11-
1210
def _get_root_new():
1311
path = os.getcwd()
1412
while len(path) > 1:
@@ -22,7 +20,6 @@ def _get_root_new():
2220
@memoize_by_cwd
2321
def get_root():
2422
return _get_root_new()
25-
return local['git']['rev-parse', '--show-toplevel']().strip()
2623

2724

2825
@memoize_by_cwd
@@ -50,23 +47,24 @@ def get_staged_files():
5047
return local['git']['diff', '--staged', '--name-only']().splitlines()
5148

5249

53-
@memoize_by_cwd
54-
def get_staged_files_matching(expr):
55-
regex = re.compile(expr)
56-
return set(
57-
filename for filename in get_staged_files() if regex.search(filename)
58-
)
59-
60-
6150
@memoize_by_cwd
6251
def get_all_files():
6352
return local['git']['ls-files']().splitlines()
6453

6554

66-
# Smell: this is duplicated above
67-
@memoize_by_cwd
68-
def get_all_files_matching(expr):
69-
regex = re.compile(expr)
70-
return set(
71-
filename for filename in get_all_files() if regex.search(filename)
72-
)
55+
def get_files_matching(all_file_list_strategy):
56+
@functools.wraps(all_file_list_strategy)
57+
@memoize_by_cwd
58+
def wrapper(expr):
59+
regex = re.compile(expr)
60+
return set(
61+
filename
62+
for filename in all_file_list_strategy()
63+
if regex.search(filename)
64+
)
65+
return wrapper
66+
67+
68+
69+
get_staged_files_matching = get_files_matching(get_staged_files)
70+
get_all_files_matching = get_files_matching(get_all_files)

pre_commit/util.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,16 @@ def __get__(self, obj, cls):
2222

2323
def memoize_by_cwd(func):
2424
"""Memoize a function call based on os.getcwd()."""
25-
cache = {}
2625
@functools.wraps(func)
2726
def wrapper(*args):
2827
cwd = os.getcwd()
2928
key = (cwd,) + args
3029
try:
31-
return cache[key]
30+
return wrapper._cache[key]
3231
except KeyError:
33-
ret = cache[key] = func(*args)
32+
ret = wrapper._cache[key] = func(*args)
3433
return ret
3534

35+
wrapper._cache = {}
36+
3637
return wrapper

0 commit comments

Comments
 (0)