]> sigrok.org Git - sigrok-util.git/blobdiff - source/new-driver
newdriver: Drop obsolete checks and code chunks.
[sigrok-util.git] / source / new-driver
index 6e6977bad8a596774b9a4ce7d7f4dedff41745c4..14178d3241dfb5849abe4886aff646601444f6d1 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/python3
+#!/usr/bin/env python3
 ##
 ## This file is part of the sigrok-util project.
 ##
 import os
 import sys
 import tempfile
-from subprocess import Popen, PIPE
+from subprocess import Popen, PIPE, check_output
 import shutil
 import re
 import socket
 import datetime
 
-TMPL_AUTOCONF_AC_ARG_ENABLE = """\
-AC_ARG_ENABLE(${short}, AC_HELP_STRING([--enable-${short}],
-       [enable ${name} support [default=yes]]),
-       [HW_${upper}="$enableval"],
-       [HW_${upper}=$HW_ENABLED_DEFAULT])
-AM_CONDITIONAL(HW_${upper}, test x$HW_${upper} = xyes)
-if test "x$HW_${upper}" = "xyes"; then
-       AC_DEFINE(HAVE_HW_${upper}, 1, [${name} support])
-fi
+TMPL_AUTOCONF_DRIVER = "SR_DRIVER([{name}], [{short}])\n"
 
-"""
-TMPL_AUTOCONF_AC_CONFIG_FILES = "\t\t hardware/${short}/Makefile\n"
-TMPL_AUTOCONF_SUMMARY = 'echo "  - ${summary}"\n'
-TMPL_HWMAKE_SUBDIR = '\t${short}'
-TMPL_HWMAKE_DRIVERLIB = """if HW_${upper}
-libsigrokhardware_la_LIBADD += ${short}/libsigrok_hw_${lib}.la
-endif
+TMPL_FILES = ('protocol.h', 'protocol.c', 'api.c')
 
-"""
-TMPL_HWDRIVER_EXTERN = """\
-#ifdef HAVE_HW_${upper}
-extern SR_PRIV struct sr_dev_driver ${lib}_driver_info;
-#endif
-"""
-TMPL_HWDRIVER_DIPTR = """\
-#ifdef HAVE_HW_${upper}
-       &${lib}_driver_info,
-#endif
-"""
-FILE_DRV_MAKEFILE = 'drv-Makefile.am'
-FILE_DRV_API = 'drv-api.c'
-FILE_DRV_PROTOCOL = 'drv-protocol.c'
-FILE_DRV_PROTOCOL_H = 'drv-protocol.h'
+TMPL_HWMAKE_DRIVERLIB = """if HW_{upper}
+src_libdrivers_la_SOURCES +="""
+for tmpl_file in TMPL_FILES:
+    TMPL_HWMAKE_DRIVERLIB += " \\\n\tsrc/hardware/{short}/" + tmpl_file
+TMPL_HWMAKE_DRIVERLIB += "\nendif\n"
 
-def tmpl(template):
-    out = re.sub(r'\${([^}]+)}', lambda x: str(names[x.group(1)]), template)
 
-    return out
+def tmpl(template, names):
+    return template.format(**names)
 
 
-def tmpl_file(filename):
-    template = open(TMPLDIR + '/' + filename).read()
+def tmpl_file(filename, tmpldir, names):
+    with open(os.path.join(tmpldir, filename)) as template:
+        return tmpl(template.read(), names)
 
-    return tmpl(template)
 
-
-def new_driver():
+def new_driver(srcurl, tmpldir, names):
     tmp = tempfile.mkdtemp()
     try:
-        os.chdir(tmp)
-        out, err = Popen("git clone " + LIBSR, shell=True, stderr=PIPE).communicate()
-        if err:
+        process = Popen(['git', 'clone', '--depth=1', srcurl, tmp],
+                        stdout=PIPE, stderr=PIPE)
+        out, err = process.communicate()
+        if process.returncode:
             raise Exception(err.decode())
-        gitdir = tmp + '/libsigrok/'
-        do_configure_ac(gitdir)
-        do_hwdriver(gitdir)
-        do_hwmake(gitdir)
-        do_driverskel(gitdir)
-        make_patch(gitdir)
+        gitdir = tmp
+        do_autoconf(gitdir, names)
+        do_automake(gitdir, names)
+        do_driverskel(gitdir, tmpldir, names)
+        make_patch(gitdir, names)
     except Exception as e:
