GithubHelp home page GithubHelp logo

python-gitlab / python-gitlab Goto Github PK

View Code? Open in Web Editor NEW
2.2K 51.0 639.0 5.23 MB

A python wrapper for the GitLab API.

Home Page: https://python-gitlab.readthedocs.io

License: GNU Lesser General Public License v3.0

Python 99.72% Dockerfile 0.05% Ruby 0.22%
python gitlab api hacktoberfest gitlab-api gitlab-ci gitlab-cli

python-gitlab's Introduction

python-gitlab

image

image

image

image

image

image

image

image

python-gitlab is a Python package providing access to the GitLab server API.

It supports the v4 API of GitLab, and provides a CLI tool (gitlab).

Features

python-gitlab enables you to:

  • write Pythonic code to manage your GitLab resources.
  • pass arbitrary parameters to the GitLab API. Simply follow GitLab's docs on what parameters are available.
  • access arbitrary endpoints as soon as they are available on GitLab, by using lower-level API methods.
  • use persistent requests sessions for authentication, proxy and certificate handling.
  • handle smart retries on network and server errors, with rate-limit handling.
  • flexible handling of paginated responses, including lazy iterators.
  • automatically URL-encode paths and parameters where needed.
  • automatically convert some complex data structures to API attribute types
  • merge configuration from config files, environment variables and arguments.

Installation

As of 4.0.0, python-gitlab is compatible with Python 3.8+.

Use pip to install the latest stable version of python-gitlab:

$ pip install --upgrade python-gitlab

The current development version is available on both GitHub.com and GitLab.com, and can be installed directly from the git repository:

$ pip install git+https://github.com/python-gitlab/python-gitlab.git

From GitLab:

$ pip install git+https://gitlab.com/python-gitlab/python-gitlab.git

Using the docker images

python-gitlab provides Docker images in two flavors, based on the Alpine and Debian slim python base images. The default tag is alpine, but you can explicitly use the alias (see below).

The alpine image is smaller, but you may want to use the Debian-based slim tag (currently based on -slim-bullseye) if you are running into issues or need a more complete environment with a bash shell, such as in CI jobs.

The images are published on the GitLab registry, for example:

  • registry.gitlab.com/python-gitlab/python-gitlab:latest (latest, alpine alias)
  • registry.gitlab.com/python-gitlab/python-gitlab:alpine (latest alpine)
  • registry.gitlab.com/python-gitlab/python-gitlab:slim-bullseye (latest slim-bullseye)
  • registry.gitlab.com/python-gitlab/python-gitlab:v3.2.0 (alpine alias)
  • registry.gitlab.com/python-gitlab/python-gitlab:v3.2.0-alpine
  • registry.gitlab.com/python-gitlab/python-gitlab:v3.2.0-slim-bullseye

You can run the Docker image directly from the GitLab registry:

$ docker run -it --rm registry.gitlab.com/python-gitlab/python-gitlab:latest <command> ...

For example, to get a project on GitLab.com (without authentication):

$ docker run -it --rm registry.gitlab.com/python-gitlab/python-gitlab:latest project get --id gitlab-org/gitlab

You can also mount your own config file:

$ docker run -it --rm -v /path/to/python-gitlab.cfg:/etc/python-gitlab.cfg registry.gitlab.com/python-gitlab/python-gitlab:latest <command> ...

Usage inside GitLab CI

If you want to use the Docker image directly inside your GitLab CI as an image, you will need to override the entrypoint, as noted in the official GitLab documentation:

Job Name:
   image:
      name: registry.gitlab.com/python-gitlab/python-gitlab:latest
      entrypoint: [""]
   before_script:
      gitlab --version
   script:
      gitlab <command>

Building the image

To build your own image from this repository, run:

$ docker build -t python-gitlab:latest .

Run your own image:

$ docker run -it --rm python-gitlab:latest <command> ...

Build a Debian slim-based image:

$ docker build -t python-gitlab:latest --build-arg PYTHON_FLAVOR=slim-bullseye .

Bug reports

Please report bugs and feature requests at https://github.com/python-gitlab/python-gitlab/issues.

Gitter Community Chat

