5 import distutils.version
9 def getInstallLines(global_options):
10 """Retrieves a list of lines from the version directory that
11 can be passed to Deployment.parse()"""
12 vs = global_options.versions
13 if os.path.isfile(vs):
14 return fileinput.input([vs])
15 return fileinput.input([vs + "/" + f for f in os.listdir(vs)])
17 class Deployment(object):
18 """Represents a deployment of an autoinstall; i.e. a concrete
19 directory in web_scripts that has .scripts-version in it."""
20 def __init__(self, location, log=None, version=None):
21 """ `location` Location of the deployment
22 `version` ApplicationVersion of the app (this is cached info)
23 `log` DeployLog of the app"""
24 self.location = location
25 self._version = version
29 """Parses a line from the results of parallel-find.pl.
30 This will work out of the box with fileinput, see
34 location, deploydir = line.split(":")
36 return Deployment(line) # lazy loaded version
37 return Deployment(location, version=ApplicationVersion.parse(deploydir))
40 """Lazily creates a deployment from a directory"""
41 return Deployment(dir)
42 def getVersionFile(self):
43 return os.path.join(self.location, '.scripts-version')
44 def getApplication(self):
45 return self.getAppVersion().application
48 self._log = DeployLog.load(self.getVersionFile())
51 """Returns the distutils Version of the deployment"""
52 return self.getAppVersion().version
53 def getAppVersion(self, force = False):
54 """Returns the ApplicationVersion of the deployment"""
55 if self._version and not force: return self._version
56 else: return self.getLog()[-1].version
58 """Simple method which registers the deployment as a +1 on the
59 appropriate version. No further inspection is done."""
60 self.getAppVersion().count(self)
62 def count_exists(self, file):
63 """Checks if the codebase has a certain file/directory in it."""
64 if os.path.exists(self.location + "/" + file):
65 self.getAppVersion().count_exists(self, file)
69 class Application(object):
70 """Represents the generic notion of an application, i.e.
71 mediawiki or phpbb."""
72 def __init__(self, name):
75 # This is 'wizard summary' specific code
79 def getRepository(self):
80 """Returns the Git repository that would contain this application."""
81 repo = os.path.join("/afs/athena.mit.edu/contrib/scripts/wizard/srv", self.name + ".git")
82 if not os.path.isdir(repo):
83 raise NoRepositoryError(app)
85 def getVersion(self, version):
86 if version not in self.versions:
87 self.versions[version] = ApplicationVersion(distutils.version.LooseVersion(version), self)
88 return self.versions[version]
89 # XXX: This code should go in summary.py; maybe as a mixin, maybe as
93 return '+' * int(math.ceil(float(v)/self._max * self.HISTOGRAM_WIDTH))
95 if not self.versions: return "%-11s no installs" % self.name
97 ["%-16s %3d installs" % (self.name, self._total)] + \
98 [v.report() for v in sorted(self.versions.values())]
99 for f,c in self._c_exists.items():
100 ret.append("%d users have %s" % (c,f))
101 return "\n".join(ret)
103 class DeployLog(list):
104 # As per #python; if you decide to start overloading magic methods,
105 # we should remove this subclass
106 """Equivalent to .scripts-version: a series of DeployRevisions."""
107 def __init__(self, revs = []):
108 """`revs` List of DeployRevision objects"""
109 list.__init__(self, revs) # pass to list
112 """Loads a scripts version file and parses it into
113 DeployLog and DeployRevision objects"""
115 rev = DeployRevision()
120 raise ScriptsVersionNotEnoughFieldsError()
125 raise ScriptsVersionNoSuchFile(file)
126 # XXX: possibly rewrite this parsing code. This might
133 rev = DeployRevision()
136 # we need the dateutil parser in order to
137 # be able to parse time offsets
138 rev.datetime = dateutil.parser.parse(line)
142 rev.source = DeploySource.parse(line)
144 rev.version = ApplicationVersion.parse(line)
147 raise ScriptsVersionTooManyFieldsError()
150 return DeployLog(revs)
152 return '<DeployLog %s>' % list.__repr__(self)
154 class DeployRevision(object):
155 """A single entry in the .scripts-version file. Contains who deployed
156 this revision, what application version this is, etc."""
157 def __init__(self, datetime=None, user=None, source=None, version=None):
158 """ `datetime` Time this revision was deployed
159 `user` Person who deployed this revision, in user@host format.
160 `source` Instance of DeploySource
161 `version` Instance of ApplicationVersion
162 Note: This object is typically built incrementally."""
163 self.datetime = datetime
166 self.version = version
168 class DeploySource(object):
169 """Source of the deployment; see subclasses for examples"""
171 raise NotImplementedError # abstract class
174 # munge out common prefix
175 rel = os.path.relpath(line, "/afs/athena.mit.edu/contrib/scripts/")
176 parts = rel.split("/")
177 if parts[0] == "wizard":
178 return WizardUpdate()
179 elif parts[0] == "deploy" or parts[0] == "deploydev":
180 isDev = ( parts[0] == "deploydev" )
182 if parts[1] == "updates":
183 return OldUpdate(isDev)
185 return TarballInstall(line, isDev)
188 return UnknownDeploySource(line)
190 class TarballInstall(DeploySource):
191 """Original installation from tarball, characterized by
192 /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z.tar.gz
194 def __init__(self, location, isDev):
195 self.location = location
198 class OldUpdate(DeploySource):
199 """Upgrade using old upgrade infrastructure, characterized by
200 /afs/athena.mit.edu/contrib/scripts/deploydev/updates/update-scripts-version.pl
202 def __init__(self, isDev):
205 class WizardUpdate(DeploySource):
206 """Upgrade using wizard infrastructure, characterized by
207 /afs/athena.mit.edu/contrib/scripts/wizard/bin/wizard HASHGOBBLEDYGOOK
212 class UnknownDeploySource(DeploySource):
213 """Deployment that we don't know the meaning of. Wot!"""
214 def __init__(self, line):
217 class ApplicationVersion(object):
218 """Represents an abstract notion of a version for an application"""
219 def __init__(self, version, application):
220 """ `version` Instance of distutils.LooseVersion
221 `application` Instance of Application
222 WARNING: Please don't call this directly; instead, use getVersion()
223 on the application you want, so that this version gets registered."""
224 self.version = version
225 self.application = application
228 def getScriptsTag(self):
229 """Returns the name of the Git tag for this version"""
230 # XXX: This assume sthat there's only a -scripts version
231 # which will not be true in the future.
232 return "v%s-scripts" % self.version
234 return cmp(x.version, y.version)
236 def parse(deploydir,applookup=None):
237 # The version of the deployment, will be:
238 # /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z for old style installs
239 # /afs/athena.mit.edu/contrib/scripts/wizard/srv/APP.git vx.y.z-scripts for new style installs
240 name = deploydir.split("/")[-1]
242 if name.find(" ") != -1:
243 raw_app, raw_version = name.split(" ")
244 version = raw_version[1:] # remove leading v
245 app, _ = raw_app.split(".") # remove trailing .git
246 elif name.find("-") != -1:
247 app, version = name.split("-")
248 # XXX: this should be removed after the next parallel-find run
249 elif name == "deploy":
250 # Assume that it's django, since those were botched
252 version = "0.1-scripts"
254 raise DeploymentParseError(deploydir)
255 except ValueError: # mostly from the a, b = foo.split(' ')
256 raise DeploymentParseError(deploydir)
257 if not applookup: applookup = applications
259 # defer to the application for version creation
260 return applookup[app].getVersion(version)
262 raise NoSuchApplication
263 # This is summary specific code
264 def count(self, deployment):
266 self.application._total += 1
267 if self.c > self.application._max:
268 self.application._max = self.c
269 def count_exists(self, deployment, n):
270 if n in self.c_exists: self.c_exists[n] += 1
271 else: self.c_exists[n] = 1
272 if n in self.application._c_exists: self.application._c_exists[n] += 1
273 else: self.application._c_exists[n] = 1
275 return " %-12s %3d %s" \
276 % (self.version, self.c, self.application._graph(self.c))
278 class Error(wizard.Error):
279 """Base error class for deploy errors"""
282 class NoSuchApplication(Error):
285 class DeploymentParseError(Error):
286 def __init__(self, malformed):
287 self.malformed = malformed
291 ERROR: Could not parse deployment string:
295 class ScriptsVersionTooManyFieldsError(Error):
299 ERROR: Could not parse .scripts-version file. It
300 contained too many fields.
303 class ScriptsVersionNotEnoughFieldsError(Error):
307 ERROR: Could not parse .scripts-version file. It
308 didn't contain enough fields.
311 class ScriptsVersionNoSuchFile(Error):
312 def __init__(self, file):
317 ERROR: File %s didn't exist.
320 # If you want, you can wrap this up into a registry and access things
321 # through that, but it's not really necessary
324 "mediawiki", "wordpress", "joomla", "e107", "gallery2",
325 "phpBB", "advancedbook", "phpical", "trac", "turbogears", "django",
326 # these are technically deprecated
327 "advancedpoll", "gallery",
330 """Hash table for looking up string application name to instance"""
331 applications = dict([(n,Application(n)) for n in application_list ])