-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
369 lines (322 loc) Β· 13.6 KB
/
cli.py
File metadata and controls
369 lines (322 loc) Β· 13.6 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/usr/bin/env python3
"""
Artifact Repository CLI Management Tool
Command-line interface for managing the centralized artifact repository
"""
import click
import os
import sys
import json
import requests
from pathlib import Path
from typing import Optional
import yaml
class ArtifactRegistryClient:
def __init__(self, base_url: str = "http://localhost:5000", token: Optional[str] = None):
self.base_url = base_url.rstrip('/')
self.token = token
self.session = requests.Session()
if token:
self.session.headers.update({'Authorization': f'Bearer {token}'})
def login(self, username: str, password: str) -> str:
"""Login and get access token."""
response = self.session.post(f"{self.base_url}/api/auth/login",
json={'username': username, 'password': password})
if response.status_code == 200:
data = response.json()
self.token = data['access_token']
self.session.headers.update({'Authorization': f'Bearer {self.token}'})
return self.token
else:
raise Exception(f"Login failed: {response.json().get('error', 'Unknown error')}")
def upload_artifact(self, file_path: str, name: str, version: str,
artifact_type: str, org: str, repo: str,
description: str = "", tags: list = None) -> dict:
"""Upload an artifact to the repository."""
if not os.path.exists(file_path):
raise FileNotFoundError(f"File not found: {file_path}")
with open(file_path, 'rb') as f:
files = {'file': f}
data = {
'name': name,
'version': version,
'description': description,
'tags': json.dumps(tags or [])
}
response = self.session.post(
f"{self.base_url}/api/organizations/{org}/repositories/{repo}/artifacts",
files=files,
data=data
)
if response.status_code == 201:
return response.json()
else:
raise Exception(f"Upload failed: {response.json().get('error', 'Unknown error')}")
def create_organization(self, name: str, display_name: str = "",
description: str = "", is_public: bool = False) -> dict:
"""Create a new organization."""
data = {
'name': name,
'display_name': display_name or name,
'description': description,
'is_public': is_public
}
response = self.session.post(f"{self.base_url}/api/organizations", json=data)
if response.status_code == 201:
return response.json()
else:
raise Exception(f"Failed to create organization: {response.json().get('error', 'Unknown error')}")
def create_repository(self, org: str, name: str, artifact_type: str,
display_name: str = "", description: str = "",
is_public: bool = False) -> dict:
"""Create a new repository."""
data = {
'name': name,
'display_name': display_name or name,
'description': description,
'artifact_type': artifact_type,
'is_public': is_public
}
response = self.session.post(
f"{self.base_url}/api/organizations/{org}/repositories",
json=data
)
if response.status_code == 201:
return response.json()
else:
raise Exception(f"Failed to create repository: {response.json().get('error', 'Unknown error')}")
def list_artifacts(self, org: str, repo: str, search: str = "", page: int = 1) -> dict:
"""List artifacts in a repository."""
params = {'page': page}
if search:
params['search'] = search
response = self.session.get(
f"{self.base_url}/api/organizations/{org}/repositories/{repo}/artifacts",
params=params
)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to list artifacts: {response.json().get('error', 'Unknown error')}")
def get_stats(self) -> dict:
"""Get repository statistics."""
response = self.session.get(f"{self.base_url}/api/stats")
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to get stats: {response.json().get('error', 'Unknown error')}")
@click.group()
@click.option('--url', default='http://localhost:5000', help='Registry URL')
@click.option('--token', help='Access token')
@click.pass_context
def cli(ctx, url, token):
"""Centralized Artifact Repository Manager CLI"""
ctx.ensure_object(dict)
ctx.obj['client'] = ArtifactRegistryClient(url, token)
@cli.command()
@click.option('--username', prompt=True, help='Username')
@click.option('--password', prompt=True, hide_input=True, help='Password')
@click.pass_context
def login(ctx, username, password):
"""Login to the registry"""
try:
token = ctx.obj['client'].login(username, password)
click.echo(f"Login successful! Token: {token}")
# Save token to config file
config_dir = Path.home() / '.artifact-registry'
config_dir.mkdir(exist_ok=True)
config_file = config_dir / 'config.json'
config = {}
if config_file.exists():
with open(config_file) as f:
config = json.load(f)
config['token'] = token
config['url'] = ctx.obj['client'].base_url
with open(config_file, 'w') as f:
json.dump(config, f, indent=2)
click.echo(f"Token saved to {config_file}")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('name')
@click.option('--display-name', help='Display name')
@click.option('--description', help='Description')
@click.option('--public', is_flag=True, help='Make organization public')
@click.pass_context
def create_org(ctx, name, display_name, description, public):
"""Create a new organization"""
try:
result = ctx.obj['client'].create_organization(
name, display_name or '', description or '', public
)
click.echo(f"Organization '{result['name']}' created successfully!")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('org')
@click.argument('name')
@click.argument('type', type=click.Choice([
'docker', 'apt', 'npm', 'python', 'maven', 'nuget', 'helm',
'generic', 'ai_model', 'dataset', 'firmware', 'documentation'
]))
@click.option('--display-name', help='Display name')
@click.option('--description', help='Description')
@click.option('--public', is_flag=True, help='Make repository public')
@click.pass_context
def create_repo(ctx, org, name, type, display_name, description, public):
"""Create a new repository"""
try:
result = ctx.obj['client'].create_repository(
org, name, type, display_name or '', description or '', public
)
click.echo(f"Repository '{result['name']}' created successfully!")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('file_path', type=click.Path(exists=True))
@click.argument('org')
@click.argument('repo')
@click.option('--name', help='Artifact name (defaults to filename)')
@click.option('--version', default='1.0.0', help='Version')
@click.option('--description', help='Description')
@click.option('--tags', help='Comma-separated tags')
@click.pass_context
def upload(ctx, file_path, org, repo, name, version, description, tags):
"""Upload an artifact"""
try:
if not name:
name = Path(file_path).stem
tag_list = []
if tags:
tag_list = [tag.strip() for tag in tags.split(',')]
# Detect artifact type based on file extension
file_ext = Path(file_path).suffix.lower()
artifact_type = 'generic' # default
for atype, config in {
'docker': ['.tar', '.tar.gz', '.tar.xz'],
'apt': ['.deb'],
'npm': ['.tgz'],
'python': ['.whl', '.zip'],
'maven': ['.jar', '.war', '.ear'],
'ai_model': ['.pkl', '.h5', '.pb', '.onnx', '.pt', '.pth'],
'dataset': ['.csv', '.json', '.parquet'],
'firmware': ['.bin', '.hex', '.fw', '.rom'],
'documentation': ['.pdf', '.md', '.html']
}.items():
if file_ext in config:
artifact_type = atype
break
result = ctx.obj['client'].upload_artifact(
file_path, name, version, artifact_type, org, repo,
description or '', tag_list
)
click.echo(f"Artifact '{result['name']}' v{result['version']} uploaded successfully!")
click.echo(f"UUID: {result['uuid']}")
click.echo(f"Size: {result['file_size']} bytes")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('org')
@click.argument('repo')
@click.option('--search', help='Search term')
@click.option('--page', default=1, help='Page number')
@click.pass_context
def list_artifacts(ctx, org, repo, search, page):
"""List artifacts in a repository"""
try:
result = ctx.obj['client'].list_artifacts(org, repo, search or '', page)
if not result['artifacts']:
click.echo("No artifacts found.")
return
click.echo(f"\nArtifacts in {org}/{repo}:")
click.echo("-" * 80)
for artifact in result['artifacts']:
click.echo(f"Name: {artifact['name']}")
click.echo(f"Version: {artifact['version']}")
click.echo(f"UUID: {artifact['uuid']}")
click.echo(f"Size: {artifact['file_size']} bytes")
click.echo(f"Downloads: {artifact['download_count']}")
click.echo(f"Created: {artifact['created_at']}")
click.echo(f"Owner: {artifact['owner']}")
if artifact.get('tags'):
click.echo(f"Tags: {', '.join(artifact['tags'])}")
click.echo("-" * 80)
pagination = result['pagination']
click.echo(f"\nPage {pagination['page']} of {pagination['pages']} "
f"({pagination['total']} total artifacts)")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.pass_context
def stats(ctx):
"""Show repository statistics"""
try:
result = ctx.obj['client'].get_stats()
click.echo("\nπ Repository Statistics")
click.echo("=" * 50)
click.echo(f"Total Artifacts: {result['total_artifacts']}")
click.echo(f"Total Organizations: {result['total_organizations']}")
click.echo(f"Total Repositories: {result['total_repositories']}")
click.echo(f"Total Downloads: {result['total_downloads']}")
click.echo(f"Storage Usage: {result['storage_usage'] / (1024*1024*1024):.2f} GB")
if result['artifact_types']:
click.echo("\nπ¦ Artifact Types:")
for atype, info in result['artifact_types'].items():
click.echo(f" {info['name']}: {info['count']}")
if result['recent_uploads']:
click.echo("\nπ Recent Uploads:")
for artifact in result['recent_uploads'][:5]:
click.echo(f" {artifact['name']} v{artifact['version']} "
f"({artifact['type']}) by {artifact['owner']}")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('config_file', type=click.Path(exists=True))
@click.pass_context
def bulk_upload(ctx, config_file):
"""Bulk upload artifacts from configuration file"""
try:
with open(config_file) as f:
if config_file.endswith('.yaml') or config_file.endswith('.yml'):
config = yaml.safe_load(f)
else:
config = json.load(f)
for item in config.get('artifacts', []):
click.echo(f"Uploading {item['file_path']}...")
result = ctx.obj['client'].upload_artifact(
item['file_path'],
item['name'],
item['version'],
item['type'],
item['organization'],
item['repository'],
item.get('description', ''),
item.get('tags', [])
)
click.echo(f"β
{result['name']} v{result['version']} uploaded")
click.echo(f"\nπ Bulk upload completed!")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
if __name__ == '__main__':
# Try to load saved config
config_file = Path.home() / '.artifact-registry' / 'config.json'
if config_file.exists():
try:
with open(config_file) as f:
config = json.load(f)
# Update CLI context with saved config
import sys
if '--url' not in sys.argv and config.get('url'):
sys.argv.extend(['--url', config['url']])
if '--token' not in sys.argv and config.get('token'):
sys.argv.extend(['--token', config['token']])
except:
pass
cli()