This file is indexed.

/usr/share/pyshared/rest2web/restindex.py is in rest2web 0.5.2~alpha+svn-r248-2.

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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# restindex.py

# Subversion Details
# $LastChangedDate: 2007-06-10 00:06:55 +0200 (Sun, 10 Jun 2007) $
# $LastChangedBy: fuzzyman $
# $HeadURL: https://svn.rest2web.python-hosting.com/trunk/rest2web/restindex.py $
# $LastChangedRevision: 246 $

# The function that parses the restindex, and associated data.
# http://www.voidspace.org.uk/python/rest2web

# Copyright Michael Foord, 2004 - 2006.
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml

# For information about bugfixes, updates and support, please join the
# rest2web mailing list.
# http://lists.sourceforge.net/lists/listinfo/rest2web-develop
# Comments, suggestions and bug reports welcome.
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# E-mail fuzzyman@voidspace.org.uk


import os
from rest2web.embedded_code import align_multiline_code


class restindexError(SyntaxError):
    """ """


# acceptable values for keywords that must be on or off
true_false_list = ['yes', 'no', 'true', 'false', 'on', 'off', '1', '0']

# keywords that are on or off
true_false_keywords = ['include', 'build']

# any keywords that take normal text values
text_keywords = [
    'file-extension', 'template', 'index-file', 'section',
    'link-title', 'page-title', 'crumb', 'target', 'encoding',
    'output-encoding', 'template-encoding', 'file', 'initialheaderlevel'
    ]

# keywords in this dictionary can only have values from a list of options
limited_keywords = {
    # FIXME: add sextile and textile
    'format': ['html', 'rest']
    }

# keywords in this dictionary have multiple values
# the entry is either the number of values expected
# or 0, meaning unspecified
# or a minus number meaning a *minimum* number
multiple_keywords = {'sectionlist': 0, 'section-title': 2,
                    'tags': 0, 'plugins': 0, 'section-pages': -1}

# keywords in this dictionary are descriptions
# they may also have a value assciated with them
# their entry is True or False - whether they have a value or not
# if they do, there may be multiple - and the value becomes part of the key
# (as a tuple)
description_keywords = {'section-description': 1, 'page-description': 0}

# keywords that can appear more than once
repeat_keywords = [
                    'section-title', 'section-description', 'file',
                    'section-pages', # 'nofile', 'filemask',
                    ]


def remove_comment(inlines):
    restindex = inlines[1:]
    indent = 0
    i = -1
    while i < len(restindex):
        i += 1
        line = restindex.pop(0)
        stripped = line.strip()
        if not stripped:
            continue
        this_indent = len(line) - len(stripped)
        if indent and this_indent < indent:
            return inlines
        indent = min(this_indent, indent or this_indent)
        if stripped == 'restindex':
            restindex.insert(0, line)
            break
    else:
        return inlines
    #
    return restindex


def find_start(inlines):
    while inlines:
        line = inlines.pop(0)
        if not line.strip():
            continue
        if line.strip().startswith('..') and  line.find('::') == -1:
            inlines.insert(0, line)
            inlines = remove_comment(inlines)
            break
        inlines.insert(0, line)
        break
    return inlines


