summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGauvain Pocentek <gauvain.pocentek@objectif-libre.com>2015-05-11 18:26:13 +0200
committerGauvain Pocentek <gauvain.pocentek@objectif-libre.com>2015-05-11 18:26:13 +0200
commit82a88a714e3cf932798c15879fda0a7d6d7047f1 (patch)
tree8b38dd9ffa9881835001813b939155c563bf9949
parent99cc43a9bb6038d3f1c9fe4976d938232b4c8207 (diff)
downloadgitlab-82a88a714e3cf932798c15879fda0a7d6d7047f1.tar.gz
Add a tox configuration file
Run pep8 tests only for now, and fix pep8 errors.
-rwxr-xr-xgitlab111
-rw-r--r--gitlab.py69
-rw-r--r--tox.ini25
3 files changed, 127 insertions, 78 deletions
diff --git a/gitlab b/gitlab
index e12e255..5e4d44a 100755
--- a/gitlab
+++ b/gitlab
@@ -16,18 +16,21 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-from __future__ import print_function, division, absolute_import
+from __future__ import print_function
+from __future__ import division
+from __future__ import absolute_import
import argparse
+from inspect import getmro
import os
-import sys
import re
-import gitlab
-from inspect import getmro
+import sys
try:
from ConfigParser import ConfigParser
-except:
+except ImportError:
from configparser import ConfigParser
+import gitlab
+
camel_re = re.compile('(.)([A-Z])')
LIST = 'list'
GET = 'get'
@@ -44,12 +47,10 @@ EXTRA_ACTION = [PROTECT, UNPROTECT, SEARCH, OWNED, ALL]
extra_actions = {
gitlab.ProjectBranch: {PROTECT: {'requiredAttrs': ['id', 'project-id']},
- UNPROTECT: {'requiredAttrs': ['id', 'project-id']}
- },
+ UNPROTECT: {'requiredAttrs': ['id', 'project-id']}},
gitlab.Project: {SEARCH: {'requiredAttrs': ['query']},
OWNED: {'requiredAttrs': []},
- ALL: {'requiredAttrs': []}
- },
+ ALL: {'requiredAttrs': []}},
}
@@ -77,36 +78,51 @@ def populate_sub_parser_by_class(cls, sub_parser):
attr = 'can' + action_name.capitalize()
try:
y = cls.__dict__[attr]
- except:
+ except AttributeError:
y = gitlab.GitlabObject.__dict__[attr]
if not y:
continue
sub_parser_action = sub_parser_class.add_parser(action_name)
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=True) for x in cls.requiredUrlAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=True)
+ for x in cls.requiredUrlAttrs]
+
if action_name == LIST:
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=True) for x in cls.requiredListAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=True)
+ for x in cls.requiredListAttrs]
sub_parser_action.add_argument("--page", required=False)
sub_parser_action.add_argument("--per-page", required=False)
+
elif action_name in [GET, DELETE]:
if cls not in [gitlab.CurrentUser]:
sub_parser_action.add_argument("--id", required=True)
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=True) for x in cls.requiredGetAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=True)
+ for x in cls.requiredGetAttrs]
+
elif action_name == CREATE:
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=True) for x in
- cls.requiredCreateAttrs]
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=False) for x in
- cls.optionalCreateAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=True)
+ for x in cls.requiredCreateAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=False)
+ for x in cls.optionalCreateAttrs]
+
elif action_name == UPDATE:
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=True) for x in
- cls.requiredCreateAttrs]
- [sub_parser_action.add_argument("--%s" % x.replace('_', '-'), required=False) for x in
- cls.optionalCreateAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=True)
+ for x in cls.requiredCreateAttrs]
+ [sub_parser_action.add_argument("--%s" % x.replace('_', '-'),
+ required=False)
+ for x in cls.optionalCreateAttrs]
if cls in extra_actions:
for action_name in sorted(extra_actions[cls]):
sub_parser_action = sub_parser_class.add_parser(action_name)
d = extra_actions[cls][action_name]
- [sub_parser_action.add_argument("--%s" % arg, required=True) for arg in d['requiredAttrs']]
+ [sub_parser_action.add_argument("--%s" % arg, required=True)
+ for arg in d['requiredAttrs']]
def do_auth():
@@ -115,14 +131,14 @@ def do_auth():
ssl_verify=ssl_verify, timeout=timeout)
gl.auth()
return gl
- except:
- die("Could not connect to GitLab (%s)" % gitlab_url)
+ except Exception as e:
+ die("Could not connect to GitLab %s (%s)" % (gitlab_url, str(e)))
def get_id():
try:
id = d.pop('id')
- except:
+ except Exception:
die("Missing --id argument")
return id
@@ -219,34 +235,42 @@ def do_project_owned():
if __name__ == "__main__":
ssl_verify = True
timeout = 60
- parser = argparse.ArgumentParser(description='Useful GitLab Command Line Interface')
- parser.add_argument("-v", "--verbosity", "--fancy", help="increase output verbosity", action="store_true")
+ parser = argparse.ArgumentParser(
+ description='GitLab API Command Line Interface')
+ parser.add_argument("-v", "--verbosity", "--fancy",
+ help="increase output verbosity",
+ action="store_true")
parser.add_argument("--gitlab", metavar='gitlab',
- help="Specifies which python-gitlab.cfg configuration section should be used. "
- "If not defined, the default selection will be used.", required=False)
+ help=("Specifies which python-gitlab.cfg "
+ "configuration section should be used. "
+ "If not defined, the default selection "
+ "will be used."),
+ required=False)
subparsers = parser.add_subparsers(
dest='what',
title="positional argument",
description='GitLab object',
help='GitLab object'
)
- #populate argparse for all Gitlab Object
+
+ # populate argparse for all Gitlab Object
for cls in gitlab.__dict__.values():
try:
if gitlab.GitlabObject in getmro(cls):
sub_parser = subparsers.add_parser(clsToWhat(cls))
populate_sub_parser_by_class(cls, sub_parser)
- except:
+ except Exception:
pass
arg = parser.parse_args()
d = arg.__dict__
+
# read the config
config = ConfigParser()
config.read(['/etc/python-gitlab.cfg',
os.path.expanduser('~/.python-gitlab.cfg')])
gitlab_id = arg.gitlab
- #conflicts with "gitlab" attribute with GitlabObject class
+ # conflicts with "gitlab" attribute from GitlabObject class
d.pop("gitlab")
verbose = arg.verbosity
action = arg.action
@@ -255,38 +279,39 @@ if __name__ == "__main__":
if gitlab_id is None:
try:
gitlab_id = config.get('global', 'default')
- except:
- die("Impossible to get the gitlab id (not specified in config file)")
+ except Exception:
+ die("Impossible to get the gitlab id "
+ "(not specified in config file)")
try:
gitlab_url = config.get(gitlab_id, 'url')
gitlab_token = config.get(gitlab_id, 'private_token')
- except:
- die("Impossible to get gitlab informations from configuration (%s)" %
- gitlab_id)
+ except Exception:
+ die("Impossible to get gitlab informations from configuration "
+ "(%s)" % gitlab_id)
try:
ssl_verify = config.getboolean('global', 'ssl_verify')
- except:
+ except Exception:
pass
try:
ssl_verify = config.getboolean(gitlab_id, 'ssl_verify')
- except:
+ except Exception:
pass
try:
timeout = config.getint('global', 'timeout')
- except:
+ except Exception:
pass
try:
timeout = config.getint(gitlab_id, 'timeout')
- except:
+ except Exception:
pass
cls = None
try:
cls = gitlab.__dict__[whatToCls(what)]
- except:
+ except Exception:
die("Unknown object: %s" % what)
gl = do_auth()
@@ -335,4 +360,4 @@ if __name__ == "__main__":
die("Unknown action: %s. Use \"gitlab -h %s\" to get details." %
(action, what))
- sys.exit(0) \ No newline at end of file
+ sys.exit(0)
diff --git a/gitlab.py b/gitlab.py
index ca94aa0..9625ac8 100644
--- a/gitlab.py
+++ b/gitlab.py
@@ -15,15 +15,15 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" Module for interfacing with GitLab-api """
-from __future__ import print_function, division, absolute_import
-
-import six
-
+from __future__ import print_function
+from __future__ import division
+from __future__ import absolute_import
+from itertools import chain
import json
-import requests
import sys
-from itertools import chain
+import requests
+import six
__title__ = 'python-gitlab'
__version__ = '0.8.1'
@@ -102,10 +102,10 @@ class GitlabTransferProjectError(GitlabOperationError):
def _raiseErrorFromResponse(response, error):
- """ Tries to parse gitlab error message from response and raises error.
+ """Tries to parse gitlab error message from response and raises error.
If response status code is 401, raises instead GitlabAuthenticationError.
-
+
response: requests response object
error: Error-class to raise. Should be inherited from GitLabError
"""
@@ -124,8 +124,8 @@ def _raiseErrorFromResponse(response, error):
class Gitlab(object):
- """ Represents a GitLab server connection
-
+ """Represents a GitLab server connection
+
Args:
url (str): the URL of the Gitlab server
private_token (str): the user private token
@@ -153,8 +153,9 @@ class Gitlab(object):
self.ssl_verify = ssl_verify
def auth(self):
- """Performs an authentication using either the private token, or the
- email/password pair.
+ """Performs an authentication.
+
+ Uses either the private token, or the email/password pair.
The user attribute will hold a CurrentUser object on success.
"""
@@ -193,7 +194,7 @@ class Gitlab(object):
url = '%s%s' % (self._url, url)
return url
- def _createHeaders(self, content_type=None, headers={} ):
+ def _createHeaders(self, content_type=None, headers={}):
request_headers = self.headers.copy()
request_headers.update(headers)
if content_type is not None:
@@ -223,7 +224,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -235,7 +236,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -248,7 +249,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -262,7 +263,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -289,7 +290,7 @@ class Gitlab(object):
r = requests.get(url, params=params, headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -309,11 +310,11 @@ class Gitlab(object):
if key in cls_kwargs:
del cls_kwargs[key]
- return [cls(self, item, **cls_kwargs) for item in r.json() if item is not None]
+ return [cls(self, item, **cls_kwargs) for item in r.json()
+ if item is not None]
else:
_raiseErrorFromResponse(r, GitlabListError)
-
def get(self, obj_class, id=None, **kwargs):
missing = []
for k in chain(obj_class.requiredUrlAttrs,
@@ -336,7 +337,7 @@ class Gitlab(object):
try:
r = requests.get(url, params=params, headers=headers,
verify=self.ssl_verify, timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -345,7 +346,6 @@ class Gitlab(object):
else:
_raiseErrorFromResponse(r, GitlabGetError)
-
def delete(self, obj, **kwargs):
params = obj.__dict__.copy()
params.update(kwargs)
@@ -371,7 +371,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -402,7 +402,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -432,7 +432,7 @@ class Gitlab(object):
headers=headers,
verify=self.ssl_verify,
timeout=self.timeout)
- except:
+ except Exception:
raise GitlabConnectionError(
"Can't connect to GitLab server (%s)" % self._url)
@@ -510,7 +510,7 @@ class Gitlab(object):
returns the matching group (or raises a GitlabGetError if not
found).
id: If id is a dict, creates a new object using attributes
- provided. The object is NOT saved on the server. Use the
+ provided. The object is NOT saved on the server. Use the
save() method on the object to write it on the server.
kwargs: Arbitrary keyword arguments
"""
@@ -568,7 +568,7 @@ def _sanitize_dict(src):
class GitlabObject(object):
- """ Baseclass for all classes that interface with GitLab
+ """Base class for all classes that interface with GitLab
Args:
gl (gitlab.Gitlab): GitLab server connection
@@ -614,13 +614,12 @@ class GitlabObject(object):
for attribute in chain(self.requiredCreateAttrs,
self.optionalCreateAttrs):
if hasattr(self, attribute):
- data[attribute] = getattr(self,attribute)
+ data[attribute] = getattr(self, attribute)
data.update(extra_parameters)
return json.dumps(data)
-
@classmethod
def list(cls, gl, **kwargs):
if not cls.canList:
@@ -708,7 +707,6 @@ class GitlabObject(object):
if not hasattr(self, "id"):
self.id = None
-
def __str__(self):
return '%s => %s' % (type(self), str(self.__dict__))
@@ -786,7 +784,6 @@ class User(GitlabObject):
'projects_limit', 'extern_uid', 'provider',
'bio', 'admin', 'can_create_group', 'website_url']
-
def Key(self, id=None, **kwargs):
return UserKey._getListOrObject(self.gitlab, id,
user_id=self.id,
@@ -811,6 +808,7 @@ class CurrentUser(GitlabObject):
def Key(self, id=None, **kwargs):
return CurrentUserKey._getListOrObject(self.gitlab, id, **kwargs)
+
class GroupMember(GitlabObject):
_url = '/groups/%(group_id)s/members'
canGet = False
@@ -844,6 +842,7 @@ class Group(GitlabObject):
if r.status_code != 201:
_raiseErrorFromResponse(r, GitlabTransferProjectError)
+
class Hook(GitlabObject):
_url = '/hooks'
canUpdate = False
@@ -907,7 +906,6 @@ class ProjectCommit(GitlabObject):
else:
_raiseErrorFromResponse(r, GitlabGetError)
-
def blob(self, filepath, **kwargs):
url = '/projects/%(project_id)s/repository/blobs/%(commit_id)s' % \
{'project_id': self.project_id, 'commit_id': self.id}
@@ -971,7 +969,8 @@ class ProjectIssue(GitlabObject):
# Gitlab-api returns labels in a json list and takes them in a
# comma separated list.
if hasattr(self, "labels"):
- if self.labels is not None and not isinstance(self.labels, six.string_types):
+ if (self.labels is not None and
+ not isinstance(self.labels, six.string_types)):
labels = ", ".join(self.labels)
extra_parameters['labels'] = labels
@@ -1227,8 +1226,8 @@ class Project(GitlabObject):
_raiseErrorFromResponse(r, GitlabGetError)
def create_file(self, path, branch, content, message, **kwargs):
- """ Creates file in project repository
-
+ """Creates file in project repository
+
Args:
path (str): Full path to new file
branch (str): The name of branch
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..d93f8e5
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,25 @@
+[tox]
+minversion = 1.6
+skipsdist = True
+envlist = pep8
+
+[testenv]
+setenv = VIRTUAL_ENV={envdir}
+usedevelop = True
+install_command = pip install {opts} {packages}
+
+deps = -r{toxinidir}/requirements.txt
+ -r{toxinidir}/test-requirements.txt
+commands =
+ python setup.py testr --testr-args='{posargs}'
+
+[testenv:pep8]
+commands =
+ flake8 {posargs} gitlab gitlab.py
+
+[testenv:venv]
+commands = {posargs}
+
+[flake8]
+exclude = .git,.venv,.tox,dist,doc,*egg,build,
+ignore = H501