IGitt.GitLab package

Submodules

IGitt.GitLab.GitLab module

Contains the Hoster implementation for GitLab.

class IGitt.GitLab.GitLab.GitLab(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken])[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Hoster.Hoster

A high level interface to GitLab.

get_repo(repository) → IGitt.GitLab.GitLabRepository.GitLabRepository[source]

Retrieve a given repository.

>>> from os import environ
>>> GitLab = GitLab(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']))
>>> repo = source.get_repo('gitmate-test-user/test')
>>> isinstance(repo, GitLabRepository)
True
Returns:A repository object.
static get_repo_name(webhook: dict)[source]

Retrieves the repository name from given webhook data.

get_user(username: str = None) → IGitt.GitLab.GitLabUser.GitLabUser[source]

Retrieves repository name from given webhook data.

Parameters:username – Username to fetch, use None to fetch authenticated user.
Returns:The user.
handle_webhook(event: str, data: dict)[source]

Handles a GitLab webhook for you.

If it’s an issue event it returns e.g. IssueActions.OPENED, [GitLabIssue(...)], for comments it returns MergeRequestActions.COMMENTED, [GitLabMergeRequest(...), GitLabComment(...)], for updates it returns IssueActions.LABELED, [GitLabIssue(...), 'new label']

Parameters:
  • event – The HTTP_X_GITLAB_EVENT of the request header.
  • data – The pythonified JSON data of the request.
Yields:

An IssueActions or MergeRequestActions member and a list of the affected IGitt objects.

master_repositories

Retrieves repositories the user has admin access to.

owned_repositories

Retrieves repositories owned by the authenticated user.

>>> from os import environ
>>> GitLab = GitLab(GitLabOAuthToken(viron['GITLAB_TEST_TOKEN']))
>>> sorted(map(lambda x: x.full_name, GitLab.owned_repositories)
{'gitmate-test-user/test'}
Returns:A set of GitLabRepository objects.

GitLab doesn’t allow searching through raw queries.

write_repositories

Retrieves the full names of repositories this user can write to.

>>> from os import environ
>>> GitLab = GitLab(GitLabOAuthToken(viron['GITLAB_TEST_TOKEN']))
>>> sorted(map(lambda x: x.full_name, GitLab.write_repositories))
['gitmate-test-user/test', 'nkprince007/gitmate-test']
Returns:A set of GitLabRepository objects.

IGitt.GitLab.GitLabComment module

Represents a comment (or note) on GitLab.

class IGitt.GitLab.GitLabComment.GitLabComment(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: str, iid: str, comment_type: IGitt.Interfaces.Comment.CommentType, comment_id: int)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Comment.Comment

Represents a comment (or note as GitLab folks call it), with mainly a body and an author, which can ofcourse be deleted.

author

Retrieves the author of the comment.

>>> from os import environ
>>> note = GitLabComment(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                      'gitmate-test-user/test', 1,
...                      CommentType.ISSUE, 31500135)
>>> note.author.username
'gitmate-test-user'
Returns:A GitLabUser object.
body

Retrieves the content of the comment.

>>> from os import environ
>>> note = GitLabComment(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                      'gitmate-test-user/test', 1,
...                      CommentType.ISSUE, 31500135)
>>> note.body
'Lemme comment on you.\r\n'
Returns:A string containing the body.
created

Retrieves a timestamp on when the comment was created.

>>> from os import environ
>>> note = GitLabComment(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                      'gitmate-test-user/test', 1,
...                      CommentType.ISSUE, 31500135)
>>> note.created
datetime.datetime(2017, 6, 5, 5, 20, 28, 418000)
delete()[source]

Deletes the comment.

iid

Retrieves the internal identifier of the linked resource (issue/merge request/commit).

number

Retrieves the id of the comment.

repository

Returns the GitLab repository this comment was posted in, as a GitLabRepository instance.

type

Retrieves the type of comment it links to.

updated

Retrieves a timestamp on when the comment was updated the last time.

>>> from os import environ
>>> note = GitLabComment(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                      'gitmate-test-user/test', 1,
...                      CommentType.ISSUE, 31500135)
>>> note.updated
datetime.datetime(2017, 6, 5, 6, 5, 34, 491000)

IGitt.GitLab.GitLabCommit module

Contains the abstraction for a commit in GitLab.

class IGitt.GitLab.GitLabCommit.GitLabCommit(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: str, sha: Optional[str], branch: Optional[str] = None)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Commit.Commit

Represents a commit on GitLab.

closes_issues

Returns a set of GitLabIssue objects which would be closed upon merging this pull request.

combined_status

Retrieves a combined status of all the commits.

Returns:Status.FAILED if any of the commits report as error or failure or canceled Status.PENDING if there are no statuses or a commit is pending or a test is running Status.SUCCESS if the latest status for all commits is success
Raises:AssertionError – If the status couldn’t be matched with any of the possible outcomes Status.SUCCESS, Status.FAILED and Status.PENDING.
comment(message: str, file: Optional[str] = None, line: Optional[int] = None, mr_number: Optional[int] = None) → IGitt.GitLab.GitLabComment.GitLabComment[source]

Places a comment on the commit.

>>> from os import environ
>>> commit = GitLabCommit(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', '3fc4b86'
... )

So this line places a comment on the bottom of the commit, not associated to any particular piece of code:

>>> commit.comment("An issue is here!")

However, we can also comment on a particular file and line, if that is included in the diff:

>>> commit.comment("Here in line 4, there's a spelling mistake!",
...                'README.md', 4)

If you supply the pr_number argument, the comment will appear in the review UI of that pull request:

>>> commit.comment("Here in line 4, there's a spelling mistake!",
...                'README.md', 4, mr_number=7)

Beat that! Of course, there’s a lot of error handling. If you give the wrong file, the comment will appear below the commit with a note about the commit, file and line:

>>> commit.comment("Oh, this'll end up below!!", 'READMENOT.md', 4)

Also if the line isn’t contained in the diff GitLab won’t accept that and it’ll also end up below - sorry!

>>> commit.comment("Oh, this'll too end up below!!", 'README.md', 8)

If you give a pull request, the comment will appear on the PR instead:

>>> commit.comment("Oh, this'll too end up on the PR.",
...                'README.md', 8, mr_number=7)
Parameters:
  • message – The body of the comment.
  • file – The file to place the comment, relative to repo root.
  • line – The line in the file in the comment or None.
  • mr_number – The iid of a merge request if this should end up in the discussions UI of the merge request.
get_patch_for_file(filename: str)[source]

Retrieves the unified diff for the commit.

>>> from os import environ
>>> commit = GitLabCommit(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', '3fc4b86'
... )
>>> assert (commit.get_patch_for_file('README.md') ==
...         '--- a/README.md\n+++ b/README.md\n@@ -1,2 +1,4 @@\n '
...         '# test\n a test repo\n+\n+a tst pr\n')

But only if it exists!

>>> commit.get_patch_for_file('IDONTEXISTFILE')
Traceback (most recent call last):
 ...
IGitt.ElementDoesntExistError: The file does not exist.
Parameters:filename – The file to retrieve patch for.
Returns:A string containing the patch.
Raises:ElementDoesntExistError – If the given filename does not exist.
get_statuses() → Set[IGitt.Interfaces.CommitStatus.CommitStatus][source]

Retrieves the all commit statuses.

Returns:A (frozen)set of CommitStatus objects.
Raises:RuntimeError – If something goes wrong (network, auth…).
mentioned_issues

Returns a set of GitLabIssue objects which are related to the merge request.

message

Returns the commit message.

Returns:Commit message as string.
parent

Retrieves the parent commit. In case of a merge commit the first parent will be returned.

>>> from os import environ
>>> commit = GitLabCommit(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', '3fc4b86'
... )
>>> commit.parent.sha
'674498fd415cfadc35c5eb28b8951e800f357c6f'
Returns:A Commit object.
repository

Retrieves the repository that holds this commit.

>>> from os import environ
>>> commit = GitLabCommit(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', '3fc4b86'
... )
>>> commit.repository.full_name
'gitmate-test-user/test'
Returns:A usable Repository instance.
set_status(status: IGitt.Interfaces.CommitStatus.CommitStatus)[source]

Adds the given status to the commit.

>>> from os import environ
>>> commit = GitLabCommit(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', '3fc4b86'
... )
>>> status = CommitStatus(Status.FAILED, 'Theres a problem',
...                       'gitmate/test')
>>> commit.set_status(status)
>>> commit.get_statuses().pop().description
'Theres a problem'

If a status with the same context already exists, it will be bluntly overridden:

>>> status.status = Status.SUCCESS
>>> status.description = "Theres no problem"
>>> commit.set_status(status)
>>> len(commit.get_statuses())
1
>>> commit.get_statuses().pop().description
'Theres no problem'
Parameters:status – The CommitStatus to set to this commit.
Raises:RuntimeError – If something goes wrong (network, auth…).
sha

Retrieves the SHA of the commit:

>>> from os import environ
>>> commit = GitLabCommit(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', '674498'
... )
>>> commit.sha
'674498'
Returns:A string holding the SHA of the commit.
unified_diff

Retrieves the unified diff for the commit excluding the diff index.

will_close_issues

Returns a set of GitLabIssue objects which would be closed as stated in this commit message.

will_fix_issues

Returns a set of GitLabIssue objects which would be fixed as stated in this commit message.

will_resolve_issues

Returns a set of GitLabIssue objects which would be resolved as stated in this commit message.

IGitt.GitLab.GitLabContent module

This contains the Content implementation for GitLab.

class IGitt.GitLab.GitLabContent.GitLabContent(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: str, path: str)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Content.Content

This class represents a content on GitHub

delete(message: str, branch: Optional[str] = None)[source]

Deletes content

Parameters:
  • message – The commit message for the deletion commit.
  • branch – The branch to delete this content from. Defaults to master.
get_content(ref='master')[source]

Get content

update(message: str, content: str, branch: Optional[str] = None)[source]

Updates existing file in repository

IGitt.GitLab.GitLabIssue module

This contains the Issue implementation for GitLab.

class IGitt.GitLab.GitLabIssue.GitLabIssue(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: str, number: int)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Issue.Issue

This class represents an issue on GitLab.

add_comment(body)[source]

Adds a comment to the issue.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> comment = issue.add_comment("Doh!")

You can use the comment right after:

>>> comment.body
'Doh!'
>>> comment.delete()

The comment will be created by the user authenticated via the oauth token.

Parameters:body – The body of the new comment to create.
Returns:The newly created comment.
add_to_total_time_spent(relative_time_spent: datetime.timedelta)[source]

Adds the value of relative_time_spent to total_time_spent. Allows for positive and negative values. Allows any time unit of the timedelta object. Does nothing when passing None or 0.

assign(*usernames)[source]

Adds the user as one of the assignees of the issue. :param users: User objects of the users to be added as an assignee.

assignees

Retrieves the assignee of the issue:

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.assignees
{'gitmate-test-user'}
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 2)
>>> issue.assignees # Returns empty set, unassigned
{}
Returns:A set containing the usernames of assignees.
author

Retrieves the author of the issue.

Returns:A GitLabUser object.
available_assignees

Retrieves a set of available assignees for the issue.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> {a.username for a in issue.available_assignees}
{'gitmate-test-user'}
Returns:A set of GitLabUsers.
available_labels

Retrieves a set of captions that are available for labelling bugs.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> sorted(issue.available_labels)
['a', 'b', 'c']
Returns:A set of label captions (str).
close()[source]

Closes the issue.

Raises:RuntimeError – If something goes wrong (network, auth…).
comments

Retrieves comments from the issue.

As of now, the list of comments is not sorted. Related issue on GitLab CE here - https://gitlab.com/gitlab-org/gitlab-ce/issues/32057

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 3)
>>> comments = issue.comments
>>> for comment in comments:
...     print(comment.body)
Stop staring at me.
Go, get your work done.
Returns:A list of Comment objects.
static create(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: str, title: str, body: str = '', issue_type: Optional[str] = None)[source]

Create a new issue with given title and body.

>>> from os import environ
>>> issue = GitLabIssue.create(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test',
...     'test issue title',
...     'sample description'
... )
>>> issue.state
<IssueStates.OPEN: 'open'>

Delete the issue to avoid filling the test repo with issues.

>>> issue.delete()
Returns:GitLabIssue object of the newly created issue.
created

Retrieves a timestamp on when the issue was created.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 4)
>>> issue.created
datetime.datetime(2017, 6, 5, 9, 45, 20, 678000)
delete()[source]