+        raise
         print(e)
-    shutil.rmtree(tmp)
+    finally:
+        shutil.rmtree(tmp)
 
 
-def do_configure_ac(gitdir):
-    cacpath = gitdir + 'configure.ac'
+# add DRIVER entry to configure.ac
+def do_autoconf(gitdir, names):
+    cacpath = os.path.join(gitdir, 'configure.ac')
     configure_ac = open(cacpath).read()
 
-    # add AC_ARG_ENABLE option
-    out = ''
-    state = 'copy'
-    for line in configure_ac.split('\n')[:-1]:
-        if state == 'copy':
-            if line == "# Hardware support '--enable' options.":
-                state = 'acarg'
-        elif state == 'acarg':
-            m = re.match('AC_ARG_ENABLE\(([^,]+)', line)
-            if m:
-                drv_short = m.group(1)
-                if drv_short.lower() > names['short']:
-                    out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
-                    state = 'done'
-            if line == '# Checks for libraries.':
-                # new one at the end
-                out += tmpl(TMPL_AUTOCONF_AC_ARG_ENABLE)
-                state = 'done'
-        out += line + '\n'
-    if state != 'done':
-        raise Exception('AC_ARG_ENABLE markers not found in configure.ac')
-    configure_ac = out
-
-    # add driver Makefile to AC_CONFIG_FILES
-    out = ''
-    state = 'copy'
-    for line in configure_ac.split('\n')[:-1]:
-        if state == 'copy':
-            if line.find("AC_CONFIG_FILES([Makefile") > -1:
-                state = 'acconf'
-        elif state == 'acconf':
-            m = re.match('\t\t hardware/([^/]+)/Makefile', line)
-            if m:
-                drv_short = m.group(1)
-                if drv_short.lower() > names['short']:
-                    out += tmpl(TMPL_AUTOCONF_AC_CONFIG_FILES)
-                    state = 'done'
-            else:
-                # new one at the end
-                out += tmpl(TMPL_AUTOCONF_AC_CONFIG_FILES)
-                state = 'done'
-        out += line + '\n'
-    if state != 'done':
-        raise Exception('AC_CONFIG_FILES marker not found in configure.ac')
-    configure_ac = out
-
-    # add summary line
     out = ''
-    state = 'copy'
-    names['summary'] = "%s%s $HW_%s" % (names['short'],
-            '.' * (32 - len(names['name'])), names['upper'])
+    state = 'driver'
+    active = False
     for line in configure_ac.split('\n')[:-1]:
-        if state == 'copy':
-            if line.find('Enabled hardware drivers') > -1:
-                state = 'echo'
-        elif state == 'echo':
-            m = re.match('echo "  - ([^\.]+)', line)
+        if state == 'driver':
+            m = re.match(r'SR_DRIVER\(\[([^\]]+)', line)
             if m:
-                drv_short = m.group(1)
-                if drv_short.lower() > names['name'].lower():
-                    out += tmpl(TMPL_AUTOCONF_SUMMARY)
+                active = True
+            if active:
+                if (m and m.group(1).upper() > names['name'].upper()) or m is None:
+                    out += tmpl(TMPL_AUTOCONF_DRIVER, names)
                     state = 'done'
-            else:
-                # new one at the end
-                out += tmpl(TMPL_AUTOCONF_SUMMARY)
-                state = 'done'
-        out += line + '\n'
-    if state != 'done':
-        raise Exception('summary marker not found in configure.ac')
-    configure_ac = out
-
-    open(cacpath, 'w').write(configure_ac)
-
-
-def do_hwdriver(gitdir):
-    path = gitdir + 'hwdriver.c'
-    hwdriver = open(path).read()
-    # add HAVE_HW_thing extern and pointers
-    out = ''
-    state = 'copy'
-    for line in hwdriver.split('\n')[:-1]:
-        if state == 'copy':
-            if line.find('/** @cond PRIVATE */') == 0:
-                state = 'extern'
-            elif line.find('static struct sr_dev_driver *drivers_list') == 0:
-                state = 'diptr'
-        elif state in ('extern', 'diptr'):
-            if state == 'extern':
-                entry = tmpl(TMPL_HWDRIVER_EXTERN)
-                next_state = 'copy'
-            else:
-                entry = tmpl(TMPL_HWDRIVER_DIPTR)
-                next_state = 'done'
-            m = re.match('#ifdef HAVE_.._(.*)', line)
-            if m:
-                drv = m.group(1)
-                if drv > names['upper']:
-                    out += entry
-                    state = next_state
-            elif not re.match('(extern|\t&|#endif)', line):
-                # new one at the end
-                out += entry
-                state = next_state
+                    active = False
         out += line + '\n'
     if state != 'done':
