-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource-restore.py
executable file
·134 lines (109 loc) · 4.39 KB
/
source-restore.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#!/usr/bin/python
import argparse
import json
import subprocess
from sys import stdout, stderr
from os import path, mkdir
from shutil import rmtree
def printError(message):
stderr.write("\033[38;5;9m" + message + "\033[0m\n\n")
def getSourceDefinitions(file):
try:
with open(file, 'r') as f:
return json.load(f)
except Exception as err:
printError("An error occurred while parsing the provided json file: " + str(err))
return None
def getRestoreResults(resultFile):
try:
if not path.exists(resultFile):
return {"sources": {}}
with open(resultFile, 'r') as f:
return json.load(f)
except Exception as err:
printError("An error occurred while parsing the provided json file: " + str(err))
return {"sources": {}}
def saveRestoreResults(resultFile, results):
with open(resultFile, 'w') as f:
return json.dump(results, f, indent=True)
def cleanseRestoreResults(results, existingKeys):
previousKeys = [x for x in restoreResults["sources"]]
for repoName in previousKeys:
if repoName not in existingKeys:
restoreResults["sources"].pop(repoName, None)
def enforceDefinition(definition, restoreResults, outputDirectory):
output = None
try:
name = definition["name"]
repo = definition["repo"]
version = definition["version"]
postRestore = definition["postRestore"] if "postRestore" in definition else None
previousResult = restoreResults['sources'][name] if name in restoreResults['sources'] else None
if previousResult is not None and "version" in previousResult and previousResult["version"] == version:
return
print("Restoring %s %s %s" % (name, repo, version))
output = path.join(outputDirectory, name)
if path.exists(output):
rmtree(output)
# Try to clone branch
stdout.write('\trestoring...')
stdout.flush()
process = subprocess.Popen(['git', 'clone', '--depth', '1', '-q', '--branch', version, repo, output], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
process.wait()
if process.returncode != 0:
if path.exists(output):
rmtree(output)
# Failed so lets just straight clone
process = subprocess.Popen(['git', 'clone', '-q', repo, output], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
process.wait()
if process.returncode == 0:
# Now that we have our clone, lets checkout a specific revision
process = subprocess.Popen(['git', 'checkout', version], cwd=output, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
process.wait()
if process.returncode != 0:
raise Exception("Failed to checkout version %s from cloned repo.\n%s" % (version, process.stderr.read()))
else:
raise Exception("Failed to clone repo.\n%s" % (process.stderr.read()))
stdout.write('\n\t done.\n')
stdout.flush()
if postRestore is not None:
stdout.write('\trunning post restore command...\n')
stdout.flush()
shellCommand = postRestore["shell"]
cwd = postRestore["cwd"] if "cwd" in postRestore else None
if cwd is None:
cwd = output
else:
cwd = path.join(output, cwd)
process = subprocess.Popen(shellCommand, shell=True, cwd=cwd)
process.wait()
if process.returncode != 0:
raise Exception("Failed to run post restore command.")
stdout.write('\n\t done.\n')
stdout.flush()
restoreResults["sources"][name] = {
"status": "success",
"repo": repo,
"version": version
}
except Exception as err:
printError("\nAn error occurred while restoring %s: %s" % (name, str(err)))
restoreResults["sources"][name] = {"status": "failed"}
if output is not None and path.exists(output):
rmtree(output)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Pulls source repos.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-f', '--file', help='The json file containing sources to restore.', required=True)
parser.add_argument('-o', '--output', default='./packages', help='The output directory to restore sources to.')
args = parser.parse_args()
if not path.exists(args.output):
mkdir(args.output)
resultFile = path.join(args.output, ".restoreResults.json")
sources = getSourceDefinitions(args.file)
restoreResults = getRestoreResults(resultFile)
existingKeys = []
for definition in sources["sources"]:
existingKeys.append(definition["name"])
enforceDefinition(definition, restoreResults, args.output)
cleanseRestoreResults(restoreResults, existingKeys)
saveRestoreResults(resultFile, restoreResults)