Deletes the issue.

Raises:RuntimeError – If something goes wrong (network, auth…).
description

Retrieves the main description of the issue.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.description
'I am a serious issue. Fix me soon, dude.'
Returns:A string containing the main description of the issue.
labels

Retrieves all labels associated with this bug.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.labels
set()

Use the property setter to set the labels:

>>> issue.labels = {'a', 'b', 'c'}
>>> sorted(issue.labels)
['a', 'b', 'c']

Use the empty set intuitively to clear all labels:

>>> issue.labels = set()
Returns:A list of label captions (str).
milestone

Retrieves the milestone.

mrs_closed_by

Returns the merge requests that close this issue.

number

Returns the issue “number” or id.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.number
1
Returns:The number of the issue.
reactions

Retrieves the reactions / award emojis applied on the issue.

reopen()[source]

Reopens the issue.

Raises:RuntimeError – If something goes wrong (network, auth…).
repository

Returns the GitLab repository this issue is linked with as a GitLabRepository instance.

state

Get’s the state of the issue.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.state
<IssueStates.OPEN: 'open'>
>>> str(issue.state)
'open'

So if we close it:

>>> issue.close()
>>> issue.state
<IssueStates.CLOSED: 'closed'>
>>> str(issue.state)
'closed'

And reopen it:

