-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathair-admin.py
More file actions
executable file
·209 lines (166 loc) · 6.1 KB
/
air-admin.py
File metadata and controls
executable file
·209 lines (166 loc) · 6.1 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
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
"""CLI tool for administrative operations on AIR reviews"""
import argparse
import configparser
import json
import sys
from pathlib import Path
import requests
# ANSI color codes
class Colors:
RESET = '\033[0m'
RED = '\033[91m'
GREEN = '\033[32m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
CYAN = '\033[96m'
BOLD = '\033[1m'
def colorize(text: str, color: str) -> str:
"""Add color to text if output is a TTY
Args:
text: Text to colorize
color: Color code
Returns:
Colored text if stdout is a TTY, otherwise plain text
"""
if sys.stdout.isatty():
return f"{color}{text}{Colors.RESET}"
return text
def load_config() -> configparser.ConfigParser:
"""Load configuration from ~/.air.conf
Returns:
ConfigParser instance (may be empty if file doesn't exist)
"""
config = configparser.ConfigParser()
config_path = Path.home() / '.air.conf'
if config_path.exists():
try:
config.read(config_path)
except Exception as e:
print(f"Warning: Failed to read config file {config_path}: {e}", file=sys.stderr)
return config
def delete_review(url: str, token: str, review_id: str) -> bool:
"""Delete a review (superuser only)
Args:
url: AIR service URL
token: API token (must be superuser)
review_id: Review ID to delete
Returns:
True if successful
"""
api_url = f"{url}/api/review"
params = {
'id': review_id,
'token': token,
}
try:
response = requests.delete(api_url, params=params, timeout=30)
response.raise_for_status()
return response.json().get('success', False)
except requests.exceptions.RequestException as e:
print(f"Error deleting review: {e}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"Error parsing response: {e}", file=sys.stderr)
sys.exit(1)
def create_token(url: str, token: str, name: str) -> str:
"""Create a new token (superuser only)
Args:
url: AIR service URL
token: API token (must be superuser)
name: Human-readable name for the new token
Returns:
The newly created token string
"""
api_url = f"{url}/api/token"
payload = {
'token': token,
'name': name,
}
try:
response = requests.post(api_url, json=payload, timeout=30)
response.raise_for_status()
data = response.json()
return data.get('token')
except requests.exceptions.RequestException as e:
print(f"Error creating token: {e}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"Error parsing response: {e}", file=sys.stderr)
sys.exit(1)
def main():
# Load config file first to get defaults
config = load_config()
parser = argparse.ArgumentParser(
description='Administrative operations for AIR reviews',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Delete a review
%(prog)s --url https://example.com/air --token mytoken --delete abc-123-def
# Create a new token
%(prog)s --url https://example.com/air --token mytoken --create-token "User Name"
Configuration file:
You can create ~/.air.conf to avoid repeating common parameters:
[air]
url = https://example.com/air
token = mytoken
Command-line arguments always override config file values.
"""
)
parser.add_argument('--url',
help='AIR service URL (e.g., https://example.com/air)')
parser.add_argument('--token',
help='API authentication token (required for admin operations)')
parser.add_argument('--delete', metavar='REVIEW_ID',
help='Delete the specified review (requires superuser token)')
parser.add_argument('--create-token', metavar='NAME',
help='Create a new token with the given name (requires superuser token)')
args = parser.parse_args()
# Fill in missing arguments from config file
if config.has_section('air'):
if args.url is None and config.has_option('air', 'url'):
args.url = config.get('air', 'url')
if args.token is None and config.has_option('air', 'token'):
args.token = config.get('air', 'token')
# Convert empty strings to None (allows unsetting config values)
if args.token == '':
args.token = None
# Validate that we have URL
if not args.url:
parser.error('--url is required (either via command-line or ~/.air.conf)')
args.url = args.url.rstrip('/')
# Check that at least one operation is specified
if not args.delete and not getattr(args, 'create_token', None):
parser.error('No operation specified. Use --delete REVIEW_ID or --create-token NAME')
# Handle --delete operation
if args.delete:
if not args.token:
parser.error('--delete requires --token (must be superuser)')
review_id = args.delete
print(f"Deleting review {review_id}...")
success = delete_review(args.url, args.token, review_id)
if success:
print(colorize(f"Review {review_id} deleted successfully", Colors.GREEN))
else:
print(colorize("Failed to delete review", Colors.RED), file=sys.stderr)
sys.exit(1)
return
# Handle --create-token operation
if getattr(args, 'create_token', None):
if not args.token:
parser.error('--create-token requires --token (must be superuser)')
name = args.create_token
print(f"Creating token for '{name}'...")
new_token = create_token(args.url, args.token, name)
if new_token:
print(colorize("Token created successfully", Colors.GREEN))
print(f"Name: {name}")
print(f"Token: {colorize(new_token, Colors.CYAN)}")
else:
print(colorize("Failed to create token", Colors.RED), file=sys.stderr)
sys.exit(1)
return
if __name__ == '__main__':
main()