Classifier Python :: 2.4 to 2.7
[docutils.git] / sandbox / py-rest-doc / sphinx / util.py
blobf927fcd20d47d25f5e30cfd5db5c1f40e8ed1c58
1 # -*- coding: utf-8 -*-
2 """
3 sphinx.util
4 ~~~~~~~~~~~
6 Utility functions for Sphinx.
8 :copyright: 2007 by Georg Brandl.
9 :license: Python license.
10 """
12 import os
13 import sys
14 import fnmatch
15 from os import path
18 def relative_uri(base, to):
19 """Return a relative URL from ``base`` to ``to``."""
20 b2 = base.split('/')
21 t2 = to.split('/')
22 # remove common segments
23 for x, y in zip(b2, t2):
24 if x != y:
25 break
26 b2.pop(0)
27 t2.pop(0)
28 return '../' * (len(b2)-1) + '/'.join(t2)
31 def ensuredir(path):
32 """Ensure that a path exists."""
33 try:
34 os.makedirs(path)
35 except OSError, err:
36 if not err.errno == 17:
37 raise
40 def status_iterator(iterable, colorfunc=lambda x: x, stream=sys.stdout):
41 """Print out each item before yielding it."""
42 for item in iterable:
43 print >>stream, colorfunc(item),
44 stream.flush()
45 yield item
46 print >>stream
49 def get_matching_files(dirname, pattern, exclude=()):
50 """Get all files matching a pattern in a directory, recursively."""
51 # dirname is a normalized absolute path.
52 dirname = path.normpath(path.abspath(dirname))
53 dirlen = len(dirname) + 1 # exclude slash
54 for root, dirs, files in os.walk(dirname):
55 dirs.sort()
56 files.sort()
57 for sfile in files:
58 if not fnmatch.fnmatch(sfile, pattern):
59 continue
60 qualified_name = path.join(root[dirlen:], sfile)
61 if qualified_name in exclude:
62 continue
63 yield qualified_name
66 def get_category(filename):
67 """Get the "category" part of a RST filename."""
68 parts = filename.split('/', 1)
69 if len(parts) < 2:
70 return
71 return parts[0]
74 def shorten_result(text='', keywords=[], maxlen=240, fuzz=60):
75 if not text:
76 text = ''
77 text_low = text.lower()
78 beg = -1
79 for k in keywords:
80 i = text_low.find(k.lower())
81 if (i > -1 and i < beg) or beg == -1:
82 beg = i
83 excerpt_beg = 0
84 if beg > fuzz:
85 for sep in ('.', ':', ';', '='):
86 eb = text.find(sep, beg - fuzz, beg - 1)
87 if eb > -1:
88 eb += 1
89 break
90 else:
91 eb = beg - fuzz
92 excerpt_beg = eb
93 if excerpt_beg < 0:
94 excerpt_beg = 0
95 msg = text[excerpt_beg:beg+maxlen]
96 if beg > fuzz:
97 msg = '... ' + msg
98 if beg < len(text)-maxlen:
99 msg = msg + ' ...'
100 return msg
103 class attrdict(dict):
104 def __getattr__(self, key):
105 return self[key]
106 def __setattr__(self, key, val):
107 self[key] = val
108 def __delattr__(self, key):
109 del self[key]