>>> issue.reopen()
>>> issue.state
<IssueStates.OPEN: 'open'>

Note: GitLab Issues & Merge Requests API underwent a change to have only two states, <IssueStates.OPEN: ‘open’> or <IssueStates.CLOSED: ‘closed’>. No ‘reopened’ state anymore.

Returns:Either <IssueStates.OPEN: ‘open’> or <IssueStates.CLOSED: ‘closed’>.
time_estimate

Retrieves the time_estimate from the ‘time_estimate’ attribute in the GitLab Issue.

title

Retrieves the title of the issue.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.title
'Take it serious, son!'

You can simply set it using the property setter:

>>> issue.title = 'dont panic'
>>> issue.title
'dont panic'
>>> issue.title = 'Take it serious, son!'
Returns:The title of the issue - as string.
total_time_spent

Retrieves the time_estimate from the ‘total_time_spent’ attribute in the GitLab Issue.

unassign(*users)[source]

Removes the user from the assignees of the issue. :param users: User objects of the users to be unassigned.

updated

Retrieves a timestamp on when the issue was updated the last time.

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 4)
>>> issue.updated
datetime.datetime(2017, 6, 5, 9, 45, 56, 115000)
weight

Retrieves the weight associated with the current issue.

IGitt.GitLab.GitLabMergeRequest module

