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