Ticket #2927: migrate-tracblog.2.py

File migrate-tracblog.2.py, 6.5 kB (added by mfisk@lanl.gov, 6 months ago)

With bugfixes to avoid SQL errors

Line 
1 #!/bin/env python
2
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2008 John Hampton <pacopablo@pacopablo.com>
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
9 # are met:
10 #
11 # 1. Redistributions of source code must retain the above copyright
12 #    notice, this list of conditions and the following disclaimer.
13 # 2. Redistributions in binary form must reproduce the above copyright
14 #    notice, this list of conditions and the following disclaimer in
15 #    the documentation and/or other materials provided with the
16 #    distribution.
17 # 3. The name of the author may not be used to endorse or promote
18 #    products derived from this software without specific prior
19 #    written permission.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS
22 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
25 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
27 # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33 # Author: John Hampton <pacopablo@pacopablo.com>
34
35 import sys
36 import time
37 import re
38 import os
39 from optparse import OptionParser
40
41 from trac.env import Environment
42 from trac.wiki.model import WikiPage
43 from trac.test import Mock, MockPerm
44
45
46 _title_split_match = re.compile(r'\s*^=+\s+([^\n\r=]+?)\s+=+\s+(.+)$',
47                                 re.MULTILINE|re.DOTALL).match
48
49 _tag_split = re.compile('[,\s]+')
50
51 def split_tags(tags):
52     """ Split the tags into a list """
53     return  [t.strip() for t in _tag_split.split(tags) if t.strip()]
54
55 def epochtime(t):
56     """ Return seconds from epoch from a datetime object """
57     return int(time.mktime(t.timetuple()))
58
59 def insert_blog_post(cur, name, version, title, body, publish_time,
60                      version_time, version_comment, version_author,
61                      author, categories):
62     """ Insert the post into the FullBlog tables """
63     try:
64         print >>sys.stderr, name
65         cur.execute("INSERT INTO fullblog_posts "
66                     "(name, version, title, body, publish_time, version_time, "
67                     "version_comment, version_author, author, categories) "
68                     "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
69                     (name, version, title, body, epochtime(publish_time),
70                     epochtime(version_time), version_comment, version_author,
71                     author, categories))
72
73         #cnx.commit()
74     except:
75         print >>sys.stderr, "Unable to insert %s into the FullBlog" % name
76         import traceback
77         traceback.print_exc()
78         print >>sys.stderr, "------"
79
80 def Main(opts):
81     """ Cross your fingers and pray """
82     env = Environment(opts.envpath)
83     from tractags.api import TagSystem
84
85     tlist = opts.tags or split_tags(env.config.get('blog', 'default_tag',
86                                                    'blog'))
87     tags = TagSystem(env)
88     req = Mock(perm=MockPerm())
89     blog = tags.query(req, ' '.join(tlist + ['realm:wiki']))
90     cnx = env.get_db_cnx()
91     cur = cnx.cursor()
92                    
93     for resource, page_tags in blog:
94         try:
95             page = WikiPage(env, version=1, name=resource.id)
96             _, publish_time, author, _, _ =  page.get_history().next()
97             if opts.deleteonly:
98                 page.delete()
99                 continue
100             categories = ' '.join([t for t in page_tags if t not in tlist])
101             page = WikiPage(env, name=resource.id)
102             for version, version_time, version_author, version_comment, \
103                 _ in page.get_history():
104                 # Currently the basename of the post url is used due to
105                 # http://trac-hacks.org/ticket/2956
106                 name = resource.id.replace('/', '_')
107                 # extract title from text:
108                 fulltext = page.text
109                 match = _title_split_match(fulltext)
110                 if match:
111                     title = match.group(1)
112                     fulltext = match.group(2)
113                 else:
114                     title = name
115                 body = fulltext
116                 insert_blog_post(cur, name, version, title, body,
117                                  publish_time, version_time,
118                                  version_comment, version_author, author,
119                                  categories)
120                 continue
121             if opts.delete:
122                 page.delete()
123                 continue
124         except:
125             env.log.debug("Error loading wiki page %s" % resource.id,
126                           exc_info=True)
127             continue
128
129     cnx.commit()
130     cur.close()
131     return 0
132    
133
134 def doArgs():
135     """Parse command line options"""
136     description = "%prog is used to migrate posts from TracBlogPlugin to " \
137                   "FullBlogPlugin."
138
139     parser = OptionParser(usage="usage: %prog [options] [environment]",
140                           version="1.0", description=description)
141     parser.add_option("-d", "--delete", dest="delete", action="store_true",
142                       help="Delete the TracBlog posts from the wiki after "
143                       "migration", default=False)
144     parser.add_option("", "--delete-only", dest="deleteonly",
145                       action="store_true", help="Only delete the TracBlog "
146                       "posts from the wiki.  Do not perform any migration "
147                       "steps", default=False)
148     parser.add_option("-t", "--tags", dest="tags", type="string",
149                       help="Comma separated list of tags specifying blog "
150                       "posts.  If not specified, the `default_tag` value "
151                       "from trac.ini is used.", metavar="<list>",
152                       default=None)
153     (options, args) = parser.parse_args()
154     if len(args) < 1:
155         print("You must specify a Trac environment")
156         sys.exit(1)
157     options.envpath = args[0]
158     if not os.path.exists(options.envpath):
159         print("The path >%s< does not exist.  Please specify an existing "
160               "path." % options.envpath)
161         sys.exit(1)
162     options.args = args
163     return options
164
165 if __name__ == '__main__':
166     options = doArgs()
167     rc = Main(options)
168     sys.exit(rc)