We have a gitter community chat available at https://gitter.im/python-gitlab/Lobby, which you can also directly access via the Open Chat button below.

If you have a simple question, the community might be able to help already, without you opening an issue. If you regularly use python-gitlab, we also encourage you to join and participate. You might discover new ideas and use cases yourself!

Documentation

The full documentation for CLI and API is available on readthedocs.

Build the docs

We use tox to manage our environment and build the documentation:

pip install tox
tox -e docs

Contributing

For guidelines for contributing to python-gitlab, refer to CONTRIBUTING.rst.

python-gitlab's People

Contributors

actions-user avatar benjamb avatar bufferoverflow avatar esabouraud avatar gpocentek avatar jacobhenner avatar johnvillalovos avatar jouve avatar kkoralsky avatar klorenz avatar lmilbaum avatar massimone88 avatar max-wittig avatar mitar avatar mjmaenpaa avatar mlq avatar nejch avatar nickbroon avatar ppaques avatar psycojoker avatar renovate-bot avatar renovate[bot] avatar rhansen avatar robinson96 avatar sathieu avatar spyoungtech avatar srikanthchelluri avatar tardyp avatar timknight-dwp avatar valentingregoire avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-gitlab's Issues

UnicodeEncodeError in verbose mode

Hi,
when using the verbose mode, I always get an UnicodeEncoreError. My OS is Windows 7 French edition ...
Best regards, Fred

python python-gitlab.py project-issue get --project-id=1 --id=118 -v


id: 118
assignee: None
author:
  id: 6
  created-at: 2013-07-22T04:51:44Z
  email: ******
  name: ******
  state: active
  username: mohierf
created-at: 2013-08-27T12:51:52Z
Traceback (most recent call last):
  File "python-gitlab.py", line 319, in <module> o.display(verbose)
  File "C:\gitIPM\Win7Kiosks-Operating\maintenance\content\gitlab\gitlab.py", line 503, in display
    self.pretty_print()
  File "C:\gitIPM\Win7Kiosks-Operating\maintenance\content\gitlab\gitlab.py", line 543, in pretty_print
    v = GitlabObject._obj_to_str(v)
  File "C:\gitIPM\Win7Kiosks-Operating\maintenance\content\gitlab\gitlab.py", line 524, in _obj_to_str
    return str(obj)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 45: ordinal not in range(128)

Modify a group member

Hi Gauvain,

Thank you for this great module. I like it because it follows the philosophy / coding style of Python (compared to pyapi-python) .

I have a little quesiton:

I tried to modify a group member:

for member in group.Member(all=True):
    if member.id == 12:
        member.access_level = 50
        member.save()

But it raised an exception that says "the function is not implemented".

Is there a way to modify a group member with the current version of python-gitlab?

Cheers,
Asher

PS: I remember you. You contributed few years ago with a Debian package for one of my free softwares 'Jargon Informatique' ;-) . Le monde est petit !

Problem connecting to gitlab

I'm using:
gitlab 6.3
ssl self-signed certificate

>>> gl = Gitlab('https://gitlab.XXXX.YYY.br', 'XXXXXXX', ssl_verify=False)
>>> gl.auth()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "gitlab.py", line 100, in auth
    self.token_auth()
  File "gitlab.py", line 118, in token_auth
    self.user = CurrentUser(self)
  File "gitlab.py", line 527, in __init__
    data = self.gitlab.get(self.__class__, data, **kwargs)
  File "gitlab.py", line 236, in get
    return r.json()
TypeError: 'dict' object is not callable

And if I try eith ssl_verify=True I get this:

....
gitlab.GitlabConnectionError: Can't connect to GitLab server (https://gitlab.XXXX.YYY.br/api/v3)

Create UserKey: NotImplemented

I wonder what the purpose of setting UserKey object's canGet attribute to False is? It had prevented me from creating the new key for user. I commented this string out and the key has created successfully.

Bug: list Gitlab users

Hi,

When there is more than one pages in the users list, the function git.Group() doesn't return all users.

To get all users, i need to do git.Group(1) and git.Group(2). It could be better of the main function returns all users automatically.

Cheers,
Asher256

Error when calling Gitlab object

