Python

python-gitlab 사용방법

비번변경 2021. 6. 19. 22:12

python-gitlab이란?

GitLab API에 대한 접근을 제공하는 Python 패키지

GitLab API를 이용하는 대부분의 작업을 Python 프로그램에서 사용할 수 있다.

터미널에서 GitLab API를 사용할 수 있도록 gitlab 명령어를 제공하기도 한다.

지원하는 클래스와 함수는 공식 문서에서 살펴볼 수 있다.

 

공식 문서 : https://python-gitlab.readthedocs.io/en/stable/#

 

Welcome to python-gitlab’s documentation! — python-gitlab 2.8.0 documentation

© Copyright 2013-2018, Gauvain Pocentek, Mika Mäenpää Revision dc535565.

python-gitlab.readthedocs.io

 

설치 방법

pip를 이용해 설치한다.

pip3 install python-gitlab
# --upgrade : 패키지 업그레이드

또는 깃허브에 업로드된 개발 버전을 설치할 수도 있다.

 

사전에 준비할 것

계정 access token

 

사용 방법

상단에 설치한 패키지를 import 한다.

import gitlab

 

사용자 인증

account = gitlab.Gitlab('GITLAB_URL', private_token='VALUE')
account.auth()

 

그룹 관련

특정 그룹 정보 확인

group = account.groups.get(group_id)
print(group.attributes)

사용자가 속한 그룹만 확인 가능하다.
정보 출력 시 그룹 아래에 속한 프로젝트 목록까지 출력된다.

 

그룹 리스트 확인

group_list = account.groups.list(all=True, order_by='id', sort='desc')
# all : 전체 항목 반환
# order_by : 정렬 속성 지정
# sort : 오름차순/내림차순 정렬

기본적으로 페이지네이션되어 있어 전체 항목을 반환하지 않는다.

 

그룹 생성

stmt = f"{{ 'name': '{name}', 'path': '{path}', 'parent_id': {parent_id}, 'visibility': '{visibility}' }}"
created = account.groups.create(eval(stmt).copy())

서브그룹이 아닌 경우에는 parent_id 값을 생략하거나 None으로 준다.

 

그룹 전체 프로젝트 확인

group = account.groups.get(group_id)
g_projects = group.projects.list(all=True)

마찬가지로 페이지네이션되어 있어 전체 항목을 반환하지 않는다.

 

서브 그룹 리스트 확인

group = account.groups.get(group_id)
subgroups = group.subgroups.list()

 

프로젝트 관련

특정 프로젝트 정보 확인

project = account.projects.get(project_id)
print(project.attributes)

 

모든 프로젝트 목록 확인

projects = account.projects.list(all=True)

 

프로젝트를 json 형식으로 변환하여 확인

# 추가로 import 할 것
import json

projects = account.projects.list(all=True)
for project in projects:
        print(json.dumps(project.attributes))

 

빈 프로젝트 확인

projects = account.projects.list(all=True)
for p in projects:
        if p.empty_repo == True:
                print(p.web_url)

 

프로젝트 생성

stmt = f"{{ 'name': '{p.name}', 'path': '{p.path}', 'namespace_id': {group_id}, 'visibility': '{p.visibility}'}}"
created = mirror.projects.create(eval(stmt).copy())
728x90