summaryrefslogtreecommitdiff
path: root/rpmlint
blob: d49c282b4e63b28a0d36ca804eead181c63c7d33 (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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#!/usr/bin/python -ttOu
# -*- coding: utf-8 -*-
#############################################################################
# File          : rpmlint
# Package       : rpmlint
# Author        : Frederic Lepied
# Created on    : Mon Sep 27 19:20:18 1999
# Version       : $Id: rpmlint 1870 2011-06-18 09:19:24Z scop $
# Purpose       : main entry point: process options, load the checks and run
#                 the checks.
#############################################################################

import getopt
import glob
import imp
import locale
import os
import re
import stat
import sys
import tempfile

# 1 instead of 0 here because we want the script dir to be looked up first,
# e.g. for in-place from tarball or SCM checkout
sys.path.insert(1, '/usr/share/rpmlint')

# Do not import anything that initializes its global variables from
# Config at load time here (or anything that imports such a thing),
# that results in those variables initialized before config files are
# loaded which is too early - settings from config files won't take
# place for those variables.

from Filter import badnessScore, badnessThreshold, printAllReasons, \
     printDescriptions, printInfo, printed_messages, setRawOut
import AbstractCheck
import Config
import Pkg


_default_user_conf = '%s/rpmlint' % \
    (os.environ.get('XDG_CONFIG_HOME') or '~/.config')

# Print usage information
def usage(name):
    print ('''usage: %s [<options>] <rpm files|installed packages|specfiles|dirs>
  options:
\t[-i|--info]
\t[-I|--explain <messageid>]
\t[-c|--check <check>]
\t[-a|--all]
\t[-C|--checkdir <checkdir>]
\t[-h|--help]
\t[-v|--verbose]
\t[-E|--extractdir <dir>]
\t[-V|--version]
\t[-n|--noexception]
\t[   --rawout <file>]
\t[-f|--file <user config file to use instead of %s]
\t[-o|--option <key value>]''' \
        % (name, _default_user_conf))

# Print version information
def printVersion():
    print ('rpmlint version %s Copyright (C) 1999-2007 Frederic Lepied, Mandriva' % Config.__version__)

def loadCheck(name):
    '''Load a (check) module by its name, unless it is already loaded.'''
    # Avoid loading more than once (initialization costs)
    loaded = sys.modules.get(name)
    if loaded:
        return loaded
    (fobj, pathname, description) = imp.find_module(name)
    try:
        imp.load_module(name, fobj, pathname, description)
    finally:
        fobj.close()

#############################################################################
# main program
#############################################################################
def main():

    locale.setlocale(locale.LC_COLLATE, '')

    # Add check dirs to the front of load path
    sys.path[0:0] = Config.checkDirs()

    # Load all checks
    for c in Config.allChecks():
        loadCheck(c)

    packages_checked = 0
    specfiles_checked = 0
    do_spec_check = 'SpecCheck' in Config.allChecks()
    if do_spec_check:
        # See comments in "top level import section" for why this isn't
        # imported earlier.
        import SpecCheck

    try:
        # Loop over all file names given in arguments
        dirs = []
        for arg in args:
            pkgs = []
            isfile = False
            try:
                if arg == "-":
                    arg = "(standard input)"
                    # Short-circuit stdin spec file check
                    if do_spec_check:
                        stdin = sys.stdin.readlines()
                        if not stdin:
                            continue
                        pkg = Pkg.FakePkg(arg)
                        check = SpecCheck.SpecCheck()
                        check.verbose = verbose
                        check.check_spec(pkg, None, spec_lines=stdin)
                        pkg.cleanup()
                        specfiles_checked += 1
                    continue

                try:
                    st = os.stat(arg)
                    isfile = True
                    if stat.S_ISREG(st[stat.ST_MODE]):
                        if arg.endswith(".spec"):
                            if do_spec_check:
                                # Short-circuit spec file checks
                                pkg = Pkg.FakePkg(arg)
                                check = SpecCheck.SpecCheck()
                                check.verbose = verbose
                                check.check_spec(pkg, arg)
                                pkg.cleanup()
                                specfiles_checked += 1
                        elif "/" in arg or arg.endswith(".rpm") or \
                                arg.endswith(".spm"):
                            pkgs.append(Pkg.Pkg(arg, extract_dir))
                        else:
                            raise OSError

                    elif stat.S_ISDIR(st[stat.ST_MODE]):
                        dirs.append(arg)
                        continue
                    else:
                        raise OSError
                except OSError:
                    ipkgs = Pkg.getInstalledPkgs(arg)
                    if not ipkgs:
                        Pkg.warn(
                            '(none): E: no installed packages by name %s' % arg)
                    else:
                        ipkgs.sort(key = lambda x: locale.strxfrm(
                                x.header.sprintf("%{NAME}.%{ARCH}")))
                        pkgs.extend(ipkgs)
            except KeyboardInterrupt:
                if isfile:
                    arg = os.path.abspath(arg)
                Pkg.warn(
                    '(none): E: interrupted, exiting while reading %s' % arg)
                sys.exit(2)
            except Exception, e:
                if isfile:
                    arg = os.path.abspath(arg)
                Pkg.warn('(none): E: error while reading %s: %s' % (arg, e))
                pkgs = []
                continue

            for pkg in pkgs:
                runChecks(pkg)
                packages_checked += 1

        for dname in dirs:
            try:
                for path, dirs, files in os.walk(dname):
                    for fname in files:
                        fname = os.path.abspath(os.path.join(path, fname))
                        try:
                            if fname.endswith('.rpm') or \
                               fname.endswith('.spm'):
                                pkg = Pkg.Pkg(fname, extract_dir)
                                runChecks(pkg)
                                packages_checked += 1

                            elif do_spec_check and fname.endswith('.spec'):
                                pkg = Pkg.FakePkg(fname)
                                check = SpecCheck.SpecCheck()
                                check.verbose = verbose
                                check.check_spec(pkg, fname)
                                pkg.cleanup()
                                specfiles_checked += 1

                        except KeyboardInterrupt:
                            Pkg.warn('(none): E: interrupted, exiting while ' +
                                     'reading %s' % fname)
                            sys.exit(2)
                        except Exception, e:
                            Pkg.warn(
                                '(none): E: while reading %s: %s' % (fname, e))
                            continue
            except Exception, e:
                Pkg.warn(
                    '(none): E: error while reading dir %s: %s' % (dname, e))
                continue

        if printAllReasons():
            Pkg.warn('(none): E: badness %d exceeds threshold %d, aborting.' %
                     (badnessScore(), badnessThreshold()))
            sys.exit(66)

    finally:
        print "%d packages and %d specfiles checked; %d errors, %d warnings." \
              % (packages_checked, specfiles_checked,
                 printed_messages["E"], printed_messages["W"])

    if badnessThreshold() < 0 and printed_messages["E"] > 0:
        sys.exit(64)
    sys.exit(0)

def runChecks(pkg):

    try:
        if verbose:
            printInfo(pkg, 'checking')

        for name in Config.allChecks():
            check = AbstractCheck.AbstractCheck.known_checks.get(name)
            if check:
                check.verbose = verbose
                check.check(pkg)
            else:
                Pkg.warn('(none): W: unknown check %s, skipping' % name)
    finally:
        pkg.cleanup()

#############################################################################
#
#############################################################################

sys.argv[0] = os.path.basename(sys.argv[0])

# parse options
try:
    (opt, args) = getopt.getopt(sys.argv[1:],
                              'iI:c:C:hVvanE:f:o:',
                              ['info',
                               'explain=',
                               'check=',
                               'checkdir=',
                               'help',
                               'version',
                               'verbose',
                               'all',
                               'noexception',
                               'extractdir=',
                               'file=',
                               'option=',
                               'rawout=',
                               ])
except getopt.GetoptError, e:
    Pkg.warn("%s: %s" % (sys.argv[0], e))
    usage(sys.argv[0])
    sys.exit(1)

# process options
checkdir = '/usr/share/rpmlint'
checks = []
verbose = False
extract_dir = None
conf_file = _default_user_conf
if not os.path.exists(os.path.expanduser(conf_file)):
    # deprecated backwards compatibility with < 0.88
    conf_file = '~/.rpmlintrc'
info_error = set()

# load global config files
configs = glob.glob('/etc/rpmlint/*config')
configs.sort()

# Was rpmlint invoked as a prefixed variant?
m = re.match(r"(?P<prefix>[\w-]+)-rpmlint(\.py)?", sys.argv[0])
if m:
    # Okay, we're a prefixed variant. Look for the variant config.
    # If we find it, use it. If not, fallback to the default.
    prefix = m.group('prefix')
    if os.path.isfile('/usr/share/rpmlint/config.%s' % prefix):
        configs.insert(0, '/usr/share/rpmlint/config.%s' % prefix)
    else:
        configs.insert(0, '/usr/share/rpmlint/config')
else:
    configs.insert(0, '/usr/share/rpmlint/config')

for f in configs:
    try:
        execfile(f)
    except IOError:
        pass
    except Exception, E:
        Pkg.warn('(none): W: error loading %s, skipping: %s' % (f, E))
# pychecker fix
del f

config_overrides = {}

# process command line options
for o in opt:
    if o[0] in ('-c', '--check'):
        checks.append(o[1])
    elif o[0] in ('-i', '--info'):
        Config.info = True
    elif o[0] in ('-I', '--explain'):
        # split by comma for deprecated backwards compatibility with < 1.2
        info_error.update(o[1].split(','))
    elif o[0] in ('-h', '--help'):
        usage(sys.argv[0])
        sys.exit(0)
    elif o[0] in ('-C', '--checkdir'):
        Config.addCheckDir(o[1])
    elif o[0] in ('-v', '--verbose'):
        verbose = True
    elif o[0] in ('-V', '--version'):
        printVersion()
        sys.exit(0)
    elif o[0] in ('-E', '--extractdir'):
        extract_dir = o[1]
        Config.setOption('ExtractDir', extract_dir)
    elif o[0] in ('-n', '--noexception'):
        Config.no_exception = True
    elif o[0] in ('-a', '--all'):
        if '*' not in args:
            args.append('*')
    elif o[0] in ('-f', '--file'):
        conf_file = o[1]
    elif o[0] in ('-o', '--option'):
        kv = o[1].split(None, 1)
        if len(kv) == 1:
            config_overrides[kv[0]] = None
        else:
            config_overrides[kv[0]] = eval(kv[1])
    elif o[0] in ('--rawout',):
        setRawOut(o[1])

# load user config file
try:
    execfile(os.path.expanduser(conf_file))
except IOError:
    pass
except Exception,E:
    Pkg.warn('(none): W: error loading %s, skipping: %s' % (conf_file, E))

# apply config overrides
for key, value in config_overrides.items():
    Config.setOption(key, value)

if not extract_dir:
    extract_dir = Config.getOption('ExtractDir', tempfile.gettempdir())

if info_error:
    Config.info = True
    sys.path[0:0] = Config.checkDirs()
    for c in checks:
        Config.addCheck(c)
    for c in Config.allChecks():
        loadCheck(c)
    for e in sorted(info_error):
        print "%s:" % e
        printDescriptions(e)
    sys.exit(0)

# if no argument print usage
if not args:
    usage(sys.argv[0])
    sys.exit(1)

if __name__ == '__main__':
    if checks:
        Config.resetChecks()
        for check in checks:
            Config.addCheck(check)
    main()

# rpmlint ends here

# Local variables:
# indent-tabs-mode: nil
# py-indent-offset: 4
# End:
# ex: ts=4 sw=4 et