I have an error when I try to initialize Gitlab object

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gitlab
>>> gl=Gitlab('http://gitlab.domain/gitlab','admin_token')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Gitlab' is not defined

I am working with :
GitLab 6.5.1
Debian 7
Python 2.7.3
python-requests 2.0.0 (Wheezy backports package)
python-gitlab (installed with pip)

Add sudo support

sudo is more or less supported in the package (although it's not explicit), but it should be usable with the CLI.

Updating existing merge request labels not working

I am attempting to update an existing merge request's labels by removing one and adding another. After connecting to the Gitlab server, I am trying the following:

for p in gl.Project():
    if (p.id == json_project):
        for mr in p.MergeRequest():
            if (mr.id == json_mr):
                final_labels = []
                for label in mr.labels:
                    if (label not in attribs['remove']):
                        final_labels.append(label)
                for label in attribs['add']:
                    final_labels.append(u'%s' % (label))
                gl_mr.labels = final_labels
                gl_mr.save()

I am getting the error: GitlabUpdateError: 400: Source branch cannot be changed

Is this the proper way to update an existing merge request or am I doing something wrong?

Generate read the docs documentation

I starting using this API a few days ago but have found myself digging through the code to learn how to do more exotic functions such as automatically create a branch in an existing gitlab repo. As I go through the code, I would love to create documentation based on my learning experience.

Error Gitlab auth() : Object doesn't exist

Hello
Now, I can't auth :

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gitlab
>>> gl=gitlab.Gitlab('http://gitlab.domain','admin_token')
>>> gl
<gitlab.Gitlab object at 0x1e91310>
>>> gl.auth()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 100, in auth
    self.token_auth()
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 118, in token_auth
    self.user = CurrentUser(self)
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 541, in __init__
    data = self.gitlab.get(self.__class__, data, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 244, in get
    raise GitlabGetError("Object doesn't exist")
gitlab.GitlabGetError: Object doesn't exist

Iteration of results

I'm using GitLab CE 7.12.2, and trying to list users via the API. I have 162 users. After connecting to GitLab using python-gitlab 0.9.2 from PyPi (my connection is self.conn), self.conn.User() returns a list with 20 items, a fraction of my users.

The GitLab API documentation says that it paginates responses with a default of 20 results per response.

It appears that python-gitlab is ignoring the pagination. The only use of the "page" response attribute that I see in the source code is on line 341 where it's deleted before passing to the constructor.

Could you please either implement pagination of responses so python-gitlab doesn't silently ignore results, or at least mention in the docs that this is happening?

Thanks.

Support for pagination?

all_projects() returns only the first page of results.

The GitLab API documentation says to use the next/pref links in there, and that at most 100 results are returned per page.

Is pagination to obtain all results supported - otherwise, methods like 'all_projects' would be useless.

can_create_group reversed when creating user

Hello

It seems that can_create_group is reversed. If can_create_group is True, the user can not create group :)

# python
Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gitlab
>>> gl = gitlab.Gitlab("http://gitlab.domain/gitlab","admin_token")
>>> gl.auth()
>>> u=gl.User({"username": "john", "email": "[email protected]", "name": "John", "password": "toto12345", "projects_limit": 10, "admin": False, "can_create_group": False})
>>> u.save()
>>> print u.can_create_group
True
>>> j=gl.User({"username": "john1", "email": "[email protected]", "name": "John1", "password": "toto12345", "projects_limit": 10, "admin": False, "can_create_group": True})
>>> j.save()
>>> print j.can_create_group
None

Official API vs python-gitlab api

The naming is somewhat inconsistent. This makes it difficult to read the official api and then use the console interface. I do not know if this affects the programmatic api.

Documentation:

Gets a user team project.

GET /user_teams/:id/projects/:project_id
Parameters:

id (required) - The ID of a user_team
project_id (required) - The ID of a user

API:

team-project get --id=ARG1 --team-id=ARG2
# id = the ID of a project
# team_id = the ID of a user_team

Should preferably be rewritten as:

team-project get --id=ARG2 --project-id=ARG1
# id = the ID of a user_team
# project_id = the ID of a project

Currently the use of --id appears to be hard-coded in the design. I'm not sure what would be the best way to change this.

User() does not list all users

Hello

I am trying to list my gitlab users. So I do :

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gitlab
>>> gl = gitlab.Gitlab('http://gitlab.domain/gitlab',"admin_token")
>>> gl.auth()
>>> for u in gl.User():
...     print u.username

But, this only list the 20 first users. Is there a way to bypass this limit ?
Thanks

GitLab 6.9.2
GitLab Shell 1.9.4
GitLab API v3
Ruby 2.1.2p95
Rails 4.0.5

Gitlab.from_config not present

Hi
the following statement

gl = gitlab.Gitlab.from_config('somewhere', ['xxxxx'])

refers to a method not present in python-gitlab 0.9.2, that is the version that my pip download (i am using python 2.7)

Is it correct? shoud i usa some different method or other?

Thanks

Please implement getting project by namespace/name

Currently gitlab cli supports 'project get' by project id only, while Gitlab API supports getting specific project also by namespace/project_name

"Get a specific project, identified by project ID or NAMESPACE/PROJECT_NAME, which is owned by the authenticated user. If using namespaced projects call make sure that the NAMESPACE/PROJECT_NAME is URL-encoded, eg. /api/v3/projects/diaspora%2Fdiaspora (where / is represented by %2F)."

In this way user can get project ID knowing only it's name and reuse this ID later (to add milestone or issue etc.)

Currently I have to store project ID's somewhere to use them with CLI.

I could also try to use "project search" or parse output from "project list" command but it's overcomplicated.

requests module

Hi,

when i do : python setup.py install and i use the build result (build/scripts-2.7/gitlab) i have this kind of error :

Traceback (most recent call last):
File "/usr/local/bin/gitlab", line 30, in
import gitlab
File "/Library/Python/2.7/site-packages/gitlab.py", line 20, in
import requests
ImportError: No module named requests

did i miss something ?

Why not use an option parser?

Is there a reason you're rolling your own option parsing rather than using the well tested optparse or argparse? This regards the gitlab CLI utility.

"Impossible to destroy object" 405 when attempting to delete project branch

When attempting to delete a project branch using the CLI I an receiving a 405 response from Gitlab:

$ gitlab project-branch list --project-id=n
name: api

name: master

$ gitlab project-branch delete --project-id=n --name api
Impossible to destroy object (405: )

Using gitlab's webUI to delete the branch is successful.

Failed request to Gitlab from CLI:

10.1.8.30 - - [24/Aug/2015:10:37:00 -0500] "DELETE //api/v3/projects/n/repository/branches?name=api&gitlab=%3Cgitlab.Gitlab+object+at+0x7f897dcdbb90%3E&protected=False&commit=%3Cclass+%27gitlab.ProjectCommit%27%3E+%3D%3E+%7Bu%27committer_email%27%3A+u%27amiller%40stuff.com%27%2C+u%27author_email%27%3A+u%27amiller%stuff.com%27%2C+u%27authored_date%27%3A+u%272015-08-24T10%3A09%3A09.000-05%3A00%27%2C+%27gitlab%27%3A+%3Cgitlab.Gitlab+object+at+0x7f897dcdbb90%3E%2C+u%27author_name%27%3A+u%27Aaron+Miller%27%2C+u%27parent_ids%27%3A+%5B%5D%2C+u%27committed_date%27%3A+u%272015-08-24T10%3A09%3A09.000-05%3A00%27%2C+%27_created%27%3A+False%2C+u%27message%27%3A+u%27first+commit%5Cn%27%2C+u%27committer_name%27%3A+u%27Aaron+Miller%27%2C+u%27id%27%3A+u%27c463222b71c7b3289761062dbdc638fa8fb36f17%27%7D&action=delete&_created=True HTTP/1.1" 405 5 "-" "python-requests/2.5.3 CPython/2.7.6 Linux/3.16.0-38-generic"

Successful request from webUI:

10.1.8.30 - - [24/Aug/2015:10:19:02 -0500] "DELETE /amiller/gl-api-test/branches/api_branch HTTP/1.1" 200 48 "https://gitlabhost/amiller/gl-api-test/branches" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36"

Module version = 0.9.2
Gitlab version = 7.7.1_omnibus.5.4.1.ci

'Gitlab' object has no attribute 'projects'

I installed python-gitlab with pip and was able to connect to with my private token and print my user information successfully, but when I try and generate a list of projects from gl.projects.list() I get an AttributeError: 'Gitlab' object has no attribute 'projects'.

gl still seems to have Group, Hook, Issue, Project, Team etc.

I tried for both root and non-root users. Thanks for the help.

Could not connect to GitLab

Hi,

My Gitlab version is GitLab 7.0.0 de9bf7d, I have installed the python-gitlab, but it can not connect to GitLab:

gitlab user list
Could not connect to GitLab (https://mydomain/api/v3)

I can capture the request from the Gitlab server with tcpdump.
How can I know the reason?

Thanks in advance.

How do I install this?

I'm not a python user - I just want a CLI. Apparently this offers one, but I have no idea how to install this system. Some instructions would be useful!

admin does not work when creating user

Hello again

I think I have found an other bug, sorry ;)

When creating user, the "admin" parameters does not work :

>>> u=gl.User({"username": "john", "email": "[email protected]", "name": "John", "password": "toto12345", "projects_limit": 10, "admin": True, "can_create_group": True})
>>> u.save()
>>> print u.admin
True
>>> print u
<class 'gitlab.User'> => {u'can_create_project': True, u'twitter': None, u'linkedin': None, u'color_scheme_id': 1, u'skype': None, u'id': 55, 'projects_limit': 10, u'state': u'active', u'provider': None, u'extern_uid': None, 'email': u'[email protected]', u'website_url': None, 'username': u'john', u'bio': None, 'can_create_group': None, u'is_admin': None, 'password': 'toto12345', 'name': u'John', 'admin': True, u'created_at': u'2014-02-21T12:54:02.098+01:00', 'gitlab': <gitlab.Gitlab object at 0x7f10014f0310>, u'theme_id': 2}

Here we see that "is_admin" value is None.

enable client certificates / two-way SSL

would like the module/CLI to work in environments that validate client certificates and have their own certificate authority certs published for server cert validation on the client side (2-way SSL).

i'm happy to submit a PR on this but wanted to create an issue to track in case someone else has already looked at it. basically you just need to accept a string (and potentially convert to boolean for backward compat) for the ssl_verify attribute of the GitLab class which would pass the path of a CA cert list in PEM encoding to the requests module (as the verify parameter, as well as a certs parameter for requests which packs two values: the client cert and matching private key (both PEM encoded, unencrypted in the case of the private key).

Improve documentation for 0.11

Unable to replace File -> files:

I've got this code, which works:

        p = self.projects.get(id=project_id)
        f = p.File(file_path=file_path, ref=ref)

After upgrade to 0.11 getting DepricationWarnings, so replacing it with...

(Pdb++) p.files.get()
*** TypeError: get() takes exactly 2 arguments (1 given)

(Pdb++) p.files.get(project_id=project_id, file_path=file_path, ref=ref)
*** TypeError: get() takes exactly 2 arguments (1 given)

(Pdb++) p.files.get({'project_id':project_id, 'file_path':file_path, 'ref': ref})
<gitlab.objects.ProjectFile object at 0x919b2b0>

(Pdb++) p.files.get({'project_id': 1, 'ref': 'master', 'file_path': 'requirements.txt'}).get()
*** TypeError: get() takes exactly 3 arguments (1 given)

And I'm stuck. Same thing with creating new issue comments.

Could you please add more documentation on how to properly move, since it seems syntax changes more dramatically than with Project -> projects, Issue -> issues.

Error 404 creating user

Hello
I have an error when I try to create a user

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gitlab
>>> gl = gitlab.Gitlab('http://gitlab.domain/gitlab',"admin_token")
>>> gl.auth()
>>> u = gl.User({'email': '[email protected]', 'password': 'toto', 'username': 'toto', 'name': 'Toto Titi'})
>>> u.save()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 526, in save
    self._create()
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 512, in _create
    json = self.gitlab.create(self)
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 293, in create
    raise GitlabCreateError('%d: %s' % (r.status_code, r.text))
gitlab.GitlabCreateError: 404: {"message":"404 Not Found"}

Thanks ;)