def read_restindex(infile):
    """
    Interpret the restindex and divide it from the contents.
    
    Given a file as a list of lines (or file object, or bounded iterable),
    read the restindex from the start. (if any)
    Returns restindex, remainder of file (which will have trailing whitespace
    removed from each line).
    restindex will be None if there isn't one.
    
    If it finds any errors it raises ``restindexError`` - which is a subclass
    of ``SyntaxError``
    """
    # FIXME: consumes the whole file immediately
    thefile = [line.rstrip() for line in infile]
    thefile.append('')
    #
    # UTF8 BOM
    if thefile[0].startswith('\xef\xbb\xbf'):
        # get rid of it
        thefile[0] = thefile[0][3:]
    #
    thefile = find_start(thefile)
    #
    started = False
    indesc = False
    thisdesc = []
    restindex = {}
    #
    index = -1
    length = len(thefile) - 1
    # indexing like this is more versatile, we can manually
    # wind forwards or back
    while index < length:
        index += 1
        origline = thefile[index]
        line = origline.strip()
        #
        if (line and
                not line.startswith('#') and
                not line == 'restindex' and
                not line.strip() == '..' and
                not started
                ):
            return None, '\n'.join(thefile)
        #
        # if we are in a multiline value
        if indesc:
            # end of a description
            if not line == '/description':
                thisdesc.append(origline)
            else:
                # join, remove indentation, and save
                value = align_multiline_code('\n'.join(thisdesc))
                # FIXME: special case for 'section-description' -
                # where indesc is a tuple
                if isinstance(indesc, tuple):
                    keyword, name = indesc
                    if restindex.has_key(keyword):
                        if restindex[keyword].has_key(name):
                            # section description twice
                            raise restindexError(('"%s" repeated for "%s"'
                                ' - line %s') % (keyword, name, index + 1))
                        restindex[keyword][name] = value
                    else:
                        restindex[keyword] = {name: value}
                else:
                    restindex[indesc] = value
                indesc = None
                thisdesc = []
            continue
        #
        if line.startswith('#') or not line:
            # comments and empty lines are skipped
            continue
        #
        if not started and line.strip() == '..':
            continue
        #
        if line == 'restindex':
            if started:
                raise restindexError(('restindex found in the wrong place'
                    ' - line %s') % (index + 1))
            started = True
            continue
        #
        if line == '/restindex':
            # the end
            body = thefile[index+1:]
            return restindex, '\n'.join(body)
        #
        if line.find(':') == -1:
            raise restindexError('No keyword on line - line %s' % (index + 1))
        keyword, value = line.split(':', 1)
        keyword = keyword.strip().lower()
        value = value.strip()
        #
        if restindex.has_key(keyword) and keyword not in repeat_keywords:
            raise restindexError('Keyword "%s" repeated - line %s' % (
                keyword, index + 1))
        #
        if keyword in true_false_keywords:
            # this keyword should be on or off
            value = value.lower()
            if value not in true_false_list:
                raise restindexError('Strange value - line %s' % (index + 1))
            restindex[keyword] = value
            continue
        #
        if keyword in text_keywords:
            if keyword in repeat_keywords:
                try:
                    restindex[keyword].append(value)
                except KeyError:
                    restindex[keyword] = [value]
            else:
                # this keyword takes a straight text value
                restindex[keyword] = value
            continue
        #
        if keyword in limited_keywords:
            # value must be one from a list of options
            value = value.lower()
            if value not in limited_keywords[keyword]:
                raise restindexError, 'Strange value - line %s' % (index + 1)
            restindex[keyword] = value
            continue
        #
        if keyword in multiple_keywords:
            # NOTE we can have multiple section titles
            numsplits = multiple_keywords[keyword]
            if numsplits < 1:
                if not value:
                    values = []
                else:
                    values = [entry.strip() or None
                                    for entry in value.split(',')]
                if numsplits < 0:
                    numsplits = int(numsplits)
                    if len(values) < numsplits:
                        raise restindexError(('Multiple keyword with too '
                                        'few values - line %s') % (index + 1))
                if keyword in repeat_keywords:
                    # keyword is a repeat
                    # first value is a name
                    name = values[0]
                    values = values[1:]
                    if restindex.has_key(keyword):
                        if restindex[keyword].has_key(name):
                            raise restindexError(('"%s" repeated for "%s"'
                                ' - line %s') % (keyword, name, index + 1))
                        restindex[keyword][name] = values
                    else:
                        restindex[keyword] = {name: values}
                #
                else:
                    restindex[keyword] = values
            else:
                values = [entry.strip() or None
                    for entry in value.split(',', numsplits-1)]
                name = values[0] or None
                # this allows UP TO numsplit values - XXXX *doesn't* choke
                # on less; NOTE: returns a list, even though will usually
                # be 0 or 1 items
                value = values[1:]
                if numsplits == 2:
                    # special case - should only have a single value
                    if value:
                        value = value[0]
                    else:
                        value = ''
                if restindex.has_key(keyword):
                    # section description twice
                    if restindex[keyword].has_key(name):
                        raise restindexError(('"%s" repeated for "%s"'
                            ' - line %s') % (keyword, name, index + 1))
                    restindex[keyword][name] = value
                #
                else:
                    restindex[keyword] = {name: value}
            continue
        #
        if keyword in description_keywords:
            if description_keywords[keyword]:
                indesc = (keyword, value or None)
            else:
                indesc = keyword
            continue
        #
        # if we get this far, we haven't recognised the keyword
        # FIXME: show the offending line?
        raise restindexError('Unrecognised keyword - line %s' % (index + 1))
    # if we get this far, we reached the end of the file
    # without finding '/restindex'
    if not started:
        return None, '\n'.join(thefile)
    raise restindexError, "No '/restindex' found."

