Commit 1dcf4b17 authored by Sebastian Ramacher's avatar Sebastian Ramacher

Imported Upstream version 0.7-svn20060621

parent e37f487b
py lib Copyright holders, 2003-2005
=======================================
Except when otherwise stated (look for LICENSE files or information at
the beginning of each file) the files in the 'py' directory are
copyrighted by one or more of the following people and organizations:
Holger Krekel <hpk@trillke.net>
merlinux GmbH, Germany <office@merlinux.de>
Armin Rigo <arigo@tunes.org>
Jan Balster <jan@balster.info>
Contributors include::
Ian Bicking <ianb@colorstudy.com>
Grig Gheorghiu <grig@gheorghiu.net>
Bob Ippolito <bob@redivi.com>
Christian Tismer <tismer@stackless.com>
Samuele Pedroni <pedronis@strakt.com>
Except when otherwise stated (look for LICENSE files or information at
the beginning of each file) all files in the 'py' directory are
licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
......@@ -7,8 +7,8 @@ from initpkg import initpkg
initpkg(__name__,
description = "py.test and the py lib",
revision = int('$LastChangedRevision: 14485 $'.split(':')[1][:-1]),
lastchangedate = '$LastChangedDate: 2005-07-11 05:12:29 -0300 (Mon, 11 Jul 2005) $',
revision = int('$LastChangedRevision: 26999 $'.split(':')[1][:-1]),
lastchangedate = '$LastChangedDate: 2006-05-09 12:38:55 -0300 (Tue, 09 May 2006) $',
version = "0.8.0-alpha2",
url = "http://codespeak.net/py",
download_url = "http://codespeak.net/download/py/py-0.8.0-alpha2.tar.gz",
......@@ -23,10 +23,10 @@ initpkg(__name__,
# helpers for use from test functions or collectors
'test.raises' : ('./test/raises.py', 'raises'),
'test.deprecated_call' : ('./test/deprecate.py', 'deprecated_call'),
'test.skip' : ('./test/item.py', 'skip'),
'test.fail' : ('./test/item.py', 'fail'),
'test.exit' : ('./test/session.py', 'exit'),
'test.skip_on_error' : ('./test/item.py', 'skip_on_error'),
'test.compat.TestCase' : ('./test/compat.py', 'TestCase'),
# configuration/initialization related test api
......@@ -62,9 +62,9 @@ initpkg(__name__,
'path.svnurl' : ('./path/svn/urlcommand.py', 'SvnCommandPath'),
'path.local' : ('./path/local/local.py', 'LocalPath'),
'path.extpy' : ('./path/extpy/extpy.py', 'Extpy'),
'path.checker' : ('./path/common.py', 'checker'),
'path.checker' : ('./path/common.py', 'checker'), # deprecated
# some nice more or less magic APIs
# some nice slightly magic APIs
'magic.greenlet' : ('./magic/greenlet.py', 'greenlet'),
'magic.invoke' : ('./magic/invoke.py', 'invoke'),
'magic.revoke' : ('./magic/invoke.py', 'revoke'),
......@@ -74,7 +74,7 @@ initpkg(__name__,
'magic.View' : ('./magic/viewtype.py', 'View'),
'magic.AssertionError' : ('./magic/assertion.py', 'AssertionError'),
# generalized inspection API
# python inspection/code-generation API
'code.compile' : ('./code/source.py', 'compile_'),
'code.Source' : ('./code/source.py', 'Source'),
'code.Code' : ('./code/code.py', 'Code'),
......@@ -84,12 +84,19 @@ initpkg(__name__,
# backports and additions of builtins
'builtin.enumerate' : ('./builtin/enumerate.py', 'enumerate'),
'builtin.reversed' : ('./builtin/reversed.py', 'reversed'),
# gateways into remote contexts
'execnet.SocketGateway' : ('./execnet/register.py', 'SocketGateway'),
'execnet.PopenGateway' : ('./execnet/register.py', 'PopenGateway'),
'execnet.SshGateway' : ('./execnet/register.py', 'SshGateway'),
# input-output helping
'io.dupfile' : ('./io/dupfile.py', 'dupfile'),
'io.FDCapture' : ('./io/capture.py', 'FDCapture'),
'io.OutErrCapture' : ('./io/capture.py', 'OutErrCapture'),
'io.callcapture' : ('./io/capture.py', 'callcapture'),
# error module, defining all errno's as Classes
'error' : ('./misc/error.py', 'error'),
......@@ -108,7 +115,10 @@ initpkg(__name__,
'log.Path' : ('./log/consumer.py', 'Path'),
'log.STDOUT' : ('./log/consumer.py', 'STDOUT'),
'log.STDERR' : ('./log/consumer.py', 'STDERR'),
'log.Syslog' : ('./log/consumer.py', 'Syslog'),
'log.get' : ('./log/logger.py', 'get'),
# compatibility modules (taken from 2.4.1)
'compat.doctest' : ('./compat/doctest.py', '*'),
'compat.optparse' : ('./compat/optparse.py', '*'),
'compat.textwrap' : ('./compat/textwrap.py', '*'),
......
#!/usr/bin/python
#!/usr/bin/env python
#
# find and import a version of 'py'
......
#!/usr/bin/python
#!/usr/bin/env python
from _findpy import py
import sys
......
......@@ -3,5 +3,10 @@
from _findpy import py
import py
for x in py.path.local().visit('*.pyc', py.path.checker(dotfile=0)):
if len(py.std.sys.argv) > 1:
path = py.path.local(py.std.sys.argv[1])
else:
path = py.path.local()
print "cleaning path", path
for x in path.visit('*.pyc', lambda x: x.check(dotfile=0)):
x.remove()
......@@ -3,53 +3,6 @@
# hands on script to compute the non-empty Lines of Code
# for tests and non-test code
import py
curdir = py.path.local()
class Filecounter:
def __init__(self):
self.counts = {}
def count(self, fn, empty=False):
if empty:
s = len(p.readlines())
else:
s = 0
for i in fn.readlines():
if i.strip():
s += 1
self.counts[fn] = s
if __name__ == '__main__':
testcounter = Filecounter()
counter = Filecounter()
args = py.std.sys.argv[1:]
if not args:
args = ['.']
locations = [py.path.local(x) for x in args]
for loc in locations:
for x in loc.visit('*.py', py.path.checker(dotfile=0)):
bn = x.basename
if bn.startswith('test_') or bn.endswith('_test.py'):
testcounter.count(x)
else:
counter.count(x)
numfiles = len(counter.counts)
numtestfiles = len(testcounter.counts)
numlines = sum(counter.counts.values())
numtestlines = sum(testcounter.counts.values())
#for x,y in counter.counts.items():
# print "%3d %30s" % (y,x)
items = counter.counts.items()
items.sort(lambda x,y: cmp(x[1], y[1]))
for x, y in items:
print "%3d %30s" % (y,x)
print "%30s %3d" %("number of testfiles", numtestfiles)
print "%30s %3d" %("number of testlines", numtestlines)
print "%30s %3d" %("number of files", numfiles)
print "%30s %3d" %("number of lines", numlines)
from _findpy import py
from py.__.misc.cmdline.countloc import countloc
countloc()
#!/usr/bin/python
#!/usr/bin/env python
from _findpy import py
import re
string = py.std.sys.argv[1]
curdir = py.path.local()
for x in curdir.visit('*.py', py.path.checker(dotfile=0)):
s = x.read()
if s.find(string) != -1:
lines = x.readlines()
for i, line in enumerate(lines):
if line.find(string) != -1:
print "%s:%d %s" %(x.relto(curdir), i+1, line.rstrip())
def rec(p):
return p.check(dotfile=0)
optparse = py.compat.optparse
parser = optparse.OptionParser()
parser.add_option("-i", "--ignore-case", action="store_true", dest="ignorecase",
help="ignore case distinctions")
if __name__ == '__main__':
(options, args) = parser.parse_args()
string = args[0]
if options.ignorecase:
string = string.lower()
for x in curdir.visit('*.py', rec):
s = x.read()
searchs = s
if options.ignorecase:
searchs = s.lower()
if s.find(string) != -1:
lines = s.splitlines()
if options.ignorecase:
searchlines = s.lower().splitlines()
else:
searchlines = lines
for i, (line, searchline) in enumerate(zip(lines, searchlines)):
if searchline.find(string) != -1:
print "%s:%d: %s" %(x.relto(curdir), i+1, line.rstrip())
#!/usr/bin/python
#!/usr/bin/env python
"""
invoke
......@@ -14,6 +14,15 @@ import os, sys
from _findpy import py
from py.__.misc import rest
if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()):
def log(msg):
print msg
else:
def log(msg):
pass
if __name__=='__main__':
basedir = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.path.insert(0, basedir)
......@@ -27,9 +36,12 @@ if __name__=='__main__':
if not p.check():
log("path %s not found, ignoring" % p)
continue
def fil(p):
return p.check(fnmatch='*.txt', versioned=True)
def rec(p):
return p.check(dotfile=0)
if p.check(dir=1):
for x in p.visit(fil=py.path.checker(fnmatch='*.txt', versioned=True),
rec=py.path.checker(dotfile=0)):
for x in p.visit(fil, rec):
rest.process(x)
elif p.check(file=1):
rest.process(p)
#!/usr/bin/env python
docstring = """
invoke
%s filename1.txt
to generate a pdf file from restructered text.
http://docutils.sourceforge.net/docs/user/rst/quickref.html
""" % __file__
from _findpy import py
from py.__.rest import directive
from py.__.rest.latex import process_rest_file, process_configfile
optparse = py.compat.optparse
parser = optparse.OptionParser(usage=docstring)
parser.add_option("-c", "--config", dest="configfile",
help="use config file")
parser.add_option("--stylesheet", dest="stylesheet", default=None,
help="use style sheet")
parser.add_option("--debug", action="store_true", dest="debug",
default=False,
help="print debug output and don't delete files")
if __name__ == '__main__':
directive.BackendStore("latex")
(options, args) = parser.parse_args()
if options.configfile is not None:
configfile = py.path.local(options.configfile)
process_configfile(options.configfile, options.debug)
elif len(args) != 1:
parser.error("please supply a file name")
else:
f = py.path.local(args[0])
process_rest_file(args[0], options.stylesheet, options.debug)
@echo off
python %~dp0\..\py.cleanup %*
\ No newline at end of file
@echo off
python "%~dp0\..\py.cleanup" %*
@echo off
python %~dp0\..\py.countloc %*
\ No newline at end of file
@echo off
python "%~dp0\..\py.countloc" %*
@echo off
python %~dp0\..\py.lookup %*
\ No newline at end of file
@echo off
python "%~dp0\..\py.lookup" %*
@echo off
python %~dp0\..\py.rest %*
\ No newline at end of file
@echo off
python "%~dp0\..\py.rest" %*
@echo off
python %~dp0\..\py.test %*
\ No newline at end of file
@echo off
python "%~dp0\..\py.test" %*
from __future__ import generators
try:
reversed = reversed
except NameError:
def reversed(sequence):
"""reversed(sequence) -> reverse iterator over values of the sequence
Return a reverse iterator
"""
if hasattr(sequence, '__reversed__'):
return sequence.__reversed__()
if not hasattr(sequence, '__getitem__'):
raise TypeError("argument to reversed() must be a sequence")
return reversed_iterator(sequence)
class reversed_iterator(object):
def __init__(self, seq):
self.seq = seq
self.remaining = len(seq)
def __iter__(self):
return self
def next(self):
i = self.remaining
if i > 0:
i -= 1
item = self.seq[i]
self.remaining = i
return item
raise StopIteration
def __length_hint__(self):
return self.remaining
from py.builtin import reversed
from py.test import raises
def test_reversed():
r = reversed("hello")
assert iter(r) is r
assert r.next() == "o"
assert r.next() == "l"
assert r.next() == "l"
assert r.next() == "e"
assert r.next() == "h"
raises(StopIteration, r.next)
assert list(reversed(list(reversed("hello")))) == ['h','e','l','l','o']
raises(TypeError, reversed, reversed("hello"))
......@@ -9,5 +9,6 @@ class Directory(py.test.collect.Directory):
# return False
# return super(Directory, self).recfilter(path)
def run(self):
py.test.skip("c-extension testing needs platform selection")
#def run(self):
# py.test.skip("c-extension testing needs platform selection")
pass
......@@ -255,6 +255,12 @@ static int slp_save_state(char* stackref)
#endif
/* This is a trick to prevent the compiler from inlining or
removing the frames */
int (*_PyGreen_slp_switch) (void);
int (*_PyGreen_switchstack) (void);
void (*_PyGreen_initialstub) (void*);
static int g_switchstack(void)
{
/* perform a stack switch according to some global variables
......@@ -271,7 +277,7 @@ static int g_switchstack(void)
ts_current->top_frame = tstate->frame;
}
ts_origin = ts_current;
err = slp_switch();
err = _PyGreen_slp_switch();
if (err < 0) { /* error */
Py_XDECREF(ts_passaround);
ts_passaround = NULL;
......@@ -288,11 +294,6 @@ static int g_switchstack(void)
return err;
}
/* This is a trick to prevent the compiler from inlining or
removing the frames */
int (*_PyGreen_switchstack) (void);
void (*_PyGreen_initialstub) (void*);
static PyObject* g_switch(PyGreenlet* target, PyObject* args)
{
/* _consumes_ a reference to the args tuple,
......@@ -529,6 +530,8 @@ static void green_dealloc(PyGreenlet* self)
return;
}
}
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
Py_XDECREF(self->run_info);
self->ob_type->tp_free((PyObject*) self);
}
......@@ -546,17 +549,116 @@ static PyObject* single_result(PyObject* results)
return results;
}
static PyObject *
throw_greenlet(PyGreenlet* self, PyObject* typ, PyObject* val, PyObject* tb)
{
/* Note: _consumes_ a reference to typ, val, tb */
PyErr_Restore(typ, val, tb);
return single_result(g_switch(self, NULL));
}
PyDoc_STRVAR(switch_doc,
"switch([val]) -> switch execution to greenlet optionally passing a value, "
"return value passed when switching back");
static PyObject* green_switch(PyGreenlet* self, PyObject* args)
{
Py_INCREF(args);
return single_result(g_switch(self, args));
}
#ifndef PyExceptionClass_Check /* Python < 2.5 */
# define PyExceptionClass_Check PyClass_Check
#endif
#ifndef PyExceptionInstance_Check /* Python < 2.5 */
# define PyExceptionInstance_Check PyInstance_Check
#endif
#ifndef PyExceptionInstance_Class /* Python < 2.5 */
# define PyExceptionInstance_Class(x) \
((PyObject*)((PyInstanceObject*)(x))->in_class)
#endif
PyDoc_STRVAR(throw_doc,
"throw(typ[,val[,tb]]) -> raise exception in greenlet, return value passed "
"when switching back");
static PyObject* green_throw(PyGreenlet* self, PyObject* args)
{
PyObject *typ = PyExc_GreenletExit;
PyObject *val = NULL;
PyObject *tb = NULL;
PyObject *ret = NULL;
if (!PyArg_ParseTuple(args, "|OOO:throw", &typ, &val, &tb))
return NULL;
/* First, check the traceback argument, replacing None with
NULL. */
if (tb == Py_None)
tb = NULL;
else if (tb != NULL && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"throw() third argument must be a traceback object");
return NULL;
}
Py_INCREF(typ);
Py_XINCREF(val);
Py_XINCREF(tb);
if (PyExceptionClass_Check(typ)) {
PyErr_NormalizeException(&typ, &val, &tb);
}
else if (PyExceptionInstance_Check(typ)) {
/* Raising an instance. The value should be a dummy. */
if (val && val != Py_None) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto failed_throw;
}
else {
/* Normalize to raise <class>, <instance> */
Py_XDECREF(val);
val = typ;
typ = PyExceptionInstance_Class(typ);
Py_INCREF(typ);
}
}
else {
/* Not something you can raise. throw() fails. */
PyErr_Format(PyExc_TypeError,
"exceptions must be classes, or instances, not %s",
typ->ob_type->tp_name);
goto failed_throw;
}
return throw_greenlet(self, typ, val, tb);
failed_throw:
/* Didn't use our arguments, so restore their original refcounts */
Py_DECREF(typ);
Py_XDECREF(val);
Py_XDECREF(tb);
return NULL;
}
static int green_nonzero(PyGreenlet* self)
{
return PyGreen_ACTIVE(self);
}
static PyObject* green_getdead(PyGreenlet* self, void* c)
{
PyObject* res;
if (PyGreen_ACTIVE(self) || !PyGreen_STARTED(self))
res = Py_False;
else
res = Py_True;
Py_INCREF(res);
return res;
}
static PyObject* green_getrun(PyGreenlet* self, void* c)
{
if (PyGreen_STARTED(self) || self->run_info == NULL) {
......@@ -672,8 +774,9 @@ int PyGreen_SetParent(PyObject* g, PyObject* nparent)
static PyMethodDef green_methods[] = {
{"switch", (PyCFunction)green_switch, METH_VARARGS, /*XXXswitch_doc*/ NULL},
{NULL, NULL} /* sentinel */
{"switch", (PyCFunction)green_switch, METH_VARARGS, switch_doc},
{"throw", (PyCFunction)green_throw, METH_VARARGS, throw_doc},
{NULL, NULL} /* sentinel */
};
static PyGetSetDef green_getsets[] = {
......@@ -683,6 +786,8 @@ static PyGetSetDef green_getsets[] = {
(setter)green_setparent, /*XXX*/ NULL},
{"gr_frame", (getter)green_getframe,
NULL, /*XXX*/ NULL},
{"dead", (getter)green_getdead,
NULL, /*XXX*/ NULL},
{NULL}
};
......@@ -700,7 +805,7 @@ static PyNumberMethods green_as_number = {
(inquiry)green_nonzero, /* nb_nonzero */
};
statichere PyTypeObject PyGreen_Type = {
PyTypeObject PyGreen_Type = {
PyObject_HEAD_INIT(NULL)
0,
"greenlet.greenlet",
......@@ -726,7 +831,7 @@ statichere PyTypeObject PyGreen_Type = {
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
offsetof(PyGreenlet, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
green_methods, /* tp_methods */
......@@ -766,6 +871,7 @@ void initgreenlet(void)
PyObject* m;
char** p;
_PyGreen_switchstack = g_switchstack;
_PyGreen_slp_switch = slp_switch;
_PyGreen_initialstub = g_initialstub;
m = Py_InitModule("greenlet", GreenMethods);
......
......@@ -20,6 +20,7 @@ typedef struct _greenlet {
PyObject* run_info;
struct _frame* top_frame;
int recursion_depth;
PyObject* weakreflist;
} PyGreenlet;
extern PyTypeObject PyGreen_Type;
......
......@@ -47,9 +47,9 @@ slp_switch(void)
: "r" (stsizediff)
);
SLP_RESTORE_STATE();
return 0;
}
__asm__ volatile ("" : : : REGS_TO_SAVE);
return 0;
}
#endif
......
......@@ -2,6 +2,10 @@
* this is the internal transfer function.
*
* HISTORY
* 07-Sep-05 (py-dev mailing list discussion)
* removed 'r31' from the register-saved. !!!! WARNING !!!!
* It means that this file can no longer be compiled statically!
* It is now only suitable as part of a dynamic library!
* 14-Jan-04 Bob Ippolito <bob@redivi.com>
* added cr2-cr4 to the registers to be saved.
* Open questions: Should we save FP registers?
......@@ -32,21 +36,18 @@
#define STACK_MAGIC 3
/* !!!!WARNING!!!! need to add "r31" in the next line if this header file