Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 278 lines (219 sloc) 7.988 kb
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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
import os, re, sys

# Cherokee Project:
# Error generation and check
#
# This script loads a error definition file, and generates .h and .c
# from it. It also checks whether all the errors are actually being
# used, look for undefined errors, and check that the number of
# parameters matches between the error definition and the source code.
#

SOURCE_DIRS = ['.', '../cget']

#
# Error reading
#
class CherokeeError:
    def __init__ (self, **kwargs):
        self.id = kwargs['id']
        self.title = kwargs['title']

        self.description = kwargs.get('desc', '').replace('\n',' ')
        self.url_admin = kwargs.get('admin', '')
        self.help = kwargs.get('help', [])
        self.debug = kwargs.get('debug', '')
        self.show_bt = kwargs.get('show_bt', True)

_errors = []

def e (error_id, title, **kwargs):
    global _errors

    # Check dup. errors
    for err in _errors:
        if error_id == err.id:
            raise ValueError, "ERROR: Duplicated error %s" %(error_id)

    # New error
    kwargs['id'] = error_id
    kwargs['title'] = title
    error = CherokeeError (**kwargs)
    _errors.append (error)


def read_errors():
    exec (open ("error_list.py", 'r').read())


def check_source_code (dirs):
    # Defined errors are unseed
    for def_e in _errors:
        def_e.__seen_in_grep = False

    # Grep the source code
    errors_seen = {}
    for d in dirs:
        for f in os.listdir(d):
            fullpath = os.path.join (d, f)
            if not fullpath.endswith('.c') or \
               not os.path.isfile(fullpath):
                continue

            # Check the source code
            content = open (fullpath, 'r').read()
            for e in re.findall (r'CHEROKEE_ERROR_([\w_]+)[ ,)]', content):
                errors_seen[e] = fullpath

                # Mark used object
                for def_e in _errors:
                    if e == def_e.id:
                        def_e.__seen_in_grep = True

    # Undefined errors in the source code
    error_found = False

    for s in errors_seen.keys():
        found = False
        for e in _errors:
            if s == e.id:
                found = True
                break
        if not found:
            print >> sys.stderr, "Undefined Error: CHEROKEE_ERROR_%s, used in %s" % (s, errors_seen[s])
            error_found = True

    # Unused errors in the definition file
    for def_e in _errors:
        if not def_e.__seen_in_grep:
            print >> sys.stderr, "Unused Error: CHEROKEE_ERROR_%s" % (def_e.id)
            error_found = True

    return error_found


def check_parameters (dirs):
    known_errors_params = {}
    source_errors_params = {}

    # Known
    for error in _errors:
        tmp = error.title + error.description + error.url_admin + error.debug
        tmp = tmp.replace('%%', '')
        known_errors_params [error.id] = tmp.count('%')

    # Source
    for d in dirs:
        for f in os.listdir(d):
            fullpath = os.path.join (d, f)
            if not fullpath.endswith('.c') or \
               not os.path.isfile(fullpath):
                continue

            # Extract the CHEROKEE_ERROR_*
            content = open (fullpath, 'r').read()

            matches_log = re.findall (r'LOG_[\w_]+ ?' +\
                                      r'\(CHEROKEE_ERROR_([\w_]+)[ ,\n\t\\]*' +\
                                      r'(.*?)\);', content, re.MULTILINE | re.DOTALL)

            matches_errno = re.findall (r'LOG_ERRNO[_S ]*' +\
                                        r'\(.+?,.+?,[ \n\t]*CHEROKEE_ERROR_([\w_]+)[ ,\n\t\\]*' +\
                                        r'(.*?)\);', content, re.MULTILINE | re.DOTALL)

            matches = matches_errno + matches_log
            for match in matches:
                error = match[0]
                params = match[1].strip()

                # Remove internal sub-parameters (function parameters)
                tmp = params
                while True:
                    internal_params = re.findall(r'(\(.*?\))', tmp)
                    if not internal_params:
                        break
                    for param in internal_params:
                        tmp = tmp.replace(param, '')

                params_num = len (filter (lambda x: len(x), tmp.split(',')))
                source_errors_params[error] = params_num

    # Compare both
    error_found = False

    for error in _errors:
        source_num = source_errors_params[error.id]
        known_num = known_errors_params[error.id]
        if source_num != known_num:
            print >> sys.stderr, "ERROR: Parameter number mismatch: %s (source %d, definition %d)" % (error.id, source_num, known_num)
            error_found = True

    return error_found

#
# File generation
#

HEADER = """/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/* Cherokee
*
* Authors:
* Alvaro Lopez Ortega <alvaro@alobbs.com>
*
* Copyright (C) 2001-2010 Alvaro Lopez Ortega
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/

/* NOTE: File automatically generated (by error_list.py). */

"""

def generate_C_defines ():
    txt = ''
    max_len = max([len(e.id) for e in _errors])

    for num in range(len(_errors)):
        err = _errors[num]
        pad = " " * (max_len - len(err.id))
        txt += '#define CHEROKEE_ERROR_%s %s %d\n' %(err.id.upper(), pad, num)

    return txt

def generate_C_errors ():
    txt = ''
    txt += 'static const cherokee_error_t __cherokee_errors[] =\n'
    txt += '{\n'
    for num in range(len(_errors)):
        err = _errors[num]

        txt += ' { % 3d, "%s", ' %(num, err.title)

        if err.description:
            txt += '"%s", ' % (err.description)
        else:
            txt += 'NULL, '

        if err.url_admin:
            txt += '"%s", ' % (err.url_admin)
        else:
            txt += 'NULL, '

        if err.debug:
            txt += '"%s", ' % (err.debug)
        else:
            txt += 'NULL, '

        txt += ('false', 'true')[err.show_bt]

        txt += ' },\n'
    txt += ' { -1, NULL, NULL, NULL, NULL, true }\n'
    txt += '};\n'
    return txt


def main():
    # Check parameters
    error = False

    do_defines = '--defines' in sys.argv
    do_errors = '--errors' in sys.argv
    dont_test = '--skip-tests' in sys.argv

    if len(sys.argv) >= 1:
        file = sys.argv[-1]
        if file.startswith ('-'):
            error = True
        if not do_defines and not do_errors:
            error = True
    else:
        error = True

    if error:
        print "USAGE:"
        print
        print " * Create the definitions file:"
        print " %s [--skip-tests] --defines output_file" %(sys.argv[0])
        print
        print " * Create the error list file:"
        print " %s [--skip-tests] --errors output_file" %(sys.argv[0])
        print
        sys.exit(1)

    # Perform
    read_errors()

    if not dont_test:
        error = check_source_code (SOURCE_DIRS)
        error |= check_parameters (SOURCE_DIRS)
        if error:
            sys.exit(1)

    if do_defines:
        txt = HEADER
        txt += generate_C_defines()
        open (file, 'w+').write(txt)

    if do_errors:
        txt = HEADER
        txt += generate_C_errors()
        open (file, 'w+').write(txt)


if __name__ == '__main__':
    main()
Something went wrong with that request. Please try again.