]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
Various refinements from our mass-upgrade run.
[wizard.git] / wizard / command / upgrade.py
1 import optparse
2 import sys
3 import distutils.version
4 import os
5 import shutil
6 import logging.handlers
7 import errno
8 import tempfile
9 import itertools
10
11 from wizard import command, deploy, shell, util
12
13 def main(argv, baton):
14     options, args = parse_args(argv, baton)
15     if args:
16         dir = args[0]
17     else:
18         dir = "."
19     shell.drop_priviledges(dir, options.log_file)
20     util.chdir(dir)
21     sh = shell.Shell()
22     util.set_git_env()
23     if options.continue_:
24         temp_wc_dir = os.getcwd()
25         user_commit, next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
26         repo = open(".git/WIZARD_REPO", "r").read()
27         version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
28         util.chdir(sh.eval("git", "config", "remote.origin.url"))
29         d = deploy.Deployment(".")
30         try:
31             sh.call("git", "status")
32             raise LocalChangesError()
33         except shell.CallError:
34             pass
35     else:
36         d = deploy.Deployment(".")
37         d.verify()
38         d.verifyTag(options.srv_path)
39         d.verifyGit(options.srv_path)
40         d.verifyConfigured()
41         d.verifyVersion()
42         repo = d.application.repository(options.srv_path)
43         version = calculate_newest_version(sh, repo)
44         if version == d.app_version.scripts_tag and not options.force:
45             raise AlreadyUpgraded
46         if not options.dry_run:
47             perform_pre_commit(sh)
48         temp_wc_dir = perform_tmp_clone(sh)
49         with util.ChangeDirectory(temp_wc_dir):
50             sh.call("git", "remote", "add", "scripts", repo)
51             sh.call("git", "fetch", "scripts")
52             user_commit, next_commit = calculate_parents(sh, version)
53             # save variables so that --continue will work
54             # yeah yeah no trailing newline whatever
55             open(".git/WIZARD_REPO", "w").write(repo)
56             open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
57             open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
58             perform_merge(sh, repo, d, version)
59     # variables: version, user_commit, next_commit, temp_wc_dir
60     with util.ChangeDirectory(temp_wc_dir):
61         message = make_commit_message(version)
62         new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
63         final_commit = sh.eval("git", "commit-tree", new_tree,
64                 "-p", user_commit, "-p", next_commit, input=message, log=True)
65         # a master branch may not necessarily exist if the user
66         # was manually installed to an earlier version
67         try:
68             sh.call("git", "checkout", "-b", "master", "--")
69         except shell.CallError:
70             sh.call("git", "checkout", "master", "--")
71         sh.call("git", "reset", "--hard", final_commit)
72     # Till now, all of our operations were in a tmp sandbox.
73     if options.dry_run:
74         logging.info("Dry run, bailing.  See results at %s" % temp_wc_dir)
75         return
76     # XXX: frob .htaccess to make site inaccessible
77     # XXX: need locking
78     # git merge (which performs a fast forward)
79     #   - merge could fail (race); that's /really/ dangerous.
80     sh.call("git", "pull", temp_wc_dir, "master")
81     # run update script
82     version_obj = distutils.version.LooseVersion(version.partition('-')[2])
83     d.application.upgrade(version_obj, options)
84     # XXX: frob .htaccess to make site accessible
85     # XXX:  - check if .htaccess changed, first.  Upgrade
86     #       process might have frobbed it.  Don't be
87     #       particularly worried if the segment dissappeared
88
89 def make_commit_message(version):
90     message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
91     try:
92         message += "\nUpgraded-by: " + util.get_operator_git()
93     except util.NoOperatorInfo:
94         pass
95     return message
96
97 def calculate_newest_version(sh, repo):
98     # XXX: put this in Application
99     return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
100
101 def calculate_parents(sh, version):
102     user_commit = sh.eval("git", "rev-parse", "HEAD")
103     next_commit = sh.eval("git", "rev-parse", version)
104     return user_commit, next_commit
105
106 def perform_pre_commit(sh):
107     message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
108     try:
109         message += "\nPre-commit-by: " + util.get_operator_git()
110     except util.NoOperatorInfo:
111         pass
112     try:
113         sh.call("git", "commit", "-a", "-m", message)
114     except shell.CallError:
115         logging.info("No changes detected")
116
117 def perform_tmp_clone(sh):
118     temp_dir = tempfile.mkdtemp(prefix="wizard")
119     temp_wc_dir = os.path.join(temp_dir, "repo")
120     logging.info("Using temporary directory: " + temp_wc_dir)
121     sh.call("git", "clone", "--shared", ".", temp_wc_dir)
122     return temp_wc_dir
123
124 def perform_merge(sh, repo, d, version):
125     # naive merge algorithm:
126     # sh.call("git", "merge", "-m", message, "scripts/master")
127     # crazy merge algorithm:
128     def make_virtual_commit(tag, parents = []):
129         """WARNING: Changes state of Git repository"""
130         sh.call("git", "checkout", tag, "--")
131         d.parametrize(".")
132         for file in d.application.parametrized_files:
133             try:
134                 sh.call("git", "add", "--", file)
135             except shell.CallError:
136                 pass
137         virtual_tree = sh.eval("git", "write-tree", log=True)
138         parent_args = itertools.chain(*(["-p", p] for p in parents))
139         virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
140                 *parent_args, input="", log=True)
141         sh.call("git", "reset", "--hard")
142         return virtual_commit
143     user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
144     base_virtual_commit = make_virtual_commit(d.app_version.scripts_tag)
145     next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
146     user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
147             "-p", base_virtual_commit, input="", log=True)
148     sh.call("git", "checkout", user_virtual_commit, "--")
149     try:
150         sh.call("git", "merge", next_virtual_commit)
151     except shell.CallError:
152         print os.getcwd()
153         logging.info("Conflict info:\n", sh.eval("git", "diff"))
154         raise MergeFailed
155
156 def parse_args(argv, baton):
157     usage = """usage: %prog upgrade [ARGS] [DIR]
158
159 Upgrades an autoinstall to the latest version.  This involves
160 updating files and running .scripts/update.
161
162 WARNING: This is still experimental."""
163     parser = command.WizardOptionParser(usage)
164     parser.add_option("--dry-run", dest="dry_run", action="store_true",
165             default=False, help="Prints would would be run without changing anything")
166     # notice trailing underscore
167     parser.add_option("--continue", dest="continue_", action="store_true",
168             default=False, help="Continues an upgrade that has had its merge manually "
169             "resolved using the current working directory as the resolved copy.")
170     parser.add_option("--force", dest="force", action="store_true",
171             default=False, help="Force running upgrade even if it's already at latest version.")
172     baton.push(parser, "srv_path")
173     options, args = parser.parse_all(argv)
174     if len(args) > 1:
175         parser.error("too many arguments")
176     return options, args
177
178 class Error(command.Error):
179     """Base exception for all exceptions raised by upgrade"""
180     pass
181
182 class AlreadyUpgraded(Error):
183     def __str__(self):
184         return """
185
186 ERROR: This autoinstall is already at the latest version."""
187
188 class MergeFailed(Error):
189     def __str__(self):
190         return """
191
192 ERROR: Merge failed.  Resolve the merge by cd'ing to the
193 temporary directory, finding conflicted files with `git status`,
194 resolving the files, adding them using `git add`, and then
195 committing your changes with `git commit` (your log message
196 will be ignored), and then running `wizard upgrade --continue`."""
197
198 class LocalChangesError(Error):
199     def __str__(self):
200         return """
201
202 ERROR: Local changes occurred in the install while the merge was
203 being processed so that a pull would not result in a fast-forward.
204 The best way to resolve this is probably to attempt an upgrade again,
205 with git rerere to remember merge resolutions (XXX: not sure if
206 this actually works)."""
207