usage example is broken

It seems that the sample usage script is broken.

First it does not include the "import gitlab", and even if you import it you will get an error that auth() is not a member of Gitlab class.

import gitlab
gl = gitlab.Gitlab('https://gitlab.example.com', '.....')
gl.auth()

a dir(gl) returns:

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'acceptmergerequest', 'addcommenttomergerequest', 'adddeploykey', 'addgroupmember', 'addprojecthook', 'addprojectmember', 'addsshkey', 'addsshkeyuser', 'addsystemhook', 'api_url', 'compare_branches_tags_commits', 'createbranch', 'createfile', 'createfork', 'createforkrelation', 'creategroup', 'createissue', 'createissuewallnote', 'createlabel', 'createmergerequest', 'createmergerequestewallnote', 'createmilestone', 'createproject', 'createprojectuser', 'createrepositorytag', 'createsnippet', 'createsnippetewallnote', 'createuser', 'currentuser', 'deletebranch', 'deletedeploykey', 'deletefile', 'deletegitlabciservice', 'deletegroup', 'deletegroupmember', 'deletelabel', 'deleteproject', 'deleteprojecthook', 'deleteprojectmember', 'deletesnippet', 'deletesshkey', 'deletesystemhook', 'deleteuser', 'editissue', 'editlabel', 'editmilestone', 'editprojecthook', 'editprojectmember', 'edituser', 'getbranch', 'getbranches', 'getcontributors', 'getdeploykey', 'getdeploykeys', 'getfile', 'getfilearchive', 'getgroupmembers', 'getgroups', 'getissues', 'getissuewallnote', 'getissuewallnotes', 'getlabels', 'getmergerequest', 'getmergerequestcomments', 'getmergerequests', 'getmergerequestwallnote', 'getmergerequestwallnotes', 'getmilestone', 'getmilestones', 'getproject', 'getprojectevents', 'getprojecthook', 'getprojecthooks', 'getprojectissue', 'getprojectissues', 'getprojectmembers', 'getprojects', 'getprojectsall', 'getprojectsowned', 'getrawblob', 'getrawfile', 'getrepositories', 'getrepositorybranch', 'getrepositorycommit', 'getrepositorycommitdiff', 'getrepositorycommits', 'getrepositorytags', 'getrepositorytree', 'getsnippet', 'getsnippetcontent', 'getsnippets', 'getsnippetwallnote', 'getsnippetwallnotes', 'getsshkey', 'getsshkeys', 'getsystemhooks', 'getuser', 'getusers', 'groups_url', 'headers', 'hook_url', 'host', 'keys_url', 'login', 'moveproject', 'projects_url', 'protectbranch', 'protectrepositorybranch', 'removeforkrelation', 'search_url', 'searchproject', 'setgitlabciservice', 'setsudo', 'testsystemhook', 'token', 'unprotectbranch', 'unprotectrepositorybranch', 'updatefile', 'updatemergerequest', 'users_url', 'verify_ssl']

