]> scripts.mit.edu Git - wizard.git/blob - wizard/deploy.py
Move a bunch of summary items to full class commands.
[wizard.git] / wizard / deploy.py
1 import os.path
2 import fileinput
3 import dateutil.parser
4 import distutils.version
5
6 import wizard
7 from wizard import log
8
9 ## -- Global Functions --
10
11 def getInstallLines(vs):
12     """Retrieves a list of lines from the version directory that
13     can be passed to Deployment.parse()"""
14     if os.path.isfile(vs):
15         return fileinput.input([vs])
16     return fileinput.input([vs + "/" + f for f in os.listdir(vs)])
17
18 def parse_install_lines(show, options, yield_errors = False):
19     if not show: show = applications()
20     show = frozenset(show)
21     for line in getInstallLines(options.versions_path):
22         # construction
23         try:
24             d = Deployment.parse(line)
25             name = d.application.name
26         except deploy.NoSuchApplication as e:
27             if yield_errors:
28                 yield e
29             continue
30         except deploy.Error:
31             # we consider this a worse error
32             logging.warning("Error with '%s'" % line.rstrip())
33             continue
34         # filter
35         if name + "-" + str(d.version) in show or name in show:
36             pass
37         else:
38             continue
39         # yield
40         yield d
41
42 ## -- Model Objects --
43
44 class Deployment(object):
45     """Represents a deployment of an autoinstall; i.e. a concrete
46     directory in web_scripts that has .scripts-version in it."""
47     def __init__(self, location, log=None, version=None):
48         """ `location`  Location of the deployment
49             `version`   ApplicationVersion of the app (this is cached info)
50             `log`       DeployLog of the app"""
51         self.location = location
52         self._app_version = version
53         self._log = log
54         self._read_cache = {}
55     def read(self, file, force = False):
56         """Reads a file's contents and stuffs it in a cache"""
57         if force or file not in self._read_cache:
58             f = open(os.path.join(self.location, file))
59             self._read_cache[file] = f.read()
60             f.close()
61         return self._read_cache[file]
62     def extract(self):
63         return self.application.extract(self)
64     def updateVersion(self, version=None):
65         """`version` Version string to update to, or leave out to simply
66             force the creation of .scripts/version file"""
67         if not version:
68             version = str(self.version)
69         else:
70             self._app_version = self.application.makeVersion(version)
71         f = open(os.path.join(self.scripts_dir, 'version'), 'w')
72         f.write(self.application.name + '-' + version + "\n")
73         f.close()
74     @property
75     def scripts_dir(self):
76         return os.path.join(self.location, '.scripts')
77     @property
78     def version_file(self):
79         return os.path.join(self.location, '.scripts-version')
80     @property
81     def application(self):
82         return self.app_version.application
83     @property
84     def log(self):
85         if not self._log:
86             self._log = log.DeployLog.load(self.version_file)
87         return self._log
88     @property
89     def version(self):
90         """Returns the distutils Version of the deployment"""
91         return self.app_version.version
92     @property
93     def app_version(self, force = False):
94         """Returns the ApplicationVersion of the deployment"""
95         if self._app_version and not force: return self._app_version
96         else: return self.log[-1].version
97     @staticmethod
98     def parse(line):
99         """Parses a line from the results of parallel-find.pl.
100         This will work out of the box with fileinput, see
101         getInstallLines()"""
102         line = line.rstrip()
103         try:
104             location, deploydir = line.split(":")
105         except ValueError:
106             return Deployment(line) # lazy loaded version
107         return Deployment(location, version=ApplicationVersion.parse(deploydir, location))
108
109 class Application(object):
110     """Represents the generic notion of an application, i.e.
111     mediawiki or phpbb."""
112     def __init__(self, name):
113         self.name = name
114         self.versions = {}
115         self._extractors = {}
116     @property
117     def repository(self):
118         """Returns the Git repository that would contain this application."""
119         repo = os.path.join("/afs/athena.mit.edu/contrib/scripts/git/autoinstalls", self.name + ".git")
120         if not os.path.isdir(repo):
121             raise NoRepositoryError(app)
122         return repo
123     def makeVersion(self, version):
124         if version not in self.versions:
125             self.versions[version] = ApplicationVersion(distutils.version.LooseVersion(version), self)
126         return self.versions[version]
127     def extract(self, deployment):
128         """Extracts wizard variables from a deployment."""
129         result = {}
130         for k,extractor in self.extractors.items():
131             result[k] = extractor(deployment)
132         return result
133     @property
134     def extractors(self):
135         return {}
136     @staticmethod
137     def make(name):
138         """Makes an application, but uses the correct subtype if available."""
139         try:
140             __import__("wizard.app." + name)
141             return getattr(wizard.app, name).Application(name)
142         except ImportError:
143             return Application(name)
144
145 class ApplicationVersion(object):
146     """Represents an abstract notion of a version for an application"""
147     def __init__(self, version, application):
148         """ `version`       Instance of distutils.LooseVersion
149             `application`   Instance of Application
150         WARNING: Please don't call this directly; instead, use getVersion()
151         on the application you want, so that this version gets registered."""
152         self.version = version
153         self.application = application
154     @property
155     def scripts_tag(self):
156         """Returns the name of the Git tag for this version"""
157         # XXX: This assumes that there's only a -scripts version
158         # which will not be true in the future.  Unfortunately, finding
159         # the "true" latest version is computationally expensive
160         return "v%s-scripts" % self.version
161     def __cmp__(x, y):
162         return cmp(x.version, y.version)
163     @staticmethod
164     def parse(deploydir,location,applookup=None):
165         # The version of the deployment, will be:
166         #   /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z for old style installs
167         name = deploydir.split("/")[-1]
168         try:
169             if name.find(" ") != -1:
170                 raw_app, raw_version = name.split(" ")
171                 version = raw_version[1:] # remove leading v
172                 app, _ = raw_app.split(".") # remove trailing .git
173             elif name.find("-") != -1:
174                 app, _, version = name.partition("-")
175             else:
176                 app = name
177                 version = "trunk"
178         except ValueError: # mostly from the a, b = foo.split(' ')
179             raise DeploymentParseError(deploydir, location)
180         if not applookup: applookup = applications()
181         try:
182             # defer to the application for version creation
183             return applookup[app].makeVersion(version)
184         except KeyError:
185             raise NoSuchApplication(app, location)
186
187 ## -- Exceptions --
188
189 class Error(Exception):
190     """Base error class for this module"""
191     pass
192
193 class NoSuchApplication(Error):
194     def __init__(self, name, location):
195         self.name = name
196         self.location = location
197     def __str__(self):
198         return "ERROR: Unrecognized app '%s' at %s" % (self.name, self.location)
199
200 class DeploymentParseError(Error):
201     def __init__(self, malformed, location):
202         self.malformed = malformed
203         self.location = location
204     def __str__(self):
205         return """ERROR: Unparseable '%s' at %s""" % (self.malformed, self.location)
206
207 class NoRepositoryError(Error):
208     def __init__(self, app):
209         self.app = app
210         self.location = "unknown"
211     def __str__(self):
212         return """
213
214 ERROR: Could not find repository for this application. Have
215 you converted the repository over? Is the name %s
216 the same as the name of the .git folder?
217 """ % self.app
218
219 # If you want, you can wrap this up into a registry and access things
220 # through that, but it's not really necessary
221
222 application_list = [
223     "mediawiki", "wordpress", "joomla", "e107", "gallery2",
224     "phpBB", "advancedbook", "phpical", "trac", "turbogears", "django",
225     # these are technically deprecated
226     "advancedpoll", "gallery",
227 ]
228 _applications = None
229
230 def applications():
231     """Hash table for looking up string application name to instance"""
232     global _applications
233     if not _applications:
234         _applications = dict([(n,Application.make(n)) for n in application_list ])
235     return _applications
236