default_restindex = {
    'include': 'yes',
    'format': 'rest',
    'file-extension': 'html',
    'template': None,
    'index-file': 'index.txt',
    'template-encoding': None,
    'section': None,
    'link-title': '',
    'page-title': None,
    'page-description': '',
    'crumb': None,
    'target': None,
    'build': 'yes',
    'sectionlist': [],
    'section-title': {},
    'section-description': {},
    'encoding': None,
    'output-encoding': None,
    'tags': [],
    'section-pages': {},
    'plugins': [],
    'file': [],
#    'filemask': [],
#    'nofile': [],
    'initialheaderlevel': '1'
}

# these keyword(s) set the default value for the whole directory
default_keywords = ['file-extension', 'initialheaderlevel']

if __name__ == '__main__':
    ri = """
restindex
    # this is a comment
        include: yes
        file: file1
        file: file2
        file: file3
        plugins:
        format: html
        tags: tag1, tag2, tag3
        file-extension: shtml
        template: template.txt
        template-encoding: utf8
        index-file: index.txt
        section:  section name
        link-title: This is the text to use in the link
        page-title: We *usually* only need a title for HTML
        page-description:
            this is a description
            It can go across several line
            And even be indented a bit.
            It will be interpreted as *reST*.
        /description
        crumb: Short Name
        build: yes
        target: thisfile.html
        encoding: utf8
        output-encoding: utf8
        sectionlist: , section-name, section-name2, section-name3
        section-title: section-name, title
        section-description: section-name
            This is also a description.
        
        /description
        section-title: , default-section-title
        section-description:
            This is the default-section description.
        
        /description
        section-pages: , page1, page2, page3
        section-pages: section-name, page1, page2, page3
/restindex
"""
    rest_index = read_restindex(ri.split('\n'))[0]
    for entry in rest_index:
        print entry, '  :  ', rest_index[entry]

    #
    ri2 = """
..
    restindex
        # this is a comment
            include: yes
            file: file1
            file: file2
            file: file3
            plugins:
            format: html
            tags: tag1, tag2, tag3
            file-extension: shtml
            template: template.txt
            template-encoding: utf8
            index-file: index.txt
            section:  section name
            link-title: This is the text to use in the link
            page-title: We *usually* only need a title for HTML
            page-description:
                this is a description
                It can go across several line
                And even be indented a bit.
                It will be interpreted as *reST*.
            /description
            crumb: Short Name
            build: yes
            target: thisfile.html
            encoding: utf8
            output-encoding: utf8
            sectionlist: , section-name, section-name2, section-name3
            section-title: section-name, title
            section-description: section-name
                This is also a description.
            
            /description
            section-title: , default-section-title
            section-description:
                This is the default-section description.
            
            /description
            section-pages: , page1, page2, page3
            section-pages: section-name, page1, page2, page3
    /restindex
"""
    print
    print
    print 'Attempting restindex in a comment:'
    print
    rest_index2 = read_restindex(ri2.split('\n'))[0]
    for entry in rest_index2:
        print entry, '  :  ', rest_index[entry]
    assert rest_index == rest_index2

# multiline parser
# for uservalues

import re

valid_line = re.compile(r'\s*([a-zA-Z_]\w*)\s*(?:=|:)(.*)')
# the reserved_names are all the names used in the namespace other than 'body'
reserved_names = [
    'title', 'breadcrumbs', 'sections', 'pagename', 'pagepath',
    'encoding', 'output_encoding', 'final_encoding', 'path_to_root',
    'sectionlist', 'rest_dict', 'doc', 'stdout', 'modified', 'modtime',
    'template_file', 'template_encoding', 'indexpage', 'indextree',
    'thispage', 'sidebar', 'minibar', 'print_crumbs', 'Processor', 'tags',
    'default_section', 'modtime', 'modtimeiso'
    ]

