當前位置: 首頁>>代碼示例>>Python>>正文


Python gitlab.Gitlab方法代碼示例

本文整理匯總了Python中gitlab.Gitlab方法的典型用法代碼示例。如果您正苦於以下問題:Python gitlab.Gitlab方法的具體用法?Python gitlab.Gitlab怎麽用?Python gitlab.Gitlab使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在gitlab的用法示例。


在下文中一共展示了gitlab.Gitlab方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_gitlab_project

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def get_gitlab_project(self):
        """Get numerical GitLab Project ID.

        Returns:
            int: Project ID number.

        Raises:
            foremast.exceptions.GitLabApiError: GitLab responded with bad status
                code.

        """
        self.server = gitlab.Gitlab(GIT_URL, private_token=GITLAB_TOKEN, api_version=4)
        project = self.server.projects.get(self.git_short)

        if not project:
            raise GitLabApiError('Could not get Project "{0}" from GitLab API.'.format(self.git_short))

        self.project = project
        return self.project 
開發者ID:foremast,項目名稱:foremast,代碼行數:21,代碼來源:lookups.py

示例2: _get_ami_file

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def _get_ami_file(region='us-east-1'):
    """Get file from Gitlab.

    Args:
        region (str): AWS Region to find AMI ID.

    Returns:
        str: Contents in json format.

    """
    LOG.info("Getting AMI from Gitlab")
    lookup = FileLookup(git_short='devops/ansible')
    filename = 'scripts/{0}.json'.format(region)
    ami_contents = lookup.remote_file(filename=filename, branch='master')
    LOG.debug('AMI file contents in %s: %s', filename, ami_contents)
    return ami_contents 
開發者ID:foremast,項目名稱:foremast,代碼行數:18,代碼來源:lookups.py

示例3: mock_gitlab

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def mock_gitlab(status="success"):
    mocks = [
        mock.patch("os.environ", {"GL_TOKEN": "token"}),
        mock.patch(
            "semantic_release.hvcs.config.get", wrapped_config_get(hvcs="gitlab")
        ),
        mock.patch("gitlab.Gitlab.auth"),
        mock.patch(
            "gitlab.v4.objects.ProjectManager",
            return_value={"owner/repo": _GitlabProject(status)},
        ),
    ]

    def wraps(func):
        for option in reversed(mocks):
            func = option(func)
        return func

    return wraps 
開發者ID:relekang,項目名稱:python-semantic-release,代碼行數:21,代碼來源:mock_gitlab.py

示例4: main

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def main():
    if 2 > len(sys.argv) > 3:
        usage()

    project_name = sys.argv[1]
    if len(sys.argv) > 2:
        branch_name = sys.argv[2]
    else:
        branch_name = 'master'

    gl_token = os.getenv('GITLAB_TOKEN')
    if gl_token is None:
        print('GITLAB_TOKEN not set!')
        exit(1)
    gl = gitlab.Gitlab('https://gitlab.com/', gl_token)

    project = gl.projects.get(project_name)
    branch = project.branches.get(branch_name)
    top_commit = project.commits.get(branch.commit['short_id'])

    if top_commit.last_pipeline['status'] == 'success':
        print(top_commit.short_id)
    else:
        exit(1) 
開發者ID:maxking,項目名稱:docker-mailman,代碼行數:26,代碼來源:get_latest_ref.py

示例5: _get_authorized_client

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def _get_authorized_client(self):
        auth_token = self.auth_token or "invalid"
        api_version = self.config.get("API_VERSION", "4")
        client = gitlab.Gitlab(
            gitlab_trigger.api_endpoint(),
            oauth_token=auth_token,
            timeout=20,
            api_version=api_version,
        )
        try:
            client.auth()
        except gitlab.GitlabGetError as ex:
            raise TriggerAuthException(ex.message)
        except gitlab.GitlabAuthenticationError as ex:
            raise TriggerAuthException(ex.message)

        return client 
開發者ID:quay,項目名稱:quay,代碼行數:19,代碼來源:gitlabhandler.py

