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'
44 TMPL_HWMAKE_DRIVERLIB = """if HW_${upper}
45 libsigrok_la_SOURCES += \
46 hardware/${short}/protocol.h \
47 hardware/${short}/protocol.c \
48 hardware/${short}/api.c
52 TMPL_HWDRIVER_EXTERN = """\
53 #ifdef HAVE_HW_${upper}
54 extern SR_PRIV struct sr_dev_driver ${lib}_driver_info;
57 TMPL_HWDRIVER_DIPTR = """\
58 #ifdef HAVE_HW_${upper}
62 FILE_DRV_API = 'drv-api.c'
63 FILE_DRV_PROTOCOL = 'drv-protocol.c'
64 FILE_DRV_PROTOCOL_H = 'drv-protocol.h'
67 out = re.sub(r'\${([^}]+)}', lambda x: str(names[x.group(1)]), template)
72 def tmpl_file(filename):
73 template = open(TMPLDIR + '/' + filename).read()
79 tmp = tempfile.mkdtemp()
82 process = Popen("git clone " + LIBSR, shell=True, stderr=PIPE)
83 out, err = process.communicate()
84 if process.returncode:
85 raise Exception(err.decode())
86 gitdir = tmp + '/libsigrok/'
87 do_configure_ac(gitdir)
92 except Exception as e:
97 def do_configure_ac(gitdir):
98 cacpath = gitdir + 'configure.ac'
99 configure_ac = open(cacpath).read()
101 # add AC_ARG_ENABLE option
104 for line in configure_ac.split('\n')[:-1]:
106 if line == "# Hardware support '--enable' options.":
108 elif state == 'acarg':
109 m = re.match('AC_ARG_ENABLE\(([^,]+)', line)
111 drv_short = m.group(1)
112 if drv_short.lower() > names['short']:
113 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
115 if line == '# Checks for libraries.':
117 out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
121 raise Exception('AC_ARG_ENABLE markers not found in configure.ac')
127 names['summary'] = "%s%s $HW_%s" % (names['short'],
128 '.' * (32 - len(names['name'])), names['upper'])
129 for line in configure_ac.split('\n')[:-1]:
131 if line.find('Enabled hardware drivers') > -1:
133 elif state == 'echo':
134 m = re.match('echo " - ([^\.]+)', line)
136 drv_short = m.group(1)
137 if drv_short.lower() > names['name'].lower():
138 out += tmpl(TMPL_AUTOCONF_SUMMARY)
142 out += tmpl(TMPL_AUTOCONF_SUMMARY)
146 raise Exception('summary marker not found in configure.ac')
149 open(cacpath, 'w').write(configure_ac)
152 def do_hwdriver(gitdir):
153 path = gitdir + 'hwdriver.c'
154 hwdriver = open(path).read()
155 # add HAVE_HW_thing extern and pointers
158 for line in hwdriver.split('\n')[:-1]:
160 if line.find('/** @cond PRIVATE */') == 0:
162 elif line.find('static struct sr_dev_driver *drivers_list') == 0:
164 elif state in ('extern', 'diptr'):
165 if state == 'extern':
166 entry = tmpl(TMPL_HWDRIVER_EXTERN)
169 entry = tmpl(TMPL_HWDRIVER_DIPTR)
171 m = re.match('#ifdef HAVE_.._(.*)', line)
174 if drv > names['upper']:
177 elif not re.match('(extern|\t&|#endif)', line):
183 raise Exception('HAVE_* markers not found in hwdriver.c')
186 open(path, 'w').write(hwdriver)
189 def do_hwmake(gitdir):
190 path = gitdir + 'Makefile.am'
191 hwmake = open(path).read()
193 # add entry at correct place in Makefile
196 for line in hwmake.split('\n')[:-1]:
198 if line.find('# Hardware drivers') > -1:
200 elif state == 'driverlib':
201 m = re.match('if [A-Z]{2}_(.*)$', line)
203 drv_short = m.group(1)
204 if drv_short > names['upper']:
205 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
209 raise Exception('markers not found in Makefile.am')
212 open(path, 'w').write(hwmake)
215 def do_driverskel(gitdir):
216 drvdir = gitdir + 'hardware/' + names['short']
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))
223 def make_patch(gitdir):
225 command('git add hardware/' + names['short'])
226 cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
227 cmd += 'configure.ac Makefile.am hwdriver.c hardware/' + names['short']
229 cmd = "git format-patch HEAD~1"
230 out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
232 raise Exception(err.decode())
233 patch = out.decode().strip()
234 shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
239 out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
241 raise Exception(err.decode())
244 def parse_gitconfig():
246 author = email = None
247 for line in open(os.environ['HOME'] + '/.gitconfig').readlines():
248 m = re.match('\s*(\w+)\s*=\s*(.*)\s*$', line)
250 key, value = m.groups()
259 if not author or not email:
260 print("Please put your name and email in ~/.gitconfig")
269 scriptdir = os.getcwd()
270 if scriptdir.split('/')[-2:] != ['sigrok-util', 'source']:
271 print("Please call this script from the 'source' directory.")
274 LIBSR = 'git://sigrok.org/libsigrok'
277 if len(sys.argv) < 2:
278 print("Usage: new-driver <name>")
281 author, email = parse_gitconfig()
282 name = ' '.join(sys.argv[1:])
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()),
289 'year': datetime.datetime.now().year,