@hasna/terminal 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/dist/cli.js +64 -16
  2. package/package.json +1 -1
  3. package/src/ai.ts +8 -0
  4. package/src/cli.tsx +57 -18
  5. package/src/output-processor.ts +6 -1
  6. package/src/output-store.ts +58 -12
  7. package/src/tool-profiles.ts +139 -0
  8. package/temp/rtk/.claude/agents/code-reviewer.md +0 -221
  9. package/temp/rtk/.claude/agents/debugger.md +0 -519
  10. package/temp/rtk/.claude/agents/rtk-testing-specialist.md +0 -461
  11. package/temp/rtk/.claude/agents/rust-rtk.md +0 -511
  12. package/temp/rtk/.claude/agents/technical-writer.md +0 -355
  13. package/temp/rtk/.claude/commands/diagnose.md +0 -352
  14. package/temp/rtk/.claude/commands/test-routing.md +0 -362
  15. package/temp/rtk/.claude/hooks/bash/pre-commit-format.sh +0 -16
  16. package/temp/rtk/.claude/hooks/rtk-rewrite.sh +0 -70
  17. package/temp/rtk/.claude/hooks/rtk-suggest.sh +0 -152
  18. package/temp/rtk/.claude/rules/cli-testing.md +0 -526
  19. package/temp/rtk/.claude/skills/issue-triage/SKILL.md +0 -348
  20. package/temp/rtk/.claude/skills/issue-triage/templates/issue-comment.md +0 -134
  21. package/temp/rtk/.claude/skills/performance.md +0 -435
  22. package/temp/rtk/.claude/skills/pr-triage/SKILL.md +0 -315
  23. package/temp/rtk/.claude/skills/pr-triage/templates/review-comment.md +0 -71
  24. package/temp/rtk/.claude/skills/repo-recap.md +0 -206
  25. package/temp/rtk/.claude/skills/rtk-tdd/SKILL.md +0 -78
  26. package/temp/rtk/.claude/skills/rtk-tdd/references/testing-patterns.md +0 -124
  27. package/temp/rtk/.claude/skills/security-guardian.md +0 -503
  28. package/temp/rtk/.claude/skills/ship.md +0 -404
  29. package/temp/rtk/.github/workflows/benchmark.yml +0 -34
  30. package/temp/rtk/.github/workflows/dco-check.yaml +0 -12
  31. package/temp/rtk/.github/workflows/release-please.yml +0 -51
  32. package/temp/rtk/.github/workflows/release.yml +0 -343
  33. package/temp/rtk/.github/workflows/security-check.yml +0 -135
  34. package/temp/rtk/.github/workflows/validate-docs.yml +0 -78
  35. package/temp/rtk/.release-please-manifest.json +0 -3
  36. package/temp/rtk/ARCHITECTURE.md +0 -1491
  37. package/temp/rtk/CHANGELOG.md +0 -640
  38. package/temp/rtk/CLAUDE.md +0 -605
  39. package/temp/rtk/CONTRIBUTING.md +0 -199
  40. package/temp/rtk/Cargo.lock +0 -1668
  41. package/temp/rtk/Cargo.toml +0 -64
  42. package/temp/rtk/Formula/rtk.rb +0 -43
  43. package/temp/rtk/INSTALL.md +0 -390
  44. package/temp/rtk/LICENSE +0 -21
  45. package/temp/rtk/README.md +0 -386
  46. package/temp/rtk/README_es.md +0 -159
  47. package/temp/rtk/README_fr.md +0 -197
  48. package/temp/rtk/README_ja.md +0 -159
  49. package/temp/rtk/README_ko.md +0 -159
  50. package/temp/rtk/README_zh.md +0 -167
  51. package/temp/rtk/ROADMAP.md +0 -15
  52. package/temp/rtk/SECURITY.md +0 -217
  53. package/temp/rtk/TEST_EXEC_TIME.md +0 -102
  54. package/temp/rtk/build.rs +0 -57
  55. package/temp/rtk/docs/AUDIT_GUIDE.md +0 -432
  56. package/temp/rtk/docs/FEATURES.md +0 -1410
  57. package/temp/rtk/docs/TROUBLESHOOTING.md +0 -309
  58. package/temp/rtk/docs/filter-workflow.md +0 -102
  59. package/temp/rtk/docs/images/gain-dashboard.jpg +0 -0
  60. package/temp/rtk/docs/tracking.md +0 -583
  61. package/temp/rtk/hooks/opencode-rtk.ts +0 -39
  62. package/temp/rtk/hooks/rtk-awareness.md +0 -29
  63. package/temp/rtk/hooks/rtk-rewrite.sh +0 -61
  64. package/temp/rtk/hooks/test-rtk-rewrite.sh +0 -442
  65. package/temp/rtk/install.sh +0 -124
  66. package/temp/rtk/release-please-config.json +0 -10
  67. package/temp/rtk/scripts/benchmark.sh +0 -592
  68. package/temp/rtk/scripts/check-installation.sh +0 -162
  69. package/temp/rtk/scripts/install-local.sh +0 -37
  70. package/temp/rtk/scripts/rtk-economics.sh +0 -137
  71. package/temp/rtk/scripts/test-all.sh +0 -561
  72. package/temp/rtk/scripts/test-aristote.sh +0 -227
  73. package/temp/rtk/scripts/test-tracking.sh +0 -79
  74. package/temp/rtk/scripts/update-readme-metrics.sh +0 -32
  75. package/temp/rtk/scripts/validate-docs.sh +0 -73
  76. package/temp/rtk/src/aws_cmd.rs +0 -880
  77. package/temp/rtk/src/binlog.rs +0 -1645
  78. package/temp/rtk/src/cargo_cmd.rs +0 -1727
  79. package/temp/rtk/src/cc_economics.rs +0 -1157
  80. package/temp/rtk/src/ccusage.rs +0 -340
  81. package/temp/rtk/src/config.rs +0 -187
  82. package/temp/rtk/src/container.rs +0 -855
  83. package/temp/rtk/src/curl_cmd.rs +0 -134
  84. package/temp/rtk/src/deps.rs +0 -268
  85. package/temp/rtk/src/diff_cmd.rs +0 -367
  86. package/temp/rtk/src/discover/mod.rs +0 -274
  87. package/temp/rtk/src/discover/provider.rs +0 -388
  88. package/temp/rtk/src/discover/registry.rs +0 -2022
  89. package/temp/rtk/src/discover/report.rs +0 -202
  90. package/temp/rtk/src/discover/rules.rs +0 -667
  91. package/temp/rtk/src/display_helpers.rs +0 -402
  92. package/temp/rtk/src/dotnet_cmd.rs +0 -1771
  93. package/temp/rtk/src/dotnet_format_report.rs +0 -133
  94. package/temp/rtk/src/dotnet_trx.rs +0 -593
  95. package/temp/rtk/src/env_cmd.rs +0 -204
  96. package/temp/rtk/src/filter.rs +0 -462
  97. package/temp/rtk/src/filters/README.md +0 -52
  98. package/temp/rtk/src/filters/ansible-playbook.toml +0 -34
  99. package/temp/rtk/src/filters/basedpyright.toml +0 -47
  100. package/temp/rtk/src/filters/biome.toml +0 -45
  101. package/temp/rtk/src/filters/brew-install.toml +0 -37
  102. package/temp/rtk/src/filters/composer-install.toml +0 -40
  103. package/temp/rtk/src/filters/df.toml +0 -16
  104. package/temp/rtk/src/filters/dotnet-build.toml +0 -64
  105. package/temp/rtk/src/filters/du.toml +0 -16
  106. package/temp/rtk/src/filters/fail2ban-client.toml +0 -15
  107. package/temp/rtk/src/filters/gcc.toml +0 -49
  108. package/temp/rtk/src/filters/gcloud.toml +0 -22
  109. package/temp/rtk/src/filters/hadolint.toml +0 -24
  110. package/temp/rtk/src/filters/helm.toml +0 -29
  111. package/temp/rtk/src/filters/iptables.toml +0 -27
  112. package/temp/rtk/src/filters/jj.toml +0 -28
  113. package/temp/rtk/src/filters/jq.toml +0 -24
  114. package/temp/rtk/src/filters/make.toml +0 -41
  115. package/temp/rtk/src/filters/markdownlint.toml +0 -24
  116. package/temp/rtk/src/filters/mix-compile.toml +0 -27
  117. package/temp/rtk/src/filters/mix-format.toml +0 -15
  118. package/temp/rtk/src/filters/mvn-build.toml +0 -44
  119. package/temp/rtk/src/filters/oxlint.toml +0 -43
  120. package/temp/rtk/src/filters/ping.toml +0 -63
  121. package/temp/rtk/src/filters/pio-run.toml +0 -40
  122. package/temp/rtk/src/filters/poetry-install.toml +0 -50
  123. package/temp/rtk/src/filters/pre-commit.toml +0 -35
  124. package/temp/rtk/src/filters/ps.toml +0 -16
  125. package/temp/rtk/src/filters/quarto-render.toml +0 -41
  126. package/temp/rtk/src/filters/rsync.toml +0 -48
  127. package/temp/rtk/src/filters/shellcheck.toml +0 -27
  128. package/temp/rtk/src/filters/shopify-theme.toml +0 -29
  129. package/temp/rtk/src/filters/skopeo.toml +0 -45
  130. package/temp/rtk/src/filters/sops.toml +0 -16
  131. package/temp/rtk/src/filters/ssh.toml +0 -44
  132. package/temp/rtk/src/filters/stat.toml +0 -34
  133. package/temp/rtk/src/filters/swift-build.toml +0 -41
  134. package/temp/rtk/src/filters/systemctl-status.toml +0 -33
  135. package/temp/rtk/src/filters/terraform-plan.toml +0 -35
  136. package/temp/rtk/src/filters/tofu-fmt.toml +0 -16
  137. package/temp/rtk/src/filters/tofu-init.toml +0 -38
  138. package/temp/rtk/src/filters/tofu-plan.toml +0 -35
  139. package/temp/rtk/src/filters/tofu-validate.toml +0 -17
  140. package/temp/rtk/src/filters/trunk-build.toml +0 -39
  141. package/temp/rtk/src/filters/ty.toml +0 -50
  142. package/temp/rtk/src/filters/uv-sync.toml +0 -37
  143. package/temp/rtk/src/filters/xcodebuild.toml +0 -99
  144. package/temp/rtk/src/filters/yamllint.toml +0 -25
  145. package/temp/rtk/src/find_cmd.rs +0 -598
  146. package/temp/rtk/src/format_cmd.rs +0 -386
  147. package/temp/rtk/src/gain.rs +0 -723
  148. package/temp/rtk/src/gh_cmd.rs +0 -1651
  149. package/temp/rtk/src/git.rs +0 -2012
  150. package/temp/rtk/src/go_cmd.rs +0 -592
  151. package/temp/rtk/src/golangci_cmd.rs +0 -254
  152. package/temp/rtk/src/grep_cmd.rs +0 -288
  153. package/temp/rtk/src/gt_cmd.rs +0 -810
  154. package/temp/rtk/src/hook_audit_cmd.rs +0 -283
  155. package/temp/rtk/src/hook_check.rs +0 -171
  156. package/temp/rtk/src/init.rs +0 -1859
  157. package/temp/rtk/src/integrity.rs +0 -537
  158. package/temp/rtk/src/json_cmd.rs +0 -231
  159. package/temp/rtk/src/learn/detector.rs +0 -628
  160. package/temp/rtk/src/learn/mod.rs +0 -119
  161. package/temp/rtk/src/learn/report.rs +0 -184
  162. package/temp/rtk/src/lint_cmd.rs +0 -694
  163. package/temp/rtk/src/local_llm.rs +0 -316
  164. package/temp/rtk/src/log_cmd.rs +0 -248
  165. package/temp/rtk/src/ls.rs +0 -324
  166. package/temp/rtk/src/main.rs +0 -2482
  167. package/temp/rtk/src/mypy_cmd.rs +0 -389
  168. package/temp/rtk/src/next_cmd.rs +0 -241
  169. package/temp/rtk/src/npm_cmd.rs +0 -236
  170. package/temp/rtk/src/parser/README.md +0 -267
  171. package/temp/rtk/src/parser/error.rs +0 -46
  172. package/temp/rtk/src/parser/formatter.rs +0 -336
  173. package/temp/rtk/src/parser/mod.rs +0 -311
  174. package/temp/rtk/src/parser/types.rs +0 -119
  175. package/temp/rtk/src/pip_cmd.rs +0 -302
  176. package/temp/rtk/src/playwright_cmd.rs +0 -479
  177. package/temp/rtk/src/pnpm_cmd.rs +0 -573
  178. package/temp/rtk/src/prettier_cmd.rs +0 -221
  179. package/temp/rtk/src/prisma_cmd.rs +0 -482
  180. package/temp/rtk/src/psql_cmd.rs +0 -382
  181. package/temp/rtk/src/pytest_cmd.rs +0 -384
  182. package/temp/rtk/src/read.rs +0 -217
  183. package/temp/rtk/src/rewrite_cmd.rs +0 -50
  184. package/temp/rtk/src/ruff_cmd.rs +0 -402
  185. package/temp/rtk/src/runner.rs +0 -271
  186. package/temp/rtk/src/summary.rs +0 -297
  187. package/temp/rtk/src/tee.rs +0 -405
  188. package/temp/rtk/src/telemetry.rs +0 -248
  189. package/temp/rtk/src/toml_filter.rs +0 -1655
  190. package/temp/rtk/src/tracking.rs +0 -1416
  191. package/temp/rtk/src/tree.rs +0 -209
  192. package/temp/rtk/src/tsc_cmd.rs +0 -259
  193. package/temp/rtk/src/utils.rs +0 -432
  194. package/temp/rtk/src/verify_cmd.rs +0 -47
  195. package/temp/rtk/src/vitest_cmd.rs +0 -385
  196. package/temp/rtk/src/wc_cmd.rs +0 -401
  197. package/temp/rtk/src/wget_cmd.rs +0 -260
  198. package/temp/rtk/tests/fixtures/dotnet/build_failed.txt +0 -11
  199. package/temp/rtk/tests/fixtures/dotnet/format_changes.json +0 -31
  200. package/temp/rtk/tests/fixtures/dotnet/format_empty.json +0 -1
  201. package/temp/rtk/tests/fixtures/dotnet/format_success.json +0 -12
  202. package/temp/rtk/tests/fixtures/dotnet/test_failed.txt +0 -18