Contains a class representing the GitLab merge request.

class IGitt.GitLab.GitLabMergeRequest.GitLabMergeRequest(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: str, number: int)[source]

Bases: IGitt.GitLab.GitLabIssue.GitLabIssue, IGitt.Interfaces.MergeRequest.MergeRequest

A Merge Request on GitLab.

affected_files

Retrieves affected files from a GitLab merge request.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> pr.affected_files
{'README.md'}
Returns:A set of filenames.
assignees

Retrieves the assignee of the issue:

>>> from os import environ
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 1)
>>> issue.assignees
{'gitmate-test-user'}
>>> issue = GitLabIssue(GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...                     'gitmate-test-user/test', 2)
>>> issue.assignees # Returns empty set, unassigned
{}
Returns:A set containing the usernames of assignees.
author

Retrieves the author of the merge request.

Returns:A GitLabUser object.
base

Retrieves the base commit as a GitLabCommit object.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> pr.base.sha
'198dd16f8249ea98ed41876efe27d068b69fa215'
Returns:A GitLabCommit object.
base_branch_name

Retrieves the base branch name of the merge request, i.e. the one it should be merged into.

Returns:A string.
closes_issues

Returns a set of GitLabIssue objects which would be closed upon merging this pull request.

commits

Retrieves a tuple of commit objects that are included in the PR.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> assert ([commit.sha for commit in pr.commits] == [
...     '99f484ae167dcfcc35008ba3b5b564443d425ee0',
...     'bbd11b50412d34072f1889e4cea04a32de183605'])
Returns:A tuple of commit objects.
diffstat

Gets additions and deletions of a merge request.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> pr.diffstat
(2, 0)
Returns:An (additions, deletions) tuple.
head

Retrieves the head commit as a GitLabCommit object.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> pr.head.sha
'99f484ae167dcfcc35008ba3b5b564443d425ee0'
Returns:A GitLabCommit object.
head_branch_name

Retrieves the head branch name of the merge request, i.e. the one which should be merged.

Returns:A string.
mentioned_issues

Returns a set of GitLabIssue objects which are related to the merge request.

merge(message: str = None, sha: str = None, should_remove_source_branch: bool = False, _github_merge_method: str = None, _gitlab_merge_when_pipeline_succeeds: bool = False)[source]

Merges the merge request.

Parameters:
  • message – The commit message.
  • sha – The commit sha that the HEAD must match in order to merge.
  • should_remove_source_branch – Whether the source branch should be removed upon a successful merge.
  • _github_merge_method – On GitHub, the merge method to use when merging the MR. Can be one of merge, squash or rebase.
  • _gitlab_wait_for_pipeline – On GitLab, whether the MR should be merged immediately after the pipeline succeeds.
Raises:
  • RuntimeError – If something goes wrong (network, auth…).
  • NotImplementedError – If an unused parameter is passed.
mergeable

Returns true if there is no merge conflict.

milestone

Retrieves the milestone.

repository

Retrieves the repository where this comes from.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> pr.repository.full_name
'gitmate-test-user/test'
Returns:The repository object.
source_repository

Retrieves the repository where this PR’s head branch is located at.

>>> from os import environ
>>> pr = GitLabMergeRequest(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test', 2
... )
>>> pr.source_repository.full_name
'gitmate-test-user/test'
Returns:The repository object.
state

Retrieves the state of the Pull Request on GitHub.

Returns:A MergeRequestStates object.
will_close_issues

Returns a set of GitLabIssue objects which would be closed as stated in this pull request.

will_fix_issues

Returns a set of GitLabIssue objects which would be fixed as stated in this pull request.

will_resolve_issues

Returns a set of GitLabIssue objects which would be resolved as stated in this pull request.

