-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject
More file actions
executable file
·379 lines (308 loc) · 10.6 KB
/
Copy pathproject
File metadata and controls
executable file
·379 lines (308 loc) · 10.6 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
"""
project - project setup and build helpers.
Subcommands:
git-init initialise a Git repo with standard
.gitattributes and .gitignore
unity-init scaffold a Unity project directory and
.gitignore
shell-script NAME create a new Bash script from a starter
template
cmake [-r] [-o] [CMAKE_ARGS...] configure or update a CMake build directory
cmake-dir BUILD_DIR GENERATOR create an out-of-source CMake build directory
Run `project <subcommand> -h` for per-command help.
"""
import argparse
import json
import os
import subprocess
import sys
# ---------------------------------------------------------------------------
# Metadata
# ---------------------------------------------------------------------------
def bc_metadata():
return {
"schema_version": 1,
"name": "project",
"summary": "Project setup and build helpers",
"command_style": "subcommands",
"config_sections": {},
"subcommands": [
{
"name": "git-init",
"summary": "Initialise a Git repository with bash_common defaults",
"safety": "write",
"args": [],
"options": [],
"artifacts": [],
},
{
"name": "unity-init",
"summary": "Scaffold a Unity project directory and .gitignore",
"safety": "write",
"args": [],
"options": [],
"artifacts": [],
},
{
"name": "shell-script",
"summary": "Create a new Bash script from a starter template",
"safety": "write",
"args": [
{"name": "name", "label": "Script filename", "kind": "path",
"required": True},
],
"options": [],
"artifacts": [
{"kind": "shell", "path_arg": "name"},
],
},
{
"name": "cmake",
"summary": "Configure or update a CMake build directory",
"safety": "write",
"args": [
{"name": "cmake_args", "label": "Extra cmake arguments",
"kind": "path-list", "required": False},
],
"options": [
{"name": "reset", "flag": "--reset", "short_flag": "-r",
"kind": "boolean", "label": "Wipe and re-configure the build directory"},
{"name": "open", "flag": "--open", "short_flag": "-o",
"kind": "boolean", "label": "Open project file after configuring"},
],
"artifacts": [],
},
{
"name": "cmake-dir",
"summary": "Create an out-of-source CMake build directory",
"safety": "write",
"args": [
{"name": "build_dir", "label": "Build directory name", "kind": "string",
"required": True},
{"name": "generator", "label": "CMake generator (e.g. Ninja, Xcode)",
"kind": "string", "required": True},
],
"options": [],
"artifacts": [],
},
],
}
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _run(argv, **kwargs):
return subprocess.run(argv, **kwargs).returncode
def _write_file(path, content):
with open(path, "w", encoding="utf-8") as fh:
fh.write(content)
# ---------------------------------------------------------------------------
# git-init
# ---------------------------------------------------------------------------
_GITATTRIBUTES = "* text=auto\n"
_GITIGNORE = """\
build*/
*.py[cod]
__pycache__/
"""
def cmd_git_init(args):
added = False
if not os.path.isdir(".git"):
_run(["git", "init"])
if not os.path.isfile(".gitattributes"):
_write_file(".gitattributes", _GITATTRIBUTES)
_run(["git", "add", ".gitattributes"])
added = True
if not os.path.isfile(".gitignore"):
_write_file(".gitignore", _GITIGNORE)
_run(["git", "add", ".gitignore"])
added = True
if added:
_run(["git", "commit", "-m", "Add git config"])
_run(["git", "log"])
return 0
# ---------------------------------------------------------------------------
# unity-init
# ---------------------------------------------------------------------------
_UNITY_GITIGNORE = """\
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/Assets/AssetStoreTools*
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pidb.meta
sysinfo.txt
*.apk
*.unitypackage
"""
_UNITY_DIRS = [
"Assets/Audio",
"Assets/Models",
"Assets/Models/Materials",
"Assets/Models/Textures",
"Assets/Prefabs",
"Assets/Scenes",
"Assets/Scripts",
]
def cmd_unity_init(args):
if not os.path.isdir(".git"):
_run(["git", "init"])
if not os.path.isfile(".gitignore"):
_write_file(".gitignore", _UNITY_GITIGNORE)
_run(["git", "add", ".gitignore"])
for d in _UNITY_DIRS:
if not os.path.isdir(d):
os.makedirs(d, exist_ok=True)
print(f"Created {d}")
return 0
# ---------------------------------------------------------------------------
# shell-script
# ---------------------------------------------------------------------------
_SHELL_TEMPLATE = """\
#!/usr/bin/env bash
SCRIPTPATH=$( cd $(dirname $0) ; pwd -P )
FILE=$1
OUT=${FILE%.*}_.mp4
usage() {
echo "Usage: $0 [-i] [-c] VIDEO"
}
# getopt "x" no-arg, "x:" required arg, "x::" optional arg
while getopts "ic" OPT; do
case "${OPT}" in
i)
echo "$FILE"
shift
;;
c)
blah
shift
;;
*) usage ;;
esac
done
shift "$((OPTIND-1))"
ARGS=$@
"""
def cmd_shell_script(args):
fname = args.name
if os.path.exists(fname):
print(f"error: file already exists: {fname}", file=sys.stderr)
return 1
_write_file(fname, _SHELL_TEMPLATE)
os.chmod(fname, os.stat(fname).st_mode | 0o100)
print(f"Created {fname}")
return 0
# ---------------------------------------------------------------------------
# cmake
# ---------------------------------------------------------------------------
def cmd_cmake(args):
build_dir = "build"
original_dir = os.getcwd()
if os.path.isfile("CMakeCache.txt"):
build_dir = os.path.basename(original_dir)
os.chdir("..")
elif not os.path.isfile("CMakeLists.txt"):
print("error: no CMakeLists.txt found. Are you in a cmake project?",
file=sys.stderr)
return 1
else:
os.makedirs(build_dir, exist_ok=True)
print(f"Build dir: {build_dir}")
if args.reset:
import shutil as _shutil
print("Resetting build dir...")
for item in os.listdir(build_dir):
p = os.path.join(build_dir, item)
if os.path.isdir(p):
_shutil.rmtree(p)
else:
os.remove(p)
os.chdir(build_dir)
cmake_argv = ["cmake"] + args.cmake_args + [".."]
rc = _run(cmake_argv)
os.chdir(original_dir)
if args.open and rc == 0:
_open_project(os.path.join(original_dir, build_dir))
return rc
def _open_project(build_path):
makefile = os.path.join(build_path, "Makefile")
if os.path.isfile(makefile):
subprocess.run(["open", makefile])
return
for item in os.listdir(build_path):
if item.endswith(".xcodeproj"):
subprocess.run(["open", os.path.join(build_path, item)])
return
# ---------------------------------------------------------------------------
# cmake-dir
# ---------------------------------------------------------------------------
def cmd_cmake_dir(args):
d = args.build_dir
if os.path.isdir(d):
print(f"error: directory already exists: {d}", file=sys.stderr)
return 1
os.makedirs(d)
rc = subprocess.run(["cmake", "-G", args.generator, ".."], cwd=d).returncode
return rc
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def _build_parser():
parser = argparse.ArgumentParser(
prog="project",
description="Project setup and build helpers.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
subs = parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND")
p = subs.add_parser("git-init",
help="initialise a Git repo with standard .gitattributes and .gitignore")
p.set_defaults(handler=cmd_git_init)
p = subs.add_parser("unity-init",
help="scaffold a Unity project directory and .gitignore")
p.set_defaults(handler=cmd_unity_init)
p = subs.add_parser("shell-script",
help="create a new Bash script from a starter template")
p.add_argument("name", help="filename for the new script")
p.set_defaults(handler=cmd_shell_script)
p = subs.add_parser("cmake",
help="configure or update a CMake build directory")
p.add_argument("-r", "--reset", action="store_true",
help="wipe the build directory before configuring")
p.add_argument("-o", "--open", action="store_true",
help="open project file after configuring")
p.add_argument("cmake_args", nargs=argparse.REMAINDER,
help="extra arguments forwarded to cmake")
p.set_defaults(handler=cmd_cmake)
p = subs.add_parser("cmake-dir",
help="create an out-of-source CMake build directory")
p.add_argument("build_dir", help="directory name to create")
p.add_argument("generator", help="CMake generator (e.g. Ninja, Xcode, \"Unix Makefiles\")")
p.set_defaults(handler=cmd_cmake_dir)
return parser
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
if argv == ["--bc-metadata"]:
print(json.dumps(bc_metadata(), indent=2, sort_keys=True))
return 0
parser = _build_parser()
args = parser.parse_args(argv)
handler = getattr(args, "handler", None)
if handler is None:
parser.print_help()
return 1
return handler(args) or 0
if __name__ == "__main__":
sys.exit(main())