This repository has been archived by the owner on Dec 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genproj
executable file
·243 lines (198 loc) · 6.2 KB
/
genproj
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
#!/usr/bin/python3
"""
Initializes a project with a makefile and the appropriate
directories, as well as a README.md
Please invoke it with the -h flag to see the available options
"""
from argparse import ArgumentParser, Namespace
from os import getcwd, mkdir
from os.path import basename, exists
from subprocess import run
from sys import stdout, stderr
from typing import List
def get_options() -> Namespace:
"""
Parses the command line options and returns a Namespace
object containing the corresponding values
"""
parser = ArgumentParser(
description='Generates a project managed by a makefile',
# epilog='''While this program is POSIX compatible, it can
# also be used with other utility programs as well, like
# fd(1) to replace find(1).'''
)
parser.add_argument(
'-g', '--git', action='store_true',
help='Initialize git vcs'
)
# parser.add_argument(
# '-p', '--cpp', action='store_true',
# help='Use C++ instead of C as the project language'
# )
parser.add_argument(
'-F', '--find', type=str, metavar='F',
default='find . -name "*.$(SRCEXT)" -printf "%P\\n"',
help='''Command used to find files. Defaults to
"find . -name *.$(SRCEXT)".'''
)
parser.add_argument(
'-D', '--no-dirs', action='store_true',
help='''Do not create directories while
running this program
'''
)
parser.add_argument(
'-m', '--make', default='Makefile', metavar='M',
help='''The name of the makefile to be generated.
Defaults to 'Makefile'.'''
)
parser.add_argument(
nargs='*', metavar='K=V', dest='vars',
type=str, help='''Variable defaults for generated makefile,
where K is the variable name and V is the value. K can be
specified as all lowercase, but in the makefile it will be
converted to all caps.'''
)
return parser.parse_args()
def git_init() -> None:
"""
Initializes the git repository
"""
run(['git', 'init'], check=True)
def get_vars(args: Namespace) -> tuple:
"""
Parse args.vars and classify them into the appropriate
dictionaries to keep them together
"""
prog = {
'PROG': 'prog',
'CC': 'gcc',
}
exts = {
'SRCEXT': 'c',
'OBJEXT': 'o',
'DEPEXT': 'd',
}
dirs = {
'SRCDIR': 'src',
'DEPDIR': 'dep',
'OBJDIR': 'obj',
'BINDIR': 'bin'
}
flag = {
'CFLAGS': '-g -O0',
'LDFLAGS': ''
}
opts = (prog, exts, dirs, flag)
other = {}
for var in args.vars:
if '=' not in var:
stderr.write(f'{var}: Variables must be of the form K=V\n')
raise SystemExit(1)
else:
key, value = var.split('=')
key = key.upper()
for opt in opts:
if key in opt.keys():
opt[key] = value
break
else:
other[key] = value
return opts + (other,)
def make_makefile(args: Namespace) -> set:
"""
Generate the Makefile to manage the project. Returns a set containing
the names of the directories that the makefile will make use of.
"""
adjust = 10
output = '$(BINDIR)/$(PROG)'
prog, exts, dirs, flag, other = get_vars(args)
# Allow the target makefile to be stdout for piping
with (stdout if args.make == '-' else open(args.make, 'w')) as file:
# Define the functions to format the makefile
def call(name: str, *args) -> str:
return f'$({name} {", ".join(args)})'
def dir_ext(name: str) -> str:
return f'$({name}DIR)/%.$({name}EXT)'
def sep() -> None:
file.write('\n')
# Define the functions to write the makefile
def assign(key: str, value: str) -> None:
line = f'{key.ljust(adjust)}:= {value}'.strip()
file.write(f'{line}\n')
def from_src(to: str) -> str:
assign(
f'{to}FILES',
f'$(SRCFILES:{dir_ext("SRC")}={dir_ext(to)})'
)
def rule(target: str, deps: str = '',
message='', *steps: List[str]) -> None:
header = f'{target}: {deps}'.strip()
file.write(f'{header}\n')
if len(message) > 0:
file.write(f'\t@echo "{message}"\n')
for step in steps:
file.write(f'\t@{step}\n')
sep()
file.write("# Generated by the genproj script\n")
file.write("# Edit to your heart's content\n\n")
for opt in (prog, exts, dirs, flag, other):
for key, value in opt.items():
assign(key, value)
sep()
assign('SRCFILES', call('shell', args.find))
from_src('OBJ')
from_src('DEP')
sep()
rule(
dir_ext('OBJ'),
dir_ext('SRC'),
'Compiling $@',
'$(CC) $(CFLAGS) -c $< -o $@'
)
rule('all', f'dirs {output}', message='Done')
rule(
output,
'$(SRCFILES)',
'Linking $<',
'$(CC) $(LDFLAGS) $^ -o $@'
)
rule(
'dirs',
' '.join(dirs.values()),
'Making directories',
'mkdir -p $^'
)
file.write('-include $(DEPFILES)\n')
sep()
rule(
dir_ext('DEP'),
dir_ext('SRC'),
"",
'rm -f $@',
'$(CC) -MM $< > $@.$$',
r"sed 's,\($*\)\.o[ :]*,$(OBJDIR)/\1.o $@ : ,g' <$@.$$ >$@",
'rm -f $@.$$'
)
rule('.PHONY', 'dirs')
return dirs.values()
def make_readme() -> None:
"""
Generate the project's README.md file
"""
with open('README.md', 'w') as file:
file.write(f'# {basename(getcwd())}\n')
def make_dirs(dirs: list) -> None:
"""
Create the directories specified by dirs
"""
for dir in dirs:
if not exists(dir):
try:
mkdir(dir)
except FileExistsError:
pass
if __name__ == "__main__":
args = get_options()
dirs = make_makefile(args)
make_dirs(dirs)