]> git.phdru.name Git - phdru.name/cgi-bin/blog-ru/search-tags.git/blob - tags.py
Docs(TODO): Try Pyleri
[phdru.name/cgi-bin/blog-ru/search-tags.git] / tags.py
1 blog_filename = "blog_dict.pickle"
2
3 try:
4    import cPickle as pickle
5 except ImportError:
6    import pickle
7
8 try:
9    blog_file = open('../../../../phdru.name/ru/' + blog_filename, "rb")
10 except IOError:
11    blog_dict = {}
12 else:
13    blog_dict = pickle.load(blog_file)
14    blog_file.close()
15
16
17 # blog_dict is a mapping
18 # (year, month, day) => [list of (file, title, lead, tags)]
19
20 def tag_exists(tag):
21     for posts in blog_dict.itervalues():
22         for _file, _title, _lead, _tags in posts:
23             if tag in _tags:
24                 return True
25     return False
26
27 def _test_post(post, tree):
28     """Test if the list of tags in the post satisfies condition
29
30     Recursively evaluate the tree against the list of tags in the post.
31
32     """
33     op = tree[0]
34     if op == 'NAME':
35         tag = tree[1]
36         assert isinstance(tag, str)
37         _tags = post[3]
38         return tag in _tags
39     elif op in ('AND', 'OR'):
40         value1 = _test_post(post, tree[1])
41         value2 = _test_post(post, tree[2])
42         if op == 'AND':
43             return value1 and value2
44         if op == 'OR':
45             return value1 or value2
46     elif op == 'NOT':
47         return not _test_post(post, tree[1])
48     elif op == 'PARENS':
49         return _test_post(post, tree[1])
50     else:
51         raise ValueError("Cannot get there")
52
53 def find_tags(tree):
54     """Test every blog post against parsed expression
55
56     Return all posts that passed the test.
57
58     """
59     _posts = []
60     for (year, month, day), posts in blog_dict.iteritems():
61         for post in posts:
62             if _test_post(post, tree):
63                 _posts.append((
64                     year, month, day,
65                     '/'.join((year, month, day, post[0][:-len("tmpl")] + "html")),
66                     post[1]))
67     _posts.sort(reverse=True)
68     return _posts