This repository has been archived by the owner. It is now read-only.
Permalink
Browse files

adding initial code

  • Loading branch information...
rfk committed Oct 4, 2011
0 parents commit f7099954025e0052dc5bdcb65bc96cf462575478
Showing with 319 additions and 0 deletions.
  1. +10 −0 .gitignore
  2. +5 −0 ChangeLog.txt
  3. +5 −0 MANIFEST.in
  4. +63 −0 README.rst
  5. +175 −0 git_remote_hg/__init__.py
  6. +61 −0 setup.py
@@ -0,0 +1,10 @@
*.pyc
*.pyo
*~
*.swp
build/
dist/
.coverage
cover
.tox
*.egg-info
@@ -0,0 +1,5 @@
v0.1.0:
* initial release - you might say *everything* has changed...
@@ -0,0 +1,5 @@
include README.rst
include LICENSE.txt
include ChangeLog.txt
@@ -0,0 +1,63 @@
dexml: a dead-simple Object-XML mapper for Python
==================================================
Let's face it: xml is a fact of modern life. I'd even go so far as to say
that it's *good* at what is does. But that doesn't mean it's easy to work
with and it doesn't mean that we have to like it. Most of the time, XML
just needs to get out of the way and let you do some actual work instead
of writing code to traverse and manipulate yet another DOM.
The dexml module takes the obvious mapping between XML tags and Python objects
and lets you capture that as cleanly as possible. Loosely inspired by Django's
ORM, you write simple class definitions to define the expected structure of
your XML document. Like so::
>>> import dexml
>>> from dexml import fields
>>> class Person(dexml.Model):
... name = fields.String()
... age = fields.Integer(tagname='age')
Then you can parse an XML document into an object like this::
>>> p = Person.parse("<Person name='Foo McBar'><age>42</age></Person>")
>>> p.name
u'Foo McBar'
>>> p.age
42
And you can render an object into an XML document like this::
>>> p = Person(name="Handsome B. Wonderful",age=36)
>>> p.render()
'<?xml version="1.0" ?><Person name="Handsome B. Wonderful"><age>36</age></Person>'
Malformed documents will raise a ParseError::
>>> p = Person.parse("<Person><age>92</age></Person>")
Traceback (most recent call last):
...
ParseError: required field not found: 'name'
Of course, it gets more interesting when you nest Model definitions, like this::
>>> class Group(dexml.Model):
... name = fields.String(attrname="name")
... members = fields.List(Person)
...
>>> g = Group(name="Monty Python")
>>> g.members.append(Person(name="John Cleese",age=69))
>>> g.members.append(Person(name="Terry Jones",age=67))
>>> g.render(fragment=True)
'<Group name="Monty Python"><Person name="John Cleese"><age>69</age></Person><Person name="Terry Jones"><age>67</age></Person></Group>'
There's support for XML namespaces, default field values, case-insensitive
parsing, and more fun stuff. Check out the documentation on the following
classes for more details:
:Model: the base class for objects that map into XML
:Field: the base class for individual model fields
:Meta: meta-information about how to parse/render a model
@@ -0,0 +1,175 @@
"""
git_remote_hg: access hg repositories as git remotes
=====================================================
"""
__ver_major__ = 0
__ver_minor__ = 1
__ver_patch__ = 0
__ver_sub__ = ""
__version__ = "%d.%d.%d%s" % (__ver_major__,__ver_minor__,__ver_patch__,__ver_sub__)
import sys
import os
import subprocess
import threading
import socket
import time
import urllib
import wsgiref.simple_server
from textwrap import dedent
def git_remote_hg(argv=None, git_dir=None):
if argv is None:
argv = sys.argv
if git_dir is None:
git_dir = os.getcwd()
hg_url = argv[2]
hg_checkout = HgGitCheckout(git_dir, hg_url)
backend = GitHttpBackend(hg_checkout.git_repo_dir)
t = backend.start()
try:
while backend.repo_url is None:
time.sleep(0.1)
hg_checkout.pull()
cmd = ("git", "remote-http", backend.repo_url, )
retcode = subprocess.call(cmd, env=os.environ)
if retcode not in (0, 1):
msg = "git-remote-http failed with error code %d" % (retcode,)
raise RuntimeError(msg)
hg_checkout.push()
finally:
backend.stop()
t.join()
class HgGitCheckout(object):
"""Class managing a local hg-git checkout."""
def __init__(self, git_dir, hg_url):
self.hg_url = hg_url
self.hg_name = hg_name = urllib.quote(hg_url, safe="")
self.hg_repo_dir = os.path.join(git_dir, ".git", "hgremotes", hg_name)
if not os.path.exists(self.hg_repo_dir):
self.initialize_hg_repo()
self.git_repo_dir = os.path.join(self.hg_repo_dir, ".hg", "git")
def _do(self, *cmd, **kwds):
kwds.setdefault("stdout", sys.stderr)
return subprocess.check_call(cmd, **kwds)
def pull(self):
self._do("hg", "pull", cwd=self.hg_repo_dir)
self._do("hg", "gexport", cwd=self.hg_repo_dir)
def push(self):
self._do("hg", "gimport", cwd=self.hg_repo_dir)
self._do("hg", "push", cwd=self.hg_repo_dir)
def initialize_hg_repo(self):
print>>sys.stderr, "initializing hg repo from", self.hg_url
hg_repo_dir = self.hg_repo_dir
os.makedirs(os.path.dirname(hg_repo_dir))
self._do("hg", "clone", self.hg_url, hg_repo_dir)
self._do("hg", "update", "null", cwd=hg_repo_dir)
with open(os.path.join(hg_repo_dir, "README.txt"), "wt") as f:
f.write(dedent("""
This is a bare mercurial checkout created by git-remote-hg.
Don't mess with it unless you know what you're doing.
"""))
with open(os.path.join(hg_repo_dir, ".hg", "hgrc"), "at") as f:
f.write(dedent("""
[extensions]
hgext.bookmarks =
hggit =
"""))
self._do("hg", "bookmark", "-r", "default", "master", cwd=hg_repo_dir)
self._do("hg", "gexport", cwd=hg_repo_dir)
class SilentWSGIRequestHandler(wsgiref.simple_server.WSGIRequestHandler):
"""WSGIRequestHandler that doesn't print to stderr for each request."""
def log_message(self, format, *args):
pass
class GitHttpBackend(object):
"""Run git-http-backend in a backend thread.
This helper class lets us run the git-http-backend server in a background
thread, bound to a local tcp port. The main thread can then interact
with it as needed.
"""
def __init__(self, git_dir):
self.git_dir = os.path.abspath(git_dir)
self.git_project_root = os.path.dirname(self.git_dir)
self.git_project_name = os.path.basename(self.git_dir)
self.server = None
self.server_url = None
self.repo_url = None
def __call__(self, environ, start_response):
cgienv = os.environ.copy()
for (k,v) in environ.iteritems():
if isinstance(v, str):
cgienv[k] = v
cgienv["GIT_PROJECT_ROOT"] = self.git_project_root
cgienv["GIT_HTTP_EXPORT_ALL"] = "ON"
cgienv["REMOTE_USER"] = "rfk"
cmd = ("git", "http-backend", )
p = subprocess.Popen(cmd, env=cgienv, cwd=self.git_dir,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
if environ.get("CONTENT_LENGTH",None):
data = environ["wsgi.input"].read(int(environ["CONTENT_LENGTH"]))
p.stdin.write(data)
p.stdin.close()
headers = []
header = p.stdout.readline()
while header.strip():
headers.append(header.split(":", 1))
header = p.stdout.readline()
headers = [(k.strip(), v.strip()) for (k,v) in headers]
start_response("200 OK", headers)
return [p.stdout.read()]
def _make_server(self, addr, port):
make = wsgiref.simple_server.make_server
return make(addr, port, self, handler_class=SilentWSGIRequestHandler)
def run(self):
port = 8091
while True:
try:
self.server = self._make_server("localhost", port)
break
except socket.error:
port += 1
self.server_url = "http://localhost:%d/" % (port,)
self.repo_url = self.server_url + self.git_project_name
self.server.serve_forever()
def start(self):
t = threading.Thread(target=self.run)
t.start()
return t
def stop(self):
self.server.shutdown()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(1)
@@ -0,0 +1,61 @@
#
# This is the git-remote-hg setuptools script.
# Originally developed by Ryan Kelly, 2011.
#
# This script is placed in the public domain.
#
from setuptools import setup
# Extract the docstring and version declaration from the module.
# To avoid errors due to missing dependencies or bad python versions,
# we explicitly read the file contents up to the end of the version
# delcaration, then exec it ourselves.
info = {}
src = open("git_remote_hg/__init__.py")
lines = []
for ln in src:
lines.append(ln)
if "__version__" in ln:
for ln in src:
if "__version__" not in ln:
break
lines.append(ln)
break
exec("".join(lines),info)
NAME = "git-remote-hg"
VERSION = info["__version__"]
DESCRIPTION = "access hg repositories as git remotes"
LONG_DESC = info["__doc__"]
AUTHOR = "Ryan Kelly"
AUTHOR_EMAIL = "ryan@rfk.id.au"
URL="http://packages.python.org/git-remote-hg"
LICENSE = "MIT"
KEYWORDS = "git hg mercurial"
CLASSIFIERS = [
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved",
"License :: OSI Approved :: MIT License",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
]
setup(name=NAME,
version=VERSION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
url=URL,
description=DESCRIPTION,
long_description=LONG_DESC,
license=LICENSE,
keywords=KEYWORDS,
packages=["git_remote_hg"],
classifiers=CLASSIFIERS
)

0 comments on commit f709995

Please sign in to comment.