This file is indexed.

/usr/share/pyshared/pocketlint/contrib/cssccc.py is in python-pocket-lint 0.5.31-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
'''
This code is in the public domain.

Check CSS code for some common coding conventions.
The code must be in a valid CSS format.
It is recommend to first parse it using cssutils.
It is also recommend to check it with pocket-lint for things like trailing
spaces or tab characters.

If a comment is on the whole line, it will consume the whole line like it
was not there.
If a comment is inside a line it will only consume its own content.

Bases on Stoyan Stefanov's http://www.phpied.com/css-coding-conventions/

'@media' rule is not supported.
    @media print {
      html {
        background: #fff;
        color: #000;
      }
      body {
        padding: 1in;
        border: 0.5pt solid #666;
      }
    }

The following at-rules are supported:
 * keyword / text at-rules
  * @charset "ISO-8859-15";
  * @import url(/css/screen.css) screen, projection;
  * @namespace foo "http://example.com/ns/foo";
 * keybord / block rules
  * @page { block; }
  * @font-face { block; }


TODO:
 * add warning for using px for fonts.
 * add Unicode support.
 * add AtRule checks
 * add support for TAB as a separator / identation.
 * add support for @media
'''
from __future__ import with_statement

__version__ = '0.1.1'

import sys

SELECTOR_SEPARATOR = ','
DECLARATION_SEPARATOR = ';'
PROPERTY_SEPARATOR = ':'
COMMENT_START = r'/*'
COMMENT_END = r'*/'
AT_TEXT_RULES = ['import', 'charset', 'namespace']
AT_BLOCK_RULES = ['page', 'font-face']
# If you want
# selector,
# selector2
# {
#     property:
# }
#IGNORED_MESSAGES = ['I013', 'I014']

# If you want
# selector,
# selector {
#     property:
# }
#IGNORED_MESSAGES = ['I005', 'I014']

# If you want
# selector,
# selector2 {
#     property:
#     }
IGNORED_MESSAGES = ['I005', 'I006']


class CSSRule(object):
    '''A CSS rule.'''

    def check(self):
        '''Check the rule.'''
        raise AssertionError('Method not implemtned.')


class CSSAtRule(object):
    '''A CSS @rule.'''

    type = object()

    def __init__(self, identifier, keyword, log, text=None, block=None):
        self.identifier = identifier
        self.keyword = keyword
        self.text = text
        self.block = block
        self.log = log

    def check(self):
        '''Check the rule.'''


class CSSRuleSet(object):
    '''A CSS rule_set.'''

    type = object()

    def __init__(self, selector, declarations, log):
        self.selector = selector
        self.declarations = declarations
        self.log = log

    def __str__(self):
        return '%s{%s}' % (str(self.selector), str(self.declarations))

    def __repr__(self):
        return '%d:%s{%s}' % (
            self.selector.start_line,
            str(self.selector),
            str(self.declarations),
            )

    def check(self):
        '''Check the rule set.'''
        self.checkSelector()
        self.checkDeclarations()

    def checkSelector(self):
        '''Check rule-set selector.'''
        start_line = self.selector.getStartLine()
        selectors = self.selector.text.split(SELECTOR_SEPARATOR)
        offset = 0
        last_selector = selectors[-1]
        first_selector = selectors[0]
        rest_selectors = selectors[1:]

        if first_selector.startswith('\n\n\n'):
            self.log(start_line, 'I002', 'To many newlines before selectors.')
        elif first_selector.startswith('\n\n'):
            pass
        elif start_line > 2:
            self.log(start_line, 'I003', 'To few newlines before selectors.')
        else:
            pass

        for selector in rest_selectors:
            if not selector.startswith('\n'):
                self.log(
                    start_line + offset,
                    'I004',
                    'Selector must be on a new line.')
            offset += selector.count('\n')

        if not last_selector.endswith('\n'):
            self.log(
                start_line + offset,
                'I005',
                'No newline after last selector.')

        if not (last_selector[-2] != ' ' and last_selector[-1] == (' ')):
            self.log(
                start_line + offset,
                'I013',
                'Last selector must be followed by " {".')

    def checkDeclarations(self):
        '''Check rule-set declarations.'''
        start_line = self.declarations.getStartLine()
        declarations = self.declarations.text.split(DECLARATION_SEPARATOR)
        offset = 0

        # Check all declarations except last as this is the new line.
        first_declaration = True
        for declaration in declarations[:-1]:
            if not declaration.startswith('\n'):
                self.log(
                    start_line + offset,
                    'I007',
                    'Each declarations should start on a new line.',
                    )
            elif (not declaration.startswith('\n    ') or
                declaration[5] == ' '):
                self.log(
                    start_line + offset,
                    'I008',
                    'Each declaration must be indented with 4 spaces.',
                    )

            parts = declaration.split(PROPERTY_SEPARATOR)
            if len(parts) != 2:
                self.log(
                    start_line + offset,
                    'I009',
                    'Wrong separator on property: value pair.',
                    )
            else:
                prop, value = parts
                if prop.endswith(' '):
                    self.log(
                        start_line + offset,
                        'I010',
                        'Whitespace before ":".',
                        )
                if not (value.startswith(' ') or value.startswith('\n')):
                    self.log(
                        start_line + offset,
                        'I011',
                        'Missing whitespace after ":".',
                        )
                elif value.startswith('  '):
                    self.log(
                        start_line + offset,
                        'I012',
                        'Multiple whitespaces after ":".',
                        )
            if first_declaration:
                first_declaration = False
            else:
                offset += declaration.count('\n')

        last_declaration = declarations[-1]
        offset += last_declaration.count('\n')
        if last_declaration != '\n':
            self.log(
                start_line + offset,
                'I006',
                'Rule declarations should end with a single new line.',
                )
        if last_declaration != '\n    ':
            self.log(
                start_line + offset,
                'I014',
                'Rule declarations should end indented on a single new line.',
                )