InsecureRequestWarning

I've been able to connect to gitlab using curl...

curl -s -H "PRIVATE-TOKEN: XXXXXX" -H 'Accept: application/json' -H 'Content-Type: application/json' https://git.domain.loc/api/v3
/home/gitmirror/gitlab-mirrors/add_mirror.sh --git --project-name puppet-staging --mirror https://github.com/nanliu/puppet-staging.git
Resolving gitlab remote.
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
Traceback (most recent call last):
  File "lib/manage_gitlab_project.py", line 109, in <module>
    found_project=createproject(project_name)
  File "lib/manage_gitlab_project.py", line 95, in createproject
    new_project=git.add_project(pname,description=description,**project_options)
  File "/usr/lib/python2.7/site-packages/gitlab3/__init__.py", line 184, in fn
    data = parent._post(api._uq_url, data=kwargs)
  File "/usr/lib/python2.7/site-packages/gitlab3/__init__.py", line 418, in _post
    return self._request(requests.post, api_url, addl_keys, data)
  File "/usr/lib/python2.7/site-packages/gitlab3/__init__.py", line 435, in _request
    self._check_status_code(r.status_code, url, data)
  File "/usr/lib/python2.7/site-packages/gitlab3/__init__.py", line 411, in _check_status_code
    raise self._code_to_exc[status_code](msg)
