Coverage for pyquickhelper/loghelper/repositories/gitlab_helper.py: 25%

36 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-03 02:21 +0200

1# -*- coding: utf-8 -*- 

2""" 

3@file 

4@brief Wrapper around GitLab API. 

5""" 

6 

7import json 

8 

9 

10class GitLabException(Exception): 

11 

12 """ 

13 specific exception, stores the request 

14 """ 

15 

16 def __init__(self, mes, req=None): 

17 """ 

18 @param mes message 

19 @param req request which caused the failure 

20 """ 

21 Exception.__init__(self, mes) 

22 self.request = req 

23 

24 def __str__(self): 

25 """ 

26 usual 

27 """ 

28 if self.request is None: 

29 return Exception.__str__(self) 

30 else: 

31 return "{0}\nCODE: {1}\n[giterror]\n{2}".format( 

32 Exception.__str__(self), self.request.status_code, self.request.content) 

33 

34 

35class GitLabAPI: 

36 

37 """ 

38 Wrapper around GitLab Server. 

39 

40 The API is defined at `gitlabhq/doc/api <https://github.com/gitlabhq/gitlabhq/tree/master/doc/api>`_ 

41 """ 

42 

43 def __init__(self, host, verify_ssl=True): 

44 """ 

45 constructor 

46 

47 @param host git lab host 

48 @param verify_ssl use_ssl (SSL connection) 

49 """ 

50 self.host = host.rstrip("/") 

51 if not self.host.startswith( 

52 "https://") and not self.host.startswith("http://"): 

53 raise GitLabException("host should start with https:// or http://") 

54 

55 self.api_url = self.host + "/api/v3" 

56 self.verify_ssl = verify_ssl 

57 

58 def login(self, user, password): 

59 """ 

60 login 

61 

62 @param user user 

63 @param password password 

64 """ 

65 import requests 

66 data = {"login": user, "password": password} 

67 url = f"{self.api_url}/Session" 

68 request = requests.post(url, data=data, verify=self.verify_ssl, 

69 headers={"connection": "close"}, 

70 timeout=10) 

71 if request.status_code == 201: 

72 self.token = json.loads( 

73 request.content.decode("utf-8"))['private_token'] 

74 self.headers = {"PRIVATE-TOKEN": self.token, "connection": "close"} 

75 elif request.status_code == 404: 

76 raise GitLabException("unable to login to " + url, request) 

77 else: 

78 msg = json.loads(request.content.decode("utf-8"))['message'] 

79 raise GitLabException( 

80 "unable to login to " + url + "\n" + msg, request) 

81 

82 def get_projects(self, page=1, per_page=100): 

83 """ 

84 returns a list of dictionaries 

85 

86 @return list of dictionaries 

87 """ 

88 import requests 

89 data = {'page': page, 'per_page': per_page} 

90 

91 request = requests.get( 

92 self.api_url, params=data, headers=self.headers, verify=self.verify_ssl, 

93 timeout=10) 

94 if request.status_code == 200: 

95 return json.loads(request.content.decode("utf-8")) 

96 else: 

97 raise GitLabException( 

98 f"unable to retreive the list of projects: {request}", request)