IGitt.GitLab.GitLabNotification module

This contains the Notification implementation for GitHub.

Take note that GitHub Notifications are actually available via Todos API.

class IGitt.GitLab.GitLabNotification.GitLabNotification(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], identifier: Union[str, int])[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Notification.Notification

This class represents a Notification on GitLab.

static fetch_all(token: Union[IGitt.GitLab.GitLabPrivateToken, IGitt.GitLab.GitLabOAuthToken])[source]

Returns the list of notifications for the user bearing the token.

identifier

Returns the id of the notification thread from GitLab.

mark_done()[source]

Marks the notification as done/read.

pending

Returns True if the notification is pending/not read.

reason

Returns the reason for notification.

repository

Returns the repository this notification is related to.

subject

Returns the subject of the notification.

Returns:A GitLabIssue or GitLabMergeRequest object.
subject_type

Returns the type of the subject the notification.

unsubscribe()[source]

Unsubscribe from this subject.

IGitt.GitLab.GitLabOrganization module

This module contains the Issue abstraction class which provides properties and actions related to issues and bug reports.

class IGitt.GitLab.GitLabOrganization.GitLabOrganization(token, name)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Organization.Organization

Represents an organization on GitLab.

billable_users

Number of paying/registered users on the organization.

static create(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], name: str, path: str, parent_id: Optional[int] = None, description: Optional[str] = None, visibility: str = 'private', lfs_enabled: bool = False, request_access_enabled: bool = False) → IGitt.Interfaces.Organization.Organization[source]

Creates a new organization from the given parameters.

Parameters:
  • token – The credentials to be used for authorization.
  • name – The name of the organization.
  • path – The path of the organization.
  • parent_id – The parent organization id to create nested organization.
  • description – The description of the organization.
  • visibility – Controls the visibility of the organization. Can be either ‘private’, ‘public’ or ‘internal’.
  • lfs_enabled – Enables Git Large File System for projects in this organization.
  • request_access_enabled – Allow users to request member access on the organization.
description

Returns the description of this organization.

filter_issues(state: Optional[str] = None, label: Optional[str] = None, assignee: Optional[str] = None) → Set[IGitt.GitLab.GitLabIssue.GitLabIssue][source]

Filters the issues in the organization based on properties

Parameters:
  • state – ‘opened’ or ‘closed’ or ‘all’
  • label – Label of the issue
  • assignee – username of issue assignee
Returns:

Set of GitLabIssue objects

identifier

Returns the identifier of the organization.

issues

Returns the list of issue objects in this organization.

masters

Returns the user handles of all master users.

name

The name of the organization.

owners

Returns the user handles of all owner users.

raw_members[source]

Gets all members including the ones of groups around subgroups as a list of dicts from the JSON responses.

repositories

Returns the list of repositories contained in this organization including subgroup repositories, recursively.

suborgs

Returns the sub-organizations within this organization, recursively.

web_url

Returns a web link for GitLab.

IGitt.GitLab.GitLabProjectMilestone module

This contains the Milestone implementation for GitLab

class IGitt.GitLab.GitLabProjectMilestone.GitLabProjectMilestone(token: (<class 'IGitt.GitLab.GitLabOAuthToken'>, <class 'IGitt.GitLab.GitLabPrivateToken'>), project, number: int)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Milestone.Milestone

This class represents a project level milestone on GitLab. This class does not support group level milestones.

close()[source]

Closes the milestone.

Raises:RuntimeError – If something goes wrong (network, auth…).
static create(token: (<class 'IGitt.GitLab.GitLabOAuthToken'>, <class 'IGitt.GitLab.GitLabPrivateToken'>), project, title: str, description: str = None, due_date=None, start_date=None)[source]

Create a new milestone with given title and body.

>>> from os import environ
>>> milestone = GitLabProjectMilestone.create(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test',
...     'test milestone title',
...     'sample description'
... )
>>> milestone.state
'active'

Delete the milestone to avoid filling the test repo with milestones.

>>> milestone.close()
Returns:GitLabProjectMilestone object of the newly created milestone.
created

Retrieves a timestamp on when the milestone was created.

delete()[source]

Deletes the milestone. This is not possible with GitLab api v4.

Raises:RuntimeError – If something goes wrong (network, auth…).
description

Retrieves the main description of the milestone.

due_date

Retrieves a timestamp on when the milestone is due.

static extract_repo_full_name(web_url)[source]

Extracts the repository name from the web_url of the issue

issues

Retrieves a set of issue objects that are assigned to this milestone.

merge_requests

Retrieves a set of merge request objects that are assigned to this milestone.

number

Returns the milestone “number” or id.

project

Returns the repository this milestone is linked with.

reopen()[source]

Reopens the milestone.

Raises:RuntimeError – If something goes wrong (network, auth…).
start_date