gitlab3.exceptions.MissingRequiredAttribute: URL: https://git.domain.loc/api/v3/projects, Data: {'wall_enabled': 'false', 'snippets_enabled': 'false', 'merge_requests_enabled': 'false', 'name': 'puppet-staging', 'issues_enabled': 'false', 'wiki_enabled': 'false', 'public': 'true', 'description': 'Mirror of https://github.com/nanliu/puppet-staging.git'}
There was an unknown issue with manage_gitlab_project.py

I've updated Python OpenSSL bindings as suggested:

pip install --upgrade requests[security]

But no luck...

samrocketman/gitlab-mirrors#88

Incorrect help text or parameter when using "project-member update"

Hi,

I wanted to update a project member and got an error using this:

vm-lm-deb64:~# gitlab project-member update --project-id=18 --user-id=2 --access-level=30
Missing --id argument

Solution: Use "--id" instead of "--user-id", though the help text suggests otherwise. It would be better to stay consistent with the other subcommands and change this "--user-id".

Block a user with the Gitlab API + python-gitlab

Hi Gauvain,

Is it possible to block a user with python-gitlab ?

This feature is already available in pyapi-gitlab:

    def blockuser(self, user_id, **kwargs):
        """Block a user.
        :param user_id: id of the user to change
        :param kwargs: Any param the the Gitlab API supports
        :return: Dict of the user
        """
        data = {}

        if kwargs:
            data.update(kwargs)

        request = requests.put("{0}/{1}/block".format(self.users_url, user_id),
                               headers=self.headers, data=data,
                               timeout=self.timeout,
                               verify=self.verify_ssl)
        if request.status_code == 200:
            return request.json()
        else:
            return False

