summaryrefslogtreecommitdiff
path: root/sandbox/py-rest-doc/sphinx/util.py
blob: f927fcd20d47d25f5e30cfd5db5c1f40e8ed1c58 (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
# -*- coding: utf-8 -*-
"""
    sphinx.util
    ~~~~~~~~~~~

    Utility functions for Sphinx.

    :copyright: 2007 by Georg Brandl.
    :license: Python license.
"""

import os
import sys
import fnmatch
from os import path


def relative_uri(base, to):
    """Return a relative URL from ``base`` to ``to``."""
    b2 = base.split('/')
    t2 = to.split('/')
    # remove common segments
    for x, y in zip(b2, t2):
        if x != y:
            break
        b2.pop(0)
        t2.pop(0)
    return '../' * (len(b2)-1) + '/'.join(t2)


def ensuredir(path):
    """Ensure that a path exists."""
    try:
        os.makedirs(path)
    except OSError, err:
        if not err.errno == 17:
            raise


def status_iterator(iterable, colorfunc=lambda x: x, stream=sys.stdout):
    """Print out each item before yielding it."""
    for item in iterable:
        print >>stream, colorfunc(item),
        stream.flush()
        yield item
    print >>stream


def get_matching_files(dirname, pattern, exclude=()):
    """Get all files matching a pattern in a directory, recursively."""
    # dirname is a normalized absolute path.
    dirname = path.normpath(path.abspath(dirname))
    dirlen = len(dirname) + 1    # exclude slash
    for root, dirs, files in os.walk(dirname):
        dirs.sort()
        files.sort()
        for sfile in files:
            if not fnmatch.fnmatch(sfile, pattern):
                continue
            qualified_name = path.join(root[dirlen:], sfile)
            if qualified_name in exclude:
                continue
            yield qualified_name


def get_category(filename):
    """Get the "category" part of a RST filename."""
    parts = filename.split('/', 1)
    if len(parts) < 2:
        return
    return parts[0]


def shorten_result(text='', keywords=[], maxlen=240, fuzz=60):
    if not text:
        text = ''
    text_low = text.lower()
    beg = -1
    for k in keywords:
        i = text_low.find(k.lower())
        if (i > -1 and i < beg) or beg == -1:
            beg = i
    excerpt_beg = 0
    if beg > fuzz:
        for sep in ('.', ':', ';', '='):
            eb = text.find(sep, beg - fuzz, beg - 1)
            if eb > -1:
                eb += 1
                break
        else:
            eb = beg - fuzz
        excerpt_beg = eb
    if excerpt_beg < 0:
        excerpt_beg = 0
    msg = text[excerpt_beg:beg+maxlen]
    if beg > fuzz:
        msg = '... ' + msg
    if beg < len(text)-maxlen:
        msg = msg + ' ...'
    return msg


class attrdict(dict):
    def __getattr__(self, key):
        return self[key]
    def __setattr__(self, key, val):
        self[key] = val
    def __delattr__(self, key):
        del self[key]