@@ -1,880 +0,0 @@
1
- //! AWS CLI output compression.
2
- //!
3
- //! Replaces verbose `--output table`/`text` with JSON, then compresses.
4
- //! Specialized filters for high-frequency commands (STS, S3, EC2, ECS, RDS, CloudFormation).
5
-
6
- use crate::json_cmd;
7
- use crate::tracking;
8
- use crate::utils::{join_with_overflow, truncate_iso_date};
9
- use anyhow::{Context, Result};
10
- use serde_json::Value;
11
- use std::process::Command;
12
-
13
- const MAX_ITEMS: usize = 20;
14
- const JSON_COMPRESS_DEPTH: usize = 4;
15
-
16
- /// Run an AWS CLI command with token-optimized output
17
- pub fn run(subcommand: &str, args: &[String], verbose: u8) -> Result<()> {
18
- // Build the full sub-path: e.g. "sts" + ["get-caller-identity"] -> "sts get-caller-identity"
19
- let full_sub = if args.is_empty() {
20
- subcommand.to_string()
21
- } else {
22
- format!("{} {}", subcommand, args.join(" "))
23
- };
24
-
25
- // Route to specialized handlers
26
- match subcommand {
27
- "sts" if !args.is_empty() && args[0] == "get-caller-identity" => {
28
- run_sts_identity(&args[1..], verbose)
29
- }
30
- "s3" if !args.is_empty() && args[0] == "ls" => run_s3_ls(&args[1..], verbose),
31
- "ec2" if !args.is_empty() && args[0] == "describe-instances" => {
32
- run_ec2_describe(&args[1..], verbose)
33
- }
34
- "ecs" if !args.is_empty() && args[0] == "list-services" => {
35
- run_ecs_list_services(&args[1..], verbose)
36
- }
37
- "ecs" if !args.is_empty() && args[0] == "describe-services" => {
38
- run_ecs_describe_services(&args[1..], verbose)
39
- }
40
- "rds" if !args.is_empty() && args[0] == "describe-db-instances" => {
41
- run_rds_describe(&args[1..], verbose)
42
- }
43
- "cloudformation" if !args.is_empty() && args[0] == "list-stacks" => {
44
- run_cfn_list_stacks(&args[1..], verbose)
45
- }
46
- "cloudformation" if !args.is_empty() && args[0] == "describe-stacks" => {
47
- run_cfn_describe_stacks(&args[1..], verbose)
48
- }
49
- _ => run_generic(subcommand, args, verbose, &full_sub),
50
- }
51
- }
52
-
53
- /// Returns true for operations that return structured JSON (describe-*, list-*, get-*).
54
- /// Mutating/transfer operations (s3 cp, s3 sync, s3 mb, etc.) emit plain text progress
55
- /// and do not accept --output json, so we must not inject it for them.
56
- fn is_structured_operation(args: &[String]) -> bool {
57
- let op = args.first().map(|s| s.as_str()).unwrap_or("");
58
- op.starts_with("describe-") || op.starts_with("list-") || op.starts_with("get-")
59
- }
60
-
61
- /// Generic strategy: force --output json for structured ops, compress via json_cmd schema
62
- fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -> Result<()> {
63
- let timer = tracking::TimedExecution::start();
64
-
65
- let mut cmd = Command::new("aws");
66
- cmd.arg(subcommand);
67
-
68
- let mut has_output_flag = false;
69
- for arg in args {
70
- if arg == "--output" {
71
- has_output_flag = true;
72
- }
73
- cmd.arg(arg);
74
- }
75
-
76
- // Only inject --output json for structured read operations.
77
- // Mutating/transfer operations (s3 cp, s3 sync, s3 mb, cloudformation deploy…)
78
- // emit plain-text progress and reject --output json.
79
- if !has_output_flag && is_structured_operation(args) {
80
- cmd.args(["--output", "json"]);
81
- }
82
-
83
- if verbose > 0 {
84
- eprintln!("Running: aws {}", full_sub);
85
- }
86
-
87
- let output = cmd.output().context("Failed to run aws CLI")?;
88
- let raw = String::from_utf8_lossy(&output.stdout).to_string();
89
- let stderr = String::from_utf8_lossy(&output.stderr).to_string();
90
-
91
- if !output.status.success() {
92
- timer.track(
93
- &format!("aws {}", full_sub),
94
- &format!("rtk aws {}", full_sub),
95
- &stderr,
96
- &stderr,
97
- );
98
- eprintln!("{}", stderr.trim());
99
- std::process::exit(output.status.code().unwrap_or(1));
100
- }
101
-
102
- let filtered = match json_cmd::filter_json_string(&raw, JSON_COMPRESS_DEPTH) {
103
- Ok(schema) => {
104
- println!("{}", schema);
105
- schema
106
- }
107
- Err(_) => {
108
- // Fallback: print raw (maybe not JSON)
109
- print!("{}", raw);
110
- raw.clone()
111
- }
112
- };
113
-
114
- timer.track(
115
- &format!("aws {}", full_sub),
116
- &format!("rtk aws {}", full_sub),
117
- &raw,
118
- &filtered,
119
- );
120
-
121
- Ok(())
122
- }
123
-
124
- fn run_aws_json(
125
- sub_args: &[&str],
126
- extra_args: &[String],
127
- verbose: u8,
128
- ) -> Result<(String, String, std::process::ExitStatus)> {
129
- let mut cmd = Command::new("aws");
130
- for arg in sub_args {
131
- cmd.arg(arg);
132
- }
133
-
134
- // Replace --output table/text with --output json
135
- let mut skip_next = false;
136
- for arg in extra_args {
137
- if skip_next {
138
- skip_next = false;
139
- continue;
140
- }
141
- if arg == "--output" {
142
- skip_next = true;
143
- continue;
144
- }
145
- cmd.arg(arg);
146
- }
147
- cmd.args(["--output", "json"]);
148
-
149
- let cmd_desc = format!("aws {}", sub_args.join(" "));
150
- if verbose > 0 {
151
- eprintln!("Running: {}", cmd_desc);
152
- }
153
-
154
- let output = cmd
155
- .output()
156
- .context(format!("Failed to run {}", cmd_desc))?;
157
- let stdout = String::from_utf8_lossy(&output.stdout).to_string();
158
- let stderr = String::from_utf8_lossy(&output.stderr).to_string();
159
-
160
- if !output.status.success() {
161
- eprintln!("{}", stderr.trim());
162
- }
163
-
164
- Ok((stdout, stderr, output.status))
165
- }
166
-
167
- fn run_sts_identity(extra_args: &[String], verbose: u8) -> Result<()> {
168
- let timer = tracking::TimedExecution::start();
169
- let (raw, stderr, status) = run_aws_json(&["sts", "get-caller-identity"], extra_args, verbose)?;
170
-
171
- if !status.success() {
172
- timer.track(
173
- "aws sts get-caller-identity",
174
- "rtk aws sts get-caller-identity",
175
- &stderr,
176
- &stderr,
177
- );
178
- std::process::exit(status.code().unwrap_or(1));
179
- }
180
-
181
- let filtered = match filter_sts_identity(&raw) {
182
- Some(f) => f,
183
- None => raw.clone(),
184
- };
185
- println!("{}", filtered);
186
-
187
- timer.track(
188
- "aws sts get-caller-identity",
189
- "rtk aws sts get-caller-identity",
190
- &raw,
191
- &filtered,
192
- );
193
- Ok(())
194
- }
195
-
196
- fn run_s3_ls(extra_args: &[String], verbose: u8) -> Result<()> {
197
- let timer = tracking::TimedExecution::start();
198
-
199
- // s3 ls doesn't support --output json, run as-is and filter text
200
- let mut cmd = Command::new("aws");
201
- cmd.args(["s3", "ls"]);
202
- for arg in extra_args {
203
- cmd.arg(arg);
204
- }
205
-
206
- if verbose > 0 {
207
- eprintln!("Running: aws s3 ls {}", extra_args.join(" "));
208
- }
209
-
210
- let output = cmd.output().context("Failed to run aws s3 ls")?;
211
- let raw = String::from_utf8_lossy(&output.stdout).to_string();
212
-
213
- if !output.status.success() {
214
- let stderr = String::from_utf8_lossy(&output.stderr).to_string();
215
- timer.track("aws s3 ls", "rtk aws s3 ls", &stderr, &stderr);
216
- eprintln!("{}", stderr.trim());
217
- std::process::exit(output.status.code().unwrap_or(1));
218
- }
219
-
220
- let filtered = filter_s3_ls(&raw);
221
- println!("{}", filtered);
222
-
223
- timer.track("aws s3 ls", "rtk aws s3 ls", &raw, &filtered);
224
- Ok(())
225
- }
226
-
227
- fn run_ec2_describe(extra_args: &[String], verbose: u8) -> Result<()> {
228
- let timer = tracking::TimedExecution::start();
229
- let (raw, stderr, status) = run_aws_json(&["ec2", "describe-instances"], extra_args, verbose)?;
230
-
231
- if !status.success() {
232
- timer.track(
233
- "aws ec2 describe-instances",
234
- "rtk aws ec2 describe-instances",
235
- &stderr,
236
- &stderr,
237
- );
238
- std::process::exit(status.code().unwrap_or(1));
239
- }
240
-
241
- let filtered = match filter_ec2_instances(&raw) {
242
- Some(f) => f,
243
- None => raw.clone(),
244
- };
245
- println!("{}", filtered);
246
-
247
- timer.track(
248
- "aws ec2 describe-instances",
249
- "rtk aws ec2 describe-instances",
250
- &raw,
251
- &filtered,
252
- );
253
- Ok(())
254
- }
255
-
256
- fn run_ecs_list_services(extra_args: &[String], verbose: u8) -> Result<()> {
257
- let timer = tracking::TimedExecution::start();
258
- let (raw, stderr, status) = run_aws_json(&["ecs", "list-services"], extra_args, verbose)?;
259
-
260
- if !status.success() {
261
- timer.track(
262
- "aws ecs list-services",
263
- "rtk aws ecs list-services",
264
- &stderr,
265
- &stderr,
266
- );
267
- std::process::exit(status.code().unwrap_or(1));
268
- }
269
-
270
- let filtered = match filter_ecs_list_services(&raw) {
271
- Some(f) => f,
272
- None => raw.clone(),
273
- };
274
- println!("{}", filtered);
275
-
276
- timer.track(
277
- "aws ecs list-services",
278
- "rtk aws ecs list-services",
279
- &raw,
280
- &filtered,
281
- );
282
- Ok(())
283
- }
284
-
285
- fn run_ecs_describe_services(extra_args: &[String], verbose: u8) -> Result<()> {
286
- let timer = tracking::TimedExecution::start();
287
- let (raw, stderr, status) = run_aws_json(&["ecs", "describe-services"], extra_args, verbose)?;
288
-
289
- if !status.success() {
290
- timer.track(
291
- "aws ecs describe-services",
292
- "rtk aws ecs describe-services",
293
- &stderr,
294
- &stderr,
295
- );
296
- std::process::exit(status.code().unwrap_or(1));
297
- }
298
-
299
- let filtered = match filter_ecs_describe_services(&raw) {
300
- Some(f) => f,
301
- None => raw.clone(),
302
- };
303
- println!("{}", filtered);
304
-
305
- timer.track(
306
- "aws ecs describe-services",
307
- "rtk aws ecs describe-services",
308
- &raw,
309
- &filtered,
310
- );
311
- Ok(())
312
- }
313
-
314
- fn run_rds_describe(extra_args: &[String], verbose: u8) -> Result<()> {
315
- let timer = tracking::TimedExecution::start();
316
- let (raw, stderr, status) =
317
- run_aws_json(&["rds", "describe-db-instances"], extra_args, verbose)?;
318
-
319
- if !status.success() {
320
- timer.track(
321
- "aws rds describe-db-instances",
322
- "rtk aws rds describe-db-instances",
323
- &stderr,
324
- &stderr,
325
- );
326
- std::process::exit(status.code().unwrap_or(1));
327
- }
328
-
329
- let filtered = match filter_rds_instances(&raw) {
330
- Some(f) => f,
331
- None => raw.clone(),
332
- };
333
- println!("{}", filtered);
334
-
335
- timer.track(
336
- "aws rds describe-db-instances",
337
- "rtk aws rds describe-db-instances",
338
- &raw,
339
- &filtered,
340
- );
341
- Ok(())
342
- }
343
-
344
- fn run_cfn_list_stacks(extra_args: &[String], verbose: u8) -> Result<()> {
345
- let timer = tracking::TimedExecution::start();
346
- let (raw, stderr, status) =
347
- run_aws_json(&["cloudformation", "list-stacks"], extra_args, verbose)?;
348
-
349
- if !status.success() {
350
- timer.track(
351
- "aws cloudformation list-stacks",
352
- "rtk aws cloudformation list-stacks",
353
- &stderr,
354
- &stderr,
355
- );
356
- std::process::exit(status.code().unwrap_or(1));
357
- }
358
-
359
- let filtered = match filter_cfn_list_stacks(&raw) {
360
- Some(f) => f,
361
- None => raw.clone(),
362
- };
363
- println!("{}", filtered);
364
-
365
- timer.track(
366
- "aws cloudformation list-stacks",
367
- "rtk aws cloudformation list-stacks",
368
- &raw,
369
- &filtered,
370
- );
371
- Ok(())
372
- }
373
-
374
- fn run_cfn_describe_stacks(extra_args: &[String], verbose: u8) -> Result<()> {
375
- let timer = tracking::TimedExecution::start();
376
- let (raw, stderr, status) =
377
- run_aws_json(&["cloudformation", "describe-stacks"], extra_args, verbose)?;
378
-
379
- if !status.success() {
380
- timer.track(
381
- "aws cloudformation describe-stacks",
382
- "rtk aws cloudformation describe-stacks",
383
- &stderr,
384
- &stderr,
385
- );
386
- std::process::exit(status.code().unwrap_or(1));
387
- }
388
-
389
- let filtered = match filter_cfn_describe_stacks(&raw) {
390
- Some(f) => f,
391
- None => raw.clone(),
392
- };
393
- println!("{}", filtered);
394
-
395
- timer.track(
396
- "aws cloudformation describe-stacks",
397
- "rtk aws cloudformation describe-stacks",
398
- &raw,
399
- &filtered,
400
- );
401
- Ok(())
402
- }
403
-
404
- // --- Filter functions (all use serde_json::Value for resilience) ---
405
-
406
- fn filter_sts_identity(json_str: &str) -> Option<String> {
407
- let v: Value = serde_json::from_str(json_str).ok()?;
408
- let account = v["Account"].as_str().unwrap_or("?");
409
- let arn = v["Arn"].as_str().unwrap_or("?");
410
- Some(format!("AWS: {} {}", account, arn))
411
- }
412
-
413
- fn filter_s3_ls(output: &str) -> String {
414
- let lines: Vec<&str> = output.lines().collect();
415
- let total = lines.len();
416
- let mut result: Vec<&str> = lines.iter().take(MAX_ITEMS + 10).copied().collect();
417
-
418
- if total > MAX_ITEMS + 10 {
419
- result.truncate(MAX_ITEMS + 10);
420
- result.push(""); // will be replaced
421
- return format!(
422
- "{}\n... +{} more items",
423
- result[..result.len() - 1].join("\n"),
424
- total - MAX_ITEMS - 10
425
- );
426
- }
427
-
428
- result.join("\n")
429
- }
430
-
431
- fn filter_ec2_instances(json_str: &str) -> Option<String> {
432
- let v: Value = serde_json::from_str(json_str).ok()?;
433
- let reservations = v["Reservations"].as_array()?;
434
-
435
- let mut instances: Vec<String> = Vec::new();
436
- for res in reservations {
437
- if let Some(insts) = res["Instances"].as_array() {
438
- for inst in insts {
439
- let id = inst["InstanceId"].as_str().unwrap_or("?");
440
- let state = inst["State"]["Name"].as_str().unwrap_or("?");
441
- let itype = inst["InstanceType"].as_str().unwrap_or("?");
442
- let ip = inst["PrivateIpAddress"].as_str().unwrap_or("-");
443
-
444
- // Extract Name tag
445
- let name = inst["Tags"]
446
- .as_array()
447
- .and_then(|tags| tags.iter().find(|t| t["Key"].as_str() == Some("Name")))
448
- .and_then(|t| t["Value"].as_str())
449
- .unwrap_or("-");
450
-
451
- instances.push(format!("{} {} {} {} ({})", id, state, itype, ip, name));
452
- }
453
- }
454
- }
455
-
456
- let total = instances.len();
457
- let mut result = format!("EC2: {} instances\n", total);
458
-
459
- for inst in instances.iter().take(MAX_ITEMS) {
460
- result.push_str(&format!(" {}\n", inst));
461
- }
462
-
463
- if total > MAX_ITEMS {
464
- result.push_str(&format!(" ... +{} more\n", total - MAX_ITEMS));
465
- }
466
-
467
- Some(result.trim_end().to_string())
468
- }
469
-
470
- fn filter_ecs_list_services(json_str: &str) -> Option<String> {
471
- let v: Value = serde_json::from_str(json_str).ok()?;
472
- let arns = v["serviceArns"].as_array()?;
473
-
474
- let mut result = Vec::new();
475
- let total = arns.len();
476
-
477
- for arn in arns.iter().take(MAX_ITEMS) {
478
- let arn_str = arn.as_str().unwrap_or("?");
479
- // Extract short name from ARN: arn:aws:ecs:...:service/cluster/name -> name
480
- let short = arn_str.rsplit('/').next().unwrap_or(arn_str);
481
- result.push(short.to_string());
482
- }
483
-
484
- Some(join_with_overflow(&result, total, MAX_ITEMS, "services"))
485
- }
486
-
487
- fn filter_ecs_describe_services(json_str: &str) -> Option<String> {
488
- let v: Value = serde_json::from_str(json_str).ok()?;
489
- let services = v["services"].as_array()?;
490
-
491
- let mut result = Vec::new();
492
- let total = services.len();
493
-
494
- for svc in services.iter().take(MAX_ITEMS) {
495
- let name = svc["serviceName"].as_str().unwrap_or("?");
496
- let status = svc["status"].as_str().unwrap_or("?");
497
- let running = svc["runningCount"].as_i64().unwrap_or(0);
498
- let desired = svc["desiredCount"].as_i64().unwrap_or(0);
499
- let launch = svc["launchType"].as_str().unwrap_or("?");
500
- result.push(format!(
501
- "{} {} {}/{} ({})",
502
- name, status, running, desired, launch
503
- ));
504
- }
505
-
506
- Some(join_with_overflow(&result, total, MAX_ITEMS, "services"))
507
- }
508
-
509
- fn filter_rds_instances(json_str: &str) -> Option<String> {
510
- let v: Value = serde_json::from_str(json_str).ok()?;
511
- let dbs = v["DBInstances"].as_array()?;
512
-
513
- let mut result = Vec::new();
514
- let total = dbs.len();
515
-
516
- for db in dbs.iter().take(MAX_ITEMS) {
517
- let name = db["DBInstanceIdentifier"].as_str().unwrap_or("?");
518
- let engine = db["Engine"].as_str().unwrap_or("?");
519
- let version = db["EngineVersion"].as_str().unwrap_or("?");
520
- let class = db["DBInstanceClass"].as_str().unwrap_or("?");
521
- let status = db["DBInstanceStatus"].as_str().unwrap_or("?");
522
- result.push(format!(
523
- "{} {} {} {} {}",
524
- name, engine, version, class, status
525
- ));
526
- }
527
-
528
- Some(join_with_overflow(&result, total, MAX_ITEMS, "instances"))
529
- }
530
-
531
- fn filter_cfn_list_stacks(json_str: &str) -> Option<String> {
532
- let v: Value = serde_json::from_str(json_str).ok()?;
533
- let stacks = v["StackSummaries"].as_array()?;
534
-
535
- let mut result = Vec::new();
536
- let total = stacks.len();
537
-
538
- for stack in stacks.iter().take(MAX_ITEMS) {
539
- let name = stack["StackName"].as_str().unwrap_or("?");
540
- let status = stack["StackStatus"].as_str().unwrap_or("?");
541
- let date = stack["LastUpdatedTime"]
542
- .as_str()
543
- .or_else(|| stack["CreationTime"].as_str())
544
- .unwrap_or("?");
545
- result.push(format!("{} {} {}", name, status, truncate_iso_date(date)));
546
- }
547
-
548
- Some(join_with_overflow(&result, total, MAX_ITEMS, "stacks"))
549
- }
550
-
551
- fn filter_cfn_describe_stacks(json_str: &str) -> Option<String> {
552
- let v: Value = serde_json::from_str(json_str).ok()?;
553
- let stacks = v["Stacks"].as_array()?;
554
-
555
- let mut result = Vec::new();
556
- let total = stacks.len();
557
-
558
- for stack in stacks.iter().take(MAX_ITEMS) {
559
- let name = stack["StackName"].as_str().unwrap_or("?");
560
- let status = stack["StackStatus"].as_str().unwrap_or("?");
561
- let date = stack["LastUpdatedTime"]
562
- .as_str()
563
- .or_else(|| stack["CreationTime"].as_str())
564
- .unwrap_or("?");
565
- result.push(format!("{} {} {}", name, status, truncate_iso_date(date)));
566
-
567
- // Show outputs if present
568
- if let Some(outputs) = stack["Outputs"].as_array() {
569
- for out in outputs {
570
- let key = out["OutputKey"].as_str().unwrap_or("?");
571
- let val = out["OutputValue"].as_str().unwrap_or("?");
572
- result.push(format!(" {}={}", key, val));
573
- }
574
- }
575
- }
576
-
577
- Some(join_with_overflow(&result, total, MAX_ITEMS, "stacks"))
578
- }
579
-
580
- #[cfg(test)]
581
- mod tests {
582
- use super::*;
583
-
584
- #[test]
585
- fn test_snapshot_sts_identity() {
586
- let json = r#"{
587
- "UserId": "AIDAEXAMPLEUSERID1234",
588
- "Account": "123456789012",
589
- "Arn": "arn:aws:iam::123456789012:user/dev-user"
590
- }"#;
591
- let result = filter_sts_identity(json).unwrap();
592
- assert_eq!(
593
- result,
594
- "AWS: 123456789012 arn:aws:iam::123456789012:user/dev-user"
595
- );
596
- }
597
-
598
- #[test]
599
- fn test_snapshot_ec2_instances() {
600
- let json = r#"{"Reservations":[{"Instances":[{"InstanceId":"i-0a1b2c3d4e5f00001","InstanceType":"t3.micro","PrivateIpAddress":"10.0.1.10","State":{"Code":16,"Name":"running"},"Tags":[{"Key":"Name","Value":"web-server-1"}],"BlockDeviceMappings":[],"SecurityGroups":[]},{"InstanceId":"i-0a1b2c3d4e5f00002","InstanceType":"t3.large","PrivateIpAddress":"10.0.2.20","State":{"Code":80,"Name":"stopped"},"Tags":[{"Key":"Name","Value":"worker-1"}],"BlockDeviceMappings":[],"SecurityGroups":[]}]}]}"#;
601
- let result = filter_ec2_instances(json).unwrap();
602
- assert!(result.contains("EC2: 2 instances"));
603
- assert!(result.contains("i-0a1b2c3d4e5f00001 running t3.micro 10.0.1.10 (web-server-1)"));
604
- assert!(result.contains("i-0a1b2c3d4e5f00002 stopped t3.large 10.0.2.20 (worker-1)"));
605
- }
606
-
607
- #[test]
608
- fn test_filter_sts_identity() {
609
- let json = r#"{
610
- "UserId": "AIDAEXAMPLE",
611
- "Account": "123456789012",
612
- "Arn": "arn:aws:iam::123456789012:user/dev"
613
- }"#;
614
- let result = filter_sts_identity(json).unwrap();
615
- assert_eq!(
616
- result,
617
- "AWS: 123456789012 arn:aws:iam::123456789012:user/dev"
618
- );
619
- }
620
-
621
- #[test]
622
- fn test_filter_sts_identity_missing_fields() {
623
- let json = r#"{}"#;
624
- let result = filter_sts_identity(json).unwrap();
625
- assert_eq!(result, "AWS: ? ?");
626
- }
627
-
628
- #[test]
629
- fn test_filter_sts_identity_invalid_json() {
630
- let result = filter_sts_identity("not json");
631
- assert!(result.is_none());
632
- }
633
-
634
- #[test]
635
- fn test_filter_s3_ls_basic() {
636
- let output = "2024-01-01 bucket1\n2024-01-02 bucket2\n2024-01-03 bucket3\n";
637
- let result = filter_s3_ls(output);
638
- assert!(result.contains("bucket1"));
639
- assert!(result.contains("bucket3"));
640
- }
641
-
642
- #[test]
643
- fn test_filter_s3_ls_overflow() {
644
- let mut lines = Vec::new();
645
- for i in 1..=50 {
646
- lines.push(format!("2024-01-01 bucket{}", i));
647
- }
648
- let input = lines.join("\n");
649
- let result = filter_s3_ls(&input);
650
- assert!(result.contains("... +20 more items"));
651
- }
652
-
653
- #[test]
654
- fn test_filter_ec2_instances() {
655
- let json = r#"{
656
- "Reservations": [{
657
- "Instances": [{
658
- "InstanceId": "i-abc123",
659
- "State": {"Name": "running"},
660
- "InstanceType": "t3.micro",
661
- "PrivateIpAddress": "10.0.1.5",
662
- "Tags": [{"Key": "Name", "Value": "web-server"}]
663
- }, {
664
- "InstanceId": "i-def456",
665
- "State": {"Name": "stopped"},
666
- "InstanceType": "t3.large",
667
- "PrivateIpAddress": "10.0.1.6",
668
- "Tags": [{"Key": "Name", "Value": "worker"}]
669
- }]
670
- }]
671
- }"#;
672
- let result = filter_ec2_instances(json).unwrap();
673
- assert!(result.contains("EC2: 2 instances"));
674
- assert!(result.contains("i-abc123 running t3.micro 10.0.1.5 (web-server)"));
675
- assert!(result.contains("i-def456 stopped t3.large 10.0.1.6 (worker)"));
676
- }
677
-
678
- #[test]
679
- fn test_filter_ec2_no_name_tag() {
680
- let json = r#"{
681
- "Reservations": [{
682
- "Instances": [{
683
- "InstanceId": "i-abc123",
684
- "State": {"Name": "running"},
685
- "InstanceType": "t3.micro",
686
- "PrivateIpAddress": "10.0.1.5",
687
- "Tags": []
688
- }]
689
- }]
690
- }"#;
691
- let result = filter_ec2_instances(json).unwrap();
692
- assert!(result.contains("(-)"));
693
- }
694
-
695
- #[test]
696
- fn test_filter_ec2_invalid_json() {
697
- assert!(filter_ec2_instances("not json").is_none());
698
- }
699
-
700
- #[test]
701
- fn test_filter_ecs_list_services() {
702
- let json = r#"{
703
- "serviceArns": [
704
- "arn:aws:ecs:us-east-1:123:service/cluster/api-service",
705
- "arn:aws:ecs:us-east-1:123:service/cluster/worker-service"
706
- ]
707
- }"#;
708
- let result = filter_ecs_list_services(json).unwrap();
709
- assert!(result.contains("api-service"));
710
- assert!(result.contains("worker-service"));
711
- assert!(!result.contains("arn:aws"));
712
- }
713
-
714
- #[test]
715
- fn test_filter_ecs_describe_services() {
716
- let json = r#"{
717
- "services": [{
718
- "serviceName": "api",
719
- "status": "ACTIVE",
720
- "runningCount": 3,
721
- "desiredCount": 3,
722
- "launchType": "FARGATE"
723
- }]
724
- }"#;
725
- let result = filter_ecs_describe_services(json).unwrap();
726
- assert_eq!(result, "api ACTIVE 3/3 (FARGATE)");
727
- }
728
-
729
- #[test]
730
- fn test_filter_rds_instances() {
731
- let json = r#"{
732
- "DBInstances": [{
733
- "DBInstanceIdentifier": "mydb",
734
- "Engine": "postgres",
735
- "EngineVersion": "15.4",
736
- "DBInstanceClass": "db.t3.micro",
737
- "DBInstanceStatus": "available"
738
- }]
739
- }"#;
740
- let result = filter_rds_instances(json).unwrap();
741
- assert_eq!(result, "mydb postgres 15.4 db.t3.micro available");
742
- }
743
-
744
- #[test]
745
- fn test_filter_cfn_list_stacks() {
746
- let json = r#"{
747
- "StackSummaries": [{
748
- "StackName": "my-stack",
749
- "StackStatus": "CREATE_COMPLETE",
750
- "CreationTime": "2024-01-15T10:30:00Z"
751
- }, {
752
- "StackName": "other-stack",
753
- "StackStatus": "UPDATE_COMPLETE",
754
- "LastUpdatedTime": "2024-02-20T14:00:00Z",
755
- "CreationTime": "2024-01-01T00:00:00Z"
756
- }]
757
- }"#;
758
- let result = filter_cfn_list_stacks(json).unwrap();
759
- assert!(result.contains("my-stack CREATE_COMPLETE 2024-01-15"));
760
- assert!(result.contains("other-stack UPDATE_COMPLETE 2024-02-20"));
761
- }
762
-
763
- #[test]
764
- fn test_filter_cfn_describe_stacks_with_outputs() {
765
- let json = r#"{
766
- "Stacks": [{
767
- "StackName": "my-stack",
768
- "StackStatus": "CREATE_COMPLETE",
769
- "CreationTime": "2024-01-15T10:30:00Z",
770
- "Outputs": [
771
- {"OutputKey": "ApiUrl", "OutputValue": "https://api.example.com"},
772
- {"OutputKey": "BucketName", "OutputValue": "my-bucket"}
773
- ]
774
- }]
775
- }"#;
776
- let result = filter_cfn_describe_stacks(json).unwrap();
777
- assert!(result.contains("my-stack CREATE_COMPLETE 2024-01-15"));
778
- assert!(result.contains("ApiUrl=https://api.example.com"));
779
- assert!(result.contains("BucketName=my-bucket"));
780
- }
781
-
782
- #[test]
783
- fn test_filter_cfn_describe_stacks_no_outputs() {
784
- let json = r#"{
785
- "Stacks": [{
786
- "StackName": "my-stack",
787
- "StackStatus": "CREATE_COMPLETE",
788
- "CreationTime": "2024-01-15T10:30:00Z"
789
- }]
790
- }"#;
791
- let result = filter_cfn_describe_stacks(json).unwrap();
792
- assert!(result.contains("my-stack CREATE_COMPLETE 2024-01-15"));
793
- assert!(!result.contains("="));
794
- }
795
-
796
- fn count_tokens(text: &str) -> usize {
797
- text.split_whitespace().count()
798
- }
799
-
800
- #[test]
801
- fn test_ec2_token_savings() {
802
- let json = r#"{
803
- "Reservations": [{
804
- "ReservationId": "r-001",
805
- "OwnerId": "123456789012",
806
- "Groups": [],
807
- "Instances": [{
808
- "InstanceId": "i-0a1b2c3d4e5f00001",
809
- "ImageId": "ami-0abcdef1234567890",
810
- "InstanceType": "t3.micro",
811
- "KeyName": "my-key-pair",
812
- "LaunchTime": "2024-01-15T10:30:00+00:00",
813
- "Placement": { "AvailabilityZone": "us-east-1a", "GroupName": "", "Tenancy": "default" },
814
- "PrivateDnsName": "ip-10-0-1-10.ec2.internal",
815
- "PrivateIpAddress": "10.0.1.10",
816
- "PublicDnsName": "ec2-54-0-0-10.compute-1.amazonaws.com",
817
- "PublicIpAddress": "54.0.0.10",
818
- "State": { "Code": 16, "Name": "running" },
819
- "SubnetId": "subnet-0abc123def456001",
820
- "VpcId": "vpc-0abc123def456001",
821
- "Architecture": "x86_64",
822
- "BlockDeviceMappings": [{ "DeviceName": "/dev/xvda", "Ebs": { "AttachTime": "2024-01-15T10:30:05+00:00", "DeleteOnTermination": true, "Status": "attached", "VolumeId": "vol-001" } }],
823
- "EbsOptimized": false,
824
- "EnaSupport": true,
825
- "Hypervisor": "xen",
826
- "NetworkInterfaces": [{ "NetworkInterfaceId": "eni-001", "PrivateIpAddress": "10.0.1.10", "Status": "in-use" }],
827
- "RootDeviceName": "/dev/xvda",
828
- "RootDeviceType": "ebs",
829
- "SecurityGroups": [{ "GroupId": "sg-001", "GroupName": "web-server-sg" }],
830
- "SourceDestCheck": true,
831
- "Tags": [{ "Key": "Name", "Value": "web-server-1" }, { "Key": "Environment", "Value": "production" }, { "Key": "Team", "Value": "backend" }],
832
- "VirtualizationType": "hvm",
833
- "CpuOptions": { "CoreCount": 1, "ThreadsPerCore": 2 },
834
- "MetadataOptions": { "State": "applied", "HttpTokens": "required", "HttpEndpoint": "enabled" }
835
- }]
836
- }]
837
- }"#;
838
- let result = filter_ec2_instances(json).unwrap();
839
- let input_tokens = count_tokens(json);
840
- let output_tokens = count_tokens(&result);
841
- let savings = 100.0 - (output_tokens as f64 / input_tokens as f64 * 100.0);
842
- assert!(
843
- savings >= 60.0,
844
- "EC2 filter: expected >=60% savings, got {:.1}%",
845
- savings
846
- );
847
- }
848
-
849
- #[test]
850
- fn test_sts_token_savings() {
851
- let json = r#"{
852
- "UserId": "AIDAEXAMPLEUSERID1234",
853
- "Account": "123456789012",
854
- "Arn": "arn:aws:iam::123456789012:user/dev-user"
855
- }"#;
856
- let result = filter_sts_identity(json).unwrap();
857
- let input_tokens = count_tokens(json);
858
- let output_tokens = count_tokens(&result);
859
- let savings = 100.0 - (output_tokens as f64 / input_tokens as f64 * 100.0);
860
- assert!(
861
- savings >= 60.0,
862
- "STS identity filter: expected >=60% savings, got {:.1}%",
863
- savings
864
- );
865
- }
866
-
867
- #[test]
868
- fn test_rds_overflow() {
869
- let mut dbs = Vec::new();
870
- for i in 1..=25 {
871
- dbs.push(format!(
872
- r#"{{"DBInstanceIdentifier": "db-{}", "Engine": "postgres", "EngineVersion": "15.4", "DBInstanceClass": "db.t3.micro", "DBInstanceStatus": "available"}}"#,
873
- i
874
- ));
875
- }
876
- let json = format!(r#"{{"DBInstances": [{}]}}"#, dbs.join(","));
877
- let result = filter_rds_instances(&json).unwrap();
878
- assert!(result.contains("... +5 more instances"));
879
- }
880
- }