示例6: get_last_comment

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def get_last_comment(self, mr):
        """
        Returns information about last comment of given
        merge request

        Args:
            mr (gitlab.v4.objects.ProjectMergeRequest): Gitlab merge request

        Returns:
            last comment (LastComment): Returns namedtuple LastComment
            with data related to last comment
        """

        for note in mr.notes.list():
            if not note.system:
                return LastComment(
                    author=note.author['username'], body=note.body,
                    created_at=datetime.datetime.strptime(
                        note.created_at, '%Y-%m-%dT%H:%M:%S.%fZ')) 
開發者ID:redhat-aqe,項目名稱:review-rot,代碼行數:21,代碼來源:gitlabstack.py

示例7: connect

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def connect(url="https://gitlab.com", token=None):
    """
    Return a connected GitLab session

    ``token`` should be a ``private_token`` from Gitlab
    """

    if token is None:
        token = os.environ.get("GITLAB_API_TOKEN", None)

    gl_session = gitlab.Gitlab(url, token)

    try:
        gl_session.version()
    except (gitlab.exceptions.GitlabAuthenticationError):
        raise RuntimeError("Invalid or missing GITLAB_API_TOKEN")

    logger.info("Connected to: %s", url)

    return gl_session 
開發者ID:LLNL,項目名稱:scraper,代碼行數:22,代碼來源:__init__.py

示例8: with_gitlab_session

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def with_gitlab_session(func: Decoratable) -> Decorator:
    async def wrapper(self, evt: MessageEvent, login: AuthInfo, **kwargs) -> Any:
        try:
            repo = kwargs["repo"]
            if isinstance(repo, DefaultRepoInfo):
                if repo.server not in self.db.get_servers(evt.sender):
                    await evt.reply(f"You're not logged into {repo.server}")
                    return
                login = self.db.get_login(evt.sender, url_alias=repo.server)
                kwargs["repo"] = repo.repo
        except KeyError:
            pass

        try:
            with Gl(login.server, login.api_token) as gl:
                return await func(self, evt, gl=gl, **kwargs)
        except GitlabAuthenticationError as e:
            await evt.reply("Invalid access token.\n\n{0}".format(e))
        except Exception:
            self.log.error("Failed to handle command", exc_info=True)

    return wrapper 
開發者ID:maubot,項目名稱:gitlab,代碼行數:24,代碼來源:util.py

示例9: default_repo

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def default_repo(self, evt: MessageEvent, repo: str, gl: Gl) -> None:
        power_levels = await self.client.get_state_event(evt.room_id, EventType.ROOM_POWER_LEVELS)
        if power_levels.get_user_level(evt.sender) < power_levels.state_default:
            await evt.reply("You don't have the permission to change the default repo of this room")
            return

        try:
            project = gl.projects.get(repo)
        except GitlabGetError as e:
            if e.response_code == 404:
                await evt.reply(f"Couldn't find {repo} on {gl.url}")
                return
            raise
        self.db.set_default_repo(evt.room_id, gl.url, repo)
        await evt.reply(f"Changed the default repo to {repo} on {gl.url}")

    # endregion
    # region !gitlab server 
開發者ID:maubot,項目名稱:gitlab,代碼行數:20,代碼來源:bot.py

示例10: diff

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def diff(self, evt: MessageEvent, repo: str, hash: str, gl: Gl) -> None:
        project = gl.projects.get(repo)
        diffs = project.commits.get(hash).diff()

        def color_diff(line: str) -> str:
            if line.startswith("@@") and re.fullmatch(r"(@@ -[0-9]+,[0-9]+ \+[0-9]+,[0-9]+ @@)",
                                                      line):
                return f"<font color='#00A'>{line}</font>"
            elif line.startswith(("+++", "---")):
                return f"<font color='#000'>{line}</font>"
            elif line.startswith("+"):
                return f"<font color='#0A0'>{line}</font>"
            elif line.startswith("-"):
                return f"<font color='#A00'>{line}</font>"
            else:
                return f"<font color='#666'>{line}</font>"

        for index, diff in enumerate(diffs):
            msg = "{path}:\n<pre><code>{diff}</code></pre>".format(
                path=diff["new_path"],
                diff="\n".join(color_diff(line) for line in diff["diff"].split("\n")))
            await evt.respond(msg, reply=index == 0, allow_html=True) 
