]> git.phdru.name Git - phdru.name/cgi-bin/blog-ru/search-tags.git/blob - tags.py
Version 0.8: Python 3
[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.values():
22         for _file, _title, _lead, _tags in posts:
23             if tag in _tags:
24                 return True
25     return False
26
27
28 def _test_post(post, tree):
29     """Test if the list of tags in the post satisfies condition
30
31     Recursively evaluate the tree against the list of tags in the post.
32
33     """
34     op = tree[0]
35     if op == 'NAME':
36         tag = tree[1]
37         assert isinstance(tag, str)
38         _tags = post[3]
39         return tag in _tags
40     elif op in ('AND', 'OR'):
41         value1 = _test_post(post, tree[1])
42         value2 = _test_post(post, tree[2])
43         if op == 'AND':
44             return value1 and value2
45         if op == 'OR':
46             return value1 or value2
47     elif op == 'NOT':
48         return not _test_post(post, tree[1])
49     elif op == 'PARENS':
50         return _test_post(post, tree[1])
51     else:
52         raise ValueError("Cannot get there")
53
54
55 def find_tags(tree):
56     """Test every blog post against parsed expression
57
58     Return all posts that passed the test.
59
60     """
61     _posts = []
62     for (year, month, day), posts in blog_dict.items():
63         for post in posts:
64             if _test_post(post, tree):
65                 _posts.append((
66                     year, month, day,
67                     '/'.join(
68                         (year, month, day, post[0][:-len("tmpl")] + "html")),
69                     post[1]))
70     _posts.sort(reverse=True)
71     return _posts