本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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'))
示例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
示例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
示例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
示例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)
示例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)
示例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)
}
示例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
示例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')
示例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))