]> sigrok.org Git - sigrok-util.git/blame - source/new-driver
new-driver: fix for libsigrok since dd5c48a6
[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
fe85502e 24from subprocess import Popen, PIPE, check_output
a65d66c0
BV
25import shutil
26import re
27import socket
28import datetime
29
fe85502e 30TMPL_AUTOCONF_DRIVER = "SR_DRIVER([${name}], [${short}])\n"
7d787983 31
d51b5323 32TMPL_HWMAKE_DRIVERLIB = """if HW_${upper}
68ec5073 33libsigrok_la_SOURCES += \\
6ebf3016
BV
34 src/hardware/${short}/protocol.h \\
35 src/hardware/${short}/protocol.c \\
36 src/hardware/${short}/api.c
d51b5323 37endif
d51b5323 38"""
a65d66c0
BV
39FILE_DRV_API = 'drv-api.c'
40FILE_DRV_PROTOCOL = 'drv-protocol.c'
41FILE_DRV_PROTOCOL_H = 'drv-protocol.h'
42
43def tmpl(template):
44 out = re.sub(r'\${([^}]+)}', lambda x: str(names[x.group(1)]), template)
45
46 return out
47
48
49def tmpl_file(filename):
50 template = open(TMPLDIR + '/' + filename).read()
51
52 return tmpl(template)
53
54
55def new_driver():
56 tmp = tempfile.mkdtemp()
57 try:
58 os.chdir(tmp)
1684b33d 59 process = Popen("git clone --depth=1 " + LIBSR, shell=True, stderr=PIPE)
617f4da0
AJ
60 out, err = process.communicate()
61 if process.returncode:
a65d66c0
BV
62 raise Exception(err.decode())
63 gitdir = tmp + '/libsigrok/'
3e61a9d8 64 do_autoconf(gitdir)
3e61a9d8 65 do_automake(gitdir)
a65d66c0
BV
66 do_driverskel(gitdir)
67 make_patch(gitdir)
68 except Exception as e:
69 print(e)
70 shutil.rmtree(tmp)
71
72
d0d6e169 73# add DRIVER and DRIVER2 entries to configure.ac
3e61a9d8 74def do_autoconf(gitdir):
a65d66c0
BV
75 cacpath = gitdir + 'configure.ac'
76 configure_ac = open(cacpath).read()
77
a65d66c0 78 out = ''
3e61a9d8
BV
79 state = 'driver'
80 active = False
a65d66c0 81 for line in configure_ac.split('\n')[:-1]:
3e61a9d8 82 if state == 'driver':
fe85502e 83 m = re.match(r'SR_DRIVER\(\[([^\]]+)', line)
a65d66c0 84 if m:
3e61a9d8
BV
85 active = True
86 if active:
87 if (m and m.group(1).upper() > names['name'].upper()) or m is None:
88 out += tmpl(TMPL_AUTOCONF_DRIVER)
3e61a9d8 89 state = 'done'
fe85502e 90 active = False
a65d66c0
BV
91 out += line + '\n'
92 if state != 'done':
fe85502e 93 raise Exception('No SR_DRIVER entries found in configure.ac')
3e61a9d8 94 open(cacpath, 'w').write(out)
a65d66c0 95
a65d66c0 96
3e61a9d8
BV
97# add HW_ entry to Makefile.am
98def do_automake(gitdir):
7d787983 99 path = gitdir + 'Makefile.am'
a65d66c0
BV
100 hwmake = open(path).read()
101
a65d66c0
BV
102 out = ''
103 state = 'copy'
104 for line in hwmake.split('\n')[:-1]:
fe85502e 105 if state == 'copy' and re.match(r'if\s+HW_\w+$', line):
3e61a9d8
BV
106 state = 'drivers'
107 if state == 'drivers':
fe85502e 108 m = re.match(r'if\s+HW_(\w+)$', line)
d51b5323
BV
109 if m:
110 drv_short = m.group(1)
111 if drv_short > names['upper']:
112 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
113 state = 'done'
fe85502e 114 elif not re.match(r'\s*libsigrok_la_SOURCES\b|\s*src/hardware/|endif\b', line):
3e61a9d8
BV
115 print("[%s]" % line.strip())
116 # we passed the last entry
117 out += tmpl(TMPL_HWMAKE_DRIVERLIB)
118 state = 'done'
a65d66c0 119 out += line + '\n'
7d787983 120 if state != 'done':
3e61a9d8
BV
121 raise Exception('No "if HW_" markers found in Makefile.am')
122 open(path, 'w').write(out)
a65d66c0
BV
123
124
125def do_driverskel(gitdir):
6ebf3016 126 drvdir = gitdir + 'src/hardware/' + names['short']
a65d66c0 127 os.mkdir(drvdir)
a65d66c0
BV
128 open(drvdir + '/api.c', 'w').write(tmpl_file(FILE_DRV_API))
129 open(drvdir + '/protocol.c', 'w').write(tmpl_file(FILE_DRV_PROTOCOL))
130 open(drvdir + '/protocol.h', 'w').write(tmpl_file(FILE_DRV_PROTOCOL_H))
131
132
133def make_patch(gitdir):
134 os.chdir(gitdir)
6ebf3016 135 command('git add src/hardware/' + names['short'])
0af91589 136 cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
466005f1 137 cmd += 'configure.ac Makefile.am src/hardware/' + names['short']
a65d66c0
BV
138 command(cmd)
139 cmd = "git format-patch HEAD~1"
140 out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
141 if err:
142 raise Exception(err.decode())
143 patch = out.decode().strip()
144 shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
145 print(patch)
146
147
148def command(cmd):
149 out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
150 if err:
151 raise Exception(err.decode())
152
153
154def parse_gitconfig():
fe85502e 155 author = email = None
0af91589 156 try:
fe85502e
DE
157 author = check_output(["git", "config", "user.name"]).decode().strip();
158 email = check_output(["git", "config", "user.email"]).decode().strip();
0af91589 159 except:
fe85502e 160 print("Please set your name and email in your git config")
0af91589 161 sys.exit()
0af91589 162 return author, email
a65d66c0
BV
163
164#
165# main
166#
167
168scriptdir = os.getcwd()
87c5b243
BV
169if scriptdir.split('/')[-2:] != ['sigrok-util', 'source']:
170 print("Please call this script from the 'source' directory.")
171 sys.exit(1)
172
173LIBSR = 'git://sigrok.org/libsigrok'
174TMPLDIR = scriptdir
a65d66c0
BV
175
176if len(sys.argv) < 2:
0af91589 177 print("Usage: new-driver <name>")
a65d66c0
BV
178 sys.exit()
179
180author, email = parse_gitconfig()
181name = ' '.join(sys.argv[1:])
182names = {
183 'name': name,
184 'short': re.sub('[^a-z0-9]', '-', name.lower()),
185 'lib': re.sub('[^a-z0-9]', '_', name.lower()),
186 'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
0af91589
UH
187 'year': datetime.datetime.now().year,
188 'author': author,
189 'email': email,
a65d66c0
BV
190}
191new_driver()
192