4 # blitiri - A single-file blog engine.
5 # Alberto Bertogli (albertito@gmail.com)
8 # Configuration section
10 # You can edit these values, or create a file named "config.py" and put them
11 # there to make updating easier. The ones in config.py take precedence.
14 # Directory where entries are stored
15 data_path = "/tmp/blog/data"
17 # Are comments allowed? (if False, comments_path option is not used)
18 enable_comments = False
20 # Directory where comments are stored (must be writeable by the web server)
21 comments_path = "/tmp/blog/comments"
23 # Path where templates are stored. Use an empty string for the built-in
24 # default templates. If they're not found, the built-in ones will be used.
25 templates_path = "/tmp/blog/templates"
27 # URL to the blog, including the name. Can be a full URL or just the path.
28 blog_url = "/blog/blitiri.cgi"
30 # Style sheet (CSS) URL. Can be relative or absolute. To use the built-in
31 # default, set it to blog_url + "/style".
32 css_url = blog_url + "/style"
35 title = "I don't like blogs"
38 author = "Hartmut Kegan"
44 class Captcha (object):
45 def __init__(self, article):
46 self.article = article
47 words = article.title.split()
48 self.nword = hash(article.title) % len(words) % 5
49 self.answer = words[self.nword]
50 self.help = 'gotcha, damn spam bot!'
53 nword = self.nword + 1
62 return "enter the %s word of the article's title" % n
63 puzzle = property(fget = get_puzzle)
65 def validate(self, form_data):
66 if form_data.captcha.lower() == self.answer.lower():
72 # End of configuration
73 # DO *NOT* EDIT ANYTHING PAST HERE
87 from docutils.core import publish_parts
88 from docutils.utils import SystemMessage
90 # Before importing the config, add our cwd to the Python path
91 sys.path.append(os.getcwd())
93 # Load the config file, if there is one
100 # Pimp *_path config variables to support relative paths
101 data_path = os.path.realpath(data_path)
102 templates_path = os.path.realpath(templates_path)
106 default_main_header = """\
107 <?xml version="1.0" encoding="utf-8"?>
108 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
109 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
111 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
113 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
114 type="application/atom+xml" />
115 <link href="%(css_url)s" rel="stylesheet" type="text/css" />
116 <title>%(title)s</title>
121 <h1><a href="%(url)s">%(title)s</a></h1>
123 <div class="content">
126 default_main_footer = """
129 %(showyear)s: %(monthlinks)s<br/>
130 years: %(yearlinks)s<br/>
131 subscribe: <a href="%(url)s/atom">atom</a><br/>
132 views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
139 default_article_header = """
140 <div class="article">
141 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
142 <span class="artinfo">
143 by %(author)s on <span class="date">
145 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
146 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
147 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
148 %(chour)02d:%(cminute)02d</span>
149 (updated on <span class="date">
150 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
151 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
152 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
153 %(uhour)02d:%(uminute)02d)</span><br/>
154 <span class="tags">tagged %(tags)s</span> -
155 <span class="comments">with %(comments)s
156 <a href="%(url)s/post/%(uuid)s#comments">comment(s)</a></span>
159 <div class="artbody">
162 default_article_footer = """
168 default_comment_header = """
169 <div class="comment">
170 <a name="comment-%(number)d" />
171 <h3><a href="#comment-%(number)d">Comment #%(number)d</a></h3>
172 <span class="cominfo">by %(linked_author)s
173 on %(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d</span>
175 <div class="combody">
178 default_comment_footer = """
184 default_comment_form = """
185 <div class="comform">
187 <h3 class="comform"><a href="#comment">Your comment</a></h3>
188 <div class="comforminner">
189 <form method="%(form_method)s" action="%(form_action)s">
190 <div class="comformauthor">
191 <label for="comformauthor">Your name %(form_author_error)s</label>
192 <input type="text" class="comformauthor" id="comformauthor"
193 name="comformauthor" value="%(form_author)s" />
195 <div class="comformlink">
196 <label for="comformlink">Your link
197 <span class="comformoptional">(optional, will be published)</span>
198 %(form_link_error)s</label>
199 <input type="text" class="comformlink" id="comformlink"
200 name="comformlink" value="%(form_link)s" />
201 <div class="comformhelp">
202 like <span class="formurlexample">http://www.example.com/</span>
203 or <span class="formurlexample">mailto:you@example.com</span>
206 <div class="comformcaptcha">
207 <label for="comformcaptcha">Your humanity proof %(form_captcha_error)s</label>
208 <input type="text" class="comformcaptcha" id="comformcaptcha"
209 name="comformcaptcha" value="%(form_captcha)s" />
210 <div class="comformhelp">%(captcha_puzzle)s</div>
212 <div class="comformbody">
213 <label for="comformbody" class="comformbody">The comment
214 %(form_body_error)s</label>
215 <textarea class="comformbody" id="comformbody" name="comformbody" rows="15"
216 cols="80">%(form_body)s</textarea>
217 <div class="comformhelp">
219 <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">\
220 RestructuredText</a> format, please
223 <div class="comformsend">
224 <button type="submit" class="comformsend" id="comformsend" name="comformsend">
233 default_comment_error = '<span class="comformerror">(%(error)s)</span>'
239 font-family: sans-serif;
250 border-bottom: 2px solid #99F;
259 border-bottom: 1px solid #99C;
266 border-bottom: 1px solid #99C;
270 text-decoration: none;
279 text-decoration: none;
283 span.artinfo a:hover {
284 text-decoration: none;
301 text-decoration: none;
305 span.cominfo a:hover {
306 text-decoration: none;
330 border-bottom: 1px solid #99C;
335 div.comform span.comformoptional {
351 span.formurlexample {
353 background-color: #EEF;
354 font-family: monospace;
356 padding-right: 0.2em;
359 textarea.comformbody {
360 font-family: monospace;
380 background-color: #99F;
388 border-top: 2px solid #99F;
393 text-decoration: none;
396 /* Articles are enclosed in <div class="section"> */
402 border-bottom: 1px dotted #99C;
408 def rst_to_html(rst, secure = True):
410 'input_encoding': encoding,
411 'output_encoding': 'utf8',
414 'file_insertion_enabled': secure,
415 'raw_enabled': secure,
417 parts = publish_parts(rst, settings_overrides = settings,
418 writer_name = "html")
419 return parts['body'].encode('utf8')
421 def validate_rst(rst, secure = True):
423 rst_to_html(rst, secure)
425 except SystemMessage, e:
426 desc = e.args[0].encode('utf-8') # the error string
427 desc = desc[9:] # remove "<string>:"
428 line = int(desc[:desc.find(':')] or 0) # get the line number
429 desc = desc[desc.find(')')+2:-1] # remove (LEVEL/N)
431 desc, context = desc.split('\n', 1)
434 if desc.endswith('.'):
436 return (line, desc, context)
438 def valid_link(link):
440 mail_re = r"^[^ \t\n\r@<>()]+@[a-z0-9][a-z0-9\.\-_]*\.[a-z]+$"
441 scheme_re = r'^[a-zA-Z]+:'
442 url_re = r'^(?:[a-z0-9\-]+|[a-z0-9][a-z0-9\-\.\_]*\.[a-z]+)' \
443 r'(?::[0-9]+)?(?:/.*)?$'
446 if re.match(scheme_re, link, re.I):
447 scheme, rest = link.split(':', 1)
448 if (not scheme or scheme == 'mailto') and re.match(mail_re, rest, re.I):
449 return 'mailto:' + link
450 if not scheme and re.match(url_re, rest, re.I):
451 return 'http://' + rest
457 if isinstance(obj, basestring):
458 return cgi.escape(obj, True)
462 # find out our URL, needed for syndication
464 n = os.environ['SERVER_NAME']
465 p = os.environ['SERVER_PORT']
466 s = os.environ['SCRIPT_NAME']
469 full_url = 'http://%s%s%s' % (n, p, s)
471 full_url = 'Not needed'
474 class Templates (object):
475 def __init__(self, tpath, db, showyear = None):
478 now = datetime.datetime.now()
490 'showyear': showyear,
491 'monthlinks': ' '.join(db.get_month_links(showyear)),
492 'yearlinks': ' '.join(db.get_year_links()),
495 def get_template(self, page_name, default_template, extra_vars = None):
496 if extra_vars is None:
499 vars = self.vars.copy()
500 vars.update(extra_vars)
502 p = '%s/%s.html' % (self.tpath, page_name)
503 if os.path.isfile(p):
504 return open(p).read() % vars
505 return default_template % vars
507 def get_main_header(self):
508 return self.get_template('header', default_main_header)
510 def get_main_footer(self):
511 return self.get_template('footer', default_main_footer)
513 def get_article_header(self, article):
514 return self.get_template(
515 'art_header', default_article_header, article.to_vars())
517 def get_article_footer(self, article):
518 return self.get_template(
519 'art_footer', default_article_footer, article.to_vars())
521 def get_comment_header(self, comment):
522 vars = comment.to_vars()
524 vars['linked_author'] = '<a href="%s">%s</a>' \
525 % (comment.link, comment.author)
527 vars['linked_author'] = comment.author
528 return self.get_template(
529 'com_header', default_comment_header, vars)
531 def get_comment_footer(self, comment):
532 return self.get_template(
533 'com_footer', default_comment_footer, comment.to_vars())
535 def get_comment_form(self, article, form_data, captcha_puzzle):
536 vars = article.to_vars()
537 vars.update(form_data.to_vars(self))
538 vars['captcha_puzzle'] = captcha_puzzle
539 return self.get_template(
540 'com_form', default_comment_form, vars)
542 def get_comment_error(self, error):
543 return self.get_template(
544 'com_error', default_comment_error, dict(error=error))
547 class CommentFormData (object):
548 def __init__(self, author = '', link = '', captcha = '', body = ''):
551 self.captcha = captcha
553 self.author_error = ''
555 self.captcha_error = ''
560 def to_vars(self, template):
561 render_error = template.get_comment_error
562 a_error = self.author_error and render_error(self.author_error)
563 l_error = self.link_error and render_error(self.link_error)
564 c_error = self.captcha_error \
565 and render_error(self.captcha_error)
566 b_error = self.body_error and render_error(self.body_error)
568 'form_author': sanitize(self.author),
569 'form_link': sanitize(self.link),
570 'form_captcha': sanitize(self.captcha),
571 'form_body': sanitize(self.body),
573 'form_author_error': a_error,
574 'form_link_error': l_error,
575 'form_captcha_error': c_error,
576 'form_body_error': b_error,
578 'form_action': self.action,
579 'form_method': self.method,
583 class Comment (object):
584 def __init__(self, article, number, created = None):
585 self.article = article
588 self.created = datetime.datetime.now()
590 self.created = created
595 self._author = author
597 self._raw_content = 'Removed comment'
600 def get_author(self):
604 author = property(fget = get_author)
610 link = property(fget = get_link)
612 def get_raw_content(self):
615 return self._raw_content
616 raw_content = property(fget = get_raw_content)
619 def set(self, author, raw_content, link = '', created = None):
621 self._author = author
622 self._raw_content = raw_content
624 self.created = created or datetime.datetime.now()
628 filename = os.path.join(comments_path, self.article.uuid,
631 raw = open(filename).readlines()
638 name, value = l.split(':', 1)
639 if name.lower() == 'author':
640 self._author = value.strip()
641 elif name.lower() == 'link':
642 self._link = value.strip()
647 self._raw_content = ''.join(raw[count + 1:])
651 filename = os.path.join(comments_path, self.article.uuid,
654 f = open(filename, 'w')
655 f.write('Author: %s\n' % self.author)
656 f.write('Link: %s\n' % self.link)
658 f.write(self.raw_content)
664 return rst_to_html(self.raw_content)
668 'number': self.number,
669 'author': sanitize(self.author),
670 'link': sanitize(self.link),
671 'date': self.created.isoformat(' '),
672 'created': self.created.isoformat(' '),
674 'year': self.created.year,
675 'month': self.created.month,
676 'day': self.created.day,
677 'hour': self.created.hour,
678 'minute': self.created.minute,
679 'second': self.created.second,
682 class CommentDB (object):
683 def __init__(self, article):
684 self.path = os.path.join(comments_path, article.uuid)
688 def load(self, article):
690 f = open(os.path.join(self.path, 'db'))
695 # Each line has the following comma separated format:
696 # number, created (epoch)
697 # Empty lines are meaningful and represent removed
698 # comments (so we can preserve the comment number)
702 d = datetime.datetime.fromtimestamp(float(l[1]))
704 # Removed/invalid comment
705 self.comments.append(None)
707 self.comments.append(Comment(article, n, d))
710 old_db = os.path.join(self.path, 'db')
711 new_db = os.path.join(self.path, 'db.tmp')
712 f = open(new_db, 'w')
713 for c in self.comments:
717 s += str(c.number) + ', '
718 s += str(time.mktime(c.created.timetuple()))
722 os.rename(new_db, old_db)
725 class Article (object):
726 def __init__(self, path, created = None, updated = None):
728 self.created = created
729 self.updated = updated
730 self.uuid = "%08x" % zlib.crc32(self.path)
735 self._title = 'Removed post'
736 self._author = author
738 self._raw_content = ''
746 title = property(fget = get_title)
748 def get_author(self):
752 author = property(fget = get_author)
758 tags = property(fget = get_tags)
760 def get_raw_content(self):
763 return self._raw_content
764 raw_content = property(fget = get_raw_content)
766 def get_comments(self):
769 return self._comments
770 comments = property(fget = get_comments)
773 def __cmp__(self, other):
774 if self.path == other.path:
778 if not other.created:
780 if self.created < other.created:
784 def title_cmp(self, other):
785 return cmp(self.title, other.title)
788 def add_comment(self, author, raw_content, link = ''):
789 c = Comment(self, len(self.comments))
790 c.set(author, raw_content, link)
791 self.comments.append(c)
796 # XXX this tweak is only needed for old DB format, where
797 # article's paths started with a slash
799 if path.startswith('/'):
801 filename = os.path.join(data_path, path)
803 raw = open(filename).readlines()
810 name, value = l.split(':', 1)
811 if name.lower() == 'title':
812 self._title = value.strip()
813 elif name.lower() == 'author':
814 self._author = value.strip()
815 elif name.lower() == 'tags':
816 ts = value.split(',')
817 ts = [t.strip() for t in ts]
823 self._raw_content = ''.join(raw[count + 1:])
825 self._comments = db.comments
829 return rst_to_html(self.raw_content)
833 'arttitle': sanitize(self.title),
834 'author': sanitize(self.author),
835 'date': self.created.isoformat(' '),
837 'tags': self.get_tags_links(),
838 'comments': len(self.comments),
840 'created': self.created.isoformat(' '),
841 'ciso': self.created.isoformat(),
842 'cyear': self.created.year,
843 'cmonth': self.created.month,
844 'cday': self.created.day,
845 'chour': self.created.hour,
846 'cminute': self.created.minute,
847 'csecond': self.created.second,
849 'updated': self.updated.isoformat(' '),
850 'uiso': self.updated.isoformat(),
851 'uyear': self.updated.year,
852 'umonth': self.updated.month,
853 'uday': self.updated.day,
854 'uhour': self.updated.hour,
855 'uminute': self.updated.minute,
856 'usecond': self.updated.second,
859 def get_tags_links(self):
861 tags = list(self.tags)
864 l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
865 (blog_url, urllib.quote(t), sanitize(t) ))
869 class ArticleDB (object):
870 def __init__(self, dbpath):
874 self.actyears = set()
875 self.actmonths = set()
878 def get_articles(self, year = 0, month = 0, day = 0, tags = None):
880 for a in self.articles:
881 if year and a.created.year != year: continue
882 if month and a.created.month != month: continue
883 if day and a.created.day != day: continue
884 if tags and not tags.issubset(a.tags): continue
890 def get_article(self, uuid):
891 return self.uuids[uuid]
895 f = open(self.dbpath)
900 # Each line has the following comma separated format:
901 # path (relative to data_path), \
910 datetime.datetime.fromtimestamp(float(l[1])),
911 datetime.datetime.fromtimestamp(float(l[2])))
912 self.uuids[a.uuid] = a
913 self.actyears.add(a.created.year)
914 self.actmonths.add((a.created.year, a.created.month))
915 self.articles.append(a)
918 f = open(self.dbpath + '.tmp', 'w')
919 for a in self.articles:
922 s += str(time.mktime(a.created.timetuple())) + ', '
923 s += str(time.mktime(a.updated.timetuple())) + '\n'
926 os.rename(self.dbpath + '.tmp', self.dbpath)
928 def get_year_links(self):
929 yl = list(self.actyears)
930 yl.sort(reverse = True)
931 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
934 def get_month_links(self, year):
935 am = [ i[1] for i in self.actmonths if i[0] == year ]
937 for i in range(1, 13):
938 name = calendar.month_name[i][:3]
940 s = '<a href="%s/%d/%d/">%s</a>' % \
941 ( blog_url, year, i, name )
951 def render_comments(article, template, form_data):
952 print '<a name="comments" />'
953 for c in article.comments:
956 print template.get_comment_header(c)
958 print template.get_comment_footer(c)
960 form_data = CommentFormData()
961 form_data.action = blog_url + '/comment/' + article.uuid + '#comment'
962 captcha = Captcha(article)
963 print template.get_comment_form(article, form_data, captcha.puzzle)
965 def render_html(articles, db, actyear = None, show_comments = False,
966 redirect = None, form_data = None):
968 print 'Status: 303 See Other\r\n',
969 print 'Location: %s\r\n' % redirect,
970 print 'Content-type: text/html; charset=utf-8\r\n',
972 template = Templates(templates_path, db, actyear)
973 print template.get_main_header()
975 print template.get_article_header(a)
977 print template.get_article_footer(a)
979 render_comments(a, template, form_data)
980 print template.get_main_footer()
982 def render_artlist(articles, db, actyear = None):
983 template = Templates(templates_path, db, actyear)
984 print 'Content-type: text/html; charset=utf-8\n'
985 print template.get_main_header()
986 print '<h2>Articles</h2>'
988 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
994 print template.get_main_footer()
996 def render_atom(articles):
997 if len(articles) > 0:
998 updated = articles[0].updated.isoformat()
1000 updated = datetime.datetime.now().isoformat()
1002 print 'Content-type: application/atom+xml; charset=utf-8\n'
1003 print """<?xml version="1.0" encoding="utf-8"?>
1005 <feed xmlns="http://www.w3.org/2005/Atom">
1006 <title>%(title)s</title>
1007 <link rel="alternate" type="text/html" href="%(url)s"/>
1008 <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
1009 <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
1010 <updated>%(updated)sZ</updated>
1022 'contents': a.to_html(),
1026 <title>%(arttitle)s</title>
1027 <author><name>%(author)s</name></author>
1028 <link href="%(url)s/post/%(uuid)s" />
1029 <id>%(url)s/post/%(uuid)s</id>
1030 <summary>%(arttitle)s</summary>
1031 <published>%(ciso)sZ</published>
1032 <updated>%(uiso)sZ</updated>
1033 <content type="xhtml">
1034 <div xmlns="http://www.w3.org/1999/xhtml"><p>
1044 print 'Content-type: text/css\r\n\r\n',
1048 import cgitb; cgitb.enable()
1050 form = cgi.FieldStorage()
1051 year = int(form.getfirst("year", 0))
1052 month = int(form.getfirst("month", 0))
1053 day = int(form.getfirst("day", 0))
1054 tags = set(form.getlist("tag"))
1059 post_preview = False
1063 if os.environ.has_key('PATH_INFO'):
1064 path_info = os.environ['PATH_INFO']
1065 style = path_info == '/style'
1066 atom = path_info == '/atom'
1067 tag = path_info.startswith('/tag/')
1068 post = path_info.startswith('/post/')
1069 post_preview = path_info.startswith('/preview/post/')
1070 artlist = path_info.startswith('/list')
1071 comment = path_info.startswith('/comment/') and enable_comments
1072 if not style and not atom and not post and not post_preview \
1073 and not tag and not comment and not artlist:
1074 date = path_info.split('/')[1:]
1076 if len(date) > 1 and date[0]:
1078 if len(date) > 2 and date[1]:
1079 month = int(date[1])
1080 if len(date) > 3 and date[2]:
1085 uuid = path_info.replace('/post/', '')
1086 uuid = uuid.replace('/', '')
1088 art_path = path_info.replace('/preview/post/', '')
1089 art_path = urllib.unquote_plus(art_path)
1090 art_path = os.path.join(data_path, art_path)
1091 art_path = os.path.realpath(art_path)
1092 common = os.path.commonprefix([data_path, art_path])
1093 if common != data_path: # something nasty happened
1094 post_preview = False
1095 art_path = art_path[len(data_path)+1:]
1097 t = path_info.replace('/tag/', '')
1098 t = t.replace('/', '')
1099 t = urllib.unquote_plus(t)
1102 uuid = path_info.replace('/comment/', '')
1103 uuid = uuid.replace('#comment', '')
1104 uuid = uuid.replace('/', '')
1105 author = form.getfirst('comformauthor', '')
1106 link = form.getfirst('comformlink', '')
1107 captcha = form.getfirst('comformcaptcha', '')
1108 body = form.getfirst('comformbody', '')
1110 db = ArticleDB(os.path.join(data_path, 'db'))
1112 articles = db.get_articles(tags = tags)
1113 articles.sort(reverse = True)
1114 render_atom(articles[:10])
1118 render_html( [db.get_article(uuid)], db, year, enable_comments )
1120 article = Article(art_path, datetime.datetime.now(),
1121 datetime.datetime.now())
1122 render_html( [article], db, year, enable_comments )
1124 articles = db.get_articles()
1125 articles.sort(cmp = Article.title_cmp)
1126 render_artlist(articles, db)
1128 form_data = CommentFormData(author.strip().replace('\n', ' '),
1129 link.strip().replace('\n', ' '), captcha,
1130 body.replace('\r', ''))
1131 article = db.get_article(uuid)
1132 captcha = Captcha(article)
1135 if not form_data.author:
1136 form_data.author_error = 'please, enter your name'
1139 link = valid_link(form_data.link)
1141 form_data.link = link
1143 form_data.link_error = 'please, enter a ' \
1146 if not captcha.validate(form_data):
1147 form_data.captcha_error = captcha.help
1149 if not form_data.body:
1150 form_data.body_error = 'please, write a comment'
1153 error = validate_rst(form_data.body, secure=False)
1154 if error is not None:
1155 (line, desc, ctx) = error
1158 at = ' at line %d' % line
1159 form_data.body_error = 'error%s: %s' % (at, desc)
1162 c = article.add_comment(form_data.author,
1163 form_data.body, form_data.link)
1165 cdb = CommentDB(article)
1166 cdb.comments = article.comments
1168 redirect = blog_url + '/post/' + uuid + '#comment-' \
1170 render_html( [article], db, year, enable_comments, redirect,
1173 articles = db.get_articles(year, month, day, tags)
1174 articles.sort(reverse = True)
1175 if not year and not month and not day and not tags:
1176 articles = articles[:10]
1177 render_html(articles, db, year)
1181 print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
1184 if len(sys.argv) != 3:
1189 art_path = os.path.realpath(sys.argv[2])
1191 if os.path.commonprefix([data_path, art_path]) != data_path:
1192 print "Error: article (%s) must be inside data_path (%s)" % \
1193 (art_path, data_path)
1195 art_path = art_path[len(data_path)+1:]
1197 db_filename = os.path.join(data_path, 'db')
1198 if not os.path.isfile(db_filename):
1199 open(db_filename, 'w').write('')
1200 db = ArticleDB(db_filename)
1203 article = Article(art_path, datetime.datetime.now(),
1204 datetime.datetime.now())
1205 for a in db.articles:
1207 print 'Error: article already exists'
1209 db.articles.append(article)
1212 comment_dir = os.path.join(comments_path, article.uuid)
1214 os.mkdir(comment_dir, 0775)
1216 if e.errno != errno.EEXIST:
1217 print "Error: can't create comments " \
1218 "directory %s (%s)" \
1220 # otherwise is probably a removed and re-added
1223 article = Article(art_path)
1224 for a in db.articles:
1228 print "Error: no such article"
1231 r = raw_input('Remove comments [y/N]? ')
1232 db.articles.remove(a)
1234 if enable_comments and r.lower() == 'y':
1235 shutil.rmtree(os.path.join(comments_path, a.uuid))
1236 elif cmd == 'update':
1237 article = Article(art_path)
1238 for a in db.articles:
1242 print "Error: no such article"
1244 a.updated = datetime.datetime.now()
1253 if os.environ.has_key('GATEWAY_INTERFACE'):
1256 sys.exit(handle_cmd())