class CSSStatementMember(object):
    '''A member of CSS statement.'''

    def __init__(self, start_line, start_character, text):
        self.start_line = start_line
        self.start_character = start_character
        self.text = text

    def getStartLine(self):
        '''Return the line number for first character in the statement and
        the number of new lines untilg the first character.'''
        index = 0
        text = self.text
        try:
            character = text[index]
            while character == '\n':
                index += 1
                character = text[index]
        except IndexError:
            # The end of string was reached without finding a statement.
            pass

        return self.start_line + index + 1

    def __str__(self):
        return self.text

    def __repr__(self):
        return '%d:%d:{%s}' % (
            self.start_line, self.start_character, self.text)


class CSSCodingConventionChecker(object):
    '''CSS coding convention checker.'''

    icons = {
        'E': 'error',
        'I': 'info',
        }

    def __init__(self, text, logger=None):
        self._text = text.splitlines(True)
        self.line_number = 0
        self.character_number = 0
        if logger:
            self._logger = logger
        else:
            self._logger = self._defaultLog

    def log(self, line_number, code, message):
        '''Log the message with `code`.'''
        if code in IGNORED_MESSAGES:
            return
        icon = self.icons[code[0]]
        self._logger(line_number, code + ': ' + message, icon=icon)

    def check(self):
        '''Check all rules.'''
        for rule in self.getRules():
            rule.check()

    def getRules(self):
        '''Generates the next CSS rule ignoring comments.'''
        while True:
            yield self.getNextRule()

    def getNextRule(self):
        '''Return the next parsed rule.

        Raise `StopIteration` if we are at the last rule.
        '''
        if self._nextStatementIsAtRule():
            text = None
            block = None
            keyword = self._parse('@')
            # TODO: user regex [ \t {]
            keyword_text = self._parse(' ')
            keyword_name = keyword_text.text
            keyword.text += '@' + keyword_name + ' '

            if keyword_name.lower() in AT_TEXT_RULES:
                text = self._parse(';')
            elif keyword_name.lower() in AT_BLOCK_RULES:
                start = self._parse('{')
                keyword.text += start.text
                block = self._parse('}')
            else:
                self._parse(';')
                raise StopIteration

            return CSSAtRule(
                identifier=keyword_name,
                keyword=keyword,
                text=text,
                block=block,
                log=self.log)
        else:
            selector = self._parse('{')
            declarations = self._parse('}')
            return CSSRuleSet(
                selector=selector,
                declarations=declarations,
                log=self.log)

    def _defaultLog(self, line_number, message, icon='info'):
        '''Log the message to STDOUT.'''
        print '    %4s:%s' % (line_number, message)

    def _nextStatementIsAtRule(self):
        '''Return True if next statement in the buffer is an at-rule.

        Just look for open brackets and see if there is an @ before that
        braket.
        '''
        search_buffer = []
        line_counter = self.line_number
        current_line = self._text[line_counter][self.character_number:]
        while current_line.find('@') == -1:
            search_buffer.append(current_line)
            line_counter += 1
            try:
                current_line = self._text[line_counter]
            except IndexError:
                return False

        text_buffer = ''.join(search_buffer)
        if text_buffer.find('{') == -1:
            return True
        else:
            return False

    def _parse(self, stop_character):
        '''Return the parsed text until stop_character.'''
        try:
            self._text[self.line_number][self.character_number]
        except IndexError:
            raise StopIteration
        result = []
        start_line = self.line_number
        start_character = self.character_number
        comment_started = False
        while True:
            try:
                data = self._text[self.line_number][self.character_number:]
            except IndexError:
                break

            # Look for comment start/end.
            (comment_update,
            before_comment,
            after_comment,
            newline_consumed) = _check_comment(data)
            if comment_update is not None:
                comment_started = comment_update

            if comment_started:
                # We are inside a comment.
                # Add the data before the comment and go to next line.
                if before_comment is not None:
                    result.append(before_comment)
                self.character_number = 0
                self.line_number += 1
                continue

            # If we have a comment, strip it from the data.
            # Remember the initial cursor position to know where to
            # continue.
            initial_position = data.find(stop_character)
            if before_comment is not None or after_comment is not None:
                if before_comment is None:
                    before_comment = ''
                if after_comment is None:
                    after_comment = ''
                data = before_comment + after_comment

            if initial_position == -1 or newline_consumed:
                # We are not at the end.
                # Go to next line and append the data.
                result.append(data)
                self.character_number = 0
                self.line_number += 1
                continue
            else:
                # Delimiter found.
                # Find it again in the text that now has no comments.
                # Append data until the delimiter.
                # Move cursor to next character and stop searching for it.
                new_position = data.find(stop_character)
                result.append(data[:new_position])
                self.character_number += initial_position + 1
                break

        return CSSStatementMember(
            start_line=start_line,
            start_character=start_character,
            text=''.join(result))


