1c2eb7a5d23af52bb21f202284b79a87b8a82bc7
[python/fast-export.git] / svn-fast-export.py
1 #!/usr/bin/python
2 #
3 # svn-fast-export.py
4 # ----------
5 #  Walk through each revision of a local Subversion repository and export it
6 #  in a stream that git-fast-import can consume.
7 #
8 # Author: Chris Lee <clee@kde.org>
9 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
10
11 trunk_path = '/trunk/'
12 branches_path = '/branches/'
13 tags_path = '/tags/'
14
15 first_rev = 1
16 final_rev = 0
17
18 import gc, sys, os.path
19 from optparse import OptionParser
20 from time import sleep, mktime, localtime, strftime, strptime
21 from svn.fs import svn_fs_dir_entries, svn_fs_file_length, svn_fs_file_contents, svn_fs_is_dir, svn_fs_revision_root, svn_fs_youngest_rev, svn_fs_revision_proplist, svn_fs_revision_prop, svn_fs_paths_changed
22 from svn.core import svn_pool_create, svn_pool_clear, svn_pool_destroy, svn_stream_read, svn_stream_close, run_app
23 from svn.repos import svn_repos_open, svn_repos_fs
24
25 ct_short = ['M', 'A', 'D', 'R', 'X']
26
27 def dump_file_blob(root, full_path, pool):
28     # Use an iteration subpool.
29     subpool = svn_pool_create(pool)
30
31     # Clear the iteration subpool.
32     svn_pool_clear(subpool)
33
34     # print full_path
35     stream_length = svn_fs_file_length(root, full_path, subpool)
36     stream = svn_fs_file_contents(root, full_path, subpool)
37     contents = svn_stream_read(stream, int(stream_length))
38     sys.stdout.write("data %s\n" % stream_length)
39     sys.stdout.write(contents)
40     sys.stdout.write("\n")
41
42     # Destroy the iteration subpool.
43     svn_pool_destroy(subpool)
44
45
46 def export_revision(rev, repo, fs, pool):
47     sys.stderr.write("Exporting revision %s... " % rev)
48
49     revpool = svn_pool_create(pool)
50     svn_pool_clear(revpool)
51
52     # Open a root object representing the youngest (HEAD) revision.
53     root = svn_fs_revision_root(fs, rev, revpool)
54
55     # And the list of what changed in this revision.
56     changes = svn_fs_paths_changed(root, revpool)
57
58     i = 1
59     marks = {}
60     file_changes = []
61
62     for path, change_type in changes.iteritems():
63         c_t = ct_short[change_type.change_kind]
64         if svn_fs_is_dir(root, path, revpool):
65             continue
66
67         if not path.startswith(trunk_path):
68             # We don't handle branches. Or tags. Yet.
69             pass
70         else:
71             if c_t == 'D':
72                 file_changes.append("D %s" % path.replace(trunk_path, ''))
73             else:
74                 sys.stdout.write("blob\nmark :%s\n" % i)
75                 marks[i] = path.replace(trunk_path, '')
76                 # dump_file_blob(root_obj, path, revpool)
77                 file_changes.append("M 644 :%s %s" % (i, marks[i]))
78                 i += 1
79
80     # Get the commit author and message
81     props = svn_fs_revision_proplist(fs, rev, revpool)
82
83     # Do the recursive crawl.
84     if props.has_key('svn:author'):
85         author = "%s <%s@localhost>" % (props['svn:author'], props['svn:author'])
86     else:
87         author = 'nobody <nobody@localhost>'
88
89     if len(file_changes) == 0:
90         svn_pool_destroy(revpool)
91         sys.stderr.write("skipping.\n")
92         return
93
94     svndate = props['svn:date'][0:-8]
95     commit_time = mktime(strptime(svndate, '%Y-%m-%dT%H:%M:%S'))
96     sys.stdout.write("commit refs/heads/master\n")
97     #sys.stdout.write("committer %s %s -0000\n" % (author, int(commit_time)))
98     #sys.stdout.write("data %s\n" % len(props['svn:log']))
99     #sys.stdout.write(props['svn:log'])
100     #sys.stdout.write("\n")
101     sys.stdout.write('\n'.join(file_changes))
102     sys.stdout.write("\n\n")
103
104     svn_pool_destroy(revpool)
105     sys.stderr.write("done!\n")
106
107     #if rev % 1000 == 0:
108     #    sys.stderr.write("gc: %s objects\n" % len(gc.get_objects()))
109     #    sleep(5)
110
111
112 def crawl_revisions(pool, repos_path):
113     """Open the repository at REPOS_PATH, and recursively crawl all its
114     revisions."""
115     global final_rev
116
117     # Open the repository at REPOS_PATH, and get a reference to its
118     # versioning filesystem.
119     repos_obj = svn_repos_open(repos_path, pool)
120     fs_obj = svn_repos_fs(repos_obj)
121
122     # Query the current youngest revision.
123     youngest_rev = svn_fs_youngest_rev(fs_obj, pool)
124
125
126     first_rev = 1
127     if final_rev == 0:
128         final_rev = youngest_rev
129     for rev in xrange(first_rev, final_rev + 1):
130         export_revision(rev, repos_obj, fs_obj, pool)
131
132
133 if __name__ == '__main__':
134     usage = '%prog [options] REPOS_PATH'
135     parser = OptionParser()
136     parser.set_usage(usage)
137     parser.add_option('-f', '--final-rev', help='Final revision to import', 
138                       dest='final_rev', metavar='FINAL_REV', type='int')
139     parser.add_option('-t', '--trunk-path', help='Path in repo to /trunk',
140                       dest='trunk_path', metavar='TRUNK_PATH')
141     parser.add_option('-b', '--branches-path', help='Path in repo to /branches',
142                       dest='branches_path', metavar='BRANCHES_PATH')
143     parser.add_option('-T', '--tags-path', help='Path in repo to /tags',
144                       dest='tags_path', metavar='TAGS_PATH')
145     (options, args) = parser.parse_args()
146
147     if options.trunk_path != None:
148         trunk_path = options.trunk_path
149     if options.branches_path != None:
150         branches_path = options.branches_path
151     if options.tags_path != None:
152         tags_path = options.tags_path
153     if options.final_rev != None:
154         final_rev = options.final_rev
155
156     if len(args) != 1:
157         parser.print_help()
158         sys.exit(2)
159
160     # Canonicalize (enough for Subversion, at least) the repository path.
161     repos_path = os.path.normpath(args[0])
162     if repos_path == '.': 
163         repos_path = ''
164
165     # Call the app-wrapper, which takes care of APR initialization/shutdown
166     # and the creation and cleanup of our top-level memory pool.
167     run_app(crawl_revisions, repos_path)