3 ## This file is part of the sigrok-util project.
5 ## Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
24 from subprocess import Popen, PIPE
30 TMPL_AUTOCONF_AC_ARG_ENABLE = """\
31 AC_ARG_ENABLE(${short}, AC_HELP_STRING([--enable-${short}],
32 [enable ${name} support [default=yes]]),
33 [HW_${upper}="$enableval"],
35 AM_CONDITIONAL(HW_${upper}, test x$HW_${upper} = xyes)
36 if test "x$HW_${upper}" = "xyes"; then
37 AC_DEFINE(HAVE_HW_${upper}, 1, [${name} support])
41 TMPL_AUTOCONF_AC_CONFIG_FILES = "\t\t hardware/${short}/Makefile\n"
42 TMPL_AUTOCONF_SUMMARY = 'echo " - ${summary}"\n'
43 TMPL_HWMAKE_SUBDIR = '\t${short}'
44 TMPL_HWMAKE_DRIVERLIB = """if HW_${upper}
45 libsigrokhardware_la_LIBADD += ${short}/libsigrok_hw_${lib}.la
49 TMPL_HWDRIVER_EXTERN = """\
50 #ifdef HAVE_HW_${upper}
51 extern SR_PRIV struct sr_dev_driver ${lib}_driver_info;
54 TMPL_HWDRIVER_DIPTR = """\
55 #ifdef HAVE_HW_${upper}
59 FILE_DRV_MAKEFILE = 'drv-Makefile.am'
60 FILE_DRV_API = 'drv-api.c'
61 FILE_DRV_PROTOCOL = 'drv-protocol.c'
62 FILE_DRV_PROTOCOL_H = 'drv-protocol.h'
65 out = re.sub(r'\${([^}]+)}', lambda x: str(names[x.group(1)]), template)
70 def tmpl_file(filename):
71 template = open(TMPLDIR + '/' + filename).read()
77 tmp = tempfile.mkdtemp()
80 out, err = Popen("git clone " + LIBSR, shell=True, stderr=PIPE).communicate()
82 raise Exception(err.decode())
83 gitdir = tmp + '/libsigrok/'
84 do_configure_ac(gitdir)
89 except Exception as e:
94 def do_configure_ac(gitdir):
95 cacpath = gitdir + 'configure.ac'
96 configure_ac = open(cacpath).read()
98 # add AC_ARG_ENABLE option
101 for line in configure_ac.split('\n')[:-1]:
103 if line == "# Hardware support '--enable' options.":
105 elif state == 'acarg':
106 m = re.match('AC_ARG_ENABLE\(([^,]+)', line)
108 drv_short = m.group(1)
109 if drv_short.lower() > names['short']:
110 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
112 if line == '# Checks for libraries.':
114 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
118 raise Exception('AC_ARG_ENABLE markers not found in configure.ac')
121 # add driver Makefile to AC_CONFIG_FILES
124 for line in configure_ac.split('\n')[:-1]:
126 if line.find("AC_CONFIG_FILES([Makefile") > -1:
128 elif state == 'acconf':
129 m = re.match('\t\t hardware/([^/]+)/Makefile', line)
131 drv_short = m.group(1)
132 if drv_short.lower() > names['short']:
133 out += tmpl(TMPL_AUTOCONF_AC_CONFIG_FILES)
137 out += tmpl(TMPL_AUTOCONF_AC_CONFIG_FILES)
141 raise Exception('AC_CONFIG_FILES marker not found in configure.ac')
147 names['summary'] = "%s%s $HW_%s" % (names['name'],
148 '.' * (32 - len(names['name'])), names['upper'])
149 for line in configure_ac.split('\n')[:-1]:
151 if line.find('Enabled hardware drivers') > -1:
153 elif state == 'echo':
154 m = re.match('echo " - ([^\.]+)', line)
156 drv_short = m.group(1)
157 if drv_short.lower() > names['name'].lower():
158 out += tmpl(TMPL_AUTOCONF_SUMMARY)
162 out += tmpl(TMPL_AUTOCONF_SUMMARY)
166 raise Exception('summary marker not found in configure.ac')
169 open(cacpath, 'w').write(configure_ac)
172 def do_hwdriver(gitdir):
173 path = gitdir + 'hwdriver.c'
174 hwdriver = open(path).read()
175 # add HAVE_HW_thing extern and pointers
178 for line in hwdriver.split('\n')[:-1]:
180 if line.find('/** @cond PRIVATE */') == 0:
182 elif line.find('static struct sr_dev_driver *drivers_list') == 0:
184 elif state in ('extern', 'diptr'):
185 if state == 'extern':
186 entry = tmpl(TMPL_HWDRIVER_EXTERN)
189 entry = tmpl(TMPL_HWDRIVER_DIPTR)
191 m = re.match('#ifdef HAVE_.._(.*)', line)
194 if drv > names['upper']:
197 elif not re.match('(extern|\t&|#endif)', line):
203 raise Exception('HAVE_* markers not found in hwdriver.c')
206 open(path, 'w').write(hwdriver)
209 def do_hwmake(gitdir):
210 path = gitdir + 'hardware/Makefile.am'
211 hwmake = open(path).read()
216 for line in hwmake.split('\n')[:-1]:
218 if line.find('SUBDIRS =') > -1:
220 elif state == 'subdirs':
221 m = re.match('\t([^ \\\]+\s*\\\)', line)
223 drv_short = m.group(1)
224 if drv_short.lower() > names['short']:
225 out += tmpl(TMPL_HWMAKE_SUBDIR) + ' \\\n'
228 out += tmpl(TMPL_HWMAKE_SUBDIR) + ' \\\n'
230 elif state == 'driverlib':
231 m = re.match('if [A-Z]{2}_(.*)$', line)
233 drv_short = m.group(1)
234 if drv_short > names['upper']:
235 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
238 if state == 'driverlib':
239 # reached end of file, add it in here
240 out += tmpl(TMPL_HWMAKE_DRIVERLIB).strip()
241 elif state != 'done':
242 raise Exception('markers not found in hardware/Makefile.am')
245 open(path, 'w').write(hwmake)
248 def do_driverskel(gitdir):
249 drvdir = gitdir + 'hardware/' + names['short']
251 open(drvdir + '/Makefile.am', 'w').write(tmpl_file(FILE_DRV_MAKEFILE))
252 open(drvdir + '/api.c', 'w').write(tmpl_file(FILE_DRV_API))
253 open(drvdir + '/protocol.c', 'w').write(tmpl_file(FILE_DRV_PROTOCOL))
254 open(drvdir + '/protocol.h', 'w').write(tmpl_file(FILE_DRV_PROTOCOL_H))
257 def make_patch(gitdir):
259 command('git add hardware/' + names['short'])
260 cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
261 cmd += 'configure.ac hwdriver.c hardware/Makefile.am hardware/' + names['short']
263 cmd = "git format-patch HEAD~1"
264 out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
266 raise Exception(err.decode())
267 patch = out.decode().strip()
268 shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
273 out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
275 raise Exception(err.decode())
278 def parse_gitconfig():
280 author = email = None
281 for line in open(os.environ['HOME'] + '/.gitconfig').readlines():
282 m = re.match('\s*(\w+)\s*=\s*(.*)\s*$', line)
284 key, value = m.groups()
293 if not author or not email:
294 print("Please put your name and email in ~/.gitconfig")
303 scriptdir = os.getcwd()
304 if socket.gethostname() == 'sigrok':
305 LIBSR = '/data/git/libsigrok'
306 TMPLDIR = '/data/tools/tmpl'
308 LIBSR = 'git://sigrok.org/libsigrok'
311 if len(sys.argv) < 2:
312 print("Usage: new-driver <name>")
315 author, email = parse_gitconfig()
316 name = ' '.join(sys.argv[1:])
319 'short': re.sub('[^a-z0-9]', '-', name.lower()),
320 'lib': re.sub('[^a-z0-9]', '_', name.lower()),
321 'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
322 'libupper': re.sub('[^A-Z0-9]', '', name.upper()),
323 'year': datetime.datetime.now().year,