-        raise Exception('HAVE_* markers not found in hwdriver.c')
-    hwdriver = out
+        raise Exception('No SR_DRIVER entries found in configure.ac')
+    open(cacpath, 'w').write(out)
 
-    open(path, 'w').write(hwdriver)
 
-
-def do_hwmake(gitdir):
-    path = gitdir + 'hardware/Makefile.am'
+# add HW_ entry to Makefile.am
+def do_automake(gitdir, names):
+    path = os.path.join(gitdir, 'Makefile.am')
     hwmake = open(path).read()
 
-    # add SUBDIRS entry
     out = ''
     state = 'copy'
     for line in hwmake.split('\n')[:-1]:
-        if state == 'copy':
-            if line.find('SUBDIRS =') > -1:
-                state = 'subdirs'
-        elif state == 'subdirs':
-            m = re.match('\t([^ \\\]+\s*\\\)', line)
-            if m:
-                drv_short = m.group(1)
-                if drv_short.lower() > names['short']:
-                    out += tmpl(TMPL_HWMAKE_SUBDIR) + ' \\\n'
-                    state = 'driverlib'
-            else:
-                out += tmpl(TMPL_HWMAKE_SUBDIR) + ' \\\n'
-                state = 'driverlib'
-        elif state == 'driverlib':
-            m = re.match('if [A-Z]{2}_(.*)$', line)
+        if state == 'copy' and re.match(r'if\s+HW_\w+$', line):
+            state = 'drivers'
+        if state == 'drivers':
+            m = re.match(r'if\s+HW_(\w+)$', line)
             if m:
                 drv_short = m.group(1)
                 if drv_short > names['upper']:
-                    out += tmpl(TMPL_HWMAKE_DRIVERLIB)
+                    out += tmpl(TMPL_HWMAKE_DRIVERLIB, names)
                     state = 'done'
+            elif not re.match(r'\s*src_libdrivers_la_SOURCES\b|\s*src/hardware/|endif\b', line):
+                print("[%s]" % line.strip())
+                # we passed the last entry
+                out += tmpl(TMPL_HWMAKE_DRIVERLIB, names)
+                state = 'done'
         out += line + '\n'
-    if state == 'driverlib':
-        # reached end of file, add it in here
-        out += tmpl(TMPL_HWMAKE_DRIVERLIB).strip()
-    elif state != 'done':
-        raise Exception('markers not found in hardware/Makefile.am')
-    hwmake = out
-
-    open(path, 'w').write(hwmake)
+    if state != 'done':
+        raise Exception('No "if HW_" markers found in Makefile.am')
+    open(path, 'w').write(out)
 
 
-def do_driverskel(gitdir):
-    drvdir = gitdir + 'hardware/' + names['short']
+def do_driverskel(gitdir, tmpldir, names):
+    drvdir = os.path.join(gitdir, 'src', 'hardware', names['short'])
     os.mkdir(drvdir)
-    open(drvdir + '/Makefile.am', 'w').write(tmpl_file(FILE_DRV_MAKEFILE))
-    open(drvdir + '/api.c', 'w').write(tmpl_file(FILE_DRV_API))
-    open(drvdir + '/protocol.c', 'w').write(tmpl_file(FILE_DRV_PROTOCOL))
-    open(drvdir + '/protocol.h', 'w').write(tmpl_file(FILE_DRV_PROTOCOL_H))
+    for fname in TMPL_FILES:
+        with open(os.path.join(drvdir, fname), 'w') as outf:
+            outf.write(tmpl_file('drv-{0}'.format(fname), tmpldir, names))
 
 
-def make_patch(gitdir):
-    os.chdir(gitdir)
-    command('git add hardware/' + names['short'])
-    cmd = 'git commit -m "%s: Initial driver skeleton." ' % names['short']
-    cmd += 'configure.ac hwdriver.c hardware/Makefile.am hardware/' + names['short']
-    command(cmd)
-    cmd = "git format-patch HEAD~1"
-    out, err = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
-    if err:
-        raise Exception(err.decode())
-    patch = out.decode().strip()
-    shutil.move(gitdir + '/' + patch, scriptdir + '/' + patch)
-    print(patch)
+def make_patch(gitdir, names):
+    cwd = os.getcwd()
+    try:
+        os.chdir(gitdir)
+        command(['git', 'add', os.path.join('src', 'hardware', names['short'])])
+        cmd = ['git', 'commit',
+               '-m', '%s: Initial driver skeleton.' % names['short'],
+               'configure.ac', 'Makefile.am',
+               os.path.join('src', 'hardware', names['short'])]
+        command(cmd)
+        cmd = ['git', 'format-patch', 'HEAD~1']
+        out, err = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
+        if err:
+            raise Exception(err.decode())
+        patch = out.decode().strip()
+        shutil.move(os.path.join(gitdir, patch), cwd)
+        print("Patch {0} has been generated in {1}".format(patch, cwd))
+    finally:
+        os.chdir(cwd)
 
 
 def command(cmd):
