-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_dependency.py
82 lines (63 loc) · 2.04 KB
/
local_dependency.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import sys
import os
import argparse
from modulegraph.modulegraph import ModuleGraph
from io import StringIO
from git import Repo
from termcolor import colored
def get_args():
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--run-file', type=str)
return parser.parse_args()
def get_dependencies_file(run_file):
# A hack that change cwd to the basedir of run file
old_cwd = os.getcwd()
path = os.path.dirname(os.path.realpath(run_file))
os.chdir(path)
m = ModuleGraph('.')
m.run_script(run_file)
# A hack that redirect stdout to string
result = StringIO()
old_stdout = sys.stdout
sys.stdout = result
m.report()
result = result.getvalue()
sys.stdout = old_stdout
cwd = os.getcwd()
os.chdir(old_cwd)
files = []
for line in result.split('\n')[3:]:
line = line.split()
if len(line) != 3:
continue
if line[2].startswith(cwd):
files.append(line[2])
return files
def check(run_file, fluffy=False):
deps = get_dependencies_file(run_file)
path = os.path.dirname(os.path.realpath(run_file))
repo = Repo(path, search_parent_directories=True)
changed_files = repo.git.diff('HEAD', name_only=True)
repo_root = repo.git.rev_parse("--show-toplevel")
deps = [os.path.relpath(item, repo_root) for item in deps]
exit_code = 0
for dep in deps:
if dep in changed_files:
status = colored('M', 'red')
exit_code = -1
elif dep in repo.untracked_files:
status = colored('U', 'magenta')
exit_code = -1
else:
status = 'C'
print(status, dep)
if exit_code == -1:
if not fluffy:
print(colored('\nPlease commit modified or untracked files!', 'red'))
exit(exit_code)
else:
print(colored('\nYou have modified or untracked files. Use at your own risk!', 'red'))
return deps
if __name__ == '__main__':
args = get_args()
check(run_file)