Repository navigation
Expand file tree
/
Copy patherror.rs
More file actions
496 lines (452 loc) · 16.6 KB
/
Copy patherror.rs
File metadata and controls
496 lines (452 loc) · 16.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use serde_json::json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum GwsError {
#[error("{message}")]
Api {
code: u16,
message: String,
reason: String,
/// For `accessNotConfigured` errors: the GCP console URL to enable the API.
enable_url: Option<String>,
},
#[error("{0}")]
Validation(String),
#[error("{0}")]
Auth(String),
#[error("{0}")]
Discovery(String),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
/// Single source of truth for the exit code taxonomy: (code, reason, meaning).
///
/// Consumed by both [`exit_codes_json()`] (machine-readable) and
/// [`EXIT_CODE_DOCUMENTATION`] (human-readable help text).
pub const EXIT_CODE_TABLE: &[(i32, &str, &str)] = &[
(0, "success", "Command completed successfully"),
(
GwsError::EXIT_CODE_API,
"apiError",
"Remote API returned an error response",
),
(
GwsError::EXIT_CODE_AUTH,
"authError",
"Missing or invalid credentials",
),
(
GwsError::EXIT_CODE_VALIDATION,
"validationError",
"Bad input or wrong arguments",
),
(
GwsError::EXIT_CODE_DISCOVERY,
"discoveryError",
"Could not load API Discovery document",
),
(
GwsError::EXIT_CODE_OTHER,
"internalError",
"Unexpected or transient failure",
),
];
/// Human-readable exit code table derived from [`EXIT_CODE_TABLE`]: (code, meaning).
///
/// Used by `print_usage()` so the help text stays in sync without manual updates.
/// Defined as a macro-generated array so it remains a `const` while still being
/// derived programmatically from `EXIT_CODE_TABLE`.
macro_rules! exit_code_documentation {
() => {{
let mut out = [(0i32, ""); EXIT_CODE_TABLE.len()];
let mut i = 0;
while i < EXIT_CODE_TABLE.len() {
out[i] = (EXIT_CODE_TABLE[i].0, EXIT_CODE_TABLE[i].2);
i += 1;
}
out
}};
}
pub const EXIT_CODE_DOCUMENTATION: [(i32, &str); EXIT_CODE_TABLE.len()] =
exit_code_documentation!();
impl GwsError {
/// Exit code for [`GwsError::Api`] variants.
pub const EXIT_CODE_API: i32 = 1;
/// Exit code for [`GwsError::Auth`] variants.
pub const EXIT_CODE_AUTH: i32 = 2;
/// Exit code for [`GwsError::Validation`] variants.
pub const EXIT_CODE_VALIDATION: i32 = 3;
/// Exit code for [`GwsError::Discovery`] variants.
pub const EXIT_CODE_DISCOVERY: i32 = 4;
/// Exit code for [`GwsError::Other`] variants.
pub const EXIT_CODE_OTHER: i32 = 5;
/// Map each error variant to a stable, documented exit code.
///
/// | Code | Meaning |
/// |------|----------------------------------------------|
/// | 0 | Success (never returned here) |
/// | 1 | API error — Google returned an error response |
/// | 2 | Auth error — credentials missing or invalid |
/// | 3 | Validation error — bad arguments or input |
/// | 4 | Discovery error — could not fetch API schema |
/// | 5 | Internal error — unexpected failure |
pub fn exit_code(&self) -> i32 {
match self {
GwsError::Api { .. } => Self::EXIT_CODE_API,
GwsError::Auth(_) => Self::EXIT_CODE_AUTH,
GwsError::Validation(_) => Self::EXIT_CODE_VALIDATION,
GwsError::Discovery(_) => Self::EXIT_CODE_DISCOVERY,
GwsError::Other(_) => Self::EXIT_CODE_OTHER,
}
}
pub fn to_json(&self) -> serde_json::Value {
match self {
GwsError::Api {
code,
message,
reason,
enable_url,
} => {
let mut error_obj = json!({
"code": code,
"message": message,
"reason": reason,
});
// Include enable_url in JSON output when present (accessNotConfigured errors).
// This preserves machine-readable compatibility while adding new optional field.
if let Some(url) = enable_url {
error_obj["enable_url"] = json!(url);
}
json!({ "error": error_obj })
}
GwsError::Validation(msg) => json!({
"error": {
"code": 400,
"message": msg,
"reason": "validationError",
}
}),
GwsError::Auth(msg) => json!({
"error": {
"code": 401,
"message": msg,
"reason": "authError",
}
}),
GwsError::Discovery(msg) => json!({
"error": {
"code": 500,
"message": msg,
"reason": "discoveryError",
}
}),
GwsError::Other(e) => json!({
"error": {
"code": 500,
"message": format!("{e:#}"),
"reason": "internalError",
}
}),
}
}
}
/// Returns true when stderr is connected to an interactive terminal,
/// meaning ANSI color codes will be visible to the user.
fn stderr_supports_color() -> bool {
use std::io::IsTerminal;
std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none()
}
/// Wrap `text` in ANSI bold + the given color code, resetting afterwards.
/// Returns the plain text unchanged when stderr is not a TTY.
fn colorize(text: &str, ansi_color: &str) -> String {
if stderr_supports_color() {
format!("\x1b[1;{ansi_color}m{text}\x1b[0m")
} else {
text.to_string()
}
}
/// Strip terminal control characters from `text` to prevent escape-sequence
/// injection when printing untrusted content (API responses, user input) to
/// stderr. Preserves newlines and tabs for readability.
pub(crate) fn sanitize_for_terminal(text: &str) -> String {
text.chars()
.filter(|&c| {
if c == '\n' || c == '\t' {
return true;
}
!c.is_control()
})
.collect()
}
/// Format a colored error label for the given error variant.
fn error_label(err: &GwsError) -> String {
match err {
GwsError::Api { .. } => colorize("error[api]:", "31"), // red
GwsError::Auth(_) => colorize("error[auth]:", "31"), // red
GwsError::Validation(_) => colorize("error[validation]:", "33"), // yellow
GwsError::Discovery(_) => colorize("error[discovery]:", "31"), // red
GwsError::Other(_) => colorize("error:", "31"), // red
}
}
/// Returns the exit code taxonomy as a JSON value for `gws exit-codes` and schema output.
///
/// Derived from [`EXIT_CODE_TABLE`] — no duplication with the constants.
pub fn exit_codes_json() -> serde_json::Value {
let codes: Vec<serde_json::Value> = EXIT_CODE_TABLE
.iter()
.map(|(code, reason, meaning)| {
serde_json::json!({ "code": code, "reason": reason, "meaning": meaning })
})
.collect();
serde_json::json!({ "exit_codes": codes })
}
/// Formats any error as a JSON object and prints to stdout.
///
/// A human-readable colored label is printed to stderr when connected to a
/// TTY. For `accessNotConfigured` errors (HTTP 403, reason
/// `accessNotConfigured`), additional guidance is printed to stderr.
/// The JSON output on stdout is unchanged (machine-readable).
pub fn print_error_json(err: &GwsError) {
let json = err.to_json();
println!(
"{}",
serde_json::to_string_pretty(&json).unwrap_or_default()
);
// Print a colored summary to stderr. For accessNotConfigured errors,
// print specialized guidance instead of the generic message to avoid
// redundant output (the full API error already appears in the JSON).
if let GwsError::Api {
reason, enable_url, ..
} = err
{
if reason == "accessNotConfigured" {
eprintln!();
let hint = colorize("hint:", "36"); // cyan
eprintln!(
"{} {hint} API not enabled for your GCP project.",
error_label(err)
);
if let Some(url) = enable_url {
eprintln!(" Enable it at: {url}");
} else {
eprintln!(" Visit the GCP Console → APIs & Services → Library to enable the required API.");
}
eprintln!(" After enabling, wait a few seconds and retry your command.");
return;
}
}
eprintln!(
"{} {}",
error_label(err),
sanitize_for_terminal(&err.to_string())
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_exit_code_api() {
let err = GwsError::Api {
code: 404,
message: "Not Found".to_string(),
reason: "notFound".to_string(),
enable_url: None,
};
assert_eq!(err.exit_code(), GwsError::EXIT_CODE_API);
}
#[test]
fn test_exit_code_auth() {
assert_eq!(
GwsError::Auth("bad token".to_string()).exit_code(),
GwsError::EXIT_CODE_AUTH
);
}
#[test]
fn test_exit_code_validation() {
assert_eq!(
GwsError::Validation("missing arg".to_string()).exit_code(),
GwsError::EXIT_CODE_VALIDATION
);
}
#[test]
fn test_exit_code_discovery() {
assert_eq!(
GwsError::Discovery("fetch failed".to_string()).exit_code(),
GwsError::EXIT_CODE_DISCOVERY
);
}
#[test]
fn test_exit_code_other() {
assert_eq!(
GwsError::Other(anyhow::anyhow!("oops")).exit_code(),
GwsError::EXIT_CODE_OTHER
);
}
#[test]
fn test_exit_codes_are_distinct() {
// Ensure all named constants are unique (regression guard).
let codes = [
GwsError::EXIT_CODE_API,
GwsError::EXIT_CODE_AUTH,
GwsError::EXIT_CODE_VALIDATION,
GwsError::EXIT_CODE_DISCOVERY,
GwsError::EXIT_CODE_OTHER,
];
let unique: std::collections::HashSet<i32> = codes.iter().copied().collect();
assert_eq!(
unique.len(),
codes.len(),
"exit codes must be distinct: {codes:?}"
);
}
#[test]
fn test_error_to_json_api() {
let err = GwsError::Api {
code: 404,
message: "Not Found".to_string(),
reason: "notFound".to_string(),
enable_url: None,
};
let json = err.to_json();
assert_eq!(json["error"]["code"], 404);
assert_eq!(json["error"]["message"], "Not Found");
assert_eq!(json["error"]["reason"], "notFound");
assert!(json["error"]["enable_url"].is_null());
}
#[test]
fn test_error_to_json_validation() {
let err = GwsError::Validation("Invalid input".to_string());
let json = err.to_json();
assert_eq!(json["error"]["code"], 400);
assert_eq!(json["error"]["message"], "Invalid input");
assert_eq!(json["error"]["reason"], "validationError");
}
#[test]
fn test_error_to_json_auth() {
let err = GwsError::Auth("Token expired".to_string());
let json = err.to_json();
assert_eq!(json["error"]["code"], 401);
assert_eq!(json["error"]["message"], "Token expired");
assert_eq!(json["error"]["reason"], "authError");
}
#[test]
fn test_error_to_json_discovery() {
let err = GwsError::Discovery("Failed to fetch doc".to_string());
let json = err.to_json();
assert_eq!(json["error"]["code"], 500);
assert_eq!(json["error"]["message"], "Failed to fetch doc");
assert_eq!(json["error"]["reason"], "discoveryError");
}
#[test]
fn test_error_to_json_other() {
let err = GwsError::Other(anyhow::anyhow!("Something went wrong"));
let json = err.to_json();
assert_eq!(json["error"]["code"], 500);
assert_eq!(json["error"]["message"], "Something went wrong");
assert_eq!(json["error"]["reason"], "internalError");
}
#[test]
fn test_exit_codes_json_contains_all_codes() {
let val = exit_codes_json();
let codes: Vec<i64> = val["exit_codes"]
.as_array()
.unwrap()
.iter()
.map(|e| e["code"].as_i64().unwrap())
.collect();
for (expected, _, _) in EXIT_CODE_TABLE {
assert!(
codes.contains(&(*expected as i64)),
"missing code {expected}"
);
}
}
// --- accessNotConfigured tests ---
#[test]
fn test_error_to_json_access_not_configured_with_url() {
let err = GwsError::Api {
code: 403,
message: "Gmail API has not been used in project 549352339482 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=549352339482 then retry.".to_string(),
reason: "accessNotConfigured".to_string(),
enable_url: Some("https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=549352339482".to_string()),
};
let json = err.to_json();
assert_eq!(json["error"]["code"], 403);
assert_eq!(json["error"]["reason"], "accessNotConfigured");
assert_eq!(
json["error"]["enable_url"],
"https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=549352339482"
);
}
#[test]
fn test_error_to_json_access_not_configured_without_url() {
let err = GwsError::Api {
code: 403,
message: "API not enabled.".to_string(),
reason: "accessNotConfigured".to_string(),
enable_url: None,
};
let json = err.to_json();
assert_eq!(json["error"]["code"], 403);
assert_eq!(json["error"]["reason"], "accessNotConfigured");
// enable_url key should not appear in JSON when None
assert!(json["error"]["enable_url"].is_null());
}
// --- colored output tests ---
#[test]
#[serial_test::serial]
fn test_colorize_respects_no_color_env() {
// NO_COLOR is the de-facto standard for disabling colors.
// When set, colorize() should return the plain text.
std::env::set_var("NO_COLOR", "1");
let result = colorize("hello", "31");
std::env::remove_var("NO_COLOR");
assert_eq!(result, "hello");
}
#[test]
fn test_error_label_contains_variant_name() {
let api_err = GwsError::Api {
code: 400,
message: "bad".to_string(),
reason: "r".to_string(),
enable_url: None,
};
let label = error_label(&api_err);
assert!(label.contains("error[api]:"));
let auth_err = GwsError::Auth("fail".to_string());
assert!(error_label(&auth_err).contains("error[auth]:"));
let val_err = GwsError::Validation("bad input".to_string());
assert!(error_label(&val_err).contains("error[validation]:"));
let disc_err = GwsError::Discovery("missing".to_string());
assert!(error_label(&disc_err).contains("error[discovery]:"));
let other_err = GwsError::Other(anyhow::anyhow!("oops"));
assert!(error_label(&other_err).contains("error:"));
}
#[test]
fn test_sanitize_for_terminal_strips_control_chars() {
// ANSI escape sequence should be stripped
let input = "normal \x1b[31mred text\x1b[0m end";
let sanitized = sanitize_for_terminal(input);
assert_eq!(sanitized, "normal [31mred text[0m end");
assert!(!sanitized.contains('\x1b'));
// Newlines and tabs preserved
let input2 = "line1\nline2\ttab";
assert_eq!(sanitize_for_terminal(input2), "line1\nline2\ttab");
// Other control characters stripped
let input3 = "hello\x07bell\x08backspace";
assert_eq!(sanitize_for_terminal(input3), "hellobellbackspace");
}
}