-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall-graphwalker.py
More file actions
203 lines (149 loc) · 6.37 KB
/
install-graphwalker.py
File metadata and controls
203 lines (149 loc) · 6.37 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""A simple python script for installing GraphWalker CLI on Linux, MacOS and Windows."""
from pathlib import Path
import subprocess
import platform
import logging
import shutil
import shlex
import sys
import re
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
pattern = re.compile('^([0-9]+\.){2}([0-9]+)$')
class Command:
def __init__(self, command, cwd=None, timeout=None):
self.command = command
self.args = shlex.split(command)
self.cwd = cwd
self.timeout = timeout
logger.info("Command: {}".format(self.command))
logger.info("Args: {}".format(self.args))
logger.info("CWD: {}".format(self.cwd))
try:
logging.info("Running subprocess: '{}'.".format(self.command))
process = subprocess.Popen(
self.command if platform.system() == "Windows" else self.args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=self.cwd,
shell=platform.system() == "Windows"
)
outs, errs = process.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
process.kill()
outs, errs = process.communicate()
self._log_output(outs, errs)
raise
except Exception as exception:
logger.error("An unexpected error ocurred while running: '{}'.".format(self.command))
logger.error(exception)
raise
else:
logger.info("Subprocess '{}' finished.".format(self.command))
self._log_output(outs, errs)
exitcode = process.returncode
if not exitcode == 0:
raise Exception("The command '{}' failed with exit code: {}.".format(self.command, exitcode))
def _log_output(self, outs, errs):
if outs:
for line in outs.decode("utf-8").splitlines():
logger.debug("[STDOUT] >>> {}".format(line))
if errs:
for line in errs.decode("utf-8").splitlines():
logger.debug("[STDERR] >>> {}".format(line))
def has_command(command, timeout=10):
"""Returns True if it can run the command, otherwise returns False."""
try:
Command(command, timeout=timeout)
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
return False
def validate_graphwalker_version(version):
if version == 'latest':
return
if not pattern.match(version):
raise Exception("Invalid GraphWalker version '{}'. The version must use a 'major.minor' pattern (e.g 3.2.1, 3.4.0).".format(version))
def get_files_by_extension(path, extension):
return [filename for filename in path.iterdir() if filename.suffix == extension]
def clone_graphwalker(path):
url = "https://github.com/GraphWalker/graphwalker-project.git"
logger.debug("Clone the GraphWalker repository from: {}".format(url))
Command("git clone {} {}".format(url, path))
def build_graphwalker(path, version):
logger.info("Build GraphWalker CLI...")
logger.debug("Path: {}".format(path))
logger.debug("Version: {}".format(version))
if version != "latest":
logger.info("Checkout to version {}...".format(version))
try:
Command("git checkout {}".format(version), cwd=path)
except Exception:
raise Exception("No matching version found for GraphWalker version '{}'.".format(version))
try:
Command("mvn package -pl graphwalker-cli -am -Dmaven.test.skip", cwd=path)
except Exception:
raise Exception("The GraphWalker build processes failed.")
build_path = path / "graphwalker-cli" / "target"
jar_files = get_files_by_extension(build_path, ".jar")
jar_file = [filename for filename in jar_files if filename.name.startswith("graphwalker-cli-")][0]
logger.debug("JAR files: {}".format(jar_files))
logger.debug("JAR file: {}".format(jar_files))
return build_path / jar_file
def create_graphwalker_script(path, jar_path):
logger.info("Create the GraphWalker CLI script file...")
logger.debug("Path: {!r}".format(path))
logger.debug("JAR path: {!r}".format(jar_path))
jar_file = jar_path.name
dst = path / jar_file
logger.info("Move '{}' to '{}'...".format(jar_path, dst))
shutil.move(jar_path, dst)
if platform.system() == "Windows":
script_file = path / "gw.bat"
logger.info("Create {}...".format(script_file))
with open(script_file, "w") as fp:
script_content = [
"@echo off",
"java -jar {} %*".format(dst)
]
fp.write('\n'.join(script_content) + '\n')
Command("setx PATH \"%PATH%;{}\"".format(path))
else:
script_file = path / "gw.sh"
logger.info("Create {}...".format(script_file))
with open(script_file, "w") as fp:
script_content = [
"#!/bin/bash",
"java -jar {} \"$@\"".format(dst)
]
fp.write('\n'.join(script_content) + '\n')
Command("chmod +x {}".format(script_file), cwd=path)
Command("ln -s {} /usr/local/bin/gw".format(script_file), cwd=path)
def main(version):
for command in [("git", "--version"), ("java", "--version"), ("mvn", "--version")]:
if not has_command(" ".join(command)):
raise Exception("Could not run '{}'. Make sure '{}' is installed.".format(" ".join(command), command[0]))
if not version:
version = "latest"
validate_graphwalker_version(version)
if platform.system() == "Windows":
path = Path.home() / "graphwalker"
else:
path = Path.home() / ".graphwalker"
logger.debug("GraphWalker home directory: {}".format(path))
path.mkdir(exist_ok=True)
repo_path = path / "graphwalker-project"
logger.debug("GraphWalker repo directory: {}".format(repo_path))
clone_graphwalker(repo_path)
try:
jar_path = build_graphwalker(repo_path, version)
logger.debug("GraphWalker jar file: {}".format(jar_path))
create_graphwalker_script(path, jar_path)
finally:
logger.debug("Remove the GraphWalker repo from: {}".format(repo_path))
# Ignore errors as a quick fix for windows
shutil.rmtree(repo_path, ignore_errors=True)
if __name__ == '__main__':
version = ""
if len(sys.argv) >= 2:
version = sys.argv[1]
main(version)