Cleanup a little bit the code

This commit is contained in:
vtemian
2014-07-14 20:21:24 +03:00
parent 763b571c84
commit 93369b0a7c
10 changed files with 100 additions and 65 deletions

View File

@@ -42,6 +42,7 @@ from .index import Index, IndexEntry
from .errors import check_error
from .ffi import ffi, C, to_str
def init_repository(path, bare=False,
flags=C.GIT_REPOSITORY_INIT_MKPATH,
mode=0,
@@ -98,7 +99,9 @@ def init_repository(path, bare=False,
return Repository(path)
@ffi.callback('int (*credentials)(git_cred **cred, const char *url, const char *username_from_url, unsigned int allowed_types, void *data)')
@ffi.callback('int (*credentials)(git_cred **cred, const char *url,'
'const char *username_from_url, unsigned int allowed_types,'
'void *data)')
def _credentials_cb(cred_out, url, username_from_url, allowed, data):
d = ffi.from_handle(data)
@@ -111,6 +114,7 @@ def _credentials_cb(cred_out, url, username_from_url, allowed, data):
return 0
def clone_repository(
url, path, bare=False, ignore_cert_errors=False,
remote_name="origin", checkout_branch=None, credentials=None):
@@ -174,6 +178,7 @@ def clone_repository(
return Repository(path)
def clone_into(repo, remote, branch=None):
"""Clone into an empty repository from the specified remote
@@ -186,11 +191,12 @@ def clone_into(repo, remote, branch=None):
This allows you specify arbitrary repository and remote configurations
before performing the clone step itself. E.g. you can replicate git-clone's
'--mirror' option by setting a refspec of '+refs/*:refs/*', 'core.mirror' to true
and calling this function.
'--mirror' option by setting a refspec of '+refs/*:refs/*', 'core.mirror'
to true and calling this function.
"""
err = C.git_clone_into(repo._repo, remote._remote, ffi.NULL, to_str(branch), ffi.NULL)
err = C.git_clone_into(repo._repo, remote._remote, ffi.NULL,
to_str(branch), ffi.NULL)
if remote._stored_exception:
raise remote._stored_exception

View File

@@ -28,16 +28,15 @@
# Import from the future
from __future__ import absolute_import, unicode_literals
from _pygit2 import Oid
from .ffi import ffi, C, to_str, is_string
from .errors import check_error, GitError
from .refspec import Refspec
from .errors import check_error
def assert_string(v, desc):
if not is_string(v):
raise TypeError("%s must be a string" % desc)
class ConfigIterator(object):
def __init__(self, config, ptr):
@@ -67,12 +66,14 @@ class ConfigIterator(object):
return name, value
class ConfigMultivarIterator(ConfigIterator):
def __next__(self):
entry = self._next_entry()
return ffi.string(entry.value).decode('utf-8')
class Config(object):
"""Git configuration management"""
@@ -140,7 +141,8 @@ class Config(object):
elif isinstance(value, int):
err = C.git_config_set_int64(self._config, to_str(key), value)
else:
err = C.git_config_set_string(self._config, to_str(key), to_str(value))
err = C.git_config_set_string(self._config, to_str(key),
to_str(value))
check_error(err)
@@ -161,13 +163,14 @@ class Config(object):
"""get_multivar(name[, regex]) -> [str, ...]
Get each value of a multivar ''name'' as a list. The optional ''regex''
parameter is expected to be a regular expression to filter the variables
we're interested in."""
parameter is expected to be a regular expression to filter the
variables we're interested in."""
assert_string(name, "name")
citer = ffi.new('git_config_iterator **')
err = C.git_config_multivar_iterator_new(citer, self._config, to_str(name), to_str(regex))
err = C.git_config_multivar_iterator_new(citer, self._config,
to_str(name), to_str(regex))
check_error(err)
return ConfigMultivarIterator(self, citer[0])
@@ -175,20 +178,22 @@ class Config(object):
def set_multivar(self, name, regex, value):
"""set_multivar(name, regex, value)
Set a multivar ''name'' to ''value''. ''regexp'' is a regular expression
to indicate which values to replace"""
Set a multivar ''name'' to ''value''. ''regexp'' is a regular
expression to indicate which values to replace"""
assert_string(name, "name")
assert_string(regex, "regex")
assert_string(value, "value")
err = C.git_config_set_multivar(self._config, to_str(name), to_str(regex), to_str(value))
err = C.git_config_set_multivar(self._config, to_str(name),
to_str(regex), to_str(value))
check_error(err)
def get_bool(self, key):
"""get_bool(key) -> Bool
Look up *key* and parse its value as a boolean as per the git-config rules
Look up *key* and parse its value as a boolean as per the git-config
rules
Truthy values are: 'true', 1, 'on' or 'yes'. Falsy values are: 'false',
0, 'off' and 'no'"""
@@ -203,10 +208,11 @@ class Config(object):
def get_int(self, key):
"""get_int(key) -> int
Look up *key* and parse its value as an integer as per the git-config rules.
Look up *key* and parse its value as an integer as per the git-config
rules.
A value can have a suffix 'k', 'm' or 'g' which stand for 'kilo', 'mega' and
'giga' respectively"""
A value can have a suffix 'k', 'm' or 'g' which stand for 'kilo',
'mega' and 'giga' respectively"""
val = self._get_string(key)
res = ffi.new('int64_t *')
@@ -220,7 +226,8 @@ class Config(object):
Add a config file instance to an existing config."""
err = C.git_config_add_file_ondisk(self._config, to_str(path), level, force)
err = C.git_config_add_file_ondisk(self._config, to_str(path), level,
force)
check_error(err)
def snapshot(self):
@@ -231,7 +238,7 @@ class Config(object):
"""
ccfg = ffi.new('git_config **')
err = C.git_config_snapshot(cfg, self._config)
err = C.git_config_snapshot(ccfg, self._config)
check_error(err)
return Config.from_c(self._repo, ccfg[0])
@@ -243,7 +250,7 @@ class Config(object):
@staticmethod
def parse_bool(text):
res = ffi.new('int *')
err = C.git_config_parse_bool(res, to_str(text))
C.git_config_parse_bool(res, to_str(text))
return res[0] != 0

View File

@@ -25,11 +25,12 @@
# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
from .ffi import ffi, C
from .ffi import C
GIT_CREDTYPE_USERPASS_PLAINTEXT = C.GIT_CREDTYPE_USERPASS_PLAINTEXT
GIT_CREDTYPE_SSH_KEY = C.GIT_CREDTYPE_SSH_KEY
class UserPass(object):
"""Username/Password credentials
@@ -53,6 +54,7 @@ class UserPass(object):
def __call__(self, _url, _username, _allowed):
return self
class Keypair(object):
"""SSH key pair credentials

View File

@@ -25,14 +25,12 @@
# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
# Import from the Standard Library
from string import hexdigits
# ffi
from .ffi import ffi, C
from _pygit2 import GitError
def check_error(err, io=False):
if err >= 0:
return
@@ -42,7 +40,8 @@ def check_error(err, io=False):
if giterr != ffi.NULL:
message = ffi.string(giterr.message).decode()
if err in [C.GIT_EEXISTS, C.GIT_EINVALIDSPEC, C.GIT_EEXISTS, C.GIT_EAMBIGUOUS]:
if err in [C.GIT_EEXISTS, C.GIT_EINVALIDSPEC, C.GIT_EEXISTS,
C.GIT_EAMBIGUOUS]:
raise ValueError(message)
elif err == C.GIT_ENOTFOUND:
if io:
@@ -55,4 +54,3 @@ def check_error(err, io=False):
raise StopIteration()
raise GitError(message)

View File

@@ -65,6 +65,7 @@ else:
ffi = FFI()
def strarray_to_strings(arr):
l = [None] * arr.count
for i in range(arr.count):
@@ -72,6 +73,7 @@ def strarray_to_strings(arr):
return l
def strings_to_strarray(l):
"""Convert a list of strings to a git_strarray

View File

@@ -31,7 +31,8 @@ from __future__ import absolute_import, unicode_literals
from _pygit2 import Oid, Tree, Diff
from .ffi import ffi, C, to_str, is_string, strings_to_strarray
from .errors import check_error, GitError
from .errors import check_error
class Index(object):
@@ -50,7 +51,7 @@ class Index(object):
@classmethod
def from_c(cls, repo, ptr):
index = cls.__new__(cls);
index = cls.__new__(cls)
index._repo = repo
index._index = ptr[0]
index._cindex = ptr
@@ -88,7 +89,7 @@ class Index(object):
raise KeyError(key)
return IndexEntry._from_c(centry)
def __iter__(self):
return IndexIterator(self)
@@ -96,10 +97,11 @@ class Index(object):
"""Update the contents the Index
Update the contents by reading from a file
Arguments:
force: if True (the default) allways reload. If False, only if the file has changed
force: if True (the default) allways reload. If False, only if
the file has changed
"""
err = C.git_index_read(self._index, force)
@@ -160,7 +162,6 @@ class Index(object):
check_error(err)
return Oid(raw=bytes(ffi.buffer(coid)[:]))
def remove(self, path):
"""Remove an entry from the Index.
"""
@@ -170,12 +171,13 @@ class Index(object):
def add_all(self, pathspecs=[]):
"""Add or update index entries matching files in the working directory.
If pathspecs are specified, only files matching those pathspecs will be added.
If pathspecs are specified, only files matching those pathspecs will
be added.
"""
arr, refs = strings_to_strarray(pathspecs)
err = C.git_index_add_all(self._index, arr, 0, ffi.NULL, ffi.NULL)
check_error(err, True)
def add(self, path_or_entry):
"""add([path|entry])
@@ -185,8 +187,8 @@ class Index(object):
relative to the root of the worktree and the Index must be associated
with a repository.
If an IndexEntry is given, that entry will be added or update in the Index
without checking for the existence of the path or id.
If an IndexEntry is given, that entry will be added or update in the
Index without checking for the existence of the path or id.
"""
if is_string(path_or_entry):
@@ -237,7 +239,8 @@ class Index(object):
copts.interhunk_lines = interhunk_lines
cdiff = ffi.new('git_diff **')
err = C.git_diff_index_to_workdir(cdiff, self._repo._repo, self._index, copts)
err = C.git_diff_index_to_workdir(cdiff, self._repo._repo,
self._index, copts)
check_error(err)
return Diff.from_c(bytes(ffi.buffer(cdiff)[:]), self._repo)
@@ -247,8 +250,8 @@ class Index(object):
Diff the index against a tree
Return a :py:class:`~pygit2.Diff` object with the differences between the
index and the given tree.
Return a :py:class:`~pygit2.Diff` object with the differences between
the index and the given tree.
Arguments:
@@ -281,7 +284,8 @@ class Index(object):
ffi.buffer(ctree)[:] = tree._pointer[:]
cdiff = ffi.new('git_diff **')
err = C.git_diff_tree_to_index(cdiff, self._repo._repo, ctree[0], self._index, copts)
err = C.git_diff_tree_to_index(cdiff, self._repo._repo, ctree[0],
self._index, copts)
check_error(err)
return Diff.from_c(bytes(ffi.buffer(cdiff)[:]), self._repo)
@@ -307,6 +311,7 @@ class Index(object):
return self._conflicts
class IndexEntry(object):
__slots__ = ['id', 'path', 'mode', '_index']
@@ -350,6 +355,7 @@ class IndexEntry(object):
return entry
class IndexIterator(object):
def __init__(self, index):
@@ -369,6 +375,7 @@ class IndexIterator(object):
return entry
class ConflictCollection(object):
def __init__(self, index):
@@ -379,7 +386,8 @@ class ConflictCollection(object):
cours = ffi.new('git_index_entry **')
ctheirs = ffi.new('git_index_entry **')
err = C.git_index_conflict_get(cancestor, cours, ctheirs, self._index._index, to_str(path))
err = C.git_index_conflict_get(cancestor, cours, ctheirs,
self._index._index, to_str(path))
check_error(err)
ancestor = IndexEntry._from_c(cancestor[0])
@@ -395,6 +403,7 @@ class ConflictCollection(object):
def __iter__(self):
return ConflictIterator(self._index)
class ConflictIterator(object):
def __init__(self, index):

View File

@@ -31,6 +31,7 @@ from __future__ import absolute_import
from .ffi import ffi, C, to_str
from .errors import check_error
class Refspec(object):
def __init__(self, owner, ptr):
self._owner = owner
@@ -70,7 +71,8 @@ class Refspec(object):
def dst_matches(self, ref):
"""dst_matches(str) -> Bool
Returns whether the given string matches the destination of this refspec"""
Returns whether the given string matches the destination of this
refspec"""
return bool(C.git_refspec_dst_matches(self._refspec, to_str(ref)))
def _transform(self, ref, fn):
@@ -86,11 +88,13 @@ class Refspec(object):
def transform(self, ref):
"""transform(str) -> str
Transform a reference name according to this refspec from the lhs to the rhs."""
Transform a reference name according to this refspec from the lhs to
the rhs."""
return self._transform(ref, C.git_refspec_transform)
def rtransform(self, ref):
"""transform(str) -> str
Transform a reference name according to this refspec from the lhs to the rhs"""
Transform a reference name according to this refspec from the lhs
to the rhs"""
return self._transform(ref, C.git_refspec_rtransform)

View File

@@ -34,6 +34,7 @@ from .ffi import ffi, C, to_str, strarray_to_strings, strings_to_strarray
from .errors import check_error, GitError
from .refspec import Refspec
def maybe_string(ptr):
if not ptr:
return None
@@ -67,6 +68,7 @@ class TransferProgress(object):
self.received_bytes = tp.received_bytes
""""Number of bytes received up to now"""
class Remote(object):
def sideband_progress(self, string):
@@ -169,7 +171,7 @@ class Remote(object):
@url.setter
def url(self, value):
err = C.git_remote_set_url(self._remote, to_str(value))
C.git_remote_set_url(self._remote, to_str(value))
@property
def push_url(self):
@@ -261,14 +263,14 @@ class Remote(object):
Add a fetch refspec to the remote"""
err = C.git_remote_add_fetch(self._remote, to_str(spec))
C.git_remote_add_fetch(self._remote, to_str(spec))
def add_push(self, spec):
"""add_push(refspec)
Add a push refspec to the remote"""
err = C.git_remote_add_push(self._remote, to_str(spec))
C.git_remote_add_push(self._remote, to_str(spec))
@ffi.callback("int (*cb)(const char *ref, const char *msg, void *data)")
def _push_cb(ref, msg, data):
@@ -303,7 +305,8 @@ class Remote(object):
if not C.git_push_unpack_ok(push):
raise GitError("remote failed to unpack objects")
err = C.git_push_status_foreach(push, self._push_cb, ffi.new_handle(self))
err = C.git_push_status_foreach(push, self._push_cb,
ffi.new_handle(self))
check_error(err)
if hasattr(self, '_bad_message'):
@@ -327,7 +330,8 @@ class Remote(object):
def _transfer_progress_cb(stats_ptr, data):
self = ffi.from_handle(data)
if not hasattr(self, 'transfer_progress') or not self.transfer_progress:
if not hasattr(self, 'transfer_progress') \
or not self.transfer_progress:
return 0
try:
@@ -354,7 +358,8 @@ class Remote(object):
return 0
@ffi.callback('int (*update_tips)(const char *refname, const git_oid *a, const git_oid *b, void *data)')
@ffi.callback('int (*update_tips)(const char *refname, const git_oid *a,'
'const git_oid *b, void *data)')
def _update_tips_cb(refname, a, b, data):
self = ffi.from_handle(data)
@@ -373,7 +378,9 @@ class Remote(object):
return 0
@ffi.callback('int (*credentials)(git_cred **cred, const char *url, const char *username_from_url, unsigned int allowed_types, void *data)')
@ffi.callback('int (*credentials)(git_cred **cred, const char *url,'
'const char *username_from_url, unsigned int allowed_types,'
'void *data)')
def _credentials_cb(cred_out, url, username, allowed, data):
self = ffi.from_handle(data)
@@ -390,6 +397,7 @@ class Remote(object):
return 0
def get_credentials(fn, url, username, allowed):
"""Call fn and return the credentials object"""
@@ -398,7 +406,8 @@ def get_credentials(fn, url, username, allowed):
creds = fn(url_str, username_str, allowed)
if not hasattr(creds, 'credential_type') or not hasattr(creds, 'credential_tuple'):
if not hasattr(creds, 'credential_type') \
or not hasattr(creds, 'credential_tuple'):
raise TypeError("credential does not implement interface")
cred_type = creds.credential_type
@@ -409,12 +418,13 @@ def get_credentials(fn, url, username, allowed):
ccred = ffi.new('git_cred **')
if cred_type == C.GIT_CREDTYPE_USERPASS_PLAINTEXT:
name, passwd = creds.credential_tuple
err = C.git_cred_userpass_plaintext_new(ccred, to_str(name), to_str(passwd))
err = C.git_cred_userpass_plaintext_new(ccred, to_str(name),
to_str(passwd))
elif cred_type == C.GIT_CREDTYPE_SSH_KEY:
name, pubkey, privkey, passphrase = creds.credential_tuple
err = C.git_cred_ssh_key_new(ccred, to_str(name),to_str(pubkey),
to_str(privkey), to_str(passphrase))
err = C.git_cred_ssh_key_new(ccred, to_str(name), to_str(pubkey),
to_str(privkey), to_str(passphrase))
else:
raise TypeError("unsupported credential type")

View File

@@ -30,7 +30,6 @@ from string import hexdigits
# Import from pygit2
from _pygit2 import Repository as _Repository
from _pygit2 import GIT_BRANCH_LOCAL, GIT_BRANCH_REMOTE
from _pygit2 import Oid, GIT_OID_HEXSZ, GIT_OID_MINPREFIXLEN
from _pygit2 import GIT_CHECKOUT_SAFE_CREATE, GIT_DIFF_NORMAL
from _pygit2 import Reference, Tree, Commit, Blob
@@ -41,6 +40,7 @@ from .remote import Remote
from .config import Config
from .index import Index
class Repository(_Repository):
def __init__(self, *args, **kwargs):
@@ -59,21 +59,18 @@ class Repository(_Repository):
value = self.git_object_lookup_prefix(key)
return value if (value is not None) else default
def __getitem__(self, key):
value = self.git_object_lookup_prefix(key)
if value is None:
raise KeyError(key)
return value
def __contains__(self, key):
return self.git_object_lookup_prefix(key) is not None
def __repr__(self):
return "pygit2.Repository(%r)" % self.path
#
# Remotes
#
@@ -85,7 +82,8 @@ class Repository(_Repository):
cremote = ffi.new('git_remote **')
err = C.git_remote_create(cremote, self._repo, to_str(name), to_str(url))
err = C.git_remote_create(cremote, self._repo, to_str(name),
to_str(url))
check_error(err)
return Remote(self, cremote[0])
@@ -111,7 +109,6 @@ class Repository(_Repository):
finally:
C.git_strarray_free(names)
#
# Configuration
#
@@ -255,7 +252,6 @@ class Repository(_Repository):
"""
# Case 1: Checkout index
if refname is None:
return self.checkout_index(**kwargs)
@@ -276,7 +272,6 @@ class Repository(_Repository):
self.checkout_tree(treeish, **kwargs)
self.head = refname
#
# Diff
#

View File

@@ -29,6 +29,7 @@ from _pygit2 import option
from _pygit2 import GIT_OPT_GET_SEARCH_PATH, GIT_OPT_SET_SEARCH_PATH
from _pygit2 import GIT_OPT_GET_MWINDOW_SIZE, GIT_OPT_SET_MWINDOW_SIZE
class SearchPathList(object):
def __getitem__(self, key):
@@ -37,6 +38,7 @@ class SearchPathList(object):
def __setitem__(self, key, value):
option(GIT_OPT_SET_SEARCH_PATH, key, value)
class Settings(object):
"""Library-wide settings"""