summaryrefslogtreecommitdiff
path: root/modules/modhelp.py
blob: 3ed75dbf6284c778e80aba3a6d3f499ac3c9e5a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/usr/bin/env python

# Module helper script.

# Copyright 2015-2023 Free Software Foundation, Inc.

# 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
# along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

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:
        print('[*] %s: ------- start -------' % m)
        print('[*] %s: running make' % m)
        r = sp.call(make_cmd, cwd=m)
        if r != 0:
            print('[E] %s: make failed' % m)
            failed += [m]
            continue

        print('[*] %s: running test' % m)
        testpath = os.path.join(m, 'test.el')
        if os.path.isfile(testpath):
            emacs_cmd = [EMACS, '-batch', '-L', '.', '-l', 'ert',
                         '-l', testpath, '-f', 'ert-run-tests-batch-and-exit']
            print(' '.join(emacs_cmd))
            r = sp.call(emacs_cmd)
            if r != 0:
                print('[E] %s: test failed' % m)
                failed += [m]
                continue
        else:
            print('[W] %s: no test to run' % m)

    print('\n[*] %d/%d MODULES OK' % (len(mods)-len(failed), len(mods)))
    for m in failed:
        print('\tfailed: %s' % m)

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):
        print("%s: file/dir '%s' already exists" % (__file__, args.module))
        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)
        print("writing %s..." % path)
        with open(path, "w+") as f:
            f.write(t.substitute(template_vars))
    print("done! you can run %s test %s" % (__file__, args.module))


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')
    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)')
    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')
    initp.add_argument('-f', '--fun', default='fun',
                       help='override name of the default function')
    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('''
#include <emacs-module.h>

int plugin_is_GPL_compatible;

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

/* Bind NAME to FUN.  */
static void
bind_function (emacs_env *env, const char *name, emacs_value Sfun)
{
  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);
}

/* Provide FEATURE to Emacs.  */
static void
provide (emacs_env *env, const char *feature)
{
  emacs_value Qfeat = env->intern (env, feature);
  emacs_value Qprovide = env->intern (env, "provide");
  emacs_value args[] = { Qfeat };

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

int
emacs_module_init (struct emacs_runtime *ert)
{
  emacs_env *env = ert->get_environment (ert);
  bind_function (env, "${lisp_func}",
                 env->make_function (env, 1, 1, ${c_func}, "doc", NULL));
  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()