From 93369b0a7c9f69c307e92f444346f309799006c7 Mon Sep 17 00:00:00 2001 From: vtemian Date: Mon, 14 Jul 2014 20:21:24 +0300 Subject: [PATCH] Cleanup a little bit the code --- pygit2/__init__.py | 14 ++++++++++---- pygit2/config.py | 43 +++++++++++++++++++++++++------------------ pygit2/credentials.py | 4 +++- pygit2/errors.py | 8 +++----- pygit2/ffi.py | 2 ++ pygit2/index.py | 39 ++++++++++++++++++++++++--------------- pygit2/refspec.py | 10 +++++++--- pygit2/remote.py | 32 +++++++++++++++++++++----------- pygit2/repository.py | 11 +++-------- pygit2/settings.py | 2 ++ 10 files changed, 100 insertions(+), 65 deletions(-) diff --git a/pygit2/__init__.py b/pygit2/__init__.py index aab855b02..4e0b0e2ec 100644 --- a/pygit2/__init__.py +++ b/pygit2/__init__.py @@ -42,6 +42,7 @@ 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 diff --git a/pygit2/config.py b/pygit2/config.py index a757b9713..eb626ec44 100644 --- a/pygit2/config.py +++ b/pygit2/config.py @@ -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 @@ def __next__(self): 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 @@ def __setitem__(self, key, value): 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 @@ def get_multivar(self, name, regex=None): """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 @@ def get_multivar(self, name, regex=None): 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 @@ def get_bool(self, key): 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 @@ def add_file(self, path, level=0, force=0): 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 @@ def snapshot(self): """ 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 @@ def snapshot(self): @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 diff --git a/pygit2/credentials.py b/pygit2/credentials.py index 9f060e2df..e4fd7f12b 100644 --- a/pygit2/credentials.py +++ b/pygit2/credentials.py @@ -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 @@ def credential_tuple(self): def __call__(self, _url, _username, _allowed): return self + class Keypair(object): """SSH key pair credentials diff --git a/pygit2/errors.py b/pygit2/errors.py index 398d08c72..6187bd5bf 100644 --- a/pygit2/errors.py +++ b/pygit2/errors.py @@ -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) - diff --git a/pygit2/ffi.py b/pygit2/ffi.py index 98de11c2a..2a7526674 100644 --- a/pygit2/ffi.py +++ b/pygit2/ffi.py @@ -65,6 +65,7 @@ def is_string(s): 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 diff --git a/pygit2/index.py b/pygit2/index.py index b8ee165fe..227957b13 100644 --- a/pygit2/index.py +++ b/pygit2/index.py @@ -31,7 +31,8 @@ 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 @@ def __init__(self, path=None): @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 @@ def __getitem__(self, key): raise KeyError(key) return IndexEntry._from_c(centry) - + def __iter__(self): return IndexIterator(self) @@ -96,10 +97,11 @@ def read(self, force=True): """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 @@ def write_tree(self, repo=None): check_error(err) return Oid(raw=bytes(ffi.buffer(coid)[:])) - def remove(self, path): """Remove an entry from the Index. """ @@ -170,12 +171,13 @@ def remove(self, path): 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 @@ def add(self, path_or_entry): 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 @@ def diff_to_workdir(self, flags=0, context_lines=3, interhunk_lines=0): 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 @@ def diff_to_tree(self, tree, flags=0, context_lines=3, interhunk_lines=0): 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 @@ def diff_to_tree(self, tree, flags=0, context_lines=3, interhunk_lines=0): 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 @@ def conflicts(self): return self._conflicts + class IndexEntry(object): __slots__ = ['id', 'path', 'mode', '_index'] @@ -350,6 +355,7 @@ def _from_c(cls, centry): return entry + class IndexIterator(object): def __init__(self, index): @@ -369,6 +375,7 @@ def __next__(self): return entry + class ConflictCollection(object): def __init__(self, index): @@ -379,7 +386,8 @@ def __getitem__(self, path): 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 @@ def __delitem__(self, path): def __iter__(self): return ConflictIterator(self._index) + class ConflictIterator(object): def __init__(self, index): diff --git a/pygit2/refspec.py b/pygit2/refspec.py index 5a99d5231..b0ee36016 100644 --- a/pygit2/refspec.py +++ b/pygit2/refspec.py @@ -31,6 +31,7 @@ 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 @@ def src_matches(self, ref): 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 @@ def _transform(self, ref, fn): 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) diff --git a/pygit2/remote.py b/pygit2/remote.py index 2b7f32d79..daa1e2d29 100644 --- a/pygit2/remote.py +++ b/pygit2/remote.py @@ -34,6 +34,7 @@ from .errors import check_error, GitError from .refspec import Refspec + def maybe_string(ptr): if not ptr: return None @@ -67,6 +68,7 @@ def __init__(self, tp): 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 @@ def url(self): @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 @@ def add_fetch(self, spec): 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 @@ def push(self, spec, signature=None, message=None): 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 @@ def push(self, spec, signature=None, message=None): 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 @@ def _sideband_progress_cb(string, length, data): 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 @@ def _update_tips_cb(refname, a, b, data): 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 @@ def _credentials_cb(cred_out, url, username, allowed, data): 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") diff --git a/pygit2/repository.py b/pygit2/repository.py index 70acbe7f6..ae6b48802 100644 --- a/pygit2/repository.py +++ b/pygit2/repository.py @@ -30,7 +30,6 @@ # 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 .config import Config from .index import Index + class Repository(_Repository): def __init__(self, *args, **kwargs): @@ -59,21 +59,18 @@ def get(self, key, default=None): 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 @@ def create_remote(self, name, url): 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 @@ def remotes(self): finally: C.git_strarray_free(names) - # # Configuration # @@ -255,7 +252,6 @@ def checkout(self, refname=None, **kwargs): """ - # Case 1: Checkout index if refname is None: return self.checkout_index(**kwargs) @@ -276,7 +272,6 @@ def checkout(self, refname=None, **kwargs): self.checkout_tree(treeish, **kwargs) self.head = refname - # # Diff # diff --git a/pygit2/settings.py b/pygit2/settings.py index b5805637b..88b69710b 100644 --- a/pygit2/settings.py +++ b/pygit2/settings.py @@ -29,6 +29,7 @@ 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 @@ def __getitem__(self, key): def __setitem__(self, key, value): option(GIT_OPT_SET_SEARCH_PATH, key, value) + class Settings(object): """Library-wide settings"""