]> sigrok.org Git - sigrok-util.git/blame - source/new-driver
Adapted new-driver to new build system
[sigrok-util.git] / source / new-driver
CommitLineData
a65d66c0 1#!/usr/bin/python3
0af91589
UH
2##
3## This file is part of the sigrok-util project.
4##
5## Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6##
7## This program is free software: you can redistribute it and/or modify
8## it under the terms of the GNU General Public License as published by
9## the Free Software Foundation, either version 3 of the License, or
10## (at your option) any later version.
11##
12## This program is distributed in the hope that it will be useful,
13## but WITHOUT ANY WARRANTY; without even the implied warranty of
14## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15## GNU General Public License for more details.
16##
17## You should have received a copy of the GNU General Public License
18## along with this program. If not, see <http://www.gnu.org/licenses/>.
19##
a65d66c0
BV
20
21import os
22import sys
23import tempfile
24from subprocess import Popen, PIPE
25import shutil
26import re
27import socket
28import datetime
29
0af91589
UH
30TMPL_AUTOCONF_AC_ARG_ENABLE = """\
31AC_ARG_ENABLE(${short}, AC_HELP_STRING([--enable-${short}],
d51b5323
BV
32 [enable ${name} support [default=yes]]),
33 [HW_${upper}="$enableval"],
28dff7d5 34 [HW_${upper}=$HW_ENABLED_DEFAULT])
a65d66c0
BV
35AM_CONDITIONAL(HW_${upper}, test x$HW_${upper} = xyes)
36if test "x$HW_${upper}" = "xyes"; then
28113f29 37 AC_DEFINE(HAVE_HW_${upper}, 1, [${name} support])
a65d66c0
BV
38fi
39
40"""
41TMPL_AUTOCONF_AC_CONFIG_FILES = "\t\t hardware/${short}/Makefile\n"
42TMPL_AUTOCONF_SUMMARY = 'echo " - ${summary}"\n'
7d787983 43
d51b5323 44TMPL_HWMAKE_DRIVERLIB = """if HW_${upper}
7d787983
AK
45libsigrok_la_SOURCES += \
46 hardware/${short}/protocol.h \
47 hardware/${short}/protocol.c \
48 hardware/${short}/api.c
d51b5323
BV
49endif
50
51"""
52TMPL_HWDRIVER_EXTERN = """\
53#ifdef HAVE_HW_${upper}
54extern SR_PRIV struct sr_dev_driver ${lib}_driver_info;
55#endif
56"""
57TMPL_HWDRIVER_DIPTR = """\
58#ifdef HAVE_HW_${upper}
59 &${lib}_driver_info,
60#endif
61"""
a65d66c0
BV
62FILE_DRV_API = 'drv-api.c'
63FILE_DRV_PROTOCOL = 'drv-protocol.c'
64FILE_DRV_PROTOCOL_H = 'drv-protocol.h'
65
66def tmpl(template):
67 out = re.sub(r'\${([^}]+)}', lambda x: str(names[x.group(1)]), template)
68
69 return out
70
71
72def tmpl_file(filename):
73 template = open(TMPLDIR + '/' + filename).read()
74
75 return tmpl(template)
76
77
78def new_driver():
79 tmp = tempfile.mkdtemp()
80 try:
81 os.chdir(tmp)
617f4da0
AJ
82 process = Popen("git clone " + LIBSR, shell=True, stderr=PIPE)
83 out, err = process.communicate()
84 if process.returncode:
a65d66c0
BV
85 raise Exception(err.decode())
86 gitdir = tmp + '/libsigrok/'
87 do_configure_ac(gitdir)
d51b5323 88 do_hwdriver(gitdir)
a65d66c0
BV
89 do_hwmake(gitdir)
90 do_driverskel(gitdir)
91 make_patch(gitdir)
92 except Exception as e:
93 print(e)
94 shutil.rmtree(tmp)
95
96
97def do_configure_ac(gitdir):
98 cacpath = gitdir + 'configure.ac'
99 configure_ac = open(cacpath).read()
100
101 # add AC_ARG_ENABLE option
102 out = ''
103 state = 'copy'
104 for line in configure_ac.split('\n')[:-1]:
105 if state == 'copy':
106 if line == "# Hardware support '--enable' options.":
107 state = 'acarg'
108 elif state == 'acarg':
109 m = re.match('AC_ARG_ENABLE\(([^,]+)', line)
110 if m:
111 drv_short = m.group(1)
112 if drv_short.lower() > names['short']:
113 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
114 state = 'done'
115 if line == '# Checks for libraries.':
116 # new one at the end
117 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
118 state = 'done'
119 out += line + '\n'
120 if state != 'done':
121 raise Exception('AC_ARG_ENABLE markers not found in configure.ac')
122 configure_ac = out
123
a65d66c0
BV
124 # add summary line
125 out = ''
126 state = 'copy'
16e3ae13 127 names['summary'] = "%s%s $HW_%s" % (names['short'],
a65d66c0
BV
128 '.' * (32 - len(names['name'])), names['upper'])
129 for line in configure_ac.split('\n')[:-1]:
130 if state == 'copy':
131 if line.find('Enabled hardware drivers') > -1:
132 state = 'echo'
133 elif state == 'echo':
134 m = re.match('echo " - ([^\.]+)', line)
135 if m:
136 drv_short = m.group(1)
137 if drv_short.lower() > names['name'].lower():
138 out += tmpl(TMPL_AUTOCONF_SUMMARY)
139 state = 'done'
140 else:
141 # new one at the end
142 out += tmpl(TMPL_AUTOCONF_SUMMARY)
143 state = 'done'
144 out += line + '\n'
145 if state != 'done':
146 raise Exception('summary marker not found in configure.ac')
147 configure_ac = out
148
149 open(cacpath, 'w').write(configure_ac)
150
151
d51b5323
BV
152def do_hwdriver(gitdir):
153 path = gitdir + 'hwdriver.c'
154 hwdriver = open(path).read()
155 # add HAVE_HW_thing extern and pointers
156 out = ''
157 state = 'copy'
158 for line in hwdriver.split('\n')[:-1]:
159 if state == 'copy':
160 if line.find('/** @cond PRIVATE */') == 0:
161 state = 'extern'
162 elif line.find('static struct sr_dev_driver *drivers_list') == 0:
163 state = 'diptr'
164 elif state in ('extern', 'diptr'):
165 if state == 'extern':
166 entry = tmpl(TMPL_HWDRIVER_EXTERN)
167 next_state = 'copy'
168 else:
169 entry = tmpl(TMPL_HWDRIVER_DIPTR)
170 next_state = 'done'
171 m = re.match('#ifdef HAVE_.._(.*)', line)
172 if m:
173 drv = m.group(1)
174 if drv > names['upper']:
175 out += entry
176 state = next_state
177 elif not re.match('(extern|\t&|#endif)', line):
178 # new one at the end
179 out += entry
180 state = next_state
181 out += line + '\n'
182 if state != 'done':
183 raise Exception('HAVE_* markers not found in hwdriver.c')
184 hwdriver = out
185
186 open(path, 'w').write(hwdriver)
187
188
a65d66c0 189def do_hwmake(gitdir):
7d787983 190 path = gitdir + 'Makefile.am'
a65d66c0
BV
191 hwmake = open(path).read()
192
7d787983 193 # add entry at correct place in Makefile
a65d66c0
BV
194 out = ''
195 state = 'copy'
196 for line in hwmake.split('\n')[:-1]:
197 if state == 'copy':
7d787983 198 if line.find('# Hardware drivers') > -1:
d51b5323
BV
199 state = 'driverlib'
200 elif state == 'driverlib':
201 m = re.match('if [A-Z]{2}_(.*)$', line)
202 if m:
203 drv_short = m.group(1)
204 if drv_short > names['upper']:
205 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
206 state = 'done'
a65d66c0 207 out += line + '\n'
7d787983
AK
208 if state != 'done':
209 raise Exception('markers not found in Makefile.am')
a65d66c0
BV
210 hwmake = out
211
212 open(path, 'w').write(hwmake)
213
214
215def do_driverskel(gitdir):
216 drvdir = gitdir + 'hardware/' + names['short']
217 os.mkdir(drvdir)
a65d66c0
BV
218 open(drvdir + '/api.c', 'w').write(tmpl_file(FILE_DRV_API))
219 open(drvdir + '/protocol.c', 'w').write(tmpl_file(FILE_DRV_PROTOCOL))
220 open(drvdir + '/protocol.h', 'w').write(tmpl_file(FILE_DRV_PROTOCOL_H))
221
222
223def make_patch(gitdir):
224 os.chdir(gitdir)
225 command('git add hardware/' + names['short'])
0af91589 226 cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
7d787983 227 cmd += 'configure.ac Makefile.am hwdriver.c hardware/' + names['short']
a65d66c0
BV
228 command(cmd)
229 cmd = "git format-patch HEAD~1"
230 out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
231 if err:
232 raise Exception(err.decode())
233 patch = out.decode().strip()
234 shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
235 print(patch)
236
237
238def command(cmd):
239 out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
240 if err:
241 raise Exception(err.decode())
242
243
244def parse_gitconfig():
0af91589
UH
245 try:
246 author = email = None
247 for line in open(os.environ['HOME'] + '/.gitconfig').readlines():
248 m = re.match('\s*(\w+)\s*=\s*(.*)\s*$', line)
249 if m:
250 key, value = m.groups()
251 if key == 'name':
252 author = value
253 elif key == 'email':
254 email = value
255 if author and email:
256 break
257 except:
258 pass
259 if not author or not email:
260 print("Please put your name and email in ~/.gitconfig")
261 sys.exit()
262
263 return author, email
a65d66c0
BV
264
265#
266# main
267#
268
269scriptdir = os.getcwd()
87c5b243
BV
270if scriptdir.split('/')[-2:] != ['sigrok-util', 'source']:
271 print("Please call this script from the 'source' directory.")
272 sys.exit(1)
273
274LIBSR = 'git://sigrok.org/libsigrok'
275TMPLDIR = scriptdir
a65d66c0
BV
276
277if len(sys.argv) < 2:
0af91589 278 print("Usage: new-driver <name>")
a65d66c0
BV
279 sys.exit()
280
281author, email = parse_gitconfig()
282name = ' '.join(sys.argv[1:])
283names = {
284 'name': name,
285 'short': re.sub('[^a-z0-9]', '-', name.lower()),
286 'lib': re.sub('[^a-z0-9]', '_', name.lower()),
287 'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
288 'libupper': re.sub('[^A-Z0-9]', '', name.upper()),
0af91589
UH
289 'year': datetime.datetime.now().year,
290 'author': author,
291 'email': email,
a65d66c0
BV
292}
293new_driver()
294