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