Retrieves a timestamp on when the milestone was started.

state

Get’s the state of the milestone.

Returns:Either MilestoneStates.OPEN or MilestoneStates.CLOSED.
title

Retrieves the title of the milestone.

updated

Retrieves a timestamp on when the milestone was updated the last time.

IGitt.GitLab.GitLabReaction module

Contains an object representation of a reaction / award emoji on GitLab.

class IGitt.GitLab.GitLabReaction.GitLabReaction(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], related: Union[IGitt.Interfaces.Issue.Issue, IGitt.Interfaces.Comment.Comment], identifier: int)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Reaction.Reaction

A GitLab Reaction or Award Emoji, e.g. heart.

name

Retrieves the name of the reaction.

user

Retrieves the user who reacted with this reaction.

IGitt.GitLab.GitLabRepository module

Contains the GitLab Repository implementation.

class IGitt.GitLab.GitLabRepository.GitLabRepository(token: Union[IGitt.GitLab.GitLabOAuthToken, IGitt.GitLab.GitLabPrivateToken], repository: Union[str, int])[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.Repository.Repository

Represents a repository on GitLab.

clone_url

Retrieves the URL of the repository.

>>> from os import environ as env
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> expected = 'https://{}@gitlab.com/gitmate-test-user/test.git'
>>> assert repo.clone_url == expected.format(env['GITLAB_TEST_TOKEN'])
Returns:A URL that can be used to clone the repository with Git.
commits

Retrieves the set of commits in this repository.

Returns:A set of GitLabCommit objects.
static create(token: Union[IGitt.Interfaces.BasicAuthorizationToken, IGitt.GitLab.GitLabPrivateToken, IGitt.GitLab.GitLabOAuthToken], name: str, path: Optional[str] = None, visibility: str = 'public', namespace_id: Optional[int] = None, default_branch: Optional[str] = 'master', description: Optional[str] = None, has_issues: bool = True, has_merge_requests: bool = True, has_jobs: bool = True, has_wiki: bool = True, has_snippets: bool = True, has_container_registry: bool = True, has_shared_runners: bool = True, has_lfs: bool = False, resolve_outdated_diff_discussions: bool = False, import_url: Optional[str] = None, public_jobs: bool = False, only_allow_merge_if_pipeline_succeeds: bool = False, only_allow_merge_if_all_discussions_are_resolved: bool = False, allow_request_access: bool = True, allow_printing_merge_request_link: bool = True, tag_list: Optional[List[str]] = None, avatar: object = None, ci_config_path: Optional[str] = None, repository_storage: Optional[str] = None, approvals_before_merge: Optional[int] = None, **kwargs)[source]

Creates a new repository and returns the associated GitLabRepository instance.

Parameters:
  • token – The credentials to be used for authentication.
  • name – The name of the new project. Equals path if not provided.
  • path – Repository name for new project. Generated based on name if not provided (generated lowercased with dashes).
  • visibility – Either of private, public or internal. Reference: https://docs.gitlab.com/ee/api/projects.html#project-visibility-level
  • namespace_id – Namespace for the new project (defaults to the current user’s namespace)
  • default_branch – The default branch to be used.
  • description – A short description of the repository.
  • has_issues – Either True to enable issues for this project or False to disable them.
  • has_merge_requests – Either True to enable merge requests for this project or False to disable them.
  • has_jobs – Either True to enable jobs for this project or False to disable them.
  • has_wiki – Either True to enable wiki for this project or False to disable it.
  • has_snippets – Either True to enable snippets for this project or False to disable them.
  • has_container_registry – Either True to enable container registry or False to disable it.
  • has_lfs – Either True to enable Git Large File Sharing or False to disable it.
  • resolve_outdated_diff_discussions – Either True to automatically resolve merge request diff discussions on lines changed with a push of False to disable it.
  • import_url – URL to import repository from.
  • public_jobs – If True, jobs can be viewed by non-project-members.
  • only_allow_merge_if_pipeline_succeeds – Set whether merge requests can only be merged with successful jobs.
  • only_allow_merge_if_all_discussions_are_resolved – Set whether merge requests can only be merged when all the discussions are resolved.
  • allow_request_access – Allow users to request member access.
  • allow_printing_merge_request_link – Show link to create/view merge request when pushing from the command line.
  • tag_list – The list of tags for a project that should be finally assigned to a project.
  • avatar – Image file for avatar of the project (base64 encoded png).
  • ci_config_path – The path to CI config file.
  • repository_storage – Which storage shard the repository is on. Available only to admins.
  • approvals_before_merge – How many approvers should approve merge request by default before allowing it to be merged.
create_file(path: str, message: str, content: str, branch: Optional[str] = None, committer: Optional[str] = None, author: Optional[dict] = None, encoding: Optional[str] = None)[source]

Create a new file in Repository

create_fork(organization: Optional[str] = None, namespace: Optional[str] = None)[source]

Create a fork of Repository

create_issue(title: str, body: str = '') → IGitt.GitLab.GitLabIssue.GitLabIssue[source]

Create a new issue in the repository.

create_label(name: str, color: str = '', **kwargs)[source]

Creates a new label with the given color. For an example, see delete_label.

If a label that already exists is attempted to be created, that throws an exception:

>>> from os import environ
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> sorted(repo.get_labels())
['a', 'b', 'c']
>>> repo.create_label('c', '#555555')
Traceback (most recent call last):
 ...
IGitt.ElementAlreadyExistsError: c already exists.
Parameters:
  • name – The name of the label to create.
  • color – A HTML color value with a leading #.
Raises:
  • ElementAlreadyExistsError – If the label name already exists.
  • RuntimeError – If something goes wrong (network, auth…).
create_merge_request(title: str, base: str, head: str, body: Optional[str] = None, target_project_id: Optional[int] = None, target_project: Optional[str] = None)[source]

Create a new merge request in Repository

delete()[source]

Delete the Repository

delete_hook(url: str)[source]

Deletes all webhooks to the given URL.

Parameters:url – The URL to not fire the webhook to anymore.
Raises:RuntimeError – If something goes wrong (network, auth…).
delete_label(name: str)[source]

Deletes a label.

Take a given repository:

>>> from os import environ
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> sorted(repo.get_labels())
['a', 'b', 'c']

Let’s create a label ‘d’:

>>> repo.create_label('d', '#555555')
>>> sorted(repo.get_labels())
['a', 'b', 'c', 'd']
>>> repo.delete_label('d')
>>> sorted(repo.get_labels())
['a', 'b', 'c']

If the label doesn’t exist it won’t get silently dropped - no! You will get an exception.

>>> repo.delete_label('d')
Traceback (most recent call last):
 ...
IGitt.ElementDoesntExistError: d doesnt exist.
Parameters:

name – The caption of the label to delete.

Raises:
  • ElementDoesntExistError – If the label doesn’t exist.
  • RuntimeError – If something goes wrong (network, auth…).
filter_commits[source]

Filter commits based on properties.

Author:Author username of the commit.
Returns:A set of GitLabCommit objects.
filter_issues(state: str = 'opened', label: Optional[str] = None, assignee: Optional[str] = None) → set[source]

Filters the issues from the repository based on properties.

Parameters:
  • state – ‘opened’ or ‘closed’ or ‘all’.
  • label – Label of the issue.
  • assignee – username of issue assignee.
filter_merge_requests(state: str = 'opened') → set[source]

Filters the merge requests from the repository based on the state of the merge requests.

Parameters:state – ‘opened’ or ‘closed’, or ‘merged’, or ‘all’.
full_name

Retrieves the full name of the repository, e.g. “sils/baritone”.

>>> from os import environ
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> repo.full_name
'gitmate-test-user/test'
Returns:The full repository name as string.
get_issue(issue_number: int) → IGitt.GitLab.GitLabIssue.GitLabIssue[source]

Retrieves an issue:

>>> from os import environ
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> repo.get_issue(1).title
'Take it serious, son!'
Parameters:

issue_number – The issue IID of the issue on GitLab.

Returns:

An Issue object.

Raises:
  • ElementDoesntExistError – If the issue doesn’t exist.
  • RuntimeError – If something goes wrong (network, auth…).
get_labels() → Set[str][source]

Retrieves the labels of the repository.

>>> from os import environ
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> sorted(repo.get_labels())
['a', 'b', 'c']
Returns:A set of strings containing the label captions.
get_mr(mr_number: int)[source]

Retrieves an MR.

Parameters:

mr_number – The MR IID of the merge_request on GitLab.

Returns:

A MergeRequest object.

Raises:
  • ElementDoesntExistError – If the MR doesn’t exist.
  • RuntimeError – If something goes wrong (network, auth…).
get_permission_level(user) → IGitt.Interfaces.AccessLevel[source]

Retrieves the permission level for the specified user on this repository.

hooks

Retrieves all URLs this repository is hooked to.

Returns:Set of URLs (str).
identifier

Returns the id of the repository.

issues

Retrieves a set of open issue objects.

>>> from os import environ
>>> repo = GitLabRepository(environ['GITLAB_TEST_TOKEN'],
...                         'gitmate-test-user/test')
>>> len(repo.issues)
13
merge_requests

Retrieves a set of open merge request objects.

>>> from os import environ
>>> repo = GitLabRepository(
...     GitLabOAuthToken(environ['GITLAB_TEST_TOKEN']),
...     'gitmate-test-user/test'
... )
>>> len(repo.merge_requests)
4
parent

Returns the repository from which this repository is forked from. Returns None if it has no fork relationship.

register_hook(url: str, secret: Optional[str] = None, events: Optional[Set[IGitt.Interfaces.Repository.WebhookEvents]] = None)[source]

Registers a webhook to the given URL. Use it as simple as:

>>> from os import environ
>>> repo = GitLabRepository(environ['GITLAB_TEST_TOKEN'],
...                         'gitmate-test-user/test')
>>> repo.register_hook("http://some.url/in/the/world")

It does nothing if the hook is already there:

>>> repo.register_hook("http://some.url/in/the/world")

To register a secret token with the webhook, simply add the secret param:

>>> repo.register_hook("http://some.url/i/have/a/secret",
...     "mylittlesecret")

To delete it simply run:

>>> repo.delete_hook("http://some.url/in/the/world")
>>> repo.delete_hook("http://some.url/i/have/a/secret")
Parameters:
  • url – The URL to fire the webhook to.
  • secret – An optional secret token to be registered with the webhook.
  • events – The events for which the webhook is to be registered against. Defaults to all possible events.
Raises:

RuntimeError – If something goes wrong (network, auth…).

search_issues(created_after: Optional[datetime.datetime] = None, created_before: Optional[datetime.datetime] = None, updated_after: Optional[datetime.datetime] = None, updated_before: Optional[datetime.datetime] = None, state: Optional[IGitt.Interfaces.IssueStates] = None)[source]

Searches for issues based on created and updated date.

search_mrs(created_after: Optional[datetime.datetime] = None, created_before: Optional[datetime.datetime] = None, updated_after: Optional[datetime.datetime] = None, updated_before: Optional[datetime.datetime] = None, state: Optional[IGitt.Interfaces.MergeRequestStates] = None)[source]

Searches for merge request based on created and updated date.

top_level_org

Returns the topmost organization, e.g. for gitmate/open-source/IGitt this is gitmate.

IGitt.GitLab.GitLabRepository.date_in_range(data, created_after: Optional[datetime.datetime] = None, created_before: Optional[datetime.datetime] = None, updated_after: Optional[datetime.datetime] = None, updated_before: Optional[datetime.datetime] = None)[source]

Returns true if issue/MR is in the given range.

IGitt.GitLab.GitLabTeam module

Contains the GitLab Team implementation.

class IGitt.GitLab.GitLabTeam.GitLabTeam(token, group_id)[source]

Bases: IGitt.GitLab.GitLabMixin

Represents a Team on GitLab.

description

Returns the description of this team.

get_organization

Returns parent team.

id

Retrieves the id of the team.

is_member(username)[source]

Checks if given username is member of this team.

members

Returns the user handles of all members of this team.

name

Name of the team.

IGitt.GitLab.GitLabUser module

Contains a representation of GitHub users.

class IGitt.GitLab.GitLabUser.GitLabUser(token: Union[IGitt.GitLab.GitLabPrivateToken, IGitt.GitLab.GitLabOAuthToken], identifier: Union[str, int, None] = None)[source]

Bases: IGitt.GitLab.GitLabMixin, IGitt.Interfaces.User.User

A GitLab user, e.g. sils :)