Thank you.

Asher256

Error adding a project member

I'm trying to add a project member and this is the error I get (I'm assuming this is the way to do it...):

"p" is a valid project
"apz11" is a valid user

Question: if I'm doing the right way, how could I set the user access level?

In [51]: p.Member(apz11.id)
---------------------------------------------------------------------------
GitlabGetError                            Traceback (most recent call last)
/home/dpasqualin/<ipython-input-51-883ffbbcc9a9> in <module>()
----> 1 p.Member(apz11.id)

/usr/local/lib/python2.7/dist-packages/python_gitlab-0.5-py2.7.egg/gitlab.pyc in Member(self, id, **kwargs)
    968         return self._getListOrObject(ProjectMember, id,
    969                                      project_id=self.id,
--> 970                                      **kwargs)
    971 
    972     def MergeRequest(self, id=None, **kwargs):

/usr/local/lib/python2.7/dist-packages/python_gitlab-0.5-py2.7.egg/gitlab.pyc in _getListOrObject(self, cls, id, **kwargs)
    477             if not cls.canGet:
    478                 raise GitlabGetError
--> 479             return cls(self.gitlab, id, **kwargs)
    480 
    481     def _getObject(self, k, v):

/usr/local/lib/python2.7/dist-packages/python_gitlab-0.5-py2.7.egg/gitlab.pyc in __init__(self, gl, data, **kwargs)
    529 
    530         if data is None or isinstance(data, int) or isinstance(data, str):
--> 531             data = self.gitlab.get(self.__class__, data, **kwargs)
    532 
    533         self._setFromDict(data)

/usr/local/lib/python2.7/dist-packages/python_gitlab-0.5-py2.7.egg/gitlab.pyc in get(self, obj_class, id, **kwargs)
    242             raise GitlabAuthenticationError(r.json()['message'])
    243         elif r.status_code == 404:
--> 244             raise GitlabGetError("Object doesn't exist")
    245         else:
    246             raise GitlabGetError('%d: %s' % (r.status_code, r.text))

GitlabGetError: Object doesn't exist

Python GitLab - update 'Linked LDAP groups'

Hi :),

