code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import re
import os
import xmlrpclib
import sys
import util
import shutil
import httplib
import urllib
import urllib2
import time
import datetime
import ConfigParser
import optparse
import zc.lockfile
import socket
import tempfile
import urlparse
import pkg_resources
from BeautifulSoup import BeautifulSoup
from glob import fnmatch
from logger import getLogger
import HTMLParser
try:
from hashlib import md5
except ImportError:
from md5 import md5
# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)
LOG = None
dev_package_regex = re.compile(r'\ddev[-_]')
def pypimirror_version():
"""
returns a version string
"""
version = pkg_resources.working_set.by_key["z3c.pypimirror"].version
return 'z3c.pypimirror/%s' % version
def urlopen(url):
""" This behaves exactly like urllib2.urlopen, but injects a header
User-Agent: z3c.pypimirror/1.0.2
"""
headers = { 'User-Agent' : pypimirror_version() }
req = urllib2.Request(url, None, headers)
return urllib2.urlopen(req)
class Stats(object):
""" This is just for statistics """
def __init__(self):
self._found = []
self._stored = []
self._error_404 = []
self._error_invalid_package = []
self._error_invalid_url = []
self._starttime = time.time()
def runtime(self):
runtime = time.time() - self._starttime
if runtime > 60:
return "%dm%2ds" % (runtime//60, runtime%60)
return "%ds" % runtime
def found(self, name):
self._found.append(name)
def stored(self, name):
self._stored.append(name)
def error_404(self, name):
self._error_404.append(name)
def error_invalid_package(self, name):
self._error_invalid_package.append(name)
def error_invalid_url(self, name):
self._error_invalid_url.append(name)
def getStats(self):
ret = []
ret.append("Statistics")
ret.append("----------")
ret.append("Found (cached): %d" % len(self._found))
ret.append("Stored (downloaded): %d" % len(self._stored))
ret.append("Not found (404): %d" % len(self._error_404))
ret.append("Invalid packages: %d" % len(self._error_invalid_package))
ret.append("Invalid URLs: %d" % len(self._error_invalid_url))
ret.append("Runtime: %s" % self.runtime())
return ret
class PypiPackageList(object):
"""
This fetches and represents a package list
"""
def __init__(self, pypi_xmlrpc_url='http://pypi.python.org/pypi'):
self._pypi_xmlrpc_url = pypi_xmlrpc_url
def list(self, filter_by=None, incremental=False, fetch_since_days=7):
server = xmlrpclib.Server(self._pypi_xmlrpc_url)
packages = server.list_packages()
if not filter_by:
return packages
filtered_packages = []
for package in packages:
if not True in [fnmatch.fnmatch(package, f) for f in filter_by]:
continue
filtered_packages.append(package)
if incremental:
changelog = server.changelog(int(time.time() - fetch_since_days*24*3600))
changed_packages = [tp[0] for tp in changelog
if 'file' in tp[3]]
changed_packages = [package for package in changed_packages if package in filtered_packages]
return changed_packages
else:
return filtered_packages
class PackageError(Exception):
pass
class Package(object):
"""
This handles the list of versions and fetches the
files
"""
def __init__(self, package_name, pypi_base_url="http://pypi.python.org/simple"):
self._links_cache = None
if not util.isASCII(package_name):
raise PackageError("%s is not a valid package name." % package_name)
try:
package_name = urllib.quote(package_name)
except KeyError:
raise PackageError("%s is not a valid package name." % package_name)
self.name = package_name
self._pypi_base_url = pypi_base_url
def url(self, filename=None, splittag=True):
if filename:
(filename, rest) = urllib.splittag(filename)
try:
filename = urllib.quote(filename)
except KeyError:
raise PackageError("%s is not a valid filename." % filename)
url = "%s/%s" % (self._pypi_base_url, self.name)
if filename:
url = "%s/%s" % (url, filename)
return url
def _fetch_index(self):
try:
html = urlopen(self.url()).read()
except urllib2.HTTPError, v:
if '404' in str(v): # sigh
raise PackageError("Package not available (404): %s" % self.url())
raise PackageError("Package not available (unknown reason): %s" % self.url())
except urllib2.URLError, v:
raise PackageError("URL Error: %s " % self.url())
except Exception, e:
raise PackageError('Generic error: %s' % e)
return html
def _fetch_links(self, html):
try:
soup = BeautifulSoup(html)
except HTMLParser.HTMLParseError, e:
raise PackageError("HTML parse error: %s" % e)
links = []
for link in soup.findAll("a"):
href = link.get("href")
if href:
links.append(href)
return links
def _links_external(self, html, filename_matches=None, follow_external_index_pages=False):
""" pypi has external "download_url"s. We try to get anything
from there too. This is really ugly and I'm not sure if there's
a sane way. The download_url directs either to a website which
contains many download links or directly to a package.
"""
download_links = set()
soup = BeautifulSoup(html)
links = soup.findAll("a")
for link in links:
if link.renderContents().endswith("download_url"):
# we have a download_url!! Yeah.
url = link.get("href")
if not url:
continue
download_links.add(url)
if link.renderContents().endswith("home_page"):
# we have a download_url!! Yeah.
url = link.get("href")
if not url:
continue
download_links.add(url)
for link in download_links:
# check if the link points directly to a file
# and get it if it matches filename_matches
if filename_matches:
if self.matches(link, filename_matches):
yield link
continue
# fetch what is behind the link and see if it's html.
# If it is html, download anything from there.
# This is extremely unreliable and therefore commented out.
if follow_external_index_pages:
try:
site = urlopen(link)
except Exception, e:
LOG.warn('Unload downloading %s (%s)' % (link, e))
continue
if site.headers.type != "text/html":
continue
# we have a valid html page now. Parse links and download them.
# They have mostly no md5 hash.
html = site.read()
real_download_links = self._fetch_links(html)
candidates = list()
for real_download_link in real_download_links:
# build absolute links
real_download_link = urllib.basejoin(site.url, real_download_link)
if not filename_matches or self.matches(real_download_link, filename_matches):
# we're not interested in dev packages
if not dev_package_regex.search(real_download_link):
# Consider only download links that starts with
# the current package name
filename = urlparse.urlsplit(real_download_link)[2].split('/')[-1]
if not filename.startswith(self.name):
continue
candidates.append(real_download_link)
def sort_candidates(url1, url2):
""" Sort all download links by package version """
parts1 = urlparse.urlsplit(url1)[2].split('/')[-1]
parts2 = urlparse.urlsplit(url2)[2].split('/')[-1]
return cmp(pkg_resources.parse_version(parts1), pkg_resources.parse_version(parts2))
# and return the 20 latest files
candidates.sort(sort_candidates)
for c in candidates[-20:][::-1]:
yield c
def _links(self, filename_matches=None, external_links=False, follow_external_index_pages=False):
""" This is an iterator which returns useful links on files for
mirroring
"""
remote_index_html = self._fetch_index()
for link in self._fetch_links(remote_index_html):
# then handle "normal" packages in pypi.
(url, hash) = urllib.splittag(link)
if not hash:
continue
try:
(hashname, hash) = hash.split("=")
except ValueError:
continue
if not hashname == "md5":
continue
if filename_matches:
if not self.matches(url, filename_matches):
continue
yield (url, hash)
if external_links:
for link in self._links_external(remote_index_html, filename_matches, follow_external_index_pages):
yield (link, None)
def matches(self, filename, filename_matches):
for filename_match in filename_matches:
if fnmatch.fnmatch(filename, filename_match):
return True
# perhaps 'filename' is part of a query string, so
# try a regex match
for filename_match in filename_matches:
regex = re.compile(r'\\%s\?' % filename_match)
if regex.search(filename):
return True
return False
def ls(self, filename_matches=None, external_links=False, follow_external_index_pages=False):
links = self._links(filename_matches=filename_matches,
external_links=external_links,
follow_external_index_pages=follow_external_index_pages)
return [(link[0], os.path.basename(link[0]), link[1]) for link in links]
def _get(self, url, filename, md5_hex=None):
""" fetches a file and checks for the md5_hex if given
"""
# since some time in Feb 2009 PyPI uses different and relative URLs
# -> complete bullshit
if url.startswith('../../packages'):
url = 'http://pypi.python.org/' + url[6:]
try:
opener = urlopen(url)
data = opener.read()
except urllib2.HTTPError, v:
if '404' in str(v): # sigh
raise PackageError("404: %s" % url)
raise PackageError("Couldn't download (HTTP Error): %s" % url)
except urllib2.URLError, v:
raise PackageError("URL Error: %s " % url)
except:
raise PackageError("Couldn't download (unknown reason): %s" % url)
if md5_hex:
# check for md5 checksum
data_md5 = md5(data).hexdigest()
if md5_hex != data_md5:
raise PackageError("MD5 sum does not match: %s / %s on package %s" %
(md5_hex, data_md5, url))
return data
def get(self, link):
""" link is a tuple of url, md5_hex
"""
return self._get(*link)
def content_length(self, link):
# First try to determine the content-length through
# HEAD request in order to save bandwidth
try:
parts = urlparse.urlsplit(link)
c = httplib.HTTPConnection(parts[1])
c.request('HEAD', parts[2])
response = c.getresponse()
ct = response.getheader('content-length')
if ct is not None:
ct = long(ct)
return ct
except Exception, e:
LOG.warn('Could not obtain content-length through a HEAD request from %s (%s)' % (link, e))
try:
return long(urlopen(link).headers.get("content-length"))
except:
return 0
class Mirror(object):
""" This represents the whole mirror directory
"""
def __init__(self, base_path):
self.base_path = base_path
self.mkdir()
def mkdir(self):
try:
os.mkdir(self.base_path)
except OSError:
# like "File exists"
pass
def package(self, package_name):
return MirrorPackage(self, package_name)
def cleanup(self, remote_list, verbose=False):
local_list = self.ls()
for local_dir in local_list:
try:
if local_dir not in remote_list:
if verbose:
LOG.debug("Removing package: %s" % local_dir)
self.rmr(os.path.join(self.base_path, local_dir))
except UnicodeDecodeError:
if verbose:
LOG.debug("Removing package: %s" % local_dir)
self.rmr(os.path.join(self.base_path, local_dir))
def rmr(self, path):
""" delete a package recursively (not really.)
"""
shutil.rmtree(path)
def ls(self):
filenames = []
for filename in os.listdir(self.base_path):
if os.path.isdir(os.path.join(self.base_path, filename)):
filenames.append(filename)
filenames.sort()
return filenames
def _html_link(self, filename):
return '<a href="%s/">%s</a>' % (filename, filename)
def _index_html(self):
header = "<html><head><title>PyPI Mirror</title></head><body>"
header += "<h1>PyPI Mirror</h1><h2>Last update: " + \
datetime.datetime.utcnow().strftime("%c UTC")+"</h2>\n"
_ls = self.ls()
links = "<br />\n".join([self._html_link(link) for link in _ls])
generator = "<p class='footer'>Generated by %s; %d packages mirrored. For details see the <a href='http://www.coactivate.org/projects/pypi-mirroring'>z3c.pypimirror project page.</a></p>" % (pypimirror_version(), len(_ls))
footer = "</body></html>\n"
return "\n".join((header, links, generator, footer))
def index_html(self):
content = self._index_html()
open(os.path.join(self.base_path, "index.html"), "wb").write(content)
def full_html(self, full_list):
header = "<html><head><title>PyPI Mirror</title></head><body>"
header += "<h1>PyPi Mirror</h1><h2>Last update: " + \
time.strftime("%c %Z")+"</h2>\n"
footer = "</body></html>\n"
fp = file(os.path.join(self.base_path, "full.html"), "wb")
fp.write(header)
fp.write("<br />\n".join(full_list))
fp.write(footer)
fp.close()
def mirror(self,
package_list,
filename_matches,
verbose,
cleanup,
create_indexes,
external_links,
follow_external_index_pages,
base_url):
stats = Stats()
full_list = []
for package_name in package_list:
LOG.debug('Processing package %s' % package_name)
try:
package = Package(package_name)
except PackageError, v:
stats.error_invalid_package(package_name)
LOG.debug("Package is not valid.")
continue
try:
links = package.ls(filename_matches, external_links,
follow_external_index_pages)
except PackageError, v:
stats.error_404(package_name)
LOG.debug("Package not available: %s" % v)
continue
mirror_package = self.package(package_name)
for (url, url_basename, md5_hash) in links:
try:
filename = self._extract_filename(url)
except PackageError, v:
stats.error_invalid_url((url, url_basename, md5_hash))
LOG.info("Invalid URL: %s" % v)
continue
# if we have a md5 check hash and continue if fine.
if md5_hash and mirror_package.md5_match(url_basename, md5_hash):
stats.found(filename)
full_list.append(mirror_package._html_link(base_url,
url_basename,
md5_hash))
if verbose:
LOG.debug("Found: %s" % filename)
continue
# if we don't have a md5, check for the filesize, if available
# and continue if it's the same:
if not md5_hash:
remote_size = package.content_length(url)
if mirror_package.size_match(url_basename, remote_size):
if verbose:
LOG.debug("Found: %s" % url_basename)
full_list.append(mirror_package._html_link(base_url, url_basename, md5_hash))
continue
# we need to download it
try:
data = package.get((url, filename, md5_hash))
except PackageError, v:
stats.error_invalid_url((url, url_basename, md5_hash))
LOG.info("Invalid URL: %s" % v)
continue
mirror_package.write(filename, data, md5_hash)
stats.stored(filename)
full_list.append(mirror_package._html_link(base_url, filename, md5_hash))
if verbose:
LOG.debug("Stored: %s [%d kB]" % (filename, len(data)//1024))
# Disabled cleanup for now since it does not deal with the changelog() implementation
# if cleanup:
# mirror_package.cleanup(links, verbose)
if create_indexes:
mirror_package.index_html(base_url)
# if cleanup:
# self.cleanup(package_list, verbose)
if create_indexes:
self.index_html()
full_list.sort()
self.full_html(full_list)
for line in stats.getStats():
LOG.debug(line)
def _extract_filename(self, url):
"""Get the real filename from an arbitary pypi download url.
Reality sucks, but we need to use heuristics here to avoid a many HEAD
requests. Use them only if heuristics is not possible.
"""
fetch_url = url
do_again = True
while do_again:
# heuristics start
url_basename = os.path.basename(fetch_url)
# do we have GET parameters?
# if not, we believe the basename is the filename
if '?' not in url_basename:
return url_basename
# now we have a bunch of crap in get parameters, we need to do a head
# request to get the filename
LOG.debug("Head-Request to get filename for %s." % fetch_url)
parsed_url = urlparse.urlparse(fetch_url)
if parsed_url.scheme == 'https':
port = parsed_url.port or 443
conn = httplib.HTTPSConnection(parsed_url.netloc, port)
else:
port = parsed_url.port or 80
conn = httplib.HTTPConnection(parsed_url.netloc, port)
conn.request('HEAD', fetch_url)
resp = conn.getresponse()
if resp.status in (301, 302):
fetch_url = resp.getheader("Location", None)
if fetch_url is not None:
continue
raise PackageError, "Redirect (%s) from %s without location" % \
(resp.status, fetch_url)
elif resp.status != 200:
raise PackageError, "URL %s can't be fetched" % fetch_url
do_again = False
content_disposition = resp.getheader("Content-Disposition", None)
if content_disposition:
content_disposition = [_.strip() for _ in \
content_disposition.split(';') \
if _.strip().startswith('filename')]
if len(content_disposition) == 1 and '=' in content_disposition[0]:
return content_disposition[0].split('=')[1].strip('"')
# so we followed redirects and no meaningful name came back, last
# fallback is to use the basename w/o request parameters.
# if this is wrong, it has to fail later.
return os.path.basename(fetch_url[:fetch_url.find('?')])
class MirrorPackage(object):
""" This checks for already existing files and creates the index
"""
def __init__(self, mirror, package_name):
self.package_name = package_name
self.mirror = mirror
self.mkdir()
def mkdir(self):
try:
os.mkdir(self.path())
except OSError:
# like "File exists"
pass
def path(self, filename=None):
if not filename:
return os.path.join(self.mirror.base_path, self.package_name)
return os.path.join(self.mirror.base_path, self.package_name, filename)
def md5_match(self, filename, md5):
file = MirrorFile(self, filename)
return file.md5 == md5
def size_match(self, filename, size):
file = MirrorFile(self, filename)
return file.size == size
def write(self, filename, data, hash=""):
self.mkdir()
file = MirrorFile(self, filename)
file.write(data)
if hash:
file.write_md5(hash)
def rm(self, filename):
MirrorFile(self, filename).rm()
def ls(self):
filenames = []
for filename in os.listdir(self.path()):
if os.path.isfile(self.path(filename)) and filename != "index.html"\
and not filename.endswith(".md5"):
filenames.append(filename)
filenames.sort()
return filenames
def _html_link(self, base_url, filename, md5_hash):
if not base_url.endswith('/'):
base_url += '/'
return '<a href="%s%s/%s#md5=%s">%s</a>' % (base_url, self.package_name, filename, md5_hash, filename)
def _index_html(self, base_url):
header = "<html><head><title>%s – PyPI Mirror</title></head><body>" % self.package_name
footer = "</body></html>"
link_list = []
for link in self.ls():
file = MirrorFile(self, link)
md5_hash = file.md5
link_list.append(self._html_link(base_url, link, md5_hash))
links = "<br />\n".join(link_list)
return "%s%s%s" % (header, links, footer)
def index_html(self, base_url):
content = self._index_html(base_url)
self.write("index.html", content)
def cleanup(self, original_file_list, verbose=False):
remote_list = [link[1] for link in original_file_list]
local_list = self.ls()
for local_file in local_list:
if not local_file.endswith(".md5") and \
local_file not in remote_list:
if verbose:
LOG.debug("Removing: %s" % local_file)
self.rm(local_file)
class MirrorFile(object):
""" This represents a mirrored file. It doesn't have to
exist.
"""
def __init__(self, mirror_package, filename):
self.path = mirror_package.path(filename)
@property
def md5(self):
# use cached md5 sum if available.
if os.path.exists(self.md5_filename):
return open(self.md5_filename,"r").read()
if os.path.exists(self.path):
return md5(open(self.path, "rb").read()).hexdigest()
return None
@property
def size(self):
if os.path.exists(self.path):
return os.path.getsize(self.path)
return 0
def write(self, data):
open(self.path, "wb").write(data)
def rm(self):
""" deletes the file
"""
if os.path.exists(self.path):
os.unlink(self.path)
if os.path.exists(self.md5_filename):
os.unlink(self.md5_filename)
def write_md5(self, hash):
md5_filename = ".%s.md5" % os.path.basename(self.path)
md5_path = os.path.dirname(self.path)
open(os.path.join(md5_path, md5_filename),"w").write(hash)
@property
def md5_filename(self):
md5_filename = ".%s.md5" % os.path.basename(self.path)
md5_path = os.path.dirname(self.path)
return os.path.join(md5_path, md5_filename)
################# Config file parser
default_logfile = os.path.join(tempfile.tempdir or '/tmp', 'pypimirror.log')
config_defaults = {
'base_url': 'http://your-host.com/index/',
'mirror_file_path': '/tmp/mirror',
'lock_file_name': 'pypi-poll-access.lock',
'filename_matches': '*.zip *.tgz *.egg *.tar.gz *.tar.bz2', # may be "" for *
'package_matches': "zope.app.* plone.app.*", # may be "" for *
'cleanup': True, # delete local copies that are remotely not available
'create_indexes': True, # create index.html files
'verbose': True, # log output
'log_filename': default_logfile,
'external_links': False, # experimental external link resolve and download
'follow_external_index_pages' : False, # experimental, scan index pages for links
}
# ATT: fix the configuration behaviour (with non-existing configuration files,
# etc.)
def get_config_options(config_filename):
"""
Get options from the DEFAULT section of our config file
@param dest
Directory configuration file
@return
dict containing a key per option
values are not reformatted - especially multiline options contain
newlines
this contains at least the following key/values:
- include - Glob-Patterns for package names to include
- suffixes - list of suffixes to mirror
"""
if not os.path.exists(config_filename):
return config_defaults
config = ConfigParser.ConfigParser(config_defaults)
config.read(config_filename)
return config.defaults()
def run(args=None):
global LOG
usage = "usage: pypimirror [options] <config-file>"
parser = optparse.OptionParser(usage=usage)
parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
default=False, help='verbose on')
parser.add_option('-f', '--log-filename', dest='log_filename', action='store',
default=False, help='Name of logfile')
parser.add_option('-I', '--initial-fetch', dest='initial_fetch', action='store_true',
default=False, help='Initial PyPI mirror fetch')
parser.add_option('-U', '--update-fetch', dest='update_fetch', action='store_true',
default=False, help='Perform incremental update of the mirror')
parser.add_option('-c', '--log-console', dest='log_console', action='store_true',
default=False, help='Also log to console')
parser.add_option('-i', '--indexes-only', dest='indexes_only', action='store_true',
default=False, help='create indexes only (no mirroring)')
parser.add_option('-e', '--follow-external-links', dest='external_links', action='store_true',
default=False, help='Follow and download external links)')
parser.add_option('-x', '--follow-external-index-pages', dest='follow_external_index_pages', action='store_true',
default=False, help='Follow external index pages and scan for links')
parser.add_option('-d', '--fetch-since-days', dest='fetch_since_days', action='store',
default=7, help='Days in past to fetch for incremental update')
options, args = parser.parse_args()
if len(args) != 1:
parser.error("No configuration file specified")
sys.exit(1)
config_file_name = os.path.abspath(args[0])
config = get_config_options(config_file_name)
# correct things from config
filename_matches = config["filename_matches"].split()
package_matches = config["package_matches"].split()
cleanup = config["cleanup"] in ("True", "1")
create_indexes = config["create_indexes"] in ("True", "1")
verbose = config["verbose"] in ("True", "1") or options.verbose
external_links = config["external_links"] in ("True", "1") or options.external_links
follow_external_index_pages = config["follow_external_index_pages"] in ("True", "1") or options.follow_external_index_pages
log_filename = config['log_filename']
fetch_since_days = int(config.get("fetch_since_days", 0) or options.fetch_since_days)
if options.log_filename:
log_filename = options.log_filename
if options.initial_fetch:
package_list = PypiPackageList().list(package_matches, incremental=False)
elif options.update_fetch:
package_list = PypiPackageList().list(package_matches, incremental=True,
fetch_since_days=fetch_since_days)
else:
raise ValueError('You must either specify the --initial-fetch or --update-fetch option ')
package_list = set(package_list)
mirror = Mirror(config["mirror_file_path"])
lock = zc.lockfile.LockFile(os.path.join(config["mirror_file_path"], config["lock_file_name"]))
LOG = getLogger(filename=log_filename,
log_console=options.log_console)
if options.indexes_only:
mirror.index_html()
else:
mirror.mirror(package_list,
filename_matches,
verbose,
cleanup,
create_indexes,
external_links,
follow_external_index_pages,
config["base_url"])
if __name__ == '__main__':
sys.exit(run()) | z3c.pypimirror | /z3c.pypimirror-1.0.16.tar.gz/z3c.pypimirror-1.0.16/src/z3c/pypimirror/mirror.py | mirror.py |
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
try:
import pkg_resources
import setuptools
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
reload(sys.modules['pkg_resources'])
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.quickentry | /z3c.quickentry-0.1.tar.gz/z3c.quickentry-0.1/bootstrap.py | bootstrap.py |
__docformat__ = "reStructuredText"
import zope.interface
import zope.schema
class IProcessError(zope.interface.Interface):
position = zope.schema.Int(
title=u'Position',
description=u'The position at which the error occured.',
required=True)
reason = zope.schema.Text(
title=u'Reason',
description=u'The reason for the parse error.',
required=True)
class ProcessError(Exception):
zope.interface.implements(IProcessError)
def __init__(self, position, reason):
self.position = position
self.reason = reason
def __repr__(self):
return '<%s at pos %r: %r>' %(
self.__class__.__name__, self.position, self.reason)
def __str__(self):
return self.reason + u' (Position %i)' %self.position
class IProcessor(zope.interface.Interface):
"""A processor for a quick entry text."""
separationCharacter = zope.interface.Attribute(
'Each value is separated by this character.')
plugins = zope.interface.Attribute(
'A sequence of plugin classes that are used to parse the text.')
def parse(text):
"""Parse the text into a tuple of plugin instances."""
def process(text, context=None):
"""Process a quick entry text.
The context can be used by plugins to look up values.
The returned value should be a dictionary of extracted variables.
"""
class IExecutingProcessor(IProcessor):
"""A processor that can apply the parsed data to a context."""
def apply(text, context):
"""Apply data once it is parsed.
The data is applied on the context.
"""
class IPlugin(zope.interface.Interface):
"""A plugin for a particular piece of the quick entry text."""
text = zope.interface.Attribute(
'The text that is going to be converted into values. '
'The processor will fill this attribute after the initial text is set.')
position = zope.schema.Int(
title=u'Position',
description=u'The position at which the text started',
default=0,
required=True)
def canProcess():
"""Determine whether the plugin can handle the text.
Returns a boolean stating the result.
"""
def process(context):
"""Process the text to create the varaiable names.
The result will be a dictionary from variable name to value. While
plugins often will only produce one variable, they can produce several.
If processing fails for some reason, a ``ValueError`` with a detailed
explanation must be raised.
"""
class IExecutingPlugin(IPlugin):
"""A plugin that can apply the parsed data to a context."""
def apply(text, context=None):
"""Apply data once it is parsed.
The data is applied on the context.
""" | z3c.quickentry | /z3c.quickentry-0.1.tar.gz/z3c.quickentry-0.1/src/z3c/quickentry/interfaces.py | interfaces.py |
__docformat__ = "reStructuredText"
import re
import zope.interface
from z3c.quickentry import interfaces
class BasePlugin(object):
"""An abstract base plugin."""
zope.interface.implements(interfaces.IPlugin)
def __init__(self, initialText, position=0):
self.text = initialText
self.position = position
def canProcess(self):
"""See interfaces.IPlugin"""
raise NotImplementedError
def process(self, context):
"""See interfaces.IPlugin"""
raise NotImplementedError
def __repr__(self):
return '<%s %r>' % (self.__class__.__name__, self.text)
class ShortNamePlugin(BasePlugin):
"""Abstract plugin that retrieves a value by short name assignment."""
# This needs to be overridden by a subclass.
shortName = 'sn'
varName = 'shortName'
def canProcess(self):
"""See interfaces.IPlugin"""
return self.text.startswith(self.shortName + '=')
def process(self, context):
"""See interfaces.IPlugin"""
return {self.varName: unicode(self.text[len(self.shortName)+1:])}
def __repr__(self):
return '<%s shortName=%r, varName=%r>' % (
self.__class__.__name__, self.shortName, self.varName)
class RegexPlugin(BasePlugin):
"""Abstract Plugin that determines the ability to process using a regular
expression.
"""
# This needs to be overridden by a subclass.
regex = None
varName = ''
def canProcess(self):
"""See interfaces.IPlugin"""
return self.regex.match(self.text) is not None
def process(self, context):
"""See interfaces.IPlugin"""
if self.regex.match(self.text) is None:
raise interfaces.ProcessError(
self.position,
(u'The regex did match anymore. Probably some text '
u'was added later that disrupted the pattern.'))
return {self.varName: unicode(self.text)}
def __repr__(self):
return '<%s varName=%r>' % (self.__class__.__name__, self.varName)
class SetAttributeMixin(object):
zope.interface.implements(interfaces.IExecutingPlugin)
def apply(self, context):
for name, value in self.process(context).items():
setattr(context, name, value) | z3c.quickentry | /z3c.quickentry-0.1.tar.gz/z3c.quickentry-0.1/src/z3c/quickentry/plugin.py | plugin.py |
===========
Quick Entry
===========
The quick entry processor allows a user to efficiently specify multiple values
in one larger text block. The processor uses plugins to dynamically define the
commands to handle.
This type of input is not aimed at the average user, but at power users and
users that can be trained. The syntax is purposefully minimized to maximize
the input speed. This method of entry has been verified in a real life
setting.
Processor Plugins
-----------------
Let's start by looking at the processor plugins, which can handle one piece of
the quick entry text. The first plugin type can handle strings of the form:
<shortName>=<value>
A base implementation of this plugin is provided by the package. Let's create
a plugin that can process a name:
>>> from z3c.quickentry import plugin
>>> class NamePlugin(plugin.ShortNamePlugin):
... shortName = 'nm'
... varName = 'name'
Any plugin is instantiated using an initial text and optionally a position
that is used during error reporting:
>>> name = NamePlugin('nm=Stephan')
>>> name
<NamePlugin shortName='nm', varName='name'>
>>> NamePlugin('nm=Stephan', 35)
<NamePlugin shortName='nm', varName='name'>
You can now ask the plugin, whether it can process this text:
>>> name.canProcess()
True
>>> NamePlugin('n=Stephan').canProcess()
False
>>> NamePlugin('Stephan').canProcess()
False
Sometimes the processor adds more text later:
>>> name.text += ' Richter'
Once all pieces have been processed by the quick entry processor, each
instantiated plugin gets processed. The result of this action is a dictionary:
>>> name.process(None)
{'name': u'Stephan Richter'}
The second type of plugin matches a regular expression to determine whether a
piece of text can be processed. Let's create a phone number plugin:
>>> import re
>>> class PhonePlugin(plugin.RegexPlugin):
... regex = re.compile('^[0-9]{3}-[0-9]{3}-[0-9]{4}$')
... varName = 'phone'
This plugin is also instantiated using an initial text:
>>> phone = PhonePlugin('978-555-5300')
>>> phone
<PhonePlugin varName='phone'>
You can now ask the plugin, whether it can process this text:
>>> name.canProcess()
True
>>> PhonePlugin('(978) 555-5300').canProcess()
False
>>> PhonePlugin('+1-978-555-5300').canProcess()
False
Let's now process the plugin:
>>> phone.process(None)
{'phone': u'978-555-5300'}
If the text changes, so that the plugin cannot parse the text anymore, a
process error is raised:
>>> phone.text += ' (ext. 2134)'
>>> phone.process(None)
Traceback (most recent call last):
...
ProcessError: The regex did match anymore. Probably some text was added
later that disrupted the pattern. (Position 0)
Finally let's have a look at a more advanced example. We would like to be able
to handle the string "<age><gender>" and parse it into 2 variables:
>>> from z3c.quickentry import interfaces
>>> class AgeGenderPlugin(plugin.BasePlugin):
... regex = re.compile('([0-9]{1,3})([FM])')
...
... def canProcess(self):
... return self.regex.match(self.text) is not None
...
... def process(self, context):
... match = self.regex.match(self.text)
... if match is None:
... raise interfaces.ProcessError(self.position, u'Error here.')
... return {'age': int(match.groups()[0]),
... 'gender': unicode(match.groups()[1])}
Let's now make sure that the plugin can handle several strings:
>>> AgeGenderPlugin('27M').canProcess()
True
>>> AgeGenderPlugin('8F').canProcess()
True
>>> AgeGenderPlugin('101F').canProcess()
True
>>> AgeGenderPlugin('27N').canProcess()
False
>>> AgeGenderPlugin('M').canProcess()
False
>>> AgeGenderPlugin('18').canProcess()
False
Let's also make sure it is processed correctly:
>>> from pprint import pprint
>>> pprint(AgeGenderPlugin('27M').process(None))
{'age': 27, 'gender': u'M'}
>>> pprint(AgeGenderPlugin('8F').process(None))
{'age': 8, 'gender': u'F'}
>>> pprint(AgeGenderPlugin('101F').process(None))
{'age': 101, 'gender': u'F'}
When an error occurs at any point during the processing, a process error must
be raised:
>>> pprint(AgeGenderPlugin('27N').process(None))
Traceback (most recent call last):
...
ProcessError: Error here. (Position 0)
The plugin above used the ``BasePlugin`` class to minimize the
boilerplate. The base plugin requires you to implement the ``canProcess()``
and ``process()``:
>>> base = plugin.BasePlugin('some text')
>>> base.canProcess()
Traceback (most recent call last):
...
NotImplementedError
>>> base.process(None)
Traceback (most recent call last):
...
NotImplementedError
Executing Plugins
-----------------
An optional feature of the package is the ability for the plugin to apply the
parsed data directly to a specified context. The simplest such case is to
simply set the attribute on the context. For this use case we have a mix-in
class:
>>> class ExecutingAgeGenderPlugin(AgeGenderPlugin, plugin.SetAttributeMixin):
... pass
Let's now create a person on which the attributes can be stored:
>>> class Person(object):
... name = None
... phone = None
... age = None
... gender = None
>>> stephan = Person()
Let's now apply the executing age/gender plugin onto the person:
>>> stephan.age
>>> stephan.gender
>>> ExecutingAgeGenderPlugin('27M').apply(stephan)
>>> stephan.age
27
>>> stephan.gender
u'M'
Processors
----------
The processor collects several plugins and handles one large chunk of quick
entry text. Let's create a processor for the plugins above, using the default
whitespace character as field separator:
>>> from z3c.quickentry import processor
>>> info = processor.BaseProcessor()
>>> info.plugins = (NamePlugin, PhonePlugin, AgeGenderPlugin)
The lowest level step of the processor is the parsing of the text; the result
is a sequence of plugin instances:
>>> info.parse('nm=Stephan 27M')
[<NamePlugin shortName='nm', varName='name'>, <AgeGenderPlugin '27M'>]
Let's now parse and process a simple texts that uses some or all plugins:
>>> pprint(info.process('nm=Stephan 27M'))
{'age': 27, 'gender': u'M', 'name': u'Stephan'}
>>> pprint(info.process('978-555-5300 27M'))
{'age': 27, 'gender': u'M', 'phone': u'978-555-5300'}
>>> pprint(info.process('nm=Stephan 978-555-5300 27M'))
{'age': 27, 'gender': u'M', 'name': u'Stephan', 'phone': u'978-555-5300'}
Note that you can also have names that contain spaces, because the last name
cannot be matched to another plugin:
>>> pprint(info.process('nm=Stephan Richter 27M'))
{'age': 27, 'gender': u'M', 'name': u'Stephan Richter'}
Optionally, you can also provide a processing context that can be used to look
up values (for example vocabularies):
>>> pprint(info.process('nm=Stephan Richter 27M', context=object()))
{'age': 27, 'gender': u'M', 'name': u'Stephan Richter'}
Let's now change the separation character to a comma:
>>> info.separationCharacter = ','
>>> pprint(info.process('nm=Stephan Richter,27M', context=object()))
{'age': 27, 'gender': u'M', 'name': u'Stephan Richter'}
But what happens, if no plugin can be found. Then a process error is raised:
>>> info.process('err=Value', context=object())
Traceback (most recent call last):
...
ProcessError: No matching plugin found. (Position 0)
Executing Processors
--------------------
These processors can apply all of the plugins on a context. Let's convert the
remaining plugins to be executable:
>>> class ExecutingNamePlugin(NamePlugin, plugin.SetAttributeMixin):
... pass
>>> class ExecutingPhonePlugin(PhonePlugin, plugin.SetAttributeMixin):
... pass
Let's now create a new user and create an executing processor:
>>> stephan = Person()
>>> proc = processor.ExecutingBaseProcessor()
>>> proc.plugins = (
... ExecutingNamePlugin, ExecutingPhonePlugin, ExecutingAgeGenderPlugin)
>>> proc.apply('nm=Stephan 978-555-5300 27M', stephan)
>>> stephan.name
u'Stephan'
>>> stephan.phone
u'978-555-5300'
>>> stephan.age
27
>>> stephan.gender
u'M'
| z3c.quickentry | /z3c.quickentry-0.1.tar.gz/z3c.quickentry-0.1/src/z3c/quickentry/README.txt | README.txt |
__docformat__ = "reStructuredText"
import zope.interface
from z3c.quickentry import interfaces
class BaseProcessor(object):
"""A base class for a processor."""
zope.interface.implements(interfaces.IProcessor)
# See interfaces.IProcessor
separationCharacter = ' '
# This needs to be properly implemented in a subclass.
plugins = ()
def parse(self, text):
position = 0
# Step 0: Get the sequence of all plugins; we store the result
# locally, since the lookup might be expensive.
plugins = self.plugins
# Step 1: Split the entire text using the separation character
pieces = text.split(self.separationCharacter)
# Whenever a plugin is found that can handle a piece of text, it is
# added to the result list
result = []
# Step 2: Now iterate through every piece and try to process them
for piece in pieces:
# Step 2.1: Check each plugin to see if it can process the piece
for pluginClass in plugins:
plugin = pluginClass(piece, position)
# Step 2.2: If the plugin can process, add it to the result
if plugin.canProcess():
result.append(plugin)
break
# Step 2.3: If no plugin can handle the piece, it is simply added
# to the text of the last plugin's test.
else:
if len(result) == 0:
raise interfaces.ProcessError(
position, u'No matching plugin found.')
result[-1].text += self.separationCharacter
result[-1].text += piece
# Step 2.4: Update the position
# (add one for the separation character)
position += len(piece) + 1
return result
def process(self, text, context=None):
"""See interfaces.IProcessor"""
resultDict = {}
for plugin in self.parse(text):
resultDict.update(plugin.process(context))
return resultDict
class ExecutingBaseProcessor(BaseProcessor):
def apply(self, text, context):
"""See interfaces.IProcessor"""
for plugin in self.parse(text):
plugin.apply(context) | z3c.quickentry | /z3c.quickentry-0.1.tar.gz/z3c.quickentry-0.1/src/z3c/quickentry/processor.py | processor.py |
=========
CHANGES
=========
2.0 (2023-02-20)
================
- Add support for Python 3.9, 3.10, 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
1.1.0 (2020-05-14)
==================
- Drop support for Python 2.6, 3.2, 3.3 and 3.4.
- Add support for Python 3.5, 3.6, 3.7, 3.8, PyPy2 and PyPy3.
- Fix file descriptor leaks. See `issue 1 <https://github.com/zopefoundation/z3c.recipe.compattest/issues/1>`_.
1.0 (2013-03-02)
================
- Depend on buildout 2 and zc.recipe.testrunner 2.
0.13.1 (2010-12-17)
===================
- Fix tests on windows.
- Fix for use with a python executable from inside a virtualenv.
0.13 (2010-10-07)
=================
- Depend on and use the new features of the zc.buildout 1.5 line. At the same
time support for zc.buildout <= 1.5.1 has been dropped.
- Updated test set up, to run with newer ``zope.testing`` version which no
longer includes testrunner.
- The z3c.recipe.scripts.scripts recipe behind zc.recipe.testrunner.TestRunner
does not accept plain dicts anymore, so we wrap the options in a
_BackwardsSupportOptions object. Ideally this should've use an official
API though.
0.12.2 (2010-02-24)
===================
- Moved the gathering of include-dependencies from the __init__ to the update
method to prevent installing dependencies before other buildout parts could
do their job.
0.12.1 (2009-12-15)
===================
- Fixed bug in using exclude introduced in 0.12 (including test to make sure
it doesn't happen again).
0.12 (2009-12-14)
=================
- Added ``include-dependencies`` option that automatically includes the
dependencies of the specified packages. Very handy to get an automatically
updated list of those packages that are most useful to test: all our
dependencies.
0.11 (2009-09-30)
=================
- Removed the "check out packages from subversion" feature.
If you require such functionality, mr.developer
<http://pypi.python.org/pypi/mr.developer> provides this much more
comprehensively (and for multiple version control systems, too) .
0.10 (2009-09-28)
=================
- Options prefixed by ``runner-`` are automatically passed to generated test
runners.
0.9 (2009-09-14)
================
- Test runner: return the exit code 1 in case of test failures; this simplifies
buildbot configurations.
0.8 (2009-08-17)
================
- Windoes is now supported.
- Changed the default master script name to the part name. (Don't add
a "test-" prefix any more.)
0.7 (2009-08-13)
================
- Simplified building the list of packages even more: we now just take a list of
packages, period.
0.6 (2009-08-07)
================
- Restructured the way we construct our list of packages to test:
We no longer filter a list we retrieved from SVN with includes/excludes,
but use an explicit list that can be populated from a buildout section,
e. g. [versions]. Thus, we can now easily test against a KGS.
- Always enable all extras of packages under test.
0.5 (2009-01-29)
================
- Fix duplicate `url` parameter in setup.py that confused Python 2.4 but
got accepted by Python 2.5.
0.4 (2009-01-29)
================
- Ignore missing package releases for packages listed in Subversion (as
long as we don't try to run from Subversion).
- Allow parallel execution of the individual test runners by stating
'max_jobs=X' in the recipe's options.
0.3 (2009-01-28)
================
- Adding the exclude parameter in buildout causes the default exclude
list to be merged with the option in buildout.cfg.
0.2 (2009-01-28)
================
- Implemented use_svn option to use SVN trunk checkouts instead of released
versions.
0.1 (2009-01-28)
================
- first released version
| z3c.recipe.compattest | /z3c.recipe.compattest-2.0.tar.gz/z3c.recipe.compattest-2.0/CHANGES.rst | CHANGES.rst |
=====================
z3c.recipe.compattest
=====================
This buildout recipe generates a list of packages to test and a test runner
that runs each package's tests (isolated from any other tests).
This is useful to check that the changes made while developing a package
do not break any packages that are using this package.
Usage
=====
Add a part to your buildout.cfg that uses this recipe.
No further configuration is required, but you can set the following options:
- ``include``: list of packages to include (whitespace-separated)
(default: empty)
- ``include-dependencies``: list of packages to include *including* their
direct dependencies. (default: empty)
- ``exclude``: packages matching any regex in this list will be excluded
(default: empty)
- ``script``: the name of the runner script (defaults to the part name)
>>> cd(sample_buildout)
>>> write('buildout.cfg', """
... [buildout]
... parts = compattest
...
... [compattest]
... recipe = z3c.recipe.compattest
... include = z3c.recipe.compattest
... """)
>>> 'Installing compattest' in system(buildout)
True
Details
=======
The recipe generates a test runner for each package, as well as a global runner
script (called `test-compat` by default) that will run all of them:
>>> ls('bin')
- buildout
- compattest
- compattest-z3c.recipe.compattest
>>> cat('bin', 'compattest')
#!...py...
...main(...compattest-z3c.recipe.compattest...
We take care about installing the test dependencies for the packages
(from their ``extras_require['test']``). To demonstrate this, we
declared a (superfluous) test dependency on ``zope.dottedname``, which is
picked up (if the package is already installed in a virtual environment, we cannot
find these dependencies):
>>> try:
... print('start')
... cat('parts', 'compattest-z3c.recipe.compattest', 'site-packages', 'site.py')
... except IOError:
... # When the tests are run from a virtualenv, the bin scripts are created
... # in a different location, and if we are also installed in
... # that location, we don't have to install any extras ourself.
... cat('bin', 'compattest-z3c.recipe.compattest')
... print('zope.dottedname')
start
...zope.dottedname...
If we use ``include-dependencies`` instead of just ``include``, its direct
dependencies are also picked up, for instance zc.buildout:
>>> write('buildout.cfg', """
... [buildout]
... parts = compattest
...
... [compattest]
... recipe = z3c.recipe.compattest
... include-dependencies = z3c.recipe.compattest
... """)
>>> print('start' + system(buildout))
start...
...
Generated script '/sample-buildout/bin/compattest-zc.buildout'.
...
All our direct dependencies have a test script now:
>>> ls('bin')
- buildout
- compattest
- compattest-z3c.recipe.compattest
- compattest-zc.buildout
- compattest-zc.recipe.testrunner
And if you want to exclude one of the automatically included dependencies, use
the ``exclude`` option:
>>> write('buildout.cfg', """
... [buildout]
... parts = compattest
...
... [compattest]
... recipe = z3c.recipe.compattest
... include-dependencies = z3c.recipe.compattest
... exclude = zc.buildout
... """)
>>> print('start' + system(buildout))
start...
Generated script '/sample-buildout/bin/compattest'...
``bin/compattest-zc.buildout`` is now missing:
>>> ls('bin')
- buildout
- compattest
- compattest-z3c.recipe.compattest
- compattest-zc.recipe.testrunner
Passing options to the test runners
===================================
If you want to use custom options in the generated test runners, you can specify
them in the part options, prefixed by ``runner-``. That is, if you want to pass
the ``--foo`` option by default to all generated test runners, you can set
``runner-defaults = ['--foo']`` in your part:
>>> write('buildout.cfg', """
... [buildout]
... parts = compattest
...
... [compattest]
... recipe = z3c.recipe.compattest
... include = z3c.recipe.compattest
... runner-defaults = ['-c', '-v', '-v']
... """)
>>> ignore = system(buildout)
>>> cat('bin', 'compattest-z3c.recipe.compattest')
#!...py...
...run(...['-c', '-v', '-v']...
Every options prefixed by ``runner-`` will be automatically passed to the
generated test runners.
Passing Extra paths to the test runners
=======================================
If you want to add some paths to the generated test runners, you can do it with
the extra-paths option in the part. This might be interesting if you want to test packages
that depends on zope2 < 2.12:
>>> write('buildout.cfg', """
... [buildout]
... parts = compattest
...
... [compattest]
... recipe = z3c.recipe.compattest
... include = z3c.recipe.compattest
... extra-paths = zope2location/lib/python
... """)
>>> ignore = system(buildout)
>>> try:
... print('start')
... cat('parts', 'compattest-z3c.recipe.compattest', 'site-packages', 'site.py')
... except IOError:
... print('start')
... # When the tests are run from a virtualenv, the bin scripts are created
... # in a different location.
... cat('bin', 'compattest-z3c.recipe.compattest')
start
...zope2location/lib/python...
| z3c.recipe.compattest | /z3c.recipe.compattest-2.0.tar.gz/z3c.recipe.compattest-2.0/README.rst | README.rst |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.recipe.compattest | /z3c.recipe.compattest-2.0.tar.gz/z3c.recipe.compattest-2.0/LICENSE.rst | LICENSE.rst |
=====================================
Combined runner for multiple packages
=====================================
To run the compatibility tests for the huge amount of individual
packages in isolation we provide a wrapper script which runs all
individual test runners together, but each in a separate process.
It monitors the stdout of those processes and reports back packages with
failures.
>>> import os, sys
>>> # Re-use zc.buildout internals in order to handle both windows
>>> # and other environments.
>>> from zc.buildout.easy_install import _create_script
>>> ok_script = os.path.join(sample_buildout, 'test-ok')
>>> _ = _create_script('''\
... #!%s
... import time
... time.sleep(1)
... print('ok') ''' % sys.executable, ok_script)
>>> failure_script = os.path.join(sample_buildout, 'test-failure')
>>> _ = _create_script('''\
... #!%s
... import time
... time.sleep(1)
... raise SystemError('Fail!') ''' % sys.executable, failure_script)
>>> from z3c.recipe.compattest.runner import main
>>> main(1, ok_script, failure_script, no_exit_code=True)
Running test-ok
Running test-failure
test-failure failed with:
Traceback (most recent call last):
...
SystemError: Fail!
<BLANKLINE>
1 failure(s).
- test-failure
Note that when we pass a number greater than 1 as the first argument,
tests are run in parallel, so the order of output varies.
>>> main(2, failure_script, ok_script, failure_script, ok_script, \
... no_exit_code=True)
Running ...
2 failure(s).
- test-failure
- test-failure
| z3c.recipe.compattest | /z3c.recipe.compattest-2.0.tar.gz/z3c.recipe.compattest-2.0/src/z3c/recipe/compattest/runner.rst | runner.rst |
import os.path
import pickle
import subprocess
import sys
import time
from io import StringIO
def usage():
print("""
usage: %s [OPTIONS]
All given options will be passed to each test runner. To know which
options you can use, refer to the test runner documentation.
""" % sys.argv[0])
windoze = sys.platform.startswith('win')
class Job:
exitcode = None
process = None
began = 0
end = 0
def __init__(self, script, args):
self.script = script
self.args = args
self.name = os.path.basename(script)
self.output = StringIO()
def start(self):
self.began = time.time()
cmd = [self.script]
# We are dealing with two problems: windoze and virtualenv.
if windoze:
# Use zc.buildout internal to sniff a virtualenv.
cmd = [self.script + '.exe']
self.process = subprocess.Popen(
cmd + ['--exit-with-status'] + self.args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=not windoze,
)
def poll(self):
if self.process is not None:
self.exitcode = self.process.poll()
if self.exitcode is not None and self.process is not None:
self.end = time.time()
# We're done, get all remaining output.
data = self.process.stdout.read()
# Close the pipes and cleanup.
self.process.communicate()
self.process = None
else:
# We're not done, so just get some
data = self.process.stdout.readline()
self.output.write(data.replace(b'\r\n', b'\n').decode('utf-8'))
def main(max_jobs, *scripts, **options):
argv = sys.argv[1:]
if '-h' in argv or '--help' in argv:
usage()
return
running = []
completed = []
scripts = list(scripts)
# Read statistics from the last run and re-order testing to start
# the slowest tests first.
stat_file_name = os.path.join(os.path.expanduser('~'), '.zope.teststats')
try:
with open(stat_file_name, 'rb') as stat_file:
stats = pickle.load(stat_file)
except OSError:
stats = {}
if stats:
default_time = sum(stats.values()) / float(len(stats))
else:
default_time = 0
scripts.sort(
key=lambda package: -stats.get(os.path.basename(package), default_time)
)
# Main loop for controlling test runs
while scripts or running:
for job in running:
job.poll()
if job.exitcode is None:
continue
completed.append(job)
running.remove(job)
if job.exitcode:
print(job.name, "failed with:")
print(job.output.getvalue())
while (len(running) < max_jobs) and scripts:
script = scripts.pop(0)
job = Job(script, sys.argv[1:])
print("Running", job.name)
job.start()
running.append(job)
# Result output
failures = [job for job in completed if job.exitcode]
print(len(failures), "failure(s).")
for job in failures:
print("-", job.name)
# Store statistics
for job in completed:
stats[job.name] = job.end - job.began
try:
with open(stat_file_name, 'wb') as stat_file:
pickle.dump(stats, stat_file)
except OSError:
# Statistics aren't that important. Just ignore that.
pass
if not options.get('no_exit_code') and failures:
sys.exit(1) | z3c.recipe.compattest | /z3c.recipe.compattest-2.0.tar.gz/z3c.recipe.compattest-2.0/src/z3c/recipe/compattest/runner.py | runner.py |
import os
import re
import pkg_resources
import zc.buildout.easy_install
import zc.recipe.egg
import zc.recipe.testrunner
def string2list(string, default):
result = string and string.split() or default
return [item.strip() for item in result]
RUNNER_PREFIX = 'runner-'
class Recipe:
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
if 'max_jobs' not in options:
options['max_jobs'] = '1'
self.include = string2list(self.options.get('include', ''), [])
self.include_dependencies = string2list(
self.options.get('include-dependencies', ''), [])
self.exclude = string2list(self.options.get('exclude', ''), [])
self.extra_paths = self.options.get('extra-paths', '')
self.script = self.options.get('script', self.name)
# gather options to be passed to the underlying testrunner
self.testrunner_options = {}
for opt in self.options:
if opt.startswith(RUNNER_PREFIX):
runner_opt = opt[len(RUNNER_PREFIX):]
self.testrunner_options[runner_opt] = self.options[opt]
def install(self):
return self.update()
def update(self):
wanted_packages = self._wanted_packages()
installed = []
installed.extend(self._install_testrunners(wanted_packages))
installed.extend(self._install_run_script(wanted_packages))
return installed
def _install_testrunners(self, wanted_packages):
installed = []
for package_name in wanted_packages:
ws = self._working_set(package_name)
package = ws.find(pkg_resources.Requirement.parse(package_name))
# Installing arbitrary extras here leads to problems in
# reproducibility.
# In particular, setuptools[tests] causes a huge dependency tree
# to be brought in.
extras = '[{}]'.format(
','.join(ex for ex in package.extras if ex in ['test']))
if package_name == 'zc.buildout':
# Installing the test dependencies for zc.buildout is also a
# problem, they don't all provide test extras
extras = ''
options = self.testrunner_options.copy()
options['eggs'] = package_name + extras
print("Installing", options['eggs'])
if self.extra_paths:
options['extra-paths'] = self.extra_paths
recipe = zc.recipe.testrunner.TestRunner(
self.buildout, f'{self.name}-{package_name}', options)
installed.extend(recipe.install())
return installed
def _install_run_script(self, wanted_packages):
bindir = self.buildout['buildout']['bin-directory']
runners = ['{}-{}'.format(self.name, package) for package
in wanted_packages]
runners = [repr(os.path.join(bindir, runner)) for runner in runners]
return zc.buildout.easy_install.scripts(
[(self.script, 'z3c.recipe.compattest.runner', 'main')],
self._working_set('z3c.recipe.compattest'),
self.buildout['buildout']['executable'],
bindir, arguments='{}, {}'.format(self.options['max_jobs'],
', '.join(runners)))
def _find_dependencies(self):
result = []
if not self.include_dependencies:
return result
for package in self.include_dependencies:
result.append(package)
ws = self._working_set(package)
dist = ws.find(pkg_resources.Requirement.parse(package))
for requirement in dist.requires():
dist = ws.find(requirement)
if not dist:
continue
result.append(dist.project_name)
return result
def _wanted_packages(self):
projects = self.include + self._find_dependencies()
projects = list(set(projects)) # Filter out duplicates.
for project in projects:
for regex in self.exclude:
if re.compile(regex).search(project):
projects.remove(project)
break
return projects
def _working_set(self, package):
eggs = zc.recipe.egg.Egg(self.buildout, self.name, dict(eggs=package))
_, ws = eggs.working_set()
return ws | z3c.recipe.compattest | /z3c.recipe.compattest-2.0.tar.gz/z3c.recipe.compattest-2.0/src/z3c/recipe/compattest/recipe.py | recipe.py |
import os
GENERATE = "./bin/%(scriptname)s %(exclude)s %(re_exclude)s %(dead_ends)s %(re_dead_ends)s %(extras)s-d \"%(package)s\" -i setuptools > %(output)s"
TRED = "tred %(input)s > %(output)s"
GRAPH = "dot -T%(format)s %(input)s > %(output)s"
SCCMAP = "sccmap %(input)s > %(output)s"
SCCGRAPH = "dot -T%(format)s %(input)s -O"
def execute(template, **kwargs):
os.system(template % kwargs)
def build_option(option, pattern):
result = ''
for i in pattern:
result += '%s %s ' % (option, i)
return result
def main(args):
name = args.get('name')
packages = args.get('packages')
package_map = args.get('package_map')
path = args.get('path')
scriptname = name + '-eggdeps'
variants = args.get('variants', ['base', 'tred', 'scc'])
formats = args.get('formats', ['svg'])
extras = args.get('extras')
exclude = build_option('-i', args.get('exclude'))
re_exclude = build_option('-I', args.get('re_exclude'))
dead_ends = build_option('-e', args.get('dead_ends'))
re_dead_ends = build_option('-E', args.get('re_dead_ends'))
for package in packages:
name = package.split('[', 1)[0].strip()
if name in package_map:
name = package_map[name]
deeppath = os.path.join(path, name.replace('.', os.sep))
if not os.path.exists(deeppath):
os.makedirs(deeppath)
if extras:
extras = '-x '
else:
extras = ''
specfile = os.path.join(deeppath, 'spec')
execute(GENERATE,
extras=extras,
scriptname=scriptname,
package=package,
exclude=exclude,
re_exclude=re_exclude,
dead_ends=dead_ends,
re_dead_ends=re_dead_ends,
output=specfile + '.dot')
for format in formats:
execute(GRAPH,
format=format,
input=specfile + '.dot',
output=specfile + '.%s' % format)
if 'tred' in variants:
execute(TRED,
input=specfile + '.dot',
output=specfile + '-tred.dot')
for format in formats:
execute(GRAPH,
format=format,
input=specfile + '-tred.dot',
output=specfile + '-tred.%s' % format)
if 'scc' in variants:
execute(SCCMAP,
input=specfile + '.dot',
output=specfile + '-sccmap')
for format in formats:
execute(SCCGRAPH,
format=format,
input=specfile + '-sccmap') | z3c.recipe.depgraph | /z3c.recipe.depgraph-0.5.zip/z3c.recipe.depgraph-0.5/src/z3c/recipe/depgraph/runner.py | runner.py |
import os
import re
from zc.buildout import easy_install
from zc.recipe.egg import Egg
EXCLUDE_PACKAGES = set((
'lxml',
'pytz',
'setuptools',
'tl.eggdeps',
'z3c.recipe.depgraph',
'zc.buildout',
'zc.recipe.egg',
))
class Recipe(object):
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
self.egg = Egg(buildout, options['recipe'], options)
self.eggs = self.options.get('eggs', '').split('\n')
self.strict = self.options.get('strict', '').lower() in ('1', 'true', 'yes')
exclude = self.options.get('exclude', '')
re_exclude = self.options.get('re-exclude', '')
dead_ends = self.options.get('dead-ends', '')
re_dead_ends = self.options.get('re-dead-ends', '')
self.exclude = set(exclude.split())
self.re_exclude = set(re_exclude.split())
self.dead_ends = set(dead_ends.split())
self.re_dead_ends = set(re_dead_ends.split())
self.output = self.options.get(
'output', os.path.join(
self.buildout['buildout']['parts-directory'], self.name))
extras = self.options.get('extras', 'false')
self.extras = extras.lower() in ('1', 'true', 'yes')
self.formats = self.options.get('formats', 'svg').split()
def install(self):
options = self.options
reqs, ws = self.egg.working_set(['z3c.recipe.depgraph'])
if not os.path.exists(self.output):
os.mkdir(self.output)
variants = options.get('variants', 'base tred scc')
variants = [v.strip() for v in variants.split()]
def matcher(names, patterns):
names = set(names)
matched_names = set()
compiled_patterns = [re.compile(pattern) for pattern in patterns]
def match(name, compiled_patterns):
for pattern in compiled_patterns:
if pattern.search(name):
# matching one pattern is sufficient
matched_names.add(name)
return
for name in names:
match(name, compiled_patterns)
return matched_names
if self.strict:
# use only eggs in the list
packages = self.eggs
else:
# Install an interpreter to find eggs
packages = set([dist.project_name for dist in ws.by_key.values()])
# Remove eggs listed in exclude option
packages = packages - EXCLUDE_PACKAGES - self.exclude
# Remove eggs listed in re-exclude option
packages = packages - matcher(packages, self.re_exclude)
packages = list(packages)
# Allow to map distribution names to different package names
pmap = dict()
package_map = options.get('package-map', '').strip()
if package_map:
pmap = self.buildout[package_map]
packages.sort()
easy_install.scripts(
[('graph-%s' % self.name, 'z3c.recipe.depgraph.runner', 'main')],
ws, options['executable'], options['bin-directory'],
arguments=dict(
packages=packages,
package_map=package_map,
name=self.name,
path=self.output,
variants=variants,
formats=self.formats,
extras=self.extras,
exclude = self.exclude,
re_exclude = self.re_exclude,
dead_ends = self.dead_ends,
re_dead_ends = self.re_dead_ends
),
)
reqs = ['tl.eggdeps']
scripts = {
'eggdeps' : '%s-eggdeps' % self.name
}
easy_install.scripts(
reqs, ws, options['executable'], options['bin-directory'],
scripts=scripts,
)
return self.output
def update(self):
self.install() | z3c.recipe.depgraph | /z3c.recipe.depgraph-0.5.zip/z3c.recipe.depgraph-0.5/src/z3c/recipe/depgraph/recipe.py | recipe.py |
==============
z3c.recipe.egg
==============
Recipes based on zc.recipe.egg for working with source
distributions.
Editable Distributions
----------------------
The z3c.recipe.egg:editable recipe uses the easy_install --editable
and --build-directory options to download multiple source
distributions.
The source distributions will be placed in the part directory and
managed by the buildout if build-directory is not specified. If so,
the distributions will be replaced when newer versions are available.
So be sure to set build-directory to a directory not managed by
buildout if you want to maintain changes to the source distributions.
The z3c.recipe.egg:editable can be used to assemble a set of
subversion checkouts to work with specifying subversion URLs in
find-links as is supported by easy_install. See the easy_install
documentation for the syntax for using subversion URLs. There are a
number of ways in which it is more flexible to control checkouts via
recipes rather than svn:externals.
Finally, if the develop option is true then the distributions will be
installed in develop mode.
See z3c/recipe/egg/editable.txt for more details.
Running Setup Scripts
---------------------
The z3c.recipe.egg:setup recipe calls arbitrary setup.py commands on
multiple distributions in a buildout.
The z3c.recipe.egg:setup recipe can be used, for example, to automate
releases. When the source is ready for release, the setup recipe is
configured to run the "register sdist bdist_egg upload" setup
commands. To ensure release only runs when intended, the setup recipe
can be used in it's own release.cfg file that extends
the buildout.cfg file. With this setup, releases for multiple
projects can be made with "bin/buildout -c release.cfg".
The z3c.recipe.egg:setup recipe also supports the develop option as
with z3c.recipe.egg:editable.
See z3c/recipe/egg/setup.txt for more details.
| z3c.recipe.egg | /z3c.recipe.egg-0.2.tar.gz/z3c.recipe.egg-0.2/README.txt | README.txt |
import sys, os, pkg_resources, subprocess
import distutils.core
import setuptools.command.easy_install
import zc.buildout.easy_install
import zc.recipe.egg
ei_logger = zc.buildout.easy_install.logger
class Setup(object):
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
def install(self):
setups = [os.path.join(self.buildout['buildout']['directory'],
setup.strip())
for setup in self.options['setup'].split('\n')
if setup.strip()]
if 'args' in self.options:
for setup in setups:
self.buildout.setup(
[setup] + self.options['args'].split())
if self.options.get('develop') == 'true':
develop(self, setups)
return ()
update = install
class Editable(zc.recipe.egg.Eggs):
def __init__(self, buildout, name, options):
super(Editable, self).__init__(buildout, name, options)
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], self.name)
if 'build-directory' not in options:
options['build-directory'] = options['location']
else:
options['build-directory'] = os.path.join(
buildout['buildout']['directory'],
options['build-directory'])
self.reqs = [
pkg_resources.Requirement.parse(r.strip())
for r in options.get('eggs', self.name).split('\n')
if r.strip()]
self.newest = buildout['buildout'].get('newest') == 'true'
self.online = (self.newest and
buildout['buildout'].get('offline') != 'true')
# Track versions
if self.online:
options['versions'] = self.get_online_versions()
else:
options['versions'] = self.get_offline_versions()
def install(self):
if not self.online:
return self.get_location()
options = self.options
dists = [req.unsafe_name for req in self.reqs if not
os.path.isdir(os.path.join(
self.options['build-directory'], req.key))]
if len(dists) > 0:
args = ['-c', zc.buildout.easy_install._easy_install_cmd]
if options.get('unzip') == 'true':
args += ['-Z']
level = ei_logger.getEffectiveLevel()
if level > 0:
args += ['-q']
elif level < 0:
args += ['-v']
args.extend(
['--find-links='+' '.join(self.links), '--editable',
'--build-directory='+options['build-directory']])
args.extend(dists)
path = self.installer._get_dist(
pkg_resources.Requirement.parse('setuptools'),
pkg_resources.WorkingSet([]), False,)[0].location
sys.stdout.flush() # We want any pending output first
sys.stderr.flush()
ei_logger.debug(
'Running easy_install:\n%s "%s"\npath=%s\n',
options['executable'], '" "'.join(args), path)
returncode = subprocess.Popen(
args=[options['executable']]+args,
env=dict(os.environ, PYTHONPATH=path)
).wait()
assert returncode == 0, (
'easy_install exited with returncode %s' % returncode)
if self.options.get('develop') == 'true':
develop(self, (
os.path.join(self.options['build-directory'],
req.key)
for req in self.reqs))
return self.get_location()
update = install
def get_location(self):
if os.path.isdir(self.options['location']):
return self.options['location']
else:
return ()
def get_online_versions(self):
options = self.options
self.installer = zc.buildout.easy_install.Installer(
links=self.links,
index = self.index,
executable = options['executable'],
always_unzip=options.get('unzip') == 'true',
path=[options['develop-eggs-directory']],
newest=self.newest)
return '\n'.join([
'%s==%s' % (dist.project_name, dist.version)
for dist in (self.installer._obtain(req, source=True)
for req in self.reqs)
if dist is not None])
def get_offline_versions(self):
options = self.options
return '\n'.join([
'%s==%s' % (dist.get_name(), dist.get_version())
for dist in (
distutils.core.run_setup(
os.path.join(options['build-directory'],
req.key, 'setup.py'),
stop_after='commandline')
for req in self.reqs
if os.path.isdir(
os.path.join(options['build-directory'],
req.key)))])
def develop(self, setups):
for setup in setups:
self.buildout._logger.info("Develop: %r", setup)
zc.buildout.easy_install.develop(
setup=setup, dest=self.buildout['buildout'][
'develop-eggs-directory']) | z3c.recipe.egg | /z3c.recipe.egg-0.2.tar.gz/z3c.recipe.egg-0.2/z3c/recipe/egg/__init__.py | __init__.py |
Goal of this recipe
===================
You have an egg (for example ``grok``) that has a lot of dependencies.
Other eggs that it depends on are found on the cheeseshop, on
sourceforge, and perhaps on some more servers. When even one of these
servers is down, other people (or you yourself) cannot install that
egg. Or perhaps your egg depends on a specific version of another egg
and that version is removed from the cheeseshop for some bad reason.
In other words: there are multiple points of failure. Interested
users want to try your egg, the install fails because a server is
down, they are disappointed, leave and never come back.
The goal of this recipe is to avoid having those multiple points of
failure. You create a tarball containing all eggs that your egg
depends on. A package like zc.sourcerelease_ can help here, but our
recipe can also create such a tar ball. Include it in a buildout like
this::
[buildout]
parts = bundlemaker
[bundlemaker]
recipe = z3c.recipe.eggbasket:creator
egg = grok
versionfile = http://grok.zope.org/releaseinfo/grok-0.12.cfg
After you have made that tar ball, you need to upload it somewhere.
In your buildout you point this recipe to your egg and the url of the
tarball, for example like this::
[buildout]
parts = eggbasket
[eggbasket]
recipe = z3c.recipe.eggbasket
eggs = grok
url = http://grok.zope.org/releaseinfo/grok-eggs-0.12.tgz
The part using this recipe should usually be the first in line. What
the recipe then does is install your egg and all its dependencies
using only the eggs found in that tarball. After that you can let the
rest of the buildout parts do their work.
.. _zc.sourcerelease: http://pypi.python.org/pypi/zc.sourcerelease
Limitations
===========
1. This approach still leaves you with multiple points of failure:
- the cheeseshop must be up so the end user can install this recipe
- the server with your tarball must be up.
2. Before buildout calls the install method of this recipe to do the
actual work, all buildout parts are initialized. This means that
all eggs and dependencies used by all recipes are installed. This
can already involve a lot of eggs and also multiple points of
failure. Workaround: you can first explicitly install the part
that uses this recipe. So with the buildout snippet from above
that would be::
bin/buildout install eggbasket
Supported options
=================
The recipe supports the following options:
eggs
One or more eggs that you want to install with a tarball.
url
Url where we can get a tarball that contains the mentioned eggs
and their dependencies.
The releasemaker script supports the following options:
egg
The main egg that we want to bundle up with its dependencies.
This is required.
versionfile
Config file that contains the wanted versions of the main egg and
its dependencies. An example is the grok version file:
http://grok.zope.org/releaseinfo/grok-0.12.cfg
This file is parsed by zc.buildout, so you can for example extend
other files. And the file can be a url or the name of a file in
the current directory.
Example usage
=============
We have a package ``orange`` that depends on the package ``colour``::
>>> import os.path
>>> import z3c.recipe.eggbasket.tests as testdir
>>> orange = os.path.join(os.path.dirname(testdir.__file__), 'orange')
>>> colour = os.path.join(os.path.dirname(testdir.__file__), 'colour')
We create source distributions for them in a directory::
>>> colours = tmpdir('colours')
>>> sdist(colour, colours)
>>> sdist(orange, colours)
>>> ls(colours)
- colour-0.1.zip
- orange-0.1.zip
We will define a buildout template that uses the recipe::
>>> buildout_template = """
... [buildout]
... index = http://pypi.python.org/simple
... parts = basket
...
... [basket]
... recipe = z3c.recipe.eggbasket
... eggs = %(eggs)s
... url = %(url)s
... """
We'll start by creating a buildout that does not specify an egg::
>>> write('buildout.cfg', buildout_template % { 'eggs': '', 'url' : 'http://nowhere'})
In this case the recipe will do nothing. So the url does not get
used. Running the buildout gives us::
>>> print 'start..\n', system(buildout)
start..
...
Installing basket.
<BLANKLINE>
Next we will specify an egg but refer to a bad url::
>>> write('buildout.cfg', buildout_template % { 'eggs': 'orange', 'url' : 'http://nowhere'})
>>> print system(buildout)
Uninstalling basket.
Installing basket.
Couldn't find index page for 'orange' (maybe misspelled?)
Getting distribution for 'orange'.
eggbasket: Not all distributions are installed. A tarball will be downloaded.
eggbasket: Downloading http://nowhere ...
eggbasket: Url not found: http://nowhere.
<BLANKLINE>
So now we create a tar ball in a directory::
>>> import tarfile
>>> tarserver = tmpdir('tarserver')
>>> cd(tarserver)
>>> tarball = tarfile.open('colours.tgz', 'w:gz')
>>> tarball.add(colours)
Note: the order of the next listing is not guaranteed, so there might
be a test failure here:
>>> tarball.list(verbose=False)
tmp/tmpDlQSIQbuildoutSetUp/_TEST_/colours/
tmp/tmpDlQSIQbuildoutSetUp/_TEST_/colours/colour-0.1.zip
tmp/tmpDlQSIQbuildoutSetUp/_TEST_/colours/orange-0.1.zip
>>> tarball.close()
>>> ls(tarserver)
- colours.tgz
We make it available on a url and use it in our buildout::
>>> cd(sample_buildout)
>>> tarball_url = 'file://' + tarserver + '/colours.tgz'
>>> write('buildout.cfg', buildout_template % { 'eggs': 'orange', 'url' : tarball_url})
>>> print system(buildout)
Uninstalling basket.
Installing basket.
Couldn't find index page for 'orange' (maybe misspelled?)
Getting distribution for 'orange'.
eggbasket: Not all distributions are installed. A tarball will be downloaded.
eggbasket: Downloading /tarserver/colours.tgz ...
eggbasket: Finished downloading.
eggbasket: Extracting tarball contents...
eggbasket: Installing eggs to /sample-buildout/eggs which will take a while...
Getting distribution for 'orange'.
Got orange 0.1.
Getting distribution for 'colour'.
Got colour 0.1.
<BLANKLINE>
| z3c.recipe.eggbasket | /z3c.recipe.eggbasket-0.4.3.tar.gz/z3c.recipe.eggbasket-0.4.3/z3c/recipe/eggbasket/README.txt | README.txt |
import logging
import os.path
import re
import shutil
import sys
import tarfile
import tempfile
import urllib
def remove_additional_root_logger_handlers():
"""Remove additional root logger handlers.
Under certain circumstances it might happen, that multiple
handlers in the root logger are installed. This leads to duplicate
lines in output we want to avoid. Therefore we remove additional
handlers.
"""
root_logger = logging.getLogger()
if len(root_logger.handlers) > 1:
for handler in root_logger.handlers[1:]:
if not isinstance(handler, logging.StreamHandler):
continue
root_logger.removeHandler(handler)
break
return
remove_additional_root_logger_handlers() # See function docstring
# XXX We may want to add command line argument handling.
logging.basicConfig(level=logging.INFO,
format='%(levelname)-5s %(name)-12s %(message)s')
log = logging.getLogger('eggbasket')
def install_distributions(distributions, target_dir, links=[],
use_empty_index=False):
"""Install distributions.
Distributions is a list of requirements, e.g. ['grok==0.13']
When use_empty_index is True we only try to install the required
distributions by using the supplied links. We do not use the
python cheese shop index then.
"""
from zc.buildout.easy_install import install
from zc.buildout.easy_install import MissingDistribution
if use_empty_index:
# When the temp dir is not writable this throws an OSError,
# which we might want to catch, but actually it is probably
# fine to just let it bubble up to the user.
try:
empty_index = tempfile.mkdtemp()
except:
log.error("Could not create temporary file")
# Reraise exception
raise
index = 'file://' + empty_index
else:
# Use the default index (python cheese shop)
index = None
try:
try:
install(distributions, target_dir, newest=False,
links=links, index=index)
except MissingDistribution:
return False
else:
return True
finally:
if use_empty_index:
shutil.rmtree(empty_index)
def distributions_are_installed_in_dir(distributions, target_dir):
# Check if the required distributions are installed. We do this
# by trying to install the distributions in the target dir and
# letting easy_install only look inside that same target dir while
# doing that.
result = install_distributions(distributions, target_dir,
links=[target_dir], use_empty_index=True)
return result
def create_source_tarball(egg=None, versionfile='buildout.cfg'):
if egg is None:
# XXX Having a way to read the setup.py in the current
# directory and get an egg name and perhaps version number
# from there would be cool. For now:
log.error("Please provide an egg name.")
sys.exit(1)
# XXX This may be a bit too hard coded.
# Perhaps try to read something from the buildout config.
links = ['http://download.zope.org/distribution/']
import zc.buildout.easy_install
import zc.buildout.buildout
# Read the buildout/versions file. versionfile can be a file in
# the current working directory or on some url. zc.buildout nicely
# takes care of that for us.
# Buildout needs a buildout:directory directive. It can compute
# one for local config files but not for URLs referencing config
# files. We pass the "." directory as the buildout:directory here.
buildout = zc.buildout.buildout.Buildout(
versionfile, [('buildout', 'directory', '.')])
versions = buildout.get('versions')
if versions is None:
log.error("Could not get versions from %s.", versionfile)
sys.exit(1)
try:
# Make temporary directories for the cache and the destination
# eggs directory. The cache is the important one here as that is
# where the sources get downloaded to.
cache = tempfile.mkdtemp()
dest = tempfile.mkdtemp()
# Set the download cache directory:
zc.buildout.easy_install.download_cache(cache)
main_egg_version = versions.get(egg)
if main_egg_version is None:
log.error("The main egg (%s) has not been pinned in the "
"version file (%s)." % (egg, versionfile))
sys.exit(1)
# Install the main egg, which pulls all dependencies into the
# download cache.
log.info("Will get main egg (%s) version %s and dependencies "
"with versions as listed in %s." %
(egg, main_egg_version, versionfile))
log.info("This could take a while...")
ws = zc.buildout.easy_install.install(
[egg], dest, versions=versions,
links=links)
# TODO: Make this optional:
log.info("Getting extra Windows distributions...")
egg_expression = re.compile(r'(.*)-([^-]*)(\.tar.gz|-py-*\.egg)')
for package in os.listdir(cache):
results = egg_expression.findall(package)
if len(results) != 1:
continue
parts = results[0]
if len(parts) != 3:
continue
package, version, dummy = parts
get_windows_egg(package, version, cache)
# Create tarball in current directory.
directory_name = '%s-eggs-%s' % (egg, main_egg_version)
tar_name = directory_name + '.tgz'
log.info("Creating %s", tar_name)
egg_tar = tarfile.open(tar_name, 'w:gz')
egg_tar.add(cache, directory_name)
# TODO: perhaps actually add latest version of grok egg if it
# is not there already, though currently the code should have
# failed already when this it is not available.
egg_tar.close()
log.info("Done.")
finally:
shutil.rmtree(dest)
shutil.rmtree(cache)
def get_windows_egg(package, version, target_dir):
base_url = 'http://pypi.python.org/simple/'
package_page = base_url + package
try:
contents = urllib.urlopen(package_page).read()
except IOError:
log.warn("%s not found.", package_page)
return
# We expect to get html with lines like this:
#
# <a href='http://pypi.python.org/packages/source/m/martian/martian-0.9.6.tar.gz#md5=98cda711bda0c5f45a05e2bdc2dc0d23'>martian-0.9.6.tar.gz</a><br/>
#
# We want to look for http....package-version-py2.x-win32.egg
expression = r'[\'"]http.*/%s-%s-py.*win32.egg.*[\'"]' % (package, version)
findings = re.compile(expression).findall(contents)
log.debug("Found %s matches.", len(findings))
for finding in findings:
# Strip off the enclosing single or double quotes:
finding = finding[1:-1]
# We probably have something like:
# ...egg#md5=3fa5e992271375eac597622d8e2fd5ec'
parts = finding.split('#md5=')
url = parts[0]
if len(parts) == 2:
md5hash = parts[1]
else:
md5hash = ''
target = os.path.join(target_dir, url.split('/')[-1])
log.info("Downloading %s to %s", url, target)
try:
urllib.urlretrieve(url, target)
except IOError:
log.error("Download error.")
else:
log.info("Finished downloading.")
# TODO: check md5hash
def download_tarball(location, url):
# Note: 'b' mode needed for Windows.
tarball = open(location, 'wb')
log.info("Downloading %s ..." % url)
try:
tarball.write(urllib.urlopen(url).read())
except IOError:
log.error("Url not found: %s." % url)
return False
tarball.close()
log.info("Finished downloading.")
return True | z3c.recipe.eggbasket | /z3c.recipe.eggbasket-0.4.3.tar.gz/z3c.recipe.eggbasket-0.4.3/z3c/recipe/eggbasket/utils.py | utils.py |
"""Recipe eggbasket"""
import logging
import tempfile
import shutil
import os
import tarfile
from zc.recipe.egg import Eggs
from z3c.recipe.eggbasket.utils import distributions_are_installed_in_dir
from z3c.recipe.eggbasket.utils import install_distributions
from z3c.recipe.eggbasket.utils import download_tarball, log
class Downloader(Eggs):
"""zc.buildout recipe for getting eggs out of a tar ball"""
def install(self):
"""Installer
"""
if self.buildout['buildout'].get('offline') == 'true':
log.error("Cannot run in offline mode.")
return tuple()
options = self.options
distributions = [
r.strip()
for r in options.get('eggs', self.name).split('\n')
if r.strip()]
url = self.options.get('url')
# Keep track of warnings and mention them at the end of
# the install() method.
temp_obj_warn = []
if not distributions_are_installed_in_dir(distributions,
options['eggs-directory']):
log.info("Not all distributions are installed. "
"A tarball will be downloaded.")
tarball_name = url.split('/')[-1]
# If the user has specified a download directory (in
# ~/.buildout/default.cfg probably) we will want to use
# it.
download_dir = self.buildout['buildout'].get('download-cache')
if download_dir:
if not os.path.exists(download_dir):
os.mkdir(download_dir)
if not os.path.isdir(download_dir):
# It exists but is not a file: we are not going to
# use the download dir.
download_dir = None
keep_tarball = False
if download_dir:
keep_tarball = True
tarball_location = os.path.join(download_dir, tarball_name)
if os.path.exists(tarball_location):
log.info("Using already downloaded %s" % tarball_location)
else:
result = download_tarball(tarball_location, url)
if not result:
# Give up.
return tuple()
if not keep_tarball:
# Make temporary file.
try:
filenum, tarball_location = tempfile.mkstemp()
except:
log.error("Could not create temporary tarball file")
# Reraise exception
raise
result = download_tarball(tarball_location, url)
if not result:
return tuple()
# We have the tarball. Now we make a temporary extraction
# directory.
try:
extraction_dir = tempfile.mkdtemp()
except:
log.error("Could not create temporary extraction directory")
# Reraise exception
raise
try:
log.info("Extracting tarball contents...")
try:
tf = tarfile.open(tarball_location, 'r:gz')
except tarfile.ReadError, e:
# Likely the download location is wrong and gives a 404.
# Or the tarball is not zipped.
log.error("No correct tarball found at %s." % url)
log.error("The error was: %s" % e)
return tuple()
links = []
for name in tf.getnames():
tf.extract(name, extraction_dir)
links.append(os.path.join(extraction_dir, name))
tf.close()
log.info("Installing eggs to %s which will take a while..."
% options['eggs-directory'])
result = install_distributions(
distributions, options['eggs-directory'],
links = links)
if result is False:
log.error("Failed to install required eggs with the tar "
"ball.")
finally:
# The Windows CPython has issues in the urllib module.
# urllib keeps files open in specific cases that can not
# be closed without finishing the process.
# Failing to remove temporary files should not stop the
# entire process. User is warned and can take action.
if not keep_tarball:
try:
os.unlink(tarball_location)
except OSError, os_error: # Most likely a WindowsError
temp_obj_warn.append(('file', tarball_location, os_error))
try:
shutil.rmtree(extraction_dir)
except OSError, os_error: # Most likely a WindowsError
temp_obj_warn.append(('directory', extraction_dir, os_error))
if len(temp_obj_warn):
for warning_ in temp_obj_warn:
type_, location_, except_ = warning_
log.warn("Could not remove temporary %s %s"
% (type_, tarball_location))
log.warn(os_error)
log.warn("!!** Please remove the %s manually **!!"
% (type_,))
# Return files that were created by the recipe. The buildout
# will remove all returned files upon reinstall.
return tuple()
def update(self):
# This recipe only needs to be called once.
pass | z3c.recipe.eggbasket | /z3c.recipe.eggbasket-0.4.3.tar.gz/z3c.recipe.eggbasket-0.4.3/z3c/recipe/eggbasket/downloader.py | downloader.py |
z3c.recipe.epydoc
====================
Introduction
------------
This buildout recipe generates epydoc documentation for you project
Usage Instructions
------------------
Let's say you have a package called ezineserver. In the buildout.cfg file of your package, add a ``docs`` section
that looks like this::
[docs]
recipe = z3c.recipe.epydoc
eggs =
z3c.recipe.epydoc
ezineserver
doc = ezineserver
Be sure to include it in the parts, as in::
[buildout]
develop = .
parts = docs
Now you can rerun buildout. The recipe will have created an
executable script in the bin directory called ``docs``.
This script will run the epydoc documentation generation tool on your
source code.
To generate documentation simply run ``docs`` script::
$ ./bin/docs
This generates all the documentation for you and placed it in the
parts directory. You can then open it up in firefox and take a look::
$ firefox parts/docs/index.html
And that's it!
Specify additional options
--------------------------
It's also possible to pass additional epydoc options to the ``docs`` script (for
a list of all available options, run the script with the ``--help`` option).
You can do this from two different ways:
* you can pass options directly to the script::
$ ./bin/docs --no-frames --include-log
* or you can use the ``defaults`` entry to the ``docs`` section::
[docs]
recipe = z3c.recipe.epydoc
eggs =
z3c.recipe.epydoc
ezineserver
doc = ezineserver
defaults = ['no-frames', '--include-log']
This allows you to create a script with the same options as if you had
specified them on the command line.
If not set, the ``defaults`` entry will default to the value ``['-v',
'--debug']``.
| z3c.recipe.epydoc | /z3c.recipe.epydoc-0.0.3.tar.gz/z3c.recipe.epydoc-0.0.3/src/z3c/recipe/epydoc/readme.txt | readme.txt |
Here is the most basic example::
>>> write('buildout.cfg',
... """
... [buildout]
... parts =
... zope2
... fakezope2eggs
...
... find-links =
... http://dist.plone.org/
...
... [zope2]
... recipe = plone.recipe.zope2install
... url = http://www.zope.org/Products/Zope/2.9.7/Zope-2.9.7-final.tgz
...
... [fakezope2eggs]
... recipe = z3c.recipe.fakezope2eggs
... """)
Now if we run the buildout::
>>> print system(buildout)
Installing zope2.
running build_ext
creating zope.proxy
copying zope/proxy/proxy.h -> zope.proxy
building 'AccessControl.cAccessControl' extension
creating build
creating build/temp.linux-i686-2.4
creating build/temp.linux-i686-2.4/AccessControl
...
Now if we list all the developped egg we have:
>>> ls(sample_buildout, 'develop-eggs')
- plone.recipe.zope2install.egg-link
- z3c.recipe.fakezope2eggs.egg-link
- zope.app.adapter.egg-info
- zope.app.annotation.egg-info
- zope.app.apidoc.egg-info
- zope.app.applicationcontrol.egg-info
- zope.app.appsetup.egg-info
- zope.app.authentication.egg-info
- zope.app.basicskin.egg-info
- zope.app.broken.egg-info
- zope.app.cache.egg-info
...
Let's have a look at the content of one of them::
>>> cat(sample_buildout, 'develop-eggs', 'zope.app.adapter.egg-info')
Metadata-Version: 1.0
Name: zope.app.adapter
Version: 0.0
You might also want to add other fake eggs to your buildout, to do so use the
additional-fake-eggs option, for example::
>>> write('buildout.cfg',
... """
... [buildout]
... parts =
... zope2
... fakezope2eggs
...
... find-links =
... http://dist.plone.org/
...
... [zope2]
... recipe = plone.recipe.zope2install
... url = http://www.zope.org/Products/Zope/2.9.7/Zope-2.9.7-final.tgz
...
... [fakezope2eggs]
... recipe = z3c.recipe.fakezope2eggs
... additional-fake-eggs = ZODB3
... """)
>>> print system(buildout)
Uninstalling fakezope2eggs.
Updating zope2.
Installing fakezope2eggs.
<BLANKLINE>
Let's check if the additionnal fake egg exists:
>>> cat(sample_buildout, 'develop-eggs', 'ZODB3.egg-info')
Metadata-Version: 1.0
Name: ZODB3
Version: 0.0
| z3c.recipe.fakezope2eggs | /z3c.recipe.fakezope2eggs-0.5.tar.gz/z3c.recipe.fakezope2eggs-0.5/src/z3c/recipe/fakezope2eggs/README.txt | README.txt |
import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__)==1 and
not os.path.exists(os.path.join(v.__path__[0],'__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source +"."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.append('buildout:accept-buildout-test-releases=true')
args.append('bootstrap')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir) | z3c.recipe.filetemplate | /z3c.recipe.filetemplate-2.2.0.tar.gz/z3c.recipe.filetemplate-2.2.0/bootstrap/bootstrap.py | bootstrap.py |
``z3c.recipe.filetemplate``
***************************
===========
Basic Usage
===========
With the ``z3c.recipe.filetemplate`` buildout recipe you can automate
the generation of text files from templates. Upon execution, the
recipe will read a number of template files, perform variable
substitution and write the result to the corresponding output files.
The recipe has several features, but it always takes template files with a
``.in`` suffix, processes the template, and writes out the file to the desired
location with the same file mode, and the same name but without the ``.in``
suffix.
For example, consider this simple template for a text file:
>>> write(sample_buildout, 'helloworld.txt.in',
... """
... Hello ${world}!
... """)
Now let's create a buildout configuration so that we can substitute
the values in this file. All we have to do is define a part that uses
the ``z3c.recipe.filetemplate`` recipe. With the ``files`` parameter
we specify one or more files that need substitution (separated by
whitespace). Then we can add arbitrary parameters to the section.
Those will be used to fill the variables in the template:
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... world = Philipp
... """)
After executing buildout, we can see that ``${world}`` has indeed been
replaced by ``Philipp``:
>>> print system(buildout)
Installing message.
>>> cat(sample_buildout, 'helloworld.txt')
Hello Philipp!
If you need to escape the ${...} pattern, you can do so by repeating the dollar
sign.
>>> update_file(sample_buildout, 'helloworld.txt.in',
... """
... Hello world! The double $${dollar-sign} escapes!
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt')
Hello world! The double ${dollar-sign} escapes!
Note that dollar signs alone, without curly braces, are not parsed.
>>> update_file(sample_buildout, 'helloworld.txt.in',
... """
... $Hello $$world! $$$profit!
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt')
$Hello $$world! $$$profit!
Note that the output file uses the same permission bits as found on the input
file.
>>> import stat
>>> import os
>>> input = os.path.join(sample_buildout, 'helloworld.txt.in')
>>> output = input[:-3]
>>> os.chmod(input, 0755)
>>> stat.S_IMODE(os.stat(input).st_mode) == 0755
True
>>> stat.S_IMODE(os.stat(output).st_mode) == 0755
False
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> stat.S_IMODE(os.stat(output).st_mode) == 0755
True
Source Folders and Globs
========================
By default, the recipe looks for a ``.in`` file relative to the buildout root,
and places it in the same folder relative to the buildout root. However, if
you don't want to clutter up the destination folder, you can add a prefix to
the source folder. Here is an example.
First, we specify a ``source-directory`` in the buildout. You can specify
``files`` as a filter if desired, but by default it will find any file (ending
with ".in"). You can also specify ``exclude-directories`` option if you want
to exclude some paths from the ``source-directory`` search path.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... world = Philipp
... """)
Now we'll make a "template" directory, as listed in the buildout configuration
above, and populate it for our example.
>>> mkdir(sample_buildout, 'template')
>>> mkdir(sample_buildout, 'template', 'etc')
>>> mkdir(sample_buildout, 'template', 'bin')
>>> write(sample_buildout, 'template', 'etc', 'helloworld.conf.in',
... """
... Hello ${world} from the etc dir!
... """)
>>> write(sample_buildout, 'template', 'bin', 'helloworld.sh.in',
... """
... Hello ${world} from the bin dir!
... """)
>>> os.chmod(
... os.path.join(
... sample_buildout, 'template', 'bin', 'helloworld.sh.in'),
... 0711)
Notice that, before running buildout, the ``helloworld.txt`` file is still
around, we don't have an etc directory, and the bin directory doesn't have our
``helloworld.sh``.
>>> ls(sample_buildout)
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
- helloworld.txt
- helloworld.txt.in
d parts
d template
>>> ls(sample_buildout, 'bin')
- buildout
Now we install. The old "helloworld.txt" is gone, and we now see etc. Note
that, for the destination, intermediate folders are created if they do not
exist.
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> ls(sample_buildout)
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
d etc
- helloworld.txt.in
d parts
d template
The files exist and have the content we expect.
>>> ls(sample_buildout, 'bin')
- buildout
- helloworld.sh
>>> cat(sample_buildout, 'bin', 'helloworld.sh')
Hello Philipp from the bin dir!
>>> stat.S_IMODE(os.stat(os.path.join(
... sample_buildout, 'bin', 'helloworld.sh')).st_mode) == 0711
True
>>> ls(sample_buildout, 'etc')
- helloworld.conf
>>> cat(sample_buildout, 'etc', 'helloworld.conf')
Hello Philipp from the etc dir!
If you use the ``files`` option along with ``source-directory``, it becomes a
filter. Every target file must match at least one of the names in ``files``.
Therefore, if we only build .sh files, the etc directory will disappear.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... files = *.sh
... world = Philipp
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> ls(sample_buildout)
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
- helloworld.txt.in
d parts
d template
>>> ls(sample_buildout, 'bin')
- buildout
- helloworld.sh
Also note that, if you use a source directory and your ``files`` specify a
directory, the directory must match precisely.
With the ``exclude-directories`` parameter, we specify one or more directories
(separated by whitespace) in which the recipe will not look for template
files. The ``exclude-directories`` option should be used along with the
``source-directory`` option.
Therefore, if we set ``exclude-directories`` to ``bin``, the
``bin/helloworld.sh`` file will disappear.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... exclude-directories = bin
... world = Philipp
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> ls(sample_buildout)
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
d etc
- helloworld.txt.in
d parts
d template
>>> ls(sample_buildout, 'etc')
- helloworld.conf
>>> ls(sample_buildout, 'bin')
- buildout
>>> # Clean up for later test.
>>> import shutil
>>> shutil.rmtree(os.path.join(sample_buildout, 'template', 'etc'))
>>> os.remove(os.path.join(
... sample_buildout, 'template', 'bin', 'helloworld.sh.in'))
==============
Advanced Usage
==============
Substituting from Other Sections
================================
Substitutions can also come from other sections in the buildout, using the
standard buildout syntax, but used in the template. Notice
``${buildout:parts}`` in the template below.
>>> update_file(sample_buildout, 'helloworld.txt.in',
... """
... Hello ${world}. I used these parts: ${buildout:parts}.
... """)
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... world = Philipp
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt')
Hello Philipp. I used these parts: message.
Path Extensions
===============
Substitutions can have path suffixes using the POSIX "/" path separator.
The template will convert these to the proper path separator for the current
OS. They also then are part of the value passed to filters, the feature
described next. Notice ``${buildout:directory/foo/bar.txt}`` in the template
below.
>>> update_file(sample_buildout, 'helloworld.txt.in',
... """
... Here's foo/bar.txt in the buildout:
... ${buildout:directory/foo/bar.txt}
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt') # doctest: +ELLIPSIS
Here's foo/bar.txt in the buildout:
/.../sample-buildout/foo/bar.txt
Filters
=======
You can use pipes within a substitution to filter the original value. This
recipe provides several filters for you to use. The syntax is reminiscent of
(and inspired by) POSIX pipes and Django template filters. For example,
if world = Philipp, ``HELLO ${world|upper}!`` would result in ``HELLO
PHILIPP!``.
A few simple Python string methods are exposed as filters right now:
- capitalize: First letter in string is capitalized.
- lower: All letters in string are lowercase.
- title: First letter of each word in string is capitalized.
- upper: All letters in string are uppercase.
Other filters are important for handling paths if buildout's relative-paths
option is true. See `Working with Paths`_ for more details.
- path-repr: Converts the path to a Python expression for the path. If
buildout's relative-paths option is false, this will simply be a repr
of the absolute path. If relative-paths is true, this will be a
function call to convert a buildout-relative path to an absolute path;
it requires that ``${python-relative-path-setup}`` be included earlier
in the template.
- shell-path: Converts the path to a shell expression for the path. Only
POSIX is supported at this time. If buildout's relative-paths option
is false, this will simply be the absolute path. If relative-paths is
true, this will be an expression to convert a buildout-relative path
to an absolute path; it requires that ``${shell-relative-path-setup}``
be included earlier in the template.
Combining the three advanced features described so far, then, if the
buildout relative-paths option were false, we were in a POSIX system, and
the sample buildout were in the root of the system, the template
expression ``${buildout:bin-directory/data/initial.csv|path-repr}``
would result in ``'/sample-buildout/bin/data/initial.csv'``.
Here's a real, working example of the string method filters. We'll have
examples of the path filters in the `Working with Paths`_ section.
>>> update_file(sample_buildout, 'helloworld.txt.in',
... """
... HELLO ${world|upper}!
... hello ${world|lower}.
... ${name|title} and the Chocolate Factory
... ${sentence|capitalize}
... """)
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... world = Philipp
... name = willy wonka
... sentence = that is a good book.
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt') # doctest: +ELLIPSIS
HELLO PHILIPP!
hello philipp.
Willy Wonka and the Chocolate Factory
That is a good book.
Sharing Variables
=================
The recipe allows extending one or more sections, to decrease
repetition, using the ``extends`` option. For instance, consider the
following buildout.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [template_defaults]
... mygreeting = Hi
... myaudience = World
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... extends = template_defaults
...
... myaudience = everybody
... """)
The "message" section now has values extended from the "template_defaults"
section, and overwritten locally. A template of
``${mygreeting}, ${myaudience}!``...
>>> update_file(sample_buildout, 'helloworld.txt.in',
... """
... ${mygreeting}, ${myaudience}!
... """)
...would thus result in ``Hi, everybody!``.
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt')
Hi, everybody!
Defining options in Python
==========================
You can specify that certain variables should be interpreted as Python using
``interpreted-options``. This takes zero or more lines. Each line should
specify an option. It can define immediately (see ``silly-range`` in
the example below) or point to an option to be interepreted, which can
be useful if you want to define a multi-line expression (see
``first-interpreted-option`` and ``message-reversed-is-egassem``).
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... interpreted-options = silly-range = repr(range(5))
... first-interpreted-option
... message-reversed-is-egassem
... first-interpreted-option =
... options['interpreted-options'].splitlines()[0].strip()
... message-reversed-is-egassem=
... ''.join(
... reversed(
... buildout['buildout']['parts']))
... not-interpreted=hello world
... """)
>>> update_file(sample_buildout, 'helloworld.txt.in', """\
... ${not-interpreted}!
... silly-range: ${silly-range}
... first-interpreted-option: ${first-interpreted-option}
... message-reversed-is-egassem: ${message-reversed-is-egassem}
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt') # doctest:+ELLIPSIS
hello world!
silly-range: [0, 1, 2, 3, 4]
first-interpreted-option: silly-range = repr(range(5))
message-reversed-is-egassem: egassem
Working with Paths
==================
We've already mentioned how to handle buildout's relative-paths option
in the discussion of filters. This section has some concrete examples
and discussion of that. It also introduces how to get a set of paths
from specifying dependencies.
Here are concrete examples of the path-repr and shell-path filters.
We'll show results when relative-paths is true and when it is false.
------------------------------
Demonstration of ``path-repr``
------------------------------
Let's say we want to make a custom Python script in the bin directory.
It will print some information from a file in a ``data`` directory
within the buildout root. Here's the template.
>>> write(sample_buildout, 'template', 'bin', 'dosomething.py.in', '''\
... #!${buildout:executable}
... ${python-relative-path-setup}
... f = open(${buildout:directory/data/info.csv|path-repr})
... print f.read()
... ''')
>>> os.chmod(
... os.path.join(
... sample_buildout, 'template', 'bin', 'dosomething.py.in'),
... 0711)
If we evaluate that template with relative-paths set to false, the results
shouldn't be too surprising.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'bin', 'dosomething.py') # doctest: +ELLIPSIS
#!...
<BLANKLINE>
f = open('/.../sample-buildout/data/info.csv')
print f.read()
``${python-relative-path-setup}`` evaluated to an empty string. The path
is absolute and quoted.
If we evaluate it with relative-paths set to true, the results are much...
bigger.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
... relative-paths = true
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'bin', 'dosomething.py') # doctest: +ELLIPSIS
#!...
import os, imp
# Get path to this file.
if __name__ == '__main__':
_z3c_recipe_filetemplate_filename = __file__
else:
# If this is an imported module, we want the location of the .py
# file, not the .pyc, because the .py file may have been symlinked.
_z3c_recipe_filetemplate_filename = imp.find_module(__name__)[1]
# Get the full, non-symbolic-link directory for this file.
_z3c_recipe_filetemplate_base = os.path.dirname(
os.path.abspath(os.path.realpath(_z3c_recipe_filetemplate_filename)))
# Ascend to buildout root.
_z3c_recipe_filetemplate_base = os.path.dirname(
_z3c_recipe_filetemplate_base)
def _z3c_recipe_filetemplate_path_repr(path):
"Return absolute version of buildout-relative path."
return os.path.join(_z3c_recipe_filetemplate_base, path)
<BLANKLINE>
f = open(_z3c_recipe_filetemplate_path_repr('data/info.csv'))
print f.read()
That's quite a bit of code. You might wonder why we don't just use '..' for
parent directories. The reason is that we want our scripts to be usable
from any place on the filesystem. If we used '..' to construct paths
relative to the generated file, then the paths would only work from
certain directories.
So that's how path-repr works. It can really come in handy if you want
to support relative paths in buildout. Now let's look at the shell-path
filter.
-------------------------------
Demonstration of ``shell-path``
-------------------------------
Maybe you want to write some shell scripts. The shell-path filter will help
you support buildout relative-paths fairly painlessly.
Right now, only POSIX is supported with the shell-path filter, as mentioned
before.
Usage is very similar to the ``path-repr`` filter. You need to include
``${shell-relative-path-setup}`` before you use it, just as you include
``${python-relative-path-setup}`` before using ``path-repr``.
Let's say we want to make a custom shell script in the bin directory.
It will print some information from a file in a ``data`` directory
within the buildout root. Here's the template.
>>> write(sample_buildout, 'template', 'bin', 'dosomething.sh.in', '''\
... #!/bin/sh
... ${shell-relative-path-setup}
... cat ${buildout:directory/data/info.csv|shell-path}
... ''')
>>> os.chmod(
... os.path.join(
... sample_buildout, 'template', 'bin', 'dosomething.sh.in'),
... 0711)
If relative-paths is set to false (the default), the results are simple.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'bin', 'dosomething.sh') # doctest: +ELLIPSIS
#!/bin/sh
<BLANKLINE>
cat /.../sample-buildout/data/info.csv
``${shell-relative-path-setup}`` evaluated to an empty string. The path
is absolute.
Now let's look at the larger code when relative-paths is set to true.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
... relative-paths = true
...
... [message]
... recipe = z3c.recipe.filetemplate
... source-directory = template
... """)
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'bin', 'dosomething.sh') # doctest: +ELLIPSIS
#!/bin/sh
# Get full, non-symbolic-link path to this file.
Z3C_RECIPE_FILETEMPLATE_FILENAME=`\
readlink -f "$0" 2>/dev/null || \
realpath "$0" 2>/dev/null || \
type -P "$0" 2>/dev/null`
# Get directory of file.
Z3C_RECIPE_FILETEMPLATE_BASE=`dirname ${Z3C_RECIPE_FILETEMPLATE_FILENAME}`
# Ascend to buildout root.
Z3C_RECIPE_FILETEMPLATE_BASE=`dirname ${Z3C_RECIPE_FILETEMPLATE_BASE}`
<BLANKLINE>
cat "$Z3C_RECIPE_FILETEMPLATE_BASE"/data/info.csv
As with the Python code, we don't just use '..' for
parent directories because we want our scripts to be usable
from any place on the filesystem.
----------------------------------
Getting Arbitrary Dependency Paths
----------------------------------
You can specify ``eggs`` and ``extra-paths`` in the recipe. The
mechanism is the same as the one provided by the zc.recipe.egg, so
pertinent options such as find-links and index are available.
If you do, the paths for the dependencies will be calculated. They will
be available as a list in the namespace of the interpreted options as
``paths``. Also, three predefined options will be available in the
recipe's options for the template.
If ``paths`` are the paths, ``shell_path`` is the ``shell-path`` filter, and
``path_repr`` is the ``path-repr`` filter, then the pre-defined options
would be defined roughly as given here:
``os-paths`` (for shell scripts)
``(os.pathsep).join(shell_path(path) for path in paths)``
``string-paths`` (for Python scripts)
``',\n '.join(path_repr(path) for path in paths)``
``space-paths`` (for shell scripts)
``' '.join(shell_path(path) for path in paths)``
Therefore, if you want to support the relative-paths option, you should
include ``${shell-relative-path-setup}`` (for ``os-paths`` and
``space-paths``) or ``${python-relative-path-setup}`` (for ``string-paths``)
as appropriate at the top of your template.
Let's consider a simple example.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... eggs = demo<0.3
...
... find-links = %(server)s
... index = %(server)s/index
... """ % dict(server=link_server))
The relative-paths option is false, the default.
>>> write(sample_buildout, 'helloworld.txt.in',
... """
... Hello! Here are the paths for the ${eggs} eggs.
... OS paths:
... ${os-paths}
... ---
... String paths:
... ${string-paths}
... ---
... Space paths:
... ${space-paths}
... """)
>>> print system(buildout)
Getting distribution for 'demo<0.3'.
Got demo 0.2.
Getting distribution for 'demoneeded'.
Got demoneeded 1.2c1.
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt') # doctest:+ELLIPSIS
Hello! Here are the paths for the demo<0.3 eggs.
OS paths:
/.../eggs/demo-0.2...egg:/.../eggs/demoneeded-1.2c1...egg
---
String paths:
'/.../eggs/demo-0.2...egg',
'/.../eggs/demoneeded-1.2c1...egg'
---
Space paths:
/.../eggs/demo-0.2...egg /.../eggs/demoneeded-1.2c1...egg
You can specify extra-paths as well, which will go at the end of the egg
paths.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... eggs = demo<0.3
... extra-paths = ${buildout:directory}/foo
...
... find-links = %(server)s
... index = %(server)s/index
... """ % dict(server=link_server))
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt') # doctest:+ELLIPSIS
Hello! Here are the paths for the demo<0.3 eggs.
OS paths:
/...demo...:/...demoneeded...:/.../sample-buildout/foo
---
String paths:
'/...demo...',
'/...demoneeded...',
'/.../sample-buildout/foo'
---
Space paths:
/...demo... /...demoneeded... .../sample-buildout/foo
To emphasize the effect of the relative-paths option, let's see what it looks
like when we set relative-paths to True.
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = message
... relative-paths = true
...
... [message]
... recipe = z3c.recipe.filetemplate
... files = helloworld.txt
... eggs = demo<0.3
... extra-paths = ${buildout:directory}/foo
...
... find-links = %(server)s
... index = %(server)s/index
... """ % dict(server=link_server))
>>> print system(buildout)
Uninstalling message.
Installing message.
>>> cat(sample_buildout, 'helloworld.txt') # doctest:+ELLIPSIS
Hello! Here are the paths for the demo<0.3 eggs.
OS paths:
"$Z3C_RECIPE_FILETEMPLATE_BASE"/eggs/demo-0.2-py...egg:"$Z3C_RECIPE_FILETEMPLATE_BASE"/eggs/demoneeded-1.2c1-py...egg:"$Z3C_RECIPE_FILETEMPLATE_BASE"/foo
---
String paths:
_z3c_recipe_filetemplate_path_repr('eggs/demo-0.2-py...egg'),
_z3c_recipe_filetemplate_path_repr('eggs/demoneeded-1.2c1-py...egg'),
_z3c_recipe_filetemplate_path_repr('foo')
---
Space paths:
"$Z3C_RECIPE_FILETEMPLATE_BASE"/eggs/demo-0.2-py...egg "$Z3C_RECIPE_FILETEMPLATE_BASE"/eggs/demoneeded-1.2c1-py...egg "$Z3C_RECIPE_FILETEMPLATE_BASE"/foo
Remember, your script won't really work unless you include
``${shell-relative-path-setup}`` (for ``os-paths`` and ``space-paths``)
or ``${python-relative-path-setup}`` (for ``string-paths``) as
appropriate at the top of your template.
Getting Dependency Paths from ``zc.recipe.egg``
-----------------------------------------------
You can get the ``eggs`` and ``extra-paths`` from another section using
zc.recipe.egg by using the ``extends`` option from the `Sharing Variables`_
section above. Then you can use the template options described above to
build your paths in your templates.
Getting Dependency Paths from ``z3c.recipe.scripts``
----------------------------------------------------
If, like the Launchpad project, you are using Gary Poster's unreleased
package ``z3c.recipe.scripts`` to generate your scripts, and you want to
have your scripts use the same Python environment as generated by that
recipe, you can just use the path-repr and shell-path filters with standard
buildout directories. Here is an example buildout.cfg.
::
[buildout]
parts = scripts message
relative-paths = true
[scripts]
recipe = z3c.recipe.scripts
eggs = demo<0.3
[message]
recipe = z3c.recipe.filetemplate
files = helloworld.py
Then the template to use this would want to simply put
``${scripts:parts-directory|path-repr}`` at the beginning of Python's path.
You can do this for subprocesses with PYTHONPATH.
${python-relative-path-setup}
import os
import subprocess
env = os.environ.copy()
env['PYTHONPATH'] = ${scripts:parts-directory|path-repr}
subprocess.call('myscript', env=env)
That's it.
Similarly, here's an approach to making a script that will have the
right environment. You want to put the parts directory of the
z3c.recipe.scripts section in the sys.path before site.py is loaded.
This is usually handled by z3c.recipe.scripts itself, but sometimes you
may want to write Python scripts in your template for some reason.
#!/usr/bin/env python -S
${python-relative-path-setup}
import sys
sys.path.insert(0, ${scripts:parts-directory|path-repr})
import site
# do stuff...
If you do this for many scripts, put this entire snippet in an option in the
recipe and use this snippet as a single substitution in the top of your
scripts.
| z3c.recipe.filetemplate | /z3c.recipe.filetemplate-2.2.0.tar.gz/z3c.recipe.filetemplate-2.2.0/z3c/recipe/filetemplate/README.txt | README.txt |
import fnmatch
import logging
import os
import re
import stat
import string
import sys
import traceback
import zc.recipe.egg
import zc.buildout
import zc.buildout.easy_install
ABS_PATH_ERROR = ('%s is an absolute path. Paths must be '
'relative to the buildout directory.')
class FileTemplate(object):
filters = {}
dynamic_options = {}
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
self.buildout_root = zc.buildout.easy_install.realpath(
buildout['buildout']['directory'])
self.logger=logging.getLogger(self.name)
# get defaults from extended sections
defaults = {}
extends = self.options.get('extends', '').split()
extends.reverse()
for section_name in extends:
defaults.update(self.buildout[section_name])
for key, value in defaults.items():
self.options.setdefault(key, value)
relative_paths = self.options.setdefault(
'relative-paths',
buildout['buildout'].get('relative-paths', 'false')
)
if relative_paths not in ('true', 'false'):
self._user_error(
'The relative-paths option must have the value of '
'true or false.')
self.relative_paths = relative_paths = (relative_paths == 'true')
self.paths = paths = []
# set up paths for eggs, if given
if 'eggs' in options:
eggs = zc.recipe.egg.Scripts(buildout, name, options)
orig_distributions, ws = eggs.working_set()
paths.extend(
zc.buildout.easy_install.realpath(dist.location)
for dist in ws)
paths.extend(
zc.buildout.easy_install.realpath(path)
for path in eggs.extra_paths)
else:
paths.extend(
os.path.join(buildout.options['directory'], p.strip())
for p in options.get('extra-paths', '').split('\n')
if p.strip()
)
options['_paths'] = '\n'.join(paths)
# get and check the files to be created
self.filenames = self.options.get('files', '*').split()
self.source_dir = self.options.get('source-directory', '').strip()
self.exclude_dirs = self.options.get('exclude-directories', '').split()
here = zc.buildout.easy_install.realpath(
self.buildout['buildout']['directory'])
self.destination_dir = here
if self.source_dir:
self.recursive = True
if os.path.isabs(self.source_dir):
self._user_error(ABS_PATH_ERROR, self.source_dir)
self.source_dir = zc.buildout.easy_install.realpath(
os.path.normpath(os.path.join(here, self.source_dir)))
if not self.source_dir.startswith(here):
self._user_error(
'source-directory must be within the buildout directory')
else:
self.recursive = False
self.options['source-directory'] = ''
self.source_dir = self.buildout['buildout']['directory']
source_patterns = []
for filename in self.filenames:
if os.path.isabs(filename):
self._user_error(ABS_PATH_ERROR, filename)
if not zc.buildout.easy_install.realpath(
os.path.normpath(os.path.join(self.source_dir, filename))
).startswith(self.source_dir):
# path used ../ to get out of buildout dir
self._user_error(
'source files must be within the buildout directory')
source_patterns.append('%s.in' % filename)
unmatched = set(source_patterns)
unexpected_dirs = []
self.actions = [] # each entry is tuple of
# (relative path, source last-modified-time, mode)
if self.recursive:
def visit(ignored, dirname, names):
relative_prefix = dirname[len(self.source_dir)+1:]
if relative_prefix in self.exclude_dirs:
# exclude current directory and its subdirectories
del names[:]
return
file_info = {}
for name in names:
val = os.path.join(relative_prefix, name)
source = os.path.join(self.source_dir, val)
statinfo = os.stat(source)
last_modified = statinfo.st_mtime
if stat.S_ISREG(statinfo.st_mode):
file_info[name] = (
val, last_modified, statinfo.st_mode)
found = set()
for orig_pattern in source_patterns:
parts = orig_pattern.split('/')
dir = os.path.sep.join(parts[:-1])
pattern = parts[-1]
if (dir and
relative_prefix != dir and
(dir != '.' or relative_prefix != '')):
# if a directory is specified, it must match
# precisely. We also support the '.' directory.
continue
matching = fnmatch.filter(file_info, pattern)
if matching:
unmatched.discard(orig_pattern)
found.update(matching)
for name in found:
self.actions.append(file_info[name])
os.path.walk(
self.source_dir, visit, None)
else:
for val in source_patterns:
source = zc.buildout.easy_install.realpath(
os.path.join(self.source_dir, val))
if os.path.exists(source):
unmatched.discard(val)
statinfo = os.stat(source)
last_modified = statinfo.st_mtime
if not stat.S_ISREG(statinfo.st_mode):
unexpected_dirs.append(source)
else:
self.actions.append(
(val, last_modified, statinfo.st_mode))
# This is supposed to be a flag so that when source files change, the
# recipe knows to reinstall.
self.options['_actions'] = repr(self.actions)
if unexpected_dirs:
self._user_error(
'Expected file but found directory: %s',
', '.join(unexpected_dirs))
if unmatched:
self._user_error(
'No template found for these file names: %s',
', '.join(unmatched))
# parse interpreted options
interpreted = self.options.get('interpreted-options')
if interpreted:
globs = {'__builtins__': __builtins__, 'os': os, 'sys': sys}
locs = {'name': name, 'options': options, 'buildout': buildout,
'paths': paths, 'all_paths': paths}
for value in interpreted.split('\n'):
if value:
value = value.split('=', 1)
key = value[0].strip()
if len(value) == 1:
try:
expression = options[key]
except KeyError:
self._user_error(
'Expression for key not found: %s', key)
else:
expression = value[1]
try:
evaluated = eval(expression, globs, locs)
except:
self._user_error(
'Error when evaluating %r expression %r:\n%s',
key, expression, traceback.format_exc())
if not isinstance(evaluated, basestring):
self._user_error(
'Result of evaluating Python expression must be a '
'string. The result of %r expression %r was %r, '
'a %s.',
key, expression, evaluated, type(evaluated))
options[key] = evaluated
def _user_error(self, msg, *args):
msg = msg % args
self.logger.error(msg)
raise zc.buildout.UserError(msg)
def install(self):
already_exists = [
rel_path[:-3] for rel_path, last_mod, st_mode in self.actions
if os.path.exists(
os.path.join(self.destination_dir, rel_path[:-3]))
]
if already_exists:
self._user_error(
'Destinations already exist: %s. Please make sure that '
'you really want to generate these automatically. Then '
'move them away.', ', '.join(already_exists))
self.seen = []
# We throw ``seen`` away right now, but could move template
# processing up to __init__ if valuable. That would mean that
# templates would be rewritten even if a value in another
# section had been referenced; however, it would also mean that
# __init__ would do virtually all of the work, with install only
# doing the writing.
for rel_path, last_mod, st_mode in self.actions:
source = os.path.join(self.source_dir, rel_path)
dest = os.path.join(self.destination_dir, rel_path[:-3])
mode=stat.S_IMODE(st_mode)
# we process the file first so that it won't be created if there
# is a problem.
processed = Template(source, dest, self).substitute()
self._create_paths(os.path.dirname(dest))
result=open(dest, "wt")
result.write(processed)
result.close()
os.chmod(dest, mode)
self.options.created(rel_path[:-3])
return self.options.created()
def _create_paths(self, path):
if not os.path.exists(path):
self._create_paths(os.path.dirname(path))
os.mkdir(path)
self.options.created(path)
def _call_and_log(self, callable, args, message_generator):
try:
return callable(*args)
except (KeyboardInterrupt, SystemExit):
raise
except:
# Argh. Would like to raise wrapped exception.
colno, lineno = self.get_colno_lineno(start)
msg = message_generator(lineno, colno)
self.logger.error(msg, exc_info=True)
raise
def update(self):
pass
class Template:
# Heavily hacked from--"inspired by"?--string.Template
pattern = re.compile(r"""
\$(?:
\${(?P<escaped>[^}]*)} | # Escape sequence of two delimiters.
{((?P<section>[-a-z0-9 ._]+):)? # Optional section name.
(?P<option>[-a-z0-9 ._]+) # Required option name.
(?P<path_extension>/[^|}]+/?)? # Optional path extensions.
([ ]*(?P<filters>(\|[ ]*[-a-z0-9._]+[ ]*)+))?
# Optional filters.
} |
{(?P<invalid>[^}]*}) # Other ill-formed delimiter exprs.
)
""", re.IGNORECASE | re.VERBOSE)
def __init__(self, source, destination, recipe):
self.source = source
self.destination = zc.buildout.easy_install.realpath(destination)
self.recipe = recipe
self.template = open(source).read()
def get_colno_lineno(self, i):
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = len(lines[-1]) + 1
lineno = len(lines)
return colno, lineno
def _get(self, section, option, start):
if section is None:
section = self.recipe.name # This sets up error messages properly.
if section == self.recipe.name:
factory = self.recipe.dynamic_options.get(option)
if factory is not None:
return self.recipe._call_and_log(
factory, (self, start, option),
lambda lineno, colno: (
'Dynamic option %r in line %d, col %d of %s '
'crashed.') % (option, lineno, colno, self.source))
# else...
options = self.recipe.options
elif section in self.recipe.buildout:
options = self.recipe.buildout[section]
else:
value = options = None
if options is not None:
value = options.get(option, None, self.recipe.seen)
if value is None:
colno, lineno = self.get_colno_lineno(start)
raise zc.buildout.buildout.MissingOption(
"Option '%s:%s', referenced in line %d, col %d of %s, "
"does not exist." %
(section, option, lineno, colno, self.source))
return value
def substitute(self):
def convert(mo):
start = mo.start()
# Check the most common path first.
option = mo.group('option')
if option is not None:
section = mo.group('section')
val = self._get(section, option, start)
path_extension = mo.group('path_extension')
filters = mo.group('filters')
if path_extension is not None:
val = os.path.join(val, *path_extension.split('/')[1:])
if filters is not None:
for filter_name in filters.split('|')[1:]:
filter_name = filter_name.strip()
filter = self.recipe.filters.get(filter_name)
if filter is None:
colno, lineno = self.get_colno_lineno(start)
raise ValueError(
'Unknown filter %r '
'in line %d, col %d of %s' %
(filter_name, lineno, colno, self.source))
val = self.recipe._call_and_log(
filter, (val, self, start, filter_name),
lambda lineno, colno: (
'Filter %r in line %d, col %d of %s '
'crashed processing value %r') % (
filter_name, lineno, colno, self.source, val))
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % (val,)
escaped = mo.group('escaped')
if escaped is not None:
return '${%s}' % (escaped,)
invalid = mo.group('invalid')
if invalid is not None:
colno, lineno = self.get_colno_lineno(mo.start('invalid'))
raise ValueError(
'Invalid placeholder %r in line %d, col %d of %s' %
(mo.group('invalid'), lineno, colno, self.source))
raise ValueError('Unrecognized named group in pattern',
self.pattern) # programmer error, AFAICT
return self.pattern.sub(convert, self.template)
############################################################################
# Filters
def filter(func):
"Helper function to register filter functions."
FileTemplate.filters[func.__name__.replace('_', '-')] = func
return func
@filter
def capitalize(val, template, start, filter):
return val.capitalize()
@filter
def title(val, template, start, filter):
return val.title()
@filter
def upper(val, template, start, filter):
return val.upper()
@filter
def lower(val, template, start, filter):
return val.lower()
@filter
def path_repr(val, template, start, filter):
# val is a path.
return _maybe_relativize(
val, template,
lambda p: "_z3c_recipe_filetemplate_path_repr(%r)" % (p,),
repr)
@filter
def shell_path(val, template, start, filter):
# val is a path.
return _maybe_relativize(
val, template,
lambda p: '"$Z3C_RECIPE_FILETEMPLATE_BASE"/%s' % (p,),
lambda p: p)
# Helpers hacked from zc.buildout.easy_install.
def _maybe_relativize(path, template, relativize, absolutize):
path = zc.buildout.easy_install.realpath(path)
if template.recipe.relative_paths:
buildout_root = template.recipe.buildout_root
if path == buildout_root:
return relativize(os.curdir)
destination = template.destination
common = os.path.dirname(os.path.commonprefix([path, destination]))
if (common == buildout_root or
common.startswith(os.path.join(buildout_root, ''))
):
return relativize(_relative_path(common, path))
return absolutize(path)
def _relative_path(common, path):
"""Return the relative path from ``common`` to ``path``.
This is a helper for _relativitize, which is a helper to
_relative_path_and_setup.
"""
r = []
while 1:
dirname, basename = os.path.split(path)
r.append(basename)
if dirname == common:
break
assert dirname != path, "dirname of %s is the same" % dirname
path = dirname
r.reverse()
return os.path.join(*r)
############################################################################
# Dynamic options
def dynamic_option(func):
"Helper function to register dynamic options."
FileTemplate.dynamic_options[func.__name__.replace('_', '-')] = func
return func
@dynamic_option
def os_paths(template, start, name):
return os.pathsep.join(
shell_path(path, template, start, 'os-paths')
for path in template.recipe.paths)
@dynamic_option
def string_paths(template, start, name):
colno, lineno = template.get_colno_lineno(start)
separator = ',\n' + ((colno - 1) * ' ')
return separator.join(
path_repr(path, template, start, 'string-paths')
for path in template.recipe.paths)
@dynamic_option
def space_paths(template, start, name):
return ' '.join(
shell_path(path, template, start, 'space-paths')
for path in template.recipe.paths)
@dynamic_option
def shell_relative_path_setup(template, start, name):
if template.recipe.relative_paths:
depth = _relative_depth(
template.recipe.buildout['buildout']['directory'],
template.destination)
value = SHELL_RELATIVE_PATH_SETUP
if depth:
value += '# Ascend to buildout root.\n'
value += depth * SHELL_DIRNAME
else:
value += '# This is the buildout root.\n'
return value
else:
return ''
SHELL_RELATIVE_PATH_SETUP = '''\
# Get full, non-symbolic-link path to this file.
Z3C_RECIPE_FILETEMPLATE_FILENAME=`\\
readlink -f "$0" 2>/dev/null || \\
realpath "$0" 2>/dev/null || \\
type -P "$0" 2>/dev/null`
# Get directory of file.
Z3C_RECIPE_FILETEMPLATE_BASE=`dirname ${Z3C_RECIPE_FILETEMPLATE_FILENAME}`
'''
SHELL_DIRNAME = '''\
Z3C_RECIPE_FILETEMPLATE_BASE=`dirname ${Z3C_RECIPE_FILETEMPLATE_BASE}`
'''
@dynamic_option
def python_relative_path_setup(template, start, name):
if template.recipe.relative_paths:
depth = _relative_depth(
template.recipe.buildout['buildout']['directory'],
template.destination)
value = PYTHON_RELATIVE_PATH_SETUP_START
if depth:
value += '# Ascend to buildout root.\n'
value += depth * PYTHON_DIRNAME
else:
value += '# This is the buildout root.\n'
value += PYTHON_RELATIVE_PATH_SETUP_END
return value
else:
return ''
PYTHON_RELATIVE_PATH_SETUP_START = '''\
import os, imp
# Get path to this file.
if __name__ == '__main__':
_z3c_recipe_filetemplate_filename = __file__
else:
# If this is an imported module, we want the location of the .py
# file, not the .pyc, because the .py file may have been symlinked.
_z3c_recipe_filetemplate_filename = imp.find_module(__name__)[1]
# Get the full, non-symbolic-link directory for this file.
_z3c_recipe_filetemplate_base = os.path.dirname(
os.path.abspath(os.path.realpath(_z3c_recipe_filetemplate_filename)))
'''
PYTHON_DIRNAME = '''\
_z3c_recipe_filetemplate_base = os.path.dirname(
_z3c_recipe_filetemplate_base)
'''
PYTHON_RELATIVE_PATH_SETUP_END = '''\
def _z3c_recipe_filetemplate_path_repr(path):
"Return absolute version of buildout-relative path."
return os.path.join(_z3c_recipe_filetemplate_base, path)
'''
def _relative_depth(common, path):
# Helper ripped from zc.buildout.easy_install.
"""Return number of dirs separating ``path`` from ancestor, ``common``.
For instance, if path is /foo/bar/baz/bing, and common is /foo, this will
return 2--in UNIX, the number of ".." to get from bing's directory
to foo.
"""
n = 0
while 1:
dirname = os.path.dirname(path)
if dirname == path:
raise AssertionError("dirname of %s is the same" % dirname)
if dirname == common:
break
n += 1
path = dirname
return n | z3c.recipe.filetemplate | /z3c.recipe.filetemplate-2.2.0.tar.gz/z3c.recipe.filetemplate-2.2.0/z3c/recipe/filetemplate/__init__.py | __init__.py |
=============================
Translation domain extraction
=============================
z3c.recipe.i18n
---------------
This Zope 3 recipes offers different tools which allows to extract i18n
translation messages from egg based packages.
The 'i18n' recipe can be used to generate the required scripts for extract
message ids from egg based packages. The i18nmerge allows to merge them into
a .po file. And the i18nstats script gives you an overview about the state
of the translated files.
Note
----
This i18nextract.py file uses different semantic for the arguments. The script
offers to define egg packages instead of one package path. This makes it easy
to define eggs as source where we extract the messages from.
Options
*******
The i18n recipe accepts the following options:
eggs
The names of one or more eggs, with their dependencies that should
be included in the Python path of the generated scripts.
packages
The names of one or more eggs which the messages should get extracted from.
Note, this is different to the original zope.app.locales implementation.
The original implementation uses one path as -d argument which assumes a
specific zope.* package structure with an old style trunk setup.
domain
The translation domain.
output
The path of the output file relative to the package root.
maker
One or more module name which can get used as additional maker. This module
must be located in the python path because it get resolved by
zope.configuration.name.resolve. For a sample maker see
z3c.csvvocabulary.csvStrings.
Makers are called with these arguments: 'path', 'base_path', 'exclude_dirs',
'domain', 'include_default_domain' and 'site_zcml'. The return value has to
be a catalog dictionary.
zcml (required)
The contents of configuration used for extraction. Normaly used for load meta
configuration. Note: To include a ZCML file outside package, you can use,
``include`` directive with ``file`` option. For example: ``<include
file="${buildout:directory}/etc/site.zcml" />``
excludeDefaultDomain (optional, default=False)
Exclude all messages found as part of the default domain. Messages are in
this domain, if their domain could not be determined. This usually happens
in page template snippets. (False if not used)
pythonOnly (optional, default=False)
Only extract message ids from Python (False if not used)
verify_domain (optional, default=False)
Retrieve all the messages in all the domains in python files when
verify_domain is False otherwise only retrive the messages of the
specified domain. (False if not used)
excludeDirectoryName (optional, default=[])
Allows to specify one or more directory name, relative to the package, to
exclude. (None if not used)
headerTemplate (optional, default=None)
The path of the pot header template relative to the buildout directory.
environment
A section name defining a set of environment variables that should be
exported before starting the tests. Can be used for set product
configuration enviroment.
extraPaths
A new line separated list of directories which are added to the PYTHONPATH.
Test
****
Lets define some (bogus) eggs that we can use in our application:
>>> mkdir('outputDir')
>>> mkdir('demo1')
>>> write('demo1', 'setup.py',
... '''
... from setuptools import setup
... setup(name = 'demo1')
... ''')
>>> mkdir('demo2')
>>> write('demo2', 'setup.py',
... '''
... from setuptools import setup
... setup(name = 'demo2', install_requires='demo1')
... ''')
Now check if the setup was correct:
>>> ls('bin')
- buildout
Lets create a minimal `buildout.cfg` file:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = i18n
... offline = true
...
... [i18n]
... recipe = z3c.recipe.i18n:i18n
... eggs = z3c.recipe.i18n
... packages = demo1
... domain = recipe
... output = outputDir
... zcml = <include package="z3c.recipe.tests" file="extract.zcml" />"
... ''' % globals())
Now, Let's run the buildout and see what we get:
>>> print(system(join('bin', 'buildout')))
Installing i18n.
i18n: setting up i18n tools
Generated script '/sample-buildout/bin/i18nextract'.
Generated script '/sample-buildout/bin/i18nmergeall'.
Generated script '/sample-buildout/bin/i18nstats'.
Generated script '/sample-buildout/bin/i18ncompile'...
After running buildout, the bin folder contains the different i18n script:
>>> ls('bin')
- buildout
- i18ncompile
- i18nextract
- i18nmergeall
- i18nstats
| z3c.recipe.i18n | /z3c.recipe.i18n-2.0-py3-none-any.whl/z3c/recipe/i18n/README.rst | README.rst |
import getopt
import os
import sys
SEARCHING = 0
COMMENT = 1
MSGID = 2
MSGSTR = 3
MSGDONE = 4
def usage(code, msg=""):
"""Display help."""
print("\n".join(__doc__.split("\n")[:-2]), file=sys.stderr)
if msg:
print("** Error: " + str(msg) + " **", file=sys.stderr)
sys.exit(code)
def getMessageDictionary(file):
"""Simple state machine."""
msgs = []
comment = []
msgid = []
msgstr = []
fuzzy = False
line_counter = 0
status = SEARCHING
for line in file.readlines():
line = line.strip("\n")
line_counter += 1
# Handle Events
if line.startswith("#"):
status = COMMENT
elif line.startswith("msgid"):
line = line[6:]
line_number = line_counter
status = MSGID
elif line.startswith("msgstr"):
line = line[7:]
status = MSGSTR
elif line == "":
status = MSGDONE
# Actions based on status
if status == MSGID:
msgid.append(line.strip('"'))
elif status == MSGSTR:
msgstr.append(line.strip('"'))
elif status == COMMENT:
if line.startswith("#, fuzzy"):
fuzzy = True
comment.append(line[1:].strip())
elif status == MSGDONE:
status = SEARCHING
# Avoid getting the meta-data message string
if "".join(msgid):
msgs.append(
(
"".join(msgid),
"".join(msgstr),
line_number,
"\n".join(comment),
fuzzy,
)
)
comment = []
msgid = []
msgstr = []
fuzzy = False
return msgs
def stats(path):
print("Language Total Done Not Done Fuzzy Done %")
print("==========================================================")
languages = sorted(os.listdir(path))
for language in languages:
lc_messages_path = os.path.join(path, language, "LC_MESSAGES")
# Make sure we got a language directory
if not os.path.isdir(lc_messages_path):
continue
msgs = []
for domain_file in os.listdir(lc_messages_path):
if domain_file.endswith(".po"):
domain_path = os.path.join(lc_messages_path, domain_file)
with open(domain_path) as f:
msgs += getMessageDictionary(f)
# We are dealing with the default language, which always has just one
# message string for the meta data (which is not recorded).
if len(msgs) == 0:
continue
total = len(msgs)
not_done = len([msg for msg in msgs if msg[1] == ""])
fuzzy = len([msg for msg in msgs if msg[4] is True])
done = total - not_done - fuzzy
percent_done = 100.0 * done / total
line = language + " " * (8 - len(language))
line += " " * (9 - len(str(total))) + str(total)
line += " " * (8 - len(str(done))) + str(done)
line += " " * (12 - len(str(not_done))) + str(not_done)
line += " " * (9 - len(str(fuzzy))) + str(fuzzy)
pd_str = "%0.2f %%" % percent_done
line += " " * (12 - len(pd_str)) + pd_str
print(line)
def main(argv=sys.argv):
try:
opts, args = getopt.getopt(argv[1:], "l:h", ["help", "locals-dir="])
except getopt.error as msg:
usage(1, msg)
path = None
for opt, arg in opts:
if opt in ("-h", "--help"):
usage(0)
elif opt in ("-l", "--locales-dir"):
cwd = os.getcwd()
# This is for symlinks. Thanks to Fred for this trick.
if "PWD" in os.environ:
cwd = os.environ["PWD"]
path = os.path.normpath(os.path.join(cwd, arg))
if path is None:
usage(1, "You must specify the path to the locales directory.")
stats(path)
if __name__ == "__main__":
main() | z3c.recipe.i18n | /z3c.recipe.i18n-2.0-py3-none-any.whl/z3c/recipe/i18n/i18nstats.py | i18nstats.py |
import getopt
import os
import sys
from zope.app.locales.extract import POTMaker
from zope.app.locales.extract import py_strings
from zope.app.locales.extract import tal_strings
from zope.app.locales.extract import zcml_strings
from zope.configuration.name import resolve
def usage(code, msg=""):
print(__doc__, file=sys.stderr)
if msg:
print(msg, file=sys.stderr)
sys.exit(code)
def main(argv=sys.argv):
try:
opts, args = getopt.getopt(
argv[1:],
"hed:s:i:m:p:o:x:t:",
[
"help",
"domain=",
"site_zcml=",
"path=",
"python-only",
"verify-domain",
"exclude-default-domain",
],
)
except getopt.error as msg:
usage(1, msg)
domain = "z3c"
include_default_domain = True
output_dir = None
exclude_dirs = []
python_only = False
verify_domain = False
site_zcml = None
makers = []
eggPaths = []
header_template = None
for opt, arg in opts:
if opt in ("-h", "--help"):
usage(0)
elif opt in ("-d", "--domain"):
domain = arg
elif opt in ("-s", "--site_zcml"):
site_zcml = arg
elif opt in ("-e", "--exclude-default-domain"):
include_default_domain = False
elif opt in ("-m",):
makers.append(resolve(arg))
elif opt in ("-o",):
output_dir = arg
elif opt in ("-x",):
exclude_dirs.append(arg)
elif opt in ("--python-only",):
python_only = True
elif opt in ("--verify-domain"):
verify_domain = True
elif opt in ("-p", "--package"):
package = resolve(arg)
path = os.path.dirname(package.__file__)
if not os.path.exists(path):
usage(1, "The specified path does not exist.")
eggPaths.append((arg, path))
elif opt in ("-t",):
if not os.path.exists(arg):
usage(1, "The specified header template does not exist.")
header_template = arg
# setup output file
output_file = domain + ".pot"
if output_dir:
if not os.path.exists(output_dir):
os.mkdir(output_dir)
output_file = os.path.join(output_dir, output_file)
print(
"domain: %r\n"
"configuration: %s\n"
"exclude dirs: %r\n"
"include default domain: %r\n"
"python only: %r\n"
"verify domain: %r\n"
"header template: %r\n"
% (
domain,
site_zcml,
exclude_dirs,
include_default_domain,
python_only,
verify_domain,
header_template,
)
)
# setup pot maker
maker = POTMaker(output_file, "", header_template)
# add maker for each given path
for pkgName, path in eggPaths:
basePath = path
moduleNames = pkgName.split(".")
moduleNames.reverse()
for mName in moduleNames:
mIdx = path.rfind(mName)
basePath = basePath[:mIdx]
pkgPath = path[len(basePath):]
print(
"package: %r\n"
"base: %r\n"
"path: %r\n" % (pkgPath, basePath, path)
)
maker.add(
py_strings(
path, domain, exclude=exclude_dirs, verify_domain=verify_domain
),
basePath,
)
if not python_only:
maker.add(zcml_strings(path, domain, site_zcml), basePath)
maker.add(
tal_strings(
path, domain, include_default_domain, exclude=exclude_dirs
),
basePath,
)
for maker_func in makers:
try:
maker.add(
maker_func(
path=path,
base_path=basePath,
exclude_dirs=exclude_dirs,
domain=domain,
include_default_domain=include_default_domain,
site_zcml=site_zcml,
),
basePath,
)
except TypeError:
# BBB: old arguments
maker.add(maker_func(path, basePath, exclude_dirs), basePath)
maker.write()
print("output: %r\n" % output_file)
if __name__ == "__main__":
main() | z3c.recipe.i18n | /z3c.recipe.i18n-2.0-py3-none-any.whl/z3c/recipe/i18n/i18nextract.py | i18nextract.py |
import logging
import os
import pkg_resources
import zc.buildout
import zc.recipe.egg
this_loc = pkg_resources.working_set.find(
pkg_resources.Requirement.parse("z3c.recipe.i18n")
).location
zcmlTemplate = """<configure xmlns='http://namespaces.zope.org/zope'
xmlns:meta="http://namespaces.zope.org/meta"
>
%s
</configure>
"""
initialization_template = """import os
sys.argv[0] = os.path.abspath(sys.argv[0])
os.chdir('%s')
"""
env_template = """os.environ['%s'] = %r
"""
class I18nSetup:
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
if "eggs" not in self.options:
self.options["eggs"] = ""
self.options["eggs"] = (
self.options["eggs"] + "\n" + "zope.app.locales [extract]"
)
self.egg = zc.recipe.egg.Egg(buildout, name, options)
def install(self):
logging.getLogger(self.name).info("setting up i18n tools")
requirements, ws = self.egg.working_set()
excludeDefaultDomain = self.options.get("excludeDefaultDomain", False)
pythonOnly = self.options.get("pythonOnly", False)
verify_domain = self.options.get("verify_domain", False)
# setup configuration file
zcml = self.options.get("zcml", None)
if zcml is None:
raise zc.buildout.UserError("No zcml configuration defined.")
zcml = zcmlTemplate % zcml
# get domain
domain = self.options.get("domain", None)
if domain is None:
raise zc.buildout.UserError("No domain given.")
# get output path
output = self.options.get("output", None)
if output is None:
raise zc.buildout.UserError("No output path given.")
output = os.path.abspath(output)
partsDir = os.path.join(
self.buildout["buildout"]["parts-directory"], self.name
)
if not os.path.exists(partsDir):
os.mkdir(partsDir)
zcmlFilename = os.path.join(partsDir, "configure.zcml")
with open(zcmlFilename, "w") as zcmlFile:
zcmlFile.write(zcml)
# Generate i18nextract
arguments = [
"%sextract" % self.name,
"-d", domain,
"-s", zcmlFilename,
"-o", output,
]
if excludeDefaultDomain:
arguments.extend(["--exclude-default-domain"])
if pythonOnly:
arguments.extend(["--python-only"])
if verify_domain:
arguments.extend(["--verify-domain"])
makers = [m for m in self.options.get("maker", "").split() if m != ""]
for m in makers:
arguments.extend(["-m", m])
# add package names as -p multi option
packages = [
p for p in self.options.get("packages", "").split() if p != ""
]
for p in packages:
arguments.extend(["-p", p])
excludeDirNames = [
x
for x in self.options.get("excludeDirectoryName", "").split()
if x != ""
]
for x in excludeDirNames:
arguments.extend(["-x", x])
header_template = self.options.get("headerTemplate", None)
if header_template is not None:
header_template = os.path.normpath(
os.path.join(
self.buildout["buildout"]["directory"],
header_template.strip(),
)
)
arguments.extend(["-t", header_template])
initialization = initialization_template % this_loc
env_section = self.options.get("environment", "").strip()
if env_section:
env = self.buildout[env_section]
for key, value in env.items():
initialization += env_template % (key, value)
extra_paths = [this_loc] + self.options.get("extraPaths", "").split(
"\n"
)
extra_paths = [p for p in extra_paths if p]
# Generate i18nextract
generated = zc.buildout.easy_install.scripts(
[("%sextract" % self.name, "z3c.recipe.i18n.i18nextract", "main")],
ws,
self.options["executable"],
self.buildout["buildout"]["bin-directory"],
extra_paths=extra_paths,
arguments=arguments,
initialization=initialization,
)
# Generate i18nmergeall
arguments = ["%smergeall" % self.name, "-l", output]
generated.extend(
zc.buildout.easy_install.scripts(
[
(
"%smergeall" % self.name,
"z3c.recipe.i18n.i18nmergeall",
"main",
)
],
ws,
self.options["executable"],
self.buildout["buildout"]["bin-directory"],
extra_paths=extra_paths,
arguments=arguments,
)
)
# Generate i18nstats
arguments = ["%sstats" % self.name, "-l", output]
generated.extend(
zc.buildout.easy_install.scripts(
[("%sstats" % self.name, "z3c.recipe.i18n.i18nstats", "main")],
ws,
self.options["executable"],
self.buildout["buildout"]["bin-directory"],
extra_paths=extra_paths,
arguments=arguments,
)
)
# Generate i18ncompile
arguments = ["%scompile" % self.name, "-l", output]
generated.extend(
zc.buildout.easy_install.scripts(
[
(
"%scompile" % self.name,
"z3c.recipe.i18n.i18ncompile",
"main",
)
],
ws,
self.options["executable"],
self.buildout["buildout"]["bin-directory"],
extra_paths=extra_paths,
arguments=arguments,
)
)
return generated
update = install | z3c.recipe.i18n | /z3c.recipe.i18n-2.0-py3-none-any.whl/z3c/recipe/i18n/i18n.py | i18n.py |
"""Recipe ldap"""
import sys, os, signal, subprocess
import zc.buildout
import zc.recipe.egg
import conf
class Slapd(object):
"""This recipe is used by zc.buildout"""
def __init__(self, buildout, name, options):
self.name, self.options = name, options
# Avoid clobbering the index option
# TODO Figure out how to test for this
index = options.pop('index', None)
self.egg = zc.recipe.egg.Egg(buildout, options['recipe'],
options)
if index is None:
options.pop('index', None)
else:
options['index'] = index
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], name)
if 'slapd' in options:
options['slapd'] = os.path.join(
buildout['buildout']['directory'], options['slapd'])
else:
options['slapd'] = 'slapd'
if 'conf' not in options:
options['conf'] = os.path.join(
options['location'], name+'.conf')
if 'pidfile' not in options:
options['pidfile'] = os.path.join(
options['location'], name+'.pid')
if 'directory' not in options:
options['directory'] = os.path.join(
buildout['buildout']['directory'], 'var', name)
if 'urls' in options and 'use-socket' in options:
raise ValueError('Cannot specify both the "urls" and '
'"use-socket" options')
if 'use-socket' in options:
options['urls'] = 'ldapi://%s' % os.path.join(
options['location'], name+'.socket').replace(
'/', '%2F')
# Initialize the conf options
conf.init_options(
options, dir=buildout['buildout']['directory'])
def install(self):
"""installer"""
# Install slapd.conf
os.makedirs(self.options['location'])
conf_file = file(self.options['conf'], 'w')
conf_file.writelines(conf.get_lines(self.options))
conf_file.close()
if not os.path.exists(self.options['directory']):
# Install the DB dir
os.makedirs(self.options['directory'])
# Install the control script
_, ws = self.egg.working_set(['z3c.recipe.ldap'])
zc.buildout.easy_install.scripts(
[(self.name, 'z3c.recipe.ldap.ctl', 'main')],
ws, self.options['executable'],
self.options['bin-directory'],
arguments=repr(self.options))
return (self.options['location'],)
def update(self):
"""updater"""
pass | z3c.recipe.ldap | /z3c.recipe.ldap-0.1.tar.gz/z3c.recipe.ldap-0.1/z3c/recipe/ldap/slapd.py | slapd.py |
=======================
z3c.recipe.ldap package
=======================
.. contents::
What is z3c.recipe.ldap ?
=========================
This recipe can be used to deploy an OpenLDAP server in a
zc.buildout. More specifically it provides for initializing an LDAP
database from an LDIF file and for setting up an LDAP instance in the
buildout. This recipe can also be used to provide an isolated LDAP
instance as a test fixture.
How to use z3c.recipe.ldap ?
============================
-------------------------
Installing slapd instance
-------------------------
The default recipe in z3c.recipe.ldap can be used to deploy a slapd
LDAP server in the buildout. Options in the slapd part not used by
the recipe itself will be used to create and populate a slapd.conf
file.
The only required option is the suffix argupent. Specifying the
suffix with a dc requires that the "dc" LDAP attribute type
configuration. Write a buildout.cfg with a suffix and include
core.schema for the attribute type configuration. Also specify that
the server should use a socket instead of a network port::
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = slapd
... find-links = http://download.zope.org/ppix/
...
... [slapd]
... recipe = z3c.recipe.ldap
... slapd = %(openldap)s/libexec/slapd
... use-socket = True
... allow = bind_v2
... include =
... %(openldap)s/etc/openldap/schema/core.schema
... foo.schema
... bar.conf
... modulepath =
... moduleload =
... suffix = "dc=localhost"
... """ % globals())
Create the files to be included::
>>> write(sample_buildout, 'foo.schema', '\n')
>>> write(sample_buildout, 'bar.conf', '\n')
Run the buildout::
>>> print system(buildout),
Installing slapd.
Generated script '/sample-buildout/bin/slapd'.
The configuration file is created in the part by default. Note that
keys that can be specified multiple times in slapd.conf, such as
include, will be constitued from multiple line separated values when
present. Also note that keys that contain file paths in slapd.conf,
such as include, will be expanded from the buildout directory.
Finally note that options specified with blank values will be
excluded::
>>> ls(sample_buildout, 'parts', 'slapd')
- slapd.conf
>>> cat(sample_buildout, 'parts', 'slapd', 'slapd.conf')
include .../etc/openldap/schema/core.schema
include /sample-buildout/foo.schema
include /sample-buildout/bar.conf
pidfile /sample-buildout/parts/slapd/slapd.pid
allow bind_v2
database bdb
suffix "dc=localhost"
directory /sample-buildout/var/slapd
dbconfig set_cachesize 0 268435456 1
dbconfig set_lg_regionmax 262144
dbconfig set_lg_bsize 2097152
index objectClass eq
The socket path is properly escaped in the configuration::
>>> cat(sample_buildout, '.installed.cfg')
[buildout]...
[slapd]...
urls = ldapi://...%2Fsample-buildout%2Fparts%2Fslapd%2Fslapd.socket
...
An empty directory is created for the LDAP database::
>>> ls(sample_buildout, 'var')
d slapd
>>> ls(sample_buildout, 'var', 'slapd')
A script is also created for starting and stopping the slapd server::
>>> ls(sample_buildout, 'bin')
- buildout
- slapd
Start the slapd server::
>>> bin = join(sample_buildout, 'bin', 'slapd')
>>> print system(bin+' start'),
On first run, the LDAP database is created::
>>> ls(sample_buildout, 'var', 'slapd')
- DB_CONFIG
- __db.001...
While the server is running a pid file is created and also a socket in
this case::
>>> ls(sample_buildout, 'parts', 'slapd')
- slapd.conf
- slapd.pid
- slapd.socket
Stop the slapd server::
>>> print system(bin+' stop'),
When the slapd server finishes shutting down the pid file is deleted::
>>> ls(sample_buildout, 'parts', 'slapd')
- slapd.conf
The slapd binary
----------------
The slapd binary to be used can be specified as we did above when we
specified the slapd binary from the buildout OpenLDAP CMMI part::
>>> cat(sample_buildout, '.installed.cfg')
[buildout]...
[slapd]...
slapd = .../parts/openldap/libexec/slapd
...
If no binary is specified, it's left up to the environment.
Write a buildout.cfg with no slapd specified::
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = slapd
...
... [slapd]
... recipe = z3c.recipe.ldap
... use-socket = True
... """)
Run the buildout::
>>> print system(buildout),
Uninstalling slapd.
Installing slapd.
Generated script '/sample-buildout/bin/slapd'.
Now it will find the binary on the system path::
>>> cat(sample_buildout, '.installed.cfg')
[buildout]...
[slapd]...
slapd = slapd
...
----------------------------
Initalizing an LDAP database
----------------------------
The z3c.recipe.ldap.Slapadd can be used initialize an LDAP database
from an LDIF file. In the simplest form, simply provide an "ldif"
option in the part with one or more filenames.
Write a buildout.cfg that lists some LDIF files::
>>> write(sample_buildout, 'buildout.cfg',
... """
... [buildout]
... parts = slapd slapadd
...
... [slapd]
... recipe = z3c.recipe.ldap
... include =
... %(openldap)s/etc/openldap/schema/core.schema
... %(openldap)s/etc/openldap/schema/cosine.schema
... modulepath =
... moduleload =
... suffix = "dc=localhost"
...
... [slapadd]
... recipe = z3c.recipe.ldap:slapadd
... slapadd = %(openldap)s/sbin/slapadd
... conf = ${slapd:conf}
... ldif =
... dc.ldif
... admin.ldif
... """ % globals())
Write the LDIF files::
>>> write(sample_buildout, 'dc.ldif',
... """
... dn: dc=localhost
... dc: localhost
... objectClass: top
... objectClass: domain
... """)
>>> write(sample_buildout, 'admin.ldif',
... """
... dn: cn=admin,dc=localhost
... objectClass: person
... cn: admin
... sn: Manager
... """)
Run the buildout::
>>> print system(buildout),
Uninstalling slapd.
Installing slapd.
Generated script '/sample-buildout/bin/slapd'.
Installing slapadd.
The entries have been added to the LDAP database::
>>> print system(os.path.join(openldap, 'sbin', 'slapcat')+' -f '+
... os.path.join(sample_buildout,
... 'parts', 'slapd', 'slapd.conf')),
dn: dc=localhost
dc: localhost
objectClass: top
objectClass: domain...
dn: cn=admin,dc=localhost
objectClass: person
cn: admin
sn: Manager...
The LDIF files are added on update also.
Remove the existing LDAP database::
>>> rmdir(sample_buildout, 'var', 'slapd')
>>> mkdir(sample_buildout, 'var', 'slapd')
Run the Buildout to add the LDIF files again::
>>> print system(buildout),
Updating slapd.
Updating slapadd.
The entries have been added to the LDAP database::
>>> print system(os.path.join(openldap, 'sbin', 'slapcat')+' -f '+
... os.path.join(sample_buildout,
... 'parts', 'slapd', 'slapd.conf')),
dn: dc=localhost
dc: localhost
objectClass: top
objectClass: domain...
dn: cn=admin,dc=localhost
objectClass: person
cn: admin
sn: Manager...
| z3c.recipe.ldap | /z3c.recipe.ldap-0.1.tar.gz/z3c.recipe.ldap-0.1/z3c/recipe/ldap/docs/README.txt | README.txt |
:mod:`z3c.recipe.mkdir` Usage
=============================
Recipe Options
--------------
``z3c.recipe.mkdir`` provides the following options:
* ``paths``
Contains the path(s) of directories created in normalized,
absolute form. I.e.::
mydir/../foo/bar
becomes::
/path/to/buildout-dir/foo/bar
* ``remove-on-update``
Default: ``no``
By default, created directories are not removed
on updates of buildout configuration. This is a security measure
as created directories might contain valuable data.
You can, however, enforce automatic removing on updates by
setting this option to ``on``, ``yes`` or ``true``.
* ``user``
Default: system-dependent
You can optionally set a username that should own created
directories. The username must be valid name (not an uid) and the
system must support setting a user ownership for files. Of
course, the running process must have the permission to set the
requested user.
* ``group``
Default: system-dependent
You can optionally set a usergroup that should own created
directories.The group name must be a valid name (not a gid) and
the system must support setting a group ownership for files. Of
course, the running process must have the permission to set the
requested group.
* ``mode``
Default: system-dependent
You can optionally set file permissions for created directories
as octal numbers as usually used on Unix systems. These file
permissions will be set for each created directory if the running
process is allowed to do so.
Normally, a value of ``0700`` will give rwx permissions to the
owner and no permissions to group members or others.
If you don't specify a mode, the system default will be used.
* ``create-intermediate``
Default: ``yes``
If set to `no`, the parent directory of the path to create _must_
already exist when running the recipe (and an error occurs if not).
If set to `yes`, any missing intermediate directories will be
created. E.g. if creating a relative dir
``a/b/c/``
with ``create-intermediate`` set to ``no``, the relative path
``a/b/`` must exist already.
Simple creation of directories via buildout
-------------------------------------------
Lets create a minimal `buildout.cfg` file:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... ''')
Now we can run buildout:
>>> printx(system(join('bin', 'buildout')))
Installing mydir.
mydir: created path: /sample-buildout/parts/mydir
The directory was indeed created in the ``parts`` directory:
>>> ls_parts()
d mydir
As we did not specify a special path, the name of the created
directory is like the section name ``mydir``.
Creating a directory in a given path
------------------------------------
Lets create a minimal `buildout.cfg` file. This time the directory
has a name different from section name and we have to tell explicitly,
that we want it to be created in the ``parts/`` directory. We set the
``paths`` option to do so:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = ${buildout:parts-directory}/myotherdir
... ''')
Now we can run buildout:
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/parts/myotherdir
The directory was indeed created:
>>> ls_parts()
d mydir
d myotherdir
Creating directories that are removed on updates
------------------------------------------------
We can tell the recipe that a directory should be removed on updates by using
the ``remove-on-update`` option:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... remove-on-update = true
... paths = newdir
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/newdir
The ``newdir/`` directory was created:
>>> ls('.')
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
d newdir
d parts
We rewrite `buildout.cfg` and set a different path:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... remove-on-update = true
... paths = newdir2
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/newdir2
Now ``newdir/`` has vanished and ``newdir2`` exists:
>>> ls('.')
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
d newdir2
d parts
Note, that the created directory will be removed on next modification
of `buildout.cfg`.
Setting User, Group, and Permissions
------------------------------------
You can optionally set ``user``, ``group``, or ``mode`` option for the
dirs to be created.
While ``user`` and ``group`` give the user/group that should own the
created directory (and all not existing intermediate directories),
``mode`` is expected to be an octal number to represent the directory
permissions in Unix style.
Of course, setting all these permissions and ownerships only works if
the system supports it and the running user has the permissions to do
so.
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = my/new/dir
... mode = 700
... user = %s
... group = %s
... ''' % (user, group))
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/my
mydir: mode 0700, user 'USER', group 'GROUP'
mydir: created path: /sample-buildout/my/new
mydir: mode 0700, user 'USER', group 'GROUP'
mydir: created path: /sample-buildout/my/new/dir
mydir: mode 0700, user 'USER', group 'GROUP'
>>> lls('my')
drwx------ USER GROUP my/new
>>> lls('my/new')
drwx------ USER GROUP my/new/dir
These options are optional, so you can leave any of them out and the system
defaults will be used instead.
.. note:: Please note, that the permissions will only be set on newly
created directories. On updates only the permissions of the
leaf directory will be updated, not any intermediate
directories (except you set remove-on-update, which will
recreate also intermediate paths and set permissions
accordingly).
On updates only the leaf directories are changed
permission-wise. E.g. if we change the mode from the original buildout
from ``0700`` to ``0750``:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = my/new/dir
... remove-on-update = true
... mode = 750
... user = %s
... group = %s
... ''' % (user, group))
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: set permissions for /sample-buildout/my/new/dir
mydir: mode 0750, user 'USER', group 'GROUP'
the permissions of the leaf directory were updated:
>>> lls('my/new')
drwxr-x--- USER GROUP my/new/dir
while its parent's permissions are the same as before:
>>> lls('my')
drwx------ USER GROUP my/new
Clean up:
>>> import shutil
>>> shutil.rmtree('my')
Creating relative paths
-----------------------
If we specify a relative path, this path will be created relative to the
buildout directory:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = myrootdir
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/myrootdir
>>> ls('.')
- .installed.cfg
d bin
- buildout.cfg
d develop-eggs
d eggs
d myrootdir
d parts
The old directories will **not** vanish:
>>> ls_parts()
d mydir
d myotherdir
Creating intermediate paths
---------------------------
If we specify several levels of directories, the intermediate parts
will be created for us as well by default:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = myrootdir/other/dir/finaldir
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/myrootdir/other
mydir: created path: /sample-buildout/myrootdir/other/dir
mydir: created path: /sample-buildout/myrootdir/other/dir/finaldir
>>> ls('myrootdir', 'other', 'dir')
d finaldir
If we set the ``create-intermediate`` option to ``no`` (default is
``yes``), the resulting dir will only be created if the parent
directory exists already:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = leaf/dir/without/existing/parent
... create-intermediate = no
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
While:
Installing mydir.
Error: Cannot create: /sample-buildout/leaf/dir/without/existing/parent
Parent does not exist or not a directory.
If you want to be explicit about the paths to be created (and which
not), you can set ``create-intermediate`` to ``no`` and simply list
each part of the path in ``paths`` option. This has the nice
sideeffect of setting permissions correctly also for intermediate
paths:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = mydir
... mydir/with
... mydir/with/existing
... mydir/with/existing/parent
... create-intermediate = no
... mode = 750
... ''')
>>> printx(system(join('bin', 'buildout')))
Installing mydir.
mydir: created path: /sample-buildout/mydir
mydir: mode 0750
mydir: created path: /sample-buildout/mydir/with
mydir: mode 0750
mydir: created path: /sample-buildout/mydir/with/existing
mydir: mode 0750
mydir: created path: /sample-buildout/mydir/with/existing/parent
mydir: mode 0750
This is more text to write down, but you can be sure that only
explicitly named dirs are created and permissions set accordingly.
For instance you can require a certain path to exist already and
create only the trailing path parts. Say, we expect a local `etc/` to
exist and want to create `etc/myapp/conf.d`. The following config
would do the trick:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = etc/myapp
... etc/myapp/conf.d
... create-intermediate = no
... mode = 750
... ''')
If the local `etc/` dir does not exist, we fail:
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
While:
Installing mydir.
Error: Cannot create: /sample-buildout/etc/myapp
Parent does not exist or not a directory.
But if this dir exists:
>>> mkdir('etc')
>>> printx(system(join('bin', 'buildout')))
Installing mydir.
mydir: created path: /sample-buildout/etc/myapp
mydir: mode 0750
mydir: created path: /sample-buildout/etc/myapp/conf.d
mydir: mode 0750
the subdirectories are created as expected.
It does, by the way, not matter, in which order you put the partial
parts into ``paths`` as this list is sorted before being
processed. So, any path `a/b/` will be processed before `a/b/c/`
regardless of the order in which both parts appear in the
configuration file.
Paths are normalized
--------------------
If we specify a non-normalized path (i.e. one that contains references
to parent directories or similar), the path will be normalized before
creating it:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = myroot/foo/../dir1/../bar/.
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/myroot
mydir: created path: /sample-buildout/myroot/bar
Only ``bar/`` will be created:
>>> ls('myroot')
d bar
Creating multiple paths in a row
--------------------------------
We can create multiple paths in one buildout section:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = myroot/dir1
... myroot/dir2
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/myroot/dir1
mydir: created path: /sample-buildout/myroot/dir2
>>> ls('myroot')
d bar
d dir1
d dir2
Note, that in this case you cannot easily reference the set path from
other recipes or templates. If, for example in a template you
reference::
root_dir = ${mydir:path}
the result will become::
root_dir = /path/to/buildout/dir1
path/to/buildout/dir2
If you specify only one path, however, the second line will not appear.
Use several sections using `z3c.recipe.mkdir` if you want to reference
different created paths from templates or similar.
Trailing slashes do not matter
------------------------------
It doesn't matter, whether you specify the paths with trailing slash
or without:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = myroot/dir3/
... myroot/dir4
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/myroot/dir3
mydir: created path: /sample-buildout/myroot/dir4
>>> ls('myroot')
d bar
d dir1
d dir2
d dir3
d dir4
Things to be aware of
---------------------
If you change the setting of some path, the old directory and all its
contents will **not** be deleted (as you might expect from a buildout
recipe):
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = path1
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/path1
>>> write(join('path1', 'myfile'), 'blah\n')
>>> ls('path1')
- myfile
Now we switch the setting of mydir to ``path2``:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = path2
... ''')
>>> printy(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
mydir: created path: /sample-buildout/path2
<BLANKLINE>
The file we created above is still alive:
>>> ls('path1')
- myfile
Things one should not do
------------------------
Trying to create directories that exist and are files
#####################################################
If a part of a given path already exists and is a file, an error is
raised:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = mydir
... offline = true
...
... [mydir]
... recipe = z3c.recipe.mkdir
... paths = rootdir2/somefile/foo
... ''')
Now we create the first part of the path beforehand:
>>> import os
>>> os.mkdir('rootdir2')
And make the second part of the path a file:
>>> write(join('rootdir2', 'somefile'),
... '''
... blah
... ''')
>>> printx(system(join('bin', 'buildout')))
Uninstalling mydir.
Installing mydir.
While:
Installing mydir.
Error: Cannot create directory: /.../rootdir2/somefile. It's a file.
Referencing options
-------------------
From other buildout recipe components you can reference the options of
`z3c.recipe.mkdir` like this::
${<sectionname>:paths}
where ``<sectionname>`` is the name of the `buildout.cfg` section
wherein you set the paths.
Options `mode`, `user`, and `group` are only referencable if they are
explicitly set.
Referencing without giving a path
#################################
You can reference also, if no path was given explicitly in
`buildout.cfg`:
>>> import z3c.recipe.mkdir
>>> buildout = dict(
... buildout = {
... 'directory': '/buildout',
... 'parts-directory' : '/buildout/parts',
... },
... somedir = {},
... )
>>> recipe = z3c.recipe.mkdir.Recipe(
... buildout, 'somedir', buildout['somedir'])
>>> printy(buildout['somedir']['paths'])
/buildout/parts/somedir
This means that if you have a `buildout.cfg` like this::
[buildout]
parts = somedir ...
[somedir]
recipe = z3c.recipe.mkdir
...
then for instance in a template you can write::
mydir = ${somedir:paths}
which will turn into::
mydir = /buildout/parts/somedir
Referencing with single path set
################################
If you reference a single path, you will get this back in references:
>>> buildout = dict(
... buildout = {
... 'directory': '/buildout',
... 'parts-directory' : '/buildout/parts',
... },
... somedir = {
... 'paths' : 'otherdir',
... },
... )
>>> recipe = z3c.recipe.mkdir.Recipe(
... buildout, 'somedir', buildout['somedir'])
>>> printy(buildout['somedir']['paths'])
/sample-buildout/otherdir
Referencing with multiple paths set
###################################
If you set several paths in `buildout.cfg`, you will get several lines
of output when referencing:
>>> buildout = dict(
... buildout = {
... 'directory': '/buildout',
... 'parts-directory' : '/buildout/parts',
... },
... somedir = {
... 'paths' : 'dir1 \n dir2',
... },
... )
>>> recipe = z3c.recipe.mkdir.Recipe(
... buildout, 'somedir', buildout['somedir'])
>>> printy(buildout['somedir']['paths'])
/sample-buildout/dir1
/sample-buildout/dir2
| z3c.recipe.mkdir | /z3c.recipe.mkdir-1.0-py3-none-any.whl/z3c/recipe/mkdir/README.rst | README.rst |
import logging
import os
import zc.buildout
class Recipe:
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
self.logger = logging.getLogger(self.name)
self.remove_on_update = string_to_bool(
options.get('remove-on-update', 'no'))
self.create_intermediate = string_to_bool(
options.get('create-intermediate', 'yes'))
paths = options.get('paths',
os.path.join(
buildout['buildout']['parts-directory'], name))
self.paths = []
for path in paths.split('\n'):
path = path.strip()
if not path:
# don't consider empty dirs
continue
self.paths.append(os.path.normpath(os.path.abspath(path)))
self.paths = sorted(self.paths)
self.mode = options.get('mode', None)
if self.mode is not None:
try:
self.mode = int(self.mode, 8)
except ValueError:
raise zc.buildout.UserError(
"'mode' must be an octal number: " % self.mode)
# determine user id
self.user = options.get('user', None)
self.uid = -1
if self.user:
try:
import pwd
self.uid = pwd.getpwnam(options['user'])[2]
except ImportError:
self.logger.warn(
"System does not support `pwd`. Using default user")
# determine group id
self.group = options.get('group', None)
self.gid = -1
if self.group:
try:
import grp
self.gid = grp.getgrnam(options['group'])[2]
except ImportError:
self.logger.warn(
"System does not support `grp`. Using default group")
# Update options to be referencable...
options['paths'] = '\n'.join(self.paths)
options['create-intermediate'] = '%s' % self.create_intermediate
options['remove-on-update'] = '%s' % self.remove_on_update
if self.mode:
options['mode'] = oct(self.mode)
if self.user:
options['user'] = self.user
if self.group:
options['group'] = self.group
def install(self):
for path in self.paths:
self.createIntermediatePaths(path)
return self.options.created()
def update(self):
return self.install()
def createIntermediatePaths(self, path):
parent = os.path.dirname(path)
if self.create_intermediate is False:
if path in self.paths and not os.path.isdir(parent):
raise zc.buildout.UserError(
"Cannot create: %s\n"
" Parent does not exist or not a directory." % path)
if os.path.exists(path) and not os.path.isdir(path):
raise zc.buildout.UserError(
"Cannot create directory: %s. It's a file." % path)
if parent == path or os.path.exists(path):
if path in self.paths:
self.logger.info('set permissions for %s' % path)
self.setPermissions(path)
return
if not os.path.isdir(parent):
self.createIntermediatePaths(parent)
os.mkdir(path)
self.logger.info('created path: %s' % path)
self.setPermissions(path)
if self.remove_on_update:
self.options.created(path)
def setPermissions(self, path):
additional_msgs = []
if self.mode is not None:
os.chmod(path, self.mode)
additional_msgs.append('mode 0%o' % self.mode)
if self.uid != -1 or self.gid != -1:
os.chown(path, self.uid, self.gid)
if self.uid != -1:
additional_msgs.append("user %r" % self.user)
if self.gid != -1:
additional_msgs.append("group %r" % self.group)
if additional_msgs:
self.logger.info(' ' + ', '.join(additional_msgs))
def string_to_bool(value):
if value is True or value is False:
return value
value = value.lower()
return value in ['yes', 'on', 'true', '1'] | z3c.recipe.mkdir | /z3c.recipe.mkdir-1.0-py3-none-any.whl/z3c/recipe/mkdir/__init__.py | __init__.py |
z3c.recipe.openoffice
=====================
This recipe download openoffice in your buildout, it can also (optional)
create egg with pyuno and change the default python used by openoffice.
More info about Python UNO: http://udk.openoffice.org/python/python-bridge.html
We are using this to generate OpenOffice documents from zope/python
Buildout configuration:
-----------------------
Add this section to your buildout configuration::
[buildout]
parts =
... your other parts ...
openoffice
...
[openoffice]
recipe = z3c.recipe.openoffice
This will just download and install openoffice in your buildout
To create the pyuno egg add the fallowing config::
[openoffice]
recipe = z3c.recipe.openoffice
install-pyuno-egg = yes
To also change openoffice python, add the following config::
[openoffice]
recipe = z3c.recipe.openoffice
install-pyuno-egg = yes
hack-openoffice-python = yes
By default it will fetch version OpenOffice 2.3 but you might want to install from another location or another version like this::
[openoffice]
recipe = z3c.recipe.openoffice
install-pyuno-egg = yes
hack-openoffice-python = yes
version = 2.3.1
download-url = ftp://ftp.openoffice.skynet.be/pub/ftp.openoffice.org/stable/2.3.1/OOo_2.3.1_LinuxIntel_install_en-US.tar.gz
Notes:
------
For this to work an OpenOffice process need to be running in background. As this require a X server and you don't want to install a real X server in a production environment you might want to use Xvfb. Here are the lines we use to start openoffice::
$ cd myBuildout
$ Xvfb :3 -ac -screen sn 800x600x16 &
$ ./parts/openoffice/program/soffice "-accept=socket,host=localhost,port=2002;urp;" -display :3 &
$ ./bin/instance start
This recipe only works with linux at the moment
To test pyuno (requires zopepy in buildout.cfg)::
$ ./bin/zopepy
>>> import pyuno
If you get the fallowing error::
"SystemError: dynamic module not initialized properly"
Do::
$ ldconfig YOURBUILDOUTFOLDER/parts/openoffice/program
Authors:
--------
Original author: Martijn Faassen - [email protected]
Modified by: Jean-Francois Roche - [email protected]
| z3c.recipe.openoffice | /z3c.recipe.openoffice-0.3.tar.gz/z3c.recipe.openoffice-0.3/README.txt | README.txt |
import glob
import logging
import os, sys
import shutil
import urllib
from distutils import sysconfig
import zc.buildout
PYUNO_SETUP = """
from setuptools import setup, find_packages
import sys, os
version = '0.1'
name='pyuno'
setup(name=name,
version=version,
author="Affinitic",
author_email="[email protected]",
description="little egg with pyuno",
license='ZPL 2.1',
keywords = "openoffice",
url='http://svn.affinitic.be',
packages=find_packages('src'),
include_package_data=True,
package_dir = {'': 'src'},
namespace_packages=[],
install_requires=['setuptools'],
zip_safe=False)
"""
class Recipe(object):
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
self.logger = logging.getLogger(self.name)
options['location'] = os.path.join(
buildout['buildout']['parts-directory'],
self.name)
python = buildout['buildout']['python']
options['executable'] = buildout[python]['executable']
options['tmp-storage'] = os.path.join(
buildout['buildout']['directory'], 'tmp-storage')
options.setdefault(
'version','2.3')
options.setdefault(
'download-url',
'ftp://ftp.openoffice.skynet.be/pub/ftp.openoffice.org/stable/2.3.1/OOo_2.3.1_LinuxIntel_install_en-US.tar.gz')
options.setdefault(
'unpack-name',
'OOG680_m9_native_packed-1_en-US.9238')
options.setdefault(
'hack-openoffice-python',
'no')
options.setdefault(
'install-pyuno-egg',
'no')
def install(self):
location = self.options['location']
if os.path.exists(location):
return location
storage = self.options['tmp-storage']
if not os.path.exists(storage):
os.mkdir(storage)
download_file = self.download(storage)
self.untar(download_file, storage)
self.unrpm(storage)
copy_created = self.copy(storage)
if copy_created and \
self.options['hack-openoffice-python'].lower() == 'yes':
self.hack_python()
if copy_created and self.options['install-pyuno-egg'].lower() == 'yes':
self.install_pyuno_egg()
return location
def download(self, whereto):
"""Download tarball into temporary location.
"""
url = self.options['download-url']
tarball_name = os.path.basename(url)
download_file = os.path.join(whereto, tarball_name)
if not os.path.exists(download_file):
self.logger.info(
'Downloading %s to %s', url, download_file)
urllib.urlretrieve(url, download_file)
else:
self.logger.info("Tarball already downloaded.")
return download_file
def untar(self, download_file, storage):
"""Untar tarball into temporary location.
"""
unpack_dir = os.path.join(storage, self.options['unpack-name'])
if os.path.exists(unpack_dir):
self.logger.info("Unpack directory (%s) already exists... "
"skipping unpack." % unpack_dir)
return
self.logger.info("Unpacking tarball")
os.chdir(storage)
status = os.system('tar xzf ' + download_file)
assert status == 0
assert os.path.exists(unpack_dir)
def unrpm(self, storage):
"""extract information from rpms into temporary locatin.
"""
unrpm_dir = os.path.join(storage, 'opt')
if os.path.exists(unrpm_dir):
self.logger.info("Unrpm directory (%s) already exists... "
"skipping unrpm." % unrpm_dir)
return
self.logger.info("Unpacking rpms")
os.chdir(storage)
unpack_dir = os.path.join(storage, self.options['unpack-name'])
for path in glob.glob(os.path.join(unpack_dir, 'RPMS', '*.rpm')):
os.system('rpm2cpio %s | cpio -idum' % path)
def copy(self, storage):
"""Copy openoffice installation into parts directory.
"""
location = self.options['location']
if os.path.exists(location):
self.logger.info('No need to re-install openoffice part')
return False
self.logger.info("Copying unpacked contents")
shutil.copytree(os.path.join(storage, 'opt', 'openoffice.org%s' % self.options['version']),
location)
return True
def install_pyuno_egg(self):
self.logger.info("Creating pyuno egg")
location = self.options['location']
program_dir = os.path.join(location, 'program')
fd = open(os.path.join(program_dir,'setup.py'), 'w')
fd.write(PYUNO_SETUP)
fd.close()
egg_src_dir = os.path.join(program_dir,'src')
if not os.path.isdir(egg_src_dir):
os.mkdir(egg_src_dir)
for filename in ['pyuno.so', 'uno.py']:
if not os.path.islink(os.path.join(egg_src_dir,filename)):
os.symlink(os.path.join(program_dir,filename),
os.path.join(egg_src_dir,filename))
eggDirectory = self.buildout['buildout']['eggs-directory']
zc.buildout.easy_install.develop(program_dir, eggDirectory)
def hack_python(self):
"""Hack a different python into the OpenOffice installation.
This is so we can use UNO from that Python.
Right now we're hacking the same Python into OpenOffice as the
one used to run buildout with.
"""
self.logger.info("Hacking python into openoffice")
location = self.options['location']
program_dir = os.path.join(location, 'program')
os.remove(os.path.join(program_dir, 'libpython2.3.so.1.0'))
shutil.rmtree(os.path.join(program_dir, 'python-core-2.3.4'))
os.remove(os.path.join(program_dir, 'pythonloader.unorc'))
pythonhome = sys.exec_prefix
pythonpath = sysconfig.get_python_lib(standard_lib=True)
so = os.path.join(
os.path.split(pythonpath)[0],
'libpython%s.so.1.0' % sys.version[:3])
os.symlink(so, os.path.join(program_dir, 'libpython2.3.so.1.0'))
f = open(os.path.join(location, 'program', 'pythonloader.unorc'), 'w')
f.write('''\
[Bootstrap]
PYTHONHOME=file://%s
PYTHONPATH=%s $ORIGIN
''' % (pythonhome, pythonpath))
f.close()
def update(self):
pass | z3c.recipe.openoffice | /z3c.recipe.openoffice-0.3.tar.gz/z3c.recipe.openoffice-0.3/src/z3c/recipe/openoffice/recipe.py | recipe.py |
import os
import zc.buildout
import zc.recipe.egg
import code
import zope.app.wsgi
import zope.app.debug
class DebugSetup:
"""Paste serve setup script."""
def __init__(self, buildout, name, options):
self.app = None
self.buildout = buildout
self.name = name
self.options = options
options['script'] = os.path.join(buildout['buildout']['bin-directory'],
options.get('script', self.name),
)
if options.get('app') is None:
raise zc.buildout.UserError(
'You have to define at the app (which has the eggs and zope.conf).')
self.app = options.get('app')
options['eggs'] = '%s\nz3c.recipe.paster' % buildout[self.app]['eggs']
if not options.get('working-directory', ''):
options['location'] = buildout[self.app].get('location',
os.path.join(buildout['buildout']['parts-directory'], self.app))
self.egg = zc.recipe.egg.Egg(buildout, name, options)
def install(self):
options = self.options
location = options['location']
executable = self.buildout['buildout']['executable']
# setup path
installed = []
if not os.path.exists(location):
os.mkdir(location)
installed.append(location)
zope_conf_path = os.path.join(location, 'zope.conf')
# setup paster script
if self.egg is not None:
extra_paths = self.egg.extra_paths
else:
extra_paths = []
eggs, ws = self.egg.working_set()
installed.extend(zc.buildout.easy_install.scripts(
[(self.name, 'z3c.recipe.paster.debug', 'main')],
ws, self.options['executable'],
self.buildout['buildout']['bin-directory'],
extra_paths = extra_paths,
arguments = "%r" % zope_conf_path,
))
return installed
update = install
def main(zope_conf):
db = zope.app.wsgi.config(zope_conf)
debugger = zope.app.debug.Debugger.fromDatabase(db)
# Invoke an interactive interpreter shell
banner = ("Welcome to the interactive debug prompt.\n"
"The 'root' variable contains the ZODB root folder.\n"
"The 'app' variable contains the Debugger, 'app.publish(path)' "
"simulates a request.")
code.interact(banner=banner, local={'debugger': debugger,
'app': debugger,
'root': debugger.root()}) | z3c.recipe.paster | /z3c.recipe.paster-0.5.3.tar.gz/z3c.recipe.paster-0.5.3/src/z3c/recipe/paster/debug.py | debug.py |
=======================
z3c.recipe.paster:serve
=======================
This Zope 3 recipes offers a Paste Deploy setup for Zope3 projects. It requires
to define a Paste Deploy *.ini file in the buoldout.cfg. If you need a simple
PasteScript setup you can use the z3c.recipe.paster:paster recipe which allows
to run already existing ``*.ini`` files.
Options
-------
The 'serve' recipe accepts the following options:
eggs
The names of one or more eggs, with their dependencies that should
be included in the Python path of the generated scripts.
ini
The paste deploy ``*.ini`` file content.
zope.conf
The zope.conf file defining the DB used in the WSGI app and the error log
section.
site.zcml
The zope site.zcml file used by the zope application.
Test
----
Lets define a (bogus) eggs that we can use in our application:
>>> mkdir('demo')
>>> write('demo', 'setup.py',
... '''
... from setuptools import setup
... setup(name = 'demo')
... ''')
Now check if the setup was correct:
>>> ls('bin')
- buildout
We'll create a ``buildout.cfg`` file that defines our paster serve configuration:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo
... parts = var myapp
...
... [var]
... recipe = zc.recipe.filestorage
...
... [myapp]
... eggs = demo
... recipe = z3c.recipe.paster:serve
... ini =
... [app:main]
... use = egg:demo
...
... [server:main]
... use = egg:Paste#http
... host = 127.0.0.1
... port = 8080
...
... zope.conf =
...
... ${var:zconfig}
...
... <eventlog>
... <logfile>
... formatter zope.exceptions.log.Formatter
... path ${buildout:directory}/parts/myapp/error.log
... </logfile>
... <logfile>
... formatter zope.exceptions.log.Formatter
... path STDOUT
... </logfile>
... </eventlog>
...
... devmode on
...
... site.zcml =
... <!-- inlcude other zcml files like principals.zcml or securitypolicy.zcml
... and your app configuration -->
... <include package="demo" file="app.zcml" />
...
... ''' % globals())
Now, Let's run the buildout and see what we get:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo'
Installing var.
Installing myapp.
Generated script '/sample-buildout/bin/myapp'.
The bin folder contains the scripts for serve our new created paste deploy
server:
>>> ls('bin')
- buildout
- myapp
Check the content of our new generated myapp script. As you can see, the
generated script uses the ``paste.script.command.run`` for starting our server:
>>> cat('bin', 'myapp')
#!"C:\Python24\python.exe"
<BLANKLINE>
import sys
sys.path[0:0] = [
'/sample-buildout/demo',
'/sample-pyN.N.egg',
...
'/sample-pyN.N.egg',
]
<BLANKLINE>
import os
sys.argv[0] = os.path.abspath(sys.argv[0])
<BLANKLINE>
<BLANKLINE>
import paste.script.command
<BLANKLINE>
if __name__ == '__main__':
paste.script.command.run([
'serve', '...myapp.ini',
]+sys.argv[1:])
Those ``sample-pyN.N.egg`` lines should be PasteScript and it's dependencies.
Check the content of our new generated myapp.ini file:
>>> cat('parts', 'myapp', 'myapp.ini')
<BLANKLINE>
[app:main]
use = egg:demo
[server:main]
use = egg:Paste#http
host = 127.0.0.1
port = 8080
Entry point
-----------
As you probably know, there is some magic going on during startup. The section
``app:main`` in the myapp.ini file above must be defined as entry_point in your
projects setup.py file. Without them, the ``app:main`` isn't available. You can
define such a app:main entry point using the default ``application_factory``
offered from the ``z3c.recipe.paster.wsgi`` package. Of corse you can define
your own application factory if you need to pass some additional configuration
for your app to the factroy defined in your custom ``*.ini`` file.
The default entry_point offered from the z3c.recipe.paster could be included in
your custom setup.py file like::
setup(
name = 'something',
version = '0.5.0dev',
...
include_package_data = True,
package_dir = {'':'src'},
namespace_packages = [],
install_requires = [
'some.package',
],
entry_points = """
[paste.app_factory]
main = z3c.recipe.paster.wsgi:application_factory
""",
)
| z3c.recipe.paster | /z3c.recipe.paster-0.5.3.tar.gz/z3c.recipe.paster-0.5.3/src/z3c/recipe/paster/README.txt | README.txt |
import os
import cStringIO
import ZConfig.schemaless
import zc.buildout
import zc.recipe.egg
class ServeSetup:
"""Paste serve setup script."""
def __init__(self, buildout, name, options):
self.egg = None
self.buildout = buildout
self.name = name
self.options = options
if options.get('eggs') is None:
raise zc.buildout.UserError(
'You have to define at least one egg for setup an application.')
if 'PasteScript' not in options.get('eggs'):
# add PasteScript egg
options['eggs'] = '%s\nPasteScript' % options.get('eggs')
options['script'] = os.path.join(buildout['buildout']['bin-directory'],
options.get('script', self.name),
)
if not options.get('working-directory', ''):
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], name)
self.egg = zc.recipe.egg.Egg(buildout, name, options)
def install(self):
options = self.options
location = options['location']
executable = self.buildout['buildout']['executable']
# setup path
dest = []
if not os.path.exists(location):
os.mkdir(location)
dest.append(location)
event_log_path = os.path.join(location, 'error.log')
site_zcml_path = os.path.join(location, 'site.zcml')
# append file to dest which will remove it on update
dest.append(site_zcml_path)
# setup site.zcml
open(site_zcml_path, 'w').write(
site_zcml_template % self.options['site.zcml']
)
# setup *.ini file
ini_conf = options.get('ini', '')+'\n'
ini_path = os.path.join(location, '%s.ini' % self.name)
open(ini_path, 'w').write(str(ini_conf))
# append file to dest which will remove it on update
dest.append(ini_path)
# setup zope.conf
zope_conf = options.get('zope.conf', '')+'\n'
zope_conf = ZConfig.schemaless.loadConfigFile(
cStringIO.StringIO(zope_conf))
zope_conf['site-definition'] = [site_zcml_path]
if not [s for s in zope_conf.sections if s.type == 'zodb']:
raise zc.buildout.UserError(
'No database sections have been defined.')
if not [s for s in zope_conf.sections if s.type == 'eventlog']:
zope_conf.sections.append(event_log(event_log_path))
zope_conf_path = os.path.join(location, 'zope.conf')
open(zope_conf_path, 'w').write(str(zope_conf))
# append file to dest which will remove it on update
dest.append(zope_conf_path)
# setup paster script
if self.egg is not None:
extra_paths = self.egg.extra_paths
else:
extra_paths = []
eggs, ws = self.egg.working_set()
defaults = options.get('defaults', '').strip()
if defaults:
defaults = '(%s) + ' % defaults
initialization = initialization_template
dest.extend(zc.buildout.easy_install.scripts(
[('%s'% self.name, 'paste.script.command', 'run')],
ws, self.options['executable'],
self.buildout['buildout']['bin-directory'],
extra_paths = extra_paths,
arguments = defaults + (arg_template % dict(
INI_PATH=ini_path,
)),
initialization = initialization_template
))
return dest
update = install
# setup helper
arg_template = """[
'serve', %(INI_PATH)r,
]+sys.argv[1:]"""
site_zcml_template = """\
<configure
xmlns="http://namespaces.zope.org/zope">
%s
</configure>
"""
initialization_template = """import os
sys.argv[0] = os.path.abspath(sys.argv[0])
"""
def event_log(path, *data):
return ZConfig.schemaless.Section(
'eventlog', '', None,
[ZConfig.schemaless.Section(
'logfile',
'',
dict(path=[path])),
]) | z3c.recipe.paster | /z3c.recipe.paster-0.5.3.tar.gz/z3c.recipe.paster-0.5.3/src/z3c/recipe/paster/serve.py | serve.py |
Recipe for installing Perl packages via download
************************************************
The perlpackages recipe automates installation of Perl packages.
This recipe is similar to zc.recipe.cmmi, but instead of performing
"configure, make, make install" it uses "perl Makefile.PL" for the configure
step.
Options
-------
url
Location to download the Perl distribution from.
extra_options
Additional parameters that are passed to Makefile.PL.
perl
Name of the Perl interpreter to use for "perl Makefile.PL". Defaults
to "perl".
flatinstallprefix
Set the installation prefix, and force all library, doc and bin files to
be flattened into three install locations:
${flatinstallprefix}/lib/perl5/
${flatinstallprefix}/bin/
${flatinstallprefix}/man/
This is suitable for creating a location that you can include in your
PERL5LIB environment variable.
| z3c.recipe.perlpackage | /z3c.recipe.perlpackage-0.1.tar.gz/z3c.recipe.perlpackage-0.1/README.txt | README.txt |
import logging, os, shutil, tempfile, urllib2, urlparse
import setuptools.archive_util
import datetime
import sha
import shutil
import zc.buildout
def system(c):
if os.system(c):
raise SystemError("Failed", c)
class Recipe:
def __init__(self, buildout, name, options):
self.name, self.options = name, options
directory = buildout['buildout']['directory']
self.download_cache = buildout['buildout'].get('download-cache')
self.install_from_cache = buildout['buildout'].get('install-from-cache')
if self.download_cache:
# cache keys are hashes of url, to ensure repeatability if the
# downloads do not have a version number in the filename
# cache key is a directory which contains the downloaded file
# download details stored with each key as cache.ini
self.download_cache = os.path.join(
directory, self.download_cache, 'perlpackages')
# we assume that install_from_cache and download_cache values
# are correctly set, and that the download_cache directory has
# been created: this is done by the main zc.buildout anyway
location = options.get(
'location', buildout['buildout']['parts-directory'])
options['location'] = os.path.join(location, name)
self.perl = options.get('perl','perl')
# option to force a 'flattened' prefix
self.flatinstallprefix = options.get('flatinstallprefix', None)
if self.flatinstallprefix:
if not os.path.exists(self.flatinstallprefix):
os.mkdir(self.flatinstallprefix)
def install(self):
logger = logging.getLogger(self.name)
dest = self.options['location']
url = self.options['url']
extra_options = self.options.get('extra_options', '')
# get rid of any newlines that may be in the options so they
# do not get passed through to the commandline
extra_options = ' '.join(extra_options.split())
patch = self.options.get('patch', '')
patch_options = self.options.get('patch_options', '-p0')
fname = getFromCache(
url, self.name, self.download_cache, self.install_from_cache)
# now unpack and work as normal
tmp = tempfile.mkdtemp('buildout-'+self.name)
logger.info('Unpacking and configuring')
setuptools.archive_util.unpack_archive(fname, tmp)
here = os.getcwd()
if not os.path.exists(dest):
os.mkdir(dest)
environ = self.options.get('environment', '').split()
if environ:
for entry in environ:
logger.info('Updating environment: %s' % entry)
environ = dict([x.split('=', 1) for x in environ])
os.environ.update(environ)
try:
os.chdir(tmp)
try:
if not (os.path.exists('Makefile.PL')):
entries = os.listdir(tmp)
if len(entries) == 1:
os.chdir(entries[0])
if patch is not '':
# patch may be a filesystem path or url
# url patches can go through the cache
if urlparse.urlparse( patch, None)[0] is not None:
patch = getFromCache( patch
, self.name
, self.download_cache
, self.install_from_cache
)
system("patch %s < %s" % (patch_options, patch))
if not os.path.exists('Makefile.PL'):
entries = os.listdir(tmp)
if len(entries) == 1:
os.chdir(entries[0])
else:
raise ValueError("Couldn't find Makefile.PL")
if not self.flatinstallprefix:
system("%s ./Makefile.PL %s" % (self.perl, dest, extra_options))
else:
system("""%s ./Makefile.PL \
PREFIX=%s \
INSTALLPRIVLIB=%s/lib/perl5 \
INSTALLARCHLIB=%s/lib/perl5 \
INSTALLSCRIPT=%s/bin \
INSTALLBIN=%s/bin \
INSTALLMAN1DIR=%s/lib/perl5/man \
INSTALLMAN3DIR=%s/lib/perl5/man \
INSTALLSITELIB=%s/lib/perl5 \
INSTALLSITEARCH=%s/lib/perl5 \
INSTALLSITEBIN=%s/bin \
INSTALLSITESCRIPT=%s/bin \
INSTALLSITEMAN1DIR=%s/lib/perl5/man \
INSTALLSITEMAN3DIR=%s/lib/perl5/man \
%s""" % (
(self.perl,) + (self.flatinstallprefix,) * 13 + (extra_options,)
)
)
system("make")
system("make install")
finally:
os.chdir(here)
except:
shutil.rmtree(dest)
raise
return dest
def update(self):
pass
def getFromCache(url, name, download_cache=None, install_from_cache=False):
if download_cache:
cache_fname = sha.new(url).hexdigest()
cache_name = os.path.join(download_cache, cache_fname)
if not os.path.isdir(download_cache):
os.mkdir(download_cache)
_, _, urlpath, _, _ = urlparse.urlsplit(url)
filename = urlpath.split('/')[-1]
# get the file from the right place
fname = tmp2 = None
if download_cache:
# if we have a cache, try and use it
logging.getLogger(name).debug(
'Searching cache at %s' % download_cache)
if os.path.isdir(cache_name):
# just cache files for now
fname = os.path.join(cache_name, filename)
logging.getLogger(name).debug(
'Using cache file %s' % cache_name)
else:
logging.getLogger(name).debug(
'Did not find %s under cache key %s' % (filename, cache_name))
if not fname:
if install_from_cache:
# no file in the cache, but we are staying offline
raise zc.buildout.UserError(
"Offline mode: file from %s not found in the cache at %s" %
(url, download_cache))
try:
# okay, we've got to download now
# XXX: do we need to do something about permissions
# XXX: in case the cache is shared across users?
tmp2 = None
if download_cache:
# set up the cache and download into it
os.mkdir(cache_name)
fname = os.path.join(cache_name, filename)
if filename != "cache.ini":
now = datetime.datetime.utcnow()
cache_ini = open(os.path.join(cache_name, "cache.ini"), "w")
print >>cache_ini, "[cache]"
print >>cache_ini, "download_url =", url
print >>cache_ini, "retrieved =", now.isoformat() + "Z"
cache_ini.close()
logging.getLogger(name).debug(
'Cache download %s as %s' % (url, cache_name))
else:
# use tempfile
tmp2 = tempfile.mkdtemp('buildout-' + name)
fname = os.path.join(tmp2, filename)
logging.getLogger(name).info('Downloading %s' % url)
open(fname, 'w').write(urllib2.urlopen(url).read())
except:
if tmp2 is not None:
shutil.rmtree(tmp2)
if download_cache:
shutil.rmtree(cache_name)
raise
return fname | z3c.recipe.perlpackage | /z3c.recipe.perlpackage-0.1.tar.gz/z3c.recipe.perlpackage-0.1/z3c/recipe/perlpackage/__init__.py | __init__.py |
=================================
The ``runscript`` Buildout Recipe
=================================
Some software packages are not easily installed using established build patterns, such
as "configure, make, make install". In those cases you want to be able to use
arbitrary scripts to build a particular part. This recipe provides a simple
implementation to run a Python callable for each installing and updating a
part.
>>> import os
>>> import z3c.recipe.runscript.tests
>>> scriptFilename = os.path.join(
... os.path.dirname(z3c.recipe.runscript.tests.__file__), 'fooscripts.py')
Let's create a sample buildout to install it:
>>> write('buildout.cfg',
... """
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.runscript
... install-script = %s:installFoo
... """ %scriptFilename)
The ``install-script`` option specifies the module and the function to call
during the part installation. The function takes the local and buildout
options as arguments. See ``tests/fooscripts.py`` for details.
When running buildout, the ``installFoo()`` function is called:
>>> print system('bin/buildout')
Installing foo.
Now executing ``installFoo()``
If we run the buildout again, the update method will be called, but since we
did not specify any, nothing happens:
>>> print system('bin/buildout')
Updating foo.
Let's now specify the update script as well, causing the ``updateFoo()``
function to be called:
>>> write('buildout.cfg',
... """
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.runscript
... install-script = %s:installFoo
... update-script = %s:updateFoo
... """ %(scriptFilename, scriptFilename))
But after a change like that, parts will be uninstalled and reinstalled:
>>> print system('bin/buildout')
Uninstalling foo.
Installing foo.
Now executing ``installFoo()``
Only now we can update the part:
>>> print system('bin/buildout')
Updating foo.
Now executing ``updateFoo()``
And that's it.
| z3c.recipe.runscript | /z3c.recipe.runscript-0.1.3.tar.gz/z3c.recipe.runscript-0.1.3/src/z3c/recipe/runscript/README.txt | README.txt |
"""Install scripts from eggs.
"""
import os
import zc.buildout
import zc.buildout.easy_install
from zc.recipe.egg.egg import ScriptBase
class Base(ScriptBase):
def __init__(self, buildout, name, options):
if 'extends' in options:
for key, value in buildout[options['extends']].items():
options.setdefault(key, value)
super(Base, self).__init__(buildout, name, options)
self.default_eggs = '' # Disables feature from zc.recipe.egg.
b_options = buildout['buildout']
options['parts-directory'] = os.path.join(
b_options['parts-directory'], self.name)
value = options.setdefault(
'allowed-eggs-from-site-packages',
b_options.get('allowed-eggs-from-site-packages', '*'))
self.allowed_eggs = tuple(name.strip() for name in value.split('\n'))
self.include_site_packages = options.query_bool(
'include-site-packages',
default=b_options.get('include-site-packages', 'false'))
self.exec_sitecustomize = options.query_bool(
'exec-sitecustomize',
default=b_options.get('exec-sitecustomize', 'false'))
class Interpreter(Base):
def __init__(self, buildout, name, options):
super(Interpreter, self).__init__(buildout, name, options)
options.setdefault('name', name)
def install(self):
reqs, ws = self.working_set()
options = self.options
generated = []
if not os.path.exists(options['parts-directory']):
os.mkdir(options['parts-directory'])
generated.append(options['parts-directory'])
generated.extend(zc.buildout.easy_install.sitepackage_safe_scripts(
options['bin-directory'], ws, options['executable'],
options['parts-directory'],
interpreter=options['name'],
extra_paths=self.extra_paths,
initialization=options.get('initialization', ''),
include_site_packages=self.include_site_packages,
exec_sitecustomize=self.exec_sitecustomize,
relative_paths=self._relative_paths,
))
return generated
update = install
class Scripts(Base):
def _install(self, reqs, ws, scripts):
options = self.options
generated = []
if not os.path.exists(options['parts-directory']):
os.mkdir(options['parts-directory'])
generated.append(options['parts-directory'])
generated.extend(zc.buildout.easy_install.sitepackage_safe_scripts(
options['bin-directory'], ws, options['executable'],
options['parts-directory'], reqs=reqs, scripts=scripts,
interpreter=options.get('interpreter'),
extra_paths=self.extra_paths,
initialization=options.get('initialization', ''),
include_site_packages=self.include_site_packages,
exec_sitecustomize=self.exec_sitecustomize,
relative_paths=self._relative_paths,
script_arguments=options.get('arguments', ''),
script_initialization=options.get('script-initialization', '')
))
return generated | z3c.recipe.scripts | /z3c.recipe.scripts-1.0.1.tar.gz/z3c.recipe.scripts-1.0.1/src/z3c/recipe/scripts/scripts.py | scripts.py |
=========
CHANGES
=========
1.1.0 (2017-07-05)
==================
- Add support for Python 3.4, 3.5 and 3.6 and PyPy.
- Remove support for Python 2.6 and 3.3.
- Change the default source suffix from ``.txt`` to ``.rst``. You can
override this using the new ``extra-conf`` setting.
- Add the ability to specify arbitrary configuration in the
``extra-conf`` setting. This is useful for things like configuring
extensions, overriding the defaults set by this recipe, and
configuring a sphinx theme.
- Stop forcing a value of ``default.css`` for ``html_style`` even when
the ``default.css`` setting is configured to an empty value. This
makes it possible to use ``html_theme`` to set a sphinx theme, and
it properly lets the default Sphinx theme be used (by setting both
``default.css`` and ``layout.html`` to empty values).
- Ignore bad eggs in the documentation working set. Previously they
would raise internal errors without any explanation. Now, they log a
warning pinpointing the bad egg. Fixes `issue 6
<https://github.com/zopefoundation/z3c.recipe.sphinxdoc/issues/6>`_.
1.0.0 (2013-02-23)
==================
- Added Python 3.3 support.
- Bug: fix layout directory if layout is overriden by user
0.0.8 (2009-05-01)
==================
- Feature: Added new option `doc-eggs` which specifies the list of eggs for
which to create documentation explicitely.
- Feature: Changed building behavior so that the documentation for each
package is built in its own sub-directory.
- Feature: Added new option `extensions` which takes a whitespace
separated list of sphinx extension modules. This extensions can be
used to build the documentation.
0.0.7 (2009-02-15)
==================
- Bug: fix python 2.4 support
- Bug: fix broken srcDir path generation for windows
0.0.6 (2009-01-19)
==================
- Feature: Allow you to specify a url or local file path to your own
default.css and layout.html files.
0.0.5 (2008-05-11)
==================
- Initial release.
| z3c.recipe.sphinxdoc | /z3c.recipe.sphinxdoc-1.1.0.tar.gz/z3c.recipe.sphinxdoc-1.1.0/CHANGES.rst | CHANGES.rst |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--setuptools-version",
help="use a specific setuptools version")
options, args = parser.parse_args()
######################################################################
# load/install setuptools
try:
if options.allow_site_packages:
import setuptools
import pkg_resources
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
sys.path[:] = [x for x in sys.path if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.recipe.sphinxdoc | /z3c.recipe.sphinxdoc-1.1.0.tar.gz/z3c.recipe.sphinxdoc-1.1.0/bootstrap.py | bootstrap.py |
======================
z3c.recipe.sphinxdoc
======================
Introduction
============
This buildout recipe aids in the generation of documentation for the
zope.org website from restructured text files located in a package.
It uses Sphinx to build static html files which can stand alone as a
very nice looking website.
Usage Instructions
==================
Suppose you have a package called ``z3c.form``. In the ``setup.py``
for ``z3c.form`` it is recommended that you add a ``docs`` section
to the extras_require argument. It should look something like this::
extras_require = dict(
docs = ['Sphinx',
'z3c.recipe.sphinxdoc']
)
Then in the buildout.cfg file for your package, add a ``docs`` section
that looks like this::
[docs]
recipe = z3c.recipe.sphinxdoc
eggs = z3c.form [docs]
Be sure to include it in the parts, as in::
[buildout]
develop = .
parts = docs
Now you can rerun buildout. The recipe will have created an
executable script in the bin directory called ``docs``.
This script will run the Sphinx documentation generation tool on your
source code. By default, it expects there to be an ``index.rst`` file
in the source code. In this case, ``index.rst`` would have to be in
``src/z3c/form/index.rst``. This file can be a standard restructured
text file, and can use all the sphinx goodies. For example, your
``index.txt`` might look like this::
Welcome to z3c.form's documentation!
====================================
Contents:
.. toctree::
:maxdepth: 2
README
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
You should read the documentation for Sphinx to learn more about it.
It is available here: http://sphinx.pocoo.org/
Now you should be able to run the ``docs`` script::
$ ./bin/docs
This generates all the documentation for you and placed it in the
parts directory. You can then open it up in firefox and take a look::
$ firefox parts/docs/z3c.form/build/index.html
Additional Options
==================
By default, this recipe generates documentation that looks like the
new zope website ( http://new.zope.org ) by overriding the default
layout template and css file used by sphinx. You can modify this
behavior with options in your buildout configuration.
Give me back Sphinx's default look!
-----------------------------------
To get back the default look of sphinx, you could use a configuration
like this::
[docs]
recipe = z3c.recipe.sphinxdoc
eggs = z3c.form [docs]
default.css =
layout.html =
I want my own custom look
-------------------------
You can also specify your own layout template and css like so::
[docs]
recipe = z3c.recipe.sphinxdoc
eggs = z3c.form [docs]
default.css = http://my.own.website.com/mystyles/some-theme.css
layout.html = /path/to/layout.html
Note that you can either specify a path on the local file system or a
url to an external css file.
Use sphinx extension modules
----------------------------
Sphinx provides a set of extensions, for example ``sphinx.ext.autodoc``
or ``sphinx.ext.doctest``. To use such an extension change your
configuration like::
[docs]
recipe = z3c.recipe.sphinxdoc
eggs = z3c.form [docs]
extensions = sphinx.ext.autodoc sphinx.ext.doctest
Arbitrary Configuration
-----------------------
Sphinx and its extensions offer many configuration options. You can
specify any of those by using the ``extra-conf`` option. This option
takes a sequence of lines that are simply inserted into the generated
``conf.py``. Anything you specify here will override other settings
this recipe established (just watch your leading line indentation)::
[docs]
recipe = z3c.recipe.sphinxdoc
eggs = z3c.form [docs]
extensions = sphinx.ext.autodoc
sphinx.ext.todo
sphinx.ext.viewcode
sphinx.ext.intersphinx
repoze.sphinx.autointerface
sphinxcontrib.programoutput
default.css =
layout.html =
extra-conf =
autodoc_default_flags = ['members', 'show-inheritance',]
autoclass_content = 'both'
intersphinx_mapping = {
'python': ('http://docs.python.org/2.7/', None),
'boto': ('http://boto.readthedocs.org/en/latest/', None),
'gunicorn': ('http://docs.gunicorn.org/en/latest/', None),
'pyquery': ('http://packages.python.org/pyquery/', None) }
intersphinx_cache_limit = -1
todo_include_todos = True
# The suffix of source filenames. Override back to txt.
source_suffix = '.txt'
# Choose an entire theme. Note that we disabled layout.html
# and default.css.
html_theme = 'classic'
| z3c.recipe.sphinxdoc | /z3c.recipe.sphinxdoc-1.1.0.tar.gz/z3c.recipe.sphinxdoc-1.1.0/src/z3c/recipe/sphinxdoc/index.rst | index.rst |
from __future__ import print_function
import sys
import os
from os.path import join, dirname, isdir, normpath
from email import message_from_string
import shutil
import zc.recipe.egg
import zc.buildout.easy_install
import pkg_resources
try:
from urllib2 import urlopen
except ImportError:
# Py3 location changed.
from urllib.request import urlopen
logger = __import__('logging').getLogger(__name__)
confPyTemplate = """
templates_path = ['%(templatesDir)s']
source_suffix = '.rst'
master_doc = '%(indexDoc)s'
project = '%(project)s'
copyright = '%(copyright)s'
version = '%(version)s'
release = '%(release)s'
today_fmt = '%%B %%d, %%Y'
pygments_style = 'sphinx'
%(html_style)s
html_static_path = ['%(staticDir)s']
html_last_updated_fmt = '%%b %%d, %%Y'
extensions = %(extensions)r
%(extra_conf)s
"""
class ZopeOrgSetup(object):
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
options['script'] = join(buildout['buildout']['bin-directory'],
options.get('script', self.name))
self.egg = zc.recipe.egg.Egg(self.buildout, self.name, self.options)
self._projectsData = {}
def openfile(self, fn):
try:
return open(fn)
except IOError:
return urlopen(fn)
def _copy_static_file(self, installed, partDir, dirName, fileName):
destDir = join(partDir, dirName)
if not isdir(destDir):
os.mkdir(destDir)
installed.append(destDir)
usingFile = False
if fileName not in self.options:
recipeDir = dirname(__file__)
shutil.copy(join(recipeDir, fileName),
join(destDir, fileName))
installed.append(join(destDir, fileName))
usingFile = True
elif self.options[fileName]:
with self.openfile(self.options[fileName]) as f:
with open(join(destDir, fileName), 'w') as w:
w.write(f.read())
installed.append(join(destDir, fileName))
usingFile = True
return destDir, usingFile
def install(self):
installed = []
eggs, workingSet = self.egg.working_set()
if 'doc-eggs' in self.options:
eggs = self.options['doc-eggs'].split()
docs = [(workingSet.find(pkg_resources.Requirement.parse(spec)), spec)
for spec in eggs]
# Create parts directory for configuration files.
installDir = join(
self.buildout['buildout']['parts-directory'], self.name)
if not isdir(installDir):
os.mkdir(installDir)
srcDirs = eval(self.options.get('src-dirs','{}'))
projectsData = {}
# Preserve projectsData for testing
self._projectsData = projectsData
# for each egg listed as a buildout option, create a configuration space.
for doc, egg_name in docs:
if not doc:
logger.warning("Specified egg '%s' cannot be resolved, ignoring.", egg_name)
continue
partDir = join(installDir, doc.project_name)
if not isdir(partDir):
os.mkdir(partDir)
installed.append(partDir)
# create static directory
staticDir, usingDefaultCss = self._copy_static_file(
installed, partDir,
'.static', 'default.css')
# create templates directory
templatesDir, _ = self._copy_static_file(
installed, partDir,
'.templates', 'layout.html')
metadata = dict(message_from_string('\n'.join(
doc._get_metadata('PKG-INFO'))).items())
# create conf.py
confPyPath = join(partDir, 'conf.py')
with open(confPyPath, 'w') as confPy:
confPy.write(confPyTemplate % dict(
project=metadata.get('Name', doc.project_name),
copyright=metadata.get('Author', 'Zope Community'),
version=metadata.get('Version', doc.version),
release=metadata.get('Version', doc.version),
staticDir=staticDir,
templatesDir=templatesDir,
html_style=("html_style = 'default.css'"
if usingDefaultCss
else ''),
indexDoc=self.options.get('index-doc','index'),
extensions=self.options.get('extensions','').split(),
extra_conf=self.options.get('extra-conf', ''),
)
)
installed.append(confPyPath)
buildDir = self.options.get('build-dir',
join(partDir, 'build'))
if not isdir(buildDir):
os.mkdir(buildDir)
buildDir = os.path.join(buildDir, doc.project_name)
if not isdir(buildDir):
os.mkdir(buildDir)
srcDir = join(doc.location, srcDirs.get(doc.project_name,
self.options.get('src-dir', doc.project_name.replace('.','/'))))
# fix bad path on windows (e.g. //foo\bar)
srcDir = normpath(srcDir)
projectsData[doc.project_name] = ['-q','-c', partDir,
srcDir, buildDir]
installed.extend(zc.buildout.easy_install.scripts(
[(self.options['script'],
'z3c.recipe.sphinxdoc',
'main'),
],
workingSet,
self.options['executable'],
self.buildout['buildout']['bin-directory'],
extra_paths=self.egg.extra_paths,
arguments = "%r" % projectsData,
))
return installed
update = install
def main(projects, argv=None, exit_on_error=False):
import sphinx
argv = argv or sys.argv
for project, args in projects.items():
print("building docs for", project, "---> sphinx-build", " ".join(args))
code = sphinx.build_main(argv=argv+args)
if exit_on_error and code:
sys.exit(code) # pragma: no cover | z3c.recipe.sphinxdoc | /z3c.recipe.sphinxdoc-1.1.0.tar.gz/z3c.recipe.sphinxdoc-1.1.0/src/z3c/recipe/sphinxdoc/__init__.py | __init__.py |
Supported options
=================
The recipe supports the following options:
**egg**
Set to the desired lxml egg, e.g. ``lxml`` or ``lxml==2.1.2``
**libxslt-url, libxml2-url**
The URL to download the source tarball of these libraries from.
If unset, the [versions] section of the buildout is searched,
if nothing is found there, either, these default values are used::
http://dist.repoze.org/lemonade/dev/cmmi/libxslt-1.1.24.tar.gz
http://dist.repoze.org/lemonade/dev/cmmi/libxml2-2.6.32.tar.gz
**build-libxslt, build-libxml2**
Set to ``true`` (default) if these should be build, ``false`` otherwise.
Needes to be ``true`` for a static build.
**libxslt-patch, libxml2-patch**
The name of an optional patch file to apply to the libraries
**static-build**
``true`` or ``false``. On OS X this defaults to ``true``.
**xml2-location**
Needed if ``libxml2`` is not built.
**xslt-location**
Needed if ``libxslt`` is not built.
**xslt-config**
Path to the ``xslt-config`` binary. Not needed if ``build-libxslt`` is
set to true.
**xml2-config**
Path to the ``xml2-config`` binary. Not needed if ``build-libxml2`` is
set to true.
**force**
Set to ``true`` to force rebuilding libraries every time.
Example usage
=============
This is an example buildout::
[buildout]
parts =
lxml
pylxml
develop = .
log-level = DEBUG
download-directory = downloads
download-cache = downloads
versions=versions
[versions]
lxml = 2.1.3
[pylxml]
recipe=zc.recipe.egg
interpreter=pylxml
eggs=
lxml
[lxml]
recipe = z3c.recipe.staticlxml
egg = lxml
This will build a ``static`` version of the ``lxml`` egg, that is, it won't have
any dependencies on ``libxml2`` and ``libxslt``.
The egg is installed in your buildout's egg directory (it is *not* installed
as a development egg). If you have a global ``eggs-directory`` configured in
your ``~/.buildout/default.cfg``, the static lxml egg is thus placed in that
global egg directory.
If you specified a specific version for the lxml egg, the egg directory is
checked for an existing lxml egg. If found, it is used as-is. Specifying
``force = true`` of course means that this check isn't performed.
Sanity check
============
This is not a complete exercise of all the ways the recipe can be configured,
rather it's a sanity check that all parts (especially, recipes we depend on)
work as expected:
>>> write('buildout.cfg',
... """
... [buildout]
... parts = lxml
... newest = false
...
... [lxml]
... recipe = z3c.recipe.staticlxml
... libxml2-url = file://%s/foo.tgz
... libxslt-url = file://%s/foo.tgz
... xml2-config = none
... xslt-config = none
... egg = lxml
... static-build = false
... """ % (distros, distros))
>>> print system('bin/buildout')
Installing lxml.
lxml: CMMI libxml2 ...
lxml: Using libxml2 download url /distros/foo.tgz...
libxml2: Unpacking and configuring
configuring foo...
echo building foo
building foo
echo installing foo
installing foo
lxml: CMMI libxslt ...
lxml: Using libxslt download url /distros/foo.tgz...
libxslt: Unpacking and configuring
configuring foo...
echo building foo
building foo
echo installing foo
installing foo...
lxml: Building lxml ...
| z3c.recipe.staticlxml | /z3c.recipe.staticlxml-0.10.tar.gz/z3c.recipe.staticlxml-0.10/src/z3c/recipe/staticlxml/README.txt | README.txt |
"""Recipe staticlxml"""
import os
import re
import sys
import logging
import tempfile
import platform
import subprocess
import pkg_resources
from fnmatch import fnmatch
from distutils import sysconfig
from zc.buildout import UserError
from zc.recipe.egg.custom import Custom
import zc.recipe.cmmi
# http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-3919
# http://people.canonical.com/~ubuntu-security/cve/2011/CVE-2011-3919.html
# http://git.gnome.org/browse/libxml2/commit/?id=5bd3c061823a8499b27422aee04ea20aae24f03e
patch_cve_2011_3919 = """diff --git a/parser.c b/parser.c
index 4e5dcb9..c55e41d 100644
--- a/parser.c
+++ b/parser.c
@@ -2709,7 +2709,7 @@ xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
buffer[nbchars++] = '&';
if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) {
- growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
+ growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE);
}
for (;i > 0;i--)
buffer[nbchars++] = *cur++;
"""
def which(fname, path=None):
"""Return first matching binary in path or os.environ["PATH"]
"""
if path is None:
path = os.environ.get("PATH")
fullpath = filter(os.path.isdir, path.split(os.pathsep))
if '.' not in fullpath:
fullpath = ['.'] + fullpath
fn = fname
for p in fullpath:
for f in os.listdir(p):
head, ext = os.path.splitext(f)
if f == fn or fnmatch(head, fn):
return os.path.join(p, f)
return None
class Recipe(object):
"""zc.buildout recipe"""
def __init__(self, buildout, name, options):
self.buildout, self.name, self.options = buildout, name, options
self.logger = logging.getLogger(name)
# force build option
force = options.get("force")
self.force = force in ("true", "True")
options["force"] = force and "true" or "false"
# XLST build or location option
build_xslt = options.get("build-libxslt", "true")
self.build_xslt = build_xslt in ("true", "True")
options["build-libxslt"] = build_xslt and "true" or "false"
if not self.build_xslt:
self.xslt_location = options.get("xslt-location")
if not self.xslt_location:
raise UserError("You must either configure ``xslt-location`` or set"
" ``build-libxslt`` to ``true``")
# XML2 build or location option
build_xml2 = options.get("build-libxml2", "true")
self.build_xml2 = build_xml2 in ("true", "True")
options["build-libxml2"] = build_xml2 and "true" or "false"
if not self.build_xml2:
self.xml2_location = options.get("xml2-location")
if not self.xml2_location:
raise UserError("You must either configure ``xml2-location`` or set"
" ``build-libxml2`` to ``true``")
# static build option
static_build = options.get("static-build", "darwin" in sys.platform and "true" or None)
self.static_build = static_build in ("true", "True")
if self.static_build and not (self.build_xml2 and self.build_xslt):
raise UserError("Static build is only possible if both "
"``build-libxml2`` and ``build-libxslt`` are ``true``.")
if self.static_build:
self.logger.info("Static build requested.")
options["static-build"] = self.static_build and "true" or "false"
# our location
location = options.get(
'location', buildout['buildout']['parts-directory'])
options['location'] = os.path.join(location, name)
def build_libxslt(self):
self.logger.info("CMMI libxslt ...")
versions = self.buildout.get(self.buildout['buildout'].get('versions', '__invalid__'), {})
self.options["libxslt-url"] = self.xslt_url = self.options.get(
"libxslt-url",
versions.get("libxslt-url", "http://xmlsoft.org/sources/libxslt-1.1.26.tar.gz"))
self.options["libxslt-patch"] = self.xslt_patch = self.options.get("libxslt-patch", "")
self.options["libxslt-patch_options"] = \
self.xslt_patch_options = self.options.get("libxslt-patch_options", "-p0")
self.logger.info("Using libxslt download url %s" % self.xslt_url)
if self.xslt_patch != "":
self.logger.info(
"Patching libxslt with %s using %s", self.xslt_patch, self.xslt_patch_options)
options = self.options.copy()
options["url"] = self.xslt_url
options["patch"] = self.xslt_patch
options["patch_options"] = self.xslt_patch_options
options["extra_options"] = "--with-libxml-prefix=%s --without-python --without-crypto" % self.xml2_location
# ^^^ crypto is off as libgcrypt can lead to problems on especially osx and also on some linux machines.
if platform.machine() in ('x86_64', 'amd64'):
options["extra_options"] += ' --with-pic'
self.xslt_cmmi = zc.recipe.cmmi.Recipe(self.buildout, "libxslt", options)
if os.path.exists(os.path.join(self.xslt_cmmi.options["location"], "bin", "xslt-config")):
self.logger.info("Skipping build of libxslt: already there")
loc = self.xslt_cmmi.options.get("location")
else:
loc = self.xslt_cmmi.install()
self.options["xslt-location"] = self.xslt_location = loc
def make_cve_2011_3919_patch(self):
"""make_cve_2011_3919_patch() -> path to patch file
Write patch file, return path.
"""
fd, path = tempfile.mkstemp(suffix=".patch")
f = os.fdopen(fd, "w")
f.write(patch_cve_2011_3919)
f.close()
return path
def build_libxml2(self):
self.logger.info("CMMI libxml2 ...")
versions = self.buildout.get(self.buildout['buildout'].get('versions', '__invalid__'), {})
self.options["libxml2-url"] = self.xml2_url = self.options.get(
"libxml2-url",
versions.get("libxml2-url", "http://xmlsoft.org/sources/libxml2-2.7.8.tar.gz"))
self.options["libxml2-patch"] = self.xml2_patch = self.options.get("libxml2-patch", "")
self.options["libxml2-patch_options"] = \
self.xml2_patch_options = self.options.get("libxml2-patch_options", "-p0")
self.logger.info("Using libxml2 download url %s" % self.xml2_url)
if self.xml2_patch != "":
self.logger.info(
"Patching libxml2 with %s using %s", self.xml2_patch, self.xml2_patch_options)
options = self.options.copy()
options["url"] = self.xml2_url
options["patch"] = self.make_cve_2011_3919_patch()
options["patch_options"] = "-p1"
options["extra_options"] = "--without-python"
options["patch"] = self.xml2_patch
options["patch_options"] = self.xml2_patch_options
if platform.machine() in ('x86_64', 'amd64'):
options["extra_options"] += ' --with-pic'
self.xml2_cmmi = zc.recipe.cmmi.Recipe(self.buildout, "libxml2", options)
if not self.force and os.path.exists(os.path.join(self.xml2_cmmi.options["location"], "bin", "xml2-config")):
self.logger.info("Skipping build of libxml2: already there")
loc = self.xml2_cmmi.options["location"]
else:
loc = self.xml2_cmmi.install()
self.options["xml2-location"] = self.xml2_location = loc
def update(self):
pass
def install(self):
options = self.options
install_location = self.buildout['buildout']['eggs-directory']
if not os.path.exists(options['location']):
os.mkdir(options['location'])
# Only do expensive download/compilation when there's no existing egg.
path = [install_location]
req_string = self.options['egg'] # 'lxml' or 'lxml == 2.0.9'
version_part = self.buildout['buildout'].get('versions')
if version_part:
version_req = self.buildout[version_part].get('lxml')
if version_req:
# [versions] wins and is often the place where it is specified.
req_string = 'lxml == %s' % version_req
req = pkg_resources.Requirement.parse(req_string)
matching_dists = [d for d in pkg_resources.Environment(path)['lxml']
if d in req]
if matching_dists and not self.force:
# We have found existing lxml eggs that match our requirements.
# If we specified an exact version, we'll trust that the matched
# egg is good. We don't currently accept matches for not-pinned
# versions as that would mean lots of code duplication with
# easy_install (handling newest=t/f and so).
specs = req.specs
if len(specs) == 1 and specs[0][0] == '==':
self.logger.info("Using existing %s. Delete it if that one "
"isn't statically compiled.",
matching_dists[0].location)
return ()
# build dependent libs if requested
if self.build_xml2:
self.build_libxml2()
else:
self.logger.warn("Using configured libxml2 at %s" % self.xml2_location)
if self.build_xslt:
self.build_libxslt()
else:
self.logger.warn("Using configured libxslt at %s" % self.xslt_location)
# get the config executables
self.get_configs(os.path.join(self.xml2_location, "bin"), os.path.join(self.xslt_location, "bin"))
if self.static_build:
self.remove_dynamic_libs(self.xslt_location)
self.remove_dynamic_libs(self.xml2_location)
# build LXML
dest = options.get("location")
if not os.path.exists(dest):
os.mkdir(dest)
options["include-dirs"] = '\n'.join([
os.path.join(self.xml2_location, "include", "libxml2"),
os.path.join(self.xslt_location, "include")])
options["library-dirs"] = '\n'.join([
os.path.join(self.xml2_location, "lib"),
os.path.join(self.xslt_location, "lib")])
options["rpath"] = '\n'.join([
os.path.join(self.xml2_location, "lib"),
os.path.join(self.xslt_location, "lib")])
if "darwin" in sys.platform:
self.logger.warn("Adding ``iconv`` to libs due to a lxml setup bug.")
options["libraries"] = "iconv"
self.lxml_custom = Custom(self.buildout, self.name, self.options)
self.lxml_custom.environment = self.lxml_build_env()
self.lxml_custom.options["_d"] = install_location
self.logger.info("Building lxml ...")
self.lxml_dest = self.lxml_custom.install()
return ()
def get_ldshared(self):
LDSHARED = sysconfig.get_config_vars().get("LDSHARED")
self.logger.debug("LDSHARED=%s" % LDSHARED)
if "darwin" in sys.platform:
self.logger.warn("OS X detected.")
# remove macports "-L/opt/local/lib"
if "-L/opt/local/lib" in LDSHARED:
self.logger.warn("*** Removing '-L/opt/local/lib' from 'LDSHARED'")
LDSHARED = LDSHARED.replace("-L/opt/local/lib", "")
if self.static_build:
self.logger.info("Static build -- adding '-Wl,-search_paths_first'")
LDSHARED = LDSHARED + " -Wl,-search_paths_first "
self.logger.debug("LDSHARED'=%s" % LDSHARED)
return LDSHARED
def remove_dynamic_libs(self, path):
self.logger.info("Removing dynamic libs from path %s ..." % path)
soext = "so"
if "darwin" in sys.platform:
soext = "dylib"
paths = (os.path.join(path, "lib"),
os.path.join(path, "lib64"))
for path in paths:
if not os.path.exists(path):
continue
for fname in os.listdir(path):
if fname.endswith(soext):
os.unlink(os.path.join(path, fname))
self.logger.debug("removing %s" % fname)
def get_configs(self, xml2_location=None, xslt_location=None):
"""Get the executables for libxml2 and libxslt configuration
If not configured, then try to get them from a built location.
If the location is not given, then search os.environ["PATH"] and
warn the user about that.
"""
self.xslt_config = self.options.get("xslt-config")
if not self.xslt_config:
self.xslt_config = which("xslt-config", xslt_location)
if not self.xslt_config:
raise UserError("No ``xslt-config`` binary configured and none found in path.")
self.logger.warn("Using xslt-config found in %s." % self.xslt_config)
self.xml2_config = self.options.get("xml2-config")
if not self.xml2_config:
self.xml2_config = which("xml2-config", xml2_location)
if not self.xml2_config:
raise UserError("No ``xml2-config`` binary configured and none found in path.")
self.logger.warn("Using xml2-config found in %s." % self.xml2_config)
self.logger.debug("xslt-config: %s" % self.xslt_config)
self.logger.debug("xml2-config: %s" % self.xml2_config)
update = install
def lxml_build_env(self):
env = dict(
XSLT_CONFIG=self.xslt_config,
XML_CONFIG=self.xml2_config,
LDSHARED=self.get_ldshared(),
)
# see if ld accepts --no-as-needed flag
po = subprocess.Popen("ld --no-as-needed",
shell=True,
universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = po.communicate()
if "unknown option" not in stdout.lower():
self.logger.info("Adding LDFLAGS to prevent underlinking of librt")
env['LDFLAGS'] = "-Wl,--no-as-needed,-lrt"
return env
# vim: set ft=python ts=4 sw=4 expandtab : | z3c.recipe.staticlxml | /z3c.recipe.staticlxml-0.10.tar.gz/z3c.recipe.staticlxml-0.10/src/z3c/recipe/staticlxml/__init__.py | __init__.py |
=======
CHANGES
=======
1.0 (2023-02-09)
----------------
- Drop support for Python < 3.7.
- Add support for Python 3.7 up to 3.11.
- Require ``zc.buildout >= 3``.
0.8 (2014-10-20)
----------------
- Add --tag-relative option to support relative tag generation.
0.7 (2013-03-22)
----------------
- Support and require zc.buildout 2.0.
- Add supported Python version (3.6, 2.7, 3.2, 3.3) classifiers to
setup.py
0.6 (2012-09-07)
----------------
- Update manifest to allow package generation fron non-VCS export. Counters the
0.5 "brown bag" release.
0.5 (2012-09-06)
----------------
- Exclude Python import statements by default from showing up as tags.
- Add 'defaults' option to allow adding default command line options (e.g. to
set '-v' by default)
0.4.1 (2012-01-11)
------------------
* Skip nonexistent sys.path directories to avoid ctags warnings.
0.4.0 (2010-08-29)
------------------
* Support new script features from zc.buildout 1.5 and higher. This version
requires zc.buildout 1.5 or higher.
* Also index Mako and HTML files with id-utils.
0.3.0 (2009-08-16)
------------------
* Add support for using this recipe as a `paver <http://www.blueskyonmars.com/projects/paver/>`_ task.
* Also index Javascript, CSS and ReStructuredText files with id-utils.
* Define a default entry point for zc.buildout, so you can simply say::
[ctags]
recipe = z3c.recipe.tag
0.2.0 (2008-08-28)
------------------
* Allow command-line choices for what files to build, and what languages ctags
should parse. (Note that the default behavior of running ``./bin/tags``
is the same as previous releases.)
* Support the Mac OS X packaging system "macports" (exuberant ctags is
``ctags-exuberant`` in Ubuntu and ``ctags`` in macports).
* Support creating BBEdit-style ctags files.
* Small changes for development (use bootstrap external, set svn:ignore)
0.1.0 (2008-03-16)
------------------
- Initial release.
* buildout recipe for generating ctags of eggs used.
| z3c.recipe.tag | /z3c.recipe.tag-1.0.tar.gz/z3c.recipe.tag-1.0/CHANGES.rst | CHANGES.rst |
==============
z3c.recipe.tag
==============
|buildstatus|_
.. contents::
Introduction
------------
This recipe generates a TAGS database file that can be used with a
number of different editors to quickly look up class and function
definitions in your package's source files and egg dependencies.
Dependencies
------------
Before running a tags enabled buildout, you must install the
appropriate command line tag generation tools: exuberant-ctags and
id-utils. In Ubuntu, you can install these with apt-get::
$ sudo apt-get install exuberant-ctags id-utils
On a Mac, download and install ``port`` from http://www.macports.org/ and then
install ctags and idutils in this way::
$ sudo port install ctags idutils
How to use this recipe
----------------------
With Buildout
.............
Suppose you have an egg called ``MyApplication``. To use this recipe with
buildout, you would add the following to the ``buildout.cfg`` file::
[tags]
recipe = z3c.recipe.tag
eggs = MyApplication
This produces a script file in the ``bin/`` directory which you can
then run like this::
$ ./bin/tags
By default, this script produces three files in the directory from
which you ran the script:
- a ctags file called ``TAGS`` for use by emacs,
- a ctags file called ``tags`` for use by vi, and
- an idutils file called ``ID`` for use by id-utils (gid, lid).
You can then use these files in your editor of choice.
Optionally, you can select which files to build. The following is the output
of ``./bin/tags --help``::
usage: build_tags [options]
options:
-h, --help show this help message and exit
-l LANGUAGES, --languages=LANGUAGES
ctags comma-separated list of languages. defaults to
``-JavaScript``
-e, --ctags-emacs flag to build emacs ctags ``TAGS`` file
-v, --ctags-vi flag to build vi ctags ``tags`` file
-b, --ctags-bbedit flag to build bbedit ctags ``tags`` file
-i, --idutils flag to build idutils ``ID`` file
If you'd like to set command line options by default (e.g. to limit
building to ctags-vi by default) you can pass the ``default`` option in
your buildout.cfg::
[tags]
recipe = z3c.recipe.tag
eggs = MyApplication
default = ['-v']
With virtualenv
...............
You can use this with `virtualenv
<https://pypi.python.org/pypi/virtualenv>`__ too::
my_venv/bin/pip install z3c.recipe.tag
my_venv/bin/build_tags
this will build a tags file for all the packages installed in that virtualenv.
With Paver
..........
If you are using `Paver
<http://www.blueskyonmars.com/projects/paver/>`_ and already have
z3c.recipe.tag installed, then all you have to do is add this line to
your ``pavement.py`` file::
import z3c.recipe.tag
And then run the ``z3c.recipe.tag.tags`` task from the command line::
$ paver z3c.recipe.tag.tags
Additional Resources
--------------------
For additional information on using tags tables with different editors
see the following websites:
- **Emacs**: http://www.gnu.org/software/emacs/manual/html_node/emacs/Tags.html
- to jump to the location of a tag, type ``M-x find-tag`` and the
name of the tag. Or use ``M-.`` to jump to the tag matching the token
the cursor is currently on. The first time you do this, you will
be prompted for the location of the TAGS file.
- **VIM**: http://vimdoc.sourceforge.net/htmldoc/tagsrch.html
- **BBEdit**: http://pine.barebones.com/manual/BBEdit_9_User_Manual.pdf
Chapter 14, page 324
For more information on ctags, visit http://ctags.sourceforge.net/
(BBEdit_ is a Macintosh text editor.)
.. _BBEdit: http://barebones.com/products/bbedit/
For more information about GNU id-utils (basically a local text
indexing/search engine; think of it as a very fast version of ``grep
-w``), see the `id-utils manual
<http://www.gnu.org/software/idutils/manual/idutils.html>`__.
.. |buildstatus| image:: https://github.com/zopefoundation/z3c.recipe.tag/workflows/tests/badge.svg
.. _buildstatus: https://github.com/zopefoundation/z3c.recipe.tag/actions?query=workflow%3Atests
| z3c.recipe.tag | /z3c.recipe.tag-1.0.tar.gz/z3c.recipe.tag-1.0/README.rst | README.rst |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.recipe.tag | /z3c.recipe.tag-1.0.tar.gz/z3c.recipe.tag-1.0/LICENSE.rst | LICENSE.rst |
import optparse
import os
import subprocess
import sys
import pkg_resources
import zc.buildout.easy_install
import zc.recipe.egg
class TagsMaker:
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
# We do this early so the "extends" functionality works before we get
# to the other options below.
self._delegated = zc.recipe.egg.Egg(buildout, name, options)
options['script'] = os.path.join(buildout['buildout']['bin-directory'],
options.get('script', self.name),
)
if not options.get('working-directory', ''):
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], name)
def install(self):
options = self.options
generated = []
eggs, ws = self._delegated.working_set(('z3c.recipe.tag',))
wd = options.get('working-directory', '')
if not wd:
wd = options['location']
if os.path.exists(wd):
assert os.path.isdir(wd)
else:
os.mkdir(wd)
generated.append(wd)
initialization = initialization_template % (
self.buildout['buildout']['directory'])
env_section = options.get('environment', '').strip()
if env_section:
env = self.buildout[env_section]
for key, value in env.items():
initialization += env_template % (key, value)
initialization_section = options.get('initialization', '').strip()
if initialization_section:
initialization += initialization_section
arguments = options.get('defaults', '')
if arguments:
arguments = arguments + ' + sys.argv[1:]'
generated.extend(zc.buildout.easy_install.scripts(
[(options['script'], 'z3c.recipe.tag', 'build_tags')],
ws, options['executable'],
self.buildout['buildout']['bin-directory'],
extra_paths=self._delegated.extra_paths,
initialization=initialization,
))
return generated
update = install
initialization_template = """import os
sys.argv[0] = os.path.abspath(sys.argv[0])
os.chdir(%r)
"""
env_template = """os.environ['%s'] = %r
"""
def getpath(candidates):
paths = os.environ['PATH'].split(os.pathsep)
for c in candidates:
for p in paths:
full = os.path.join(p, c)
if os.path.exists(full):
return full
raise RuntimeError(
'Can\'t find executable for any of: %s' % candidates)
class Builder:
def get_relpaths(self, paths):
working_dir = os.getcwd()
return [os.path.relpath(path, working_dir) for path in paths]
def __call__(self, targets=None, languages=None, tag_relative=False):
if not targets:
targets = ('idutils', 'ctags_vi', 'ctags_emacs') # legacy behavior
self.languages = languages or ''
self.tag_relative = tag_relative
paths = [path for path in sys.path
if os.path.isdir(path)]
if self.tag_relative:
# ctags will ignore --tag-relative=yes for absolute paths so we
# must pass relative paths to it.
paths = self.get_relpaths(paths)
self.paths = paths
results = {}
for target in targets:
tool_candidates, arguments, source, destination = getattr(
self, '_build_{}'.format(target))()
arguments[0:0] = [getpath(tool_candidates)]
res = subprocess.call(arguments)
if res == 0:
res = subprocess.call(['mv', source, destination])
results[target] = res
return results
def _build_idutils(self):
return [
[
'mkid'
], [
'-m',
pkg_resources.resource_filename(
"z3c.recipe.tag", "id-lang.map.txt"),
'-o',
'ID.new'
] + self.paths,
'ID.new',
'ID']
def _build_ctags_vi(self):
res = [['ctags-exuberant', 'ctags'],
['-R',
'--python-kinds=-i',
'-f',
'tags.new'] + self.paths,
'tags.new',
'tags']
if self.languages:
res[1][0:0] = ['--languages=%s' % self.languages]
if self.tag_relative:
res[1][0:0] = ['--tag-relative=yes']
return res
def _build_ctags_emacs(self):
res = self._build_ctags_vi()
res[1][0:0] = ['-e']
res[3] = 'TAGS'
return res
def _build_ctags_bbedit(self):
res = self._build_ctags_vi()
try:
res[1].remove('--tag-relative=yes')
except ValueError:
pass
res[1][0:0] = [
'--excmd=number', '--tag-relative=no', '--fields=+a+m+n+S']
return res
def append_const(option, opt_str, value, parser, const):
# 'append_const' action added in Py 2.5, and we're in 2.4 :-(
if getattr(parser.values, 'targets', None) is None:
parser.values.targets = []
parser.values.targets.append(const)
def build_tags(args=None):
parser = optparse.OptionParser()
parser.add_option('-l', '--languages', dest='languages',
default='-JavaScript',
help='ctags comma-separated list of languages. '
'defaults to ``-JavaScript``')
parser.add_option('-e', '--ctags-emacs', action='callback',
callback=append_const, callback_args=('ctags_emacs',),
help='flag to build emacs ctags ``TAGS`` file')
parser.add_option('-v', '--ctags-vi', action='callback',
callback=append_const, callback_args=('ctags_vi',),
help='flag to build vi ctags ``tags`` file')
parser.add_option('-b', '--ctags-bbedit', action='callback',
callback=append_const, callback_args=('ctags_bbedit',),
help='flag to build bbedit ctags ``tags`` file')
parser.add_option('-i', '--idutils', action='callback',
callback=append_const, callback_args=('idutils',),
help='flag to build idutils ``ID`` file')
parser.add_option('-r', '--tag-relative', action='store_true',
dest='tag_relative', default=False,
help=('generate tags with paths relative to'
' tags file instead of absolute paths'
' (works with vim tags only)'))
options, args = parser.parse_args(args)
if args:
parser.error('no arguments accepted')
targets = getattr(options, 'targets', None)
if (targets and 'ctags_bbedit' in targets and 'ctags_vi' in targets):
parser.error('cannot build both vi and bbedit ctags files (same name)')
builder = Builder()
builder(targets, languages=options.languages,
tag_relative=options.tag_relative)
try:
import paver.easy
except ImportError:
HAS_PAVER = False
else: # pragma: nocover
HAS_PAVER = True
if HAS_PAVER: # pragma: nocover
@paver.easy.task
@paver.easy.consume_args
def tags(args):
"""Build tags database file for emacs, vim, or bbedit"""
build_tags(args) | z3c.recipe.tag | /z3c.recipe.tag-1.0.tar.gz/z3c.recipe.tag-1.0/src/z3c/recipe/tag/__init__.py | __init__.py |
Introduction
************
This recipe can be used to generate textfiles from a (text)
template. Different to `collective.recipe.template`_ you can also
specify a path to the output file and the path will be created, if it
does not exist.
A short example::
[buildout]
parts = zope.conf
[message]
recipe = collective.recipe.template
input = templates/message.in
output = ${buildout:parts-directory}/etc/message
mymessage = Hello, World!
In the template you can use the exact same variables as you can use
in the buildout configuration. For example an input file can look like this::
My top level directory is ${buildout:directory}
Executables are stored in ${buildout:bin-directory}
As an extension to the buildout syntax you can reference variables from
the current buildout part directly. For example::
My message is: ${mymessage}
Why another template recipe?
============================
Both `iw.recipe.template`_ and `inquant.recipe.textfile`_ claim to do the
same thing. I have found them to be undocumented and too buggy for real
world use, and neither are in a public repository where I could fix them. In
addition this implementation leverages the buildout variable substitution
code, making it a lot simpler.
`collective.recipe.template`_ actually lacks support for creating
paths of target files to be generated (and tests).
.. _iw.recipe.template: http://pypi.python.org/pypi/iw.recipe.template
.. _inquant.recipe.textfile: http://pypi.python.org/pypi/inquant.recipe.textfile
.. _collective.recipe.template: http://pypi.python.org/pypi/collective.recipe.template
| z3c.recipe.template | /z3c.recipe.template-0.1.tar.gz/z3c.recipe.template-0.1/README.txt | README.txt |
Detailed Description
********************
Simple creation of a file out of a template
===========================================
Lets create a minimal `buildout.cfg` file::
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = template
... offline = true
...
... [template]
... recipe = z3c.recipe.template
... input = template.in
... output = template
... ''')
We create a template file::
>>> write('template.in',
... '''#
... My template knows about buildout path:
... ${buildout:directory}
... ''')
Now we can run buildout::
>>> print system(join('bin', 'buildout')),
Installing template.
The template was indeed created::
>>> cat('template')
#
My template knows about buildout path:
.../sample-buildout
The variable ``buildout:directory`` was also substituted by a path.
Creating a template in a variable path
======================================
Lets create a minimal `buildout.cfg` file. This time the output should
happen in a variable path::
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = template
... offline = true
...
... [template]
... recipe = z3c.recipe.template
... input = template.in
... output = ${buildout:parts-directory}/template
... ''')
Now we can run buildout::
>>> print system(join('bin', 'buildout')),
Uninstalling template.
Installing template.
The template was indeed created::
>>> cat('parts', 'template')
#
My template knows about buildout path:
.../sample-buildout
Creating missing paths
======================
If an output file should be created in a path that does not yet exist,
then the missing items will be created for us::
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = template
... offline = true
...
... [template]
... recipe = z3c.recipe.template
... input = template.in
... output = ${buildout:parts-directory}/etc/template
... ''')
>>> print system(join('bin', 'buildout')),
Uninstalling template.
Installing template.
Also creation of several subdirectories is supported::
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = template
... offline = true
...
... [template]
... recipe = z3c.recipe.template
... input = template.in
... output = ${buildout:parts-directory}/foo/bar/template
... ''')
>>> print system(join('bin', 'buildout')),
Uninstalling template.
Installing template.
>>> cat('parts', 'foo', 'bar', 'template')
#
My template knows about buildout path:
.../sample-buildout
When changes happen to the output path, then the old path is removed
on uninstall. Therefore the ``etc/`` directory created above has
vanished now::
>>> ls('parts')
d foo
| z3c.recipe.template | /z3c.recipe.template-0.1.tar.gz/z3c.recipe.template-0.1/z3c/recipe/template/README.txt | README.txt |
z3c.recipe.usercrontab changes
==============================
1.5 (2018-12-20)
----------------
- Officially support Python 3.5, 3.6, 3.7, PyPy and PyPy3.
1.4 (2015-10-29)
----------------
- Added an ``enabled`` option that's on by default. By setting this to false,
you can generate cronjobs that are commented out.
This can be useful if you have to perform other tasks in your deployment
before a cronjob can be switched on (by uncommenting manually or by a
script).
[WouterVH]
1.3 (2015-10-05)
----------------
- New 'comment' option. This way you can add a small explanatory one-line
option to your crontab entry.
[reinout]
1.2.1 (2015-09-11)
------------------
- Moved development to https://github.com/reinout/z3c.recipe.usercrontab
[reinout]
- Made a few small fixes to get everything running on python 3.
[reinout]
1.1 (2010-11-09)
----------------
- Append and prepend less white space per cron item, so you do not get
increasing extra white space everytime you run bin/buildout.
[maurits]
1.0 (2009-11-10)
----------------
- Only small documentation changes; version bumped to 1.0 to signal
stability. [reinout]
0.7 (2009-08-24)
----------------
- The crontab now gets checked every time buildout runs, not only when there's
a change in the configuration. [reinout]
0.6.1 (2009-06-17)
------------------
- Documentation fixes. [reinout]
0.6 (2009-06-16)
----------------
- Removed essentially-unused complete environment variable handling.
[reinout]
- Adding our entries with descriptive comments now: it includes the buildout
file and the part name. [reinout]
0.5.1 (2009-06-16)
------------------
- Reverted the "BUILDOUT=..." environment variable, including migration. I'll
add a better way after this release. [reinout]
0.5 (2009-06-15)
----------------
* Added migration code for pre-0.5 entries without a BUILDOUT variable.
[reinout]
* Added extra blank line in front of "BUILDOUT=..." variable to allow for
better readability. [reinout]
* Added "BUILDOUT=...." as environment variable for every set of crontab lines
handled by one buildout. This makes it much easier to spot what got added
by which buildout (in case you have multiple) or which buildout at all (if
you have no clue where the buildout can be found). [reinout]
0.4 (2008-02-25)
----------------
* Fix bug where UserCrontabs with empty readcrontab and writecrontab
constructor arguments where broken
0.3 (2008-02-23)
----------------
* Renamed to z3c.recipe.usercrontab
* Add an option to change the command used to read and write crontabs
* Improved tests to not modify the real crontab
0.2 (2008-01-12)
----------------
* Warn if an entry cannot be removed in buildout uninstall
* Break if multiple entries would be removed in buildout uninstall
* Have del_entry return the number of removed
0.1 (2008-01-12)
----------------
* Initial release.
| z3c.recipe.usercrontab | /z3c.recipe.usercrontab-1.5.tar.gz/z3c.recipe.usercrontab-1.5/CHANGES.rst | CHANGES.rst |
z3c.recipe.usercrontab
======================
The problem
-----------
When deploying applications, it can be useful to have maintenance
tasks be started periodically. On Unix platforms this is usually done
using ``cron`` which starts `cronjobs`. Adding cronjobs to the
system-wide cron directory (for example by placing a file in
``/etc/cron.d``) can be handled using the ``zc.recipe.deployment``
package, but it does not support adding cronjobs by normal
users. (as ``/etc/cron.d`` usually is world-writable).
The solution
------------
``z3c.recipe.usercrontab`` interfaces with cron using ``crontab(1)``,
and allows normal users to install their own cronjobs. This is done by
having buildout add and remove cronjobs when installing and
uninstalling packages.
How to use it
-------------
To use ``z3c.recipe.usercrontab`` you need to add the following to
your buildout.cfg::
[mycronjob]
recipe = z3c.recipe.usercrontab
times = 0 12 * * *
command = echo nothing happens at noon
and finally add ``mycronjob`` to the ``parts`` line(s) of your
buildout.cfg
To add a comment to your cron-entry::
[mycronjob]
recipe = z3c.recipe.usercrontab
times = 0 12 * * *
command = echo nothing happens at noon
comment = Run daily at noon
If you prefer to manually enable cronjobs, you can generate a cron-entry
that is commented out by setting ``enabled`` to ``False``::
[mycronjob]
recipe = z3c.recipe.usercrontab
times = 0 12 * * *
command = echo nothing happens at noon
enabled = false
After running the buildout, you can check the generated cron-entries
via ``crontab -l``.
Credits
-------
Original authors: Jasper Spaans and Jan-Jaap Driessen.
Most recent versions and current maintainer: `Reinout van Rees
<http://reinout.vanrees.org>`_.
| z3c.recipe.usercrontab | /z3c.recipe.usercrontab-1.5.tar.gz/z3c.recipe.usercrontab-1.5/README.rst | README.rst |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
__version__ = '2015-07-01'
# See zc.buildout's changelog if this version is up to date.
tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
options, args = parser.parse_args()
if options.version:
print("bootstrap.py version %s" % __version__)
sys.exit(0)
######################################################################
# load/install setuptools
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
requirement = 'zc.buildout'
version = options.buildout_version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.recipe.usercrontab | /z3c.recipe.usercrontab-1.5.tar.gz/z3c.recipe.usercrontab-1.5/bootstrap.py | bootstrap.py |
.. -*- mode: doctest -*-
Detailed documentation
======================
The recipe z3c.recipe.usercrontab is a small recipe to facilitate the
installing of cronjobs into user crontabs.
>>> from z3c.recipe.usercrontab.usercrontab import UserCrontabManager
Entry handling
--------------
A user crontab manager manages a user's crontab for one specific buildout
part. The part ends up in the identifier. We'll use 'test' here.
>>> c = UserCrontabManager(identifier='test')
In these tests, we can fake a crontab by filling the list of cron entries
manually:
>>> c.crontab = ['@reboot echo "hello world"']
>>> print(c) # Handy shortcut
@reboot echo "hello world"
Now, we're adding an entry to it using the official way. The entry is
surrounded by markers:
>>> c.add_entry('@reboot echo "I just got added"')
>>> print(c)
@reboot echo "hello world"
<BLANKLINE>
# Generated by test
@reboot echo "I just got added"
# END test
<BLANKLINE>
Removing entries also works. As long as the "Generated by" markers are
present, it doesn't matter which entry you remove: everything surrounded by
the markers is zapped:
>>> c.del_entry('bla bla') == 1
True
>>> print(c)
@reboot echo "hello world"
An entry can also include an explanatory comment line:
>>> c.add_entry('@reboot echo "I just got added"',
... comment="This ought to happen first")
>>> print(c)
@reboot echo "hello world"
<BLANKLINE>
# Generated by test
# This ought to happen first
@reboot echo "I just got added"
# END test
<BLANKLINE>
Pre-0.6, a WARNING environment variable was used. An entry (which content
matters now!) is found there:
>>> c.crontab = ['@reboot echo "hello world"',
... 'WARNING="Everything below is added by bla bla',
... '@reboot echo "old entry 1"',
... '@reboot echo "old entry 2"']
>>> print(c)
@reboot echo "hello world"
WARNING="Everything below is added by bla bla
@reboot echo "old entry 1"
@reboot echo "old entry 2"
>>> c.del_entry('@reboot echo "old entry 1"')
1
>>> print(c)
@reboot echo "hello world"
WARNING="Everything below is added by bla bla
@reboot echo "old entry 2"
Removing the last remaining entry under WARNING also removes the WARNING:
>>> c.del_entry('@reboot echo "old entry 2"')
1
>>> print(c)
@reboot echo "hello world"
Briefly in the 0.5 version, a 'BUILDOUT' environment variable was used for
grouping items per buildout. Now for some up/downgrade testing. 0.5.1 removes
the environment variable again. We'll add an entry with such a (now
deprecated) "grouping environment variable". First the start situation:
>>> c.crontab=[
... 'WARNING="Everything below is added by bla bla',
... 'BUILDOUT=my/buildout',
... '@reboot echo nothing happens']
>>> print(c)
WARNING="Everything below is added by bla bla
BUILDOUT=my/buildout
@reboot echo nothing happens
Doing anything (adding/removing) zaps BUILDOUT statement:
>>> c.del_entry('nonexisting')
0
>>> print(c)
WARNING="Everything below is added by bla bla
@reboot echo nothing happens
And just to make sure, deleting that entry empties out the whole file:
>>> c.del_entry('@reboot echo nothing happens')
1
>>> print(c)
<BLANKLINE>
Read/write crontab methods
--------------------------
Next, test the read_crontab and write_crontab methods; we'll use
``cat`` and a temporary file to not modifiy the crontab of the user
running these tests:
>>> import tempfile
>>> t = tempfile.NamedTemporaryFile('w')
>>> crontestfile = t.name
>>> dont_care = t.write("#dummy\n")
>>> c = UserCrontabManager(readcrontab="cat %s" % crontestfile,
... writecrontab="cat >%s" % crontestfile,
... identifier='test')
>>> c.read_crontab()
>>> a = repr(c)
>>> c.add_entry('# improbable entry')
>>> c.write_crontab()
>>> c.read_crontab()
>>> b =repr(c)
>>> a == b
False
Now, delete this entry again and make sure the old crontab is restored:
>>> c.del_entry('# improbable entry') == 1
True
>>> c.write_crontab()
>>> c.read_crontab()
>>> b = repr(c)
>>> a == b
True
Buildout recipe usage
---------------------
Do the buildout shuffle:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> import os
>>> 'Installing foo' in system(buildout)
True
Check that it really was added to the crontab:
>>> c.read_crontab()
>>> b = repr(c)
>>> a == b
False
>>> '@reboot\techo nothing happens' in c.crontab
True
>>> print(c)
# Generated by /sample-buildout [foo]
@reboot echo nothing happens
# END /sample-buildout [foo]
Re-running buildout runs the crontab recipe even when there's no change:
>>> output = system(buildout)
>>> 'Updating foo' in output or 'Installing foo' in output
True
>>> c.read_crontab()
>>> print(c)
# Generated by /sample-buildout [foo]
@reboot echo nothing happens
# END /sample-buildout [foo]
This means that a crontab is fixed up if we mucked it up by hand:
>>> c.crontab = []
>>> c.write_crontab()
>>> c.read_crontab()
>>> print(c)
>>> output = system(buildout)
>>> 'Updating foo' in output or 'Installing foo' in output
True
>>> c.read_crontab()
>>> print(c)
# Generated by /sample-buildout [foo]
@reboot echo nothing happens
# END /sample-buildout [foo]
You can also add a comment to the crontab entry:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... comment = Step 1: mention that nothing happens
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> 'Installing foo' in system(buildout)
True
>>> c.read_crontab()
>>> print(c)
# Generated by /sample-buildout [foo]
# Step 1: mention that nothing happens
@reboot echo nothing happens
# END /sample-buildout [foo]
An entry is by default enabled, leading to an active cronjob:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... enabled = true
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> 'Installing foo' in system(buildout)
True
>>> c.read_crontab()
>>> print(c)
# Generated by /sample-buildout [foo]
@reboot echo nothing happens
# END /sample-buildout [foo]
You can also generate an inactive cronjob that is commented out, by setting
the enabled-option to False:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... enabled = false
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> 'Installing foo' in system(buildout)
True
>>> c.read_crontab()
>>> print(c)
# Generated by /sample-buildout [foo]
# @reboot echo nothing happens
# END /sample-buildout [foo]
Uninstall the recipe:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts =
... ''' % ( { 'crontest': crontestfile } ))
>>> 'Uninstalling foo' in system(buildout)
True
And check that its entry was removed (i.e., the contents of the
crontab are the same as when this test was started; in any case, the
teardown from the testrunner makes sure the old situation is
restored):
>>> c.read_crontab()
>>> b = repr(c)
>>> a == b
True
A second part installs fine:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo bar
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
...
... [bar]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo something happens
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> output = system(buildout)
>>> 'Installing foo' in output
True
>>> 'Installing bar' in output
True
>>> c.read_crontab()
>>> print(c)
<BLANKLINE>
# Generated by /sample-buildout [foo]
@reboot echo nothing happens
# END /sample-buildout [foo]
<BLANKLINE>
<BLANKLINE>
# Generated by /sample-buildout [bar]
@reboot echo something happens
# END /sample-buildout [bar]
<BLANKLINE>
Uninstalling also works fine
>>> write('buildout.cfg',
... '''
... [buildout]
... parts =
... ''' % ( { 'crontest': crontestfile } ))
>>> output = system(buildout)
>>> 'Uninstalling bar' in output
True
>>> 'Uninstalling foo' in output
True
Safety valves
-------------
If the section has been removed, nothing can be found by the uninstall. You
get warnings that way:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> import os
>>> 'Installing foo' in system(buildout)
True
>>> c.crontab = []
>>> c.write_crontab()
>>> write('buildout.cfg',
... '''
... [buildout]
... parts =
... ''' % ( { 'crontest': crontestfile } ))
>>> 'WARNING: Did not find a crontab-entry during uninstall' in system(buildout)
True
Another test: pre-0.6 config simulation:
>>> write('buildout.cfg',
... '''
... [buildout]
... parts = foo
...
... [foo]
... recipe = z3c.recipe.usercrontab
... times = @reboot
... command = echo nothing happens
... readcrontab = cat %(crontest)s
... writecrontab = cat >%(crontest)s
... ''' % ( { 'crontest': crontestfile } ))
>>> import os
>>> 'Installing foo' in system(buildout)
True
>>> c.crontab = ['WARNING="Everything below is added by bla bla"',
... 'BUILDOUT=/somewhere/out/there',
... '@reboot\techo nothing happens']
>>> c.write_crontab()
>>> write('buildout.cfg',
... '''
... [buildout]
... parts =
... ''' % ( { 'crontest': crontestfile } ))
>>> 'Running uninstall recipe' in system(buildout)
True
>>> c.read_crontab()
>>> print(c)
<BLANKLINE>
| z3c.recipe.usercrontab | /z3c.recipe.usercrontab-1.5.tar.gz/z3c.recipe.usercrontab-1.5/z3c/recipe/usercrontab/README.rst | README.rst |
import logging
from zc.buildout.buildout import bool_option
from z3c.recipe.usercrontab.usercrontab import UserCrontabManager
class UserCrontab:
def __init__(self, buildout, name, options):
self.options = options
options['entry'] = '%s\t%s' % (options['times'], options['command'])
self.comment = options.get('comment')
if not bool_option(self.options, 'enabled', default=True):
self.options['entry'] = '# ' + self.options['entry']
# readcrontab and writecrontab are solely for testing.
readcrontab = self.options.get('readcrontab', None)
writecrontab = self.options.get('writecrontab', None)
self.options['identifier'] = '%s [%s]' % (
buildout['buildout']['directory'], name)
self.crontab = UserCrontabManager(
readcrontab, writecrontab,
identifier=self.options['identifier'])
def install(self):
self.crontab.read_crontab()
self.crontab.add_entry(self.options['entry'], self.comment)
self.crontab.write_crontab()
return ()
def update(self):
self.install()
def uninstall_usercrontab(name, options):
readcrontab = options.get('readcrontab', None)
writecrontab = options.get('writecrontab', None)
identifier = options.get('identifier', 'NO IDENTIFIER')
crontab = UserCrontabManager(
readcrontab, writecrontab,
identifier=identifier)
crontab.read_crontab()
nuked = crontab.del_entry(options['entry'])
if nuked == 0:
logging.getLogger(name).warning(
"WARNING: Did not find a crontab-entry during uninstall; "
"please check manually if everything was removed correctly")
elif nuked > 1:
logging.getLogger(name).error(
"FATAL ERROR: Found more than one matching crontab-entry during "
"uninstall; please resolve manually.\nMatched lines: %s",
(options['entry']))
raise RuntimeError(
"Found more than one matching crontab-entry during uninstall")
crontab.write_crontab() | z3c.recipe.usercrontab | /z3c.recipe.usercrontab-1.5.tar.gz/z3c.recipe.usercrontab-1.5/z3c/recipe/usercrontab/__init__.py | __init__.py |
=====================
z3c.recipe.winservice
=====================
This recipe offers windows service installation support.
The 'service' recipe installes the required scripts and files which can be
used to install a windows service.
Using the ``runscript`` option it is able to make any executable a service.
Options
*******
The 'service' recipe accepts the following options:
name
The windows service name option.
description
The windows service description option.
runzope
The script name which gets run by the winservice.
If the script name contains any path, it's taken as it is, otherwise the
buildout bin folder is prepended. winservice will check on install if this
script exists.
The install takes care of adding ``-script.py`` if necessary.
This script can get setup for exmaple with the z3c.recipe.dev.app recipe.
runscript
The script (.py) or executable (.exe) name to be run by the winservice.
The value will get NO treatment, you need to pass an exact specification.
winservice will check on install if this script/exe exists.
Use this option OR runzope, but never both.
parameters
This value will get passed to the script (runzope or runscript) as a
parameter. The value will get NO treatment, you need to take care of adding
any quotes if necessary.
debug
Adding this option to the recipe wraps the whole script to run into
a catch all except that logs the exception to the windows event log.
This is good for debugging weird exceptions that occur before the Zope
logging system is in place.
This does not work if runscript is an executable.
| z3c.recipe.winservice | /z3c.recipe.winservice-0.7.0.zip/z3c.recipe.winservice-0.7.0/README.txt | README.txt |
=====================
z3c.recipe.winservice
=====================
This recipe offers windows service installation support.
Test
****
Lets define some (bogus) eggs that we can use in our application:
>>> mkdir('demo1')
>>> write('demo1', 'setup.py',
... '''
... from setuptools import setup
... setup(name = 'demo1')
... ''')
>>> mkdir('demo2')
>>> write('demo2', 'setup.py',
... '''
... from setuptools import setup
... setup(name = 'demo2', install_requires='demo1')
... ''')
We also need to setup an application. This is normaly done with the app recipe
defined in z3c.recipe.dev:
>>> write('bin', 'app-script.py',
... '''
... dummy start script
... ''')
Now check if the setup was correct. This is true if we have already the
buildout files and our fake app-script.py installed:
>>> ls('bin')
- app-script.py
- buildout-script.py
- buildout.exe
We'll create a `buildout.cfg` file that defines our winservice configuration:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo1 demo2
... parts = winservice
...
... [winservice]
... recipe = z3c.recipe.winservice:service
... name = Zope 3 Windows Service
... description = Zope 3 Windows Service description
... runzope = app
...
... ''' % globals())
Now, Let's run the buildout and see what we get:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Installing winservice.
The bin folder contains the windows service installer script:
>>> ls('bin')
- app-script.py
- buildout-script.py
- buildout.exe
- winservice.py
The winservice.py contains the service setup for our zope windows service:
>>> cat('bin', 'winservice.py')
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""A Zope Windows NT service frontend.
<BLANKLINE>
Usage:
<BLANKLINE>
Installation
<BLANKLINE>
You can manually install, uninstall the service from the commandline.
<BLANKLINE>
python bin\winservice.py [options] install|update|remove|start [...]
|stop|restart [...]|debug [...]
<BLANKLINE>
Options for 'install' and 'update' commands only:
<BLANKLINE>
--username domain\username : The Username the service is to run
under
<BLANKLINE>
--password password : The password for the username
<BLANKLINE>
--startup [manual|auto|disabled] : How the service starts,
default = manual
<BLANKLINE>
Commands
<BLANKLINE>
install : Installs the service
<BLANKLINE>
update : Updates the service, use this when you change
the service class implementation
<BLANKLINE>
remove : Removes the service
<BLANKLINE>
start : Starts the service, this can also be done from the
services control panel
<BLANKLINE>
stop : Stops the service, this can also be done from the
services control panel
<BLANKLINE>
restart : Restarts the service
<BLANKLINE>
debug : Runs the service in debug mode
<BLANKLINE>
You can view the usage options by running ntservice.py without any
arguments.
<BLANKLINE>
Note: you may have to register the Python service program first,
<BLANKLINE>
win32\PythonService.exe /register
<BLANKLINE>
Starting Zope
<BLANKLINE>
Start Zope by clicking the 'start' button in the services control
panel. You can set Zope to automatically start at boot time by
choosing 'Auto' startup by clicking the 'statup' button.
<BLANKLINE>
Stopping Zope
<BLANKLINE>
Stop Zope by clicking the 'stop' button in the services control
panel. You can also stop Zope through the web by going to the
Zope control panel and by clicking 'Shutdown'.
<BLANKLINE>
Event logging
<BLANKLINE>
Zope events are logged to the NT application event log. Use the
event viewer to keep track of Zope events.
<BLANKLINE>
"""
<BLANKLINE>
import sys, os, time
import pywintypes
import win32serviceutil
import win32service
import win32event
import win32process
<BLANKLINE>
# these are replacements from winservice recipe
PYTHONSERVICE_EXE = r'...\Lib\site-packages\win32\pythonservice.exe'
PYTHON = r'...\python.exe'
TOSTART = r'/sample-buildout/bin/app-script.py'
PARAMETERS = r''
SERVICE_NAME = '...sample_buildout_bin_app_script_py'
SERVICE_DISPLAY_NAME = r'Zope 3 Windows Service'
SERVICE_DESCRIPTION = r'Zope 3 Windows Service description'
INSTANCE_HOME = r'/sample-buildout'
<BLANKLINE>
<BLANKLINE>
# the max seconds we're allowed to spend backing off
BACKOFF_MAX = 300
# if the process runs successfully for more than BACKOFF_CLEAR_TIME
# seconds, we reset the backoff stats to their initial values
BACKOFF_CLEAR_TIME = 30
# the initial backoff interval (the amount of time we wait to restart
# a dead process)
BACKOFF_INITIAL_INTERVAL = 5
<BLANKLINE>
<BLANKLINE>
class NullOutput:
"""A stdout / stderr replacement that discards everything."""
<BLANKLINE>
def noop(self, *args, **kw):
pass
<BLANKLINE>
write = writelines = close = seek = flush = truncate = noop
<BLANKLINE>
def __iter__(self):
return self
<BLANKLINE>
def next(self):
raise StopIteration
<BLANKLINE>
def isatty(self):
return False
<BLANKLINE>
def tell(self):
return 0
<BLANKLINE>
def read(self, *args, **kw):
return ''
<BLANKLINE>
readline = read
<BLANKLINE>
def readlines(self, *args, **kw):
return []
<BLANKLINE>
<BLANKLINE>
class Zope3Service(win32serviceutil.ServiceFramework):
""" A class representing a Windows NT service that can manage an
instance-home-based Zope/ZEO/ZRS processes """
<BLANKLINE>
# The PythonService model requires that an actual on-disk class declaration
# represent a single service. Thus, the below definition of start_cmd,
# must be overridden in a subclass in a file within the instance home for
# each instance. The below-defined start_cmd (and _svc_display_name_
# and _svc_name_) are just examples.
<BLANKLINE>
_svc_name_ = SERVICE_NAME
_svc_display_name_ = SERVICE_DISPLAY_NAME
_svc_description_ = SERVICE_DESCRIPTION
<BLANKLINE>
_exe_name_ = PYTHONSERVICE_EXE
start_cmd = ''
<BLANKLINE>
def __init__(self, args):
cmdLine = ''
if PYTHON:
if not os.path.exists(PYTHON):
raise OSError("%s does not exist" % PYTHON)
cmdLine += '"%s" ' % PYTHON
if not os.path.exists(TOSTART):
raise OSError("%s does not exist" % TOSTART)
cmdLine += '"%s" ' % TOSTART
<BLANKLINE>
if PARAMETERS:
cmdLine += PARAMETERS
<BLANKLINE>
self.start_cmd = cmdLine
<BLANKLINE>
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.redirectOutput()
<BLANKLINE>
def redirectOutput(self):
sys.stdout.close()
sys.stderr.close()
sys.stdout = NullOutput()
sys.stderr = NullOutput()
<BLANKLINE>
def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
<BLANKLINE>
# TODO: This TerminateProcess call doesn't make much sense: it's
# doing a hard kill _first_, never giving the process a chance to
# shut down cleanly. Compare to current Zope2 service code, which
# uses Windows events to give the process a chance to shut down
# cleanly, doing a hard kill only if that doesn't succeed.
<BLANKLINE>
# stop the process if necessary
try:
win32process.TerminateProcess(self.hZope, 0)
except pywintypes.error:
# the process may already have been terminated
pass
# And set my event.
win32event.SetEvent(self.hWaitStop)
<BLANKLINE>
# SvcStop only gets triggered when the user explictly stops (or restarts)
# the service. To shut the service down cleanly when Windows is shutting
# down, we also need to hook SvcShutdown.
SvcShutdown = SvcStop
<BLANKLINE>
def createProcess(self, cmd):
#need to set current dir to INSTANCE_HOME otherwise pkg_resources will
#be pissed (in a combination with paster)
return win32process.CreateProcess(
None, cmd, None, None, 0, 0, None,
INSTANCE_HOME,
win32process.STARTUPINFO())
<BLANKLINE>
def SvcDoRun(self):
# indicate to Zope that the process is daemon managed (restartable)
os.environ['ZMANAGED'] = '1'
<BLANKLINE>
# daemon behavior: we want to to restart the process if it
# dies, but if it dies too many times, we need to give up.
<BLANKLINE>
# we use a simple backoff algorithm to determine whether
# we should try to restart a dead process: for each
# time the process dies unexpectedly, we wait some number of
# seconds to restart it, as determined by the backoff interval,
# which doubles each time the process dies. if we exceed
# BACKOFF_MAX seconds in cumulative backoff time, we give up.
# at any time if we successfully run the process for more thab
# BACKOFF_CLEAR_TIME seconds, the backoff stats are reset.
<BLANKLINE>
# the initial number of seconds between process start attempts
backoff_interval = BACKOFF_INITIAL_INTERVAL
# the cumulative backoff seconds counter
backoff_cumulative = 0
<BLANKLINE>
import servicemanager
<BLANKLINE>
# log a service started message
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ' (%s)' % self._svc_display_name_))
<BLANKLINE>
while 1:
start_time = time.time()
info = self.createProcess(self.start_cmd)
self.hZope = info[0] # the pid
if backoff_interval > BACKOFF_INITIAL_INTERVAL:
# if we're in a backoff state, log a message about
# starting a new process
servicemanager.LogInfoMsg(
'%s (%s): recovering from died process, new process '
'started' % (self._svc_name_, self._svc_display_name_)
)
rc = win32event.WaitForMultipleObjects(
(self.hWaitStop, self.hZope), 0, win32event.INFINITE)
if rc == win32event.WAIT_OBJECT_0:
# user sent a stop service request
self.SvcStop()
break
else:
# user did not send a service stop request, but
# the process died; this may be an error condition
status = win32process.GetExitCodeProcess(self.hZope)
if status == 0:
# the user shut the process down from the web
# interface (or it otherwise exited cleanly)
break
else:
# this was an abormal shutdown. if we can, we want to
# restart the process but if it seems hopeless,
# don't restart an infinite number of times.
if backoff_cumulative > BACKOFF_MAX:
# it's hopeless
servicemanager.LogErrorMsg(
'%s (%s): process could not be restarted due to max '
'restart attempts exceeded' % (
self._svc_display_name_, self._svc_name_
))
self.SvcStop()
break
servicemanager.LogWarningMsg(
'%s (%s): process died unexpectedly. Will attempt '
'restart after %s seconds.' % (
self._svc_name_, self._svc_display_name_,
backoff_interval
)
)
# if BACKOFF_CLEAR_TIME seconds have elapsed since we last
# started the process, reset the backoff interval
# and the cumulative backoff time to their original
# states
if time.time() - start_time > BACKOFF_CLEAR_TIME:
backoff_interval = BACKOFF_INITIAL_INTERVAL
backoff_cumulative = 0
# we sleep for the backoff interval. since this is async
# code, it would be better done by sending and
# catching a timed event (a service
# stop request will need to wait for us to stop sleeping),
# but this works well enough for me.
time.sleep(backoff_interval)
# update backoff_cumulative with the time we spent
# backing off.
backoff_cumulative = backoff_cumulative + backoff_interval
# bump the backoff interval up by 2* the last interval
backoff_interval = backoff_interval * 2
<BLANKLINE>
# loop and try to restart the process
<BLANKLINE>
# log a service stopped message
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ' (%s) ' % self._svc_display_name_))
<BLANKLINE>
<BLANKLINE>
if __name__ == '__main__':
import win32serviceutil
if os.path.exists(PYTHONSERVICE_EXE):
# This ensures that pythonservice.exe is registered...
os.system('"%s" -register' % PYTHONSERVICE_EXE)
win32serviceutil.HandleCommandLine(Zope3Service)
Parameters for the script
-------------------------
Let's add now parameters to the script:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo1 demo2
... parts = winservice
...
... [winservice]
... recipe = z3c.recipe.winservice:service
... name = Zope 3 Windows Service
... description = Zope 3 Windows Service description
... runzope = app
... parameters = -C zope.conf
...
... ''' % globals())
Let's buildout:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Uninstalling winservice.
Installing winservice.
The bin folder contains the windows service installer script:
>>> ls('bin')
- app-script.py
- buildout-script.py
- buildout.exe
- winservice.py
PARAMETERS gets filled in:
>>> cat('bin', 'winservice.py')
##############################################################################
...
# these are replacements from winservice recipe
PYTHONSERVICE_EXE = r'...\Lib\site-packages\win32\pythonservice.exe'
PYTHON = r'...\python.exe'
TOSTART = r'/sample-buildout/bin/app-script.py'
PARAMETERS = r'-C zope.conf'
SERVICE_NAME = '...sample_buildout_bin_app_script_py'
SERVICE_DISPLAY_NAME = r'Zope 3 Windows Service'
SERVICE_DESCRIPTION = r'Zope 3 Windows Service description'
INSTANCE_HOME = r'/sample-buildout'
...
A script not in ``bin``
-----------------------
We can have the script in a different folder than ``bin``:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo1 demo2
... parts = winservice
...
... [winservice]
... recipe = z3c.recipe.winservice:service
... name = Zope 3 Windows Service
... description = Zope 3 Windows Service description
... runzope = parts\zope-app\zope-dev
...
... ''' % globals())
Let's buildout:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Uninstalling winservice.
Installing winservice.
While:
Installing winservice.
Error: App start script parts\zope-app\zope-dev-script.py does not exist.
Oops, the script does not exist yet.
>>> import os
>>> os.mkdir('parts/zope-app')
>>> write('parts', 'zope-app', 'zope-dev-script.py',
... '''
... other dummy app script
... ''')
Buildout again:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Installing winservice.
The bin folder contains the windows service installer script:
>>> ls('bin')
- app-script.py
- buildout-script.py
- buildout.exe
- winservice.py
TOSTART respects the folder given in runzope:
>>> cat('bin', 'winservice.py')
##############################################################################
...
PYTHONSERVICE_EXE = r'...\Lib\site-packages\win32\pythonservice.exe'
PYTHON = r'...\python.exe'
TOSTART = r'parts\zope-app\zope-dev-script.py'
PARAMETERS = r''
SERVICE_NAME = 'parts_zope_app_zope_dev_script_py'
SERVICE_DISPLAY_NAME = r'Zope 3 Windows Service'
SERVICE_DESCRIPTION = r'Zope 3 Windows Service description'
INSTANCE_HOME = r'/sample-buildout'
...
``runscript`` executable
-------------------------
Let's use now the ``runscript`` option:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo1 demo2
... parts = winservice
...
... [winservice]
... recipe = z3c.recipe.winservice:service
... name = Zope 3 Windows Service
... description = Zope 3 Windows Service description
... runscript = parts\exe\some.exe
... parameters = -C zope.conf
...
... ''' % globals())
Let's buildout:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Uninstalling winservice.
Installing winservice.
While:
Installing winservice.
Error: App start script parts\exe\some.exe does not exist.
Darn, the executable must exist.
Try again:
>>> import os
>>> os.mkdir('parts/exe')
>>> write('parts', 'exe', 'some.exe',
... '''
... dummy executable
... ''')
Buildout again:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Installing winservice.
The bin folder contains the windows service installer script:
>>> ls('bin')
- app-script.py
- buildout-script.py
- buildout.exe
- winservice.py
PYTHON gets blanked, because this is an executable,
TOSTART gets filled with the right executable,
PARAMETERS is still as before.
>>> cat('bin', 'winservice.py')
##############################################################################
...
# these are replacements from winservice recipe
PYTHONSERVICE_EXE = r'...\Lib\site-packages\win32\pythonservice.exe'
PYTHON = r''
TOSTART = r'parts\exe\some.exe'
PARAMETERS = r'-C zope.conf'
SERVICE_NAME = 'parts_exe_some_exe'
SERVICE_DISPLAY_NAME = r'Zope 3 Windows Service'
SERVICE_DESCRIPTION = r'Zope 3 Windows Service description'
INSTANCE_HOME = r'/sample-buildout'
...
``runscript`` python script
----------------------------
Let's use now the ``runscript`` option:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo1 demo2
... parts = winservice
...
... [winservice]
... recipe = z3c.recipe.winservice:service
... name = Zope 3 Windows Service
... description = Zope 3 Windows Service description
... runscript = parts\exe\some.py
... parameters = -C zope.conf
...
... ''' % globals())
>>> write('parts', 'exe', 'some.py',
... '''
... dummy python script
... ''')
Let's buildout:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Uninstalling winservice.
Installing winservice.
The bin folder contains the windows service installer script:
>>> ls('bin')
- app-script.py
- buildout-script.py
- buildout.exe
- winservice.py
PYTHON is back, because this is a script,
TOSTART gets filled with the right python script,
PARAMETERS is still as before.
>>> cat('bin', 'winservice.py')
##############################################################################
...
# these are replacements from winservice recipe
PYTHONSERVICE_EXE = r'...\Lib\site-packages\win32\pythonservice.exe'
PYTHON = r'...\python.exe'
TOSTART = r'parts\exe\some.py'
PARAMETERS = r'-C zope.conf'
SERVICE_NAME = 'parts_exe_some_py'
SERVICE_DISPLAY_NAME = r'Zope 3 Windows Service'
SERVICE_DESCRIPTION = r'Zope 3 Windows Service description'
INSTANCE_HOME = r'/sample-buildout'
...
Debug
-----
This option is for service scripts having fundamental problems.
The problem with those scripts is that they are starting and stopping at once.
Seemingly there is no output, no sing that the script did something.
And because they run in a subprocess until those scripts have logging established
they won't have any chance to report the error.
For this we'll setup a bare catch-all around the whole script and log any
exceptions to the windows event log.
CAUTION: this takes a copy of the app-script.py but does not update the patched
result when it changes!
We can enable the ``debug`` option:
>>> write('buildout.cfg',
... '''
... [buildout]
... develop = demo1 demo2
... parts = winservice
...
... [winservice]
... recipe = z3c.recipe.winservice:service
... name = Zope 3 Windows Service
... description = Zope 3 Windows Service description
... runzope = app
... debug = true
...
... ''' % globals())
Now, Let's run the buildout and see what we get:
>>> print system(join('bin', 'buildout')),
Develop: '/sample-buildout/demo1'
Develop: '/sample-buildout/demo2'
Uninstalling winservice.
Installing winservice.
The bin folder contains the windows service installer script:
>>> ls('bin')
- app-script.py
- app-servicedebug.py
- buildout-script.py
- buildout.exe
- winservice.py
The winservice.py file gets changed according to the new script name:
>>> cat('bin', 'winservice.py')
##############################################################################
...TOSTART = r'/sample-buildout/bin/app-servicedebug.py'...
...SERVICE_NAME = '...bin_app_script_py'...
The debug script contains a bare catch-all and a logger:
>>> cat('bin', 'app-servicedebug.py')
<BLANKLINE>
def exceptionlogger():
import servicemanager
import traceback
servicemanager.LogErrorMsg("Script %s had an exception: %s" % (
__file__, traceback.format_exc()
))
<BLANKLINE>
try:
<BLANKLINE>
dummy start script
<BLANKLINE>
except Exception, e:
exceptionlogger()
| z3c.recipe.winservice | /z3c.recipe.winservice-0.7.0.zip/z3c.recipe.winservice-0.7.0/src/z3c/recipe/winservice/README.txt | README.txt |
========================
HTTP-Referer Credentials
========================
It is sometimes necessary to restrict access to a site by looking at the the
site the user is coming from. For example, a user can only enter the site when
he comes from within the corporate network. If the two sites cannot share any
specific information, such as an authentication token, the only useful piece
of information is the ``HTTP-Referer`` request header.
__Note__: Yes I know this is not fully secure and someone could spoof the
header. But this is acceptable in this particular application. I guess it
keeps away the honest. And yes, this is a real world scenario -- would I
implement this package otherwise? :-)
So let's have a look at the credentials plugin:
>>> from z3c.referercredentials import credentials
>>> creds = credentials.HTTPRefererCredentials()
Let's look at the positive case first. The referer credentials plugin has an
attribute that specifies all allowed hosts:
>>> creds.allowedHosts
('localhost',)
In this example, we only want to allow peopl eto the site coming from
``www.zope.org``.
>>> creds.allowedHosts = ('www.zope.org',)
Now, a user coming from that site will have a request containing this referer:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest(HTTP_REFERER='http://www.zope.org/index.html')
The credentials can now be extracted as follows:
>>> creds.extractCredentials(request)
Nothing is returned. This is because we have not defined any credentials that
represent the "referer user". With setting the credentials, it should work:
>>> creds.credentials = {'login': 'mgr', 'password': 'mgrpw'}
>>> creds.extractCredentials(request)
{'login': 'mgr', 'password': 'mgrpw'}
Once an acceptable referer has been passed in, the credentials are always
returned:
>>> del request._environ['HTTP_REFERER']
>>> creds.extractCredentials(request)
{'login': 'mgr', 'password': 'mgrpw'}
We have to log out in order to loose the credentials:
>>> creds.logout(request)
True
Now, no credentials are returned when not sending in a correct referer:
>>> creds.extractCredentials(request)
When the user could not be authenticated, the plugin is asked to pose a
challenge:
>>> creds.challenge(request)
True
>>> request.response.getHeader('Redirect')
By default we are getting the "unauthorized.html" view on the site. But you
can change the view name:
>>> creds.challengeView = 'challenge.html'
>>> creds.challenge(request)
True
>>> request.response.getHeader('Redirect')
Final Note: Of course, this credentials plugin only works with HTTP-based
requests:
>>> request = object()
>>> creds.extractCredentials(request)
>>> creds.challenge(request)
False
>>> creds.logout(request)
False
| z3c.referercredentials | /z3c.referercredentials-0.1.0.tar.gz/z3c.referercredentials-0.1.0/src/z3c/referercredentials/README.txt | README.txt |
__docformat__ = "reStructuredText"
import persistent
import transaction
import urllib2
import zope.interface
from zope.app.component import hooks
from zope.app.container import contained
from zope.app.session.interfaces import ISession
from zope.publisher.interfaces.http import IHTTPRequest
from zope.traversing.browser import absoluteURL
from z3c.referercredentials import interfaces
class HTTPRefererCredentials(persistent.Persistent, contained.Contained):
zope.interface.implements(interfaces.IHTTPRefererCredentials)
sessionKey = 'z3c.referercredentials'
allowedHosts = ('localhost',)
credentials = None
challengeView = 'unauthorized.html'
def extractCredentials(self, request):
"""See zope.app.authentication.interfaces.ICredentialsPlugin"""
# Step 0: This credentials plugin only works for HTTP request
if not IHTTPRequest.providedBy(request):
return None
# Step 1: If the referer hostname matches
url = request.getHeader('Referer', '')
host = urllib2.splithost(urllib2.splittype(url)[-1])[0]
if host in self.allowedHosts:
ISession(request)[self.sessionKey]['authenticated'] = True
# Step 2: If the "authenticated" flag is set, return the
# pre-determined credentials."
if ISession(request)[self.sessionKey].get('authenticated'):
return self.credentials
return None
def challenge(self, request):
"""See zope.app.authentication.interfaces.ICredentialsPlugin"""
# Step 0: This credentials plugin only works for HTTP request
if not IHTTPRequest.providedBy(request):
return False
# Step 1: Produce a URL and redirect to it
site = hooks.getSite()
url = '%s/@@%s' % (absoluteURL(site, request), self.challengeView)
request.response.redirect(url)
return True
def logout(self, request):
"""See zope.app.authentication.interfaces.ICredentialsPlugin"""
# Step 0: This credentials plugin only works for HTTP request
if not IHTTPRequest.providedBy(request):
return False
# Step 1: Delete the session variable.
del ISession(request)[self.sessionKey]['authenticated']
transaction.commit()
return True | z3c.referercredentials | /z3c.referercredentials-0.1.0.tar.gz/z3c.referercredentials-0.1.0/src/z3c/referercredentials/credentials.py | credentials.py |
from functools import total_ordering
from persistent import Persistent
from z3c.objpath.interfaces import IObjectPath
from zope import component
from zope.interface import Declaration
from zope.interface import implementer
from zope.interface import providedBy
from zope.intid.interfaces import IIntIds
from z3c.relationfield.interfaces import IRelationValue
from z3c.relationfield.interfaces import ITemporaryRelationValue
@implementer(IRelationValue)
@total_ordering
class RelationValue(Persistent):
_broken_to_path = None
def __init__(self, to_id):
self.to_id = to_id
# these will be set automatically by events
self.from_object = None
self.__parent__ = None
self.from_attribute = None
def __hash__(self):
"""There should only be one RelationVaule per sort_key."""
return id(self) // 16
@property
def from_id(self):
intids = component.getUtility(IIntIds)
return intids.getId(self.from_object)
@property
def from_path(self):
return _path(self.from_object)
@property
def from_interfaces(self):
return providedBy(self.from_object)
@property
def from_interfaces_flattened(self):
return _interfaces_flattened(self.from_interfaces)
@property
def to_object(self):
return _object(self.to_id)
@property
def to_path(self):
if self.to_object is None:
return self._broken_to_path
return _path(self.to_object)
@property
def to_interfaces(self):
return providedBy(self.to_object)
@property
def to_interfaces_flattened(self):
return _interfaces_flattened(self.to_interfaces)
def __eq__(self, other):
if not isinstance(other, RelationValue):
return False
self_sort_key = self._sort_key()
other_sort_key = other._sort_key()
# if one of the relations we are comparing doesn't have a source
# yet, only compare targets. This is to make comparisons within
# ChoiceWidget work; a stored relation would otherwise not compare
# equal with a relation generated for presentation in the UI
if self_sort_key[0] is None or other_sort_key[0] is None:
return self_sort_key[-1] == other_sort_key[-1]
# otherwise do a full comparison
return self_sort_key == other_sort_key
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
"""Relations are sorted by default on a combination of the relation
name, the path of the object the relation is one and the path of the
object the relation is pointing to.
"""
if (self.from_attribute or '') < (other.from_attribute or ''):
return True
if (self.from_path or '') < (other.from_path or ''):
return True
if (self.to_path or '') < (other.to_path or ''):
return True
return False
def _sort_key(self):
return (self.from_attribute, self.from_path, self.to_path)
def broken(self, to_path):
self._broken_to_path = to_path
self.to_id = None
def isBroken(self):
return self.to_id is None or self.from_object is None
@implementer(ITemporaryRelationValue)
class TemporaryRelationValue(Persistent):
"""A relation that isn't fully formed yet.
It needs to be finalized afterwards, when we are sure all potential
target objects exist.
"""
def __init__(self, to_path):
self.to_path = to_path
def convert(self):
return create_relation(self.to_path)
def _object(id):
if id is None:
return None
intids = component.getUtility(IIntIds)
try:
return intids.getObject(id)
except KeyError:
# XXX catching this error is not the right thing to do.
# instead, breaking a relation by removing an object should
# be caught and the relation should be adjusted that way.
return None
def _path(obj):
if obj is None:
return ''
object_path = component.getUtility(IObjectPath)
return object_path.path(obj)
def _interfaces_flattened(interfaces):
return Declaration(*interfaces).flattened()
def create_relation(to_path):
"""Create a relation to a particular path.
Will create a broken relation if the path cannot be resolved.
"""
object_path = component.getUtility(IObjectPath)
try:
to_object = object_path.resolve(to_path)
intids = component.getUtility(IIntIds)
return RelationValue(intids.getId(to_object))
except ValueError:
# create broken relation
result = RelationValue(None)
result.broken(to_path)
return result | z3c.relationfield | /z3c.relationfield-1.1-py3-none-any.whl/z3c/relationfield/relation.py | relation.py |
z3c.relationfield
*****************
Introduction
============
This package implements a new schema field Relation, and the
RelationValue objects that store actual relations. It can index these
relations using the ``zc.relation`` infractructure, and using these
indexes can efficiently answer questions about the relations.
The package `z3c.relationfieldui`_ in addition provides a widget to
edit and display Relation fields.
.. _`z3c.relationfieldui`: http://pypi.python.org/pypi/z3c.relationfieldui
Setup
=====
``z3c.relationfield.Relation`` is a schema field that can be used to
express relations. Let's define a schema IItem that uses a relation
field:
.. code-block:: python
>>> from z3c.relationfield import Relation
>>> from zope.interface import Interface
>>> class IItem(Interface):
... rel = Relation(title=u"Relation")
We also define a class ``Item`` that implements both ``IItem``
and the special ``z3c.relationfield.interfaces.IHasRelations``
interface:
.. code-block:: python
>>> from z3c.relationfield.interfaces import IHasRelations
>>> from persistent import Persistent
>>> from zope.interface import implementer
>>> @implementer(IItem, IHasRelations)
... class Item(Persistent):
...
... def __init__(self):
... self.rel = None
The ``IHasRelations`` marker interface is needed to let the relations
on ``Item`` be cataloged (when they are put in a container and removed
from it, for instance). It is in fact a combination of
``IHasIncomingRelations`` and ``IHasOutgoingRelations``, which is fine
as we want items to support both.
Finally we need a test application:
.. code-block:: python
>>> from zope.site.site import SiteManagerContainer
>>> from zope.container.btree import BTreeContainer
>>> class TestApp(SiteManagerContainer, BTreeContainer):
... pass
We set up the test application:
.. code-block:: python
>>> from ZODB.MappingStorage import DB
>>> db = DB()
>>> conn = db.open()
>>> root = conn.root()['root'] = TestApp()
>>> conn.add(root)
We make sure that this is the current site, so we can look up local
utilities in it and so on. Normally this is done automatically by
Zope's traversal mechanism:
.. code-block:: python
>>> from zope.site.site import LocalSiteManager
>>> root.setSiteManager(LocalSiteManager(root))
>>> from zope.component.hooks import setSite
>>> setSite(root)
For this site to work with ``z3c.relationship``, we need to set up two
utilities. Firstly, an ``IIntIds`` that tracks unique ids for objects
in the ZODB:
.. code-block:: python
>>> from zope.intid import IntIds
>>> from zope.intid.interfaces import IIntIds
>>> root['intids'] = intids = IntIds()
>>> sm = root.getSiteManager()
>>> sm.registerUtility(intids, provided=IIntIds)
And secondly a relation catalog that actually indexes the relations:
.. code-block:: python
>>> from z3c.relationfield import RelationCatalog
>>> from zc.relation.interfaces import ICatalog
>>> root['catalog'] = catalog = RelationCatalog()
>>> sm.registerUtility(catalog, provided=ICatalog)
Using the relation field
========================
We'll add an item ``a`` to our application:
.. code-block:: python
>>> root['a'] = Item()
All items, including the one we just created, should have unique int
ids as this is required to link to them:
.. code-block:: python
>>> from zope import component
>>> from zope.intid.interfaces import IIntIds
>>> intids = component.getUtility(IIntIds)
>>> a_id = intids.getId(root['a'])
>>> a_id >= 0
True
The relation is currently ``None``:
.. code-block:: python
>>> root['a'].rel is None
True
Now we can create an item ``b`` that links to item ``a`` (through its
int id):
.. code-block:: python
>>> from z3c.relationfield import RelationValue
>>> b = Item()
>>> b.rel = RelationValue(a_id)
We now store the ``b`` object in a container, which will also set up
its relation (as an ``IObjectAddedEvent`` will be fired):
.. code-block:: python
>>> root['b'] = b
Let's examine the relation. First we'll check which attribute of the
pointing object ('b') this relation is pointing from:
.. code-block:: python
>>> root['b'].rel.from_attribute
'rel'
We can ask for the object it is pointing at:
.. code-block:: python
>>> to_object = root['b'].rel.to_object
>>> to_object.__name__
'a'
We can also get the object that is doing the pointing; since we
supplied the ``IHasRelations`` interface, the event system took care
of setting this:
.. code-block:: python
>>> from_object = root['b'].rel.from_object
>>> from_object.__name__
'b'
This object is also known as the ``__parent__``; again the event
sytem took care of setting this:
.. code-block:: python
>>> parent_object = root['b'].rel.__parent__
>>> parent_object is from_object
True
The relation also knows about the interfaces of both the pointing object
and the object that is being pointed at:
.. code-block:: python
>>> from pprint import pprint
>>> pprint(sorted(root['b'].rel.from_interfaces))
[<InterfaceClass zope.location.interfaces.IContained>,
<InterfaceClass z3c.relationfield.interfaces.IHasRelations>,
<InterfaceClass builtins.IItem>,
<InterfaceClass persistent.interfaces.IPersistent>]
>>> pprint(sorted(root['b'].rel.to_interfaces))
[<InterfaceClass zope.location.interfaces.IContained>,
<InterfaceClass z3c.relationfield.interfaces.IHasRelations>,
<InterfaceClass builtins.IItem>,
<InterfaceClass persistent.interfaces.IPersistent>]
We can also get the interfaces in flattened form:
.. code-block:: python
>>> pprint(sorted(root['b'].rel.from_interfaces_flattened))
[<InterfaceClass zope.location.interfaces.IContained>,
<InterfaceClass z3c.relationfield.interfaces.IHasIncomingRelations>,
<InterfaceClass z3c.relationfield.interfaces.IHasOutgoingRelations>,
<InterfaceClass z3c.relationfield.interfaces.IHasRelations>,
<InterfaceClass builtins.IItem>,
<InterfaceClass zope.location.interfaces.ILocation>,
<InterfaceClass persistent.interfaces.IPersistent>,
<InterfaceClass zope.interface.Interface>]
>>> pprint(sorted(root['b'].rel.to_interfaces_flattened))
[<InterfaceClass zope.location.interfaces.IContained>,
<InterfaceClass z3c.relationfield.interfaces.IHasIncomingRelations>,
<InterfaceClass z3c.relationfield.interfaces.IHasOutgoingRelations>,
<InterfaceClass z3c.relationfield.interfaces.IHasRelations>,
<InterfaceClass builtins.IItem>,
<InterfaceClass zope.location.interfaces.ILocation>,
<InterfaceClass persistent.interfaces.IPersistent>,
<InterfaceClass zope.interface.Interface>]
Paths
=====
We can also obtain the path of the relation (both from where it is
pointing as well as to where it is pointing). The path should be a
human-readable reference to the object we are pointing at, suitable
for serialization. In order to work with paths, we first need to set
up an ``IObjectPath`` utility.
Since in this example we only place objects into a single flat root
container, the paths in this demonstration can be extremely simple:
just the name of the object we point to. In more sophisticated
applications a path would typically be a slash separated path, like
``/foo/bar``:
.. code-block:: python
>>> from zope.interface import Interface
>>> from zope.interface import implementer
>>> from z3c.objpath.interfaces import IObjectPath
>>> @implementer(IObjectPath)
... class ObjectPath(object):
...
... def path(self, obj):
... return obj.__name__
... def resolve(self, path):
... try:
... return root[path]
... except KeyError:
... raise ValueError("Cannot resolve path %s" % path)
>>> from zope.component import getGlobalSiteManager
>>> gsm = getGlobalSiteManager()
>>> op = ObjectPath()
>>> gsm.registerUtility(op)
After this, we can get the path of the object the relation points to:
.. code-block:: python
>>> root['b'].rel.to_path
'a'
We can also get the path of the object that is doing the pointing:
.. code-block:: python
>>> root['b'].rel.from_path
'b'
Comparing and sorting relations
===============================
Let's create a bunch of ``RelationValue`` objects and compare them:
.. code-block:: python
>>> rel_to_a = RelationValue(a_id)
>>> b_id = intids.getId(root['b'])
>>> rel_to_b = RelationValue(b_id)
>>> rel_to_a == rel_to_b
False
Relations of course are equal to themselves:
.. code-block:: python
>>> rel_to_a == rel_to_a
True
A relation that is stored is equal to a relation that isn't stored yet:
.. code-block:: python
>>> root['b'].rel == rel_to_a
True
We can also sort relations:
.. code-block:: python
>>> expected = [('', 'a'), ('', 'b'), ('b', 'a')]
>>> observed = [(rel.from_path, rel.to_path) for rel in
... sorted([root['b'].rel, rel_to_a, rel_to_b])]
>>> expected == observed
True
Relation queries
================
Now that we have set up and indexed a relationship between ``a`` and
``b``, we can issue queries using the relation catalog. Let's first
get the catalog:
.. code-block:: python
>>> from zc.relation.interfaces import ICatalog
>>> catalog = component.getUtility(ICatalog)
Let's ask the catalog about the relation from ``b`` to ``a``:
.. code-block:: python
>>> l = sorted(catalog.findRelations({'to_id': intids.getId(root['a'])}))
>>> l
[<...RelationValue object at ...>]
We look at this relation object again. We indeed go the right one:
.. code-block:: python
>>> rel = l[0]
>>> rel.from_object.__name__
'b'
>>> rel.to_object.__name__
'a'
>>> rel.from_path
'b'
>>> rel.to_path
'a'
Asking for relations to ``b`` will result in an empty list, as no such
relations have been set up:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': intids.getId(root['b'])}))
[]
We can also issue more specific queries, restricting it on the
attribute used for the relation field and the interfaces provided by
the related objects. Here we look for all relations between ``b`` and
``a`` that are stored in object attribute ``rel`` and are pointing
from an object with interface ``IItem`` to another object with the
interface ``IItem``:
.. code-block:: python
>>> sorted(catalog.findRelations({
... 'to_id': intids.getId(root['a']),
... 'from_attribute': 'rel',
... 'from_interfaces_flattened': IItem,
... 'to_interfaces_flattened': IItem}))
[<...RelationValue object at ...>]
There are no relations stored for another attribute:
.. code-block:: python
>>> sorted(catalog.findRelations({
... 'to_id': intids.getId(root['a']),
... 'from_attribute': 'foo'}))
[]
There are also no relations stored for a new interface we'll introduce
here:
.. code-block:: python
>>> class IFoo(IItem):
... pass
>>> sorted(catalog.findRelations({
... 'to_id': intids.getId(root['a']),
... 'from_interfaces_flattened': IItem,
... 'to_interfaces_flattened': IFoo}))
[]
Changing the relation
=====================
Let's create a new object ``c``:
.. code-block:: python
>>> root['c'] = Item()
>>> c_id = intids.getId(root['c'])
Nothing points to ``c`` yet:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': c_id}))
[]
We currently have a relation from ``b`` to ``a``:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': intids.getId(root['a'])}))
[<...RelationValue object at ...>]
We can change the relation to point at a new object ``c``:
.. code-block:: python
>>> root['b'].rel = RelationValue(c_id)
We need to send an ``IObjectModifiedEvent`` to let the catalog know we
have changed the relations:
.. code-block:: python
>>> from zope.event import notify
>>> from zope.lifecycleevent import ObjectModifiedEvent
>>> notify(ObjectModifiedEvent(root['b']))
We should find now a single relation from ``b`` to ``c``:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': c_id}))
[<...RelationValue object at ...>]
The relation to ``a`` should now be gone:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': intids.getId(root['a'])}))
[]
If we store the relation in a non schema field it should persist
the ObjectModifiedEvent.
.. code-block:: python
>>> from z3c.relationfield.event import _setRelation
>>> _setRelation(root['b'], 'my-fancy-relation', rel_to_a)
>>> sorted(catalog.findRelations({'to_id': intids.getId(root['a'])}))
[<...RelationValue object at ...>]
>>> notify(ObjectModifiedEvent(root['b']))
>>> rel = sorted(catalog.findRelations({'to_id': intids.getId(root['a'])}))
>>> rel
[<...RelationValue object at ...>]
>>> catalog.unindex(rel[0])
Removing the relation
=====================
We have a relation from ``b`` to ``c`` right now:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': c_id}))
[<...RelationValue object at ...>]
We can clean up an existing relation from ``b`` to ``c`` by setting it
to ``None``:
.. code-block:: python
>>> root['b'].rel = None
We need to send an ``IObjectModifiedEvent`` to let the catalog know we
have changed the relations:
.. code-block:: python
>>> notify(ObjectModifiedEvent(root['b']))
Setting the relation on ``b`` to ``None`` should remove that relation
from the relation catalog, so we shouldn't be able to find it anymore:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': intids.getId(root['c'])}))
[]
Let's reestablish the removed relation:
.. code-block:: python
>>> root['b'].rel = RelationValue(c_id)
>>> notify(ObjectModifiedEvent(root['b']))
>>> sorted(catalog.findRelations({'to_id': c_id}))
[<...RelationValue object at ...>]
Copying an object with relations
================================
Let's copy an object with relations:
.. code-block:: python
>>> from zope.copypastemove.interfaces import IObjectCopier
>>> IObjectCopier(root['b']).copyTo(root)
'b-2'
>>> 'b-2' in root
True
Two relations to ``c`` can now be found, one from the original, and
the other from the copy:
.. code-block:: python
>>> l = sorted(catalog.findRelations({'to_id': c_id}))
>>> len(l)
2
>>> l[0].from_path
'b'
>>> l[1].from_path
'b-2'
Relations are sortable
======================
Relations are sorted by default on a combination of the relation name,
the path of the object the relation is one and the path of the object
the relation is pointing to.
Let's query all relations availble right now and sort them:
.. code-block:: python
>>> l = sorted(catalog.findRelations())
>>> len(l)
2
>>> l[0].from_attribute
'rel'
>>> l[1].from_attribute
'rel'
>>> l[0].from_path
'b'
>>> l[1].from_path
'b-2'
Removing an object with relations
=================================
We will remove ``b-2`` again. Its relation should automatically be remove
from the catalog:
.. code-block:: python
>>> del root['b-2']
>>> l = sorted(catalog.findRelations({'to_id': c_id}))
>>> len(l)
1
>>> l[0].from_path
'b'
Breaking a relation
===================
We have a relation from ``b`` to ``c`` right now:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': c_id}))
[<...RelationValue object at ...>]
We have no broken relations:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': None}))
[]
The relation isn't broken:
.. code-block:: python
>>> b.rel.isBroken()
False
We are now going to break this relation by removing ``c``:
.. code-block:: python
>>> del root['c']
The relation is broken now:
.. code-block:: python
>>> b.rel.isBroken()
True
The original relation still has a ``to_path``:
.. code-block:: python
>>> b.rel.to_path
'c'
It's broken however as there is no ``to_object``:
.. code-block:: python
>>> b.rel.to_object is None
True
The ``to_id`` is also gone:
.. code-block:: python
>>> b.rel.to_id is None
True
We cannot find the broken relation in the catalog this way as it's not
pointing to ``c_id`` anymore:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': c_id}))
[]
We can however find it by searching for relations that have a
``to_id`` of ``None``:
.. code-block:: python
>>> sorted(catalog.findRelations({'to_id': None}))
[<...RelationValue object at ...>]
A broken relation isn't equal to ``None`` (this was a bug):
.. code-block:: python
>>> b.rel == None
False
RelationChoice
==============
A ``RelationChoice`` field is much like an ordinary ``Relation`` field
but can be used to render a special widget that allows a choice of
selections.
We will first demonstrate a ``RelationChoice`` field has the same effect
as a ``Relation`` field itself:
.. code-block:: python
>>> from z3c.relationfield import RelationChoice
>>> class IChoiceItem(Interface):
... rel = RelationChoice(title=u"Relation", values=[])
>>> @implementer(IChoiceItem, IHasRelations)
... class ChoiceItem(Persistent):
...
... def __init__(self):
... self.rel = None
Let's create an object to point the relation to:
.. code-block:: python
>>> root['some_object'] = Item()
>>> some_object_id = intids.getId(root['some_object'])
And let's establish the relation:
:.. code-block:: python
>>> choice_item = ChoiceItem()
>>> choice_item.rel = RelationValue(some_object_id)
>>> root['choice_item'] = choice_item
We can query for this relation now:
.. code-block:: python
>>> l = sorted(catalog.findRelations({'to_id': some_object_id}))
>>> l
[<...RelationValue object at ...>]
RelationList
============
Let's now experiment with the ``RelationList`` field which can be used
to maintain a list of relations:
.. code-block:: python
>>> from z3c.relationfield import RelationList
>>> class IMultiItem(Interface):
... rel = RelationList(title=u"Relation")
We also define a class ``MultiItem`` that implements both
``IMultiItem`` and the special
``z3c.relationfield.interfaces.IHasRelations`` interface:
.. code-block:: python
>>> @implementer(IMultiItem, IHasRelations)
... class MultiItem(Persistent):
...
... def __init__(self):
... self.rel = None
We set up a few object we can then create relations between:
.. code-block:: python
>>> root['multi1'] = MultiItem()
>>> root['multi2'] = MultiItem()
>>> root['multi3'] = MultiItem()
Let's create a relation from ``multi1`` to both ``multi2`` and
``multi3``:
.. code-block:: python
>>> multi1_id = intids.getId(root['multi1'])
>>> multi2_id = intids.getId(root['multi2'])
>>> multi3_id = intids.getId(root['multi3'])
>>> root['multi1'].rel = [RelationValue(multi2_id),
... RelationValue(multi3_id)]
We need to notify that we modified the ObjectModifiedEvent
.. code-block:: python
>>> notify(ObjectModifiedEvent(root['multi1']))
Now that this is set up, let's verify whether we can find the
proper relations in in the catalog:
.. code-block:: python
>>> len(list(catalog.findRelations({'to_id': multi2_id})))
1
>>> len(list(catalog.findRelations({'to_id': multi3_id})))
1
>>> len(list(catalog.findRelations({'from_id': multi1_id})))
2
Temporary relations
===================
If we have an import procedure where we import relations from some
external source such as an XML file, it may be that we read a relation
that points to an object that does not yet exist as it is yet to be
imported. We provide a special ``TemporaryRelationValue`` for this
case. A ``TemporaryRelationValue`` just contains the path of what it
is pointing to, but does not resolve it yet. Let's use
``TemporaryRelationValue`` in a new object, creating a relation to
``a``:
.. code-block:: python
>>> from z3c.relationfield import TemporaryRelationValue
>>> root['d'] = Item()
>>> root['d'].rel = TemporaryRelationValue('a')
A modification event does not actually get this relation cataloged:
.. code-block:: python
>>> before = sorted(catalog.findRelations({'to_id': a_id}))
>>> notify(ObjectModifiedEvent(root['d']))
>>> after = sorted(catalog.findRelations({'to_id': a_id}))
>>> len(before) == len(after)
True
We will now convert all temporary relations on ``d`` to real ones:
.. code-block:: python
>>> from z3c.relationfield import realize_relations
>>> realize_relations(root['d'])
>>> notify(ObjectModifiedEvent(root['d']))
We can see the real relation object now:
.. code-block:: python
>>> root['d'].rel
<...RelationValue object at ...>
The relation will also now show up in the catalog:
.. code-block:: python
>>> after2 = sorted(catalog.findRelations({'to_id': a_id}))
>>> len(after2) > len(before)
True
Temporary relation values also work with ``RelationList`` objects:
.. code-block:: python
>>> root['multi_temp'] = MultiItem()
>>> root['multi_temp'].rel = [TemporaryRelationValue('a')]
Let's convert this to a real relation:
.. code-block:: python
>>> realize_relations(root['multi_temp'])
>>> notify(ObjectModifiedEvent(root['multi_temp']))
Again we can see the real relation object when we look at it:
.. code-block:: python
>>> root['multi_temp'].rel
[<...RelationValue object at ...>]
And we will now see this new relation appear in the catalog:
.. code-block:: python
>>> after3 = sorted(catalog.findRelations({'to_id': a_id}))
>>> len(after3) > len(after2)
True
Broken temporary relations
==========================
Let's create another temporary relation, this time a broken one that
cannot be resolved:
.. code-block:: python
>>> root['e'] = Item()
>>> root['e'].rel = TemporaryRelationValue('nonexistent')
Let's try realizing this relation:
.. code-block:: python
>>> realize_relations(root['e'])
We end up with a broken relation:
.. code-block:: python
>>> root['e'].rel.isBroken()
True
It's pointing to the nonexistent path:
.. code-block:: python
>>> root['e'].rel.to_path
'nonexistent'
Setting up a releation catalog
==============================
This package provides a RelationCatalog initialized with a set of indexes commonly useful for queries on RelationValue objects.
The default indexes are `from_id`, `to_id`, `from_attribute`, `from_interfaces_flattened` and `to_interfaces_flattened`.
Sometimes it is needed to define custom indexes or use less than the default ones.
The `zc.relationfield.index.RelationCatalog` class can be initialized with a list of dicts with keys `element` and `kwargs` to be passed to RelationCatalog `addValueIndex` method.
As `element` in general the attribute on the `IRelationValue` like `IRelationValue['from_id']` is expected.
However, if theres a subclass of `IRelationValue` is used with additional fields, those fields can be added here as indexes.
| z3c.relationfield | /z3c.relationfield-1.1-py3-none-any.whl/z3c/relationfield/README.rst | README.rst |
from zc.relation.interfaces import ICatalog
from zope import component
from zope.event import notify
from zope.interface import implementer
from zope.interface import providedBy
from zope.intid.interfaces import IIntIds
from zope.lifecycleevent import ObjectModifiedEvent
from zope.schema import getFields
from z3c.relationfield.interfaces import IHasIncomingRelations
from z3c.relationfield.interfaces import IHasOutgoingRelations
from z3c.relationfield.interfaces import IRelation
from z3c.relationfield.interfaces import IRelationBrokenEvent
from z3c.relationfield.interfaces import IRelationList
from z3c.relationfield.interfaces import IRelationValue
from z3c.relationfield.interfaces import ITemporaryRelationValue
@implementer(IRelationBrokenEvent)
class RelationBrokenEvent(ObjectModifiedEvent):
__doc__ = IRelationBrokenEvent.__doc__
def addRelations(obj, event):
"""Register relations.
Any relation object on the object will be added.
"""
for name, relation in _relations(obj):
_setRelation(obj, name, relation)
# zope.intid dispatches a normal event, so we need to check that
# the object has relations. This adds a little overhead to every
# intid registration, which would not be needed if an object event
# were dispatched in zope.intid.
def addRelationsEventOnly(event):
obj = event.object
if not IHasOutgoingRelations.providedBy(obj):
return
addRelations(obj, event)
def removeRelations(obj, event):
"""Remove relations.
Any relation object on the object will be removed from the catalog.
"""
catalog = component.queryUtility(ICatalog)
if catalog is None:
return
for name, relation in _relations(obj):
if relation is not None:
try:
catalog.unindex(relation)
except KeyError:
# The relation value has already been unindexed.
pass
def updateRelations(obj, event):
"""Re-register relations, after they have been changed.
"""
catalog = component.queryUtility(ICatalog)
intids = component.queryUtility(IIntIds)
if catalog is None or intids is None:
return
# check that the object has an intid, otherwise there's nothing to be done
try:
obj_id = intids.getId(obj)
except KeyError:
# The object has not been added to the ZODB yet
return
# remove previous relations coming from id (now have been overwritten) have
# to activate query here with list() before unindexing them so we don't get
# errors involving buckets changing size
rels = list(catalog.findRelations({'from_id': obj_id}))
for rel in rels:
if hasattr(obj, rel.from_attribute):
catalog.unindex(rel)
# add new relations
addRelations(obj, event)
def breakRelations(event):
"""Break relations on any object pointing to us.
That is, store the object path on the broken relation.
"""
obj = event.object
if not IHasIncomingRelations.providedBy(obj):
return
catalog = component.queryUtility(ICatalog)
intids = component.queryUtility(IIntIds)
if catalog is None or intids is None:
return
# find all relations that point to us
try:
obj_id = intids.getId(obj)
except KeyError:
# our intid was unregistered already
return
rels = list(catalog.findRelations({'to_id': obj_id}))
for rel in rels:
rel.broken(rel.to_path)
# we also need to update the relations for these objects
notify(RelationBrokenEvent(rel.from_object))
def realize_relations(obj):
"""Given an object, convert any temporary relations on it to real ones.
"""
for name, index, relation in _potential_relations(obj):
if ITemporaryRelationValue.providedBy(relation):
if index is None:
# relation
setattr(obj, name, relation.convert())
else:
# relation list
getattr(obj, name)[index] = relation.convert()
def _setRelation(obj, name, value):
"""Set a relation on an object.
Sets up various essential attributes on the relation.
"""
# if the Relation is None, we're done
if value is None:
return
# make sure relation has a __parent__ so we can make an intid for it
value.__parent__ = obj
# also set from_object to parent object
value.from_object = obj
# and the attribute to the attribute name
value.from_attribute = name
# now we can create an intid for the relation
intids = component.getUtility(IIntIds)
id = intids.register(value)
# and index the relation with the catalog
catalog = component.getUtility(ICatalog)
catalog.index_doc(id, value)
def _relations(obj):
"""Given an object, return tuples of name, relation value.
Only real relations are returned, not temporary relations.
"""
for name, index, relation in _potential_relations(obj):
if IRelationValue.providedBy(relation):
yield name, relation
def _potential_relations(obj):
"""Given an object return tuples of name, index, relation value.
Returns both IRelationValue attributes as well as ITemporaryRelationValue
attributes.
If this is a IRelationList attribute, index will contain the index
in the list. If it's a IRelation attribute, index will be None.
"""
for iface in providedBy(obj).flattened():
for name, field in getFields(iface).items():
if IRelation.providedBy(field):
try:
relation = getattr(obj, name)
except AttributeError:
# can't find this relation on the object
continue
yield name, None, relation
if IRelationList.providedBy(field):
try:
l_ = getattr(obj, name)
except AttributeError:
# can't find the relation list on this object
continue
if l_ is not None:
for i, relation in enumerate(l_):
yield name, i, relation | z3c.relationfield | /z3c.relationfield-1.1-py3-none-any.whl/z3c/relationfield/event.py | event.py |
from zope.interface import Attribute
from zope.interface import Interface
from zope.lifecycleevent.interfaces import IObjectModifiedEvent
from zope.schema.interfaces import IField
from zope.schema.interfaces import IList
class IHasOutgoingRelations(Interface):
"""Marker interface indicating that the object has outgoing relations.
Provide this interface on your own objects with outgoing relations
to make sure that the relations get added and removed from the
catalog when appropriate.
"""
class IHasIncomingRelations(Interface):
"""Marker interface indicating the the object has incoming relations.
Provide this interface on your own objects with incoming
relations. This will make sure that broken relations to that
object are tracked properly.
"""
class IHasRelations(IHasIncomingRelations, IHasOutgoingRelations):
"""Marker interface indicating that the object has relations of any kind.
Provide this interface if the object can have both outgoing as
well as incoming relations.
"""
class IRelation(IField):
"""Simple one to one relations.
"""
class IRelationChoice(IRelation):
"""A one to one relation where a choice of target objects is available.
"""
class IRelationList(IList):
"""A one to many relation.
"""
class IRelationValue(Interface):
"""A relation between the parent object and another one.
This should be stored as the value in the object when the schema uses the
Relation field.
"""
from_object = Attribute("The object this relation is pointing from.")
from_id = Attribute("Id of the object this relation is pointing from.")
from_path = Attribute("The path of the from object.")
from_interfaces = Attribute("The interfaces of the from object.")
from_interfaces_flattened = Attribute(
"Interfaces of the from object, flattened. "
"This includes all base interfaces.")
from_attribute = Attribute("The name of the attribute of the from object.")
to_object = Attribute("The object this relation is pointing to. "
"This value is None if the relation is broken.")
to_id = Attribute("Id of the object this relation is pointing to. "
"This value is None if the relation is broken.")
to_path = Attribute("The path of the object this relation is pointing to. "
"If the relation is broken, this value will still "
"point to the last path the relation pointed to.")
to_interfaces = Attribute("The interfaces of the to-object.")
to_interfaces_flattened = Attribute(
"The interfaces of the to object, flattened. "
"This includes all base interfaces.")
def broken(to_path):
"""Set this relation as broken.
to_path - the (non-nonexistent) path that the relation pointed to.
The relation will be broken. If you provide
IHasIncomingRelations on objects that have incoming relations,
relations will be automatically broken when you remove an
object.
"""
def isBroken():
"""Return True if this is a broken relation.
"""
class ITemporaryRelationValue(Interface):
"""A temporary relation.
When importing relations from XML, we cannot resolve them into
true RelationValue objects yet, as it may be that the object that is
being related to has not yet been loaded. Instead we create
a TemporaryRelationValue object that can be converted into a real one
after the import has been concluded.
"""
def convert():
"""Convert temporary relation into a real one.
Returns real relation object
"""
class IRelationBrokenEvent(IObjectModifiedEvent):
"""
Event that is triggered when relation is broken.
""" | z3c.relationfield | /z3c.relationfield-1.1-py3-none-any.whl/z3c/relationfield/interfaces.py | interfaces.py |
import grokcore.component as grok
from xml.sax.saxutils import escape
from zope.app.form.interfaces import IInputWidget, IDisplayWidget
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.app.form.browser import TextWidget, DisplayWidget
from zope import component
from zope.component.interfaces import ComponentLookupError
from zope.app.form.browser.widget import renderElement
from zope.app.form.browser.interfaces import ISimpleInputWidget
from zope.app.form.browser import ChoiceInputWidget
from zope.traversing.browser import absoluteURL
from z3c.objpath.interfaces import IObjectPath
from hurry.resource import Library, ResourceInclusion
from z3c.relationfield.schema import IRelation, IRelationChoice
from z3c.relationfield import create_relation
relation_lib = Library('z3c.relationfieldui')
relation_resource = ResourceInclusion(relation_lib, 'relation.js')
class RelationWidget(grok.MultiAdapter, TextWidget):
grok.adapts(IRelation, IBrowserRequest)
grok.provides(IInputWidget)
def __call__(self):
result = TextWidget.__call__(self)
explorer_url = component.getMultiAdapter((self.context.context,
self.request),
name="explorerurl")()
from_attribute = self.context.__name__
object_path = component.getUtility(IObjectPath)
from_path = object_path.path(self.context.context)
explorer_url += '?from_attribute=%s&from_path=%s' % (
from_attribute, from_path)
result += renderElement(
'input', type='button', value='get relation',
onclick="Z3C.relation.popup(this.previousSibling, '%s')" %
explorer_url)
relation_resource.need()
return result
def _toFieldValue(self, input):
if not input:
return None
return create_relation(input)
def _toFormValue(self, value):
if value is None:
return ''
return value.to_path
@grok.adapter(IRelationChoice, IBrowserRequest)
@grok.implementer(ISimpleInputWidget)
def RelationChoiceInputWidget(field, request):
return ChoiceInputWidget(field, request)
class RelationDisplayWidget(grok.MultiAdapter, DisplayWidget):
grok.adapts(IRelation, IBrowserRequest)
grok.provides(IDisplayWidget)
def __call__(self):
if self._renderedValueSet():
value = self._data
else:
value = self.context.default
if value == self.context.missing_value:
return ""
if value.isBroken():
return u"Broken relation to: %s" % value.to_path
to_object = value.to_object
try:
to_url = component.getMultiAdapter((to_object, self.request),
name="relationurl")()
except ComponentLookupError:
to_url = absoluteURL(to_object, self.request)
return '<a href="%s">%s</a>' % (
to_url,
escape(value.to_path)) | z3c.relationfieldui | /z3c.relationfieldui-0.5.tar.gz/z3c.relationfieldui-0.5/src/z3c/relationfieldui/widget.py | widget.py |
*******************
z3c.relationfieldui
*******************
This package implements a ``zope.formlib`` compatible widget for
relations as defined by `z3c.relationfield`_.
.. _`z3c.relationfield`: http://pypi.python.org/pypi/z3c.relationfield
This package does not provide a ``z3c.form`` widget for
``z3c.relationfield``, but it is hoped that will eventually be
developed as well (in another package).
Setup
=====
In order to demonstrate our widget, we need to first set up a relation
field (for the details of this see z3c.relationfield's
documentation)::
>>> from z3c.relationfield import Relation
>>> from zope.interface import Interface
>>> class IItem(Interface):
... rel = Relation(title=u"Relation")
>>> from z3c.relationfield.interfaces import IHasRelations
>>> from persistent import Persistent
>>> from zope.interface import implements
>>> class Item(Persistent):
... implements(IItem, IHasRelations)
... def __init__(self):
... self.rel = None
>>> from zope.app.component.site import SiteManagerContainer
>>> from zope.app.container.btree import BTreeContainer
>>> class TestApp(SiteManagerContainer, BTreeContainer):
... pass
Set up the application with the right utilities::
>>> root = getRootFolder()['root'] = TestApp()
>>> from zope.app.component.site import LocalSiteManager
>>> root.setSiteManager(LocalSiteManager(root))
>>> from zope.app.component.hooks import setSite
>>> setSite(root)
>>> from zope.app.intid import IntIds
>>> from zope.app.intid.interfaces import IIntIds
>>> root['intids'] = intids = IntIds()
>>> sm = root.getSiteManager()
>>> sm.registerUtility(intids, provided=IIntIds)
>>> from z3c.relationfield import RelationCatalog
>>> from zc.relation.interfaces import ICatalog
>>> root['catalog'] = catalog = RelationCatalog()
>>> sm.registerUtility(catalog, provided=ICatalog)
Items ``a`` and ``b`` with a relation from ``b`` to ``a``::
>>> root['a'] = Item()
>>> from z3c.relationfield import RelationValue
>>> b = Item()
>>> from zope import component
>>> from zope.app.intid.interfaces import IIntIds
>>> intids = component.getUtility(IIntIds)
>>> a_id = intids.getId(root['a'])
>>> b.rel = RelationValue(a_id)
>>> root['b'] = b
We also need to set up a utility that knows how to generate an object
path for a given object, and back::
>>> import grokcore.component as grok
>>> from z3c.objpath.interfaces import IObjectPath
>>> class ObjectPath(grok.GlobalUtility):
... grok.provides(IObjectPath)
... def path(self, obj):
... return obj.__name__
... def resolve(self, path):
... try:
... return root[path]
... except KeyError:
... raise ValueError("Cannot resolve: %s" % path)
>>> grok.testing.grok_component('ObjectPath', ObjectPath)
True
Let's also set up a broken relation::
>>> d = root['d'] = Item()
>>> d_id = intids.getId(root['d'])
>>> c = Item()
>>> c.rel = RelationValue(d_id)
>>> root['c'] = c
>>> del root['d']
>>> root['c'].rel.to_object is None
True
>>> root['c'].rel.isBroken()
True
The relation widget
===================
The relation widget can be looked up for a relation field. The widget
will render with a button that can be used to set the
relation. Pressing this button will show a pop up window. The URL
implementing the popup window is defined on a special view that needs
to be available on the context object (that the relation is defined
on). This view must be named "explorerurl". We'll provide one here::
>>> from zope.interface import Interface
>>> import grokcore.view
>>> class ExplorerUrl(grokcore.view.View):
... grok.context(Interface)
... def render(self):
... return 'http://grok.zope.org'
Now we can Grok the view::
>>> grok.testing.grok_component('ExplorerUrl', ExplorerUrl)
True
Let's take a look at the relation widget now::
>>> from zope.publisher.browser import TestRequest
>>> from z3c.relationfieldui import RelationWidget
>>> request = TestRequest()
>>> field = IItem['rel']
>>> bound = field.bind(root['b'])
>>> widget = RelationWidget(bound, request)
>>> widget.setRenderedValue(bound.get(root['b']))
>>> print widget()
<input class="textType" id="field.rel" name="field.rel" size="20" type="text" value="a" /><input class="buttonType" onclick="Z3C.relation.popup(this.previousSibling, 'http://grok.zope.org?from_attribute=rel&from_path=b')" type="button" value="get relation" />
Let's also try it with the broken relation::
>>> bound = field.bind(root['c'])
>>> widget = RelationWidget(bound, request)
>>> widget.setRenderedValue(bound.get(root['c']))
When we render the widget, the value is still correct (even though
it's broken)::
>>> print widget()
<input class="textType" id="field.rel" name="field.rel" size="20" type="text" value="d" /><input class="buttonType" onclick="Z3C.relation.popup(this.previousSibling, 'http://grok.zope.org?from_attribute=rel&from_path=c')" type="button" value="get relation" />
Relation Choice
===============
Let's examine the ``RelationChoice`` field from ``z3c.relationfield``. We
need to provide a source of possible relations for it, and we can do this
using the ``RelationSourceFactory``::
>>> from z3c.relationfieldui import RelationSourceFactory
>>> class MyRelationSourceFactory(RelationSourceFactory):
... def getTargets(self):
... return [root['a'], root['b'], root['c']]
In the source, we simply return an iterable of objects that are
possible relation targets.
Let's now create an object that makes use of this source::
>>> from z3c.relationfield import RelationChoice
>>> class IItemChoice(Interface):
... rel = RelationChoice(title=u"Relation", required=False,
... source=MyRelationSourceFactory())
We can now take a look at the widget, using ``ChoiceInputWidget``::
>>> from zope.app.form.browser import ChoiceInputWidget
>>> class ItemChoice(Persistent):
... implements(IItemChoice, IHasRelations)
... def __init__(self):
... self.rel = None
>>> root['choice_a'] = ItemChoice()
>>> field = IItemChoice['rel']
>>> bound = field.bind(root['choice_a'])
>>> widget = ChoiceInputWidget(bound, request)
Let's first render the widget without a particular rendered value set::
>>> print widget()
<div>
<div class="value">
<select id="field.rel" name="field.rel" size="1" >
<option selected="selected" value="">(no value)</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</div>
<input name="field.rel-empty-marker" type="hidden" value="1" />
</div>
Let's try it again with a value set as a relation to ``a``::
>>> choice_b = ItemChoice()
>>> choice_b.rel = RelationValue(a_id)
>>> root['choice_b'] = choice_b
>>> bound = field.bind(root['choice_b'])
>>> widget = ChoiceInputWidget(bound, request)
>>> widget.setRenderedValue(bound.get(root['b']))
When we look at the widget we see that this relation is indeed selected::
>>> print widget()
<div>
<div class="value">
<select id="field.rel" name="field.rel" size="1" >
<option value="">(no value)</option>
<option selected="selected" value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</div>
<input name="field.rel-empty-marker" type="hidden" value="1" />
</div>
Relation display widget
=======================
The display widget for relation will render a URL to the object it relates
to. What this URL will be exactly can be controlled by defining a view
on the object called "relationurl". Without such a view, the display
widget will link directly to the object::
>>> from z3c.relationfieldui import RelationDisplayWidget
>>> bound = field.bind(root['b'])
>>> widget = RelationDisplayWidget(bound, request)
>>> widget.setRenderedValue(bound.get(root['b']))
The widget will point to the plain URL of ``rel``'s ``to_object``::
>>> print widget()
<a href="http://127.0.0.1/root/a">a</a>
Now we register a special ``relationurl`` view::
>>> class RelationUrl(grokcore.view.View):
... grok.context(Interface)
... def render(self):
... return self.url('edit')
>>> grok.testing.grok_component('RelationUrl', RelationUrl)
True
We should now see a link postfixed with ``/edit``::
>>> print widget()
<a href="http://127.0.0.1/root/a/edit">a</a>
When the relation is broken, it will still display, but as broken::
>>> bound = field.bind(root['c'])
>>> widget = RelationDisplayWidget(bound, request)
>>> widget.setRenderedValue(bound.get(root['c']))
>>> print widget()
Broken relation to: d
| z3c.relationfieldui | /z3c.relationfieldui-0.5.tar.gz/z3c.relationfieldui-0.5/src/z3c/relationfieldui/README.txt | README.txt |
if (typeof Z3C == "undefined" || !Z3C) {
var Z3C = {};
}
// create a new namespace (under Z3C)
Z3C.namespace = function(name) {
var ns = Z3C;
var parts = name.split(".");
if (parts[0] == "Z3C") {
parts = parts.slice(1);
}
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
ns[part] = ns[part] || {};
ns = ns[part];
}
return ns;
};
(function() {
Z3C.namespace('relation');
var winwidth = 750;
var winheight = 500;
var window_id = 0;
var features2string = function(features) {
var features_l = [];
for (key in features) {
if (!features.hasOwnProperty(key)) {
continue;
}
features_l.push(key + '=' + features[key]);
};
return features_l.join(',');
}
Z3C.relation.RelationCreator = function(el, url) {
this._el = el;
this._url = url;
};
Z3C.relation.RelationCreator.prototype.show = function() {
var leftpos = (screen.width - winwidth) / 2;
var toppos = (screen.height - winheight) / 2;
var features = {
'toolbar': 'yes',
'status': 'yes',
'scrollbars': 'yes',
'resizeable': 'yes',
'width': winwidth,
'height': winheight,
'left': leftpos,
'top': toppos
};
this._win = window.open(this._url, 'relation_window_' + window_id,
features2string(features));
this._win.focus();
// the popup window has to call call relation_creator.setRelations
// with a list of strings to set the relations
this._win.relation_creator = this;
// increase window id so we open a new window each time
window_id++;
};
Z3C.relation.RelationCreator.prototype.setRelations = function(values) {
if (values.length > 0) {
this._el.value = values[0];
}
// break potential circular reference
this._win.relation_creator = null;
this._win.close();
};
Z3C.relation.popup = function(el, url) {
var o = new Z3C.relation.RelationCreator(el, url);
o.show();
};
})(); | z3c.relationfieldui | /z3c.relationfieldui-0.5.tar.gz/z3c.relationfieldui-0.5/src/z3c/relationfieldui/resources/relation.js | relation.js |
=================
z3c.repoexternals
=================
Use the --help option for usage details::
usage: repoexternals [options] url_or_path
Recursively retrieves subversion directory listings from the url or
path and matches directories against a previous set of svn:externals
if provided then against regular expressions and generates
qualifying svn:externals lines. The defaults generate a set of
svn:externals for all the trunks in a repository and keeps them up
to date with the repository as new trunks are added when the
previous externals are provided thereafter.
options:
-h, --help show this help message and exit
-v, --verbose Output logging to standard error. Set twice
to log debugging messages.
-p FILE, --previous=FILE
If provided, only URLs in the repository not
included in the previous externals will be
included. If the filename is '-', use
standard input. Valid svn:externals lines
beginning with one comment character, '#',
will also affect output. This is useful,
for example, to prevent lengthy recursions
into directories that are known not to
contain any desired matches. The file is
read completely and closed before anything
is output, so it is safe to append output to
the previous file:
"repoexternals -p EXTERNALS.txt http://svn.foo.org/repos/main >>EXTERNALS.txt".
-i REGEXP, --include=REGEXP
Directory names matching this python regular
expression will be included in output and
will not be descended into.
[default: (?i)^((.*)/.+?|.*)/trunk$]
-e REGEXP, --exclude=REGEXP
Directory names matching this python regular
expression will be excluded from output and
will not be descended into. Include
overrides exclude. [default:
(?i)^.*/(branch(es)?|tags?|releases?|vendor|bundles?|sandbox|build|dist)$]
-m TEMPLATE, --matched-template=TEMPLATE
The result of expanding previous file URL
matches with the include regular expression
through this template is added to the set of
previous URLs excluded from output and
descending. The default will add the
parents of trunks to the set of previous
URLs excluded. [default: \1]
-t TEMPLATE, --parent-template=TEMPLATE
The result of expanding previous file URL
matches with the include regular expression
through this template is removed from the
set of matched previous URLs excluded from
output and descending. The default ensures
that directories containing trunks within a
directory that contains a trunk are not
excluded. [default: \2]
-d INT, --depth=INT The maximum directory depth to descend to.
WARNING: large values can greatly increase
run time. [default: 5]
-s INT, --pool-size=INT
The number of concurrent svn clients.
WARNING: large values can DOS the
repository. [default: 5]
The source distribution is also a zc.buildout that installs the script
locally for use without affecting the system python installation::
$ easy_install --editable --build-directory=foo z3c.repoexternals
$ cd foo
$ python bootstrap/bootstrap.py -v
$ ./bin/buildout -v
$ ./bin/repoexternals --help | z3c.repoexternals | /z3c.repoexternals-0.3.tar.gz/z3c.repoexternals-0.3/README.txt | README.txt |
import sys, os, re, logging, thread, threading, Queue, optparse
import pysvn
usage = "usage: %prog [options] url_or_path"
parser = optparse.OptionParser(usage=usage, description=__doc__)
parser.add_option(
"-v", "--verbose", action="count",
help=("Output logging to standard error. Set twice to log "
"debugging messages."))
parser.add_option(
"-p", "--previous", metavar='FILE',
help=("""If provided, only URLs in the repository not
included in the previous externals will be included. If the filename
is '-', use standard input. Valid svn:externals lines beginning with
one comment character, '#', will also affect output. This is useful,
for example, to prevent lengthy recursions into directories that are
known not to contain any desired matches. The file is read completely
and closed before anything is output, so it is safe to append output
to the previous file: "repoexternals -p EXTERNALS.txt
http://svn.foo.org/repos/main >>EXTERNALS.txt"."""))
include = r'(?i)^((.*)/.+?|.*)/trunk$'
parser.add_option(
"-i", "--include", default=include, metavar='REGEXP',
help=("Directory names matching this python regular expression "
"will be included in output and will not be descended into."
" [default: %default]"))
exclude = (r'(?i)^.*/(branch(es)?|tags?|releases?|vendor|bundles?'
r'|sandbox|build|dist)$')
parser.add_option(
"-e", "--exclude", default=exclude, metavar='REGEXP',
help=("Directory names matching this python regular expression "
"will be excluded from output and will not be descended "
"into. Include overrides exclude. [default: %default]"))
matched_template = r'\1'
parser.add_option(
"-m", "--matched-template", default=matched_template,
metavar='TEMPLATE',
help=("""The result of expanding previous file URL matches with
the include regular expression through this template is added to the
set of previous URLs excluded from output and descending. The default
will add the parents of trunks to the set of previous URLs
excluded. [default: %default]"""))
parent_template = r'\2'
parser.add_option(
"-t", "--parent-template", default=parent_template,
metavar='TEMPLATE',
help=("""The result of expanding previous file URL matches with
the include regular expression through this template is removed from
the set of matched previous URLs excluded from output and descending.
The default ensures that directories containing trunks within a
directory that contains a trunk are not excluded.
[default: %default]"""))
depth = 5
parser.add_option(
"-d", "--depth", type="int", default=depth, metavar='INT',
help=("The maximum directory depth to descend to. WARNING: "
"large values can greatly increase run time. "
"[default: %default]"))
pool_size = 5
parser.add_option(
"-s", "--pool-size", type="int", default=pool_size, metavar='INT',
help=("The number of concurrent svn clients. WARNING: large "
"values can DOS the repository. [default: %default]"))
shutdown = object()
class Thread(threading.Thread):
def __init__(self, queue=None, results=None, **kwargs):
super(Thread, self).__init__(**kwargs)
if queue is None:
queue = Queue.Queue()
if results is None:
results = Queue.Queue()
self.queue = queue
self.results = results
def run(self):
try:
payload = self.queue.get()
while payload is not shutdown:
payload(self)
payload = self.queue.get()
except:
thread.interrupt_main()
raise
def shutdown(self):
self.queue.put(shutdown)
self.join()
def interrupt(self):
self.queue.mutex.acquire()
self.queue._init(self.queue.maxsize)
self.queue._put(shutdown)
self.queue.not_empty.notify()
self.queue.mutex.release()
self.join()
class ClientThread(Thread):
def __init__(self, *args, **kwargs):
super(ClientThread, self).__init__(*args, **kwargs)
self.client = pysvn.Client()
class ClientPool(Queue.Queue):
def __init__(self, size=pool_size, results=None,
**kwargs):
Queue.Queue.__init__(self, **kwargs)
if results is None:
results = Queue.Queue()
self.results = results
self.threads = [
ClientThread(queue=self, results=self.results)
for ignored in xrange(size)]
def start(self):
for thread in self.threads:
thread.start()
logging.getLogger('repoexternals').debug(
'Started %s client threads' % len(self.threads))
def shutdown(self):
for thread in self.threads:
self.put(shutdown)
for thread in self.threads:
thread.join()
def interrupt(self):
self.mutex.acquire()
self._init(self.maxsize)
for thread in self.threads:
self._put(shutdown)
self.not_empty.notify()
self.mutex.release()
for thread in self.threads:
if thread.isAlive():
thread.join()
class Root(object):
"""Return self unless overridden in a child instance"""
def __get__(self, instance, owner):
return instance
class Line(object):
def __init__(self, path, dirent):
self.path = path
self.dirent = dirent
def __str__(self):
return '%s %s' % (self.path, self.dirent.path)
class Listing(object):
"""A single svn listing"""
def __init__(self, url, include=include, exclude=exclude,
depth=depth):
self.url = url
self.include = re.compile(include)
self.exclude = re.compile(exclude)
self.depth = depth
self.results = Queue.Queue()
def list(self, thread):
"""Retrieve the svn listing from the repository"""
try:
self.listing = thread.client.list(
self.url, dirent_fields=pysvn.SVN_DIRENT_KIND)
except pysvn.ClientError, e:
logging.getLogger('repoexternals').exception(
'pysvn.ClientError %s' % self.url)
self.listing = []
# Queue for processing
thread.results.put(self.process)
root = Root()
def getchild(self, url):
"""Create and return a child listing setting it's root"""
child = Listing(url, include=self.include,
exclude=self.exclude, depth=self.depth)
child.root = self.root
return child
def process(self, thread):
"""Process the results of the svn listing"""
# Use local names in the inner loop
dir_node_kind = pysvn.node_kind.dir
root_url = self.root.url
include_match = self.include.match
exclude_match = self.exclude.match
results_put = self.results.put
lLine = Line
info = logging.getLogger('repoexternals').info
depth = self.depth
getchild = self.getchild
thread_results_put = thread.results.put
previous = self.root.previous
for dirent, ignored in self.listing[1:]:
if dirent.kind != dir_node_kind:
# externals can only be directories
continue
dirent_path = dirent.path
if dirent_path in previous:
info('In previous, skipping %s' % dirent_path)
continue
# No previous line, use matching
path = dirent_path[len(root_url):].lstrip('/')
if include_match(dirent_path) is not None:
# Include this line in the results
results_put(lLine(path=path, dirent=dirent))
elif exclude_match(dirent_path) is not None:
info('Excluding %s' % dirent_path)
elif len(path.split('/')) >= depth:
info('Too deep, skipping %s' % dirent_path)
else:
child = getchild(dirent_path)
info('Descending into %s' % dirent_path)
thread_results_put(child.list)
results_put(child)
# Let the iterator know we're done
results_put(shutdown)
def __iter__(self):
item = self.results.get()
while item is not shutdown:
if isinstance(item, Line):
yield item
else:
for child in item:
yield child
item = self.results.get()
# Match valid externals definitions in existing externals
external = re.compile(r'^\s*#?\s*([^#\s]+)\s(.*\s|)(\S+)\s*$')
def run(url, previous=(), include=include, exclude=exclude,
matched_template=matched_template,
parent_template=parent_template,
depth=depth, pool_size=pool_size):
pool = ClientPool(size=pool_size)
thread = Thread(queue=pool.results, results=pool)
pool.start()
thread.start()
try:
root = Listing(url, include=include, exclude=exclude,
depth=depth)
# Build the set of previous URLs
include_match = root.include.match
root.previous = set()
raw_add = root.previous.add
matched = set()
matched_add = matched.add
parents = set()
parents_add = parents.add
external_match = external.match
for line in previous:
match = external_match(line)
if match is not None:
# TODO: also use pysvn.Cliens.is_url to verify url
# validity?
line_url = match.group(3)
raw_add(line_url)
include_matched = include_match(line_url)
if include_matched is not None:
matched_add(
include_matched.expand(matched_template))
parents_add(
include_matched.expand(parent_template))
root.previous.update(matched.difference(parents))
pool.put(root.list)
for line in root:
yield line
except:
# TODO: can't find a way to test interrupt-ability
pool.interrupt()
thread.interrupt()
raise
else:
pool.shutdown()
thread.shutdown()
def main():
options, args = parser.parse_args()
if len(args) != 1:
parser.error("requires one url_or_path")
url, = args
if options.verbose is not None:
verbose = options.verbose <= 2 and options.verbose or 2
logging.basicConfig(level=logging.WARN - (verbose * 10))
previous = ()
if options.previous:
if options.previous == '-':
previous = sys.stdin
else:
previous = file(options.previous)
for line in run(url, previous, options.include, options.exclude,
options.matched_template, options.parent_template,
options.depth, options.pool_size):
print line
if __name__ == '__main__':
main() | z3c.repoexternals | /z3c.repoexternals-0.3.tar.gz/z3c.repoexternals-0.3/z3c/repoexternals/__init__.py | __init__.py |
Introduction
============
Log and show ram usage of a zope instance per request.
By calling @@requestlet, you'll get a nice graph and
(if you mark something in it) a table with ram usage,
difference to the last request and the URI over time.
This product was created in the hope to see patterns
on which requests how much ram is "lost". It was
inspired by http://code.google.com/p/zope-memory-readings/
and uses the graph-code from there.
The logging was taken from seletz' requestlet code and
was extended by the ram usage.
Installation / Usage
====================
Add this to your buildout.cfg
[buildout]
eggs = z3c.requestlet
[instance]
zcml = z3c.requestlet
Then install the product using plone's portal_quickinstaller.
If the product is not installed, it will not log and it won't
provide the @@requestlet view.
After installation you may call
http://yoursite/@@requestlet
The default logfile is /tmp/requestlet.txt and may be set using
an environment variable called "REQUESTLET_LOGNAME".
You may also log only hits that take more than a specific time
to render using an environment variable called "MIN_LOG_TIME".
The logfile will provide detailled page generation information
like this:
2009-07-01 16:21:39,755 requestlet INFO ELAPSED 0.038s (min 0s) METHOD GET RAM 423124kB URL: localhost:10054/site/++resource++z3c.requestlet.data/layout.css rinfo: last-modified='Wed, 01 Jul 2009 12:51:28 GMT' content-length='169' content-type='text/css; charset=utf-8' cache-control='public,max-age=86400'
This provides:
- time to render the page in plone (ELAPSED)
- request method (METHOD)
- total vmsize of the zope process (RAM)
- the called URL (URL)
- the request info (rinfo)
Compatibility
=============
This product will only work with systems, where you
can get the memory-info from /proc/<pid>/status.
This is linux.
Contribution
============
To contribute, feel free to send patches as we don't have
this in a public svn currently. It's managed with bzr ;)
Authors
=======
- Daniel Kraft <[email protected]>
- Stefan Eletzhofer <[email protected]>
| z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/README.txt | README.txt |
from zope.interface import implements, Interface
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from time import mktime
import datetime
from z3c.requestlet.rlog import LOGNAME
class RLog(BrowserView):
"""
rlog browser view
generate graphs ;)
"""
def __init__(self, context, request):
self.context = context
self.request = request
self.min_memory = None
self.max_memory = 0
self.data = []
self.first_timestamp = self.last_timestamp = None
self.update()
def update(self):
# fetch info
f = file(LOGNAME)
for line in f.readlines():
if 'ELAPSED' not in line:
continue
date, time, _, _, _, elapsed, _, _, _, _, method, meminfo, _, uri = line.split()[:14]
memory = int(meminfo[:-2])
y, m, d = date.split("-")
h, i, s = time.split(",")[0].split(":")
timestamp = mktime(datetime.datetime(int(y), int(m), int(d), int(h), int(i), int(s)).timetuple())
timestamp = round(timestamp, 2)
if not self.first_timestamp:
self.first_timestamp = timestamp
self.data.append("[%s,%s,'%s']" % (timestamp, memory, uri))
if self.min_memory is None:
self.min_memory = memory
elif memory < self.min_memory:
self.min_memory = memory
if memory > self.max_memory:
self.max_memory = memory
self.last_timestamp = timestamp
def data_array(self):
return "[%s]" % ', '.join([str(x) for x in self.data])
def title(self):
date = datetime.datetime.fromtimestamp(self.first_timestamp)
title = date.strftime('%Y/%m/%d %H:%M:%S')
seconds = self.last_timestamp - self.first_timestamp
if seconds < 60:
title += ' (%d seconds)' % seconds
elif seconds < 60*60:
title += ' (%.1f minutes)' % (seconds/60.0)
elif seconds < 60*60*24:
title += ' (%.1f hours)' % (seconds/60.0/60.0)
else:
title += ' (%.1f days)' % (seconds/60.0/60/24)
return title | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/rlog.py | rlog.py |
(function(){if(window.jQuery)var _jQuery=window.jQuery;var jQuery=window.jQuery=function(selector,context){return new jQuery.prototype.init(selector,context);};if(window.$)var _$=window.$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var isSimple=/^.[^:#\[\.]*$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}else if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem)if(elem.id!=match[3])return jQuery().find(selector);else{this[0]=elem;this.length=1;return this;}else
selector=[];}}else
return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.3",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;this.each(function(i){if(this==elem)ret=i;});return ret;},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],name)||undefined;else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return!selector?this:this.pushStack(jQuery.merge(this.get(),selector.constructor==String?jQuery(selector).get():selector.length!=undefined&&(!selector.nodeName||jQuery.nodeName(selector,"form"))?selector:[selector]));},is:function(selector){return selector?jQuery.multiFilter(selector,this).length>0:false;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
return(this[0].value||"").replace(/\r/g,"");}return undefined;}return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=value.constructor==Array?value:[value];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this.length?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value==null){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data==undefined&&this.length)data=jQuery.data(this[0],key);return data==null&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script")){scripts=scripts.add(elem);}else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.prototype.init.prototype=jQuery.prototype;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==1){target=this;i=0;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){if(target===options[name])continue;if(deep&&options[name]&&typeof options[name]=="object"&&target[name]&&!options[name].nodeType)target[name]=jQuery.extend(target[name],options[name]);else if(options[name]!=undefined)target[name]=options[name];}return target;};var expando="jQuery"+(new Date()).getTime(),uuid=0,windowData={};var exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i;jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.appendChild(script);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!=undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){if(args){if(object.length==undefined){for(var name in object)if(callback.apply(object[name],args)===false)break;}else
for(var i=0,length=object.length;i<length;i++)if(callback.apply(object[i],args)===false)break;}else{if(object.length==undefined){for(var name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var i=0,length=object.length,value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret;function color(elem){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=elem.style.outline;elem.style.outline="0 solid black";elem.style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&elem.style&&elem.style[name])ret=elem.style[name];else if(document.defaultView&&document.defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var getComputedStyle=document.defaultView.getComputedStyle(elem,null);if(getComputedStyle&&!color(elem))ret=getComputedStyle.getPropertyValue(name);else{var swap=[],stack=[];for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(var i=0;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(getComputedStyle&&getComputedStyle.getPropertyValue(name))||"";for(var i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var style=elem.style.left,runtimeStyle=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;elem.style.left=ret||0;ret=elem.style.pixelLeft+"px";elem.style.left=style;elem.runtimeStyle.left=runtimeStyle;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem=elem.toString();if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,""+value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(typeof array!="array")for(var i=0,length=array.length;i<length;i++)ret.push(array[i]);else
ret=array.slice(0);return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]==elem)return i;return-1;},merge:function(first,second){if(jQuery.browser.msie){for(var i=0;second[i];i++)if(second[i].nodeType!=8)first.push(second[i]);}else
for(var i=0;second[i];i++)first.push(second[i]);return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv&&callback(elems[i],i)||inv&&!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!==null&&value!=undefined){if(value.constructor!=Array)value=[value];ret=ret.concat(value);}}return ret;}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,innerHTML:"innerHTML",className:"className",value:"value",disabled:"disabled",checked:"checked",readonly:"readOnly",selected:"selected",maxlength:"maxLength",selectedIndex:"selectedIndex",defaultValue:"defaultValue",tagName:"tagName",nodeName:"nodeName"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem))r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval!=undefined)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered)return val;val=jQuery.event.handle.apply(arguments.callee.elem,arguments);return val;});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data||[]);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event)data.unshift(this.fix({type:type,target:elem}));data[0].type=type;if(exclusive)data[0].exclusive=true;if(jQuery.isFunction(jQuery.data(elem,"handle")))val=jQuery.data(elem,"handle").apply(elem,data);if(!fn&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var handlers=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in handlers){var handler=handlers[j];args[0].handler=handler;args[0].data=handler.data;if(!parts[1]&&!event.exclusive||handler.type==parts[1]){var ret=handler.apply(this,args);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie)event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=originalEvent.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0])return jQuery.event.trigger(type,data,this[0],false,fn);return undefined;},toggle:function(){var args=arguments;return this.click(function(event){this.lastToggle=0==this.lastToggle?1:0;event.preventDefault();return args[this.lastToggle].apply(this,arguments)||false;});},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var jsonp,jsre=/=\?(&|$)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get"){var ts=(new Date()).getTime();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");xml.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xml;},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(!elem)return undefined;type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].apply(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.apply(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=(new Date()).getTime();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),fixed=jQuery.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&jQuery.css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||jQuery.css(offsetChild,"position")=="absolute"))||(mozilla&&jQuery.css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}return results;};})(); | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/data/jquery.js | jquery.js |
function kbytesFormatter(val, axis) {
return Math.round(val,2) + ' kB';
}
function uriFormatter(uri, maxlength) {
if(maxlength == null) maxlength=200;
if (uri.length > maxlength) {
return uri.substr(0, 3*parseInt(maxlength/4))+' ... '+uri.substr(3*parseInt(maxlength/4), uri.length);
}
return uri;
}
var options = {
points: { show: true },
lines: { show: true, lineWidth: 3, fill: true },
xaxis: { mode: "time" },
yaxis: { tickFormatter: kbytesFormatter, tickDecimals: 2, labelWidth: 56 },
selection: { mode: "x" },
grid: { clickable: false, mouseCatchingArea: 6, triggerOnMouseOver: true }
};
$(function () {
max_value += parseInt(0.01 * max_value);
plot = $.plot($("#placeholder"), [d], options);
/* Commented out until this is solved
* http://groups.google.com/group/flot-graphs/browse_thread/thread/10a7eee60fd25d32
overview = $.plot($("#overview"), [d], {
lines: { show: true, lineWidth: 1, fill: true },
shadowSize: 0,
xaxis: { ticks: [], mode: "time" },
yaxis: { ticks: [], min: min_value, max: max_value },
selection: { mode: "x" }
});
*/
// now connect the two
var internalSelection = false;
$("#placeholder").bind("selected", function (event, area) {
// console.log("event on #placeholder");
printURLs(area.x1, area.x2);
/*
plot = $.plot($("#placeholder"), [d],
$.extend(true, {}, options, {
xaxis: { min: area.x1, max: area.x2 }
}));
if (internalSelection)
return; // prevent eternal loop
internalSelection = true;
overview.setSelection(area);
internalSelection = false;
*/
});
$("#overview").bind("selected", function (event, area) {
console.log("event on #overview");
// do the zooming
if (internalSelection)
return;
internalSelection = true;
plot.setSelection(area);
internalSelection = false;
});
});
function __get_flux(value, prev) {
if (prev != null) {
if (value > prev) {
return '+' + (kbytesFormatter(value-prev,0));
} else if (value < prev) {
return ''+ (kbytesFormatter(value-prev,0));
}
}
return '';
}
function printURLs(x1, x2) {
$('tbody', $('#urls')).remove();
$('thead', $('#urls')).remove();
$('#urls').append(
$('<thead></thead>').append(
$('<tr></tr>').append(
$('<th></th>').text('Memory size')
).append(
$('<th></th>').text('Change')
).append(
$('<th></th>').text('URI')
)
)
);
var keep = new Array();
var prev = null;
var line;
$.each(d, function() {
if (this[0] >= x1 && this[0] < x2) {
line = kbytesFormatter(this[1]);
$('#urls').append(
$('<tbody></tbody>').append(
$('<tr></tr>').append(
$('<td></td>').text(kbytesFormatter(this[1])).attr('align','right')
).append(
$('<td></td>').text(__get_flux(this[1], prev)).attr('align','right')
).append(
$('<td></td>').text(uriFormatter(this[2]))
)
)
);
if (prev != null) {
if (this[1] > prev) {
line += ' (+' + (this[1]-prev) + ')';
} else if (this[1] < prev) {
line += ' (' + (this[1]-prev) + ')';
}
}
line += ' ' + this[2]
keep.push(line);
prev = this[1];
}
});
return keep;
}
function resetPlotSelection() {
location.href=location.href;
} | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/data/flotter.js | flotter.js |
import os
import datetime
import marshal
from time import mktime
def generate(file_name):
html = open(os.path.join(os.path.dirname(__file__), 'template.html')).read()
data = []
first_timestamp = last_timestamp = None
min_memory = None
max_memory = 0
f = file(file_name)
for line in f.readlines():
if 'ELAPSED' not in line:
continue
date, time, _, _, _, elapsed, _, _, _, _, method, meminfo, _, uri = line.split()[:14]
memory = int(meminfo[:-2])
y, m, d = date.split("-")
h, i, s = time.split(",")[0].split(":")
timestamp = mktime(datetime.datetime(int(y), int(m), int(d), int(h), int(i), int(s)).timetuple()) # XXX
timestamp = round(timestamp, 2)
if not first_timestamp:
first_timestamp = timestamp
data.append("[%s,%s,'%s']" % (timestamp, memory, uri))
if min_memory is None:
min_memory = memory
elif memory < min_memory:
min_memory = memory
if memory > max_memory:
max_memory = memory
last_timestamp = timestamp
html = html.replace('{{max_value}}', str(max_memory))
html = html.replace('{{min_value}}', str(min_memory))
html = html.replace('{{data_array}}', '[%s]' % ', '.join([str(x) for x in data]))
title = _generate_title(first_timestamp, last_timestamp)
html = html.replace('{{title}}', title)
save_dir = _title2foldername(title)
if not os.path.isdir(save_dir):
os.mkdir(save_dir)
open(os.path.join(save_dir, 'index.html'),'w').write(html)
report_file = os.path.join(save_dir, 'index.html')
print report_file
return report_file
def _generate_title(first_timestamp, last_timestamp):
date = datetime.datetime.fromtimestamp(first_timestamp)
title = date.strftime('%Y/%m/%d %H:%M:%S')
seconds = last_timestamp - first_timestamp
if seconds < 60:
title += ' (%d seconds)' % seconds
elif seconds < 60*60:
title += ' (%.1f minutes)' % (seconds/60.0)
elif seconds < 60*60*24:
title += ' (%.1f hours)' % (seconds/60.0/60.0)
else:
title += ' (%.1f days)' % (seconds/60.0/60/24)
return title
def _title2foldername(title):
title = title.replace(':','.')
title = title.replace('(',' ').replace(')','')
title = title.replace(' ','_')
title = title.replace('/','-')
return title
if __name__=='__main__':
import sys
generate("/tmp/requestlet.txt") | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/data/generate_graph.py | generate_graph.py |
if(!window.CanvasRenderingContext2D){(function(){var m=Math;var mr=m.round;var ms=m.sin;var mc=m.cos;var Z=10;var Z2=Z/2;var G_vmlCanvasManager_={init:function(opt_doc){var doc=opt_doc||document;if(/MSIE/.test(navigator.userAgent)&&!window.opera){var self=this;doc.attachEvent("onreadystatechange",function(){self.init_(doc)})}},init_:function(doc){if(doc.readyState=="complete"){if(!doc.namespaces["g_vml_"]){doc.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml")}var ss=doc.createStyleSheet();ss.cssText="canvas{display:inline-block;overflow:hidden;"+"text-align:left;width:300px;height:150px}"+"g_vml_\\:*{behavior:url(#default#VML)}";var els=doc.getElementsByTagName("canvas");for(var i=0;i<els.length;i++){if(!els[i].getContext){this.initElement(els[i])}}}},fixElement_:function(el){var outerHTML=el.outerHTML;var newEl=el.ownerDocument.createElement(outerHTML);if(outerHTML.slice(-2)!="/>"){var tagName="/"+el.tagName;var ns;while((ns=el.nextSibling)&&ns.tagName!=tagName){ns.removeNode()}if(ns){ns.removeNode()}}el.parentNode.replaceChild(newEl,el);return newEl},initElement:function(el){el=this.fixElement_(el);el.getContext=function(){if(this.context_){return this.context_}return this.context_=new CanvasRenderingContext2D_(this)};el.attachEvent('onpropertychange',onPropertyChange);el.attachEvent('onresize',onResize);var attrs=el.attributes;if(attrs.width&&attrs.width.specified){el.style.width=attrs.width.nodeValue+"px"}else{el.width=el.clientWidth}if(attrs.height&&attrs.height.specified){el.style.height=attrs.height.nodeValue+"px"}else{el.height=el.clientHeight}return el}};function onPropertyChange(e){var el=e.srcElement;switch(e.propertyName){case'width':el.style.width=el.attributes.width.nodeValue+"px";el.getContext().clearRect();break;case'height':el.style.height=el.attributes.height.nodeValue+"px";el.getContext().clearRect();break}}function onResize(e){var el=e.srcElement;if(el.firstChild){el.firstChild.style.width=el.clientWidth+'px';el.firstChild.style.height=el.clientHeight+'px'}}G_vmlCanvasManager_.init();var dec2hex=[];for(var i=0;i<16;i++){for(var j=0;j<16;j++){dec2hex[i*16+j]=i.toString(16)+j.toString(16)}}function createMatrixIdentity(){return[[1,0,0],[0,1,0],[0,0,1]]}function matrixMultiply(m1,m2){var result=createMatrixIdentity();for(var x=0;x<3;x++){for(var y=0;y<3;y++){var sum=0;for(var z=0;z<3;z++){sum+=m1[x][z]*m2[z][y]}result[x][y]=sum}}return result}function copyState(o1,o2){o2.fillStyle=o1.fillStyle;o2.lineCap=o1.lineCap;o2.lineJoin=o1.lineJoin;o2.lineWidth=o1.lineWidth;o2.miterLimit=o1.miterLimit;o2.shadowBlur=o1.shadowBlur;o2.shadowColor=o1.shadowColor;o2.shadowOffsetX=o1.shadowOffsetX;o2.shadowOffsetY=o1.shadowOffsetY;o2.strokeStyle=o1.strokeStyle;o2.arcScaleX_=o1.arcScaleX_;o2.arcScaleY_=o1.arcScaleY_}function processStyle(styleString){var str,alpha=1;styleString=String(styleString);if(styleString.substring(0,3)=="rgb"){var start=styleString.indexOf("(",3);var end=styleString.indexOf(")",start+1);var guts=styleString.substring(start+1,end).split(",");str="#";for(var i=0;i<3;i++){str+=dec2hex[Number(guts[i])]}if((guts.length==4)&&(styleString.substr(3,1)=="a")){alpha=guts[3]}}else{str=styleString}return[str,alpha]}function processLineCap(lineCap){switch(lineCap){case"butt":return"flat";case"round":return"round";case"square":default:return"square"}}function CanvasRenderingContext2D_(surfaceElement){this.m_=createMatrixIdentity();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.strokeStyle="#000";this.fillStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=Z*1;this.globalAlpha=1;this.canvas=surfaceElement;var el=surfaceElement.ownerDocument.createElement('div');el.style.width=surfaceElement.clientWidth+'px';el.style.height=surfaceElement.clientHeight+'px';el.style.overflow='hidden';el.style.position='absolute';surfaceElement.appendChild(el);this.element_=el;this.arcScaleX_=1;this.arcScaleY_=1}var contextPrototype=CanvasRenderingContext2D_.prototype;contextPrototype.clearRect=function(){this.element_.innerHTML="";this.currentPath_=[]};contextPrototype.beginPath=function(){this.currentPath_=[]};contextPrototype.moveTo=function(aX,aY){this.currentPath_.push({type:"moveTo",x:aX,y:aY});this.currentX_=aX;this.currentY_=aY};contextPrototype.lineTo=function(aX,aY){this.currentPath_.push({type:"lineTo",x:aX,y:aY});this.currentX_=aX;this.currentY_=aY};contextPrototype.bezierCurveTo=function(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){this.currentPath_.push({type:"bezierCurveTo",cp1x:aCP1x,cp1y:aCP1y,cp2x:aCP2x,cp2y:aCP2y,x:aX,y:aY});this.currentX_=aX;this.currentY_=aY};contextPrototype.quadraticCurveTo=function(aCPx,aCPy,aX,aY){var cp1x=this.currentX_+2.0/3.0*(aCPx-this.currentX_);var cp1y=this.currentY_+2.0/3.0*(aCPy-this.currentY_);var cp2x=cp1x+(aX-this.currentX_)/3.0;var cp2y=cp1y+(aY-this.currentY_)/3.0;this.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,aX,aY)};contextPrototype.arc=function(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){aRadius*=Z;var arcType=aClockwise?"at":"wa";var xStart=aX+(mc(aStartAngle)*aRadius)-Z2;var yStart=aY+(ms(aStartAngle)*aRadius)-Z2;var xEnd=aX+(mc(aEndAngle)*aRadius)-Z2;var yEnd=aY+(ms(aEndAngle)*aRadius)-Z2;if(xStart==xEnd&&!aClockwise){xStart+=0.125}this.currentPath_.push({type:arcType,x:aX,y:aY,radius:aRadius,xStart:xStart,yStart:yStart,xEnd:xEnd,yEnd:yEnd})};contextPrototype.rect=function(aX,aY,aWidth,aHeight){this.moveTo(aX,aY);this.lineTo(aX+aWidth,aY);this.lineTo(aX+aWidth,aY+aHeight);this.lineTo(aX,aY+aHeight);this.closePath()};contextPrototype.strokeRect=function(aX,aY,aWidth,aHeight){this.beginPath();this.moveTo(aX,aY);this.lineTo(aX+aWidth,aY);this.lineTo(aX+aWidth,aY+aHeight);this.lineTo(aX,aY+aHeight);this.closePath();this.stroke()};contextPrototype.fillRect=function(aX,aY,aWidth,aHeight){this.beginPath();this.moveTo(aX,aY);this.lineTo(aX+aWidth,aY);this.lineTo(aX+aWidth,aY+aHeight);this.lineTo(aX,aY+aHeight);this.closePath();this.fill()};contextPrototype.createLinearGradient=function(aX0,aY0,aX1,aY1){var gradient=new CanvasGradient_("gradient");return gradient};contextPrototype.createRadialGradient=function(aX0,aY0,aR0,aX1,aY1,aR1){var gradient=new CanvasGradient_("gradientradial");gradient.radius1_=aR0;gradient.radius2_=aR1;gradient.focus_.x=aX0;gradient.focus_.y=aY0;return gradient};contextPrototype.drawImage=function(image,var_args){var dx,dy,dw,dh,sx,sy,sw,sh;var oldRuntimeWidth=image.runtimeStyle.width;var oldRuntimeHeight=image.runtimeStyle.height;image.runtimeStyle.width='auto';image.runtimeStyle.height='auto';var w=image.width;var h=image.height;image.runtimeStyle.width=oldRuntimeWidth;image.runtimeStyle.height=oldRuntimeHeight;if(arguments.length==3){dx=arguments[1];dy=arguments[2];sx=sy=0;sw=dw=w;sh=dh=h}else if(arguments.length==5){dx=arguments[1];dy=arguments[2];dw=arguments[3];dh=arguments[4];sx=sy=0;sw=w;sh=h}else if(arguments.length==9){sx=arguments[1];sy=arguments[2];sw=arguments[3];sh=arguments[4];dx=arguments[5];dy=arguments[6];dw=arguments[7];dh=arguments[8]}else{throw"Invalid number of arguments";}var d=this.getCoords_(dx,dy);var w2=sw/2;var h2=sh/2;var vmlStr=[];var W=10;var H=10;vmlStr.push(' <g_vml_:group',' coordsize="',Z*W,',',Z*H,'"',' coordorigin="0,0"',' style="width:',W,';height:',H,';position:absolute;');if(this.m_[0][0]!=1||this.m_[0][1]){var filter=[];filter.push("M11='",this.m_[0][0],"',","M12='",this.m_[1][0],"',","M21='",this.m_[0][1],"',","M22='",this.m_[1][1],"',","Dx='",mr(d.x/Z),"',","Dy='",mr(d.y/Z),"'");var max=d;var c2=this.getCoords_(dx+dw,dy);var c3=this.getCoords_(dx,dy+dh);var c4=this.getCoords_(dx+dw,dy+dh);max.x=Math.max(max.x,c2.x,c3.x,c4.x);max.y=Math.max(max.y,c2.y,c3.y,c4.y);vmlStr.push("padding:0 ",mr(max.x/Z),"px ",mr(max.y/Z),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",filter.join(""),", sizingmethod='clip');")}else{vmlStr.push("top:",mr(d.y/Z),"px;left:",mr(d.x/Z),"px;")}vmlStr.push(' ">','<g_vml_:image src="',image.src,'"',' style="width:',Z*dw,';',' height:',Z*dh,';"',' cropleft="',sx/w,'"',' croptop="',sy/h,'"',' cropright="',(w-sx-sw)/w,'"',' cropbottom="',(h-sy-sh)/h,'"',' />','</g_vml_:group>');this.element_.insertAdjacentHTML("BeforeEnd",vmlStr.join(""))};contextPrototype.stroke=function(aFill){var lineStr=[];var lineOpen=false;var a=processStyle(aFill?this.fillStyle:this.strokeStyle);var color=a[0];var opacity=a[1]*this.globalAlpha;var W=10;var H=10;lineStr.push('<g_vml_:shape',' fillcolor="',color,'"',' filled="',Boolean(aFill),'"',' style="position:absolute;width:',W,';height:',H,';"',' coordorigin="0 0" coordsize="',Z*W,' ',Z*H,'"',' stroked="',!aFill,'"',' strokeweight="',this.lineWidth,'"',' strokecolor="',color,'"',' path="');var newSeq=false;var min={x:null,y:null};var max={x:null,y:null};for(var i=0;i<this.currentPath_.length;i++){var p=this.currentPath_[i];if(p.type=="moveTo"){lineStr.push(" m ");var c=this.getCoords_(p.x,p.y);lineStr.push(mr(c.x),",",mr(c.y))}else if(p.type=="lineTo"){lineStr.push(" l ");var c=this.getCoords_(p.x,p.y);lineStr.push(mr(c.x),",",mr(c.y))}else if(p.type=="close"){lineStr.push(" x ")}else if(p.type=="bezierCurveTo"){lineStr.push(" c ");var c=this.getCoords_(p.x,p.y);var c1=this.getCoords_(p.cp1x,p.cp1y);var c2=this.getCoords_(p.cp2x,p.cp2y);lineStr.push(mr(c1.x),",",mr(c1.y),",",mr(c2.x),",",mr(c2.y),",",mr(c.x),",",mr(c.y))}else if(p.type=="at"||p.type=="wa"){lineStr.push(" ",p.type," ");var c=this.getCoords_(p.x,p.y);var cStart=this.getCoords_(p.xStart,p.yStart);var cEnd=this.getCoords_(p.xEnd,p.yEnd);lineStr.push(mr(c.x-this.arcScaleX_*p.radius),",",mr(c.y-this.arcScaleY_*p.radius)," ",mr(c.x+this.arcScaleX_*p.radius),",",mr(c.y+this.arcScaleY_*p.radius)," ",mr(cStart.x),",",mr(cStart.y)," ",mr(cEnd.x),",",mr(cEnd.y))}if(c){if(min.x==null||c.x<min.x){min.x=c.x}if(max.x==null||c.x>max.x){max.x=c.x}if(min.y==null||c.y<min.y){min.y=c.y}if(max.y==null||c.y>max.y){max.y=c.y}}}lineStr.push(' ">');if(typeof this.fillStyle=="object"){var focus={x:"50%",y:"50%"};var width=(max.x-min.x);var height=(max.y-min.y);var dimension=(width>height)?width:height;focus.x=mr((this.fillStyle.focus_.x/width)*100+50)+"%";focus.y=mr((this.fillStyle.focus_.y/height)*100+50)+"%";var colors=[];if(this.fillStyle.type_=="gradientradial"){var inside=(this.fillStyle.radius1_/dimension*100);var expansion=(this.fillStyle.radius2_/dimension*100)-inside}else{var inside=0;var expansion=100}var insidecolor={offset:null,color:null};var outsidecolor={offset:null,color:null};this.fillStyle.colors_.sort(function(cs1,cs2){return cs1.offset-cs2.offset});for(var i=0;i<this.fillStyle.colors_.length;i++){var fs=this.fillStyle.colors_[i];colors.push((fs.offset*expansion)+inside,"% ",fs.color,",");if(fs.offset>insidecolor.offset||insidecolor.offset==null){insidecolor.offset=fs.offset;insidecolor.color=fs.color}if(fs.offset<outsidecolor.offset||outsidecolor.offset==null){outsidecolor.offset=fs.offset;outsidecolor.color=fs.color}}colors.pop();lineStr.push('<g_vml_:fill',' color="',outsidecolor.color,'"',' color2="',insidecolor.color,'"',' type="',this.fillStyle.type_,'"',' focusposition="',focus.x,', ',focus.y,'"',' colors="',colors.join(""),'"',' opacity="',opacity,'" />')}else if(aFill){lineStr.push('<g_vml_:fill color="',color,'" opacity="',opacity,'" />')}else{lineStr.push('<g_vml_:stroke',' opacity="',opacity,'"',' joinstyle="',this.lineJoin,'"',' miterlimit="',this.miterLimit,'"',' endcap="',processLineCap(this.lineCap),'"',' weight="',this.lineWidth,'px"',' color="',color,'" />')}lineStr.push("</g_vml_:shape>");this.element_.insertAdjacentHTML("beforeEnd",lineStr.join(""))};contextPrototype.fill=function(){this.stroke(true)};contextPrototype.closePath=function(){this.currentPath_.push({type:"close"})};contextPrototype.getCoords_=function(aX,aY){return{x:Z*(aX*this.m_[0][0]+aY*this.m_[1][0]+this.m_[2][0])-Z2,y:Z*(aX*this.m_[0][1]+aY*this.m_[1][1]+this.m_[2][1])-Z2}};contextPrototype.save=function(){var o={};copyState(this,o);this.aStack_.push(o);this.mStack_.push(this.m_);this.m_=matrixMultiply(createMatrixIdentity(),this.m_)};contextPrototype.restore=function(){copyState(this.aStack_.pop(),this);this.m_=this.mStack_.pop()};contextPrototype.translate=function(aX,aY){var m1=[[1,0,0],[0,1,0],[aX,aY,1]];this.m_=matrixMultiply(m1,this.m_)};contextPrototype.rotate=function(aRot){var c=mc(aRot);var s=ms(aRot);var m1=[[c,s,0],[-s,c,0],[0,0,1]];this.m_=matrixMultiply(m1,this.m_)};contextPrototype.scale=function(aX,aY){this.arcScaleX_*=aX;this.arcScaleY_*=aY;var m1=[[aX,0,0],[0,aY,0],[0,0,1]];this.m_=matrixMultiply(m1,this.m_)};contextPrototype.clip=function(){};contextPrototype.arcTo=function(){};contextPrototype.createPattern=function(){return new CanvasPattern_};function CanvasGradient_(aType){this.type_=aType;this.radius1_=0;this.radius2_=0;this.colors_=[];this.focus_={x:0,y:0}}CanvasGradient_.prototype.addColorStop=function(aOffset,aColor){aColor=processStyle(aColor);this.colors_.push({offset:1-aOffset,color:aColor})};function CanvasPattern_(){}G_vmlCanvasManager=G_vmlCanvasManager_;CanvasRenderingContext2D=CanvasRenderingContext2D_;CanvasGradient=CanvasGradient_;CanvasPattern=CanvasPattern_})()} | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/data/flot/excanvas.pack.js | excanvas.pack.js |
// Known Issues:
//
// * Patterns are not implemented.
// * Radial gradient are not implemented. The VML version of these look very
// different from the canvas one.
// * Clipping paths are not implemented.
// * Coordsize. The width and height attribute have higher priority than the
// width and height style values which isn't correct.
// * Painting mode isn't implemented.
// * Canvas width/height should is using content-box by default. IE in
// Quirks mode will draw the canvas using border-box. Either change your
// doctype to HTML5
// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
// or use Box Sizing Behavior from WebFX
// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
// * Optimize. There is always room for speed improvements.
// only add this code if we do not already have a canvas implementation
if (!window.CanvasRenderingContext2D) {
(function () {
// alias some functions to make (compiled) code shorter
var m = Math;
var mr = m.round;
var ms = m.sin;
var mc = m.cos;
// this is used for sub pixel precision
var Z = 10;
var Z2 = Z / 2;
var G_vmlCanvasManager_ = {
init: function (opt_doc) {
var doc = opt_doc || document;
if (/MSIE/.test(navigator.userAgent) && !window.opera) {
var self = this;
doc.attachEvent("onreadystatechange", function () {
self.init_(doc);
});
}
},
init_: function (doc) {
if (doc.readyState == "complete") {
// create xmlns
if (!doc.namespaces["g_vml_"]) {
doc.namespaces.add("g_vml_", "urn:schemas-microsoft-com:vml");
}
// setup default css
var ss = doc.createStyleSheet();
ss.cssText = "canvas{display:inline-block;overflow:hidden;" +
// default size is 300x150 in Gecko and Opera
"text-align:left;width:300px;height:150px}" +
"g_vml_\\:*{behavior:url(#default#VML)}";
// find all canvas elements
var els = doc.getElementsByTagName("canvas");
for (var i = 0; i < els.length; i++) {
if (!els[i].getContext) {
this.initElement(els[i]);
}
}
}
},
fixElement_: function (el) {
// in IE before version 5.5 we would need to add HTML: to the tag name
// but we do not care about IE before version 6
var outerHTML = el.outerHTML;
var newEl = el.ownerDocument.createElement(outerHTML);
// if the tag is still open IE has created the children as siblings and
// it has also created a tag with the name "/FOO"
if (outerHTML.slice(-2) != "/>") {
var tagName = "/" + el.tagName;
var ns;
// remove content
while ((ns = el.nextSibling) && ns.tagName != tagName) {
ns.removeNode();
}
// remove the incorrect closing tag
if (ns) {
ns.removeNode();
}
}
el.parentNode.replaceChild(newEl, el);
return newEl;
},
/**
* Public initializes a canvas element so that it can be used as canvas
* element from now on. This is called automatically before the page is
* loaded but if you are creating elements using createElement you need to
* make sure this is called on the element.
* @param {HTMLElement} el The canvas element to initialize.
* @return {HTMLElement} the element that was created.
*/
initElement: function (el) {
el = this.fixElement_(el);
el.getContext = function () {
if (this.context_) {
return this.context_;
}
return this.context_ = new CanvasRenderingContext2D_(this);
};
// do not use inline function because that will leak memory
el.attachEvent('onpropertychange', onPropertyChange);
el.attachEvent('onresize', onResize);
var attrs = el.attributes;
if (attrs.width && attrs.width.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setWidth_(attrs.width.nodeValue);
el.style.width = attrs.width.nodeValue + "px";
} else {
el.width = el.clientWidth;
}
if (attrs.height && attrs.height.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setHeight_(attrs.height.nodeValue);
el.style.height = attrs.height.nodeValue + "px";
} else {
el.height = el.clientHeight;
}
//el.getContext().setCoordsize_()
return el;
}
};
function onPropertyChange(e) {
var el = e.srcElement;
switch (e.propertyName) {
case 'width':
el.style.width = el.attributes.width.nodeValue + "px";
el.getContext().clearRect();
break;
case 'height':
el.style.height = el.attributes.height.nodeValue + "px";
el.getContext().clearRect();
break;
}
}
function onResize(e) {
var el = e.srcElement;
if (el.firstChild) {
el.firstChild.style.width = el.clientWidth + 'px';
el.firstChild.style.height = el.clientHeight + 'px';
}
}
G_vmlCanvasManager_.init();
// precompute "00" to "FF"
var dec2hex = [];
for (var i = 0; i < 16; i++) {
for (var j = 0; j < 16; j++) {
dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
}
}
function createMatrixIdentity() {
return [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
}
function matrixMultiply(m1, m2) {
var result = createMatrixIdentity();
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 3; y++) {
var sum = 0;
for (var z = 0; z < 3; z++) {
sum += m1[x][z] * m2[z][y];
}
result[x][y] = sum;
}
}
return result;
}
function copyState(o1, o2) {
o2.fillStyle = o1.fillStyle;
o2.lineCap = o1.lineCap;
o2.lineJoin = o1.lineJoin;
o2.lineWidth = o1.lineWidth;
o2.miterLimit = o1.miterLimit;
o2.shadowBlur = o1.shadowBlur;
o2.shadowColor = o1.shadowColor;
o2.shadowOffsetX = o1.shadowOffsetX;
o2.shadowOffsetY = o1.shadowOffsetY;
o2.strokeStyle = o1.strokeStyle;
o2.arcScaleX_ = o1.arcScaleX_;
o2.arcScaleY_ = o1.arcScaleY_;
}
function processStyle(styleString) {
var str, alpha = 1;
styleString = String(styleString);
if (styleString.substring(0, 3) == "rgb") {
var start = styleString.indexOf("(", 3);
var end = styleString.indexOf(")", start + 1);
var guts = styleString.substring(start + 1, end).split(",");
str = "#";
for (var i = 0; i < 3; i++) {
str += dec2hex[Number(guts[i])];
}
if ((guts.length == 4) && (styleString.substr(3, 1) == "a")) {
alpha = guts[3];
}
} else {
str = styleString;
}
return [str, alpha];
}
function processLineCap(lineCap) {
switch (lineCap) {
case "butt":
return "flat";
case "round":
return "round";
case "square":
default:
return "square";
}
}
/**
* This class implements CanvasRenderingContext2D interface as described by
* the WHATWG.
* @param {HTMLElement} surfaceElement The element that the 2D context should
* be associated with
*/
function CanvasRenderingContext2D_(surfaceElement) {
this.m_ = createMatrixIdentity();
this.mStack_ = [];
this.aStack_ = [];
this.currentPath_ = [];
// Canvas context properties
this.strokeStyle = "#000";
this.fillStyle = "#000";
this.lineWidth = 1;
this.lineJoin = "miter";
this.lineCap = "butt";
this.miterLimit = Z * 1;
this.globalAlpha = 1;
this.canvas = surfaceElement;
var el = surfaceElement.ownerDocument.createElement('div');
el.style.width = surfaceElement.clientWidth + 'px';
el.style.height = surfaceElement.clientHeight + 'px';
el.style.overflow = 'hidden';
el.style.position = 'absolute';
surfaceElement.appendChild(el);
this.element_ = el;
this.arcScaleX_ = 1;
this.arcScaleY_ = 1;
}
var contextPrototype = CanvasRenderingContext2D_.prototype;
contextPrototype.clearRect = function() {
this.element_.innerHTML = "";
this.currentPath_ = [];
};
contextPrototype.beginPath = function() {
// TODO: Branch current matrix so that save/restore has no effect
// as per safari docs.
this.currentPath_ = [];
};
contextPrototype.moveTo = function(aX, aY) {
this.currentPath_.push({type: "moveTo", x: aX, y: aY});
this.currentX_ = aX;
this.currentY_ = aY;
};
contextPrototype.lineTo = function(aX, aY) {
this.currentPath_.push({type: "lineTo", x: aX, y: aY});
this.currentX_ = aX;
this.currentY_ = aY;
};
contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
aCP2x, aCP2y,
aX, aY) {
this.currentPath_.push({type: "bezierCurveTo",
cp1x: aCP1x,
cp1y: aCP1y,
cp2x: aCP2x,
cp2y: aCP2y,
x: aX,
y: aY});
this.currentX_ = aX;
this.currentY_ = aY;
};
contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
// the following is lifted almost directly from
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
var cp1x = this.currentX_ + 2.0 / 3.0 * (aCPx - this.currentX_);
var cp1y = this.currentY_ + 2.0 / 3.0 * (aCPy - this.currentY_);
var cp2x = cp1x + (aX - this.currentX_) / 3.0;
var cp2y = cp1y + (aY - this.currentY_) / 3.0;
this.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, aX, aY);
};
contextPrototype.arc = function(aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise) {
aRadius *= Z;
var arcType = aClockwise ? "at" : "wa";
var xStart = aX + (mc(aStartAngle) * aRadius) - Z2;
var yStart = aY + (ms(aStartAngle) * aRadius) - Z2;
var xEnd = aX + (mc(aEndAngle) * aRadius) - Z2;
var yEnd = aY + (ms(aEndAngle) * aRadius) - Z2;
// IE won't render arches drawn counter clockwise if xStart == xEnd.
if (xStart == xEnd && !aClockwise) {
xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
// that can be represented in binary
}
this.currentPath_.push({type: arcType,
x: aX,
y: aY,
radius: aRadius,
xStart: xStart,
yStart: yStart,
xEnd: xEnd,
yEnd: yEnd});
};
contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
};
contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
// Will destroy any existing path (same as FF behaviour)
this.beginPath();
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.stroke();
};
contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
// Will destroy any existing path (same as FF behaviour)
this.beginPath();
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.fill();
};
contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
var gradient = new CanvasGradient_("gradient");
return gradient;
};
contextPrototype.createRadialGradient = function(aX0, aY0,
aR0, aX1,
aY1, aR1) {
var gradient = new CanvasGradient_("gradientradial");
gradient.radius1_ = aR0;
gradient.radius2_ = aR1;
gradient.focus_.x = aX0;
gradient.focus_.y = aY0;
return gradient;
};
contextPrototype.drawImage = function (image, var_args) {
var dx, dy, dw, dh, sx, sy, sw, sh;
// to find the original width we overide the width and height
var oldRuntimeWidth = image.runtimeStyle.width;
var oldRuntimeHeight = image.runtimeStyle.height;
image.runtimeStyle.width = 'auto';
image.runtimeStyle.height = 'auto';
// get the original size
var w = image.width;
var h = image.height;
// and remove overides
image.runtimeStyle.width = oldRuntimeWidth;
image.runtimeStyle.height = oldRuntimeHeight;
if (arguments.length == 3) {
dx = arguments[1];
dy = arguments[2];
sx = sy = 0;
sw = dw = w;
sh = dh = h;
} else if (arguments.length == 5) {
dx = arguments[1];
dy = arguments[2];
dw = arguments[3];
dh = arguments[4];
sx = sy = 0;
sw = w;
sh = h;
} else if (arguments.length == 9) {
sx = arguments[1];
sy = arguments[2];
sw = arguments[3];
sh = arguments[4];
dx = arguments[5];
dy = arguments[6];
dw = arguments[7];
dh = arguments[8];
} else {
throw "Invalid number of arguments";
}
var d = this.getCoords_(dx, dy);
var w2 = sw / 2;
var h2 = sh / 2;
var vmlStr = [];
var W = 10;
var H = 10;
// For some reason that I've now forgotten, using divs didn't work
vmlStr.push(' <g_vml_:group',
' coordsize="', Z * W, ',', Z * H, '"',
' coordorigin="0,0"' ,
' style="width:', W, ';height:', H, ';position:absolute;');
// If filters are necessary (rotation exists), create them
// filters are bog-slow, so only create them if abbsolutely necessary
// The following check doesn't account for skews (which don't exist
// in the canvas spec (yet) anyway.
if (this.m_[0][0] != 1 || this.m_[0][1]) {
var filter = [];
// Note the 12/21 reversal
filter.push("M11='", this.m_[0][0], "',",
"M12='", this.m_[1][0], "',",
"M21='", this.m_[0][1], "',",
"M22='", this.m_[1][1], "',",
"Dx='", mr(d.x / Z), "',",
"Dy='", mr(d.y / Z), "'");
// Bounding box calculation (need to minimize displayed area so that
// filters don't waste time on unused pixels.
var max = d;
var c2 = this.getCoords_(dx + dw, dy);
var c3 = this.getCoords_(dx, dy + dh);
var c4 = this.getCoords_(dx + dw, dy + dh);
max.x = Math.max(max.x, c2.x, c3.x, c4.x);
max.y = Math.max(max.y, c2.y, c3.y, c4.y);
vmlStr.push("padding:0 ", mr(max.x / Z), "px ", mr(max.y / Z),
"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",
filter.join(""), ", sizingmethod='clip');");
} else {
vmlStr.push("top:", mr(d.y / Z), "px;left:", mr(d.x / Z), "px;");
}
vmlStr.push(' ">' ,
'<g_vml_:image src="', image.src, '"',
' style="width:', Z * dw, ';',
' height:', Z * dh, ';"',
' cropleft="', sx / w, '"',
' croptop="', sy / h, '"',
' cropright="', (w - sx - sw) / w, '"',
' cropbottom="', (h - sy - sh) / h, '"',
' />',
'</g_vml_:group>');
this.element_.insertAdjacentHTML("BeforeEnd",
vmlStr.join(""));
};
contextPrototype.stroke = function(aFill) {
var lineStr = [];
var lineOpen = false;
var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
var color = a[0];
var opacity = a[1] * this.globalAlpha;
var W = 10;
var H = 10;
lineStr.push('<g_vml_:shape',
' fillcolor="', color, '"',
' filled="', Boolean(aFill), '"',
' style="position:absolute;width:', W, ';height:', H, ';"',
' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
' stroked="', !aFill, '"',
' strokeweight="', this.lineWidth, '"',
' strokecolor="', color, '"',
' path="');
var newSeq = false;
var min = {x: null, y: null};
var max = {x: null, y: null};
for (var i = 0; i < this.currentPath_.length; i++) {
var p = this.currentPath_[i];
if (p.type == "moveTo") {
lineStr.push(" m ");
var c = this.getCoords_(p.x, p.y);
lineStr.push(mr(c.x), ",", mr(c.y));
} else if (p.type == "lineTo") {
lineStr.push(" l ");
var c = this.getCoords_(p.x, p.y);
lineStr.push(mr(c.x), ",", mr(c.y));
} else if (p.type == "close") {
lineStr.push(" x ");
} else if (p.type == "bezierCurveTo") {
lineStr.push(" c ");
var c = this.getCoords_(p.x, p.y);
var c1 = this.getCoords_(p.cp1x, p.cp1y);
var c2 = this.getCoords_(p.cp2x, p.cp2y);
lineStr.push(mr(c1.x), ",", mr(c1.y), ",",
mr(c2.x), ",", mr(c2.y), ",",
mr(c.x), ",", mr(c.y));
} else if (p.type == "at" || p.type == "wa") {
lineStr.push(" ", p.type, " ");
var c = this.getCoords_(p.x, p.y);
var cStart = this.getCoords_(p.xStart, p.yStart);
var cEnd = this.getCoords_(p.xEnd, p.yEnd);
lineStr.push(mr(c.x - this.arcScaleX_ * p.radius), ",",
mr(c.y - this.arcScaleY_ * p.radius), " ",
mr(c.x + this.arcScaleX_ * p.radius), ",",
mr(c.y + this.arcScaleY_ * p.radius), " ",
mr(cStart.x), ",", mr(cStart.y), " ",
mr(cEnd.x), ",", mr(cEnd.y));
}
// TODO: Following is broken for curves due to
// move to proper paths.
// Figure out dimensions so we can do gradient fills
// properly
if(c) {
if (min.x == null || c.x < min.x) {
min.x = c.x;
}
if (max.x == null || c.x > max.x) {
max.x = c.x;
}
if (min.y == null || c.y < min.y) {
min.y = c.y;
}
if (max.y == null || c.y > max.y) {
max.y = c.y;
}
}
}
lineStr.push(' ">');
if (typeof this.fillStyle == "object") {
var focus = {x: "50%", y: "50%"};
var width = (max.x - min.x);
var height = (max.y - min.y);
var dimension = (width > height) ? width : height;
focus.x = mr((this.fillStyle.focus_.x / width) * 100 + 50) + "%";
focus.y = mr((this.fillStyle.focus_.y / height) * 100 + 50) + "%";
var colors = [];
// inside radius (%)
if (this.fillStyle.type_ == "gradientradial") {
var inside = (this.fillStyle.radius1_ / dimension * 100);
// percentage that outside radius exceeds inside radius
var expansion = (this.fillStyle.radius2_ / dimension * 100) - inside;
} else {
var inside = 0;
var expansion = 100;
}
var insidecolor = {offset: null, color: null};
var outsidecolor = {offset: null, color: null};
// We need to sort 'colors' by percentage, from 0 > 100 otherwise ie
// won't interpret it correctly
this.fillStyle.colors_.sort(function (cs1, cs2) {
return cs1.offset - cs2.offset;
});
for (var i = 0; i < this.fillStyle.colors_.length; i++) {
var fs = this.fillStyle.colors_[i];
colors.push( (fs.offset * expansion) + inside, "% ", fs.color, ",");
if (fs.offset > insidecolor.offset || insidecolor.offset == null) {
insidecolor.offset = fs.offset;
insidecolor.color = fs.color;
}
if (fs.offset < outsidecolor.offset || outsidecolor.offset == null) {
outsidecolor.offset = fs.offset;
outsidecolor.color = fs.color;
}
}
colors.pop();
lineStr.push('<g_vml_:fill',
' color="', outsidecolor.color, '"',
' color2="', insidecolor.color, '"',
' type="', this.fillStyle.type_, '"',
' focusposition="', focus.x, ', ', focus.y, '"',
' colors="', colors.join(""), '"',
' opacity="', opacity, '" />');
} else if (aFill) {
lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />');
} else {
lineStr.push(
'<g_vml_:stroke',
' opacity="', opacity,'"',
' joinstyle="', this.lineJoin, '"',
' miterlimit="', this.miterLimit, '"',
' endcap="', processLineCap(this.lineCap) ,'"',
' weight="', this.lineWidth, 'px"',
' color="', color,'" />'
);
}
lineStr.push("</g_vml_:shape>");
this.element_.insertAdjacentHTML("beforeEnd", lineStr.join(""));
//this.currentPath_ = [];
};
contextPrototype.fill = function() {
this.stroke(true);
};
contextPrototype.closePath = function() {
this.currentPath_.push({type: "close"});
};
/**
* @private
*/
contextPrototype.getCoords_ = function(aX, aY) {
return {
x: Z * (aX * this.m_[0][0] + aY * this.m_[1][0] + this.m_[2][0]) - Z2,
y: Z * (aX * this.m_[0][1] + aY * this.m_[1][1] + this.m_[2][1]) - Z2
}
};
contextPrototype.save = function() {
var o = {};
copyState(this, o);
this.aStack_.push(o);
this.mStack_.push(this.m_);
this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
};
contextPrototype.restore = function() {
copyState(this.aStack_.pop(), this);
this.m_ = this.mStack_.pop();
};
contextPrototype.translate = function(aX, aY) {
var m1 = [
[1, 0, 0],
[0, 1, 0],
[aX, aY, 1]
];
this.m_ = matrixMultiply(m1, this.m_);
};
contextPrototype.rotate = function(aRot) {
var c = mc(aRot);
var s = ms(aRot);
var m1 = [
[c, s, 0],
[-s, c, 0],
[0, 0, 1]
];
this.m_ = matrixMultiply(m1, this.m_);
};
contextPrototype.scale = function(aX, aY) {
this.arcScaleX_ *= aX;
this.arcScaleY_ *= aY;
var m1 = [
[aX, 0, 0],
[0, aY, 0],
[0, 0, 1]
];
this.m_ = matrixMultiply(m1, this.m_);
};
/******** STUBS ********/
contextPrototype.clip = function() {
// TODO: Implement
};
contextPrototype.arcTo = function() {
// TODO: Implement
};
contextPrototype.createPattern = function() {
return new CanvasPattern_;
};
// Gradient / Pattern Stubs
function CanvasGradient_(aType) {
this.type_ = aType;
this.radius1_ = 0;
this.radius2_ = 0;
this.colors_ = [];
this.focus_ = {x: 0, y: 0};
}
CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
aColor = processStyle(aColor);
this.colors_.push({offset: 1-aOffset, color: aColor});
};
function CanvasPattern_() {}
// set up externs
G_vmlCanvasManager = G_vmlCanvasManager_;
CanvasRenderingContext2D = CanvasRenderingContext2D_;
CanvasGradient = CanvasGradient_;
CanvasPattern = CanvasPattern_;
})();
} // if | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/data/flot/excanvas.js | excanvas.js |
(function($) {
function Plot(target_, data_, options_) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label" }
var series = [];
var options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85 // set to 0 to avoid background
},
xaxis: {
mode: null, // null or "time"
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
// mode specific options
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null, // number or [number, "unit"]
monthNames: null, // list of names of months
timeformat: null // format string to use
},
yaxis: {
autoscaleMargin: 0.02
},
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff"
},
lines: {
show: false,
lineWidth: 2, // in pixels
fill: false,
fillColor: null
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null
},
grid: {
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
tickColor: "#dddddd", // color used for the ticks
labelMargin: 3, // in pixels
borderWidth: 2,
clickable: null,
coloredAreas: null, // array of { x1, y1, x2, y2 } or fn: plot area -> areas
coloredAreasColor: "#f4f4f4"
},
selection: {
mode: null, // one of null, "x", "y" or "xy"
color: "#e8cfac"
},
shadowSize: 4
};
var canvas = null, overlay = null, eventHolder = null,
ctx = null, octx = null,
target = target_,
xaxis = {}, yaxis = {},
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
canvasWidth = 0, canvasHeight = 0,
plotWidth = 0, plotHeight = 0,
hozScale = 0, vertScale = 0,
// dedicated to storing data for buggy standard compliance cases
workarounds = {};
this.setData = setData;
this.setupGrid = setupGrid;
this.draw = draw;
this.clearSelection = clearSelection;
this.setSelection = setSelection;
this.getCanvas = function() { return canvas; };
this.getPlotOffset = function() { return plotOffset; };
this.getData = function() { return series; };
this.getAxes = function() { return { xaxis: xaxis, yaxis: yaxis }; };
// initialize
parseOptions(options_);
setData(data_);
constructCanvas();
setupGrid();
draw();
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s;
if (d[i].data) {
s = {};
for (var v in d[i])
s[v] = d[i][v];
}
else {
s = { data: d[i] };
}
res.push(s);
}
return res;
}
function parseOptions(o) {
$.extend(true, options, o);
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
}
function fillInSeriesOptions() {
var i;
// collect what we already got of colors
var neededColors = series.length;
var usedColors = [];
var assignedColors = [];
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
--neededColors;
if (typeof sc == "number")
assignedColors.push(sc);
else
usedColors.push(parseColor(series[i].color));
}
}
// we might need to generate more colors if higher indices
// are assigned
for (i = 0; i < assignedColors.length; ++i) {
neededColors = Math.max(neededColors, assignedColors[i] + 1);
}
// produce colors as needed
var colors = [];
var variation = 0;
i = 0;
while (colors.length < neededColors) {
var c;
if (options.colors.length == i) // check degenerate case
c = new Color(100, 100, 100);
else
c = parseColor(options.colors[i]);
// vary color if needed
var sign = variation % 2 == 1 ? -1 : 1;
var factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
c.scale(factor, factor, factor);
// FIXME: if we're getting to close to something else,
// we should probably skip this one
colors.push(c);
++i;
if (i >= options.colors.length) {
i = 0;
++variation;
}
}
// fill in the options
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// copy the rest
s.lines = $.extend(true, {}, options.lines, s.lines);
s.points = $.extend(true, {}, options.points, s.points);
s.bars = $.extend(true, {}, options.bars, s.bars);
if (s.shadowSize == null)
s.shadowSize = options.shadowSize;
}
}
function processData() {
var top_sentry = Number.POSITIVE_INFINITY,
bottom_sentry = Number.NEGATIVE_INFINITY;
xaxis.datamin = yaxis.datamin = top_sentry;
xaxis.datamax = yaxis.datamax = bottom_sentry;
for (var i = 0; i < series.length; ++i) {
var data = series[i].data;
for (var j = 0; j < data.length; ++j) {
if (data[j] == null)
continue;
var x = data[j][0], y = data[j][1];
// convert to number
if (x == null || y == null || isNaN(x = +x) || isNaN(y = +y)) {
data[j] = null; // mark this point as invalid
continue;
}
if (x < xaxis.datamin)
xaxis.datamin = x;
if (x > xaxis.datamax)
xaxis.datamax = x;
if (y < yaxis.datamin)
yaxis.datamin = y;
if (y > yaxis.datamax)
yaxis.datamax = y;
}
}
if (xaxis.datamin == top_sentry)
xaxis.datamin = 0;
if (yaxis.datamin == top_sentry)
yaxis.datamin = 0;
if (xaxis.datamax == bottom_sentry)
xaxis.datamax = 1;
if (yaxis.datamax == bottom_sentry)
yaxis.datamax = 1;
}
function constructCanvas() {
canvasWidth = target.width();
canvasHeight = target.height();
target.html(""); // clear target
target.css("position", "relative"); // for positioning labels and overlay
if (canvasWidth <= 0 || canvasHeight <= 0)
throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
// the canvas
canvas = $('<canvas width="' + canvasWidth + '" height="' + canvasHeight + '"></canvas>').appendTo(target).get(0);
if ($.browser.msie) // excanvas hack
canvas = window.G_vmlCanvasManager.initElement(canvas);
ctx = canvas.getContext("2d");
// overlay canvas for interactive features
overlay = $('<canvas style="position:absolute;left:0px;top:0px;" width="' + canvasWidth + '" height="' + canvasHeight + '"></canvas>').appendTo(target).get(0);
if ($.browser.msie) // excanvas hack
overlay = window.G_vmlCanvasManager.initElement(overlay);
octx = overlay.getContext("2d");
// we include the canvas in the event holder too, because IE 7
// sometimes has trouble with the stacking order
eventHolder = $([overlay, canvas]);
// bind events
if (options.selection.mode != null) {
eventHolder.mousedown(onMouseDown);
// FIXME: temp. work-around until jQuery bug 1871 is fixed
eventHolder.each(function () {
this.onmousemove = onMouseMove;
});
}
if (options.grid.clickable)
eventHolder.click(onClick);
}
function setupGrid() {
// x axis
setRange(xaxis, options.xaxis);
prepareTickGeneration(xaxis, options.xaxis);
setTicks(xaxis, options.xaxis);
extendXRangeIfNeededByBar();
// y axis
setRange(yaxis, options.yaxis);
prepareTickGeneration(yaxis, options.yaxis);
setTicks(yaxis, options.yaxis);
setSpacing();
insertLabels();
insertLegend();
}
function setRange(axis, axisOptions) {
var min = axisOptions.min != null ? axisOptions.min : axis.datamin;
var max = axisOptions.max != null ? axisOptions.max : axis.datamax;
if (max - min == 0.0) {
// degenerate case
var widen;
if (max == 0.0)
widen = 1.0;
else
widen = 0.01;
min -= widen;
max += widen;
}
else {
// consider autoscaling
var margin = axisOptions.autoscaleMargin;
if (margin != null) {
if (axisOptions.min == null) {
min -= (max - min) * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin >= 0)
min = 0;
}
if (axisOptions.max == null) {
max += (max - min) * margin;
if (max > 0 && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function prepareTickGeneration(axis, axisOptions) {
// estimate number of ticks
var noTicks;
if (typeof axisOptions.ticks == "number" && axisOptions.ticks > 0)
noTicks = axisOptions.ticks;
else if (axis == xaxis)
noTicks = canvasWidth / 100;
else
noTicks = canvasHeight / 60;
var delta = (axis.max - axis.min) / noTicks;
var size, generator, unit, formatter, i, magn, norm;
if (axisOptions.mode == "time") {
// pretty handling of time
function formatDate(d, fmt, monthNames) {
var leftPad = function(n) {
n = "" + n;
return n.length == 1 ? "0" + n : n;
};
var r = [];
var escape = false;
if (monthNames == null)
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'h': c = "" + d.getUTCHours(); break;
case 'H': c = leftPad(d.getUTCHours()); break;
case 'M': c = leftPad(d.getUTCMinutes()); break;
case 'S': c = leftPad(d.getUTCSeconds()); break;
case 'd': c = "" + d.getUTCDate(); break;
case 'm': c = "" + (d.getUTCMonth() + 1); break;
case 'y': c = "" + d.getUTCFullYear(); break;
case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
}
r.push(c);
escape = false;
}
else {
if (c == "%")
escape = true;
else
r.push(c);
}
}
return r.join("");
}
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var spec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"], [3, "month"], [6, "month"],
[1, "year"]
];
var minSize = 0;
if (axisOptions.minTickSize != null) {
if (typeof axisOptions.tickSize == "number")
minSize = axisOptions.tickSize;
else
minSize = axisOptions.minTickSize[0] * timeUnitSize[axisOptions.minTickSize[1]];
}
for (i = 0; i < spec.length - 1; ++i)
if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
break;
size = spec[i][0];
unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
norm = (delta / timeUnitSize.year) / magn;
if (norm < 1.5)
size = 1;
else if (norm < 3)
size = 2;
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
}
if (axisOptions.tickSize) {
size = axisOptions.tickSize[0];
unit = axisOptions.tickSize[1];
}
generator = function(axis) {
var ticks = [],
tickSize = axis.tickSize[0], unit = axis.tickSize[1],
d = new Date(axis.min);
var step = tickSize * timeUnitSize[unit];
if (unit == "second")
d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
if (unit == "minute")
d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
if (unit == "hour")
d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
if (unit == "month")
d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
if (unit == "year")
d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
// reset smaller components
d.setUTCMilliseconds(0);
if (step >= timeUnitSize.minute)
d.setUTCSeconds(0);
if (step >= timeUnitSize.hour)
d.setUTCMinutes(0);
if (step >= timeUnitSize.day)
d.setUTCHours(0);
if (step >= timeUnitSize.day * 4)
d.setUTCDate(1);
if (step >= timeUnitSize.year)
d.setUTCMonth(0);
var carry = 0, v = Number.NaN, prev;
do {
prev = v;
v = d.getTime();
ticks.push({ v: v, label: axis.tickFormatter(v, axis) });
if (unit == "month") {
if (tickSize < 1) {
// a bit complicated - we'll divide the month
// up but we need to take care of fractions
// so we don't end up in the middle of a day
d.setUTCDate(1);
var start = d.getTime();
d.setUTCMonth(d.getUTCMonth() + 1);
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getUTCHours();
d.setUTCHours(0);
}
else
d.setUTCMonth(d.getUTCMonth() + tickSize);
}
else if (unit == "year") {
d.setUTCFullYear(d.getUTCFullYear() + tickSize);
}
else
d.setTime(v + step);
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
var d = new Date(v);
// first check global format
if (axisOptions.timeformat != null)
return formatDate(d, axisOptions.timeformat, axisOptions.monthNames);
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
if (t < timeUnitSize.minute)
fmt = "%h:%M:%S";
else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day)
fmt = "%h:%M";
else
fmt = "%b %d %h:%M";
}
else if (t < timeUnitSize.month)
fmt = "%b %d";
else if (t < timeUnitSize.year) {
if (span < timeUnitSize.year)
fmt = "%b";
else
fmt = "%b %y";
}
else
fmt = "%y";
return formatDate(d, fmt, axisOptions.monthNames);
};
}
else {
// pretty rounding of base-10 numbers
var maxDec = axisOptions.tickDecimals;
var dec = -Math.floor(Math.log(delta) / Math.LN10);
if (maxDec != null && dec > maxDec)
dec = maxDec;
magn = Math.pow(10, -dec);
norm = delta / magn; // norm is between 1.0 and 10.0
if (norm < 1.5)
size = 1;
else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
}
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
if (axisOptions.minTickSize != null && size < axisOptions.minTickSize)
size = axisOptions.minTickSize;
if (axisOptions.tickSize != null)
size = axisOptions.tickSize;
axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec);
generator = function (axis) {
var ticks = [];
var start = floorInBase(axis.min, axis.tickSize);
// then spew out all possible ticks
var i = 0, v = Number.NaN, prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push({ v: v, label: axis.tickFormatter(v, axis) });
++i;
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
}
axis.tickSize = unit ? [size, unit] : size;
axis.tickGenerator = generator;
if ($.isFunction(axisOptions.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + axisOptions.tickFormatter(v, axis); };
else
axis.tickFormatter = formatter;
if (axisOptions.labelWidth != null)
axis.labelWidth = axisOptions.labelWidth;
if (axisOptions.labelHeight != null)
axis.labelHeight = axisOptions.labelHeight;
}
function extendXRangeIfNeededByBar() {
if (options.xaxis.max == null) {
// great, we're autoscaling, check if we might need a bump
var newmax = xaxis.max;
for (var i = 0; i < series.length; ++i)
if (series[i].bars.show && series[i].bars.barWidth + xaxis.datamax > newmax)
newmax = xaxis.datamax + series[i].bars.barWidth;
xaxis.max = newmax;
}
}
function setTicks(axis, axisOptions) {
axis.ticks = [];
if (axisOptions.ticks == null)
axis.ticks = axis.tickGenerator(axis);
else if (typeof axisOptions.ticks == "number") {
if (axisOptions.ticks > 0)
axis.ticks = axis.tickGenerator(axis);
}
else if (axisOptions.ticks) {
var ticks = axisOptions.ticks;
if ($.isFunction(ticks))
// generate the ticks
ticks = ticks({ min: axis.min, max: axis.max });
// clean up the user-supplied ticks, copy them over
var i, v;
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = t[0];
if (t.length > 1)
label = t[1];
}
else
v = t;
if (label == null)
label = axis.tickFormatter(v, axis);
axis.ticks[i] = { v: v, label: label };
}
}
if (axisOptions.autoscaleMargin != null && axis.ticks.length > 0) {
// snap to ticks
if (axisOptions.min == null)
axis.min = Math.min(axis.min, axis.ticks[0].v);
if (axisOptions.max == null && axis.ticks.length > 1)
axis.max = Math.min(axis.max, axis.ticks[axis.ticks.length - 1].v);
}
}
function setSpacing() {
var i, labels = [], l;
if (yaxis.labelWidth == null || yaxis.labelHeight == null) {
// calculate y label dimensions
for (i = 0; i < yaxis.ticks.length; ++i) {
l = yaxis.ticks[i].label;
if (l)
labels.push('<div class="tickLabel">' + l + '</div>');
}
if (labels.length > 0) {
var dummyDiv = $('<div style="position:absolute;top:-10000px;font-size:smaller">'
+ labels.join("") + '</div>').appendTo(target);
if (yaxis.labelWidth == null)
yaxis.labelWidth = dummyDiv.width();
if (yaxis.labelHeight == null)
yaxis.labelHeight = dummyDiv.find("div").height();
dummyDiv.remove();
}
if (yaxis.labelWidth == null)
yaxis.labelWidth = 0;
if (yaxis.labelHeight == null)
yaxis.labelHeight = 0;
}
var maxOutset = options.grid.borderWidth / 2;
if (options.points.show)
maxOutset = Math.max(maxOutset, options.points.radius + options.points.lineWidth/2);
for (i = 0; i < series.length; ++i) {
if (series[i].points.show)
maxOutset = Math.max(maxOutset, series[i].points.radius + series[i].points.lineWidth/2);
}
plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset;
if (yaxis.labelWidth > 0)
plotOffset.left += yaxis.labelWidth + options.grid.labelMargin;
plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
// set width for labels; to avoid measuring the widths of
// the labels, we construct fixed-size boxes and put the
// labels inside them, the fixed-size boxes are easy to
// mid-align
if (xaxis.labelWidth == null)
xaxis.labelWidth = plotWidth / 6;
if (xaxis.labelHeight == null) {
// measure x label heights
labels = [];
for (i = 0; i < xaxis.ticks.length; ++i) {
l = xaxis.ticks[i].label;
if (l)
labels.push('<span class="tickLabel" width="' + xaxis.labelWidth + '">' + l + '</span>');
}
xaxis.labelHeight = 0;
if (labels.length > 0) {
var dummyDiv = $('<div style="position:absolute;top:-10000px;font-size:smaller">'
+ labels.join("") + '</div>').appendTo(target);
xaxis.labelHeight = dummyDiv.height();
dummyDiv.remove();
}
}
if (xaxis.labelHeight > 0)
plotOffset.bottom += xaxis.labelHeight + options.grid.labelMargin;
plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
hozScale = plotWidth / (xaxis.max - xaxis.min);
vertScale = plotHeight / (yaxis.max - yaxis.min);
}
function draw() {
drawGrid();
for (var i = 0; i < series.length; i++) {
drawSeries(series[i]);
}
}
function tHoz(x) {
return (x - xaxis.min) * hozScale;
}
function tVert(y) {
return plotHeight - (y - yaxis.min) * vertScale;
}
function drawGrid() {
var i;
ctx.save();
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.translate(plotOffset.left, plotOffset.top);
// draw background, if any
if (options.grid.backgroundColor) {
ctx.fillStyle = options.grid.backgroundColor;
ctx.fillRect(0, 0, plotWidth, plotHeight);
}
// draw colored areas
if (options.grid.coloredAreas) {
var areas = options.grid.coloredAreas;
if ($.isFunction(areas))
areas = areas({ xmin: xaxis.min, xmax: xaxis.max, ymin: yaxis.min, ymax: yaxis.max });
for (i = 0; i < areas.length; ++i) {
var a = areas[i];
// clip
if (a.x1 == null || a.x1 < xaxis.min)
a.x1 = xaxis.min;
if (a.x2 == null || a.x2 > xaxis.max)
a.x2 = xaxis.max;
if (a.y1 == null || a.y1 < yaxis.min)
a.y1 = yaxis.min;
if (a.y2 == null || a.y2 > yaxis.max)
a.y2 = yaxis.max;
var tmp;
if (a.x1 > a.x2) {
tmp = a.x1;
a.x1 = a.x2;
a.x2 = tmp;
}
if (a.y1 > a.y2) {
tmp = a.y1;
a.y1 = a.y2;
a.y2 = tmp;
}
if (a.x1 >= xaxis.max || a.x2 <= xaxis.min || a.x1 == a.x2
|| a.y1 >= yaxis.max || a.y2 <= yaxis.min || a.y1 == a.y2)
continue;
ctx.fillStyle = a.color || options.grid.coloredAreasColor;
ctx.fillRect(Math.floor(tHoz(a.x1)), Math.floor(tVert(a.y2)),
Math.floor(tHoz(a.x2) - tHoz(a.x1)), Math.floor(tVert(a.y1) - tVert(a.y2)));
}
}
// draw the inner grid
ctx.lineWidth = 1;
ctx.strokeStyle = options.grid.tickColor;
ctx.beginPath();
var v;
for (i = 0; i < xaxis.ticks.length; ++i) {
v = xaxis.ticks[i].v;
if (v <= xaxis.min || v >= xaxis.max)
continue; // skip those lying on the axes
ctx.moveTo(Math.floor(tHoz(v)) + ctx.lineWidth/2, 0);
ctx.lineTo(Math.floor(tHoz(v)) + ctx.lineWidth/2, plotHeight);
}
for (i = 0; i < yaxis.ticks.length; ++i) {
v = yaxis.ticks[i].v;
if (v <= yaxis.min || v >= yaxis.max)
continue;
ctx.moveTo(0, Math.floor(tVert(v)) + ctx.lineWidth/2);
ctx.lineTo(plotWidth, Math.floor(tVert(v)) + ctx.lineWidth/2);
}
ctx.stroke();
if (options.grid.borderWidth) {
// draw border
ctx.lineWidth = options.grid.borderWidth;
ctx.strokeStyle = options.grid.color;
ctx.lineJoin = "round";
ctx.strokeRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
}
function insertLabels() {
target.find(".tickLabels").remove();
var i, tick;
var html = '<div class="tickLabels" style="font-size:smaller;color:' + options.grid.color + '">';
// do the x-axis
for (i = 0; i < xaxis.ticks.length; ++i) {
tick = xaxis.ticks[i];
if (!tick.label || tick.v < xaxis.min || tick.v > xaxis.max)
continue;
html += '<div style="position:absolute;top:' + (plotOffset.top + plotHeight + options.grid.labelMargin) + 'px;left:' + (plotOffset.left + tHoz(tick.v) - xaxis.labelWidth/2) + 'px;width:' + xaxis.labelWidth + 'px;text-align:center" class="tickLabel">' + tick.label + "</div>";
}
// do the y-axis
for (i = 0; i < yaxis.ticks.length; ++i) {
tick = yaxis.ticks[i];
if (!tick.label || tick.v < yaxis.min || tick.v > yaxis.max)
continue;
html += '<div style="position:absolute;top:' + (plotOffset.top + tVert(tick.v) - yaxis.labelHeight/2) + 'px;left:0;width:' + yaxis.labelWidth + 'px;text-align:right" class="tickLabel">' + tick.label + "</div>";
}
html += '</div>';
target.append(html);
}
function drawSeries(series) {
if (series.lines.show || (!series.bars.show && !series.points.show))
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(data, offset) {
var prev, cur = null, drawx = null, drawy = null;
ctx.beginPath();
for (var i = 0; i < data.length; ++i) {
prev = cur;
cur = data[i];
if (prev == null || cur == null)
continue;
var x1 = prev[0], y1 = prev[1],
x2 = cur[0], y2 = cur[1];
// clip with ymin
if (y1 <= y2 && y1 < yaxis.min) {
if (y2 < yaxis.min)
continue; // line segment is outside
// compute new intersection point
x1 = (yaxis.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = yaxis.min;
}
else if (y2 <= y1 && y2 < yaxis.min) {
if (y1 < yaxis.min)
continue;
x2 = (yaxis.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = yaxis.min;
}
// clip with ymax
if (y1 >= y2 && y1 > yaxis.max) {
if (y2 > yaxis.max)
continue;
x1 = (yaxis.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = yaxis.max;
}
else if (y2 >= y1 && y2 > yaxis.max) {
if (y1 > yaxis.max)
continue;
x2 = (yaxis.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = yaxis.max;
}
// clip with xmin
if (x1 <= x2 && x1 < xaxis.min) {
if (x2 < xaxis.min)
continue;
y1 = (xaxis.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = xaxis.min;
}
else if (x2 <= x1 && x2 < xaxis.min) {
if (x1 < xaxis.min)
continue;
y2 = (xaxis.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = xaxis.min;
}
// clip with xmax
if (x1 >= x2 && x1 > xaxis.max) {
if (x2 > xaxis.max)
continue;
y1 = (xaxis.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = xaxis.max;
}
else if (x2 >= x1 && x2 > xaxis.max) {
if (x1 > xaxis.max)
continue;
y2 = (xaxis.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = xaxis.max;
}
if (drawx != tHoz(x1) || drawy != tVert(y1) + offset)
ctx.moveTo(tHoz(x1), tVert(y1) + offset);
drawx = tHoz(x2);
drawy = tVert(y2) + offset;
ctx.lineTo(drawx, drawy);
}
ctx.stroke();
}
function plotLineArea(data) {
var prev, cur = null;
var bottom = Math.min(Math.max(0, yaxis.min), yaxis.max);
var top, lastX = 0;
var areaOpen = false;
for (var i = 0; i < data.length; ++i) {
prev = cur;
cur = data[i];
if (areaOpen && prev != null && cur == null) {
// close area
ctx.lineTo(tHoz(lastX), tVert(bottom));
ctx.fill();
areaOpen = false;
continue;
}
if (prev == null || cur == null)
continue;
var x1 = prev[0], y1 = prev[1],
x2 = cur[0], y2 = cur[1];
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < xaxis.min) {
if (x2 < xaxis.min)
continue;
y1 = (xaxis.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = xaxis.min;
}
else if (x2 <= x1 && x2 < xaxis.min) {
if (x1 < xaxis.min)
continue;
y2 = (xaxis.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = xaxis.min;
}
// clip with xmax
if (x1 >= x2 && x1 > xaxis.max) {
if (x2 > xaxis.max)
continue;
y1 = (xaxis.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = xaxis.max;
}
else if (x2 >= x1 && x2 > xaxis.max) {
if (x1 > xaxis.max)
continue;
y2 = (xaxis.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = xaxis.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(tHoz(x1), tVert(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= yaxis.max && y2 >= yaxis.max) {
ctx.lineTo(tHoz(x1), tVert(yaxis.max));
ctx.lineTo(tHoz(x2), tVert(yaxis.max));
continue;
}
else if (y1 <= yaxis.min && y2 <= yaxis.min) {
ctx.lineTo(tHoz(x1), tVert(yaxis.min));
ctx.lineTo(tHoz(x2), tVert(yaxis.min));
continue;
}
// else it's a bit more complicated, there might
// be two rectangles and two triangles we need to fill
// in; to find these keep track of the current x values
var x1old = x1, x2old = x2;
// and clip the y values, without shortcutting
// clip with ymin
if (y1 <= y2 && y1 < yaxis.min && y2 >= yaxis.min) {
x1 = (yaxis.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = yaxis.min;
}
else if (y2 <= y1 && y2 < yaxis.min && y1 >= yaxis.min) {
x2 = (yaxis.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = yaxis.min;
}
// clip with ymax
if (y1 >= y2 && y1 > yaxis.max && y2 <= yaxis.max) {
x1 = (yaxis.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = yaxis.max;
}
else if (y2 >= y1 && y2 > yaxis.max && y1 <= yaxis.max) {
x2 = (yaxis.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = yaxis.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
if (y1 <= yaxis.min)
top = yaxis.min;
else
top = yaxis.max;
ctx.lineTo(tHoz(x1old), tVert(top));
ctx.lineTo(tHoz(x1), tVert(top));
}
// fill the triangles
ctx.lineTo(tHoz(x1), tVert(y1));
ctx.lineTo(tHoz(x2), tVert(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
if (y2 <= yaxis.min)
top = yaxis.min;
else
top = yaxis.max;
ctx.lineTo(tHoz(x2old), tVert(top));
ctx.lineTo(tHoz(x2), tVert(top));
}
lastX = Math.max(x2, x2old);
}
if (areaOpen) {
ctx.lineTo(tHoz(lastX), tVert(bottom));
ctx.fill();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth;
var sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (sw > 0) {
// draw shadow in two steps
ctx.lineWidth = sw / 2;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotLine(series.data, lw/2 + sw/2 + ctx.lineWidth/2);
ctx.lineWidth = sw / 2;
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotLine(series.data, lw/2 + ctx.lineWidth/2);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
setFillStyle(series.lines, series.color);
if (series.lines.fill)
plotLineArea(series.data, 0);
plotLine(series.data, 0);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(data, radius, fill) {
for (var i = 0; i < data.length; ++i) {
if (data[i] == null)
continue;
var x = data[i][0], y = data[i][1];
if (x < xaxis.min || x > xaxis.max || y < yaxis.min || y > yaxis.max)
continue;
ctx.beginPath();
ctx.arc(tHoz(x), tVert(y), radius, 0, 2 * Math.PI, true);
if (fill)
ctx.fill();
ctx.stroke();
}
}
function plotPointShadows(data, offset, radius) {
for (var i = 0; i < data.length; ++i) {
if (data[i] == null)
continue;
var x = data[i][0], y = data[i][1];
if (x < xaxis.min || x > xaxis.max || y < yaxis.min || y > yaxis.max)
continue;
ctx.beginPath();
ctx.arc(tHoz(x), tVert(y) + offset, radius, 0, Math.PI, false);
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.lines.lineWidth;
var sw = series.shadowSize;
if (sw > 0) {
// draw shadow in two steps
ctx.lineWidth = sw / 2;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPointShadows(series.data, sw/2 + ctx.lineWidth/2, series.points.radius);
ctx.lineWidth = sw / 2;
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPointShadows(series.data, ctx.lineWidth/2, series.points.radius);
}
ctx.lineWidth = series.points.lineWidth;
ctx.strokeStyle = series.color;
setFillStyle(series.points, series.color);
plotPoints(series.data, series.points.radius, series.points.fill);
ctx.restore();
}
function drawSeriesBars(series) {
function plotBars(data, barWidth, offset, fill) {
for (var i = 0; i < data.length; i++) {
if (data[i] == null)
continue;
var x = data[i][0], y = data[i][1];
var drawLeft = true, drawTop = true, drawRight = true;
var left = x, right = x + barWidth, bottom = 0, top = y;
if (right < xaxis.min || left > xaxis.max || top < yaxis.min || bottom > yaxis.max)
continue;
// clip
if (left < xaxis.min) {
left = xaxis.min;
drawLeft = false;
}
if (right > xaxis.max) {
right = xaxis.max;
drawRight = false;
}
if (bottom < yaxis.min)
bottom = yaxis.min;
if (top > yaxis.max) {
top = yaxis.max;
drawTop = false;
}
// fill the bar
if (fill) {
ctx.beginPath();
ctx.moveTo(tHoz(left), tVert(bottom) + offset);
ctx.lineTo(tHoz(left), tVert(top) + offset);
ctx.lineTo(tHoz(right), tVert(top) + offset);
ctx.lineTo(tHoz(right), tVert(bottom) + offset);
ctx.fill();
}
// draw outline
if (drawLeft || drawRight || drawTop) {
ctx.beginPath();
ctx.moveTo(tHoz(left), tVert(bottom) + offset);
if (drawLeft)
ctx.lineTo(tHoz(left), tVert(top) + offset);
else
ctx.moveTo(tHoz(left), tVert(top) + offset);
if (drawTop)
ctx.lineTo(tHoz(right), tVert(top) + offset);
else
ctx.moveTo(tHoz(right), tVert(top) + offset);
if (drawRight)
ctx.lineTo(tHoz(right), tVert(bottom) + offset);
else
ctx.moveTo(tHoz(right), tVert(bottom) + offset);
ctx.stroke();
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var bw = series.bars.barWidth;
var lw = Math.min(series.bars.lineWidth, bw);
// FIXME: figure out a way to add shadows
/*
var sw = series.shadowSize;
if (sw > 0) {
// draw shadow in two steps
ctx.lineWidth = sw / 2;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotBars(series.data, bw, lw/2 + sw/2 + ctx.lineWidth/2, false);
ctx.lineWidth = sw / 2;
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotBars(series.data, bw, lw/2 + ctx.lineWidth/2, false);
}*/
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
setFillStyle(series.bars, series.color);
plotBars(series.data, bw, 0, series.bars.fill);
ctx.restore();
}
function setFillStyle(obj, seriesColor) {
var fill = obj.fill;
if (fill) {
if (obj.fillColor)
ctx.fillStyle = obj.fillColor;
else {
var c = parseColor(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
ctx.fillStyle = c.toString();
}
}
}
function insertLegend() {
target.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [];
var rowStarted = false;
for (i = 0; i < series.length; ++i) {
if (!series[i].label)
continue;
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
var label = series[i].label;
if (options.legend.labelFormatter != null)
label = options.legend.labelFormatter(label);
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:14px;height:10px;background-color:' + series[i].color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + label + '</td>');
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length > 0) {
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
options.legend.container.append(table);
else {
var pos = "";
var p = options.legend.position, m = options.legend.margin;
if (p.charAt(0) == "n")
pos += 'top:' + (m + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m + plotOffset.bottom) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(target);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
var tmp;
if (options.grid.backgroundColor)
tmp = options.grid.backgroundColor;
else
tmp = extractColor(legend);
c = parseColor(tmp).adjust(null, null, null, 1).toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
}
var lastMousePos = { pageX: null, pageY: null };
var selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1} };
var prevSelection = null;
var selectionInterval = null;
var ignoreClick = false;
function onMouseMove(ev) {
// FIXME: temp. work-around until jQuery bug 1871 is fixed
var e = ev || window.event;
if (e.pageX == null && e.clientX != null) {
var de = document.documentElement, b = document.body;
lastMousePos.pageX = e.clientX + (de && de.scrollLeft || b.scrollLeft || 0);
lastMousePos.pageY = e.clientY + (de && de.scrollTop || b.scrollTop || 0);
}
else {
lastMousePos.pageX = e.pageX;
lastMousePos.pageY = e.pageY;
}
}
function onMouseDown(e) {
if (e.which != 1) // only accept left-click
return;
// cancel out any text selections
document.body.focus();
// prevent text selection and drag in old-school browsers
if (document.onselectstart !== undefined && workarounds.onselectstart == null) {
workarounds.onselectstart = document.onselectstart;
document.onselectstart = function () { return false; };
}
if (document.ondrag !== undefined && workarounds.ondrag == null) {
workarounds.ondrag = document.ondrag;
document.ondrag = function () { return false; };
}
setSelectionPos(selection.first, e);
if (selectionInterval != null)
clearInterval(selectionInterval);
lastMousePos.pageX = null;
selectionInterval = setInterval(updateSelectionOnMouseMove, 200);
$(document).one("mouseup", onSelectionMouseUp);
}
function onClick(e) {
if (ignoreClick) {
ignoreClick = false;
return;
}
var offset = eventHolder.offset();
var pos = {};
pos.x = e.pageX - offset.left - plotOffset.left;
pos.x = xaxis.min + pos.x / hozScale;
pos.y = e.pageY - offset.top - plotOffset.top;
pos.y = yaxis.max - pos.y / vertScale;
target.trigger("plotclick", [ pos ]);
}
function triggerSelectedEvent() {
var x1, x2, y1, y2;
if (selection.first.x <= selection.second.x) {
x1 = selection.first.x;
x2 = selection.second.x;
}
else {
x1 = selection.second.x;
x2 = selection.first.x;
}
if (selection.first.y >= selection.second.y) {
y1 = selection.first.y;
y2 = selection.second.y;
}
else {
y1 = selection.second.y;
y2 = selection.first.y;
}
x1 = xaxis.min + x1 / hozScale;
x2 = xaxis.min + x2 / hozScale;
y1 = yaxis.max - y1 / vertScale;
y2 = yaxis.max - y2 / vertScale;
target.trigger("selected", [ { x1: x1, y1: y1, x2: x2, y2: y2 } ]);
}
function onSelectionMouseUp(e) {
if (document.onselectstart !== undefined)
document.onselectstart = workarounds.onselectstart;
if (document.ondrag !== undefined)
document.ondrag = workarounds.ondrag;
if (selectionInterval != null) {
clearInterval(selectionInterval);
selectionInterval = null;
}
setSelectionPos(selection.second, e);
clearSelection();
if (!selectionIsSane() || e.which != 1)
return false;
drawSelection();
triggerSelectedEvent();
ignoreClick = true;
return false;
}
function setSelectionPos(pos, e) {
var offset = $(overlay).offset();
if (options.selection.mode == "y") {
if (pos == selection.first)
pos.x = 0;
else
pos.x = plotWidth;
}
else {
pos.x = e.pageX - offset.left - plotOffset.left;
pos.x = Math.min(Math.max(0, pos.x), plotWidth);
}
if (options.selection.mode == "x") {
if (pos == selection.first)
pos.y = 0;
else
pos.y = plotHeight;
}
else {
pos.y = e.pageY - offset.top - plotOffset.top;
pos.y = Math.min(Math.max(0, pos.y), plotHeight);
}
}
function updateSelectionOnMouseMove() {
if (lastMousePos.pageX == null)
return;
setSelectionPos(selection.second, lastMousePos);
clearSelection();
if (selectionIsSane())
drawSelection();
}
function clearSelection() {
if (prevSelection == null)
return;
var x = Math.min(prevSelection.first.x, prevSelection.second.x),
y = Math.min(prevSelection.first.y, prevSelection.second.y),
w = Math.abs(prevSelection.second.x - prevSelection.first.x),
h = Math.abs(prevSelection.second.y - prevSelection.first.y);
octx.clearRect(x + plotOffset.left - octx.lineWidth,
y + plotOffset.top - octx.lineWidth,
w + octx.lineWidth*2,
h + octx.lineWidth*2);
prevSelection = null;
}
function setSelection(area) {
clearSelection();
if (options.selection.mode == "x") {
selection.first.y = 0;
selection.second.y = plotHeight;
}
else {
selection.first.y = (yaxis.max - area.y1) * vertScale;
selection.second.y = (yaxis.max - area.y2) * vertScale;
}
if (options.selection.mode == "y") {
selection.first.x = 0;
selection.second.x = plotWidth;
}
else {
selection.first.x = (area.x1 - xaxis.min) * hozScale;
selection.second.x = (area.x2 - xaxis.min) * hozScale;
}
drawSelection();
triggerSelectedEvent();
}
function drawSelection() {
if (prevSelection != null &&
selection.first.x == prevSelection.first.x &&
selection.first.y == prevSelection.first.y &&
selection.second.x == prevSelection.second.x &&
selection.second.y == prevSelection.second.y)
return;
octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString();
octx.lineWidth = 1;
ctx.lineJoin = "round";
octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString();
prevSelection = { first: { x: selection.first.x,
y: selection.first.y },
second: { x: selection.second.x,
y: selection.second.y } };
var x = Math.min(selection.first.x, selection.second.x),
y = Math.min(selection.first.y, selection.second.y),
w = Math.abs(selection.second.x - selection.first.x),
h = Math.abs(selection.second.y - selection.first.y);
octx.fillRect(x + plotOffset.left, y + plotOffset.top, w, h);
octx.strokeRect(x + plotOffset.left, y + plotOffset.top, w, h);
}
function selectionIsSane() {
var minSize = 5;
return Math.abs(selection.second.x - selection.first.x) >= minSize &&
Math.abs(selection.second.y - selection.first.y) >= minSize;
}
}
$.plot = function(target, data, options) {
var plot = new Plot(target, data, options);
/*var t0 = new Date();
var t1 = new Date();
var tstr = "time used (msecs): " + (t1.getTime() - t0.getTime())
if (window.console)
console.log(tstr);
else
alert(tstr);*/
return plot;
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
// color helpers, inspiration from the jquery color animation
// plugin by John Resig
function Color (r, g, b, a) {
var rgba = ['r','g','b','a'];
var x = 4; //rgba.length
while (-1<--x) {
this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0);
}
this.toString = function() {
if (this.a >= 1.0) {
return "rgb("+[this.r,this.g,this.b].join(",")+")";
} else {
return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")";
}
};
this.scale = function(rf, gf, bf, af) {
x = 4; //rgba.length
while (-1<--x) {
if (arguments[x] != null)
this[rgba[x]] *= arguments[x];
}
return this.normalize();
};
this.adjust = function(rd, gd, bd, ad) {
x = 4; //rgba.length
while (-1<--x) {
if (arguments[x] != null)
this[rgba[x]] += arguments[x];
}
return this.normalize();
};
this.clone = function() {
return new Color(this.r, this.b, this.g, this.a);
};
var limit = function(val,minVal,maxVal) {
return Math.max(Math.min(val, maxVal), minVal);
};
this.normalize = function() {
this.r = limit(parseInt(this.r), 0, 255);
this.g = limit(parseInt(this.g), 0, 255);
this.b = limit(parseInt(this.b), 0, 255);
this.a = limit(this.a, 0, 1);
return this;
};
this.normalize();
}
var lookupColors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
function extractColor(element) {
var color, elem = element;
do {
color = elem.css("background-color").toLowerCase();
// keep going until we find an element that has color, or
// we hit the body
if (color != '' && color != 'transparent')
break;
elem = elem.parent();
} while (!$.nodeName(elem.get(0), "body"));
// catch Safari's way of signalling transparent
if (color == "rgba(0, 0, 0, 0)")
return "transparent";
return color;
}
// parse string, returns Color
function parseColor(str) {
var result;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))
return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10));
// Look for rgba(num,num,num,num)
if (result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4]));
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))
return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55);
// Look for rgba(num%,num%,num%,num)
if (result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]));
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))
return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16));
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))
return new Color(parseInt(result[1]+result[1], 16), parseInt(result[2]+result[2], 16), parseInt(result[3]+result[3], 16));
// Otherwise, we're most likely dealing with a named color
var name = $.trim(str).toLowerCase();
if (name == "transparent")
return new Color(255, 255, 255, 0);
else {
result = lookupColors[name];
return new Color(result[0], result[1], result[2]);
}
}
})(jQuery); | z3c.requestlet | /z3c.requestlet-0.9.1.tar.gz/z3c.requestlet-0.9.1/z3c/requestlet/browser/data/flot/jquery.flot.js | jquery.flot.js |
__docformat__ = 'restructuredtext'
from zope.app.component import hooks
from zope.traversing.interfaces import TraversalError
from zope.traversing.namespace import view
from zope.traversing.namespace import getResource
from z3c.resource import interfaces
class resource(view):
"""Traversal handler for ++resource++
Placeless setup:
>>> import zope.component
>>> from zope.app.testing import placelesssetup, ztapi
>>> placelesssetup.setUp()
>>> from zope.annotation.attribute import AttributeAnnotations
>>> from z3c.resource.adapter import getResource
>>> from z3c.resource import testing
>>> from z3c.resource.resource import Resource
>>> zope.component.provideAdapter(AttributeAnnotations)
Setup IResourceLocation and IResource adapters:
>>> zope.component.provideAdapter(getResource)
Now we create our resource traversable container:
>>> from z3c.resource.testing import Content
>>> from zope.publisher.browser import TestRequest
>>> content = Content()
>>> request = TestRequest
Traverse the resource traversable container without a name:
>>> traverser = resource(content, request)
>>> isinstance(traverser.traverse(None, ''), Resource)
True
>>> traverser.traverse(None, '').__parent__ is content
True
>>> traverser.traverse(None, '').__name__ == u'++resource++'
True
Traverse an existing name:
>>> foo = testing.TestResourceItem()
>>> res = interfaces.IResource(content)
>>> res[u'foo'] = foo
>>> traverser.traverse(u'foo', '') == foo
True
Traverse a non IResourceTraversable access:
>>> fake = object()
>>> traverser = resource(fake, request)
>>> try:
... traverser.traverse('', None)
... except TraversalError, e:
... e[0] is fake, e[1]
(True, 'Parameter context: IResourceTraversable required.')
Tear down::
>>> placelesssetup.tearDown()
"""
def __init__(self, context, request=None):
self.context = context
self.request = request
def traverse(self, name, ignored):
# preconditions
traversable = self.context
if not interfaces.IResourceTraversable.providedBy(traversable):
raise TraversalError(traversable,
'Parameter context: IResourceTraversable required.')
# essentials
resource = interfaces.IResource(traversable)
if name:
try:
return resource[name]
except KeyError, e:
pass
site = hooks.getSite()
return getResource(site, name, self.request)
else:
return resource | z3c.resource | /z3c.resource-0.5.0.zip/z3c.resource-0.5.0/src/z3c/resource/namespace.py | namespace.py |
======
README
======
A IResource is a container located in a object annotation providing a
container which contains IResourceItem. A resource item can be a file or
a image implementation marked with a IResourceItem interface. Such resource
items can get ``local`` traversed via the ``++resource++`` namespace.
Let's show how this works:
>>> from z3c.resource import interfaces
>>> from z3c.resource.resource import Resource
>>> res = Resource()
>>> interfaces.IResource.providedBy(res)
True
For the next test, we define a contant object providing IResourceTraversable:
>>> import zope.interface
>>> from zope.annotation import IAttributeAnnotatable
>>> from zope.annotation.attribute import AttributeAnnotations
>>> zope.component.provideAdapter(AttributeAnnotations)
>>> class Content(object):
... zope.interface.implements(interfaces.IResourceTraversable,
... IAttributeAnnotatable)
>>> content = Content()
Such IResourceTraversable object can get adapted to IResource:
>>> import zope.component
>>> from z3c.resource.adapter import getResource
>>> zope.component.provideAdapter(getResource)
>>> res = interfaces.IResource(content)
>>> res
<z3c.resource.resource.Resource object at ...>
>>> len(res)
0
We can add a IResourceItem to this resource:
>>> class Item(object):
... zope.interface.implements(interfaces.IResourceItem)
>>> item = Item()
>>> res['item'] = item
>>> len(res)
1
There is also a namespace which makes the resource item traversable on
the content object:
>>> from z3c.resource.namespace import resource as resourceNamspace
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> traverser = resourceNamspace(content, request)
We can traverse to the IResource:
>>> traverser.traverse(None, None)
<z3c.resource.resource.Resource object at ...>
>>> traverser.traverse(None, None).__parent__ is content
True
>>> traverser.traverse(None, None).__name__ == u'++resource++'
True
And we can traverse to the resource item by it's name:
>>> traverser.traverse('item', None)
<Item object at ...>
| z3c.resource | /z3c.resource-0.5.0.zip/z3c.resource-0.5.0/src/z3c/resource/README.txt | README.txt |
__docformat__ = 'restructuredtext'
from zope.interface import implements
from z3c.resource import interfaces
from z3c.proxy.container import ContainerLocationProxy
class ResourceLocationProxy(ContainerLocationProxy):
"""Proxy a resource container.
The specific resource container implementation of a traversable component
can be proxied.
Now we create our resource test implementation. We take a container that
implements ResourceTraversable:
>>> from z3c.resource.testing import ResourceTraversableContainer
>>> resourcetraversable = ResourceTraversableContainer()
Inside this resource traversabel we put our resource container:
>>> from z3c.resource.testing import TestResourceContainer
>>> resourcetraversable['pc'] = pc = TestResourceContainer()
Now we proxy our prototyped resource container implementation. The
resourcetraversable will be the parent of the proxied resource container and
that should be named to '@@':
>>> pcproxy = ResourceLocationProxy(pc, resourcetraversable)
>>> pcproxy.__name__ == u'@@'
True
>>> pcproxy.__parent__ is resourcetraversable
True
Containment put into the resource container appears in the
resource location proxy:
>>> from z3c.resource.testing import TestResourceItem
>>> pc['x'] = x = TestResourceItem()
>>> x1 = pcproxy['x']
>>> from zope.proxy import isProxy
>>> isProxy(x1)
True
>>> x1 == x
True
Containment put into the resource location proxy appears in
the resource container:
>>> pcproxy['y'] = y = TestResourceItem()
>>> pc['y'] is y
True
>>> y1 = pcproxy['y']
>>> isProxy(y1)
True
>>> y1 == y
True
Finaly we check all other methods of the proxy:
>>> 'x' in pcproxy
True
>>> pcproxy.has_key('x')
1
>>> keys = [key for key in pcproxy.keys()]; keys.sort(); keys
[u'x', u'y']
>>> items = [item for item in pcproxy.items()]; items.sort()
>>> items == [(u'x', x), (u'y', y)]
True
>>> pcproxy.get('x') == x
True
>>> iterator = iter(pcproxy)
>>> iterator.next() in pcproxy
True
>>> iterator.next() in pcproxy
True
>>> iterator.next()
Traceback (most recent call last):
...
StopIteration
>>> values = pcproxy.values(); values.sort();
>>> x in values, y in values
(True, True)
>>> len(pcproxy)
2
>>> del pcproxy['x']
>>> 'x' in pcproxy
False
"""
implements(interfaces.IResourceLocationProxy)
def __init__(self, context, parent):
# preconditions
if not interfaces.IResourceContainer.providedBy(context):
raise ValueError(
'Parameter context: IResourceContainer required.')
if not interfaces.IResourceTraversable.providedBy(parent):
raise ValueError(
'Parameter parent: IResourceTraversable required.')
# essentails
super(ResourceLocationProxy, self).__init__(context)
self.__name__ = u'@@'
self.__parent__ = parent | z3c.resource | /z3c.resource-0.5.0.zip/z3c.resource-0.5.0/src/z3c/resource/proxy.py | proxy.py |
from zope.interface import implements
from zope.location import locate
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.traversing.interfaces import TraversalError
from zope.publisher.browser import BrowserView
from zope.app import zapi
from z3c.resource import interfaces
class Resources(BrowserView):
"""Provide a URL-accessible resource view."""
implements(IBrowserPublisher)
def publishTraverse(self, request, name):
"""See zope.publisher.interfaces.browser.IBrowserPublisher"""
if not interfaces.IResourceTraversable.providedBy(self.context):
raise TraversalError(self.context,
'Parameter context: IResourceTraversable required.')
# get the resource instance
resource = interfaces.IResource(self.context)
# first check if we get a name, if not, we return the resource
# container itself. No fear local resource can't override global
# resources because we lookup on different context for local resource
# then for a global resource.
if name == '':
return resource
# first search for a resource in local resource location
try:
return resource[name]
except KeyError, e:
# no resource item found in local resource, doesn't matter.
pass
# query the default site resource and raise not found if there is no
# resource item found. If you don't like to lookup at global resources
# then you can override Resources view in your layer and skip this
# part.
return self._getSiteResource(name)
def _getSiteResource(self, name):
"""This will lookup resources on a ISite."""
resource = zapi.queryAdapter(self.request, name=name)
if resource is None:
raise NotFound(self, name)
sm = zapi.getSiteManager()
locate(resource, sm, name)
return resource
def browserDefault(self, request):
"""See zope.publisher.interfaces.browser.IBrowserPublisher"""
return empty, ()
def __getitem__(self, name):
return self.publishTraverse(self.request, name)
def empty():
return '' | z3c.resource | /z3c.resource-0.5.0.zip/z3c.resource-0.5.0/src/z3c/resource/browser/views.py | views.py |
import zope.interface
import zope.configuration.fields
import zope.component
import zope.schema
from zope.app import zapi
from zope.app.publisher.browser import metaconfigure
from interfaces import ICollectorUtility
from browser import CollectorResource
from utility import CollectorUtility
class ICollectorDirective(zope.interface.Interface):
name = zope.schema.TextLine(
title=u"The name of the resource library",
description=u"""\
This is the name used to disambiguate resource libraries. No two
libraries can be active with the same name.""",
required=True,
)
type = zope.configuration.fields.GlobalInterface(
title=u"Request type",
required=True
)
content_type = zope.schema.TextLine(
title=u"Content type",
required=False
)
def handleCollector(_context, name, type, content_type = None):
zapi.getGlobalSiteManager().registerUtility(CollectorUtility(content_type),name=name)
class_=CollectorResource
for_ = (zope.interface.Interface,)
provides = zope.interface.Interface
metaconfigure.resource(_context, name, layer=type, factory=class_,)
class ICollectorItemDirective(zope.interface.Interface):
collector = zope.schema.TextLine(
title=u"The name of the resource library",
description=u"""\
The name of the resourcelibrary where we want to add our resources""",
required=True,
)
item = zope.schema.TextLine(
title=u"The resource to add to the resource library",
description=u"""\
The resource""",
required=True,
)
weight = zope.schema.Int(
title=u"The position of the resource in the library",
description=u"""\
The position of the resource in the library""",
required=True,
)
def handleCollectorItem(_context, collector, item, weight):
_context.action(
discriminator = (collector, item),
callable = addCollectorItem,
args = (collector, item, weight)
)
def addCollectorItem(collector, item, weight):
rs = zope.component.getUtility(ICollectorUtility, collector)
resource = {}
resource['weight']=weight
resource['resource']=item
rs.resources[item]=resource | z3c.resourcecollector | /z3c.resourcecollector-1.1.3.tar.gz/z3c.resourcecollector-1.1.3/src/z3c/resourcecollector/zcml.py | zcml.py |
import time
import zope.component
from zope.viewlet import viewlet
from zope.app.publisher.browser.fileresource import FileResource
from zope.app.form.browser.widget import renderElement
from interfaces import ICollectorUtility
class CollectorResource(FileResource):
def __init__(self, request):
self.request = request
def GET(self):
rs = zope.component.getUtility(ICollectorUtility, self.__name__)
resources = rs.getResources(self.request)
if rs.content_type is not None:
self.request.response.setHeader('Content-Type', rs.content_type)
secs = 31536000
self.request.response.setHeader('Cache-Control',
'public,max-age=%s' % secs)
t = time.time() + secs
self.request.response.setHeader('Expires',
time.strftime("%a, %d %b %Y %H:%M:%S GMT",
time.gmtime(t)))
return resources
class CollectorViewlet(viewlet.ViewletBase):
@property
def collector(self):
return self.__name__
def renderElement(self, url):
return self.template% {'url':url}
def render(self):
originalHeader = self.request.response.getHeader('Content-Type')
if originalHeader is None:
originalHeader = "text/html"
rs = zope.component.getUtility(ICollectorUtility, self.collector)
versionedresource = rs.getUrl(self.context,self.request)
view=zope.component.getAdapter(self.request, name=self.collector)
url = '%s?hash=%s'% (view(), versionedresource)
script = self.renderElement(url)
self.request.response.setHeader('Content-Type', originalHeader)
return script
class JSCollectorViewlet(CollectorViewlet):
"""Render a link to include Javascript resources"""
def renderElement(self, url):
return renderElement('script',
src=url,
extra='type="text/javascript"',
contents=' ',
)
class CSSCollectorViewlet(CollectorViewlet):
"""Render a link to include CSS resources"""
media = 'screen'
def renderElement(self, url):
return renderElement('link',
rel='stylesheet',
href=url,
media=self.media,
extra='type="text/css"',
)
class CSSIECollectorViewlet(CollectorViewlet):
"""Renders a IE Only include CSS resource
to set lower then just overwride ieVersion in your zcml"""
# set ieVersion to e.g. "6"
ieVersion = None
# set versionOperator e.g. to "lt" or "gt"
versionOperator = None
def renderElement(self, url):
if self.ieVersion is None:
return '<!--[if IE]><link rel="stylesheet"'\
' type="text/css" href="%s" /><![endif]-->' % url
else:
if self.versionOperator:
_vo = '%s ' % self.versionOperator
else:
_vo = ''
return '<!--[if %sIE %s]><link rel="stylesheet"'\
' type="text/css" href="%s" /><![endif]-->' % (_vo,
self.ieVersion,
url) | z3c.resourcecollector | /z3c.resourcecollector-1.1.3.tar.gz/z3c.resourcecollector-1.1.3/src/z3c/resourcecollector/browser.py | browser.py |
Overview
--------
The package is able to include the following types of resources:
* Cascading stylesheets (.css)
* Kinetic stylesheets (.kss)
* Javascript (.js)
Usage
-----
The package operates with browser resources, registered individually
or using the resource directory factory.
A simple example::
<configure xmlns="http://namespaces.zope.org/zope"
xmlns:browser="http://namespaces.zope.org/browser">
<include package="z3c.resourceinclude" file="meta.zcml" />
<include package="z3c.resourceinclude" />
<browser:resource name="example.css" file="example.css" />
<browser:resourceInclude
layer="zope.publisher.interfaces.browser.IDefaultBrowserLayer"
include="example.css"
/>
</configure>
This registration means that whenever the request provides
``IDefaultBrowserLayer`` the resource named 'example.css' will be
included on the page.
To render HTML snippets that include applicable resources, a content
provider is provided, see ``z3c/resourceinclude/provide.py``. You may
also use one of the viewlets::
<browser:viewlet
name="resourceinclude"
class="z3c.resourceinclude.viewlets.CacheOneHourViewlet"
permission="zope.View" />
A convenience method is provided to require a given resource layer:
>>> from z3c.resourceinclude import include
>>> include(IMyLayer)
Ordering
--------
Resources are included in the order they're registered; that is, the
order in which the ZCML-directives are processed.
Stylesheets are included before javascripts as per general
recommendation. Kinetic stylesheets are included last.
Merging
-------
When not in 'devmode', the resource collector will automatically merge
resources, giving them a filename based on the contents (sha
digest). This has the side effect that merged resources are set to
never expire.
| z3c.resourceinclude | /z3c.resourceinclude-0.3.1.tar.gz/z3c.resourceinclude-0.3.1/README.txt | README.txt |
from zope import interface
from zope import component
from zope.configuration.fields import Tokens, GlobalObject, GlobalInterface
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.schema import TextLine
from manager import ResourceManager
from interfaces import IResourceManager
managers = {}
class IResourceIncludeDirective(interface.Interface):
include = Tokens(
title=u"Files to include",
description=u"The files containing the resource data.",
required=True,
value_type=TextLine())
base = TextLine(
title=u"Base path for includes",
required=False)
layer = GlobalInterface(
title=u"The layer the resource should be found in",
description=u"""
For information on layers, see the documentation for the skin
directive. Defaults to "default".""",
required=False
)
manager = GlobalObject(
title=u"Include manager",
required=False)
def includeDirective(_context, include, base=u"", layer=IDefaultBrowserLayer, manager=None):
if base:
include = [base+'/'+name for name in include]
_context.action(
discriminator = ('resourceInclude', IBrowserRequest, layer, "".join(include)),
callable = handler,
args = (include, layer, manager, _context.info),
)
def handler(include, layer, manager, info):
"""Set up includes."""
global managers
manager_override = manager is not None
for path in include:
try:
extension = path.rsplit('.', 1)[1]
except IndexError:
extension = None
key = (layer, extension)
if not manager_override:
manager = managers.get(key)
if manager is None:
# create new resource manager
managers[key] = manager = component.createObject(
'z3c.resourceinclude.ResourceManager')
# maintain order by creating a name that corresponds to
# the current number of resource managers
name = "%s-resource-manager-%03d" % (extension, len(managers))
# register as an adapter
component.provideAdapter(
manager, (layer,), IResourceManager, name=name)
manager.add(path) | z3c.resourceinclude | /z3c.resourceinclude-0.3.1.tar.gz/z3c.resourceinclude-0.3.1/z3c/resourceinclude/zcml.py | zcml.py |
z3c.resourceinclude
-------------------
This package provides functionality to define web-resources for
inclusion in HTML documents.
Registering resources
---------------------
Let's set up a browser resource.
>>> from z3c.resourceinclude.testing import MockResourceFactory
>>> from zope import component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from zope.component.interfaces import IResource
Let's register a couple of resources.
>>> component.provideAdapter(
... MockResourceFactory('text/plain'),
... (IDefaultBrowserLayer,), IResource, name='1')
>>> component.provideAdapter(
... MockResourceFactory('text/plain'),
... (IDefaultBrowserLayer,), IResource, name='2')
We'll now instantiate a resource manager and register it as an adapter
on the default browser layer.
>>> from z3c.resourceinclude.manager import ResourceManager
>>> from z3c.resourceinclude.interfaces import IResourceManager
>>> manager = ResourceManager()
>>> component.provideAdapter(
... manager, (IDefaultBrowserLayer,), IResourceManager, name='A')
Let's register the first resource for this layer by adding it to the
manager we just registered.
>>> manager.add('1')
Now we'll introduce another layer and register the second resource for
it.
>>> class ISpecificLayer(IDefaultBrowserLayer):
... """A specific layer."""
>>> manager = ResourceManager()
>>> component.provideAdapter(
... manager, (ISpecificLayer,), IResourceManager, name='B')
>>> manager.add('2')
Collecting resources
--------------------
A resource collector is responsible for gathering resources that apply
to the current browser request.
>>> from z3c.resourceinclude.collector import ResourceCollector
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> collector = ResourceCollector(request)
Let's ask the collector to gather resources available for this
request.
>>> collector.collect()
(<MockResource type="text/plain">,)
Let's confirm that if we provide the specific layer on the request,
that we'll get the other resource as well.
>>> from zope import interface
>>> interface.alsoProvides(request, ISpecificLayer)
>>> collector.collect()
(<MockResource type="text/plain">,
<MockResource type="text/plain">)
Resources are only included once.
>>> manager.add('1')
>>> collector.collect()
(<MockResource type="text/plain">,
<MockResource type="text/plain">)
Resources are sorted by their content-type.
>>> component.provideAdapter(
... MockResourceFactory('text/x-web-markup'),
... (IDefaultBrowserLayer,), IResource, name='3')
>>> component.provideAdapter(
... MockResourceFactory('text/plain'),
... (IDefaultBrowserLayer,), IResource, name='4')
>>> manager.add('3')
>>> manager.add('4')
>>> collector.collect()
(<MockResource type="text/plain">,
<MockResource type="text/plain">,
<MockResource type="text/plain">,
<MockResource type="text/x-web-markup">)
Including resources in an HTML document
---------------------------------------
Let's register a few browser resources:
>>> component.provideAdapter(
... MockResourceFactory('text/css'),
... (IDefaultBrowserLayer,), IResource, name='base.css')
>>> component.provideAdapter(
... MockResourceFactory('application/x-javascript'),
... (IDefaultBrowserLayer,), IResource, name='base.js')
>>> component.provideAdapter(
... MockResourceFactory('text/kss'),
... (IDefaultBrowserLayer,), IResource, name='base.kss')
>>> manager.add('base.css')
>>> manager.add('base.js')
>>> manager.add('base.kss')
Let's register the resource collector as a component.
>>> component.provideAdapter(ResourceCollector)
We can now render the resource includes.
>>> from z3c.resourceinclude.provider import ResourceIncludeProvider
>>> provider = ResourceIncludeProvider(None, request, None)
>>> provider.update()
>>> print provider.render()
<script type="text/javascript" src="http://nohost/site/@@/mock">
</script>
<style media="all" type="text/css">
<!-- @import url("http://nohost/site/@@/mock"); -->
</style>
<link type="text/kss" rel="kinetic-stylesheet" href="http://nohost/site/@@/mock" />
| z3c.resourceinclude | /z3c.resourceinclude-0.3.1.tar.gz/z3c.resourceinclude-0.3.1/z3c/resourceinclude/README.txt | README.txt |
from zope import interface
from zope import component
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.publisher.browser import TestRequest
from zope.app.publisher.browser.resource import Resource
from zope.publisher.interfaces import NotFound
from zope.datetime import rfc1123_date
from zope.datetime import time as timeFromDateTimeString
from interfaces import IResourceCollector
from interfaces import IResourceManager
import mimetypes
import tempfile
import sha
import time
class TemporaryResource(Resource):
interface.implements(IBrowserPublisher)
def __init__(self, request, f, content_type, lmt):
self.request = request
self.__file = f
self.content_type = content_type
self.lmt = lmt
self.context = self
def publishTraverse(self, request, name):
'''See interface IBrowserPublisher'''
raise NotFound(None, name)
def browserDefault(self, request):
'''See interface IBrowserPublisher'''
return getattr(self, request.method), ()
def GET(self):
lmt = self.lmt
request = self.request
response = request.response
# HTTP If-Modified-Since header handling. This is duplicated
# from OFS.Image.Image - it really should be consolidated
# somewhere...
header = request.getHeader('If-Modified-Since', None)
if header is not None:
header = header.split(';')[0]
# Some proxies seem to send invalid date strings for this
# header. If the date string is not valid, we ignore it
# rather than raise an error to be generally consistent
# with common servers such as Apache (which can usually
# understand the screwy date string as a lucky side effect
# of the way they parse it).
try: mod_since=long(timeFromDateTimeString(header))
except: mod_since=None
if mod_since is not None:
last_mod = long(lmt)
if last_mod > 0 and last_mod <= mod_since:
response.setStatus(304)
return ''
# set response headers
response.setHeader('Content-Type', self.content_type)
response.setHeader('Last-Modified', rfc1123_date(lmt))
secs = 31536000 # one year - never expire
t = time.time() + secs
response.setHeader('Cache-Control', 'public,max-age=%s' % secs)
response.setHeader(
'Expires', time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(t)))
f = self.__file
f.seek(0)
return f.read()
class TemporaryResourceFactory(object):
def __init__(self, f, checker, content_type, name):
self.__file = f
self.__name = name
self.__checker = checker
self.content_type = content_type
self.lmt = time.time()
def __call__(self, request):
resource = TemporaryResource(request, self.__file, self.content_type, self.lmt)
resource.__Security_checker__ = self.__checker
resource.__name__ = self.__name
return resource
class TemporaryRequest(TestRequest):
def __init__(self, request):
self.__request = request
TestRequest.__init__(self)
def getURL(self, *args, **kwargs):
return self.__request.getURL(*args, **kwargs)
def getApplicationURL(self, *args, **kwargs):
return self.__request.getApplicationURL(*args, **kwargs)
def getVirtualHostRoot(self):
return self.__request.getVirtualHostRoot()
class ResourceCollector(object):
interface.implements(IResourceCollector)
component.adapts(IBrowserRequest)
def __init__(self, request):
self.request = request
def collect(self):
resources = []
names = []
request = self._get_request()
for name, manager in self._get_managers():
items = manager.getResources(request)
# filter out duplicates
rs = [resource for name, resource in items if name not in names]
names.extend((name for name, resource in items))
# sort
self.sort(rs)
# merge
self.merge(rs)
resources.extend(rs)
return tuple(resources)
def sort(self, resources):
resources.sort(key=lambda resource: resource.context.content_type)
def merge(self, resources):
pass
def _get_request(self):
return TemporaryRequest(self.request)
def _get_managers(self):
managers = [(name, manager) for name, manager in \
component.getAdapters((self.request,), IResourceManager) if \
manager.available()]
managers.sort(key=lambda (name, manager): name)
return managers
class DigestResourceCollector(ResourceCollector):
def _build_factory(self, f, resource, content_type, name):
# adopt last resource's security checker
checker = resource.__Security_checker__
return TemporaryResourceFactory(f, checker, content_type, name)
def merge(self, resources):
by_type = {}
for resource in resources:
by_type.setdefault(resource.context.content_type, []).append(resource)
del resources[:]
merged = resources
for content_type, resources in by_type.items():
f = tempfile.TemporaryFile()
for resource in resources:
method, views = resource.browserDefault(self.request)
print >> f, "/* %s */" % resource.__name__
f.write(method())
print >> f, ""
# generate filename
ext = mimetypes.guess_extension(content_type)
f.seek(0)
digest = sha.new(f.read()).hexdigest()
name = digest + ext
# check if resource is already registered
res = component.queryAdapter((self.request,), name=name)
if res is None:
factory = self._build_factory(
f, resource, content_type, name)
# register factory
component.provideAdapter(
factory, (IBrowserRequest,), interface.Interface, name=name)
res = factory(self.request)
merged.append(res) | z3c.resourceinclude | /z3c.resourceinclude-0.3.1.tar.gz/z3c.resourceinclude-0.3.1/z3c/resourceinclude/collector.py | collector.py |
z3c.rest_publisher Package
==========================
Overview
--------
This product registers Zope-traverses (IBrowserPublisher) to implement basic REST requests in a simpler way.
This is done by registering traversable objects (IBrowserPublisher) to represent each method or level of the REST API.
No documents or folders will be accessed directly. It is necessary to create classes for each information to be accessed by the API.
For example, in the following request:
curl http://localhost:8080/api/members/my_user
where
- api - It's a view (inherited from APIBase) registered for ROOT
- members - It's a object inherited from APIBase included in "api"
- myuser - It's a object inherited from APIBase included in "members"
Install
-------
pip install z3c.rest_publisher
Configuration
-------------
1 - API Root
The starting point for the API is a traditional view registered in Zope ZCML. e.g.
```xml
<view
name="api"
for="zope.location.interfaces.IRoot"
type="zope.publisher.interfaces.browser.IBrowserRequest"
provides="zope.publisher.interfaces.browser.IBrowserPublisher"
factory=".rest_api.APIRoot"
permission="zope.Public"
allowed_attributes="publishTraverse browserDefault __call__">
</view>
```
Authentication
--------------
1 - Zope-Authentication
You can use traditional Zope systems for authentication, for example by changing permissions for the view
permission="zope.Public"
or
permission="zope.ManageContent"
2 - Custom authentication
If you wish, you can include customized authentication for the API. Just overwrite the "check_authentication" method in the class.
For example, to implement a basic authentication:
class APIRoot(APIBase):
def check_authentication(self):
user, pwd = self.request._authUserPW()
return user == 'demo' and pwd == 'demo'
To test:
curl --user demo:demo http://localhost:8080/api/
REST functions
--------------
There are two ways to add a REST function to the Object.
1 - REST function as a method
Include a method in the format {HTTP-Method}_{Name} (lower-case), e.g.
class APIRoot(APIBase):
def get_list_admins(self):
return [{'id': '1', 'firstname': 'Alberto', 'lastname': 'Santos-Dumont'},
{'id': '2', 'firstname': 'Edson', 'lastname': 'Arantes do Nascimento'}]
def put_list_admins(self):
return self.get_list_admins()
To test:
curl -X GET http://localhost:8080/api/list_admins
curl -X PUT http://localhost:8080/api/list_admins
2 - Concatenated REST objects
It is possible to create a new REST object and concatenate it with the current object.
This is the equivalent implementation from the previous method.
class APIListAdmins(APIBase):
def get(self):
return [{'id': 'user1', 'firstname': 'Alberto', 'lastname': 'Santos-Dumont'},
{'id': 'user2', 'firstname': 'Edson', 'lastname': 'Arantes do Nascimento'}]
def put(self):
return self.get()
class APIRoot(APIBase):
content = {'list_admins': APIListAdmins}
To test:
curl -X GET http://localhost:8080/api/list_admins
curl -X PUT http://localhost:8080/api/list_admins
2.1 - REST function for objects (catch all)
To implement a "generic" traverse to access specific database objects, use the wildcard "*".
class APIUSer(APIBase):
def get(self):
if self.name == 'user1'
return {'id': 'user1', 'firstname': 'Alberto', 'lastname': 'Santos-Dumont'}
elif self.name == 'user2':
return {'id': 'user2', 'firstname': 'Edson', 'lastname': 'Arantes do Nascimento'}
else:
self.request.response.setStatus(404)
return "User not found"
class APIMembers(APIBase):
content = {'*': APIUSer}
class APIRoot(APIBase):
content = {'members': APIListAdmins}
Be aware that curl just send data with POST methods. This is a limitation discussed in some posts.
To test these methods with curl, use the 'querystring_verb_name' option as documented. e.g.
querystring_verb_name=verb
curl -X POST --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users/user4?verb=PATCH --data-raw '{"firstname": "New Name"}'
To test:
curl -X GET http://localhost:8080/api/members/user1
(Check more examples in example/README.txt)
API documentation
-----------------
The class RestDoc provide a simple built-in documentation of all REST-APi methods.
The default url is '[API_ROOT]/help' but you can change the property 'doc_endpoint' (APIBase) if you desire.
Example
-------
Please see "z3c.rest_publisher/example" for an example.
| z3c.rest-publisher | /z3c.rest_publisher-0.9.2.tar.gz/z3c.rest_publisher-0.9.2/README.md | README.md |
import datetime
import json
import logging
from wcore import interfaces
from zope.browserpage import ViewPageTemplateFile
from zope.component import adapts, queryMultiAdapter
from zope.interface import implements
from zope.publisher.browser import BrowserPage
from zope.publisher.browser import BrowserPage
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces import TraversalException
from zope.publisher.interfaces.browser import IBrowserRequest, IBrowserPublisher
logger = logging.getLogger(__name__)
class APIBase(object):
""" Base class for REST Objects """
adapts(IBrowserRequest)
implements(IBrowserPublisher)
# False (default) is used to avoid returning the default error page (HTML).
raise_exceptions = False
# it is possible to inform the verb in the query-string in case you can't use http-methods.
# e.g. If querystring_verb_name='verb', send a POST request and add something like ?verb=PATCH in the query-string.
querystring_verb_name = ""
# Make this API public - It will not check the custom authentication
public = False
# All methods supported by this API
allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
def __init__(self, context, request, name, parent_api_obj=None):
self.context = context
self.request = request
self.name = name
self.parent_api_obj = parent_api_obj
def check_authentication(self, name):
""" Overwrite this method to add a custom authentication for your REST API """
return True
@staticmethod
def format_unsupported_value(value):
""" Use this static function if there is a value that is not supported by the standard 'format_output'
function """
if isinstance(value, datetime.datetime):
return value.isoformat()
elif isinstance(value, datetime.date):
return value.isoformat()
elif value is None:
return ''
else:
return str(value)
def format_output(self, data):
""" format the output. default: json """
return json.dumps(data, default=self.format_unsupported_value)
def browserDefault(self, request):
return self, ()
def error_verb(self, ex):
""" Overwrite this function if you want specific action on verb errors """
logger.error(ex, exc_info=True)
if not self.raise_exceptions:
self.request.response.setStatus(500)
return "Server error (verb) - %s" % ex
else:
raise
def error_traverse(self, ex, request, name):
""" Overwrite this function if you want specific action on traverse errors """
logger.error(ex, exc_info=True)
raise
def __call__(self):
try:
method = self.request['REQUEST_METHOD'].lower()
if self.querystring_verb_name:
method = self.request.get(self.querystring_verb_name, method).lower()
if method not in self.allowed_methods:
self.request.response.setStatus(403)
return "The HTTP-method '%s' is not supported" % method
if not self.public and not self.check_authentication(method):
self.request.response.setStatus(403)
return "Access denied"
# Search for a method with the same name as REQUEST_METHOD and call it
fnc = "verb_%s" % method
if hasattr(self, fnc):
res = getattr(self, fnc)()
return self.format_output(res)
else:
self.request.response.setStatus(500)
return "The HTTP-method '%s' is not supported here" % method
except Exception as ex:
return self.error_verb(ex)
def publishTraverse(self, request, name):
try:
if not self.public and not self.check_authentication(name):
raise TraversalException("Access denied")
# Traverse 1 - Call traverse_{Name} to get one API-Object with the name {Name}
method = self.request['REQUEST_METHOD'].lower()
func = "traverse_{name}".format(name=name)
if hasattr(self, func):
obj = getattr(self, func)(request, name)
return obj
# Traverse 2 - Call traverse_NAME to return a child-object with the key = {name}
func = "traverse_NAME"
if hasattr(self, func):
obj = getattr(self, func)(request, name)
return obj
# Traverse 3 - Fall back to views
view = queryMultiAdapter((self.context, request), name=name)
if view is not None:
return view
# Traverse 4 - If nothing found, this method will be called
func = "traverse_DEFAULT"
if hasattr(self, func):
obj = getattr(self, func)(request, name)
return obj
# Return a 404 Not Found error page
raise NotFound(self.context, name, request)
except NotFound:
raise
except Exception as ex:
return self.error_traverse(ex, request, name) | z3c.rest-publisher | /z3c.rest_publisher-0.9.2.tar.gz/z3c.rest_publisher-0.9.2/z3c/rest_publisher/base.py | base.py |
import json
import os
from z3c.rest_publisher.base import APIBase
from zope.publisher.interfaces import NotFound
# Read the DATA from file
f = open(os.path.join(os.path.dirname(__file__), "DB.json"))
DB = json.load(f)[0]
# Example with a object
class Headquarter(object):
name = "The companie Group"
city = "Neverland"
state = "SC"
mail = "[email protected]"
headquarter = Headquarter()
class SecureAPIBase(APIBase):
""" A API Base class with custom authentication """
querystring_verb_name = "verb"
def check_authentication(self, name):
""" Authenticate requests with basic-authentication user:demo, pwd:demo """
return True
# TODO
cred = self.request._authUserPW()
if cred and len(cred) == 2:
user, pwd = self.request._authUserPW()
if user == 'demo' and pwd == 'demo':
return True
class APIUser(SecureAPIBase):
""" /api/companies/IdX/sectors/IdY/users/IdZ - API for user IdZ in sector IdY in the company IdX """
def verb_get(self):
""" List details about this user """
user = self.context
return dict([(k, v) for (k, v) in user.items() if k in ["id", "firstname", "lastname", "mail", "admin"]])
def verb_delete(self):
""" Delete the user """
user = self.context
users_api = self.parent_api_obj
users = users_api.context
users.remove(user)
return "user removed"
def verb_patch(self):
""" Update some attributes from user """
user = self.context
import pdb;
pdb.set_trace()
for k, v in self.request.form.items():
user[k] = v
return self.verb_get()
def verb_post(self):
""" Update all attributes from user """
return self.verb_patch()
class APIUsers(SecureAPIBase):
""" /api/companies/IdX/sectors/IdY/users - API for all users in sector IdY in the company IdX """
def traverse_NAME(self, request, name):
""" search for a user with id = name and return the API for the user object """
users = self.context
user = [s for s in users if s['id'] == name]
if user:
return APIUser(context=user[0], request=request, name=name, parent_api_obj=self)
else:
raise NotFound(self.context, name, request)
def verb_get(self):
""" Get data from all users """
users = self.context
ret = []
for u in users:
ret.append({"id": u["id"], "firstname": u["firstname"], "admin": u["admin"]})
return ret
def verb_post(self):
""" Add a new user """
data = self.request.form
users = self.context
data["admin"] = data.get("admin", "FALSE").upper() == "TRUE"
users.append(data)
return self.verb_get()
class APISector(SecureAPIBase):
""" /api/companies/IdX/sectors/IdY - API for sector IdY in the company IdX
"""
def traverse_users(self, request, name):
""" return the API for members objects """
sector = self.context
return APIUsers(context=sector["users"], request=request, name=name, parent_api_obj=self)
def verb_get(self):
""" List details about this sector """
sector = self.context
return dict([(k, v) for (k, v) in sector.items() if k in ["id", "title"]])
class APISectors(SecureAPIBase):
""" /api/companies/IdX/sectors/IdY - API for all sectors in the company IdX
"""
def traverse_NAME(self, request, name):
""" search for a sector with id = name and return the API for the sector object """
sectors = self.context
sector = [s for s in sectors if s['id'] == name]
if sector:
return APISector(context=sector[0], request=request, name=name, parent_api_obj=self)
else:
raise NotFound(self.context, name, request)
def verb_get(self):
""" Get data from all sectors """
sectors = self.context
ret = []
for c in sectors:
ret.append({"id": c["id"], "title": c["title"], "users": [s["id"] for s in c["users"]]})
return ret
class APICompany(SecureAPIBase):
""" /api/companies/IdX - API for the company IdX
"""
def traverse_sectors(self, request, name):
""" return the API for sectors """
company = self.context
return APISectors(context=company["sectors"], request=request, name=name, parent_api_obj=self)
def verb_get(self):
""" List details about this company """
company = self.context
return dict([(k, v) for (k, v) in company.items() if k in ["id", "title", "telephone", "mail"]])
class APICompanies(SecureAPIBase):
""" /api/companies/ - API for all companies
"""
def traverse_NAME(self, request, name):
""" search for a company with id = name and return the API for the company object """
dbroot = self.context
company = [c for c in dbroot['companies'] if c['id'] == name]
if company:
return APICompany(context=company[0], request=request, name=name, parent_api_obj=self)
else:
raise NotFound(self.context, name, request)
def verb_get(self):
""" Get data from all companies """
dbroot = self.context
ret = []
for c in dbroot['companies']:
ret.append({"id": c["id"], "title": c["title"], "sectors": [s["id"] for s in c["sectors"]]})
return ret
class APIHeadquarter(SecureAPIBase):
""" /api/headquarter - API for headquarter object
"""
def verb_get(self):
""" Get data from object headquarter """
headquarter_obj = self.context
ret = {}
for obj_attr in ['name', 'city', 'state', 'mail']:
ret[obj_attr] = getattr(headquarter_obj, obj_attr, "[Not_Found]")
return ret
class APIRoot(SecureAPIBase):
""" REST - Access the API as a view
Check the README.txt for some examples how to test with curl, e.g.
curl -X GET --user demo:demo http://localhost:8080/api/companies
"""
public = True
def traverse_headquarter(self, request, name):
"""
Return information from headquarter
:return: APIHeadquarter
"""
return APIHeadquarter(context=headquarter, request=request, name=name, parent_api_obj=self)
def traverse_companies(self, request, name):
return APICompanies(context=DB, request=request, name=name, parent_api_obj=self)
def __init__(self, context, request):
self.name = "testapi"
self.context = context
self.request = request | z3c.rest-publisher | /z3c.rest_publisher-0.9.2.tar.gz/z3c.rest_publisher-0.9.2/z3c/rest_publisher/example/rest_api_example.py | rest_api_example.py |
This is a simple application to test the API.
The data is in the DB.json file
Install
-------
To use this example API just add the configure.zcml in your application, e.g.
<configure xmlns="http://namespaces.zope.org/zope">
<include package="z3c.rest_publisher.example" />
</configure>
TESTS
-----
To test with curl, e.g.
curl -X GET --user demo:demo http://127.0.0.1:9095/testapi
curl -X GET --user demo:demo http://127.0.0.1:9095/testapi/headquarter
curl -X GET --user demo:demo http://127.0.0.1:9095/testapi/companies
curl -X GET --user demo:demo http://127.0.0.1:9095/testapi/companies/company1
curl -X GET --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users
curl -X GET --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users/user4
curl -X POST --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users -d 'id=user10&firstname=ana&lastname=smith&[email protected]'
curl -X DELETE --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users/user3
curl -X PATCH --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users/user4 -d 'firstname=My New Name!'
TESTS with querystring_verb_name
--------------------------------
Be aware that some applications just send the data with POST methods.
To avoid these limitations use the POST method in combination with the 'querystring_verb_name' option.
Check the documentation for more details.
e.g.
Test "querystring_verb_name='verb'" with:
curl -X POST --user demo:demo http://127.0.0.1:9095/testapi/companies/company1/sectors/sector2/users/user4?verb=PATCH -d 'firstname=My New Name!'
| z3c.rest-publisher | /z3c.rest_publisher-0.9.2.tar.gz/z3c.rest_publisher-0.9.2/z3c/rest_publisher/example/README.txt | README.txt |
import zope.interface
import zope.schema
from zope.location.interfaces import ILocation
from zope.publisher.interfaces import http
class IRESTRequest(http.IHTTPRequest):
"""A special type of request for handling REST-based requests."""
class IRESTResponse(http.IHTTPResponse):
"""A special type of response for handling REST-based requests."""
class IRESTView(ILocation):
"""A REST view"""
class ILink(zope.interface.Interface):
"""An object representing a hyperlink."""
href = zope.schema.TextLine(
title=u"URL",
description=u"The normalized URL of the link",
required=False)
title = zope.schema.TextLine(
title=u'Title',
description=u'The title of the link',
required=False)
def click():
"""click the link, going to the URL referenced"""
class IRESTClient(zope.interface.Interface):
"""A REST client.
This client provides a high-level API to access RESTful Web APIs. The
interface is designed to resemble the test browser API as much as
practical.
"""
connectionFactory = zope.schema.Field(
title=u"Connection Facotry",
description=(u'A callable that creates an `httplib`-compliant '
u'connection object.'),
required=True)
requestHeaders = zope.schema.Dict(
title=u"Request Headers",
description=(u"A set of headers that will be sent in every request."),
required=True)
url = zope.schema.URI(
title=u"URL",
description=(u"The URL the browser is currently showing. It is "
u"always a full, absolute URL."),
required=True)
headers = zope.schema.List(
title=u"Response Headers",
description=(u'A list of all headers that have been returned '
u'in the last request.'),
required=True)
contents = zope.schema.Text(
title=u"Contents",
description=u"The complete response body of the HTTP request.",
required=True)
status = zope.schema.Int(
title=u"Status",
description=u"The status code of the last response.",
min=0,
required=True)
reason = zope.schema.TextLine(
title=u"Reason",
description=u"A short explanation of the status of the last response.",
required=True)
fullStatus = zope.schema.TextLine(
title=u"Full Status",
description=u"The status code and reason of the last response.",
required=True)
def open(url='', data=None, params=None, headers=None, method='GET'):
"""Open a URL and retrieve the result.
The `url` argument can either be a full URL or a URL relative to the
previous one. If no URL is specified, then the previous URL will be
used.
The `data` is the contents of the request body. It is used to send
information to the server.
The `params` describe additional query parameters that will be added
to the request. Query string parameters are frequently used by RESTive
APIs to provide additional return value options.
The `headers` specify additional request headers that are specific for
this particular request.
The `method` specifies the HTTP method or verb to use to access the
resource on the server. While there are only a few methods in RFC
2616, an string is allowed, since any particular API can extend the
set of allowed methods.
"""
def get(url='', params=None, headers=None):
"""Make a GET request to the server.
For argument details see ``open()``.
"""
def put(url='', data='', params=None, headers=None):
"""Make a PUT request to the server.
For argument details see ``open()``.
"""
def post(url='', data='', params=None, headers=None):
"""Make a POST request to the server.
For argument details see ``open()``.
"""
def delete(url='', params=None, headers=None):
"""Make a DELETE request to the server.
For argument details see ``open()``.
"""
def setCredentials(username, password):
"""Set the credentials.
This method adds the necessary information to authenticate the user. A
common example is basic auth, which inserts the `Authentication`
request header.
"""
def goBack(count=1):
"""Go back in history by a certain amount of visisted pages.
The ``count`` argument specifies how far to go back. It is set to 1 by
default.
"""
def reload():
"""Reload the current resource.
All arguments, including the HTTP method, parameters and additional
headers are honored.
"""
def getLink(title=None, url=None, index=0):
"""Return an ILink of the found link.
This method assumes that the current content type of the response body
is XML.
The link is found by the arguments of the method. Only one can be
used at a time:
o ``title`` -- The title or a sub-string thereof of the link.
o ``url`` -- The URL the link is going to.
If multiple matching links are found, the `index` specifies which one
to use.
"""
def xpath(expr, nsmap=None, single=False):
"""Returns the result of an XPath search expression.
This method assumes that the current content type of the response body
is XML.
The `expr` argument is the actual XPath expression. If the expression
is incorrect, an unspecified error must be raised.
The `nsmap` is a mapping from the short version to the full URL of
each XML namespace used in the expression.
If `single` is set to ``True``, then only one result is returned,
instead of a list. If the XPath expression results in more than one
result, a ``ValueError`` must be raised.
"""
class IPublisherRESTClient(IRESTClient):
"""An extension to the REST client to support test-specific features."""
handleErrors = zope.schema.Bool(
title=u"Handle Errors",
description=(u"Describes whether server-side errors will be handled "
u"by the publisher. If set to ``False``, the error will "
u"progress all the way to the test, which is good for "
u"debugging."),
default=True,
required=True) | z3c.rest | /z3c.rest-0.4.0.tar.gz/z3c.rest-0.4.0/src/z3c/rest/interfaces.py | interfaces.py |
import lxml
import lxml.etree
import httplib
import socket
import urllib
import urlparse
import base64
import zope.interface
from z3c.rest import interfaces
def isRelativeURL(url):
"""Determines whether the given URL is a relative path segment."""
pieces = urlparse.urlparse(url)
if not pieces[0] and not pieces[1]:
return True
return False
def absoluteURL(base, url):
"""Convertes a URL to an absolute URL given a base."""
if not isRelativeURL(url):
return url
pieces = list(urlparse.urlparse(base))
urlPieces = list(urlparse.urlparse(url))
if not pieces[2].endswith('/'):
pieces[2] += '/'
pieces[2] = urlparse.urljoin(pieces[2], urlPieces[2])
if urlPieces[4]:
if pieces[4]:
pieces[4] = pieces[4] + '&' + urlPieces[4]
else:
pieces[4] = urlPieces[4]
return urlparse.urlunparse(pieces)
def getFullPath(pieces, params):
"""Build a full httplib request path, including a query string."""
query = ''
if pieces[4]:
query = pieces[4]
if params:
encParams = urllib.urlencode(params)
if query:
query += '&' + encParams
else:
query = encParams
return urlparse.urlunparse(
('', '', pieces[2], pieces[3], query, pieces[5]))
class XLink(object):
"""A link implementation for simple XLinks."""
zope.interface.implements(interfaces.ILink)
def __init__(self, client, title, url):
self._client = client
self.title = title
self.url = url
def click(self):
"""See interfaces.ILink"""
self._client.get(self.url)
def __repr__(self):
return '<%s title=%r url=%r>' %(
self.__class__.__name__, self.title, self.url)
class RESTClient(object):
zope.interface.implements(interfaces.IRESTClient)
connectionFactory = httplib.HTTPConnection
sslConnectionFactory = httplib.HTTPSConnection
def __init__(self, url=None):
self.requestHeaders = {}
self._reset()
self._history = []
self._requestData = None
self.url = ''
if url:
self.open(url)
@property
def fullStatus(self):
return '%i %s' %(self.status, self.reason)
def _reset(self):
self.headers = []
self.contents = {}
self.status = None
self.reason = None
def open(self, url='', data=None, params=None, headers=None, method='GET'):
# Create a correct absolute URL and set it.
self.url = absoluteURL(self.url, url)
# Create the full set of request headers
requestHeaders = self.requestHeaders.copy()
if headers:
requestHeaders.update(headers)
# Let's now reset all response values
self._reset()
# Store all the request data
self._requestData = (url, data, params, headers, method)
# Make a connection and retrieve the result
pieces = urlparse.urlparse(self.url)
if pieces[0] == 'https':
connection = self.sslConnectionFactory(pieces[1])
else:
connection = self.connectionFactory(pieces[1])
try:
connection.request(
method, getFullPath(pieces, params), data, requestHeaders)
response = connection.getresponse()
except socket.error, e:
connection.close()
self.status, self.reason = e.args
self._addHistory()
raise e
else:
self.headers = response.getheaders()
self.contents = response.read()
self.status = response.status
self.reason = response.reason
connection.close()
self._addHistory()
def get(self, url='', params=None, headers=None):
self.open(url, None, params, headers)
def put(self, url='', data='', params=None, headers=None):
self.open(url, data, params, headers, 'PUT')
def post(self, url='', data='', params=None, headers=None):
self.open(url, data, params, headers, 'POST')
def delete(self, url='', params=None, headers=None):
self.open(url, None, params, headers, 'DELETE')
def setCredentials(self, username, password):
creds = username + u':' + password
creds = "Basic " + base64.encodestring(creds.encode('utf-8')).strip()
self.requestHeaders['Authorization'] = creds
def _addHistory(self):
self._history.append((
self.url, self.requestHeaders, self.headers, self.contents,
self.status, self.reason, self._requestData
))
def goBack(self, count=1):
# The user really does not want to go back.
if count == 0:
return
# The user wants to reach before a pre-historical state.
if len(self._history) < count:
raise ValueError('There is not enough history.')
# Let's now get the entry and set the history back to that state.
entry = self._history[-(count+1)]
self._history = self._history[:-count]
# Reset the state.
(self.url, self.requestHeaders, self.headers, self.contents,
self.status, self.reason, self._requestData) = entry
def reload(self):
self.open(*self._requestData)
def getLink(self, title=None, url=None, index=0):
nsmap = {'xlink': "http://www.w3.org/1999/xlink"}
tree = lxml.etree.fromstring(self.contents)
res = []
if title is not None:
res = tree.xpath(
'//*[@xlink:title="%s"]' %title, namespaces=nsmap)
elif url is not None:
res = tree.xpath(
'//*[@xlink:href="%s"]' %url, namespaces=nsmap)
else:
raise ValueError('You must specify a title or URL.')
elem = res[index]
url = elem.attrib.get('{%(xlink)s}href' %nsmap, '')
return XLink(self,
elem.attrib.get('{%(xlink)s}title' %nsmap),
absoluteURL(self.url, url))
def xpath(self, expr, nsmap=None, single=False):
res = lxml.etree.fromstring(self.contents).xpath(expr, namespaces=nsmap)
if not single:
return res
if len(res) != 1:
raise ValueError('XPath expression returned more than one result.')
return res[0] | z3c.rest | /z3c.rest-0.4.0.tar.gz/z3c.rest-0.4.0/src/z3c/rest/client.py | client.py |
===================================================
A Framework for Building RESTive Services in Zope 3
===================================================
This package implements several components that relate to building RESTive Web
services using the Zope publisher. Each set of components is documented in a
corresponding text file.
* ``client.txt`` [must read]
This package also provides a REST Web client, which can be used for testing
or for accessing a RESTive API within an application.
* ``null.txt`` [advanced user]
In order to create new resources, the publisher must be able to traverse to
resources/objects that do not yet exist. This file explains how those null
resources work.
* ``traverser.txt`` [advanced user]
The ``traverser`` module contains several traversal helper components for
common traversal scenarios, suhc as containers and null resources.
* ``rest.txt`` [informative]
This document introduces the hooks required to manage RESTive requests in
the publisher. It also discusses hwo those components are used by the
publisher.
| z3c.rest | /z3c.rest-0.4.0.tar.gz/z3c.rest-0.4.0/src/z3c/rest/README.txt | README.txt |
import cgi
import types
import zope.interface
from z3c.rest import interfaces
from zope.pagetemplate.pagetemplatefile import PageTemplateFile
from zope.app.publication.interfaces import IPublicationRequestFactory
from zope.app.publication.http import HTTPPublication
from zope.publisher.http import HTTPRequest, HTTPResponse
from zope.publisher.interfaces import Redirect
class RESTRequest(HTTPRequest):
zope.interface.implements(interfaces.IRESTRequest)
__slots__ = (
'parameters', # Parameters sent via the query string.
)
def __init__(self, body_instream, environ, response=None):
self.parameters = {}
super(RESTRequest, self).__init__(body_instream, environ, response)
def processInputs(self):
'See IPublisherRequest'
if 'QUERY_STRING' not in self._environ:
return
# Parse the query string into our parameters dictionary.
self.parameters = cgi.parse_qs(
self._environ['QUERY_STRING'], keep_blank_values=1)
# Since the parameter value is always a list (sigh), let's at least
# detect single values and store them.
for name, value in self.parameters.items():
if len(value) == 1:
self.parameters[name] = value[0]
def keys(self):
'See Interface.Common.Mapping.IEnumerableMapping'
d = {}
d.update(self._environ)
d.update(self.parameters)
return d.keys()
def get(self, key, default=None):
'See Interface.Common.Mapping.IReadMapping'
marker = object()
result = self.parameters.get(key, marker)
if result is not marker:
return result
return super(RESTRequest, self).get(key, default)
def _createResponse(self):
return RESTResponse()
class RESTResponse(HTTPResponse):
zope.interface.implements(interfaces.IRESTResponse)
errorTemplate = PageTemplateFile("baseerror.pt")
def handleException(self, exc_info, trusted=False):
errorClass, error = exc_info[:2]
if isinstance(errorClass, (types.ClassType, type)):
if issubclass(errorClass, Redirect):
self.redirect(error.getLocation(), trusted=trusted)
return
title = tname = errorClass.__name__
else:
title = tname = unicode(errorClass)
# Throwing non-protocol-specific exceptions is a good way
# for apps to control the status code.
self.setStatus(tname)
self.setHeader("Content-Type", "text/xml")
self.setResult(
self.errorTemplate(name=title, explanation=str(error)))
class RESTView(object):
zope.interface.implements(interfaces.IRESTView)
def __init__(self, context, request):
self.context = context
self.request = request
@apply
def __parent__():
def get(self):
return getattr(self, '_parent', self.context)
def set(self, parent):
self._parent = parent
return property(get, set)
class RESTPublicationRequestFactory(object):
zope.interface.implements(IPublicationRequestFactory)
def __init__(self, db):
"""See zope.app.publication.interfaces.IPublicationRequestFactory"""
self.publication = HTTPPublication(db)
def __call__(self, input_stream, env, output_stream=None):
"""See zope.app.publication.interfaces.IPublicationRequestFactory"""
request = RESTRequest(input_stream, env)
request.setPublication(self.publication)
return request | z3c.rest | /z3c.rest-0.4.0.tar.gz/z3c.rest-0.4.0/src/z3c/rest/rest.py | rest.py |
=======
CHANGES
=======
4.4.0 (2023-08-23)
------------------
- Add support for the splitByRow and splitInRow arguments to BlockTable.
- Add ``rlPyCairo`` as install requirement as ``reportlab >= 4.0`` needs that library.
(`#117 <https://github.com/zopefoundation/z3c.rml/issues/117>_`)
4.3.0 (2023-04-25)
------------------
- Add support for Python 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
- Added support for text anchor points on images.
- Make sure we only close input files if we opened them.
- Delegate image ratio to drawImage. (PR #105)
- Accepts "None" for label box colors.
- Use svglib for the svg to rml conversion instead of maintaining our own.
- Allow unicode characters as bullets.
4.2.1 (2022-09-30)
------------------
- Add support for Python 3.10.
- Add back support for Python 3.6.
- Fix name clash in repository on file systems which are not case sensitive but
just case preserving.
- Move output directory of tests to a temporary directory.
- Support `pikepdf` 6.0+.
4.2.0 (2021-10-14)
------------------
- Upgrade to using `pikepdf` 3.0+.
4.1.2 (2020-12-14)
------------------
- Fix include on first page. (PR #84)
4.1.1 (2020-12-08)
------------------
- Allow ``<registerTTFont>`` to search default font directories instead of
requiring absolute or relative path. (Fixes issue #46.)
- Make sure a includePages adds blank pages at the end of a document when
there is no flowable after it.
4.1.0 (2020-12-07)
------------------
- Implement new tag ``<blockNosplit>`` for ``<blockTableStyle>``.
- Fix dynamic tags in paragraph. Fixes page numbering.
- Make new bullet styles of Reportlab 3.5 avaialable.
- Support for custom ``Canvas`` classes.
4.0.0 (2020-12-07)
------------------
- Dropped support for Python 2.x.
- Dropped `PyPDF2` for `pikepdf`.
3.10.0 (2020-03-27)
-------------------
- Added ``inFill`` property to ``<linePlot>`` which will fill the area below
the line makign it effectively an area plot.
- Added ability to specify the ``labelTextFormat`` property of ``<xValueAxis>``
and ``<yValueAxis>`` to be a reference to a function via a Python path.
- Added an example from Stack Overflow that exercises the new features. See
``tag0linePlot.rml``.
- Remove Python 3.6 support and add 3.8.
3.9.1 (2019-10-04)
------------------
- Adding textTransform implementation.
3.9.0 (2019-07-19)
------------------
- Create a proper, parsable DTD. Add a test that verifies its validity.
- Updated `rml.dtd`.
- ``strandLabels`` does not support text content. That was accidentally
asserted due to bad schema inheritance.
3.8.0 (2019-06-24)
------------------
- Unified ``paraStyle`` and ``spanStyle`` even more.
- Extended ``<spanStyle>`` to support underline and strike as well.
- Simplified implemnetation of strike and underline style implementation. It
is also the more correct implementation.
3.7.0 (2019-06-14)
------------------
- Drop support for running tests using ``python setup.py test``.
- Drop Python 3.5 support.
- Extended ``<paraStyle>``:
* ``underline``: A boolean field indicating whether the entire paragraph is
underlined. The following related attributes have also been added to the
style: ``underlineColor``, ``underlineOffset``, ``underlineWidth``,
``underlineGap``, and ``underlineKind``
* ``strike``: A boolean field indicating whether the entire paragraph is
stricken. The following related attributes have also been added to the
style: ``strikeColor``, ``strikeOffset``, ``strikeWidth``,
``strikeGap``, and ``strikeKind``
* ``justifyLastLine``: Added attribute that is available in the API.
* ``justifyBreaks``: Added attribute that is available in the API.
* ``spaceShrinkage``: Added attribute that is available in the API.
* ``linkUnderline``: Added attribute that is available in the API.
3.6.3 (2019-04-11)
------------------
- Added missing ``lineBelowDash``, ``lineAboveDash``, ``lineLeftDash``,
``lineRightDash`` attributes
3.6.2 (2019-03-27)
------------------
- Fix num2words (missing import, two digit dashes)
- Added test to check what happens with text not in tags
(e.g. not in a ``<para>`` tag)
3.6.1 (2018-12-01)
------------------
- Add Python 3.7 Trove classifier.
3.6.0 (2018-12-01)
------------------
- Upgraded to support Python 3.7
- Allow ``<place>`` to contain ``<fixedSize>``, which allows content to be
fitted into the place boundaries.
3.5.1 (2018-10-09)
------------------
- Upgraded to support Reportlab 3.5.9
3.5.0 (2018-04-10)
------------------
- Honor the order of attribute choices in the docs.
- Abstracted span styles out of base paragraph style, so that attributes can
be reused.
- Remove all default values for ``SpanStyle`` styles, so that all values can
be inherited from the paragraph.
- Support for package-relative ``src`` values in ``<para>`` ``<img>`` tags.
3.4.0 (2018-04-09)
------------------
- Drop Python 3.4 support.
- Feature: Support for ``<span style="NAME">`` and corresponding
``<spanStyle>`` styles.
- Bug: ``attr.Sequence``'s ``min_length`` and ``max_length`` was ineffective
3.3.0 (2017-12-06)
------------------
- Add support for non-rml header and footer statements
This is to be able to support export to Open Document Format.
- Dropped Support for Python 3.3
3.2.0 (2017-01-08)
------------------
- Improve ``IntegerSequence`` field to return ranges using lists of two
numbers instead of listing them all out.
- Extended ``IntegerSequence`` to allow specification of first number and
lower/upper bound inclusion.
- Updated ``ConcatenationPostProcessor`` to handle the new integer sequence
data structure. Since this is so much more efficient for the merging
library, there was a 5x improvement when including PDFs with page ranges.
- Implemented a PdfTk-based concatenation post-processor. PdfTk is very fast,
but unfortunatelya lot of the gain is lost, since the outline must be merged
in manually. The PdfTk post-processor can be enabled by::
from z3c.rml import pdfinclude
pdfinclude.IncludePdfPages.ConcatenationPostProcessorFactory = \
pdfinclude.PdfTkConcatenationPostProcessor
- Fix initial blank page when PDF inclusion is first flowable. [Kyle MacFarlane]
- Support for Python 3.5 [Kyle MacFarlane]
- attr.getFileInfo() crashed if the context element wasn't parsed.
3.1.0 (2016-04-04)
------------------
- Feature: Added new paragraph style attributes ``splitLongWords``,
``underlineProportion``, and ``bulletAnchor``.
- Feature: Added ``topPadder`` directive. Patch by Alvin Gonzales.
- Bug: Default SVG fill is black. Patch by Alvin Gonzales.
- Bug: Fixes drawing incorrectly showing when the SVG `viewBox` is not
anchored at coordinate (0, 0). Patch by Alvin Gonzales.
- Test: Updated versions.cfg to reference the latest releases of all
dependencies.
- Bug: Avoid raising an exception of PdfReadWarning when including PDFs.
Patch by Adam Groszer.
3.0.0 (2015-10-02)
------------------
- Support for python 3.3 and 3.4
- Add 'bulletchar' as a valid unordered bullet type.
- Added nice help to rml2pdf script.
- Allow "go()" to accept input and output file objects.
- Fix "Unresolved bookmark" issue.
- Fix Issue #10.
2.9.3 (2015-09-18)
------------------
- Support transparent images in <image> tag
2.9.2 (2015-06-16)
------------------
- Fix spelling "nineth" to "ninth".
2.9.1 (2015-06-15)
------------------
- Add missing file missing from brow-bag 2.9.0 release.
2.9.0 (2015-06-15)
------------------
- Added support for more numbering schemes for ordered lists. The following
new `bulletType` values are supported:
* 'l' - Numbers as lower-cased text.
* 'L' - Numbers as upper-cased text.
* 'o' - Lower-cased ordinal with numbers converted to text.
* 'O' - Upper-cased ordinal with numbers converted to text.
* 'r' - Lower-cased ordinal with numbers.
* 'R' - Upper-cased ordinal with numbers.
2.8.1 (2015-05-05)
------------------
- Added `barBorder` attribute to ``barCode`` and ``barCodeFlowable``
tags. This attribute controls the thickness of a white border around a QR
code.
2.8.0 (2015-02-02)
------------------
- Get version of reference manual from package version.
- Added the ability to specify any set of characters as the "bullet content"
like it is supported by ReportLab.
- Fixed code to work with ReportLab 3.1.44.
2.7.2 (2014-10-28)
------------------
- Now the latest PyPDF2 versions are supported.
2.7.1 (2014-09-10)
------------------
- Fixed package name.
2.7.0 (2014-09-10)
------------------
- Added ``bulletType`` sypport for the ``listStyle`` tag.
- Added "bullet" as a valid unordered list type value.
2.6.0 (2014-07-24)
------------------
- Implemented ability to use the ``mergePage`` tag inside the ``pageTemplate``
tag. This way you can use a PDF as a background for a page.
- Updated code to work with ReportLab 3.x, specifically the latest 3.1.8. This
includes a monkeypatch to the code formatter for Python 2.
- Updated code to work with PyPDF2 1.21. There is a bug in 1.22 that prohibits
us from upgrading fully.
- Changed buildout to create a testable set of scripts on Ubuntu. In the
process all package versions were nailed for testing.
2.5.0 (2013-12-10)
------------------
- Reimplamented ``includePdfPages`` directive to use the new PyPDF2 merger
component that supports simple appending of pages. Also optimized page
creation and minimized file loading. All of this resulted in a 95% speedup.
2.4.1 (2013-12-10)
------------------
- Fixed a bug when rendering a table with the same style twice. Unfortuantely,
Reportlab modifies a style during usage, so that a copy mustbe created for
each use. [Marcin Nowak]
2.4.0 (2013-12-05)
------------------
- Switch from ``pyPdf`` to the newer, maintained ``PyPDF2`` library.
2.3.1 (2013-12-03)
------------------
- Report correct element during error reporting.
- ``registerFontFamily`` never worked until now, since the directive was not
properly registered.
2.3.0 (2013-09-03)
------------------
- Added ``title``, ``subject``, ``author``, and ``creator`` attributes to
``document`` element. Those are set as PDF annotations, which are now
commonly used to hint viewers window titles, etc. (Those fields are not
available in RML2PDF.)
2.2.1 (2013-08-06)
------------------
- Make the number of max rendering passes configurable by exposing the setting
in the API.
- Added `align` attribute to ``img`` tag.
2.2.0 (2013-07-08)
------------------
- Added a new console script "rml2pdf" that renders an RML file to PDF.
- Added ``preserveAspectRatio`` to ``img`` tag flowable. The attribute was
already supported for the ``image`` tag.
2.1.0 (2013-03-07)
------------------
- Implemented all PDF viewer preferences. [Kyle MacFarlane]
* HideToolbar
* HideMenubar
* HideWindowUI
* FitWindow
* CenterWindow
* DisplayDocTitle
* NonFullScreenPageMode
* Direction
* ViewArea
* ViewClip
* PrintArea
* PrintClip
* PrintScaling
They are all available via the ``docinit`` tag.
- Added SVG support to the ``image`` and ``imageAndFlowables`` tags. [Kyle
MacFarlane]
Approach: Convert the drawing to a PIL ``Image`` instance and pass that
around just like a regular image. The big problem is that in the conversion
from ``Drawing`` to ``Image`` stroke width can often get messed up and
become too thick. I think this is maybe down to how scaling is done but you
can avoid it by editing the SVGs you want to insert. You also lose any
transparency and get a white background. Basically you no longer really have
a vector graphic but instead a 300 DPI bitmap that is automatically scaled
to the correct size with little quality loss.
- Added ability to look for font files in packages using the standard
"[package.path]/dir/filename" notation. [Kyle MacFarlane]
- Documented the ``pageSize`` versus ``pagesize`` attribute difference on
``template`` and ``pageTemplate`` elements compared to RML2PDF. [Kyle
MacFarlane]
- ``namedString`` element now evaluates its contents so you can use things
like ``pageNumber`` inside of it. [Kyle MacFarlane]
- Implemented ``evalString`` using Python's ``eval()`` with builtins
disabled. [Kyle MacFarlane]
- ``getName`` element now checks if it has a default attribute. This is used
as a width measurement for a first pass or as the actual value if the
reference isn't resolved after the second pass. [Kyle MacFarlane]
- ``getName`` element now supports forward references. This means you can now
do things like "Page X of Y". This only works in the ``drawString`` and
``para`` elements. [Kyle MacFarlane]
- General performance improvements. [Kyle MacFarlane]
- Improved performance by not applying a copy of the default style to every
table cell and also by not even trying to initialise the attributes if lxml
says they don't exist. [Kyle MacFarlane]
- ``MergePostProcessor`` class did not copy document info and table of
contents (aka Outlines) of ``inputFile1``. That meant that if you used any
``includePdfPages`` or ``mergePage`` directives you lost any ``outlineAdd``
directive effect. [Alex Garel]
- Fixed any failing tests, including the ones failing on Windows. [Kyle
MacFarlane]
- Fixed the table borders not printing or even appearing in some
viewers. [Kyle MacFarlane]
- Updated ``bootstrap.py`` and ``buildout.cfg`` to work with the latest
version of ``zc.buildout``.
- Updated build to use latest version of lxml.
2.0.0 (2012-12-21)
------------------
- Implemented ``saveState`` and ``restoreState`` directives. (LP #666194)
- Implemented ``storyPlace`` directive. (LP #665941)
- Implemented ``clip`` attribute of ``path`` directive. See RML example 041.
- Added ``h4``, ``h5``, and ``h6`` directives.
- Implemented ``codesnippet`` directive.
- Implemented ``pageBreakBefore``, ``frameBreakBefore``, ``textTransform``,
and ``endDots`` attributes for paragraph styles.
- Added ``maxLineLength`` and ``newLineChars`` attributes to the ``pre``
directive.
- Implemented ``pageNumber`` element for all ``draw*String`` elements.
- Implemented ``NamedString`` directive.
- Implemented ``startIndex`` and ``showIndex`` directive. Also hooked up
``index`` in paragraphs properly. You can now create real book indexes.
- Implemented ``ol``, ``ul``, and ``li`` directives, which allow highly
flexible lists to be created. Also implemented a complimentary ``listStyle``
directive.
- Implemented the following doc-programming directives:
* docAssert
* docAssign
* docElse
* docIf
* docExec
* docPara
* docWhile
- Added ``encName`` attribute to ``registerCidFont`` directive.
- Renamed ``bookmark`` to ``bookmarkPage``.
- Created a new canvas directive called ``bookmark``.
- Added ``img`` directive, which is a simple image flowable.
- Implemented crop marks support fully.
- Added ``pageLayout`` and ``pageMode`` to ``docInit`` directive.
- Implemented all logging related directives.
- Implemented ``color`` directive inside the ``initialize`` directive.
- Renamed ``pdfInclude`` to documented ``includePdfPages`` and added `pages`
attribute, so that you can only include specific pages.
- Don't show "doc" namespace in reference snippets.
- Create a list of RML2PDF and z3c.rml differences.
- Implemented the ``ABORT_ON_INVALID_DIRECTIVE`` flag, that when set ``True``
will raise a ``ValueError`` error on the first occurence of a bad tag.
- Implemented ``setFontSize`` directive for page drawings.
- Implemented ``plugInGraphic`` which allows inserting graphics rendered in
Python.
- Added `href` and `destination` to table cells and rectangles.
- Bug: Due to a logic error, bad directives were never properly detected and
logged about.
- Bug: Overwriting the default paragraph styles did not work properly.
- Bug: Specifying a color in any tag inside the paragraph would fail, if the
color was a referenced name.
- Bug: Moved premature ``getName`` evaluation into runtime to properly handle
synamic content now. This is now properly done for any paragraph and
draw string variant.
- Bug: Fixed DTD generator to properly ignore Text Nodes as attributes. Also
text nodes were not properly documented as element PCDATA.
1.1.0 (2012-12-18)
------------------
- Upgrade to ReportLab 2.6. This required some font changes and several
generated PDFs did not match, since some default fonts changed to sans-serif.
- Added ``pdfInclude`` directive from Alex Garel. (LP #969399).
- Switched to Pillow (from PIL).
- Switched RML highlighting in RML Reference from SilverCity to Pygments.
- Bug: Addressed a bug in ReportLab 2.6 that disallowed 3-D pie charts from
rendering.
- Bug: Properly reset pdfform before rendering a document.
- Bug: Reset fonts properly before a rendering.
1.0.0 (2012-04-02)
------------------
- Using Python's ``doctest`` module instead of depreacted
``zope.testing.doctest``.
0.9.1 (2010-07-22)
------------------
- I found a more complete paragraph border patch from Yuan Hong. Now the DTD
is updated, the border supports a border radius and the tag-para.rml sample
has been updated.
0.9.0 (2010-07-22)
------------------
- Upgraded to ReportLab 2.4. This required some font changes and several
generated PDFs did not match, since some default fonts changed.
- Upgraded to latest lxml. This only required a trivial change. Patch by Felix
Schwarz.
- Implemented ``linePlot3D`` directive. Patch by Faisal Puthuparackat.
- Added paragraph border support. Patch by Yuan Hong.
- Bug: Fixed version number in reference.pt. Patch by Felix Schwarz.
- Bug: Write PDF documents in binary mode. Patch by Felix Schwarz.
0.8.0 (2009-02-18)
------------------
- Bug: Use python executable as a part of the subprocess command.
- Add support for RML's `pageNumber` element.
0.7.3 (2007-11-10)
------------------
- Make sure that the output dir is included in the distribution.
0.7.2 (2007-11-10)
------------------
- Upgraded to work with ReportLab 2.1 and lxml 1.3.6.
- Fix sub-process tests for a pure egg setup.
0.7.1 (2007-07-31)
------------------
- Bug: When the specified page size (within the ``pageInfo`` element) was a
word or set thereof, the processing would fail. Thanks to Chris Zelenak for
reporting the bug and providing a patch.
0.7.0 (2007-06-19)
------------------
- Feature: Added a Chinese PDF sample file to ``tests/expected`` under the
name ``sample-shipment-chinese.pdf``.
- Feature: Added another tag that is commonly needed in projects. The
``<keepTogether>`` tag will keep the child flowables in the same frame.
When necessary, the frame break will be automatic. Patch by Yuan Hong.
- Feature: Added the "alignment" attribute to the ``blockTable``
directive. This attribute defines the horizontal alignment for a table that
is not 100% in width of the containing flowable. Patch by Yuan Hong.
- Feature: When creating Chinese PDF documents, the normal TTF for Chinese
printing is 'simsun'. However, when bold text is neeed, we switch to
'simhei'. To properly register this, we need the
``reportlab.lib.fonts.addMapping`` function. This is missing in the reportlab
RML specification, so a new directive has been defined::
<addMapping faceName="simsun" bold="1" italic="0" psName="simhei" />
Patch by Yuan Hong.
- Feature: The ``para`` and ``paraStyle`` directive now support the "wordWrap"
attribute, which allows for selecting a different wrod wrapping
algorithm. This is needed because some far-East Asian languages do not use
white space to separate words. Patch by Yuan Hong.
- Bug: Handle Windows drive letters correctly. Report and fix by Yuan Hong.
0.6.0 (2007-06-19)
------------------
- Bug: Fixed setup.py to include all dependencies.
- Bug: Added test to show that a blocktable style can be applied multiple
times. A user reported that this is not working, but I could not replicate
the problem.
- Update: Updated the expected renderings to ReportLab 2.1. There were some
good layout fixes that broke the image comparison.
0.5.0 (2007-04-01)
------------------
- Initial Release
| z3c.rml | /z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/CHANGES.rst | CHANGES.rst |
===================================================
``z3c.rml`` -- An alternative implementation of RML
===================================================
.. image:: https://img.shields.io/pypi/v/z3c.rml.svg
:target: https://pypi.org/project/z3c.rml/
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/z3c.rml.svg
:target: https://pypi.org/project/z3c.rml/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/z3c.rml/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/z3c.rml/actions/workflows/tests.yml
:alt: Build Status
.. image:: https://coveralls.io/repos/github/zopefoundation/z3c.rml/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/z3c.rml?branch=master
This is an alternative implementation of ReportLab's RML PDF generation XML
format. Like the original implementation, it is based on ReportLab's
``reportlab`` library.
You can read all about ``z3c.rml`` and see many examples on how to use it,
see the `RML Reference`_
.. _RML Reference: https://github.com/zopefoundation/z3c.rml/blob/master/src/z3c/rml/rml-reference.pdf?raw=true
Install on pip::
pip install z3c.rml
z3c.rml is then available on the commandline as z3c.rml.::
$ z3c.rml --help
usage: rml2pdf [-h]
xmlInputName [outputFileName] [outDir]
[dtdDir]
Converts file in RML format into PDF file.
positional arguments:
xmlInputName RML file to be processed
outputFileName output PDF file name
outDir output directory
dtdDir directory with XML DTD (not yet supported)
optional arguments:
-h, --help show this help message and exit
Copyright (c) 2007 Zope Foundation and Contributors.
Save this file as file.rml::
<!DOCTYPE document SYSTEM "rml.dtd">
<document filename="example_01.pdf">
<template showBoundary="1"> <!--Debugging is now turned on, frame outlines -->
<!--will appear on the page -->
<pageTemplate id="main">
<!-- two frames are defined here: -->
<frame id="first" x1="100" y1="400" width="150" height="200"/>
<frame id="second" x1="300" y1="400" width="150" height="200"/>
</pageTemplate>
</template>
<stylesheet>
<!-- still empty...-->
</stylesheet>
<story>
<para>
Welcome to RML.
</para>
</story>
</document>
Then run::
$ z3c.rml file.rml
The output will be example_01.pdf as defined in the document
Codewise you can do::
from z3c.rml import rml2pdf
rml2pdf.go('file.rml','file.pdf') | z3c.rml | /z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/README.rst | README.rst |
==============================================
RML2PDF and z3c.rml Implementation Differences
==============================================
This document outlines the differences between ReportLab Inc.'s RML2PDF
library and z3c.rml.
Incompatibilies
---------------
- ``<template>``
* `pageSize`: This is called `pagesize` in this implementation to match the
API.
- ``<pageTemplate>``
* `pageSize`: This is called `pagesize` in this implementation to match the
API.
- ``<addMapping>``: This is a useful API function that was supported in
earlier versions of RML2PDF. It is now gone, but this library still supports
it.
- ``<barCode>``
* Most barcode attributes available via the API and the flowable are not
supported in the drawing version in RML2PDF. I have no idea why!
* `isoScale`: This attributes forces the bar code to keep the original
aspect ratio. This is straight from the API.
- ``<barCodeFlowable>``
* `widthSize`: This is called `width` in this implementation to match the
API.
* `heightSize`: This is called `height` in this implementation to match the
API.
* `tracking`: This is only used for USPS4S and the API actually uses the
`value` argument for this. Thus this attribute is omitted.
- ``<catchForms>``: This feature requires PageCatcher, which is a ReportLab
commercial product and there is no Open Source alternative.
- ``<docinit>``:
* ``outlineAdd`` directive really does not make much sense here. The API
docs claim its availability but the hand-written docs state it must be
within a story.
* ``alias`` directive is completely undocumented in this context.
- ``<drawing>``: There is no documentation for this tag and I do not know what
it is supposed to do. Thus z3c.rml does not implement it.
- ``<img>``: Support for `preserveAspectRatio` attribute, which is not
available in RML or ReportLab.
- ``<join>``: This directive is not implemented due to lack of documentation.
- ``<keepTogether>``: This directive is not implemented in RML2PDF, but there
exists an API flowable for it and it seems obviously useful.
- ``<length>``: This directive is not implemented due to lack of documentation.
- ``<template>``: The `firstPageTemplate` attribute is not implemented, since
it belongs to the ``<story>`` directive. Several RML2PDF examples use it
that way too, so why is it documented differently?
- ``<widget>``: There is no documentation for this tag and I do not know what
it is supposed to do. Thus z3c.rml does not implement it.
- ``<paraStyle>``:
* ``underline``: A boolean field indicating whether the entire paragraph is
underlined. The following related attributes have also been added to the
style: ``underlineColor``, ``underlineOffset``, ``underlineWidth``,
``underlineGap``, and ``underlineKind``
* ``strike``: A boolean field indicating whether the entire paragraph is
stricken. The following related attributes have also been added to the
style: ``strikeColor``, ``strikeOffset``, ``strikeWidth``,
``strikeGap``, and ``strikeKind``
* ``justifyLastLine``: Added attribute that is available in the API.
* ``justifyBreaks``: Added attribute that is available in the API.
* ``spaceShrinkage``: Added attribute that is available in the API.
* ``linkUnderline``: Added attribute that is available in the API.
Extensions
----------
z3c.rml implements ``<header>`` and ``<footer>`` directives. These go inside
``<pageTemplate>`` directives, and are equivalent to having
``<pageGraphics><place>`` and take the same arguments as ``<pageGraphics>``.
The purpose of these directives is to be able to handle headers and footers
differently then from other graphical elements when dealing with other
formats than PDF.
If you want one left aligned header or footer, and one right aligned, you
simply add multiple headers or footers.
See src/z3c/rml/tests/input/rml-examples-050-header-footer.rml for an example.
To be Done
----------
Each major bullet represents a missing element. Names after the elements are
missing attributes. A "-" (minus) sign in front of an element or attribute
denotes a feature not in RML2PDF. The "->" arrow designates a difference in
naming.
- pre/xpre: -bulletText, -dedent
- blockTable: -repeatRows, -alignment
- evalString
- image: -showBoundary, -preserveAspectRatio
- doForm
- figure
- imageFigure
- checkBox
- letterBoxes
- textBox
- boxStyle
- form
- lineMode: -miterLimit
- paraStyle: fontName -> fontname, fontSize -> fontsize, -keepWithNext,
-wordWrap, -border*
- blockTableStyle: -keepWithNext
- blockBackground: -colorsByRow, -colorsByCol
- -blockRowBackground
- -blockColBackground
- lineStyle: -join
- bulkData: +stripBlock, stripLines, stripFields, fieldDelim, recordDelim
- excelData
- frame: -*Padding, -showBoundary
| z3c.rml | /z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/RML-DIFFERENCES.rst | RML-DIFFERENCES.rst |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.