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_DRIVER = "DRIVER([${name}], [${short}])\n"
31 TMPL_AUTOCONF_DRIVER2 = "DRIVER2([HW_${upper}], [$HW_${upper}], [HAVE_HW_${upper}])\n"
33 TMPL_HWMAKE_DRIVERLIB = """if HW_${upper}
34 libsigrok_la_SOURCES += \\
35 src/hardware/${short}/protocol.h \\
36 src/hardware/${short}/protocol.c \\
37 src/hardware/${short}/api.c
40 TMPL_DRIVERS_EXTERN = """\
41 #ifdef HAVE_HW_${upper}
42 extern SR_PRIV struct sr_dev_driver ${lib}_driver_info;
45 TMPL_DRIVERS_POINTER = """\
46 #ifdef HAVE_HW_${upper}
50 FILE_DRV_API = 'drv-api.c'
51 FILE_DRV_PROTOCOL = 'drv-protocol.c'
52 FILE_DRV_PROTOCOL_H = 'drv-protocol.h'
55 out = re.sub(r'\${([^}]+)}', lambda x: str(names[x.group(1)]), template)
60 def tmpl_file(filename):
61 template = open(TMPLDIR + '/' + filename).read()
67 tmp = tempfile.mkdtemp()
70 process = Popen("git clone --depth=1 " + LIBSR, shell=True, stderr=PIPE)
71 out, err = process.communicate()
72 if process.returncode:
73 raise Exception(err.decode())
74 gitdir = tmp + '/libsigrok/'
80 except Exception as e:
85 # add DRIVER and DRIVER2 entries to configure.ac
86 def do_autoconf(gitdir):
87 cacpath = gitdir + 'configure.ac'
88 configure_ac = open(cacpath).read()
93 for line in configure_ac.split('\n')[:-1]:
95 m = re.match('DRIVER\(\[([^\]]+)', line)
99 if (m and m.group(1).upper() > names['name'].upper()) or m is None:
100 out += tmpl(TMPL_AUTOCONF_DRIVER)
103 elif state == 'automake':
104 m = re.match('DRIVER2\(\[([^\]]+)', line)
108 submatch = re.match('DRIVER2\(\[([^\]]+)', line)
109 if active and submatch is None:
110 # we're past the DRIVER2 list
111 out += tmpl(TMPL_AUTOCONF_DRIVER2)
114 if (m and m.group(1) > 'HW_' + names['upper']):
115 out += tmpl(TMPL_AUTOCONF_DRIVER2)
119 raise Exception('No DRIVER entries found in configure.ac')
120 open(cacpath, 'w').write(out)
123 # add HAVE_HW_ extern and pointers to drivers.c
124 def do_drivers(gitdir):
125 path = gitdir + 'src/drivers.c'
126 source = open(path).read()
130 for line in source.split('\n')[:-1]:
131 m = re.match('#ifdef HAVE_HW_(.*)', line)
134 first_entry = m.group(1)
135 elif m.group(1) == first_entry:
136 # second time we see this, so we're past the externs
138 # tack driver on to the end of the list
139 out += tmpl(TMPL_DRIVERS_EXTERN)
141 if state == 'extern':
142 if m.group(1) > names['upper']:
143 out += tmpl(TMPL_DRIVERS_EXTERN)
145 elif state == 'pointer':
146 if m.group(1) > names['upper']:
147 out += tmpl(TMPL_DRIVERS_POINTER)
149 elif state == 'pointer' and not re.match('(\s*&|#endif|$)', line):
150 # we passed the last entry
151 out += tmpl(TMPL_DRIVERS_POINTER)
155 raise Exception('No "HAVE_HW_*" markers found in drivers.c' + state)
156 open(path, 'w').write(out)
159 # add HW_ entry to Makefile.am
160 def do_automake(gitdir):
161 path = gitdir + 'Makefile.am'
162 hwmake = open(path).read()
166 for line in hwmake.split('\n')[:-1]:
167 if state == 'copy' and re.match('if HW_(.*)$', line):
169 if state == 'drivers':
170 m = re.match('if HW_(.*)$', line)
172 drv_short = m.group(1)
173 if drv_short > names['upper']:
174 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
176 elif not re.match('(libsigrok_la_SOURCES|\s*src/hardware/|endif)', line):
177 print("[%s]" % line.strip())
178 # we passed the last entry
179 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
183 raise Exception('No "if HW_" markers found in Makefile.am')
184 open(path, 'w').write(out)
187 def do_driverskel(gitdir):
188 drvdir = gitdir + 'src/hardware/' + names['short']
190 open(drvdir + '/api.c', 'w').write(tmpl_file(FILE_DRV_API))
191 open(drvdir + '/protocol.c', 'w').write(tmpl_file(FILE_DRV_PROTOCOL))
192 open(drvdir + '/protocol.h', 'w').write(tmpl_file(FILE_DRV_PROTOCOL_H))
195 def make_patch(gitdir):
197 command('git add src/hardware/' + names['short'])
198 cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
199 cmd += 'configure.ac Makefile.am src/drivers.c src/hardware/' + names['short']
201 cmd = "git format-patch HEAD~1"
202 out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
204 raise Exception(err.decode())
205 patch = out.decode().strip()
206 shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
211 out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
213 raise Exception(err.decode())
216 def parse_gitconfig():
218 author = email = None
219 for line in open(os.environ['HOME'] + '/.gitconfig').readlines():
220 m = re.match('\s*(\w+)\s*=\s*(.*)\s*$', line)
222 key, value = m.groups()
231 if not author or not email:
232 print("Please put your name and email in ~/.gitconfig")
241 scriptdir = os.getcwd()
242 if scriptdir.split('/')[-2:] != ['sigrok-util', 'source']:
243 print("Please call this script from the 'source' directory.")
246 LIBSR = 'git://sigrok.org/libsigrok'
249 if len(sys.argv) < 2:
250 print("Usage: new-driver <name>")
253 author, email = parse_gitconfig()
254 name = ' '.join(sys.argv[1:])
257 'short': re.sub('[^a-z0-9]', '-', name.lower()),
258 'lib': re.sub('[^a-z0-9]', '_', name.lower()),
259 'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
260 'libupper': re.sub('[^A-Z0-9]', '', name.upper()),
261 'year': datetime.datetime.now().year,