def _check_comment(data):
    '''Check the data for comment markers.'''

    comment_started = None
    before_comment = None
    after_comment = None
    newline_consumed = False

    comment_start = data.find(COMMENT_START)
    if comment_start != -1:
        comment_started = True
        before_comment = data[:comment_start]
        # Only use `None` to signal that there is no text before the comment.
        if before_comment == '':
            before_comment = None

    comment_end = data.find(COMMENT_END)
    if comment_end != -1:
        comment_started = False
        # Set comment end after the lenght of the actual comment end
        # marker.
        comment_end += len(COMMENT_END)
        if before_comment is None and data[comment_end] == '\n':
            # Consume the new line if it next to the comment end and
            # the comment in on the whole line.
            comment_end += 1
            newline_consumed = True
        after_comment = data[comment_end:]
    return (comment_started, before_comment, after_comment, newline_consumed)


def show_usage():
    '''Print the command usage.'''
    print 'Usage: cssccc OPTIONS'
    print '  -h, --help\t\tShow this help.'
    print '  -v, --version\t\tShow version.'
    print '  -f FILE, --file=FILE\tCheck FILE'


def read_file(filename):
    '''Return the content of filename.'''
    text = ''
    with open(filename, 'r') as f:
        text = f.read()
    return text


if __name__ == '__main__':
    if len(sys.argv) < 2:
        show_usage()
    elif sys.argv[1] in ['-v', '--version']:
        print 'CSS Code Convention Checker %s' % (__version__)
        sys.exit(0)
    elif sys.argv[1] == '-f':
        text = read_file(sys.argv[2])
        checker = CSSCodingConventionChecker(text)
        sys.exit(checker.check())
    elif sys.argv[1] == '--file=':
        text = read_file(sys.argv[1][len('--file='):])
        checker = CSSCodingConventionChecker(text)
        sys.exit(checker.check())
    else:
        show_usage()