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"],
34 [HW_${upper}=$HW_ENABLED_DEFAULT])
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 process = Popen("git clone " + LIBSR, shell=True, stderr=PIPE)
81 out, err = process.communicate()
82 if process.returncode:
83 raise Exception(err.decode())
84 gitdir = tmp + '/libsigrok/'
85 do_configure_ac(gitdir)
90 except Exception as e:
95 def do_configure_ac(gitdir):
96 cacpath = gitdir + 'configure.ac'
97 configure_ac = open(cacpath).read()
99 # add AC_ARG_ENABLE option
102 for line in configure_ac.split('\n')[:-1]:
104 if line == "# Hardware support '--enable' options.":
106 elif state == 'acarg':
107 m = re.match('AC_ARG_ENABLE\(([^,]+)', line)
109 drv_short = m.group(1)
110 if drv_short.lower() > names['short']:
111 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
113 if line == '# Checks for libraries.':
115 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
119 raise Exception('AC_ARG_ENABLE markers not found in configure.ac')
122 # add driver Makefile to AC_CONFIG_FILES
125 for line in configure_ac.split('\n')[:-1]:
127 if line.find("AC_CONFIG_FILES([Makefile") > -1:
129 elif state == 'acconf':
130 m = re.match('\t\t hardware/([^/]+)/Makefile', line)
132 drv_short = m.group(1)
133 if drv_short.lower() > names['short']:
134 out += tmpl(TMPL_AUTOCONF_AC_CONFIG_FILES)
138 out += tmpl(TMPL_AUTOCONF_AC_CONFIG_FILES)
142 raise Exception('AC_CONFIG_FILES marker not found in configure.ac')
148 names['summary'] = "%s%s $HW_%s" % (names['short'],
149 '.' * (32 - len(names['name'])), names['upper'])
150 for line in configure_ac.split('\n')[:-1]:
152 if line.find('Enabled hardware drivers') > -1:
154 elif state == 'echo':
155 m = re.match('echo " - ([^\.]+)', line)
157 drv_short = m.group(1)
158 if drv_short.lower() > names['name'].lower():
159 out += tmpl(TMPL_AUTOCONF_SUMMARY)
163 out += tmpl(TMPL_AUTOCONF_SUMMARY)
167 raise Exception('summary marker not found in configure.ac')
170 open(cacpath, 'w').write(configure_ac)
173 def do_hwdriver(gitdir):
174 path = gitdir + 'hwdriver.c'
175 hwdriver = open(path).read()
176 # add HAVE_HW_thing extern and pointers
179 for line in hwdriver.split('\n')[:-1]:
181 if line.find('/** @cond PRIVATE */') == 0:
183 elif line.find('static struct sr_dev_driver *drivers_list') == 0:
185 elif state in ('extern', 'diptr'):
186 if state == 'extern':
187 entry = tmpl(TMPL_HWDRIVER_EXTERN)
190 entry = tmpl(TMPL_HWDRIVER_DIPTR)
192 m = re.match('#ifdef HAVE_.._(.*)', line)
195 if drv > names['upper']:
198 elif not re.match('(extern|\t&|#endif)', line):
204 raise Exception('HAVE_* markers not found in hwdriver.c')
207 open(path, 'w').write(hwdriver)
210 def do_hwmake(gitdir):
211 path = gitdir + 'hardware/Makefile.am'
212 hwmake = open(path).read()
217 for line in hwmake.split('\n')[:-1]:
219 if line.find('SUBDIRS =') > -1:
221 elif state == 'subdirs':
222 m = re.match('\t([^ \\\]+\s*\\\)', line)
224 drv_short = m.group(1)
225 if drv_short.lower() > names['short']:
226 out += tmpl(TMPL_HWMAKE_SUBDIR) + ' \\\n'
229 out += tmpl(TMPL_HWMAKE_SUBDIR) + ' \\\n'
231 elif state == 'driverlib':
232 m = re.match('if [A-Z]{2}_(.*)$', line)
234 drv_short = m.group(1)
235 if drv_short > names['upper']:
236 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
239 if state == 'driverlib':
240 # reached end of file, add it in here
241 out += tmpl(TMPL_HWMAKE_DRIVERLIB).strip()
242 elif state != 'done':
243 raise Exception('markers not found in hardware/Makefile.am')
246 open(path, 'w').write(hwmake)
249 def do_driverskel(gitdir):
250 drvdir = gitdir + 'hardware/' + names['short']
252 open(drvdir + '/Makefile.am', 'w').write(tmpl_file(FILE_DRV_MAKEFILE))
253 open(drvdir + '/api.c', 'w').write(tmpl_file(FILE_DRV_API))
254 open(drvdir + '/protocol.c', 'w').write(tmpl_file(FILE_DRV_PROTOCOL))
255 open(drvdir + '/protocol.h', 'w').write(tmpl_file(FILE_DRV_PROTOCOL_H))
258 def make_patch(gitdir):
260 command('git add hardware/' + names['short'])
261 cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
262 cmd += 'configure.ac hwdriver.c hardware/Makefile.am hardware/' + names['short']
264 cmd = "git format-patch HEAD~1"
265 out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
267 raise Exception(err.decode())
268 patch = out.decode().strip()
269 shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
274 out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
276 raise Exception(err.decode())
279 def parse_gitconfig():
281 author = email = None
282 for line in open(os.environ['HOME'] + '/.gitconfig').readlines():
283 m = re.match('\s*(\w+)\s*=\s*(.*)\s*$', line)
285 key, value = m.groups()
294 if not author or not email:
295 print("Please put your name and email in ~/.gitconfig")
304 scriptdir = os.getcwd()
305 if scriptdir.split('/')[-2:] != ['sigrok-util', 'source']:
306 print("Please call this script from the 'source' directory.")
309 LIBSR = 'git://sigrok.org/libsigrok'
312 if len(sys.argv) < 2:
313 print("Usage: new-driver <name>")
316 author, email = parse_gitconfig()
317 name = ' '.join(sys.argv[1:])
320 'short': re.sub('[^a-z0-9]', '-', name.lower()),
321 'lib': re.sub('[^a-z0-9]', '_', name.lower()),
322 'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
323 'libupper': re.sub('[^A-Z0-9]', '', name.upper()),
324 'year': datetime.datetime.now().year,