-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircleci_env_cli.py
More file actions
executable file
·317 lines (267 loc) · 9.78 KB
/
circleci_env_cli.py
File metadata and controls
executable file
·317 lines (267 loc) · 9.78 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python
import logging
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as pkg_version
import click
from pycircleci.api import Api, CircleciError
try:
__version__ = pkg_version("circleci-env-cli")
except PackageNotFoundError:
__version__ = "unknown"
@dataclass
class _Ctx:
client: Api
logger: logging.Logger
def _make_circle_context(api_url: str, token: str, debug: bool = False) -> _Ctx:
if not token:
raise SystemExit(
"Error: CircleCI token is required. Set CIRCLE_TOKEN or use -t/--token."
)
if debug:
logging.basicConfig(
level=logging.DEBUG,
format="[%(levelname)s] %(module)s:%(funcName)s - %(message)s",
stream=sys.stdout,
)
else:
logging.basicConfig(
level=logging.INFO,
format="> %(message)s",
stream=sys.stdout,
)
return _Ctx(
client=Api(token=token, url=api_url),
logger=logging.getLogger(__name__),
)
def get_context_id(
circle_context: _Ctx, org: str, owner_type: str, vcs_type: str, context: str
) -> str | None:
try:
contexts = circle_context.client.get_contexts(
username=org, owner_type=owner_type, vcs_type=vcs_type, paginate=True
)
matched = list(filter(lambda c: c["name"] == context, contexts))
except Exception as error:
raise SystemExit(f"Error: {error}")
return matched[0]["id"] if matched else None
def create_context(
circle_context: _Ctx, org: str, owner_type: str, vcs_type: str, context: str
) -> str:
answer = input(f'The context named "{context}" was not found. Do you want to create it? [y/n]: ')
if answer.lower() != "y":
circle_context.logger.info("Context creation cancelled.")
sys.exit(0)
new_context = circle_context.client.add_context(
context, username=org, owner_type=owner_type, vcs_type=vcs_type
)
circle_context.logger.info(f"Successfully created context: {context}")
return new_context["id"]
def delete_context(circle_context: _Ctx, context_id: str, context: str) -> None:
confirm = input(f'Are you sure want to delete the context "{context}"? [y/n]: ')
if confirm.lower() == "y":
circle_context.client.delete_context(context_id)
circle_context.logger.info(f"Successfully deleted context: {context}")
sys.exit(0)
def delete_context_var(circle_context: _Ctx, context_id: str, env: str) -> bool:
try:
circle_context.client.delete_context_envvar(context_id, env)
circle_context.logger.info(f"Successfully deleted context variable: {env}")
return True
except Exception as error:
circle_context.logger.error(f"Error: {error}")
return False
def upsert_context_var(circle_context: _Ctx, context_id: str, env: str, value: str) -> bool:
try:
circle_context.client.add_context_envvar(context_id, env, value)
circle_context.logger.info(f"Successfully added/updated context variable: {env}")
return True
except Exception as error:
circle_context.logger.error(f"Error: {error}")
return False
def upsert_project_var(
circle_context: _Ctx, org: str, vcs_type: str, project: str, env: str, value: str
) -> bool:
try:
circle_context.client.add_envvar(org, project, env, value, vcs_type)
circle_context.logger.info(f"Successfully added/updated variable: {env}")
return True
except Exception as error:
circle_context.logger.error(f"Error: {error}")
return False
def delete_project_var(
circle_context: _Ctx, org: str, vcs_type: str, project: str, env: str
) -> bool:
try:
circle_context.client.delete_envvar(org, project, env, vcs_type)
circle_context.logger.info(f"Successfully deleted variable: {env}")
return True
except Exception as error:
circle_context.logger.error(f"Error: {error}")
return False
def run(
circle_context: _Ctx,
owner_type: str,
context: str,
project_slug: str,
env: tuple,
env_file,
list_envs: bool,
delete: bool,
) -> None:
env_vars = []
parts = project_slug.split("/")
if len(parts) == 2:
vcs_type, org = parts
project_name = None
elif len(parts) == 3:
vcs_type, org, project_name = parts
else:
raise SystemExit(
"Error: Invalid project slug. Expected github/org-name or github/org-name/project-name."
)
if not any([env, env_file, list_envs, delete, context]):
raise SystemExit("Error: nothing to do. Specify -e, -ef, -l, -d, or -c. Use --help for usage.")
if env:
env_vars += list(env)
if env_file:
seen = set()
for line in env_file.read().splitlines():
if line and line not in seen:
seen.add(line)
env_vars.append(line)
context_id = None
if context:
context_id = get_context_id(circle_context, org, owner_type, vcs_type, context)
if not context_id:
context_id = create_context(circle_context, org, owner_type, vcs_type, context)
if list_envs:
context_envs = circle_context.client.get_context_envvars(context_id, True)
names = sorted(x["variable"] for x in context_envs)
circle_context.logger.info(f"Context variables ({len(names)}):\n" + "\n".join(names))
sys.exit(0)
if not env_vars and delete and context_id:
delete_context(circle_context, context_id, context)
if list_envs:
if not project_name:
raise SystemExit("Error: project name required for this operation. Use github/org-name/project-name.")
try:
envvars = circle_context.client.list_envvars(org, project_name, vcs_type)
names = sorted(x["name"] for x in envvars)
circle_context.logger.info(f"Project variables ({len(names)}):\n" + "\n".join(names))
sys.exit(0)
except Exception as error:
circle_context.logger.error(f"Error: {error}")
with ThreadPoolExecutor(max_workers=5) as executor:
threadpool = []
for var in env_vars:
try:
key, value = var.split("=", 1)
except ValueError:
key, value = (var, "")
except Exception:
raise SystemExit(f"Error: failed to proccess variable {var}...")
key, value = key.strip(), value.strip()
if context:
if context_id is None:
raise SystemExit(f"Error: could not resolve context '{context}'")
if delete:
threadpool.append(
executor.submit(delete_context_var, circle_context, context_id, key)
)
else:
threadpool.append(
executor.submit(upsert_context_var, circle_context, context_id, key, value)
)
else:
if not project_name:
raise SystemExit(
"Error: project name required for this operation. Use github/org-name/project-name."
)
if delete:
threadpool.append(
executor.submit(delete_project_var, circle_context, org, vcs_type, project_name, key)
)
else:
threadpool.append(
executor.submit(upsert_project_var, circle_context, org, vcs_type, project_name, key, value)
)
for thread in as_completed(threadpool):
thread.result()
@click.command(context_settings={"auto_envvar_prefix": "CIRCLE"})
@click.version_option(version=__version__)
@click.option(
"-u", "--api-url",
metavar="<circleci_api_url>",
default="https://circleci.com/api",
show_default=True,
)
@click.option(
"-t", "--token",
metavar="<circleci_token>",
show_default="CIRCLE_TOKEN",
)
@click.option(
"-c", "--context",
metavar="<context_name>",
help="It will ask for create if does not exists",
)
@click.option(
"-p", "--project",
metavar="<project_slug>",
required=True,
help="github/org-name for context ops, github/org-name/project-name for project ops",
)
@click.option(
"-e", "--env",
multiple=True,
metavar="<environment_var>",
)
@click.option(
"-ef", "--env-file",
metavar="<environment_vars_file>",
type=click.File("r"),
)
@click.option(
"-l", "--list-envs",
metavar="<environment_vars_list>",
is_flag=True,
)
@click.option(
"-d", "--delete",
metavar="<environment_var_delete>",
is_flag=True,
help=(
"Delete mode. Behavior depends on other options:\n\b\n"
" -c only: delete the entire context\n"
" -c + -e/-ef: delete specific context variables\n"
" -e/-ef only: delete specific project variables"
),
)
@click.option(
"-ot", "--owner-type",
metavar="<owner_type>",
default="organization",
show_default=True,
)
@click.option(
"--debug",
metavar="<debug>",
default=False,
is_flag=True,
)
@click.pass_context
def cli(ctx, api_url, token, context, project, env, env_file, list_envs, delete, owner_type, debug):
"""CLI tool for manage CircleCI contexts and environment vars
All options can be specified as environment variables in the format:
CIRCLE_<OPTION>. Example: CIRCLE_TOKEN=********
"""
try:
ctx.obj = _make_circle_context(api_url, token, debug)
run(ctx.obj, owner_type, context, project, env, env_file, list_envs, delete)
except CircleciError as error:
raise SystemExit(f"Error: {error}")
if __name__ == "__main__":
cli()