Commit 9f7673c4 by Eric Coissac

Add a get_orgasm.py script able to install orgasm automatically in a virtualenv

parent 563a73dc
......@@ -8,7 +8,6 @@ from os import path
import os.path
import glob
import sys
import re
try:
......
......@@ -20,12 +20,12 @@ class Distribution(ori_Distribution):
ori_Distribution.__init__(self, attrs)
self.global_options.index(0,('serenity', None, "install or build the package in a python virtualenv "
self.global_options.insert(0,('serenity', None, "install or build the package in a python virtualenv "
"without polluting the installed python and with many "
"checks during the installation process"
))
self.global_options.index(0,('virtualen', None, "if the installation is done using the serenity mode "
"this ioption allows for specifying the virtualenv name. "
self.global_options.insert(0,('virtualenv', None, "if the installation is done using the serenity mode "
"this option allows for specifying the virtualenv name. "
"By default the name is PACKAGE-VERSION"
))
......
......@@ -14,7 +14,7 @@ from distutils.version import LooseVersion
from distutils import log
from obidistutils.serenity.globals import PIP_MINVERSION, \
local_virtualenv
local_virtualenv # @UnusedImport
from obidistutils.serenity.checkpip import get_a_pip_module
......@@ -35,7 +35,6 @@ def get_a_virtualenv_module(pip=None):
global local_virtualenv
if not local_virtualenv:
if pip is None:
pip = get_a_pip_module()
......@@ -51,10 +50,8 @@ def get_a_virtualenv_module(pip=None):
ok = pip_install_package(virtualenv_req,directory=tmpdir,pip=pip)
log.info('temp install dir : %s' % tmpdir)
os.system("ls -la %s > ~/toto/toto.txt" % tmpdir,)
log.debug('temp install dir : %s' % tmpdir)
if ok!=0:
raise DistutilsError, "I cannot install a virtualenv package"
......
This source diff could not be displayed because it is too large. You can view the blob instead.
# -*- coding: utf-8 -*-
"""
Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net>
This module offers extensions to the standard Python
datetime module.
"""
__author__ = "Tomi Pieviläinen <tomi.pievilainen@iki.fi>"
__license__ = "Simplified BSD"
__version__ = "2.2"
"""
Copyright (c) 2003-2007 Gustavo Niemeyer <gustavo@niemeyer.net>
This module offers extensions to the standard Python
datetime module.
"""
__license__ = "Simplified BSD"
import datetime
__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"]
EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
EASTER_WESTERN = 3
def easter(year, method=EASTER_WESTERN):
"""
This method was ported from the work done by GM Arts,
on top of the algorithm by Claus Tondering, which was
based in part on the algorithm of Ouding (1940), as
quoted in "Explanatory Supplement to the Astronomical
Almanac", P. Kenneth Seidelmann, editor.
This algorithm implements three different easter
calculation methods:
1 - Original calculation in Julian calendar, valid in
dates after 326 AD
2 - Original method, with date converted to Gregorian
calendar, valid in years 1583 to 4099
3 - Revised method, in Gregorian calendar, valid in
years 1583 to 4099 as well
These methods are represented by the constants:
EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
EASTER_WESTERN = 3
The default method is method 3.
More about the algorithm may be found at:
http://users.chariot.net.au/~gmarts/eastalg.htm
and
http://www.tondering.dk/claus/calendar.html
"""
if not (1 <= method <= 3):
raise ValueError("invalid method")
# g - Golden year - 1
# c - Century
# h - (23 - Epact) mod 30
# i - Number of days from March 21 to Paschal Full Moon
# j - Weekday for PFM (0=Sunday, etc)
# p - Number of days from March 21 to Sunday on or before PFM
# (-6 to 28 methods 1 & 3, to 56 for method 2)
# e - Extra days to add for method 2 (converting Julian
# date to Gregorian date)
y = year
g = y % 19
e = 0
if method < 3:
# Old method
i = (19*g+15)%30
j = (y+y//4+i)%7
if method == 2:
# Extra dates to convert Julian to Gregorian date
e = 10
if y > 1600:
e = e+y//100-16-(y//100-16)//4
else:
# New method
c = y//100
h = (c-c//4-(8*c+13)//25+19*g+15)%30
i = h-(h//28)*(1-(h//28)*(29//(h+1))*((21-g)//11))
j = (y+y//4+i+2-c+c//4)%7
# p can be from -6 to 56 corresponding to dates 22 March to 23 May
# (later dates apply to method 2, although 23 May never actually occurs)
p = i-j+e
d = 1+(p+27+(p+6)//40)%31
m = 3+(p+26)//30
return datetime.date(int(y), int(m), int(d))
# This code was originally contributed by Jeffrey Harris.
import datetime
import struct
import winreg
__all__ = ["tzwin", "tzwinlocal"]
ONEWEEK = datetime.timedelta(7)
TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones"
TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
def _settzkeyname():
global TZKEYNAME
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
try:
winreg.OpenKey(handle, TZKEYNAMENT).Close()
TZKEYNAME = TZKEYNAMENT
except WindowsError:
TZKEYNAME = TZKEYNAME9X
handle.Close()
_settzkeyname()
class tzwinbase(datetime.tzinfo):
"""tzinfo class based on win32's timezones available in the registry."""
def utcoffset(self, dt):
if self._isdst(dt):
return datetime.timedelta(minutes=self._dstoffset)
else:
return datetime.timedelta(minutes=self._stdoffset)
def dst(self, dt):
if self._isdst(dt):
minutes = self._dstoffset - self._stdoffset
return datetime.timedelta(minutes=minutes)
else:
return datetime.timedelta(0)
def tzname(self, dt):
if self._isdst(dt):
return self._dstname
else:
return self._stdname
def list():
"""Return a list of all time zones known to the system."""
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
tzkey = winreg.OpenKey(handle, TZKEYNAME)
result = [winreg.EnumKey(tzkey, i)
for i in range(winreg.QueryInfoKey(tzkey)[0])]
tzkey.Close()
handle.Close()
return result
list = staticmethod(list)
def display(self):
return self._display
def _isdst(self, dt):
dston = picknthweekday(dt.year, self._dstmonth, self._dstdayofweek,
self._dsthour, self._dstminute,
self._dstweeknumber)
dstoff = picknthweekday(dt.year, self._stdmonth, self._stddayofweek,
self._stdhour, self._stdminute,
self._stdweeknumber)
if dston < dstoff:
return dston <= dt.replace(tzinfo=None) < dstoff
else:
return not dstoff <= dt.replace(tzinfo=None) < dston
class tzwin(tzwinbase):
def __init__(self, name):
self._name = name
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
tzkey = winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name))
keydict = valuestodict(tzkey)
tzkey.Close()
handle.Close()
self._stdname = keydict["Std"].encode("iso-8859-1")
self._dstname = keydict["Dlt"].encode("iso-8859-1")
self._display = keydict["Display"]
# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
tup = struct.unpack("=3l16h", keydict["TZI"])
self._stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1
self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1
(self._stdmonth,
self._stddayofweek, # Sunday = 0
self._stdweeknumber, # Last = 5
self._stdhour,
self._stdminute) = tup[4:9]
(self._dstmonth,
self._dstdayofweek, # Sunday = 0
self._dstweeknumber, # Last = 5
self._dsthour,
self._dstminute) = tup[12:17]
def __repr__(self):
return "tzwin(%s)" % repr(self._name)
def __reduce__(self):
return (self.__class__, (self._name,))
class tzwinlocal(tzwinbase):
def __init__(self):
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
tzlocalkey = winreg.OpenKey(handle, TZLOCALKEYNAME)
keydict = valuestodict(tzlocalkey)
tzlocalkey.Close()
self._stdname = keydict["StandardName"].encode("iso-8859-1")
self._dstname = keydict["DaylightName"].encode("iso-8859-1")
try:
tzkey = winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname))
_keydict = valuestodict(tzkey)
self._display = _keydict["Display"]
tzkey.Close()
except OSError:
self._display = None
handle.Close()
self._stdoffset = -keydict["Bias"]-keydict["StandardBias"]
self._dstoffset = self._stdoffset-keydict["DaylightBias"]
# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
tup = struct.unpack("=8h", keydict["StandardStart"])
(self._stdmonth,
self._stddayofweek, # Sunday = 0
self._stdweeknumber, # Last = 5
self._stdhour,
self._stdminute) = tup[1:6]
tup = struct.unpack("=8h", keydict["DaylightStart"])
(self._dstmonth,
self._dstdayofweek, # Sunday = 0
self._dstweeknumber, # Last = 5
self._dsthour,
self._dstminute) = tup[1:6]
def __reduce__(self):
return (self.__class__, ())
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
"""dayofweek == 0 means Sunday, whichweek 5 means last instance"""
first = datetime.datetime(year, month, 1, hour, minute)
weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1))
for n in range(whichweek):
dt = weekdayone+(whichweek-n)*ONEWEEK
if dt.month == month:
return dt
def valuestodict(key):
"""Convert a registry key's values to a dictionary."""
dict = {}
size = winreg.QueryInfoKey(key)[1]
for i in range(size):
data = winreg.EnumValue(key, i)
dict[data[0]] = data[1]
return dict
# -*- coding: utf-8 -*-
"""
Copyright (c) 2003-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
This module offers extensions to the standard Python
datetime module.
"""
import logging
import os
from subprocess import call
from tarfile import TarFile
from dateutil.tz import tzfile
__author__ = "Tomi Pieviläinen <tomi.pievilainen@iki.fi>"
__license__ = "Simplified BSD"
__all__ = ["setcachesize", "gettz", "rebuild"]
CACHE = []
CACHESIZE = 10
class tzfile(tzfile):
def __reduce__(self):
return (gettz, (self._filename,))
def getzoneinfofile():
filenames = sorted(os.listdir(os.path.join(os.path.dirname(__file__))))
filenames.reverse()
for entry in filenames:
if entry.startswith("zoneinfo") and ".tar." in entry:
return os.path.join(os.path.dirname(__file__), entry)
return None
ZONEINFOFILE = getzoneinfofile()
del getzoneinfofile
def setcachesize(size):
global CACHESIZE, CACHE
CACHESIZE = size
del CACHE[size:]
def gettz(name):
tzinfo = None
if ZONEINFOFILE:
for cachedname, tzinfo in CACHE:
if cachedname == name:
break
else:
tf = TarFile.open(ZONEINFOFILE)
try:
zonefile = tf.extractfile(name)
except KeyError:
tzinfo = None
else:
tzinfo = tzfile(zonefile)
tf.close()
CACHE.insert(0, (name, tzinfo))
del CACHE[CACHESIZE:]
return tzinfo
def rebuild(filename, tag=None, format="gz"):
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz.
"""
import tempfile, shutil
tmpdir = tempfile.mkdtemp()
zonedir = os.path.join(tmpdir, "zoneinfo")
moduledir = os.path.dirname(__file__)
if tag: tag = "-"+tag
targetname = "zoneinfo%s.tar.%s" % (tag, format)
try:
tf = TarFile.open(filename)
# The "backwards" zone file contains links to other files, so must be
# processed as last
for name in sorted(tf.getnames(),
key=lambda k: k != "backward" and k or "z"):
if not (name.endswith(".sh") or
name.endswith(".tab") or
name == "leapseconds"):
tf.extract(name, tmpdir)
filepath = os.path.join(tmpdir, name)
try:
# zic will return errors for nontz files in the package
# such as the Makefile or README, so check_call cannot
# be used (or at least extra checks would be needed)
call(["zic", "-d", zonedir, filepath])
except OSError as e:
if e.errno == 2:
logging.error(
"Could not find zic. Perhaps you need to install "
"libc-bin or some other package that provides it, "
"or it's not in your PATH?")
raise
tf.close()
target = os.path.join(moduledir, targetname)
for entry in os.listdir(moduledir):
if entry.startswith("zoneinfo") and ".tar." in entry:
os.unlink(os.path.join(moduledir, entry))
tf = TarFile.open(target, "w:%s" % format)
for entry in os.listdir(zonedir):
entrypath = os.path.join(zonedir, entry)
tf.add(entrypath, entry)
tf.close()
finally:
shutil.rmtree(tmpdir)
__version__ = '0.3.24'
(T_URL, T_PATH) = ('url', 'path')
import subprocess
import logging
import dateutil.parser
import collections
import xml.etree.ElementTree
import svn
_logger = logging.getLogger('svn')
class CommonClient(object):
def __init__(self, url_or_path, type_):
self.__url_or_path = url_or_path
if type_ not in (svn.T_URL, svn.T_PATH):
raise ValueError("Type is invalid: %s" % (type_))
self.__type = type_
def run_command(self, subcommand, args, success_code=0,
return_stderr=False, combine=False, return_binary=False):
cmd = ['svn', subcommand] + args
_logger.debug("RUN: %s" % (cmd,))
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode != success_code:
raise ValueError("Command failed with (%d): %s\n%s\n%s" %
(p.returncode, cmd, stdout, stderr))
s = stderr if return_stderr is True else stdout
if return_binary is True:
return s
s = s.decode('ASCII')
return s if combine is True else s.split("\n")
def rows_to_dict(self, rows, lc=True):
d = {}
for row in rows:
row = row.strip()
if not row:
continue
pivot = row.index(': ')
k = row[:pivot]
v = row[pivot + 2:]
if lc is True:
k = k.lower()
d[k] = v
return d
def info(self):
result = self.run_command(
'info',
['--xml', self.__url_or_path],
combine=True)
root = xml.etree.ElementTree.fromstring(result)
entry_attr = root.find('entry').attrib
commit_attr = root.find('entry/commit').attrib
relative_url = root.find('entry/relative-url')
author = root.find('entry/commit/author')
wcroot_abspath = root.find('entry/wc-info/wcroot-abspath')
wcinfo_schedule = root.find('entry/wc-info/schedule')
wcinfo_depth = root.find('entry/wc-info/depth')
info = {
'entry#kind': entry_attr['kind'],
'entry#path': entry_attr['path'],
'entry#revision': int(entry_attr['revision']),
'url': root.find('entry/url').text,
'relative_url': relative_url.text \
if relative_url is not None and \
len(relative_url) \
else None,
'repository/root': root.find('entry/repository/root').text,
'repository/uuid': root.find('entry/repository/uuid').text,
'wc-info/wcroot-abspath': wcroot_abspath.text \
if wcroot_abspath is not None and \
len(wcroot_abspath) \
else None,
'wc-info/schedule': wcinfo_schedule.text \
if wcinfo_schedule is not None and \
len(wcinfo_schedule) \
else None,
'wc-info/depth': wcinfo_depth.text \
if wcinfo_depth is not None and \
len(wcinfo_depth) \
else None,
'commit/author': author.text \
if author is not None and \
len(author) \
else None,
'commit/date': dateutil.parser.parse(
root.find('entry/commit/date').text),
'commit#revision': int(commit_attr['revision']),
}
# Set some more intuitive keys, because no one likes dealing with
# symbols. However, we retain the old ones to maintain backwards-
# compatibility.
info['entry_kind'] = info['entry#kind']
info['entry_path'] = info['entry#path']
info['entry_revision'] = info['entry#revision']
info['repository_root'] = info['repository/root']
info['repository_uuid'] = info['repository/uuid']
info['wcinfo_wcroot_abspath'] = info['wc-info/wcroot-abspath']
info['wcinfo_schedule'] = info['wc-info/schedule']
info['wcinfo_depth'] = info['wc-info/depth']
info['commit_author'] = info['commit/author']
info['commit_date'] = info['commit/date']
info['commit_revision'] = info['commit#revision']
return info
def cat(self, rel_filepath):
# TODO(dustin): Verify that this handles binaries well.
return self.run_command(
'cat',
[self.__url_or_path + '/' + rel_filepath],
return_binary=True)
def log_default(self, timestamp_from_dt=None, timestamp_to_dt=None,
limit=None):
"""Allow for the most-likely kind of log listing: the complete list, a
FROM and TO timestamp, a FROM timestamp only, or a quantity limit.
"""
timestamp_from_phrase = ('{' + timestamp_from_dt.isoformat() + '}') \
if timestamp_from_dt \
else ''
timestamp_to_phrase = ('{' + timestamp_to_dt.isoformat() + '}') \
if timestamp_to_dt \
else ''
args = []
if timestamp_from_phrase or timestamp_to_phrase:
if not timestamp_from_phrase:
raise ValueError("The default log retriever can not take a TO "
"timestamp without a FROM timestamp.")
if not timestamp_to_phrase:
timestamp_to_phrase = 'HEAD'
args += ['-r', timestamp_from_phrase + ':' + timestamp_to_phrase]
if limit is not None:
args += ['-l', str(limit)]
result = self.run_command(
'log',
args + ['--xml', self.__url_or_path],
combine=True)
root = xml.etree.ElementTree.fromstring(result)
c = collections.namedtuple(
'LogEntry',
['date', 'msg', 'revision', 'author'])
for e in root.findall('logentry'):
entry_info = dict([(x.tag, x.text) for x in e.getchildren()])
yield c(
msg=entry_info['msg'],
author=entry_info['author'],
revision=int(e.get('revision')),
date=dateutil.parser.parse(entry_info['date']))
def export(self, to_path, revision=None):
cmd = []
if revision is not None:
cmd += ['-r', str(revision)]
cmd += [self.__url_or_path, to_path]
self.run_command('export', cmd)
@property
def url(self):
if self.__type != svn.T_URL:
raise EnvironmentError("Only the remote-client has access to the URL.")
return self.__url_or_path
@property
def path(self):
if self.__type != svn.T_PATH:
raise EnvironmentError("Only the local-client has access to the path.")
return self.__url_or_path
import os.path
import svn
import svn.common
class LocalClient(svn.common.CommonClient):
def __init__(self, path_, *args, **kwargs):
if os.path.exists(path_) is False:
raise EnvironmentError("Path does not exist: %s" % (path_))
super(LocalClient, self).__init__(path_, svn.T_PATH, *args, **kwargs)
def __repr__(self):
return ('<SVN(LOCAL) %s>' % (self.path))
import svn
from svn import common
class RemoteClient(common.CommonClient):
def __init__(self, url, *args, **kwargs):
super(RemoteClient, self).__init__(url, svn.T_URL, *args, **kwargs)
def checkout(self, path, revision=None):
cmd = []
if revision is not None:
cmd += ['-r', str(revision)]