in Python GitLab, how can i update 'Linked LDAP groups' : LDAP Group cn, LDAP Access...

git = gitlab.Gitlab('http://gitlab..., email='..', password='.....')
git.auth()
dict = {
'name': 'TestGroup4',
'path': 'TestGroup4',
'ldap_group_links':[{'cn':'Cloud Management Tools','group_access':50,
'provider':'ldapmain'}]

        }

g = git.Group(dict)
g.save()

This warning will only appear once by default. InsecureRequestWarning

Dear all,

dong@dong-Ubuntu:~$ gitlab project list
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py:730: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html (This warning will only appear once by default.)
  InsecureRequestWarning)

It's showing every time. Anything I can do to turn it off?

Best,

Dong

Can't close an issue

The method to close an issue documented into the README file doesn't work :

    issue.closed = 1
    issue.save()

And I can't find a way to close an issue.

Error getting project commit

I get a weird error while trying to retrieve a single project commit. It turns out that the data I'm passing in is actually of the "unicode" type and not a string. I think you need a little better handling for unicode strings. This change on line 526 fixed the issue for me:

-        if data is None or isinstance(data, int) or isinstance(data, str):
+        if data is None or isinstance(data, int) or isinstance(data, str) or isinstance(data, unicode):

Not sure if there is a more general solution for this. I also was able to fix it once I tracked it down by converting my id data to a string before passing it to the API.

error when saving project

I tried to write a script to change a project's visibility level. After retrieving the project via 'all_projects()', I did:

p.visibility_level = 0  # Private
p.save()

However, this fails with

gitlab.GitlabCreateError: 400: {u'path': [u'has already been taken'], u'name': [u'has already been taken']}

What am I doing wrong?

cli error references unknown config entry

I have a config file:

cat ~/.python-gitlab.cfg
[global]
url=http://ca-ovsx32:8888
private_token=hmy-BNCwmRChRveoUsds

I tried listing the users:

[toby.ferguson@ca-ovsx32 ~]$ gitlab -v user list
Impossible to get the gitlab id (not specified in config file)

but what is the gitlab id? There's no mention of this keyword for the config file? I tried id, username & user_nameIndeed, there's no complete list of keywords :-(

How to create Issues via python-gitlab?

Hello,

i want to use python-gitlab to create issues, but could not figure how it works?

Two questions:

    1. Can this script create Issues?
    1. If yes, how can i create new Issues ? :)

Hope someone can help me out.

Documentation for further methods?

Hi, I've successfully used python-gitlab to pre-populate a local Gitlab install of several thousand staff and student users for our University (getting around the automatic email settings in Gitlab is a real headache!

I'm also pre-loading all of their academic modules and courses as Gitlab 'Groups', to which I'd like to add the students, so that on login, they're all already members of the 'Groups' containing the repositories for their individual modules of study.

However, I can't find any details on how to /add/ a member to a group - retrieving, yes, but not setting. What object do I need a new instance of before calling save() on it?

No support for Unicode in titles or description

I've been trying to add milestone with some Polish character "ล›".
gitlabcli returned:

Traceback (most recent call last):
  File "/usr/local/bin/gitlab", line 333, in <module>
    o.display(verbose)
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 556, in display
    self.short_print()
  File "/usr/local/lib/python2.7/dist-packages/gitlab.py", line 564, in short_print
    self.__dict__[self.shortPrintAttr]))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u015b' in position 11: ordinal not in range(128)

can't delete repo via gitlab command line

$ gitlab project list
id: 6
path: UBER

$ gitlab project delete --id 6
Traceback (most recent call last):
File "/usr/bin/gitlab", line 9, in
load_entry_point('python-gitlab==0.9', 'console_scripts', 'gitlab')()
File "/usr/lib/python2.7/dist-packages/gitlab/cli.py", line 340, in main
o = globals()['do_%s' % action.lower()](cls, gl, what, args)
File "/usr/lib/python2.7/dist-packages/gitlab/cli.py", line 185, in do_delete
o = do_get(cls, args)
TypeError: do_get() takes exactly 4 arguments (2 given)

can create:
$ gitlab project create --name FISH
id: 7
path: fish

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.