-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitlab-variables.py
More file actions
118 lines (105 loc) · 5.76 KB
/
gitlab-variables.py
File metadata and controls
118 lines (105 loc) · 5.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import sys
import json
import requests
import argparse
def query_yes_no(question, default_no=True):
choices = ' [y/N]: ' if default_no else ' [Y/n]: '
default_answer = 'n' if default_no else 'y'
reply = str(input(question + choices)).lower().strip() or default_answer
if reply[0] == 'y':
return True
if reply[0] == 'n':
return False
else:
return False if default_no else True
parser = argparse.ArgumentParser(prog='GitLab Variables operator', description='Работа с переменными групп/проектов GitLab')
parser.add_argument('-v', '--version', action='version', version='%(prog)s v0.2b')
subparsers = parser.add_subparsers(dest='command', help='Команды')
subparsers.required = True
# A list command
list_parser = subparsers.add_parser('list', help='Вывести список всех переменных группы/проекта')
list_parser.add_argument('-c', '--config', action='store', help='Файл конфигурации репозитория', required=True)
list_parser.add_argument('-j', '--json', action='store_true', help='"Красивый" вывод с отступами')
# A create command
create_parser = subparsers.add_parser('create', help='Создать переменные, перечисленные в файле данных. Существующие переменные не изменяются')
create_parser.add_argument('-c', '--config', action='store', help='Файл конфигурации репозитория', required=True)
create_parser.add_argument('-d', '--data', action='store', help='Файл с данными в формате JSON')
# An update command
update_parser = subparsers.add_parser('update', help='Заменить значение переменных, перечисленных в файле данных. Отсутствующие переменные пропускаются')
update_parser.add_argument('-c', '--config', action='store', help='Файл конфигурации репозитория', required=True)
update_parser.add_argument('-d', '--data', action='store', help='Файл с данными в формате JSON')
# A remove command
remove_parser = subparsers.add_parser('remove', help='Удалить переменные, перечисленные в файле данных')
remove_parser.add_argument('-c', '--config', action='store', help='Файл конфигурации репозитория', required=True)
remove_parser.add_argument('-d', '--data', action='store', help='Файл с данными в формате JSON')
remove_parser.add_argument('-y', '--yes', action='store_true', help='Ответить "YES" на все вопросы. Удаление без подтверждения!!!', default=False)
args = parser.parse_args()
#print (args)
with open(args.config, 'r') as settingsFile:
s: dict = json.load(settingsFile)
locals().update(s[0])
print('Выполняется операция',args.command,'с переменными',resource,id,'на сервере',url,file=sys.stderr)
if args.command == "list":
response = requests.get(
url=f'{url}/api/v4/{resource}/{id}/variables?per_page=100&page=1',
headers={'PRIVATE-TOKEN': token},
)
if args.json:
result = json.dumps(response.json(), indent=2, sort_keys=True)
else:
result = json.loads(response.text)
print (result)
if response.status_code >= 200 and response.status_code <= 299:
print ('OK', file=sys.stderr)
if response.status_code >= 400:
print (list(response.json().values())[0], file=sys.stderr)
# print (response.json()["message"], file=sys.stderr)
# print ("HTTP status code -", response.status_code, file=sys.stderr)
elif args.command == "create":
with open(data, 'r') as infile:
variables: dict = json.load(infile)
for variable in variables:
print ('Creating '+variable["key"]+'... ',end='', flush=True, file=sys.stderr)
response = requests.post(
url=f'{url}/api/v4/{resource}/{id}/variables',
headers={'PRIVATE-TOKEN': token},
data=variable
)
if response.status_code >= 200 and response.status_code <= 299:
print ('OK', file=sys.stderr)
if response.status_code >= 400:
print (response.json()["message"]["key"][0], file=sys.stderr)
elif args.command == "update":
with open(data, 'r') as infile:
variables: dict = json.load(infile)
for variable in variables:
print ('Creating '+variable["key"]+'... ',end='', flush=True, file=sys.stderr)
response = requests.put(
url=f'{url}/api/v4/{resource}/{id}/variables/{variable["key"]}',
headers={'PRIVATE-TOKEN': token},
data=variable
)
if response.status_code >= 200 and response.status_code <= 299:
print ('OK', file=sys.stderr)
if response.status_code >= 400:
print (response.json()["message"], file=sys.stderr)
elif args.command == "remove":
with open(data, 'r') as infile:
variables: dict = json.load(infile)
for variable in variables:
ask = args.yes
if not ask:
ask=query_yes_no('Remove '+ variable["key"])
if ask:
print ('Removing '+variable["key"]+'... ',end='', flush=True, file=sys.stderr)
response = requests.delete(
url=f'{url}/api/v4/{resource}/{id}/variables/{variable["key"]}',
headers={'PRIVATE-TOKEN': token},
data=variable
)
if response.status_code >= 200 and response.status_code <= 299:
print ('OK', file=sys.stderr)
if response.status_code >= 400:
print (response.json()["message"], file=sys.stderr)
else:
print("Incorrect option")