13B0LEy9ZQAGOybTWJzJJQ changeset

Changeset646465363833 (b)
ParentNone (a)
ab
0+#!/usr/bin/env python
0+# Licensed to the Apache Software Foundation (ASF) under one or more
0+# contributor license agreements.  See the NOTICE file distributed with
0+# this work for additional information regarding copyright ownership.
0+# The ASF licenses this file to you under the Apache License, Version 2.0
0+# (the "License"); you may not use this file except in compliance with
0+# the License.  You may obtain a copy of the License at
0+#
0+#     http://www.apache.org/licenses/LICENSE-2.0
0+#
0+# Unless required by applicable law or agreed to in writing, software
0+# distributed under the License is distributed on an "AS IS" BASIS,
0+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0+# See the License for the specific language governing permissions and
0+# limitations under the License.
0+
0+import optparse as op
0+import os
0+import re
0+import subprocess as sp
0+import sys
0+import tempfile
0+import textwrap
0+import urlparse
0+
0+
0+__usage__ = "%prog [OPTIONS] SVN_PATH GIT_DIR"
0+
0+SVN_BASE = "https://svn.apache.org/repos/asf/"
0+REF_RE = re.compile("refs/remotes/([^@]+)")
0+
0+
0+def options():
0+    return [
0+        op.make_option('-a', '--authors', metavar="FILE", dest="authors",
0+            default="/usr/local/etc/asf-authors",
0+            help="Path to the ASF authors file."),
0+        op.make_option('-d', '--description', metavar="DESC", dest='desc',
0+            help="A short project description. ie, 'Apache Jackrabbit'")
0+    ]
0+
0+
0+def main():
0+    parser = op.OptionParser(usage=__usage__, option_list=options())
0+    opts, args = parser.parse_args()
0+
0+    if len(args) == 0:
0+        parser.error("Missing required SVN_URL and GIT_DIR arguments.")
0+    if len(args) == 1:
0+        parser.error("Missing required GIT_DIR argument.")
0+    if len(args) > 2:
0+        parser.error("Unknown arguments: %s" % ", ".join(args[2:]))
0+
0+    svn_url = urlparse.urljoin(SVN_BASE, args[0].lstrip().lstrip("/"))
0+    git_dir = args[1]
0+    os.putenv("GIT_DIR", git_dir)
0+
0+    if opts.authors is None:
0+        opts.authors = "/usr/local/etc/asf-authors"
0+
0+    if os.path.exists(git_dir):
0+        error("Git directory exists: %s" % git_dir)
0+    if not os.path.exists(opts.authors):
0+        error("Missing authors file: %s" % opts.authors)
0+
0+    init_git_dir(git_dir, svn_url, opts.desc)
0+    clone_svn(git_dir, opts.authors)
0+    cleanup_clone()
0+    configure_asfgit(git_dir)
0+
0+
0+def init_git_dir(git_dir, svn_url, desc):
0+    log("Creating mirror in: %s" % git_dir)
0+
0+    git("svn", "init", "-s", svn_url)
0+    git("config", "gitweb.owner", "The Apache Software Foundation")
0+    save(os.path.join(git_dir, "HEAD"), "ref: refs/heads/trunk")
0+    git("update-server-info")
0+   
0+    if desc is None:
0+        desc = run_editor(initial="Project description, ie 'Apache Jackrabbit'")
0+    if desc is None:
0+        error("No repository description provided.")
0+    save(os.path.join(git_dir, "description"), desc)
0+
0+
0+def clone_svn(git_dir, authors):
0+    log("Initializing Git repository.")
0+    git("svn", "fetch", "--authors-file", authors, "--log-window-size=10000")
0+   
0+    log("Updating branch refs.")
0+    refs = git("for-each-ref", "refs/remotes", capture=True)
0+    for ref in refs.splitlines():
0+        match = REF_RE.match(ref.split()[-1])
0+        if not match:
0+            continue
0+        ref = match.group(1)
0+        if ref.startswith("tags/"):
0+            continue
0+        git("update-ref", "refs/heads/%s" % ref, "refs/remotes/%s" % ref)
0+
0+    log("Creating Git tags from SVN pseudo-tags")
0+    refs = git("for-each-ref", "refs/remotes/tags", capture=True)
0+    for ref in refs.splitlines():
0+        ref = ref.split()[-1]
0+        if ref.find("@") >= 0:
0+            continue
0+        tag = ref.split("/", 3)[-1]
0+
0+        for opt in ("name", "email", "date"):
0+            fmt = "--format=%%(committer%s)" % opt
0+            val = git("for-each-ref", fmt, ref, capture=True).strip()
0+            os.putenv("GIT_COMMITTER_%s" % opt.upper(), val)
0+        git("tag", "-f", "-m", tag, tag, ref)
0+
0+
0+def cleanup_clone():
0+    log("Cleaning up new Git clone.")
0+    git("update-server-info")
0+    git("gc", "--aggressive")
0+
0+
0+def configure_asfgit(git_dir):
0+    asfgit = os.getenv("ASFGIT_ADMIN") or "/usr/local/etc/asfgit-admin"
0+    if not os.path.exists(asfgit):
0+        log("WARNING: asfgit-admin directory not found.")
0+        log("WARNING: Skipping hosting configuration.")
0+        return
0+   
0+    log("Installing hook symlinks.")
0+    for name in ("pre-receive", "post-receive"):
0+        src = os.path.abspath(os.path.join(asfgit, "hooks", name))
0+        dst = os.path.join(git_dir, "hooks", name)
0+        if not os.path.exists(src):
0+            error("Missing pre-receive hook: %s" % name)
0+        if os.path.exists(dst):
0+            os.unlink(dst)
0+        os.symlink(src, dst)
0+   
0+    log("Initializaing hosting configuration")
0+
0+    cfgfile = os.path.join(asfgit, "conf", "gitconfig")
0+    dstfile = os.path.join(git_dir, "config")
0+   
0+    # Make sure it hasn't already been initialized
0+    try:
0+        sp.check_output(["git", "config", "hooks.asfgit.debug"])
0+        added = True
0+    except sp.CalledProcessError:
0+        added = False
0+
0+    if not added:
0+        # Get base config
0+        if not os.path.exists(cfgfile):
0+            error("Missing default git configuration: %s" % cfgfile)
0+        with open(cfgfile) as handle:
0+            config = handle.read()
0+        git_repo = os.path.basename(git_dir)
0+        config = config % {"git_repo": git_repo}
0+
0+        # Append the config data to the git config
0+        # and let the user review it.
0+        if not os.path.exists(dstfile):
0+            error("Missing destinationg git config: %s" % dstfile)
0+        with open(dstfile, "a") as handle:
0+            handle.write(config)
0+       
0+    # Boot the user's editor to review the conifg.
0+    run_editor(filename=dstfile)
0+   
0+    # Final steps
0+    git_repo = os.path.basename(git_dir)
0+    log(textwrap.dedent("""\
0+       
0+       
0+        To finish the hosting configuration you need to copy %(git_repo)s to
0+        the repository hosting directory and run the following:
0+             
0+          $ sudo chown -R nobody:daemon $(REPOS)/%(git_repo)s
0+          $ sudo chmod g+x $(REPOS)/%(git_repo)s
0+       
0+        At the time of this writing, $(REPOS) should be:
0+       
0+          /usr/local/www/git-wip-us.apache.org/repos/asf
0+       
0+        """ % {"git_repo": git_repo}))
0+   
0+
0+
0+def run_editor(filename=None, initial=""):
0+    editor = os.getenv("EDITOR", "nano")
0+    if filename is None:
0+        with tempfile.NamedTemporaryFile(delete=False) as tf:
0+            fname = tf.name
0+            tf.write(initial)
0+    else:
0+        fname = filename
0+    try:
0+        if sp.call([editor, fname]) != 0:
0+            return None
0+        with open(fname) as handle:
0+            return handle.read()
0+    finally:
0+        if filename is None:
0+            os.remove(fname)
0+
0+
0+def git(cmd, *args, **kwargs):
0+    cmd = ["git", cmd] + list(args)
0+    if kwargs.pop("capture", False):
0+        return run(cmd, stderr=sp.STDOUT)
0+    sp.check_call(cmd)
0+
0+
0+def run(cmd, *args, **kwargs):
0+    if isinstance(cmd, list):
0+        return sp.check_output(cmd, **kwargs)
0+    else:
0+        return sp.check_output([cmd] + list(args), **kwargs)
0+
0+
0+def save(fname, contents):
0+    with open(fname, "w") as handle:
0+        handle.write(contents)
0+
0+
0+def log(mesg):
0+    sys.stderr.write("%s\n" % mesg)
0+
0+
0+def error(mesg, exit_code=1):
0+    sys.stderr.write("ERROR: %s\n" % mesg)
0+    sys.exit(exit_code)
0+
0+
0+if __name__ == '__main__':
0+    main()
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
--- Revision None
+++ Revision 646465363833
@@ -0,0 +1,237 @@
+#!/usr/bin/env python
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import optparse as op
+import os
+import re
+import subprocess as sp
+import sys
+import tempfile
+import textwrap
+import urlparse
+
+
+__usage__ = "%prog [OPTIONS] SVN_PATH GIT_DIR"
+
+SVN_BASE = "https://svn.apache.org/repos/asf/"
+REF_RE = re.compile("refs/remotes/([^@]+)")
+
+
+def options():
+ return [
+ op.make_option('-a', '--authors', metavar="FILE", dest="authors",
+ default="/usr/local/etc/asf-authors",
+ help="Path to the ASF authors file."),
+ op.make_option('-d', '--description', metavar="DESC", dest='desc',
+ help="A short project description. ie, 'Apache Jackrabbit'")
+ ]
+
+
+def main():
+ parser = op.OptionParser(usage=__usage__, option_list=options())
+ opts, args = parser.parse_args()
+
+ if len(args) == 0:
+ parser.error("Missing required SVN_URL and GIT_DIR arguments.")
+ if len(args) == 1:
+ parser.error("Missing required GIT_DIR argument.")
+ if len(args) > 2:
+ parser.error("Unknown arguments: %s" % ", ".join(args[2:]))
+
+ svn_url = urlparse.urljoin(SVN_BASE, args[0].lstrip().lstrip("/"))
+ git_dir = args[1]
+ os.putenv("GIT_DIR", git_dir)
+
+ if opts.authors is None:
+ opts.authors = "/usr/local/etc/asf-authors"
+
+ if os.path.exists(git_dir):
+ error("Git directory exists: %s" % git_dir)
+ if not os.path.exists(opts.authors):
+ error("Missing authors file: %s" % opts.authors)
+
+ init_git_dir(git_dir, svn_url, opts.desc)
+ clone_svn(git_dir, opts.authors)
+ cleanup_clone()
+ configure_asfgit(git_dir)
+
+
+def init_git_dir(git_dir, svn_url, desc):
+ log("Creating mirror in: %s" % git_dir)
+
+ git("svn", "init", "-s", svn_url)
+ git("config", "gitweb.owner", "The Apache Software Foundation")
+ save(os.path.join(git_dir, "HEAD"), "ref: refs/heads/trunk")
+ git("update-server-info")
+
+ if desc is None:
+ desc = run_editor(initial="Project description, ie 'Apache Jackrabbit'")
+ if desc is None:
+ error("No repository description provided.")
+ save(os.path.join(git_dir, "description"), desc)
+
+
+def clone_svn(git_dir, authors):
+ log("Initializing Git repository.")
+ git("svn", "fetch", "--authors-file", authors, "--log-window-size=10000")
+
+ log("Updating branch refs.")
+ refs = git("for-each-ref", "refs/remotes", capture=True)
+ for ref in refs.splitlines():
+ match = REF_RE.match(ref.split()[-1])
+ if not match:
+ continue
+ ref = match.group(1)
+ if ref.startswith("tags/"):
+ continue
+ git("update-ref", "refs/heads/%s" % ref, "refs/remotes/%s" % ref)
+
+ log("Creating Git tags from SVN pseudo-tags")
+ refs = git("for-each-ref", "refs/remotes/tags", capture=True)
+ for ref in refs.splitlines():
+ ref = ref.split()[-1]
+ if ref.find("@") >= 0:
+ continue
+ tag = ref.split("/", 3)[-1]
+
+ for opt in ("name", "email", "date"):
+ fmt = "--format=%%(committer%s)" % opt
+ val = git("for-each-ref", fmt, ref, capture=True).strip()
+ os.putenv("GIT_COMMITTER_%s" % opt.upper(), val)
+ git("tag", "-f", "-m", tag, tag, ref)
+
+
+def cleanup_clone():
+ log("Cleaning up new Git clone.")
+ git("update-server-info")
+ git("gc", "--aggressive")
+
+
+def configure_asfgit(git_dir):
+ asfgit = os.getenv("ASFGIT_ADMIN") or "/usr/local/etc/asfgit-admin"
+ if not os.path.exists(asfgit):
+ log("WARNING: asfgit-admin directory not found.")
+ log("WARNING: Skipping hosting configuration.")
+ return
+
+ log("Installing hook symlinks.")
+ for name in ("pre-receive", "post-receive"):
+ src = os.path.abspath(os.path.join(asfgit, "hooks", name))
+ dst = os.path.join(git_dir, "hooks", name)
+ if not os.path.exists(src):
+ error("Missing pre-receive hook: %s" % name)
+ if os.path.exists(dst):
+ os.unlink(dst)
+ os.symlink(src, dst)
+
+ log("Initializaing hosting configuration")
+
+ cfgfile = os.path.join(asfgit, "conf", "gitconfig")
+ dstfile = os.path.join(git_dir, "config")
+
+ # Make sure it hasn't already been initialized
+ try:
+ sp.check_output(["git", "config", "hooks.asfgit.debug"])
+ added = True
+ except sp.CalledProcessError:
+ added = False
+
+ if not added:
+ # Get base config
+ if not os.path.exists(cfgfile):
+ error("Missing default git configuration: %s" % cfgfile)
+ with open(cfgfile) as handle:
+ config = handle.read()
+ git_repo = os.path.basename(git_dir)
+ config = config % {"git_repo": git_repo}
+
+ # Append the config data to the git config
+ # and let the user review it.
+ if not os.path.exists(dstfile):
+ error("Missing destinationg git config: %s" % dstfile)
+ with open(dstfile, "a") as handle:
+ handle.write(config)
+
+ # Boot the user's editor to review the conifg.
+ run_editor(filename=dstfile)
+
+ # Final steps
+ git_repo = os.path.basename(git_dir)
+ log(textwrap.dedent("""\
+
+
+ To finish the hosting configuration you need to copy %(git_repo)s to
+ the repository hosting directory and run the following:
+
+ $ sudo chown -R nobody:daemon $(REPOS)/%(git_repo)s
+ $ sudo chmod g+x $(REPOS)/%(git_repo)s
+
+ At the time of this writing, $(REPOS) should be:
+
+ /usr/local/www/git-wip-us.apache.org/repos/asf
+
+ """ % {"git_repo": git_repo}))
+
+
+
+def run_editor(filename=None, initial=""):
+ editor = os.getenv("EDITOR", "nano")
+ if filename is None:
+ with tempfile.NamedTemporaryFile(delete=False) as tf:
+ fname = tf.name
+ tf.write(initial)
+ else:
+ fname = filename
+ try:
+ if sp.call([editor, fname]) != 0:
+ return None
+ with open(fname) as handle:
+ return handle.read()
+ finally:
+ if filename is None:
+ os.remove(fname)
+
+
+def git(cmd, *args, **kwargs):
+ cmd = ["git", cmd] + list(args)
+ if kwargs.pop("capture", False):
+ return run(cmd, stderr=sp.STDOUT)
+ sp.check_call(cmd)
+
+
+def run(cmd, *args, **kwargs):
+ if isinstance(cmd, list):
+ return sp.check_output(cmd, **kwargs)
+ else:
+ return sp.check_output([cmd] + list(args), **kwargs)
+
+
+def save(fname, contents):
+ with open(fname, "w") as handle:
+ handle.write(contents)
+
+
+def log(mesg):
+ sys.stderr.write("%s\n" % mesg)
+
+
+def error(mesg, exit_code=1):
+ sys.stderr.write("ERROR: %s\n" % mesg)
+ sys.exit(exit_code)
+
+
+if __name__ == '__main__':
+ main()