開發者ID:maubot,項目名稱:gitlab,代碼行數:24,代碼來源:bot.py

示例11: log

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def log(self, evt: MessageEvent, repo: str, page: int, per_page: int, gl: Gl) -> None:
        project = gl.projects.get(repo)
        commits = project.commits.list(page=page or 1, per_page=per_page or 10)

        def first_line(message: str) -> str:
            lines = message.strip().split("\n")
            message = lines[0][:80]
            if len(lines[0]) > 80:
                message += "…"
            elif len(lines) > 1:
                message += " (…)"
            return message

        await evt.reply("".join(f"* [`{commit.short_id}`]({gl.url}/{repo}/commit/{commit.id})"
                                f" {first_line(commit.message)}\n"
                                for commit in commits),
                        allow_html=True) 
開發者ID:maubot,項目名稱:gitlab,代碼行數:19,代碼來源:bot.py

示例12: get_gitlab_group

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def get_gitlab_group(query):
    token = generate_personal_access_token('mytoken', query['passwd'], query['gitlab_ip'])

    gl = gitlab.Gitlab('http://{0}'.format(query['gitlab_ip']), api_version=4, private_token=token)

    slfGroup = gl.groups.create({'name': 'SLF', 'path': 'slf', 'description': 'Jazz framework, templates and services'})
    gl.groups.create({'name': 'CAS', 'path': 'cas', 'description': 'User created services repository'})

    # Update the username from the `root` user to scm_username, because for some
    # reason downstream stuff needs it.
    # TODO Downstream stuff should only need the access token, investigate if user
    # creds can be dropped after this point in favor of the PAT
    rootUser = gl.users.list(username='root')[0]
    rootUser.username = query['scm_username']
    rootUser.save()

    return {
        'gitlab_slfid': str(slfGroup.id),
        'gitlab_token': str(token)
    } 
開發者ID:tmobile,項目名稱:jazz-installer,代碼行數:22,代碼來源:configure-gitlab.py

示例13: get_gitlab_instance

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def get_gitlab_instance() -> gitlab.Gitlab:
    gl = gitlab.Gitlab(
        current_app.config['GITLAB_URL'],
        oauth_token=current_user.access_token,
        api_version=current_app.config['GITLAB_API_VERSION']
    )

    gl.auth()

    return gl 
開發者ID:Salamek,項目名稱:gitlab-tools,代碼行數:12,代碼來源:gitlab.py

示例14: __init__

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def __init__(self, bundle, intergration=False, url=None, ignore_ssl=False):
        self.bundle = bundle
        self.url = url
        self.ignore_ssl = ignore_ssl
        if intergration:
            raise NotImplementedError(
                'Gitlab provider does not support integration mode') 
開發者ID:pyupio,項目名稱:pyup,代碼行數:9,代碼來源:gitlab.py

示例15: _api

# 需要導入模塊: import gitlab [as 別名]
# 或者: from gitlab import Gitlab [as 別名]
def _api(self, token):
        parts = token.split('@')
        if len(parts) == 1:
            host = self.url or 'https://gitlab.com'
            auth = parts[0]
        elif len(parts) == 2:
            auth, host = parts
        else:
            raise BadTokenError(
                'Got token "{}": format should be wither "apikey" for '
                'gitlab.com, or "apikey@https://yourgitlab.local"'.format(
                    token))
        return Gitlab(host, auth, ssl_verify=(not self.ignore_ssl)) 
開發者ID:pyupio,項目名稱:pyup,代碼行數:15,代碼來源:gitlab.py


注:本文中的gitlab.Gitlab方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。