-    out, err = Popen(cmd, shell=True, stderr=PIPE).communicate()
+    out, err = Popen(cmd, stderr=PIPE).communicate()
     if err:
         raise Exception(err.decode())
 
 
 def parse_gitconfig():
     try:
-        author = email = None
-        for line in open(os.environ['HOME'] + '/.gitconfig').readlines():
-            m = re.match('\s*(\w+)\s*=\s*(.*)\s*$', line)
-            if m:
-                key, value = m.groups()
-                if key == 'name':
-                    author = value
-                elif key == 'email':
-                    email = value
-                if author and email:
-                    break
+        author = check_output(["git", "config", "user.name"]).decode().strip();
     except:
-        pass
-    if not author or not email:
-        print("Please put your name and email in ~/.gitconfig")
-        sys.exit()
-
+        author = None
+    try:
+        email = check_output(["git", "config", "user.email"]).decode().strip();
+    except:
+        email = None
     return author, email
 
+
 #
 # main
 #
 
-scriptdir = os.getcwd()
-if scriptdir.split('/')[-2:] != ['sigrok-util', 'source']:
-       print("Please call this script from the 'source' directory.")
-       sys.exit(1)
-
-LIBSR = 'git://sigrok.org/libsigrok'
-TMPLDIR = scriptdir
-
-if len(sys.argv) < 2:
-    print("Usage: new-driver <name>")
-    sys.exit()
-
-author, email = parse_gitconfig()
-name = ' '.join(sys.argv[1:])
-names = {
-    'name': name,
-    'short': re.sub('[^a-z0-9]', '-', name.lower()),
-    'lib': re.sub('[^a-z0-9]', '_', name.lower()),
-    'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
-    'libupper': re.sub('[^A-Z0-9]', '', name.upper()),
-    'year': datetime.datetime.now().year,
-    'author': author,
-    'email': email,
-}
-new_driver()
+if __name__ == '__main__':
+    from argparse import ArgumentParser
+
+    defaulturl = 'git://sigrok.org/libsigrok'
+    defaultdir = os.path.abspath(os.path.dirname(__file__))
+    author, email = parse_gitconfig()
+
+    parser = ArgumentParser(description='Bootstrap a new sigrok hardware driver')
+    parser.add_argument('name', nargs='*', default=[], help='new driver name')
+    parser.add_argument('--giturl', default=defaulturl,
+                        help='URL of the libsigrok git repository '
+                        '(defaults to {0})'.format(defaulturl))
+    parser.add_argument('--tmpl-dir', default=defaultdir,
+                        help='Directory in which the templates are stored '
+                        '(defaults to {0})'.format(defaultdir))
+    parser.add_argument('--author', default=author, required=not author,
+                        help='User name to write the Copyright lines')
+    parser.add_argument('--email', default=email, required=not email,
+                        help='Email address to write the Copyright lines')
+    opts = parser.parse_args()
+
+    if not opts.author or not opts.email:
+        parser.error('Please provide your username and email address, '
+                     'or set your git configuration up.')
+    name = ' '.join(opts.name)
+    if not name:
+        parser.error('Please provide a driver name.')
+    names = {
+        'name': name,
+        'short': re.sub('[^a-z0-9]', '-', name.lower()),
+        'lib': re.sub('[^a-z0-9]', '_', name.lower()),
+        'upper': re.sub('[^A-Z0-9]', '_', name.upper()),
+        'year': datetime.datetime.now().year,
+        'author': opts.author,
+        'email': opts.email,
+    }
+    new_driver(opts.giturl, opts.tmpl_dir, names)