def parse_user_values(content, directory):
    """
    Read the content of a page, as a list of lines (after the restindex
    has been read). Parse and extracts any 'uservalues'

    Return (uservalues, content) - (dict, string)
    uservalues will be ``None`` if there is no uservalues section.
    """
    quot = ''
    user_values = {}
    found_end = False
    started = False
    index = -1
    length = len(content) - 1
    while index < length:
        index += 1
        line = content[index]
        #
        if quot:
            val = val + '\n'
            if line.rstrip().endswith(quot):
                val += line.rstrip()[:-3]
                quot = False
                user_values[name] = val
            else:
                val += line
            continue
        #
        if line.lstrip().startswith('#') or not line.strip():
            continue
        elif not started and line.strip() == 'uservalues':
            started = True
            continue
        elif not started:
            return None, '\n'.join(content)
        #
        # XXXX if we find a '/uservalues' without a start
        # XXXX should we raise an error ?
        elif line.strip() ==('/uservalues'):
            found_end = True
            break
        #
        mat = valid_line.match(line)
        if not mat:
            raise SyntaxError, 'Invalid line in uservalues:\n    "%s"' % line
        name, val = mat.groups()
        if name in reserved_names:
            raise SyntaxError, ('Use of reserved name in uservalues:\n'
                '    "%s"') % line
        if val.lstrip()[:3] in ['"""', "'''"]:
            quot = val.lstrip()[:3]
            val = val.lstrip()[3:]
            if val.rstrip().endswith(quot):
                quot = ''
                val = val.rstrip()[:-3]
            else:
                continue
        user_values[name] = val.strip()
    #
    if not started:
        # only blank lines or comments
        return None, '\n'.join(content)
    if quot:
        raise SyntaxError, 'No end to a triple quoted section.'
    if not found_end:
        raise SyntaxError, 'No end to "uservalues" section.'
    #
    content = content[index+1:]
    if user_values.has_key('body'):
        loc = os.path.normpath(os.path.join(directory, user_values['body']))
        # XXXX os.path.join ? technically this value will be in URL form
        # - not native
        #
        content = open(loc).readlines()
        del user_values['body']
    #
    return user_values, '\n'.join(content)

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

if __name__ == '__main__':
    print
    print '#'*30
    print
    #
    content1 = '''
    
    #comment
    
    uservalues
        test: 3
        # a comment
        test2: a value
        test3 = \''' a multiline
    """ value"""
    \'''
        test4 = """ A test """
        test5 = """
        
        A long
        line.
        """
    /uservalues
    
    The content...
'''
    
    content2 = '''
    
    uservalues
    test = """
    
    /uservalues
    '''
    directory = ''
    (user_values, content) = parse_user_values(
        content1.split('\n'), directory)
    print 'Content: ', content
    for entry in user_values:
        print entry, '  :  ', user_values[entry]
    #
    try:
        (user_values, content) = parse_user_values(
            content2.split('\n'), directory)
    except SyntaxError:
        print 'Picked up the error in content2.'
    else:
        print '***FAIL** failed to pick up the error in content2.'
        raise SyntaxError
    


"""
CHANGELOG
=========


2006/08/13
----------

Allow the restindex and uservalues to be in a ReST comment.


2005/10/12
----------

Added the 'section-pages' keyword. Only valid for indexes.


2005/07/26
Added 'file' and 'plugins' keywords
Added 'tags' to reserved name
An empty multiple value now returns '[]' rather than '[None]'


2005/07/23
Added the tags keyword.


2005/06/18
Changes by Nicola Larosa
    Code cleanup
        lines shortened
        comments on line above code
        empty comments in empty lines


2005/06/12
Added the parser for "uservalues"


2005/05/20
Added the 'template-encoding' keyword.
Allowed for default section in sectionlist.


2005/05/16
restindex['section-title'] is now a dictionary of single values, rather than a
dictionary of lists !


2005/05/15
``read_restindex`` removes UTF8 BOM at start of files
Added ``output-encoding`` keyword.
If no name is given with a section-description, then we use ``None`` (the default section)
A ``section-title`` with no name (``section-title: , Title Line``) is a title for the default section.
Added test.

"""