modhelp.py 5.6 KB
Newer Older
1
#!/usr/bin/env python
2 3 4

# Module helper script.

Paul Eggert's avatar
Paul Eggert committed
5
# Copyright 2015-2019 Free Software Foundation, Inc.
6 7 8 9 10 11 12 13 14 15 16 17 18 19

# This file is part of GNU Emacs.

# GNU Emacs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# GNU Emacs is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
20
# along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
import os
import string
import subprocess as sp
import argparse
import re

EMACS = os.path.join('..', 'src', 'emacs')

def find_modules():
    modpaths = []
    for (dirname, dirs, files) in os.walk('.'):
        if 'Makefile' in files:
            modpaths.append(dirname)
    return modpaths

def cmd_test(args):
    mods = args.module
    if not mods:
        mods = find_modules()

    make_cmd = ['make']
    if args.force:
        make_cmd.append('-B')

    failed = []
    for m in mods:
48 49
        print('[*] %s: ------- start -------' % m)
        print('[*] %s: running make' % m)
50 51
        r = sp.call(make_cmd, cwd=m)
        if r != 0:
52
            print('[E] %s: make failed' % m)
53 54 55
            failed += [m]
            continue

56
        print('[*] %s: running test' % m)
57 58
        testpath = os.path.join(m, 'test.el')
        if os.path.isfile(testpath):
59 60
            emacs_cmd = [EMACS, '-batch', '-L', '.', '-l', 'ert',
                         '-l', testpath, '-f', 'ert-run-tests-batch-and-exit']
61
            print(' '.join(emacs_cmd))
62 63
            r = sp.call(emacs_cmd)
            if r != 0:
64
                print('[E] %s: test failed' % m)
65 66 67
                failed += [m]
                continue
        else:
68
            print('[W] %s: no test to run' % m)
69

70
    print('\n[*] %d/%d MODULES OK' % (len(mods)-len(failed), len(mods)))
71
    for m in failed:
72
        print('\tfailed: %s' % m)
73 74 75 76 77 78 79 80 81 82 83

def to_lisp_sym(sym):
    sym = re.sub('[_ ]', '-', sym)
    return sym

def to_c_sym(sym):
    sym = re.sub('[- ]', '_', sym)
    return sym

def cmd_init(args):
    if os.path.exists(args.module):
84
        print("%s: file/dir '%s' already exists" % (__file__, args.module))
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        return

    os.mkdir(args.module)

    template_vars = {
        'module': args.module,
        'func': args.fun,
        'c_file': '%s.c' % args.module,
        'c_func': 'F%s_%s' % (to_c_sym(args.module), to_c_sym(args.fun)),
        'lisp_func': '%s-%s' % (args.module,  to_lisp_sym(args.fun)),
    }

    for path, t in TEMPLATES.items():
        if isinstance(path, string.Template):
            path = path.substitute(template_vars)
        path = os.path.join(args.module, path)
101
        print("writing %s..." % path)
102 103
        with open(path, "w+") as f:
            f.write(t.substitute(template_vars))
104
    print("done! you can run %s test %s" % (__file__, args.module))
105 106 107 108 109 110 111 112 113 114


def main():
    # path always written relative to this file
    os.chdir(os.path.dirname(os.path.realpath(__file__)))

    mainp = argparse.ArgumentParser()
    subp = mainp.add_subparsers()

    testp = subp.add_parser('test', help='run tests')
115 116 117 118
    testp.add_argument('-f', '--force', action='store_true',
                       help='force regeneration (make -B)')
    testp.add_argument('module', nargs='*',
                       help='path to module to test (default all)')
119 120 121 122
    testp.set_defaults(func=cmd_test)

    initp = subp.add_parser('init', help='create a test module from a template')
    initp.add_argument('module', help='name of the new module')
123
    initp.add_argument('-f', '--fun', default='fun',
Paul Eggert's avatar
Paul Eggert committed
124
                       help='override name of the default function')
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    initp.set_defaults(func=cmd_init)

    args = mainp.parse_args()
    args.func(args)


# double the $ to escape python template syntax
TEMPLATES = {
    'Makefile': string.Template('''
ROOT = ../..

CC      = gcc
LD      = gcc
CFLAGS  = -ggdb3 -Wall
LDFLAGS =

all: ${module}.so ${module}.doc

%.so: %.o
	$$(LD) -shared $$(LDFLAGS) -o $$@ $$<

%.o: %.c
	$$(CC) $$(CFLAGS) -I$$(ROOT)/src -fPIC -c $$<

'''),

    string.Template('${c_file}'): string.Template('''
152
#include <emacs-module.h>
153 154 155

int plugin_is_GPL_compatible;

156
static emacs_value
157
${c_func} (emacs_env *env, ptrdiff_t nargs, emacs_value args[], void *data)
158 159 160 161
{
  return env->intern (env, "t");
}

162 163 164
/* Bind NAME to FUN.  */
static void
bind_function (emacs_env *env, const char *name, emacs_value Sfun)
165 166 167 168 169 170 171 172
{
  emacs_value Qfset = env->intern (env, "fset");
  emacs_value Qsym = env->intern (env, name);
  emacs_value args[] = { Qsym, Sfun };

  env->funcall (env, Qfset, 2, args);
}

173 174 175
/* Provide FEATURE to Emacs.  */
static void
provide (emacs_env *env, const char *feature)
176 177 178 179 180 181 182 183
{
  emacs_value Qfeat = env->intern (env, feature);
  emacs_value Qprovide = env->intern (env, "provide");
  emacs_value args[] = { Qfeat };

  env->funcall (env, Qprovide, 1, args);
}

184 185
int
emacs_module_init (struct emacs_runtime *ert)
186 187
{
  emacs_env *env = ert->get_environment (ert);
188 189
  bind_function (env, "${lisp_func}",
                 env->make_function (env, 1, 1, ${c_func}, "doc", NULL));
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  provide (env, "${module}");
  return 0;
}
'''),
    'test.el': string.Template('''
(require 'ert)
(require 'module-test-common)

;; #$$ works when loading, buffer-file-name when evaluating from emacs
(module-load (module-path (or #$$ (expand-file-name (buffer-file-name)))))

(ert-deftest ${lisp_func}-test ()
  (should (eq (${lisp_func} 42) t)))
''')
}

if __name__ == '__main__':
    main()