get_installations(jwt)[source]

Gets the installations this user has access to.

GitLab doesn’t support building installations yet.

identifier

Gets a unique id for the user that never changes.

installed_repositories(installation_id: int)[source]

List repositories that are accessible to the authenticated user for an installation.

GitLab doesn’t support building installations yet.

username

Retrieves the login for the user.

Module contents

This package contains the GitLab implementations of the interfaces in server.git.Interfaces. GitLab drops the support of API version 3 as of August 22, 2017. So, IGitt adopts v4 to stay future proof.

class IGitt.GitLab.GitLabMixin[source]

Bases: IGitt.Utils.CachedDataMixin

Base object for things that are on GitLab.

static absolute_url(url)[source]

Makes a URL like /repo/coala/coala absolute.

hoster

Tells you that this is a gitlab object.

url

Returns gitlab API url.

web_url

Returns a web link for GitLab.

class IGitt.GitLab.GitLabOAuthToken(token)[source]

Bases: IGitt.Interfaces.Token

Object representation of OAuth2 tokens.

auth

A AuthBase instance that can be readily used to configure any kind of authentication easily with requests library.

headers

GitLab OAuth token does not require any special headers.

parameter

No additional query parameters are used with the token.

value

Token value

class IGitt.GitLab.GitLabPrivateToken(token)[source]

Bases: IGitt.Interfaces.Token

Object representation of private tokens.

auth

Private token based authorization for GitLab cannot be used directly via an AuthBase object.

headers

GitLab Private token does not require any special headers.

parameter

Parameter to be used for authentication

value

Token value