Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1927ed043c | ||
|
|
0476918cbe | ||
|
|
5ee23f778f | ||
|
|
ee927b372c | ||
|
|
3e8bb2eafd | ||
|
|
b53d776fce | ||
|
|
c2cc8f3c72 | ||
|
|
fab035e88c | ||
|
|
91b96bf335 | ||
|
|
f2a7306cae | ||
|
|
9b4b5a8e3f | ||
|
|
cf1a79005e | ||
|
|
945ee34066 | ||
|
|
1be358907e | ||
|
|
8b162fe647 | ||
|
|
810d7ffb63 | ||
|
|
ff8e490c85 | ||
|
|
b29344f68b | ||
|
|
0414020d57 | ||
|
|
5b57c4204a |
No files matched your search
@@ -0,0 +1,237 @@
|
||||
---
|
||||
description: >
|
||||
Triage complet RTK : exécute issue-triage + pr-triage en parallèle,
|
||||
puis croise les données pour détecter doubles couvertures, trous sécurité,
|
||||
P0 sans PR, et conflits internes. Sauvegarde dans claudedocs/RTK-YYYY-MM-DD.md.
|
||||
Args: "en"/"fr" pour la langue (défaut: fr), "save" pour forcer la sauvegarde.
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Write
|
||||
- Read
|
||||
- AskUserQuestion
|
||||
---
|
||||
|
||||
# /rtk-triage
|
||||
|
||||
Orchestrateur de triage RTK. Fusionne issue-triage + pr-triage et produit une analyse croisée.
|
||||
|
||||
---
|
||||
|
||||
## Quand utiliser
|
||||
|
||||
- Hebdomadaire ou avant chaque sprint
|
||||
- Quand le backlog PR/issues grossit rapidement
|
||||
- Pour identifier les doublons avant de reviewer
|
||||
|
||||
---
|
||||
|
||||
## Workflow en 4 phases
|
||||
|
||||
### Phase 0 — Préconditions
|
||||
|
||||
```bash
|
||||
git rev-parse --is-inside-work-tree
|
||||
gh auth status
|
||||
```
|
||||
|
||||
Vérifier que la date actuelle est connue (utiliser `date +%Y-%m-%d`).
|
||||
|
||||
---
|
||||
|
||||
### Phase 1 — Data gathering (parallèle)
|
||||
|
||||
Lancer les deux collectes simultanément :
|
||||
|
||||
**Issues** :
|
||||
```bash
|
||||
gh repo view --json nameWithOwner -q .nameWithOwner
|
||||
|
||||
gh issue list --state open --limit 150 \
|
||||
--json number,title,author,createdAt,updatedAt,labels,assignees,body
|
||||
|
||||
gh issue list --state closed --limit 20 \
|
||||
--json number,title,labels,closedAt
|
||||
|
||||
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
|
||||
```
|
||||
|
||||
**PRs** :
|
||||
```bash
|
||||
gh pr list --state open --limit 60 \
|
||||
--json number,title,author,createdAt,updatedAt,additions,deletions,changedFiles,isDraft,mergeable,reviewDecision,statusCheckRollup,body
|
||||
|
||||
# Pour chaque PR, récupérer les fichiers modifiés (nécessaire pour overlap detection)
|
||||
# Prioriser les PRs candidates (même domaine, même auteur)
|
||||
gh pr view {num} --json files --jq '[.files[].path] | join(",")'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 2 — Triage individuel
|
||||
|
||||
Exécuter les analyses de `/issue-triage` et `/pr-triage` séparément (même logique que les skills individuels) pour produire :
|
||||
|
||||
**Issues** :
|
||||
- Catégorisation (Bug/Feature/Enhancement/Question/Duplicate)
|
||||
- Risque (Rouge/Jaune/Vert)
|
||||
- Staleness (>30j)
|
||||
- Map `issue_number → [PR numbers]` via scan `fixes #N`, `closes #N`, `resolves #N`
|
||||
|
||||
**PRs** :
|
||||
- Taille (XS/S/M/L/XL)
|
||||
- CI status (clean/dirty)
|
||||
- Nos PRs vs externes
|
||||
- Overlaps (>50% fichiers communs entre 2 PRs)
|
||||
- Clusters (auteur avec 3+ PRs)
|
||||
|
||||
Afficher les tableaux standards de chaque skill (voir SKILL.md de issue-triage et pr-triage pour le format exact).
|
||||
|
||||
---
|
||||
|
||||
### Phase 3 — Analyse croisée (cœur de ce skill)
|
||||
|
||||
C'est ici que ce skill apporte de la valeur au-delà des deux skills individuels.
|
||||
|
||||
#### 3.1 Double couverture — 2 PRs pour 1 issue
|
||||
|
||||
Pour chaque issue liée à ≥2 PRs (via scan des bodies + overlap fichiers) :
|
||||
|
||||
| Issue | PR1 (infos) | PR2 (infos) | Verdict recommandé |
|
||||
|-------|-------------|-------------|-------------------|
|
||||
| #N (titre) | PR#X — auteur, taille, CI | PR#Y — auteur, taille, CI | Garder la plus ciblée. Fermer/coordonner l'autre |
|
||||
|
||||
Règle de verdict :
|
||||
- Préférer la plus petite (XS < S < M) si même scope
|
||||
- Préférer CI clean sur CI dirty
|
||||
- Préférer "nos PRs" si l'une est interne
|
||||
- Si overlap de fichiers >80% → conflit quasi-certain, signaler
|
||||
|
||||
#### 3.2 Trous de couverture sécurité
|
||||
|
||||
Pour chaque issue rouge (#640-type security review) :
|
||||
- Lister les sous-findings mentionnés dans le body
|
||||
- Croiser avec les PRs existantes (mots-clés dans titre/body)
|
||||
- Identifier les findings sans PR
|
||||
|
||||
Format :
|
||||
```
|
||||
## Issue #N — security review (finding par finding)
|
||||
| Finding | PR associée | Status |
|
||||
|---------|-------------|--------|
|
||||
| Description finding 1 | PR#X | En review |
|
||||
| **Description finding critique** | **AUCUNE** | ⚠️ Trou |
|
||||
```
|
||||
|
||||
#### 3.3 P0/P1 bugs sans PR
|
||||
|
||||
Issues labelisées P0 ou P1 (ou mots-clés : "crash", "truncat", "cap", "hardcoded") sans aucune PR liée.
|
||||
|
||||
Format :
|
||||
```
|
||||
## Bugs critiques sans PR
|
||||
| Issue | Titre | Pattern commun | Effort estimé |
|
||||
|-------|-------|----------------|---------------|
|
||||
```
|
||||
|
||||
Chercher un pattern commun (ex: "cap hardcodé", "exit code perdu") — si 3+ bugs partagent un pattern, suggérer un sprint groupé.
|
||||
|
||||
#### 3.4 Nos PRs dirty — causes probables
|
||||
|
||||
Pour chaque PR interne avec CI dirty ou CONFLICTING :
|
||||
- Vérifier si un autre PR touche les mêmes fichiers
|
||||
- Vérifier si un merge récent sur develop peut expliquer le conflit
|
||||
- Recommander : rebase, fermeture, ou attente
|
||||
|
||||
Format :
|
||||
```
|
||||
## Nos PRs dirty
|
||||
| PR | Issue(s) | Cause probable | Action |
|
||||
|----|----------|----------------|--------|
|
||||
```
|
||||
|
||||
#### 3.5 PRs sans issue trackée
|
||||
|
||||
PRs internes sans `fixes #N` dans le body — signaler pour traçabilité.
|
||||
|
||||
---
|
||||
|
||||
### Phase 4 — Output final
|
||||
|
||||
#### Afficher l'analyse croisée complète (sections 3.1 → 3.5)
|
||||
|
||||
Puis afficher le résumé chiffré :
|
||||
|
||||
```
|
||||
## Résumé chiffré — YYYY-MM-DD
|
||||
|
||||
| Catégorie | Count |
|
||||
|-----------|-------|
|
||||
| PRs prêtes à merger (nos) | N |
|
||||
| Quick wins externes | N |
|
||||
| Double couverture (conflicts) | N paires |
|
||||
| P0/P1 bugs sans PR | N |
|
||||
| Security findings sans PR | N |
|
||||
| Nos PRs dirty à rebaser | N |
|
||||
| PRs à fermer (recommandé) | N |
|
||||
```
|
||||
|
||||
#### Sauvegarder dans claudedocs
|
||||
|
||||
```bash
|
||||
date +%Y-%m-%d # Pour construire le nom de fichier
|
||||
```
|
||||
|
||||
Sauvegarder dans `claudedocs/RTK-YYYY-MM-DD.md` avec :
|
||||
- Les tableaux de triage issues + PRs (Phase 2)
|
||||
- L'analyse croisée complète (Phase 3)
|
||||
- Le résumé chiffré
|
||||
|
||||
Confirmer : `Sauvegardé dans claudedocs/RTK-YYYY-MM-DD.md`
|
||||
|
||||
---
|
||||
|
||||
## Format du fichier sauvegardé
|
||||
|
||||
```markdown
|
||||
# RTK Triage — YYYY-MM-DD
|
||||
|
||||
Croisement issues × PRs. {N} PRs ouvertes, {N} issues ouvertes.
|
||||
|
||||
---
|
||||
|
||||
## 1. Double couverture
|
||||
...
|
||||
|
||||
## 2. Trous sécurité
|
||||
...
|
||||
|
||||
## 3. P0/P1 sans PR
|
||||
...
|
||||
|
||||
## 4. Nos PRs dirty
|
||||
...
|
||||
|
||||
## 5. Nos PRs prêtes à merger
|
||||
...
|
||||
|
||||
## 6. Quick wins externes
|
||||
...
|
||||
|
||||
## 7. Actions prioritaires
|
||||
(liste ordonnée par impact/urgence)
|
||||
|
||||
---
|
||||
|
||||
## Résumé chiffré
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Règles
|
||||
|
||||
- Langue : argument `en`/`fr`. Défaut : `fr`. Les commentaires GitHub restent toujours en anglais.
|
||||
- Ne jamais poster de commentaires GitHub sans validation utilisateur (AskUserQuestion).
|
||||
- Si >150 issues ou >60 PRs : prévenir l'utilisateur, proposer de filtrer par label ou date.
|
||||
- L'analyse croisée (Phase 3) est toujours exécutée — c'est la valeur ajoutée de ce skill.
|
||||
- Le fichier claudedocs est sauvegardé automatiquement sauf si l'utilisateur dit "no save".
|
||||
@@ -0,0 +1,13 @@
|
||||
## Summary
|
||||
<!-- What does this PR do? Keep it short (1-3 bullet points). -->
|
||||
|
||||
-
|
||||
|
||||
## Test plan
|
||||
<!-- How did you verify this works? -->
|
||||
|
||||
- [ ] `cargo fmt --all && cargo clippy --all-targets && cargo test`
|
||||
- [ ] Manual testing: `rtk <command>` output inspected
|
||||
|
||||
> **Important:** All PRs must target the `develop` branch (not `master`).
|
||||
> See [CONTRIBUTING.md](../blob/master/CONTRIBUTING.md) for details.
|
||||
@@ -0,0 +1,43 @@
|
||||
name: PR Target Branch Check
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, edited]
|
||||
|
||||
jobs:
|
||||
check-target:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip develop→master PRs (maintainer releases)
|
||||
if: >-
|
||||
github.event.pull_request.base.ref == 'master' &&
|
||||
github.event.pull_request.head.ref != 'develop'
|
||||
steps:
|
||||
- name: Add wrong-base label
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
|
||||
// Add label
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: ['wrong-base']
|
||||
});
|
||||
|
||||
// Post comment
|
||||
const body = `👋 Thanks for the PR! It looks like this targets \`master\`, but all PRs should target the **\`develop\`** branch.
|
||||
|
||||
Please update the base branch:
|
||||
1. Click **Edit** at the top right of this PR
|
||||
2. Change the base branch from \`master\` to \`develop\`
|
||||
|
||||
See [CONTRIBUTING.md](https://github.com/${context.repo.owner}/${context.repo.repo}/blob/master/CONTRIBUTING.md) for details.`;
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
body: body
|
||||
});
|
||||
+1
-1
@@ -293,7 +293,7 @@ SHARED utils.rs Helpers N/A ✓
|
||||
tee.rs Full output recovery N/A ✓
|
||||
```
|
||||
|
||||
**Total: 60 modules** (38 command modules + 22 infrastructure modules)
|
||||
**Total: 66 modules** (44 command modules + 22 infrastructure modules)
|
||||
|
||||
### Module Count Breakdown
|
||||
|
||||
|
||||
+68
-30
@@ -40,6 +40,11 @@ fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<Str
|
||||
return args.to_vec();
|
||||
}
|
||||
|
||||
// If args already contain `--` (Clap preserved it), no restoration needed
|
||||
if args.iter().any(|a| a == "--") {
|
||||
return args.to_vec();
|
||||
}
|
||||
|
||||
// Find `--` in the original command line
|
||||
let sep_pos = match raw_args.iter().position(|a| a == "--") {
|
||||
Some(pos) => pos,
|
||||
@@ -259,7 +264,7 @@ fn filter_cargo_install(output: &str) -> String {
|
||||
// Already installed / up to date
|
||||
if already_installed {
|
||||
let info = ignored_line.split('`').nth(1).unwrap_or(&ignored_line);
|
||||
return format!("✓ cargo install: {} already installed", info);
|
||||
return format!("cargo install: {} already installed", info);
|
||||
}
|
||||
|
||||
// Errors
|
||||
@@ -308,10 +313,7 @@ fn filter_cargo_install(output: &str) -> String {
|
||||
// Success
|
||||
let crate_info = format_crate_info(&installed_crate, &installed_version, "package");
|
||||
|
||||
let mut result = format!(
|
||||
"✓ cargo install ({}, {} deps compiled)",
|
||||
crate_info, compiled
|
||||
);
|
||||
let mut result = format!("cargo install ({}, {} deps compiled)", crate_info, compiled);
|
||||
|
||||
for line in &replaced_lines {
|
||||
result.push_str(&format!("\n {}", line));
|
||||
@@ -497,7 +499,7 @@ fn filter_cargo_nextest(output: &str) -> String {
|
||||
} else {
|
||||
format!("{}, {}s", binary_text, duration)
|
||||
};
|
||||
return format!("✓ cargo nextest: {} ({})", parts.join(", "), meta);
|
||||
return format!("cargo nextest: {} ({})", parts.join(", "), meta);
|
||||
}
|
||||
|
||||
// With failures - show failure details then summary
|
||||
@@ -620,7 +622,7 @@ fn filter_cargo_build(output: &str) -> String {
|
||||
}
|
||||
|
||||
if error_count == 0 && warnings == 0 {
|
||||
return format!("✓ cargo build ({} crates compiled)", compiled);
|
||||
return format!("cargo build ({} crates compiled)", compiled);
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -734,11 +736,11 @@ impl AggregatedTestResult {
|
||||
|
||||
if self.has_duration {
|
||||
format!(
|
||||
"✓ cargo test: {} ({}, {:.2}s)",
|
||||
"cargo test: {} ({}, {:.2}s)",
|
||||
counts, suite_text, self.duration_secs
|
||||
)
|
||||
} else {
|
||||
format!("✓ cargo test: {} ({})", counts, suite_text)
|
||||
format!("cargo test: {} ({})", counts, suite_text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,7 +828,7 @@ fn filter_cargo_test(output: &str) -> String {
|
||||
|
||||
// Fallback: use original behavior if regex failed
|
||||
for line in &summary_lines {
|
||||
result.push_str(&format!("✓ {}\n", line));
|
||||
result.push_str(&format!("{}\n", line));
|
||||
}
|
||||
return result.trim().to_string();
|
||||
}
|
||||
@@ -926,7 +928,7 @@ fn filter_cargo_clippy(output: &str) -> String {
|
||||
}
|
||||
|
||||
if error_count == 0 && warning_count == 0 {
|
||||
return "✓ cargo clippy: No issues found".to_string();
|
||||
return "cargo clippy: No issues found".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -1054,6 +1056,42 @@ mod tests {
|
||||
assert_eq!(result, vec!["--", "-D", "warnings"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_double_dash_clippy_with_package_flags() {
|
||||
// rtk cargo clippy -p my-service -p my-crate -- -D warnings
|
||||
// Clap with trailing_var_arg preserves "--" when args precede it
|
||||
// → clap gives ["-p", "my-service", "-p", "my-crate", "--", "-D", "warnings"]
|
||||
let args: Vec<String> = vec![
|
||||
"-p".into(),
|
||||
"my-service".into(),
|
||||
"-p".into(),
|
||||
"my-crate".into(),
|
||||
"--".into(),
|
||||
"-D".into(),
|
||||
"warnings".into(),
|
||||
];
|
||||
let raw = vec![
|
||||
"rtk".into(),
|
||||
"cargo".into(),
|
||||
"clippy".into(),
|
||||
"-p".into(),
|
||||
"my-service".into(),
|
||||
"-p".into(),
|
||||
"my-crate".into(),
|
||||
"--".into(),
|
||||
"-D".into(),
|
||||
"warnings".into(),
|
||||
];
|
||||
let result = restore_double_dash_with_raw(&args, &raw);
|
||||
// Should NOT double the "--"
|
||||
assert_eq!(
|
||||
result,
|
||||
vec!["-p", "my-service", "-p", "my-crate", "--", "-D", "warnings"]
|
||||
);
|
||||
// Verify only one "--" exists
|
||||
assert_eq!(result.iter().filter(|a| *a == "--").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_cargo_build_success() {
|
||||
let output = r#" Compiling libc v0.2.153
|
||||
@@ -1062,7 +1100,7 @@ mod tests {
|
||||
Finished dev [unoptimized + debuginfo] target(s) in 15.23s
|
||||
"#;
|
||||
let result = filter_cargo_build(output);
|
||||
assert!(result.contains("✓ cargo build"));
|
||||
assert!(result.contains("cargo build"));
|
||||
assert!(result.contains("3 crates compiled"));
|
||||
}
|
||||
|
||||
@@ -1098,7 +1136,7 @@ test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
|
||||
"#;
|
||||
let result = filter_cargo_test(output);
|
||||
assert!(
|
||||
result.contains("✓ cargo test: 15 passed (1 suite, 0.01s)"),
|
||||
result.contains("cargo test: 15 passed (1 suite, 0.01s)"),
|
||||
"Expected compact format, got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1155,7 +1193,7 @@ test result: ok. 32 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
|
||||
"#;
|
||||
let result = filter_cargo_test(output);
|
||||
assert!(
|
||||
result.contains("✓ cargo test: 137 passed (4 suites, 1.45s)"),
|
||||
result.contains("cargo test: 137 passed (4 suites, 1.45s)"),
|
||||
"Expected aggregated format, got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1219,7 +1257,7 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
|
||||
"#;
|
||||
let result = filter_cargo_test(output);
|
||||
assert!(
|
||||
result.contains("✓ cargo test: 0 passed (3 suites, 0.00s)"),
|
||||
result.contains("cargo test: 0 passed (3 suites, 0.00s)"),
|
||||
"Expected compact format for zero tests, got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1239,7 +1277,7 @@ test result: ok. 18 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; fin
|
||||
"#;
|
||||
let result = filter_cargo_test(output);
|
||||
assert!(
|
||||
result.contains("✓ cargo test: 63 passed, 5 ignored, 2 filtered out (2 suites, 0.70s)"),
|
||||
result.contains("cargo test: 63 passed, 5 ignored, 2 filtered out (2 suites, 0.70s)"),
|
||||
"Expected compact format with ignored and filtered, got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1254,7 +1292,7 @@ test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
|
||||
"#;
|
||||
let result = filter_cargo_test(output);
|
||||
assert!(
|
||||
result.contains("✓ cargo test: 15 passed (1 suite, 0.01s)"),
|
||||
result.contains("cargo test: 15 passed (1 suite, 0.01s)"),
|
||||
"Expected singular 'suite', got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1268,9 +1306,9 @@ running 15 tests
|
||||
test result: MALFORMED LINE WITHOUT PROPER FORMAT
|
||||
"#;
|
||||
let result = filter_cargo_test(output);
|
||||
// Should fallback to original behavior (show line with checkmark)
|
||||
// Should fallback to original behavior (show line without checkmark)
|
||||
assert!(
|
||||
result.contains("✓ test result: MALFORMED"),
|
||||
result.contains("test result: MALFORMED"),
|
||||
"Expected fallback format, got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1282,7 +1320,7 @@ test result: MALFORMED LINE WITHOUT PROPER FORMAT
|
||||
Finished dev [unoptimized + debuginfo] target(s) in 1.53s
|
||||
"#;
|
||||
let result = filter_cargo_clippy(output);
|
||||
assert!(result.contains("✓ cargo clippy: No issues found"));
|
||||
assert!(result.contains("cargo clippy: No issues found"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1325,7 +1363,7 @@ warning: `rtk` (bin) generated 2 warnings
|
||||
Replaced package `rtk v0.9.4` with `rtk v0.11.0` (/Users/user/.cargo/bin/rtk)
|
||||
"#;
|
||||
let result = filter_cargo_install(output);
|
||||
assert!(result.contains("✓ cargo install"), "got: {}", result);
|
||||
assert!(result.contains("cargo install"), "got: {}", result);
|
||||
assert!(result.contains("rtk v0.11.0"), "got: {}", result);
|
||||
assert!(result.contains("5 deps compiled"), "got: {}", result);
|
||||
assert!(result.contains("Replaced"), "got: {}", result);
|
||||
@@ -1342,7 +1380,7 @@ warning: `rtk` (bin) generated 2 warnings
|
||||
Replaced package `rtk v0.9.4` with `rtk v0.11.0` (/Users/user/.cargo/bin/rtk)
|
||||
"#;
|
||||
let result = filter_cargo_install(output);
|
||||
assert!(result.contains("✓ cargo install"), "got: {}", result);
|
||||
assert!(result.contains("cargo install"), "got: {}", result);
|
||||
assert!(result.contains("Replacing"), "got: {}", result);
|
||||
assert!(result.contains("Replaced"), "got: {}", result);
|
||||
}
|
||||
@@ -1387,7 +1425,7 @@ error: aborting due to 1 previous error
|
||||
#[test]
|
||||
fn test_filter_cargo_install_empty_output() {
|
||||
let result = filter_cargo_install("");
|
||||
assert!(result.contains("✓ cargo install"), "got: {}", result);
|
||||
assert!(result.contains("cargo install"), "got: {}", result);
|
||||
assert!(result.contains("0 deps compiled"), "got: {}", result);
|
||||
}
|
||||
|
||||
@@ -1401,7 +1439,7 @@ error: aborting due to 1 previous error
|
||||
warning: be sure to add `/Users/user/.cargo/bin` to your PATH
|
||||
"#;
|
||||
let result = filter_cargo_install(output);
|
||||
assert!(result.contains("✓ cargo install"), "got: {}", result);
|
||||
assert!(result.contains("cargo install"), "got: {}", result);
|
||||
assert!(
|
||||
result.contains("be sure to add"),
|
||||
"PATH warning should be kept: {}",
|
||||
@@ -1451,7 +1489,7 @@ error: aborting due to 2 previous errors
|
||||
Installing rtk v0.11.0
|
||||
"#;
|
||||
let result = filter_cargo_install(output);
|
||||
assert!(result.contains("✓ cargo install"), "got: {}", result);
|
||||
assert!(result.contains("cargo install"), "got: {}", result);
|
||||
assert!(!result.contains("Locking"), "got: {}", result);
|
||||
assert!(!result.contains("Blocking"), "got: {}", result);
|
||||
assert!(!result.contains("Downloading"), "got: {}", result);
|
||||
@@ -1465,7 +1503,7 @@ error: aborting due to 2 previous errors
|
||||
"#;
|
||||
let result = filter_cargo_install(output);
|
||||
// Path-based install: crate info not extracted from path
|
||||
assert!(result.contains("✓ cargo install"), "got: {}", result);
|
||||
assert!(result.contains("cargo install"), "got: {}", result);
|
||||
assert!(result.contains("1 deps compiled"), "got: {}", result);
|
||||
}
|
||||
|
||||
@@ -1491,7 +1529,7 @@ error: aborting due to 2 previous errors
|
||||
"#;
|
||||
let result = filter_cargo_nextest(output);
|
||||
assert_eq!(
|
||||
result, "✓ cargo nextest: 301 passed (1 binary, 0.192s)",
|
||||
result, "cargo nextest: 301 passed (1 binary, 0.192s)",
|
||||
"got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1576,7 +1614,7 @@ error: test run failed
|
||||
"#;
|
||||
let result = filter_cargo_nextest(output);
|
||||
assert_eq!(
|
||||
result, "✓ cargo nextest: 50 passed, 3 skipped (2 binaries, 0.500s)",
|
||||
result, "cargo nextest: 50 passed, 3 skipped (2 binaries, 0.500s)",
|
||||
"got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1627,7 +1665,7 @@ error: test run failed
|
||||
"#;
|
||||
let result = filter_cargo_nextest(output);
|
||||
assert_eq!(
|
||||
result, "✓ cargo nextest: 100 passed (5 binaries, 1.234s)",
|
||||
result, "cargo nextest: 100 passed (5 binaries, 1.234s)",
|
||||
"got: {}",
|
||||
result
|
||||
);
|
||||
@@ -1662,7 +1700,7 @@ error: test run failed
|
||||
result
|
||||
);
|
||||
assert!(
|
||||
result.contains("✓ cargo nextest: 10 passed"),
|
||||
result.contains("cargo nextest: 10 passed"),
|
||||
"got: {}",
|
||||
result
|
||||
);
|
||||
|
||||
+6
-5
@@ -14,6 +14,7 @@ use crate::utils::{format_cpt, format_tokens, format_usd};
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
#[allow(dead_code)]
|
||||
const BILLION: f64 = 1e9;
|
||||
|
||||
// API pricing ratios (verified Feb 2026, consistent across Claude models <=200K context)
|
||||
@@ -249,7 +250,7 @@ fn merge_weekly(cc: Option<Vec<CcusagePeriod>>, rtk: Vec<WeekStats>) -> Vec<Peri
|
||||
let monday_key = match convert_saturday_to_monday(&entry.week_start) {
|
||||
Some(m) => m,
|
||||
None => {
|
||||
eprintln!("⚠️ Invalid week_start format: {}", entry.week_start);
|
||||
eprintln!("[warn] Invalid week_start format: {}", entry.week_start);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -441,7 +442,7 @@ fn display_summary(tracker: &Tracker, verbose: u8) -> Result<()> {
|
||||
|
||||
let totals = compute_totals(&periods);
|
||||
|
||||
println!("💰 Claude Code Economics");
|
||||
println!("[cost] Claude Code Economics");
|
||||
println!("════════════════════════════════════════════════════");
|
||||
println!();
|
||||
|
||||
@@ -549,7 +550,7 @@ fn display_daily(tracker: &Tracker, verbose: u8) -> Result<()> {
|
||||
.context("Failed to load daily token savings from database")?;
|
||||
let periods = merge_daily(cc_daily, rtk_daily);
|
||||
|
||||
println!("📅 Daily Economics");
|
||||
println!("Daily Economics");
|
||||
println!("════════════════════════════════════════════════════");
|
||||
print_period_table(&periods, verbose);
|
||||
Ok(())
|
||||
@@ -563,7 +564,7 @@ fn display_weekly(tracker: &Tracker, verbose: u8) -> Result<()> {
|
||||
.context("Failed to load weekly token savings from database")?;
|
||||
let periods = merge_weekly(cc_weekly, rtk_weekly);
|
||||
|
||||
println!("📅 Weekly Economics");
|
||||
println!("Weekly Economics");
|
||||
println!("════════════════════════════════════════════════════");
|
||||
print_period_table(&periods, verbose);
|
||||
Ok(())
|
||||
@@ -577,7 +578,7 @@ fn display_monthly(tracker: &Tracker, verbose: u8) -> Result<()> {
|
||||
.context("Failed to load monthly token savings from database")?;
|
||||
let periods = merge_monthly(cc_monthly, rtk_monthly);
|
||||
|
||||
println!("📅 Monthly Economics");
|
||||
println!("Monthly Economics");
|
||||
println!("════════════════════════════════════════════════════");
|
||||
print_period_table(&periods, verbose);
|
||||
Ok(())
|
||||
|
||||
+4
-3
@@ -112,6 +112,7 @@ fn build_command() -> Option<Command> {
|
||||
}
|
||||
|
||||
/// Check if ccusage CLI is available (binary or via npx)
|
||||
#[allow(dead_code)]
|
||||
pub fn is_available() -> bool {
|
||||
build_command().is_some()
|
||||
}
|
||||
@@ -125,7 +126,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
|
||||
let mut cmd = match build_command() {
|
||||
Some(cmd) => cmd,
|
||||
None => {
|
||||
eprintln!("⚠️ ccusage not found. Install: npm i -g ccusage (or use npx ccusage)");
|
||||
eprintln!("[warn] ccusage not found. Install: npm i -g ccusage (or use npx ccusage)");
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
@@ -145,7 +146,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
|
||||
|
||||
let output = match output {
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ ccusage execution failed: {}", e);
|
||||
eprintln!("[warn] ccusage execution failed: {}", e);
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(o) => o,
|
||||
@@ -154,7 +155,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprintln!(
|
||||
"⚠️ ccusage exited with {}: {}",
|
||||
"[warn] ccusage exited with {}: {}",
|
||||
output.status,
|
||||
stderr.trim()
|
||||
);
|
||||
|
||||
@@ -16,6 +16,8 @@ pub struct Config {
|
||||
pub telemetry: TelemetryConfig,
|
||||
#[serde(default)]
|
||||
pub hooks: HooksConfig,
|
||||
#[serde(default)]
|
||||
pub limits: LimitsConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
@@ -94,6 +96,37 @@ impl Default for TelemetryConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct LimitsConfig {
|
||||
/// Max total grep results to show (default: 200)
|
||||
pub grep_max_results: usize,
|
||||
/// Max matches per file in grep output (default: 25)
|
||||
pub grep_max_per_file: usize,
|
||||
/// Max staged/modified files shown in git status (default: 15)
|
||||
pub status_max_files: usize,
|
||||
/// Max untracked files shown in git status (default: 10)
|
||||
pub status_max_untracked: usize,
|
||||
/// Max chars for parser passthrough fallback (default: 2000)
|
||||
pub passthrough_max_chars: usize,
|
||||
}
|
||||
|
||||
impl Default for LimitsConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
grep_max_results: 200,
|
||||
grep_max_per_file: 25,
|
||||
status_max_files: 15,
|
||||
status_max_untracked: 10,
|
||||
passthrough_max_chars: 2000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get limits config. Falls back to defaults if config can't be loaded.
|
||||
pub fn limits() -> LimitsConfig {
|
||||
Config::load().map(|c| c.limits).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Check if telemetry is enabled in config. Returns None if config can't be loaded.
|
||||
pub fn telemetry_enabled() -> Option<bool> {
|
||||
Config::load().ok().map(|c| c.telemetry.enabled)
|
||||
|
||||
+85
-30
@@ -53,21 +53,26 @@ fn docker_ps(_verbose: u8) -> Result<()> {
|
||||
let mut rtk = String::new();
|
||||
|
||||
if stdout.trim().is_empty() {
|
||||
rtk.push_str("🐳 0 containers");
|
||||
rtk.push_str("[docker] 0 containers");
|
||||
println!("{}", rtk);
|
||||
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let count = stdout.lines().count();
|
||||
rtk.push_str(&format!("🐳 {} containers:\n", count));
|
||||
rtk.push_str(&format!("[docker] {} containers:\n", count));
|
||||
|
||||
for line in stdout.lines().take(15) {
|
||||
let parts: Vec<&str> = line.split('\t').collect();
|
||||
if parts.len() >= 4 {
|
||||
let id = &parts[0][..12.min(parts[0].len())];
|
||||
let name = parts[1];
|
||||
let short_image = parts.get(3).unwrap_or(&"").split('/').last().unwrap_or("");
|
||||
let short_image = parts
|
||||
.get(3)
|
||||
.unwrap_or(&"")
|
||||
.split('/')
|
||||
.next_back()
|
||||
.unwrap_or("");
|
||||
let ports = compact_ports(parts.get(4).unwrap_or(&""));
|
||||
if ports == "-" {
|
||||
rtk.push_str(&format!(" {} {} ({})\n", id, name, short_image));
|
||||
@@ -114,7 +119,7 @@ fn docker_images(_verbose: u8) -> Result<()> {
|
||||
let mut rtk = String::new();
|
||||
|
||||
if lines.is_empty() {
|
||||
rtk.push_str("🐳 0 images");
|
||||
rtk.push_str("[docker] 0 images");
|
||||
println!("{}", rtk);
|
||||
timer.track("docker images", "rtk docker images", &raw, &rtk);
|
||||
return Ok(());
|
||||
@@ -141,7 +146,11 @@ fn docker_images(_verbose: u8) -> Result<()> {
|
||||
} else {
|
||||
format!("{:.0}MB", total_size_mb)
|
||||
};
|
||||
rtk.push_str(&format!("🐳 {} images ({})\n", lines.len(), total_display));
|
||||
rtk.push_str(&format!(
|
||||
"[docker] {} images ({})\n",
|
||||
lines.len(),
|
||||
total_display
|
||||
));
|
||||
|
||||
for line in lines.iter().take(15) {
|
||||
let parts: Vec<&str> = line.split('\t').collect();
|
||||
@@ -183,8 +192,21 @@ fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("docker logs {}", container),
|
||||
"rtk docker logs",
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let analyzed = crate::log_cmd::run_stdin_str(&raw);
|
||||
let rtk = format!("🐳 Logs for {}:\n{}", container, analyzed);
|
||||
let rtk = format!("[docker] Logs for {}:\n{}", container, analyzed);
|
||||
println!("{}", rtk);
|
||||
timer.track(
|
||||
&format!("docker logs {}", container),
|
||||
@@ -208,10 +230,19 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
let mut rtk = String::new();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
rtk.push_str("☸️ No pods found");
|
||||
rtk.push_str("No pods found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
|
||||
return Ok(());
|
||||
@@ -219,7 +250,7 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
|
||||
};
|
||||
|
||||
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
rtk.push_str("☸️ No pods found");
|
||||
rtk.push_str("No pods found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
|
||||
return Ok(());
|
||||
@@ -265,21 +296,21 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
|
||||
|
||||
let mut parts = Vec::new();
|
||||
if running > 0 {
|
||||
parts.push(format!("{} ✓", running));
|
||||
parts.push(format!("{}", running));
|
||||
}
|
||||
if pending > 0 {
|
||||
parts.push(format!("{} pending", pending));
|
||||
}
|
||||
if failed > 0 {
|
||||
parts.push(format!("{} ✗", failed));
|
||||
parts.push(format!("{} [x]", failed));
|
||||
}
|
||||
if restarts_total > 0 {
|
||||
parts.push(format!("{} restarts", restarts_total));
|
||||
}
|
||||
|
||||
rtk.push_str(&format!("☸️ {} pods: {}\n", pods.len(), parts.join(", ")));
|
||||
rtk.push_str(&format!("{} pods: {}\n", pods.len(), parts.join(", ")));
|
||||
if !issues.is_empty() {
|
||||
rtk.push_str("⚠️ Issues:\n");
|
||||
rtk.push_str("[warn] Issues:\n");
|
||||
for issue in issues.iter().take(10) {
|
||||
rtk.push_str(&format!(" {}\n", issue));
|
||||
}
|
||||
@@ -306,10 +337,19 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
let mut rtk = String::new();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
rtk.push_str("☸️ No services found");
|
||||
rtk.push_str("No services found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
|
||||
return Ok(());
|
||||
@@ -317,12 +357,12 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
|
||||
};
|
||||
|
||||
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
rtk.push_str("☸️ No services found");
|
||||
rtk.push_str("No services found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
|
||||
return Ok(());
|
||||
};
|
||||
rtk.push_str(&format!("☸️ {} services:\n", services.len()));
|
||||
rtk.push_str(&format!("{} services:\n", services.len()));
|
||||
|
||||
for svc in services.iter().take(15) {
|
||||
let ns = svc["metadata"]["namespace"].as_str().unwrap_or("-");
|
||||
@@ -381,8 +421,23 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
|
||||
|
||||
let output = cmd.output().context("Failed to run kubectl logs")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("kubectl logs {}", pod),
|
||||
"rtk kubectl logs",
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let analyzed = crate::log_cmd::run_stdin_str(&raw);
|
||||
let rtk = format!("☸️ Logs for {}:\n{}", pod, analyzed);
|
||||
let rtk = format!("Logs for {}:\n{}", pod, analyzed);
|
||||
println!("{}", rtk);
|
||||
timer.track(
|
||||
&format!("kubectl logs {}", pod),
|
||||
@@ -400,10 +455,10 @@ pub fn format_compose_ps(raw: &str) -> String {
|
||||
let lines: Vec<&str> = raw.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
|
||||
if lines.is_empty() {
|
||||
return "🐳 0 compose services".to_string();
|
||||
return "[compose] 0 services".to_string();
|
||||
}
|
||||
|
||||
let mut result = format!("🐳 {} compose services:\n", lines.len());
|
||||
let mut result = format!("[compose] {} services:\n", lines.len());
|
||||
|
||||
for line in lines.iter().take(20) {
|
||||
let parts: Vec<&str> = line.split('\t').collect();
|
||||
@@ -442,19 +497,19 @@ pub fn format_compose_ps(raw: &str) -> String {
|
||||
/// Format `docker compose logs` output into compact form
|
||||
pub fn format_compose_logs(raw: &str) -> String {
|
||||
if raw.trim().is_empty() {
|
||||
return "🐳 No logs".to_string();
|
||||
return "[compose] No logs".to_string();
|
||||
}
|
||||
|
||||
// docker compose logs prefixes each line with "service-N | "
|
||||
// Use the existing log deduplication engine
|
||||
let analyzed = crate::log_cmd::run_stdin_str(raw);
|
||||
format!("🐳 Compose logs:\n{}", analyzed)
|
||||
format!("[compose] Logs:\n{}", analyzed)
|
||||
}
|
||||
|
||||
/// Format `docker compose build` output into compact summary
|
||||
pub fn format_compose_build(raw: &str) -> String {
|
||||
if raw.trim().is_empty() {
|
||||
return "🐳 Build: no output".to_string();
|
||||
return "[compose] Build: no output".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -462,7 +517,7 @@ pub fn format_compose_build(raw: &str) -> String {
|
||||
// Extract the summary line: "[+] Building 12.3s (8/8) FINISHED"
|
||||
for line in raw.lines() {
|
||||
if line.contains("Building") && line.contains("FINISHED") {
|
||||
result.push_str(&format!("🐳 {}\n", line.trim()));
|
||||
result.push_str(&format!("[compose] {}\n", line.trim()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -470,9 +525,9 @@ pub fn format_compose_build(raw: &str) -> String {
|
||||
if result.is_empty() {
|
||||
// No FINISHED line found — might still be building or errored
|
||||
if let Some(line) = raw.lines().find(|l| l.contains("Building")) {
|
||||
result.push_str(&format!("🐳 {}\n", line.trim()));
|
||||
result.push_str(&format!("[compose] {}\n", line.trim()));
|
||||
} else {
|
||||
result.push_str("🐳 Build:\n");
|
||||
result.push_str("[compose] Build:\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -516,7 +571,7 @@ fn compact_ports(ports: &str) -> String {
|
||||
// Extract just the port numbers
|
||||
let port_nums: Vec<&str> = ports
|
||||
.split(',')
|
||||
.filter_map(|p| p.split("->").next().and_then(|s| s.split(':').last()))
|
||||
.filter_map(|p| p.split("->").next().and_then(|s| s.split(':').next_back()))
|
||||
.collect();
|
||||
|
||||
if port_nums.len() <= 3 {
|
||||
@@ -771,8 +826,11 @@ mod tests {
|
||||
let raw = "redis-1\tredis:7\tUp 5 hours\t";
|
||||
let out = format_compose_ps(raw);
|
||||
assert!(out.contains("redis"), "should show service name");
|
||||
// Should not show port info when no ports (but [compose] prefix is OK)
|
||||
let lines: Vec<&str> = out.lines().collect();
|
||||
let redis_line = lines.iter().find(|l| l.contains("redis")).unwrap();
|
||||
assert!(
|
||||
!out.contains("["),
|
||||
!redis_line.contains("] ["),
|
||||
"should not show port brackets when empty"
|
||||
);
|
||||
}
|
||||
@@ -801,10 +859,7 @@ web-1 | 192.168.1.1 - GET /favicon.ico 404
|
||||
api-1 | Server listening on port 3000
|
||||
api-1 | Connected to database";
|
||||
let out = format_compose_logs(raw);
|
||||
assert!(
|
||||
out.contains("Compose logs"),
|
||||
"should have compose logs header"
|
||||
);
|
||||
assert!(out.contains("Logs"), "should have compose logs header");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+5
-5
@@ -26,7 +26,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
|
||||
if cargo_path.exists() {
|
||||
found = true;
|
||||
raw.push_str(&fs::read_to_string(&cargo_path).unwrap_or_default());
|
||||
rtk.push_str("📦 Rust (Cargo.toml):\n");
|
||||
rtk.push_str("Rust (Cargo.toml):\n");
|
||||
rtk.push_str(&summarize_cargo_str(&cargo_path)?);
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
|
||||
if package_path.exists() {
|
||||
found = true;
|
||||
raw.push_str(&fs::read_to_string(&package_path).unwrap_or_default());
|
||||
rtk.push_str("📦 Node.js (package.json):\n");
|
||||
rtk.push_str("Node.js (package.json):\n");
|
||||
rtk.push_str(&summarize_package_json_str(&package_path)?);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
|
||||
if requirements_path.exists() {
|
||||
found = true;
|
||||
raw.push_str(&fs::read_to_string(&requirements_path).unwrap_or_default());
|
||||
rtk.push_str("📦 Python (requirements.txt):\n");
|
||||
rtk.push_str("Python (requirements.txt):\n");
|
||||
rtk.push_str(&summarize_requirements_str(&requirements_path)?);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
|
||||
if pyproject_path.exists() {
|
||||
found = true;
|
||||
raw.push_str(&fs::read_to_string(&pyproject_path).unwrap_or_default());
|
||||
rtk.push_str("📦 Python (pyproject.toml):\n");
|
||||
rtk.push_str("Python (pyproject.toml):\n");
|
||||
rtk.push_str(&summarize_pyproject_str(&pyproject_path)?);
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
|
||||
if gomod_path.exists() {
|
||||
found = true;
|
||||
raw.push_str(&fs::read_to_string(&gomod_path).unwrap_or_default());
|
||||
rtk.push_str("📦 Go (go.mod):\n");
|
||||
rtk.push_str("Go (go.mod):\n");
|
||||
rtk.push_str(&summarize_gomod_str(&gomod_path)?);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -22,7 +22,7 @@ pub fn run(file1: &Path, file2: &Path, verbose: u8) -> Result<()> {
|
||||
let mut rtk = String::new();
|
||||
|
||||
if diff.added == 0 && diff.removed == 0 {
|
||||
rtk.push_str("✅ Files are identical");
|
||||
rtk.push_str("[ok] Files are identical");
|
||||
println!("{}", rtk);
|
||||
timer.track(
|
||||
&format!("diff {} {}", file1.display(), file2.display()),
|
||||
@@ -33,7 +33,7 @@ pub fn run(file1: &Path, file2: &Path, verbose: u8) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
rtk.push_str(&format!("📊 {} → {}\n", file1.display(), file2.display()));
|
||||
rtk.push_str(&format!("{} → {}\n", file1.display(), file2.display()));
|
||||
rtk.push_str(&format!(
|
||||
" +{} added, -{} removed, ~{} modified\n\n",
|
||||
diff.added, diff.removed, diff.modified
|
||||
@@ -168,7 +168,7 @@ fn condense_unified_diff(diff: &str) -> String {
|
||||
// File header
|
||||
if line.starts_with("+++ ") {
|
||||
if !current_file.is_empty() && (added > 0 || removed > 0) {
|
||||
result.push(format!("📄 {} (+{} -{})", current_file, added, removed));
|
||||
result.push(format!("[file] {} (+{} -{})", current_file, added, removed));
|
||||
for c in changes.iter().take(10) {
|
||||
result.push(format!(" {}", c));
|
||||
}
|
||||
@@ -199,7 +199,7 @@ fn condense_unified_diff(diff: &str) -> String {
|
||||
|
||||
// Last file
|
||||
if !current_file.is_empty() && (added > 0 || removed > 0) {
|
||||
result.push(format!("📄 {} (+{} -{})", current_file, added, removed));
|
||||
result.push(format!("[file] {} (+{} -{})", current_file, added, removed));
|
||||
for c in changes.iter().take(10) {
|
||||
result.push(format!(" {}", c));
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ pub struct ExtractedCommand {
|
||||
/// Whether the tool_result indicated an error
|
||||
pub is_error: bool,
|
||||
/// Chronological sequence index within the session
|
||||
#[allow(dead_code)]
|
||||
pub sequence_index: usize,
|
||||
}
|
||||
|
||||
@@ -347,7 +348,7 @@ mod tests {
|
||||
let cmds = provider.extract_commands(jsonl.path()).unwrap();
|
||||
assert_eq!(cmds.len(), 1);
|
||||
assert_eq!(cmds[0].command, "git commit --ammend");
|
||||
assert_eq!(cmds[0].is_error, true);
|
||||
assert!(cmds[0].is_error);
|
||||
assert!(cmds[0].output_content.is_some());
|
||||
assert_eq!(
|
||||
cmds[0].output_content.as_ref().unwrap(),
|
||||
@@ -365,8 +366,8 @@ mod tests {
|
||||
let provider = ClaudeProvider;
|
||||
let cmds = provider.extract_commands(jsonl.path()).unwrap();
|
||||
assert_eq!(cmds.len(), 2);
|
||||
assert_eq!(cmds[0].is_error, false);
|
||||
assert_eq!(cmds[1].is_error, true);
|
||||
assert!(!cmds[0].is_error);
|
||||
assert!(cmds[1].is_error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+213
-7
@@ -48,6 +48,10 @@ lazy_static! {
|
||||
.collect();
|
||||
static ref ENV_PREFIX: Regex =
|
||||
Regex::new(r"^(?:sudo\s+|env\s+|[A-Z_][A-Z0-9_]*=[^\s]*\s+)+").unwrap();
|
||||
// Git global options that appear before the subcommand: -C <path>, -c <key=val>,
|
||||
// --git-dir <dir>, --work-tree <dir>, and flag-only options (#163)
|
||||
static ref GIT_GLOBAL_OPT: Regex =
|
||||
Regex::new(r"^(?:(?:-C\s+\S+|-c\s+\S+|--git-dir(?:=\S+|\s+\S+)|--work-tree(?:=\S+|\s+\S+)|--no-pager|--no-optional-locks|--bare|--literal-pathspecs)\s+)+").unwrap();
|
||||
}
|
||||
|
||||
/// Classify a single (already-split) command.
|
||||
@@ -76,6 +80,12 @@ pub fn classify_command(cmd: &str) -> Classification {
|
||||
return Classification::Ignored;
|
||||
}
|
||||
|
||||
// Normalize absolute binary paths: /usr/bin/grep → grep (#485)
|
||||
let cmd_normalized = strip_absolute_path(cmd_clean);
|
||||
// Strip git global options: git -C /tmp status → git status (#163)
|
||||
let cmd_normalized = strip_git_global_opts(&cmd_normalized);
|
||||
let cmd_clean = cmd_normalized.as_str();
|
||||
|
||||
// Exclude cat/head/tail with redirect operators — these are writes, not reads (#315)
|
||||
if cmd_clean.starts_with("cat ")
|
||||
|| cmd_clean.starts_with("head ")
|
||||
@@ -262,6 +272,42 @@ pub fn split_command_chain(cmd: &str) -> Vec<&str> {
|
||||
results
|
||||
}
|
||||
|
||||
/// Strip git global options before the subcommand (#163).
|
||||
/// `git -C /tmp status` → `git status`, preserving the rest.
|
||||
/// Returns the original string unchanged if not a git command.
|
||||
fn strip_git_global_opts(cmd: &str) -> String {
|
||||
// Only applies to commands starting with "git "
|
||||
if !cmd.starts_with("git ") {
|
||||
return cmd.to_string();
|
||||
}
|
||||
let after_git = &cmd[4..]; // skip "git "
|
||||
let stripped = GIT_GLOBAL_OPT.replace(after_git, "");
|
||||
format!("git {}", stripped.trim())
|
||||
}
|
||||
|
||||
/// Normalize absolute binary paths: `/usr/bin/grep -rn foo` → `grep -rn foo` (#485)
|
||||
/// Only strips if the first word contains a `/` (Unix path).
|
||||
fn strip_absolute_path(cmd: &str) -> String {
|
||||
let first_space = cmd.find(' ');
|
||||
let first_word = match first_space {
|
||||
Some(pos) => &cmd[..pos],
|
||||
None => cmd,
|
||||
};
|
||||
if first_word.contains('/') {
|
||||
// Extract basename
|
||||
let basename = first_word.rsplit('/').next().unwrap_or(first_word);
|
||||
if basename.is_empty() {
|
||||
return cmd.to_string();
|
||||
}
|
||||
match first_space {
|
||||
Some(pos) => format!("{}{}", basename, &cmd[pos..]),
|
||||
None => basename.to_string(),
|
||||
}
|
||||
} else {
|
||||
cmd.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a command has RTK_DISABLED= prefix in its env prefix portion.
|
||||
pub fn has_rtk_disabled_prefix(cmd: &str) -> bool {
|
||||
let trimmed = cmd.trim();
|
||||
@@ -355,8 +401,18 @@ fn rewrite_compound(cmd: &str, excluded: &[String]) -> Option<String> {
|
||||
} else {
|
||||
// `|` pipe — rewrite first segment only, pass through the rest unchanged
|
||||
let seg = cmd[seg_start..i].trim();
|
||||
let rewritten =
|
||||
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
// Skip rewriting `find`/`fd` in pipes — rtk find outputs a grouped
|
||||
// format that is incompatible with pipe consumers like xargs, grep,
|
||||
// wc, sort, etc. which expect one path per line (#439).
|
||||
let is_pipe_incompatible = seg.starts_with("find ")
|
||||
|| seg == "find"
|
||||
|| seg.starts_with("fd ")
|
||||
|| seg == "fd";
|
||||
let rewritten = if is_pipe_incompatible {
|
||||
seg.to_string()
|
||||
} else {
|
||||
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string())
|
||||
};
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
@@ -679,12 +735,10 @@ mod tests {
|
||||
"tail -f app.log > /dev/null",
|
||||
];
|
||||
for cmd in &write_commands {
|
||||
match classify_command(cmd) {
|
||||
Classification::Supported { .. } => {
|
||||
panic!("{} should NOT be classified as Supported", cmd)
|
||||
}
|
||||
_ => {} // Unsupported or Ignored is fine
|
||||
if let Classification::Supported { .. } = classify_command(cmd) {
|
||||
panic!("{} should NOT be classified as Supported", cmd)
|
||||
}
|
||||
// Unsupported or Ignored is fine
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1113,6 +1167,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_find_pipe_skipped() {
|
||||
// find in a pipe should NOT be rewritten — rtk find output format
|
||||
// is incompatible with pipe consumers like xargs (#439)
|
||||
assert_eq!(
|
||||
rewrite_command("find . -name '*.rs' | xargs grep 'fn run'", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_find_pipe_xargs_wc() {
|
||||
assert_eq!(rewrite_command("find src -type f | wc -l", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_find_no_pipe_still_rewritten() {
|
||||
// find WITHOUT a pipe should still be rewritten
|
||||
assert_eq!(
|
||||
rewrite_command("find . -name '*.rs'", &[]),
|
||||
Some("rtk find . -name '*.rs'".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_heredoc_returns_none() {
|
||||
assert_eq!(rewrite_command("cat <<'EOF'\nfoo\nEOF", &[]), None);
|
||||
@@ -2061,4 +2139,132 @@ mod tests {
|
||||
);
|
||||
assert_eq!(strip_disabled_prefix("git status"), "git status");
|
||||
}
|
||||
|
||||
// --- #485: absolute path normalization ---
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_grep() {
|
||||
assert_eq!(
|
||||
classify_command("/usr/bin/grep -rni pattern"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk grep",
|
||||
category: "Files",
|
||||
estimated_savings_pct: 75.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_ls() {
|
||||
assert_eq!(
|
||||
classify_command("/bin/ls -la"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk ls",
|
||||
category: "Files",
|
||||
estimated_savings_pct: 65.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_git() {
|
||||
assert_eq!(
|
||||
classify_command("/usr/local/bin/git status"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_no_args() {
|
||||
// /usr/bin/find alone → still classified
|
||||
assert_eq!(
|
||||
classify_command("/usr/bin/find ."),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk find",
|
||||
category: "Files",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_absolute_path_helper() {
|
||||
assert_eq!(strip_absolute_path("/usr/bin/grep -rn foo"), "grep -rn foo");
|
||||
assert_eq!(strip_absolute_path("/bin/ls -la"), "ls -la");
|
||||
assert_eq!(strip_absolute_path("grep -rn foo"), "grep -rn foo");
|
||||
assert_eq!(strip_absolute_path("/usr/local/bin/git"), "git");
|
||||
}
|
||||
|
||||
// --- #163: git global options ---
|
||||
|
||||
#[test]
|
||||
fn test_classify_git_with_dash_c_path() {
|
||||
assert_eq!(
|
||||
classify_command("git -C /tmp status"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_git_no_pager_log() {
|
||||
assert_eq!(
|
||||
classify_command("git --no-pager log -5"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_git_git_dir() {
|
||||
assert_eq!(
|
||||
classify_command("git --git-dir /tmp/.git status"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_git_dash_c() {
|
||||
assert_eq!(
|
||||
rewrite_command("git -C /tmp status", &[]),
|
||||
Some("rtk git -C /tmp status".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_git_no_pager() {
|
||||
assert_eq!(
|
||||
rewrite_command("git --no-pager log -5", &[]),
|
||||
Some("rtk git --no-pager log -5".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_git_global_opts_helper() {
|
||||
assert_eq!(strip_git_global_opts("git -C /tmp status"), "git status");
|
||||
assert_eq!(strip_git_global_opts("git --no-pager log"), "git log");
|
||||
assert_eq!(strip_git_global_opts("git status"), "git status");
|
||||
assert_eq!(strip_git_global_opts("cargo test"), "cargo test");
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ pub fn format_duration(ms: u64) -> String {
|
||||
|
||||
/// Trait for period-based statistics that can be displayed in tables
|
||||
pub trait PeriodStats {
|
||||
/// Icon for this period type (e.g., "📅", "📊", "📆")
|
||||
/// Icon for this period type (e.g., "D", "W", "M")
|
||||
fn icon() -> &'static str;
|
||||
|
||||
/// Label for this period type (e.g., "Daily", "Weekly", "Monthly")
|
||||
@@ -143,7 +143,7 @@ pub fn print_period_table<T: PeriodStats>(data: &[T]) {
|
||||
|
||||
impl PeriodStats for DayStats {
|
||||
fn icon() -> &'static str {
|
||||
"📅"
|
||||
"D"
|
||||
}
|
||||
|
||||
fn label() -> &'static str {
|
||||
@@ -193,7 +193,7 @@ impl PeriodStats for DayStats {
|
||||
|
||||
impl PeriodStats for WeekStats {
|
||||
fn icon() -> &'static str {
|
||||
"📊"
|
||||
"W"
|
||||
}
|
||||
|
||||
fn label() -> &'static str {
|
||||
@@ -253,7 +253,7 @@ impl PeriodStats for WeekStats {
|
||||
|
||||
impl PeriodStats for MonthStats {
|
||||
fn icon() -> &'static str {
|
||||
"📆"
|
||||
"M"
|
||||
}
|
||||
|
||||
fn label() -> &'static str {
|
||||
@@ -322,7 +322,7 @@ mod tests {
|
||||
assert_eq!(day.commands(), 10);
|
||||
assert_eq!(day.saved_tokens(), 200);
|
||||
assert_eq!(day.avg_time_ms(), 150);
|
||||
assert_eq!(DayStats::icon(), "📅");
|
||||
assert_eq!(DayStats::icon(), "D");
|
||||
assert_eq!(DayStats::label(), "Daily");
|
||||
}
|
||||
|
||||
@@ -342,7 +342,7 @@ mod tests {
|
||||
|
||||
assert_eq!(week.period(), "01-20 → 01-26");
|
||||
assert_eq!(week.avg_time_ms(), 100);
|
||||
assert_eq!(WeekStats::icon(), "📊");
|
||||
assert_eq!(WeekStats::icon(), "W");
|
||||
assert_eq!(WeekStats::label(), "Weekly");
|
||||
}
|
||||
|
||||
@@ -361,7 +361,7 @@ mod tests {
|
||||
|
||||
assert_eq!(month.period(), "2026-01");
|
||||
assert_eq!(month.avg_time_ms(), 100);
|
||||
assert_eq!(MonthStats::icon(), "📆");
|
||||
assert_eq!(MonthStats::icon(), "M");
|
||||
assert_eq!(MonthStats::label(), "Monthly");
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -62,7 +62,7 @@ pub fn run(filter: Option<&str>, show_all: bool, verbose: u8) -> Result<()> {
|
||||
|
||||
// Print categorized
|
||||
if !path_vars.is_empty() {
|
||||
println!("📂 PATH Variables:");
|
||||
println!("PATH Variables:");
|
||||
for (k, v) in &path_vars {
|
||||
if k == "PATH" {
|
||||
// Split PATH for readability
|
||||
@@ -81,28 +81,28 @@ pub fn run(filter: Option<&str>, show_all: bool, verbose: u8) -> Result<()> {
|
||||
}
|
||||
|
||||
if !lang_vars.is_empty() {
|
||||
println!("\n🔧 Language/Runtime:");
|
||||
println!("\nLanguage/Runtime:");
|
||||
for (k, v) in &lang_vars {
|
||||
println!(" {}={}", k, v);
|
||||
}
|
||||
}
|
||||
|
||||
if !cloud_vars.is_empty() {
|
||||
println!("\n☁️ Cloud/Services:");
|
||||
println!("\nCloud/Services:");
|
||||
for (k, v) in &cloud_vars {
|
||||
println!(" {}={}", k, v);
|
||||
}
|
||||
}
|
||||
|
||||
if !tool_vars.is_empty() {
|
||||
println!("\n🛠️ Tools:");
|
||||
println!("\nTools:");
|
||||
for (k, v) in &tool_vars {
|
||||
println!(" {}={}", k, v);
|
||||
}
|
||||
}
|
||||
|
||||
if !other_vars.is_empty() {
|
||||
println!("\n📋 Other:");
|
||||
println!("\nOther:");
|
||||
for (k, v) in other_vars.iter().take(20) {
|
||||
println!(" {}={}", k, v);
|
||||
}
|
||||
@@ -118,7 +118,7 @@ pub fn run(filter: Option<&str>, show_all: bool, verbose: u8) -> Result<()> {
|
||||
+ tool_vars.len()
|
||||
+ other_vars.len().min(20);
|
||||
if filter.is_none() {
|
||||
println!("\n📊 Total: {} vars (showing {} relevant)", total, shown);
|
||||
println!("\nTotal: {} vars (showing {} relevant)", total, shown);
|
||||
}
|
||||
|
||||
let raw: String = vars.iter().map(|(k, v)| format!("{}={}\n", k, v)).collect();
|
||||
|
||||
+44
-12
@@ -50,6 +50,7 @@ pub enum Language {
|
||||
Java,
|
||||
Ruby,
|
||||
Shell,
|
||||
/// Data formats (JSON, YAML, TOML, XML, CSV) — no comment stripping
|
||||
Data,
|
||||
Unknown,
|
||||
}
|
||||
@@ -67,9 +68,10 @@ impl Language {
|
||||
"java" => Language::Java,
|
||||
"rb" => Language::Ruby,
|
||||
"sh" | "bash" | "zsh" => Language::Shell,
|
||||
"json" | "jsonc" | "json5" | "yaml" | "yml" | "toml" | "xml" | "html" | "htm"
|
||||
| "css" | "scss" | "svg" | "md" | "markdown" | "txt" | "csv" | "tsv" | "env"
|
||||
| "ini" | "cfg" | "conf" | "lock" => Language::Data,
|
||||
"json" | "jsonc" | "json5" | "yaml" | "yml" | "toml" | "xml" | "csv" | "tsv"
|
||||
| "graphql" | "gql" | "sql" | "md" | "markdown" | "txt" | "env" | "lock" => {
|
||||
Language::Data
|
||||
}
|
||||
_ => Language::Unknown,
|
||||
}
|
||||
}
|
||||
@@ -249,6 +251,11 @@ lazy_static! {
|
||||
|
||||
impl FilterStrategy for AggressiveFilter {
|
||||
fn filter(&self, content: &str, lang: &Language) -> String {
|
||||
// Data formats (JSON, YAML, etc.) must never be code-filtered
|
||||
if *lang == Language::Data {
|
||||
return MinimalFilter.filter(content, lang);
|
||||
}
|
||||
|
||||
let minimal = MinimalFilter.filter(content, lang);
|
||||
let mut result = String::with_capacity(minimal.len() / 2);
|
||||
let mut brace_depth = 0;
|
||||
@@ -407,14 +414,15 @@ mod tests {
|
||||
assert_eq!(Language::from_extension("yml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("toml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("xml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("md"), Language::Data);
|
||||
assert_eq!(Language::from_extension("csv"), Language::Data);
|
||||
assert_eq!(Language::from_extension("md"), Language::Data);
|
||||
assert_eq!(Language::from_extension("lock"), Language::Data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_files_no_comment_stripping() {
|
||||
// Regression test for #464: package.json with `/*` in strings
|
||||
fn test_json_no_comment_stripping() {
|
||||
// Reproduces #464: package.json with "packages/*" was corrupted
|
||||
// because /* was treated as block comment start
|
||||
let json = r#"{
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
@@ -432,17 +440,41 @@ mod tests {
|
||||
}"#;
|
||||
let filter = MinimalFilter;
|
||||
let result = filter.filter(json, &Language::Data);
|
||||
assert!(
|
||||
result.contains("scripts"),
|
||||
"scripts section must be preserved"
|
||||
);
|
||||
// All fields must be preserved — no comment stripping on JSON
|
||||
assert!(
|
||||
result.contains("packages/*"),
|
||||
"glob pattern must be preserved"
|
||||
"packages/* should not be treated as block comment start"
|
||||
);
|
||||
assert!(
|
||||
result.contains("scripts"),
|
||||
"scripts section must not be stripped"
|
||||
);
|
||||
assert!(
|
||||
result.contains("lint-staged"),
|
||||
"lint-staged section must not be stripped"
|
||||
);
|
||||
assert!(
|
||||
result.contains("**/package.json"),
|
||||
"glob pattern must be preserved"
|
||||
"**/package.json should not be treated as block comment end"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_json_aggressive_filter_preserves_structure() {
|
||||
let json = r#"{
|
||||
"name": "my-app",
|
||||
"dependencies": {
|
||||
"react": "^18.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "next dev /* not a comment */"
|
||||
}
|
||||
}"#;
|
||||
let filter = AggressiveFilter;
|
||||
let result = filter.filter(json, &Language::Data);
|
||||
assert!(
|
||||
result.contains("/* not a comment */"),
|
||||
"Aggressive filter must not strip comment-like patterns in JSON"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
[filters.gradle]
|
||||
description = "Compact Gradle build output — strip progress, keep tasks and errors"
|
||||
match_command = "^(gradle|gradlew|\\./)gradlew?\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^> Configuring project",
|
||||
"^> Resolving dependencies",
|
||||
"^> Transform ",
|
||||
"^Download(ing)?\\s+http",
|
||||
"^\\s*<-+>\\s*$",
|
||||
"^> Task :.*UP-TO-DATE$",
|
||||
"^> Task :.*NO-SOURCE$",
|
||||
"^> Task :.*FROM-CACHE$",
|
||||
"^Starting a Gradle Daemon",
|
||||
"^Daemon will be stopped",
|
||||
]
|
||||
truncate_lines_at = 150
|
||||
max_lines = 50
|
||||
on_empty = "gradle: ok"
|
||||
|
||||
[[tests.gradle]]
|
||||
name = "strips UP-TO-DATE tasks, keeps build result"
|
||||
input = "> Configuring project :app\n> Task :app:compileJava UP-TO-DATE\n> Task :app:compileKotlin UP-TO-DATE\n> Task :app:test\n\n3 tests completed, 1 failed\n\nBUILD FAILED in 12s"
|
||||
expected = "> Task :app:test\n3 tests completed, 1 failed\nBUILD FAILED in 12s"
|
||||
|
||||
[[tests.gradle]]
|
||||
name = "clean build preserved"
|
||||
input = "BUILD SUCCESSFUL in 8s\n7 actionable tasks: 7 executed"
|
||||
expected = "BUILD SUCCESSFUL in 8s\n7 actionable tasks: 7 executed"
|
||||
|
||||
[[tests.gradle]]
|
||||
name = "empty after stripping"
|
||||
input = "> Configuring project :app\n"
|
||||
expected = "gradle: ok"
|
||||
@@ -0,0 +1,20 @@
|
||||
[filters.jira]
|
||||
description = "Compact Jira CLI output — strip verbose metadata, keep essentials"
|
||||
match_command = "^jira\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*--",
|
||||
]
|
||||
truncate_lines_at = 120
|
||||
max_lines = 40
|
||||
|
||||
[[tests.jira]]
|
||||
name = "strips blank lines from issue list"
|
||||
input = "TYPE\tKEY\tSUMMARY\tSTATUS\n\nStory\tPROJ-123\tAdd login feature\tIn Progress\n\nBug\tPROJ-456\tFix crash on startup\tOpen"
|
||||
expected = "TYPE\tKEY\tSUMMARY\tSTATUS\nStory\tPROJ-123\tAdd login feature\tIn Progress\nBug\tPROJ-456\tFix crash on startup\tOpen"
|
||||
|
||||
[[tests.jira]]
|
||||
name = "single issue view"
|
||||
input = "KEY: PROJ-123\nSummary: Add login feature\nStatus: In Progress\nAssignee: john@example.com"
|
||||
expected = "KEY: PROJ-123\nSummary: Add login feature\nStatus: In Progress\nAssignee: john@example.com"
|
||||
@@ -0,0 +1,26 @@
|
||||
[filters.just]
|
||||
description = "Compact just task runner output — strip recipe headers, keep command output"
|
||||
match_command = "^just\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*Available recipes:",
|
||||
"^\\s*just --list",
|
||||
]
|
||||
truncate_lines_at = 150
|
||||
max_lines = 50
|
||||
|
||||
[[tests.just]]
|
||||
name = "preserves command output"
|
||||
input = "cargo test\n\ntest result: ok. 42 passed; 0 failed\n"
|
||||
expected = "cargo test\ntest result: ok. 42 passed; 0 failed"
|
||||
|
||||
[[tests.just]]
|
||||
name = "preserves error output"
|
||||
input = "error: Compilation failed\nsrc/main.rs:10: expected `;`"
|
||||
expected = "error: Compilation failed\nsrc/main.rs:10: expected `;`"
|
||||
|
||||
[[tests.just]]
|
||||
name = "empty input"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,30 @@
|
||||
[filters.mise]
|
||||
description = "Compact mise task runner output — strip status lines, keep task results"
|
||||
match_command = "^mise\\s+(run|exec|install|upgrade)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^mise\\s+(trust|install|upgrade).*✓",
|
||||
"^mise\\s+Installing\\s",
|
||||
"^mise\\s+Downloading\\s",
|
||||
"^mise\\s+Extracting\\s",
|
||||
"^mise\\s+\\w+@[\\d.]+ installed",
|
||||
]
|
||||
truncate_lines_at = 150
|
||||
max_lines = 50
|
||||
on_empty = "mise: ok"
|
||||
|
||||
[[tests.mise]]
|
||||
name = "strips install noise, keeps task output"
|
||||
input = "mise Installing node@20.0.0\nmise Downloading node@20.0.0\nmise Extracting node@20.0.0\nmise node@20.0.0 installed\n\nlint check passed\n2 warnings found"
|
||||
expected = "lint check passed\n2 warnings found"
|
||||
|
||||
[[tests.mise]]
|
||||
name = "preserves error output"
|
||||
input = "mise run lint\nError: biome check failed\nsrc/index.ts:5 — unused variable"
|
||||
expected = "mise run lint\nError: biome check failed\nsrc/index.ts:5 — unused variable"
|
||||
|
||||
[[tests.mise]]
|
||||
name = "empty after stripping"
|
||||
input = "mise trust ~/dev/.mise.toml ✓\nmise install node@20 ✓\n"
|
||||
expected = "mise: ok"
|
||||
@@ -0,0 +1,25 @@
|
||||
[filters.nx]
|
||||
description = "Compact Nx monorepo output — strip task graph noise, keep results"
|
||||
match_command = "^(pnpm\\s+)?nx\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*>\\s*NX\\s+Running target",
|
||||
"^\\s*>\\s*NX\\s+Nx read the output",
|
||||
"^\\s*>\\s*NX\\s+View logs",
|
||||
"^———————",
|
||||
"^—————————",
|
||||
"^\\s+Nx \\(powered by",
|
||||
]
|
||||
truncate_lines_at = 150
|
||||
max_lines = 60
|
||||
|
||||
[[tests.nx]]
|
||||
name = "strips Nx noise, keeps build output"
|
||||
input = "\n > NX Running target build for project myapp\n\n———————————————————————————————————————\nCompiled successfully.\nOutput: dist/apps/myapp\n\n > NX View logs at /tmp/.nx/runs/abc123\n\n Nx (powered by computation caching)\n"
|
||||
expected = "Compiled successfully.\nOutput: dist/apps/myapp"
|
||||
|
||||
[[tests.nx]]
|
||||
name = "preserves error output"
|
||||
input = "ERROR: Cannot find module '@myapp/shared'\n\n > NX Running target build for project myapp\n\nFailed at step: build"
|
||||
expected = "ERROR: Cannot find module '@myapp/shared'\nFailed at step: build"
|
||||
@@ -0,0 +1,23 @@
|
||||
[filters.ollama]
|
||||
description = "Strip ANSI spinners and cursor control from ollama output, keep final text"
|
||||
match_command = "^ollama\\s+run\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\\s]*$",
|
||||
"^\\s*$",
|
||||
]
|
||||
|
||||
[[tests.ollama]]
|
||||
name = "strips spinner lines, keeps response"
|
||||
input = "⠋ \n⠙ \n⠹ \nHello! How can I help you today?"
|
||||
expected = "Hello! How can I help you today?"
|
||||
|
||||
[[tests.ollama]]
|
||||
name = "preserves multi-line response"
|
||||
input = "⠋ \n⠙ \nLine one of the response.\nLine two of the response."
|
||||
expected = "Line one of the response.\nLine two of the response."
|
||||
|
||||
[[tests.ollama]]
|
||||
name = "empty input"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,28 @@
|
||||
[filters.spring-boot]
|
||||
description = "Compact Spring Boot output — strip banner and verbose startup logs, keep key events"
|
||||
match_command = "^(mvn\\s+spring-boot:run|java\\s+-jar.*\\.jar|gradle\\s+.*bootRun)"
|
||||
strip_ansi = true
|
||||
keep_lines_matching = [
|
||||
"Started\\s.*\\sin\\s",
|
||||
"Tomcat started on port",
|
||||
"ERROR",
|
||||
"WARN",
|
||||
"Exception",
|
||||
"Caused by:",
|
||||
"Application run failed",
|
||||
"BUILD\\s",
|
||||
"Tests run:",
|
||||
"FAILURE",
|
||||
"listening on port",
|
||||
]
|
||||
max_lines = 30
|
||||
|
||||
[[tests.spring-boot]]
|
||||
name = "keeps startup summary and errors"
|
||||
input = " . ____ _ \n /\\\\ / ___'_ __ _ _(_)_ __ \n( ( )\\___ | '_ | '_| | '_ \\ \n \\/ ___)| |_)| | | | | || )\n ' |____| .__|_| |_|_| |_\\__|\n :: Spring Boot :: (v3.2.0)\n2024-01-01 INFO Initializing Spring\n2024-01-01 INFO Bean 'dataSource' created\n2024-01-01 INFO Tomcat started on port 8080\n2024-01-01 INFO Started MyApp in 3.2 seconds"
|
||||
expected = "2024-01-01 INFO Tomcat started on port 8080\n2024-01-01 INFO Started MyApp in 3.2 seconds"
|
||||
|
||||
[[tests.spring-boot]]
|
||||
name = "preserves errors"
|
||||
input = " :: Spring Boot :: (v3.2.0)\n2024-01-01 INFO Initializing Spring\n2024-01-01 ERROR Application run failed\nCaused by: java.lang.NullPointerException"
|
||||
expected = "2024-01-01 ERROR Application run failed\nCaused by: java.lang.NullPointerException"
|
||||
@@ -0,0 +1,27 @@
|
||||
[filters.task]
|
||||
description = "Compact go-task output — strip task headers, keep command results"
|
||||
match_command = "^task\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^task: \\[.*\\] ",
|
||||
"^task: Task .* is up to date",
|
||||
]
|
||||
truncate_lines_at = 150
|
||||
max_lines = 50
|
||||
on_empty = "task: ok"
|
||||
|
||||
[[tests.task]]
|
||||
name = "strips task headers, keeps output"
|
||||
input = "task: [build] go build ./...\n\ntask: [test] go test ./...\nok myapp 0.5s\n\ntask: Task \"lint\" is up to date"
|
||||
expected = "ok myapp 0.5s"
|
||||
|
||||
[[tests.task]]
|
||||
name = "preserves error output"
|
||||
input = "task: [build] go build ./...\n./main.go:10: undefined: foo\ntask: Failed to run task \"build\": exit status 1"
|
||||
expected = "./main.go:10: undefined: foo\ntask: Failed to run task \"build\": exit status 1"
|
||||
|
||||
[[tests.task]]
|
||||
name = "all up to date"
|
||||
input = "task: Task \"build\" is up to date\ntask: Task \"lint\" is up to date\n"
|
||||
expected = "task: ok"
|
||||
@@ -0,0 +1,30 @@
|
||||
[filters.turbo]
|
||||
description = "Compact Turborepo output — strip cache status noise, keep task results"
|
||||
match_command = "^turbo\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*cache (hit|miss|bypass)",
|
||||
"^\\s*\\d+ packages in scope",
|
||||
"^\\s*Tasks:\\s+\\d+",
|
||||
"^\\s*Duration:\\s+",
|
||||
"^\\s*Remote caching (enabled|disabled)",
|
||||
]
|
||||
truncate_lines_at = 150
|
||||
max_lines = 50
|
||||
on_empty = "turbo: ok"
|
||||
|
||||
[[tests.turbo]]
|
||||
name = "strips cache noise, keeps task output"
|
||||
input = " cache hit, replaying logs abc123\n cache miss, executing abc456\n\n3 packages in scope\n\n> myapp:build\n\nCompiled successfully.\n\nTasks: 2 successful, 2 total (1 cached)\nDuration: 3.2s"
|
||||
expected = "> myapp:build\nCompiled successfully."
|
||||
|
||||
[[tests.turbo]]
|
||||
name = "preserves error output"
|
||||
input = "> myapp:lint\n\nError: src/index.ts(5,1): error TS2304\n\nTasks: 0 successful, 1 total\nDuration: 1.1s"
|
||||
expected = "> myapp:lint\nError: src/index.ts(5,1): error TS2304"
|
||||
|
||||
[[tests.turbo]]
|
||||
name = "empty after stripping"
|
||||
input = " cache hit, replaying logs abc\n\n"
|
||||
expected = "turbo: ok"
|
||||
@@ -0,0 +1,21 @@
|
||||
[filters.yadm]
|
||||
description = "Compact yadm (git wrapper) output — same filtering as git"
|
||||
match_command = "^yadm\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*\\(use \"git ",
|
||||
"^\\s*\\(use \"yadm ",
|
||||
]
|
||||
truncate_lines_at = 120
|
||||
max_lines = 40
|
||||
|
||||
[[tests.yadm]]
|
||||
name = "strips hint lines"
|
||||
input = "On branch main\nYour branch is up to date with 'origin/main'.\n\n (use \"yadm add\" to update what will be committed)\n\nChanges not staged for commit:\n modified: .bashrc"
|
||||
expected = "On branch main\nYour branch is up to date with 'origin/main'.\nChanges not staged for commit:\n modified: .bashrc"
|
||||
|
||||
[[tests.yadm]]
|
||||
name = "short output preserved"
|
||||
input = "Already up to date."
|
||||
expected = "Already up to date."
|
||||
+1
-1
@@ -305,7 +305,7 @@ pub fn run(
|
||||
let dirs_count = dirs.len();
|
||||
let total_files = files.len();
|
||||
|
||||
println!("📁 {}F {}D:", total_files, dirs_count);
|
||||
println!("{}F {}D:", total_files, dirs_count);
|
||||
println!();
|
||||
|
||||
// Display with proper --max limiting (count individual files)
|
||||
|
||||
+5
-8
@@ -168,7 +168,7 @@ fn filter_black_output(output: &str) -> String {
|
||||
// Split by comma to handle both parts
|
||||
for part in trimmed.split(',') {
|
||||
let part_lower = part.to_lowercase();
|
||||
let words: Vec<&str> = part.trim().split_whitespace().collect();
|
||||
let words: Vec<&str> = part.split_whitespace().collect();
|
||||
|
||||
if part_lower.contains("would be reformatted") {
|
||||
// Parse "X file(s) would be reformatted"
|
||||
@@ -226,7 +226,7 @@ fn filter_black_output(output: &str) -> String {
|
||||
|
||||
if !needs_formatting && (all_done || files_unchanged > 0) {
|
||||
// All files formatted correctly
|
||||
result.push_str("✓ Format (black): All files formatted");
|
||||
result.push_str("Format (black): All files formatted");
|
||||
if files_unchanged > 0 {
|
||||
result.push_str(&format!(" ({} files checked)", files_unchanged));
|
||||
}
|
||||
@@ -258,13 +258,10 @@ fn filter_black_output(output: &str) -> String {
|
||||
}
|
||||
|
||||
if files_unchanged > 0 {
|
||||
result.push_str(&format!(
|
||||
"\n✓ {} files already formatted\n",
|
||||
files_unchanged
|
||||
));
|
||||
result.push_str(&format!("\n{} files already formatted\n", files_unchanged));
|
||||
}
|
||||
|
||||
result.push_str("\n💡 Run `black .` to format these files\n");
|
||||
result.push_str("\n[hint] Run `black .` to format these files\n");
|
||||
} else {
|
||||
// Fallback: show raw output
|
||||
result.push_str(output.trim());
|
||||
@@ -349,7 +346,7 @@ mod tests {
|
||||
fn test_filter_black_all_formatted() {
|
||||
let output = "All done! ✨ 🍰 ✨\n5 files left unchanged.";
|
||||
let result = filter_black_output(output);
|
||||
assert!(result.contains("✓ Format (black)"));
|
||||
assert!(result.contains("Format (black)"));
|
||||
assert!(result.contains("All files formatted"));
|
||||
assert!(result.contains("5 files checked"));
|
||||
}
|
||||
|
||||
+4
-3
@@ -8,6 +8,7 @@ use serde::Serialize;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(
|
||||
project: bool, // added: per-project scope flag
|
||||
graph: bool,
|
||||
@@ -108,7 +109,7 @@ pub fn run(
|
||||
hook_check::HookStatus::Missing => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
"⚠️ No hook installed — run `rtk init -g` for automatic token savings"
|
||||
"[warn] No hook installed — run `rtk init -g` for automatic token savings"
|
||||
.yellow()
|
||||
);
|
||||
eprintln!();
|
||||
@@ -116,7 +117,7 @@ pub fn run(
|
||||
hook_check::HookStatus::Outdated => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
"⚠️ Hook outdated — run `rtk init -g` to update".yellow()
|
||||
"[warn] Hook outdated — run `rtk init -g` to update".yellow()
|
||||
);
|
||||
eprintln!();
|
||||
}
|
||||
@@ -658,7 +659,7 @@ fn check_rtk_disabled_bypass() -> Option<String> {
|
||||
let pct = (bypassed as f64 / total_bash as f64) * 100.0;
|
||||
if pct > 10.0 {
|
||||
Some(format!(
|
||||
"⚠️ {} commands ({:.0}%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details",
|
||||
"[warn] {} commands ({:.0}%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details",
|
||||
bypassed, pct
|
||||
))
|
||||
} else {
|
||||
|
||||
+48
-53
@@ -193,8 +193,8 @@ fn run_pr(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
"create" => pr_create(&args[1..], verbose),
|
||||
"merge" => pr_merge(&args[1..], verbose),
|
||||
"diff" => pr_diff(&args[1..], verbose),
|
||||
"comment" => pr_action("commented", &args, verbose),
|
||||
"edit" => pr_action("edited", &args, verbose),
|
||||
"comment" => pr_action("commented", args, verbose),
|
||||
"edit" => pr_action("edited", args, verbose),
|
||||
_ => run_passthrough("gh", "pr", args),
|
||||
}
|
||||
}
|
||||
@@ -235,8 +235,8 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
filtered.push_str("PRs\n");
|
||||
println!("PRs");
|
||||
} else {
|
||||
filtered.push_str("📋 Pull Requests\n");
|
||||
println!("📋 Pull Requests");
|
||||
filtered.push_str("Pull Requests\n");
|
||||
println!("Pull Requests");
|
||||
}
|
||||
|
||||
for pr in prs.iter().take(20) {
|
||||
@@ -254,10 +254,10 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
}
|
||||
} else {
|
||||
match state {
|
||||
"OPEN" => "🟢",
|
||||
"MERGED" => "🟣",
|
||||
"CLOSED" => "🔴",
|
||||
_ => "⚪",
|
||||
"OPEN" => "[open]",
|
||||
"MERGED" => "[merged]",
|
||||
"CLOSED" => "[closed]",
|
||||
_ => "[unknown]",
|
||||
}
|
||||
};
|
||||
|
||||
@@ -352,10 +352,10 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
}
|
||||
} else {
|
||||
match state {
|
||||
"OPEN" => "🟢",
|
||||
"MERGED" => "🟣",
|
||||
"CLOSED" => "🔴",
|
||||
_ => "⚪",
|
||||
"OPEN" => "[open]",
|
||||
"MERGED" => "[merged]",
|
||||
"CLOSED" => "[closed]",
|
||||
_ => "[unknown]",
|
||||
}
|
||||
};
|
||||
|
||||
@@ -368,8 +368,8 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
print!("{}", line);
|
||||
|
||||
let mergeable_str = match mergeable {
|
||||
"MERGEABLE" => "✓",
|
||||
"CONFLICTING" => "✗",
|
||||
"MERGEABLE" => "[ok]",
|
||||
"CONFLICTING" => "[x]",
|
||||
_ => "?",
|
||||
};
|
||||
let line = format!(" {} | {}\n", state, mergeable_str);
|
||||
@@ -417,11 +417,11 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
|
||||
if ultra_compact {
|
||||
if failed > 0 {
|
||||
let line = format!(" ✗{}/{} {} fail\n", passed, total, failed);
|
||||
let line = format!(" [x]{}/{} {} fail\n", passed, total, failed);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
} else {
|
||||
let line = format!(" ✓{}/{}\n", passed, total);
|
||||
let line = format!(" {}/{}\n", passed, total);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
}
|
||||
@@ -430,7 +430,7 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
if failed > 0 {
|
||||
let line = format!(" ⚠️ {} checks failed\n", failed);
|
||||
let line = format!(" [warn] {} checks failed\n", failed);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
}
|
||||
@@ -504,9 +504,9 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()>
|
||||
let mut failed_checks = Vec::new();
|
||||
|
||||
for line in stdout.lines() {
|
||||
if line.contains('✓') || line.contains("pass") {
|
||||
if line.contains("[ok]") || line.contains("pass") {
|
||||
passed += 1;
|
||||
} else if line.contains('✗') || line.contains("fail") {
|
||||
} else if line.contains("[x]") || line.contains("fail") {
|
||||
failed += 1;
|
||||
failed_checks.push(line.trim().to_string());
|
||||
} else if line.contains('*') || line.contains("pending") {
|
||||
@@ -516,20 +516,20 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()>
|
||||
|
||||
let mut filtered = String::new();
|
||||
|
||||
let line = "🔍 CI Checks Summary:\n";
|
||||
let line = "CI Checks Summary:\n";
|
||||
filtered.push_str(line);
|
||||
print!("{}", line);
|
||||
|
||||
let line = format!(" ✅ Passed: {}\n", passed);
|
||||
let line = format!(" [ok] Passed: {}\n", passed);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
|
||||
let line = format!(" ❌ Failed: {}\n", failed);
|
||||
let line = format!(" [FAIL] Failed: {}\n", failed);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
|
||||
if pending > 0 {
|
||||
let line = format!(" ⏳ Pending: {}\n", pending);
|
||||
let line = format!(" [pending] Pending: {}\n", pending);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
}
|
||||
@@ -581,7 +581,7 @@ fn pr_status(_verbose: u8, _ultra_compact: bool) -> Result<()> {
|
||||
let mut filtered = String::new();
|
||||
|
||||
if let Some(created_by) = json["createdBy"].as_array() {
|
||||
let line = format!("📝 Your PRs ({}):\n", created_by.len());
|
||||
let line = format!("Your PRs ({}):\n", created_by.len());
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
for pr in created_by.iter().take(5) {
|
||||
@@ -636,13 +636,8 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
|
||||
let mut filtered = String::new();
|
||||
|
||||
if let Some(issues) = json.as_array() {
|
||||
if ultra_compact {
|
||||
filtered.push_str("Issues\n");
|
||||
println!("Issues");
|
||||
} else {
|
||||
filtered.push_str("🐛 Issues\n");
|
||||
println!("🐛 Issues");
|
||||
}
|
||||
filtered.push_str("Issues\n");
|
||||
println!("Issues");
|
||||
for issue in issues.iter().take(20) {
|
||||
let number = issue["number"].as_i64().unwrap_or(0);
|
||||
let title = issue["title"].as_str().unwrap_or("???");
|
||||
@@ -656,9 +651,9 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
|
||||
}
|
||||
} else {
|
||||
if state == "OPEN" {
|
||||
"🟢"
|
||||
"[open]"
|
||||
} else {
|
||||
"🔴"
|
||||
"[closed]"
|
||||
}
|
||||
};
|
||||
let line = format!(" {} #{} {}\n", icon, number, truncate(title, 60));
|
||||
@@ -721,7 +716,11 @@ fn view_issue(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let author = json["author"]["login"].as_str().unwrap_or("???");
|
||||
let url = json["url"].as_str().unwrap_or("");
|
||||
|
||||
let icon = if state == "OPEN" { "🟢" } else { "🔴" };
|
||||
let icon = if state == "OPEN" {
|
||||
"[open]"
|
||||
} else {
|
||||
"[closed]"
|
||||
};
|
||||
|
||||
let mut filtered = String::new();
|
||||
|
||||
@@ -814,8 +813,8 @@ fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
filtered.push_str("Runs\n");
|
||||
println!("Runs");
|
||||
} else {
|
||||
filtered.push_str("🏃 Workflow Runs\n");
|
||||
println!("🏃 Workflow Runs");
|
||||
filtered.push_str("Workflow Runs\n");
|
||||
println!("Workflow Runs");
|
||||
}
|
||||
for run in runs {
|
||||
let id = run["databaseId"].as_i64().unwrap_or(0);
|
||||
@@ -825,8 +824,8 @@ fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
|
||||
let icon = if ultra_compact {
|
||||
match conclusion {
|
||||
"success" => "✓",
|
||||
"failure" => "✗",
|
||||
"success" => "[ok]",
|
||||
"failure" => "[x]",
|
||||
"cancelled" => "X",
|
||||
_ => {
|
||||
if status == "in_progress" {
|
||||
@@ -838,14 +837,14 @@ fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
}
|
||||
} else {
|
||||
match conclusion {
|
||||
"success" => "✅",
|
||||
"failure" => "❌",
|
||||
"cancelled" => "🚫",
|
||||
"success" => "[ok]",
|
||||
"failure" => "[FAIL]",
|
||||
"cancelled" => "[X]",
|
||||
_ => {
|
||||
if status == "in_progress" {
|
||||
"⏳"
|
||||
"[time]"
|
||||
} else {
|
||||
"⚪"
|
||||
"[pending]"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -910,7 +909,7 @@ fn view_run(args: &[String], _verbose: u8) -> Result<()> {
|
||||
|
||||
let mut filtered = String::new();
|
||||
|
||||
let line = format!("🏃 Workflow Run #{}\n", run_id);
|
||||
let line = format!("Workflow Run #{}\n", run_id);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
|
||||
@@ -924,8 +923,8 @@ fn view_run(args: &[String], _verbose: u8) -> Result<()> {
|
||||
// Skip successful jobs in compact mode
|
||||
continue;
|
||||
}
|
||||
if line.contains('✗') || line.contains("fail") {
|
||||
let formatted = format!(" ❌ {}\n", line.trim());
|
||||
if line.contains("[x]") || line.contains("fail") {
|
||||
let formatted = format!(" [FAIL] {}\n", line.trim());
|
||||
filtered.push_str(&formatted);
|
||||
print!("{}", formatted);
|
||||
}
|
||||
@@ -992,15 +991,11 @@ fn run_repo(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
|
||||
let forks = json["forkCount"].as_i64().unwrap_or(0);
|
||||
let private = json["isPrivate"].as_bool().unwrap_or(false);
|
||||
|
||||
let visibility = if private {
|
||||
"🔒 Private"
|
||||
} else {
|
||||
"🌐 Public"
|
||||
};
|
||||
let visibility = if private { "[private]" } else { "[public]" };
|
||||
|
||||
let mut filtered = String::new();
|
||||
|
||||
let line = format!("📦 {}/{}\n", owner, name);
|
||||
let line = format!("{}/{}\n", owner, name);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
|
||||
@@ -1014,7 +1009,7 @@ fn run_repo(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
|
||||
print!("{}", line);
|
||||
}
|
||||
|
||||
let line = format!(" ⭐ {} stars | 🔱 {} forks\n", stars, forks);
|
||||
let line = format!(" {} stars | {} forks\n", stars, forks);
|
||||
filtered.push_str(&line);
|
||||
print!("{}", line);
|
||||
|
||||
|
||||
+251
-67
@@ -1,3 +1,4 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
@@ -76,6 +77,9 @@ fn run_diff(
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.arg("diff");
|
||||
for arg in args {
|
||||
if arg == "--no-compact" {
|
||||
continue; // RTK flag, not a git flag
|
||||
}
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
@@ -111,6 +115,21 @@ fn run_diff(
|
||||
let output = cmd.output().context("Failed to run git diff")?;
|
||||
let stat_stdout = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
let raw = stat_stdout.to_string();
|
||||
timer.track(
|
||||
&format!("git diff {}", args.join(" ")),
|
||||
&format!("rtk git diff {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("Git diff summary:");
|
||||
}
|
||||
@@ -279,6 +298,7 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
let mut in_hunk = false;
|
||||
let mut hunk_lines = 0;
|
||||
let max_hunk_lines = 30;
|
||||
let mut was_truncated = false;
|
||||
|
||||
for line in diff.lines() {
|
||||
if line.starts_with("diff --git") {
|
||||
@@ -287,7 +307,7 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
result.push(format!(" +{} -{}", added, removed));
|
||||
}
|
||||
current_file = line.split(" b/").nth(1).unwrap_or("unknown").to_string();
|
||||
result.push(format!("\n📄 {}", current_file));
|
||||
result.push(format!("\n{}", current_file));
|
||||
added = 0;
|
||||
removed = 0;
|
||||
in_hunk = false;
|
||||
@@ -321,11 +341,13 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
if hunk_lines == max_hunk_lines {
|
||||
result.push(" ... (truncated)".to_string());
|
||||
hunk_lines += 1;
|
||||
was_truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if result.len() >= max_lines {
|
||||
result.push("\n... (more changes truncated)".to_string());
|
||||
was_truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -334,6 +356,10 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
result.push(format!(" +{} -{}", added, removed));
|
||||
}
|
||||
|
||||
if was_truncated {
|
||||
result.push("[full diff: rtk git diff --no-compact]".to_string());
|
||||
}
|
||||
|
||||
result.join("\n")
|
||||
}
|
||||
|
||||
@@ -355,7 +381,7 @@ fn run_log(
|
||||
|
||||
// Check if user provided limit flag (-N, -n N, --max-count=N, --max-count N)
|
||||
let has_limit_flag = args.iter().any(|arg| {
|
||||
(arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit()))
|
||||
(arg.starts_with('-') && arg.chars().nth(1).is_some_and(|c| c.is_ascii_digit()))
|
||||
|| arg == "-n"
|
||||
|| arg.starts_with("--max-count")
|
||||
});
|
||||
@@ -433,7 +459,7 @@ fn parse_user_limit(args: &[String]) -> Option<usize> {
|
||||
// -20 (combined digit form)
|
||||
if arg.starts_with('-')
|
||||
&& arg.len() > 1
|
||||
&& arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
|
||||
&& arg.chars().nth(1).is_some_and(|c| c.is_ascii_digit())
|
||||
{
|
||||
if let Ok(n) = arg[1..].parse::<usize>() {
|
||||
return Some(n);
|
||||
@@ -547,7 +573,7 @@ fn format_status_output(porcelain: &str) -> String {
|
||||
if let Some(branch_line) = lines.first() {
|
||||
if branch_line.starts_with("##") {
|
||||
let branch = branch_line.trim_start_matches("## ");
|
||||
output.push_str(&format!("📌 {}\n", branch));
|
||||
output.push_str(&format!("* {}\n", branch));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -592,38 +618,56 @@ fn format_status_output(porcelain: &str) -> String {
|
||||
}
|
||||
|
||||
// Build summary
|
||||
let limits = config::limits();
|
||||
let max_files = limits.status_max_files;
|
||||
let max_untracked = limits.status_max_untracked;
|
||||
|
||||
if staged > 0 {
|
||||
output.push_str(&format!("✅ Staged: {} files\n", staged));
|
||||
for f in staged_files.iter().take(5) {
|
||||
output.push_str(&format!("+ Staged: {} files\n", staged));
|
||||
for f in staged_files.iter().take(max_files) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
if staged_files.len() > 5 {
|
||||
output.push_str(&format!(" ... +{} more\n", staged_files.len() - 5));
|
||||
if staged_files.len() > max_files {
|
||||
output.push_str(&format!(
|
||||
" ... +{} more\n",
|
||||
staged_files.len() - max_files
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if modified > 0 {
|
||||
output.push_str(&format!("📝 Modified: {} files\n", modified));
|
||||
for f in modified_files.iter().take(5) {
|
||||
output.push_str(&format!("~ Modified: {} files\n", modified));
|
||||
for f in modified_files.iter().take(max_files) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
if modified_files.len() > 5 {
|
||||
output.push_str(&format!(" ... +{} more\n", modified_files.len() - 5));
|
||||
if modified_files.len() > max_files {
|
||||
output.push_str(&format!(
|
||||
" ... +{} more\n",
|
||||
modified_files.len() - max_files
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if untracked > 0 {
|
||||
output.push_str(&format!("❓ Untracked: {} files\n", untracked));
|
||||
for f in untracked_files.iter().take(3) {
|
||||
output.push_str(&format!("? Untracked: {} files\n", untracked));
|
||||
for f in untracked_files.iter().take(max_untracked) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
if untracked_files.len() > 3 {
|
||||
output.push_str(&format!(" ... +{} more\n", untracked_files.len() - 3));
|
||||
if untracked_files.len() > max_untracked {
|
||||
output.push_str(&format!(
|
||||
" ... +{} more\n",
|
||||
untracked_files.len() - max_untracked
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if conflicts > 0 {
|
||||
output.push_str(&format!("⚠️ Conflicts: {} files\n", conflicts));
|
||||
output.push_str(&format!("conflicts: {} files\n", conflicts));
|
||||
}
|
||||
|
||||
// When working tree is clean (only branch line, no changes)
|
||||
if staged == 0 && modified == 0 && untracked == 0 && conflicts == 0 {
|
||||
output.push_str("clean — nothing to commit\n");
|
||||
}
|
||||
|
||||
output.trim_end().to_string()
|
||||
@@ -660,7 +704,7 @@ fn filter_status_with_args(output: &str) -> String {
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
} else {
|
||||
result.join("\n")
|
||||
}
|
||||
@@ -680,6 +724,20 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
let raw = stdout.to_string();
|
||||
timer.track(
|
||||
&format!("git status {}", args.join(" ")),
|
||||
&format!("rtk git status {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
if verbose > 0 || !stderr.is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
@@ -772,9 +830,9 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
|
||||
// Parse "1 file changed, 5 insertions(+)" format
|
||||
let short = stat.lines().last().unwrap_or("").trim();
|
||||
if short.is_empty() {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
} else {
|
||||
format!("ok ✓ {}", short)
|
||||
format!("ok {}", short)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -833,17 +891,17 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
// Extract commit hash from output like "[main abc1234] message"
|
||||
let compact = if let Some(line) = stdout.lines().next() {
|
||||
if let Some(hash_start) = line.find(' ') {
|
||||
let hash = line[1..hash_start].split(' ').last().unwrap_or("");
|
||||
let hash = line[1..hash_start].split(' ').next_back().unwrap_or("");
|
||||
if !hash.is_empty() && hash.len() >= 7 {
|
||||
format!("ok ✓ {}", &hash[..7.min(hash.len())])
|
||||
format!("ok {}", &hash[..7.min(hash.len())])
|
||||
} else {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
}
|
||||
} else {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
}
|
||||
} else {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
};
|
||||
|
||||
println!("{}", compact);
|
||||
@@ -859,13 +917,14 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
"ok (nothing to commit)",
|
||||
);
|
||||
} else {
|
||||
eprintln!("FAILED: git commit");
|
||||
if !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr);
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
if !stdout.trim().is_empty() {
|
||||
eprintln!("{}", stdout);
|
||||
eprint!("{}", stdout);
|
||||
}
|
||||
timer.track(&original_cmd, "rtk git commit", &raw_output, &raw_output);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -900,7 +959,7 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
|
||||
if line.contains("->") {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 3 {
|
||||
result = format!("ok ✓ {}", parts[parts.len() - 1]);
|
||||
result = format!("ok {}", parts[parts.len() - 1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -908,7 +967,7 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
|
||||
if !result.is_empty() {
|
||||
result
|
||||
} else {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -992,9 +1051,9 @@ fn run_pull(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
|
||||
}
|
||||
|
||||
if files > 0 {
|
||||
format!("ok ✓ {} files +{} -{}", files, insertions, deletions)
|
||||
format!("ok {} files +{} -{}", files, insertions, deletions)
|
||||
} else {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1027,10 +1086,23 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
eprintln!("git branch");
|
||||
}
|
||||
|
||||
// Detect write operations: delete, rename, copy
|
||||
let has_action_flag = args
|
||||
.iter()
|
||||
.any(|a| a == "-d" || a == "-D" || a == "-m" || a == "-M" || a == "-c" || a == "-C");
|
||||
// Detect write operations: delete, rename, copy, upstream tracking
|
||||
let has_action_flag = args.iter().any(|a| {
|
||||
a == "-d"
|
||||
|| a == "-D"
|
||||
|| a == "-m"
|
||||
|| a == "-M"
|
||||
|| a == "-c"
|
||||
|| a == "-C"
|
||||
|| a == "--set-upstream-to"
|
||||
|| a.starts_with("--set-upstream-to=")
|
||||
|| a == "-u"
|
||||
|| a == "--unset-upstream"
|
||||
|| a == "--edit-description"
|
||||
});
|
||||
|
||||
// Detect flags that produce specific output (not a branch list)
|
||||
let has_show_flag = args.iter().any(|a| a == "--show-current");
|
||||
|
||||
// Detect list-mode flags
|
||||
let has_list_flag = args.iter().any(|a| {
|
||||
@@ -1043,11 +1115,49 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
|| a == "--no-merged"
|
||||
|| a == "--contains"
|
||||
|| a == "--no-contains"
|
||||
|| a == "--format"
|
||||
|| a.starts_with("--format=")
|
||||
|| a == "--sort"
|
||||
|| a.starts_with("--sort=")
|
||||
|| a == "--points-at"
|
||||
|| a.starts_with("--points-at=")
|
||||
});
|
||||
|
||||
// Detect positional arguments (not flags) — indicates branch creation
|
||||
let has_positional_arg = args.iter().any(|a| !a.starts_with('-'));
|
||||
|
||||
// --show-current: passthrough with raw stdout (not "ok ✓")
|
||||
if has_show_flag {
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.arg("branch");
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
let output = cmd.output().context("Failed to run git branch")?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let combined = format!("{}{}", stdout, stderr);
|
||||
|
||||
let trimmed = stdout.trim();
|
||||
timer.track(
|
||||
&format!("git branch {}", args.join(" ")),
|
||||
&format!("rtk git branch {}", args.join(" ")),
|
||||
&combined,
|
||||
trimmed,
|
||||
);
|
||||
|
||||
if output.status.success() {
|
||||
println!("{}", trimmed);
|
||||
} else {
|
||||
eprintln!("FAILED: git branch {}", args.join(" "));
|
||||
if !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr);
|
||||
}
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Write operation: action flags, or positional args without list flags (= branch creation)
|
||||
if has_action_flag || (has_positional_arg && !has_list_flag) {
|
||||
let mut cmd = git_cmd(global_args);
|
||||
@@ -1061,7 +1171,7 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
let combined = format!("{}{}", stdout, stderr);
|
||||
|
||||
let msg = if output.status.success() {
|
||||
"ok ✓"
|
||||
"ok"
|
||||
} else {
|
||||
&combined
|
||||
};
|
||||
@@ -1074,7 +1184,7 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
);
|
||||
|
||||
if output.status.success() {
|
||||
println!("ok ✓");
|
||||
println!("ok");
|
||||
} else {
|
||||
eprintln!("FAILED: git branch {}", args.join(" "));
|
||||
if !stderr.trim().is_empty() {
|
||||
@@ -1103,6 +1213,20 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let raw = stdout.to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("git branch {}", args.join(" ")),
|
||||
&format!("rtk git branch {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let filtered = filter_branch_output(&stdout);
|
||||
println!("{}", filtered);
|
||||
|
||||
@@ -1303,7 +1427,42 @@ fn run_stash(
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
Some(sub) => {
|
||||
// Unrecognized subcommand: passthrough to git stash <sub> [args]
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.args(["stash", sub]);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
let output = cmd.output().context("Failed to run git stash")?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let combined = format!("{}{}", stdout, stderr);
|
||||
|
||||
let msg = if output.status.success() {
|
||||
let msg = format!("ok stash {}", sub);
|
||||
println!("{}", msg);
|
||||
msg
|
||||
} else {
|
||||
eprintln!("FAILED: git stash {}", sub);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr);
|
||||
}
|
||||
combined.clone()
|
||||
};
|
||||
|
||||
timer.track(
|
||||
&format!("git stash {}", sub),
|
||||
&format!("rtk git stash {}", sub),
|
||||
&combined,
|
||||
&msg,
|
||||
);
|
||||
|
||||
if !output.status.success() {
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Default: git stash (push)
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.arg("stash");
|
||||
@@ -1389,7 +1548,7 @@ fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<
|
||||
let combined = format!("{}{}", stdout, stderr);
|
||||
|
||||
let msg = if output.status.success() {
|
||||
"ok ✓"
|
||||
"ok"
|
||||
} else {
|
||||
&combined
|
||||
};
|
||||
@@ -1402,7 +1561,7 @@ fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<
|
||||
);
|
||||
|
||||
if output.status.success() {
|
||||
println!("ok ✓");
|
||||
println!("ok");
|
||||
} else {
|
||||
eprintln!("FAILED: git worktree {}", args.join(" "));
|
||||
if !stderr.trim().is_empty() {
|
||||
@@ -1649,8 +1808,8 @@ mod tests {
|
||||
fn test_format_status_output_modified_files() {
|
||||
let porcelain = "## main...origin/main\n M src/main.rs\n M src/lib.rs\n";
|
||||
let result = format_status_output(porcelain);
|
||||
assert!(result.contains("📌 main...origin/main"));
|
||||
assert!(result.contains("📝 Modified: 2 files"));
|
||||
assert!(result.contains("* main...origin/main"));
|
||||
assert!(result.contains("~ Modified: 2 files"));
|
||||
assert!(result.contains("src/main.rs"));
|
||||
assert!(result.contains("src/lib.rs"));
|
||||
assert!(!result.contains("Staged"));
|
||||
@@ -1661,8 +1820,8 @@ mod tests {
|
||||
fn test_format_status_output_untracked_files() {
|
||||
let porcelain = "## feature/new\n?? temp.txt\n?? debug.log\n?? test.sh\n";
|
||||
let result = format_status_output(porcelain);
|
||||
assert!(result.contains("📌 feature/new"));
|
||||
assert!(result.contains("❓ Untracked: 3 files"));
|
||||
assert!(result.contains("* feature/new"));
|
||||
assert!(result.contains("? Untracked: 3 files"));
|
||||
assert!(result.contains("temp.txt"));
|
||||
assert!(result.contains("debug.log"));
|
||||
assert!(result.contains("test.sh"));
|
||||
@@ -1678,35 +1837,60 @@ A added.rs
|
||||
?? untracked.txt
|
||||
"#;
|
||||
let result = format_status_output(porcelain);
|
||||
assert!(result.contains("📌 main"));
|
||||
assert!(result.contains("✅ Staged: 2 files"));
|
||||
assert!(result.contains("* main"));
|
||||
assert!(result.contains("+ Staged: 2 files"));
|
||||
assert!(result.contains("staged.rs"));
|
||||
assert!(result.contains("added.rs"));
|
||||
assert!(result.contains("📝 Modified: 1 files"));
|
||||
assert!(result.contains("~ Modified: 1 files"));
|
||||
assert!(result.contains("modified.rs"));
|
||||
assert!(result.contains("❓ Untracked: 1 files"));
|
||||
assert!(result.contains("? Untracked: 1 files"));
|
||||
assert!(result.contains("untracked.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_status_output_truncation() {
|
||||
// Test that >5 staged files show "... +N more"
|
||||
let porcelain = r#"## main
|
||||
M file1.rs
|
||||
M file2.rs
|
||||
M file3.rs
|
||||
M file4.rs
|
||||
M file5.rs
|
||||
M file6.rs
|
||||
M file7.rs
|
||||
"#;
|
||||
let result = format_status_output(porcelain);
|
||||
assert!(result.contains("✅ Staged: 7 files"));
|
||||
// Test that >15 staged files show "... +N more"
|
||||
let mut porcelain = String::from("## main\n");
|
||||
for i in 1..=20 {
|
||||
porcelain.push_str(&format!("M file{}.rs\n", i));
|
||||
}
|
||||
let result = format_status_output(&porcelain);
|
||||
assert!(result.contains("+ Staged: 20 files"));
|
||||
assert!(result.contains("file1.rs"));
|
||||
assert!(result.contains("file5.rs"));
|
||||
assert!(result.contains("... +2 more"));
|
||||
assert!(!result.contains("file6.rs"));
|
||||
assert!(!result.contains("file7.rs"));
|
||||
assert!(result.contains("file15.rs"));
|
||||
assert!(result.contains("... +5 more"));
|
||||
assert!(!result.contains("file16.rs"));
|
||||
assert!(!result.contains("file20.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_status_modified_truncation() {
|
||||
// Test that >15 modified files show "... +N more"
|
||||
let mut porcelain = String::from("## main\n");
|
||||
for i in 1..=20 {
|
||||
porcelain.push_str(&format!(" M file{}.rs\n", i));
|
||||
}
|
||||
let result = format_status_output(&porcelain);
|
||||
assert!(result.contains("~ Modified: 20 files"));
|
||||
assert!(result.contains("file1.rs"));
|
||||
assert!(result.contains("file15.rs"));
|
||||
assert!(result.contains("... +5 more"));
|
||||
assert!(!result.contains("file16.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_status_untracked_truncation() {
|
||||
// Test that >10 untracked files show "... +N more"
|
||||
let mut porcelain = String::from("## main\n");
|
||||
for i in 1..=15 {
|
||||
porcelain.push_str(&format!("?? file{}.rs\n", i));
|
||||
}
|
||||
let result = format_status_output(&porcelain);
|
||||
assert!(result.contains("? Untracked: 15 files"));
|
||||
assert!(result.contains("file1.rs"));
|
||||
assert!(result.contains("file10.rs"));
|
||||
assert!(result.contains("... +5 more"));
|
||||
assert!(!result.contains("file11.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1916,7 +2100,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
let porcelain = "## main\n M สวัสดี.txt\n?? ทดสอบ.rs\n";
|
||||
let result = format_status_output(porcelain);
|
||||
// Should not panic
|
||||
assert!(result.contains("📌 main"));
|
||||
assert!(result.contains("* main"));
|
||||
assert!(result.contains("สวัสดี.txt"));
|
||||
assert!(result.contains("ทดสอบ.rs"));
|
||||
}
|
||||
@@ -1925,7 +2109,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
fn test_format_status_output_emoji_filename() {
|
||||
let porcelain = "## main\nA 🎉-party.txt\n M 日本語ファイル.rs\n";
|
||||
let result = format_status_output(porcelain);
|
||||
assert!(result.contains("📌 main"));
|
||||
assert!(result.contains("* main"));
|
||||
}
|
||||
|
||||
/// Regression test: --oneline and other user format flags must preserve all commits.
|
||||
|
||||
+9
-9
@@ -348,7 +348,7 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
|
||||
if !has_failures {
|
||||
return format!(
|
||||
"✓ Go test: {} passed in {} packages",
|
||||
"Go test: {} passed in {} packages",
|
||||
total_pass, total_packages
|
||||
);
|
||||
}
|
||||
@@ -372,7 +372,7 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
}
|
||||
|
||||
result.push_str(&format!(
|
||||
"\n📦 {} [build failed]\n",
|
||||
"\n{} [build failed]\n",
|
||||
compact_package_name(package)
|
||||
));
|
||||
|
||||
@@ -392,14 +392,14 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
}
|
||||
|
||||
result.push_str(&format!(
|
||||
"\n📦 {} ({} passed, {} failed)\n",
|
||||
"\n{} ({} passed, {} failed)\n",
|
||||
compact_package_name(package),
|
||||
pkg_result.pass,
|
||||
pkg_result.fail
|
||||
));
|
||||
|
||||
for (test, outputs) in &pkg_result.failed_tests {
|
||||
result.push_str(&format!(" ❌ {}\n", test));
|
||||
result.push_str(&format!(" [FAIL] {}\n", test));
|
||||
|
||||
// Show failure output (limit to key lines)
|
||||
let relevant_lines: Vec<&String> = outputs
|
||||
@@ -452,7 +452,7 @@ fn filter_go_build(output: &str) -> String {
|
||||
}
|
||||
|
||||
if errors.is_empty() {
|
||||
return "✓ Go build: Success".to_string();
|
||||
return "Go build: Success".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -484,7 +484,7 @@ fn filter_go_vet(output: &str) -> String {
|
||||
}
|
||||
|
||||
if issues.is_empty() {
|
||||
return "✓ Go vet: No issues found".to_string();
|
||||
return "Go vet: No issues found".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -524,7 +524,7 @@ mod tests {
|
||||
{"Time":"2024-01-01T10:00:02Z","Action":"pass","Package":"example.com/foo","Elapsed":0.5}"#;
|
||||
|
||||
let result = filter_go_test_json(output);
|
||||
assert!(result.contains("✓ Go test"));
|
||||
assert!(result.contains("Go test"));
|
||||
assert!(result.contains("1 passed"));
|
||||
assert!(result.contains("1 packages"));
|
||||
}
|
||||
@@ -547,7 +547,7 @@ mod tests {
|
||||
fn test_filter_go_build_success() {
|
||||
let output = "";
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("✓ Go build"));
|
||||
assert!(result.contains("Go build"));
|
||||
assert!(result.contains("Success"));
|
||||
}
|
||||
|
||||
@@ -567,7 +567,7 @@ main.go:15:2: cannot use x (type int) as type string"#;
|
||||
fn test_filter_go_vet_no_issues() {
|
||||
let output = "";
|
||||
let result = filter_go_vet(output);
|
||||
assert!(result.contains("✓ Go vet"));
|
||||
assert!(result.contains("Go vet"));
|
||||
assert!(result.contains("No issues found"));
|
||||
}
|
||||
|
||||
|
||||
+7
-3
@@ -1,3 +1,4 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::{resolved_command, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
@@ -9,8 +10,10 @@ struct Position {
|
||||
#[serde(rename = "Filename")]
|
||||
filename: String,
|
||||
#[serde(rename = "Line")]
|
||||
#[allow(dead_code)]
|
||||
line: usize,
|
||||
#[serde(rename = "Column")]
|
||||
#[allow(dead_code)]
|
||||
column: usize,
|
||||
}
|
||||
|
||||
@@ -19,6 +22,7 @@ struct Issue {
|
||||
#[serde(rename = "FromLinter")]
|
||||
from_linter: String,
|
||||
#[serde(rename = "Text")]
|
||||
#[allow(dead_code)]
|
||||
text: String,
|
||||
#[serde(rename = "Pos")]
|
||||
pos: Position,
|
||||
@@ -106,7 +110,7 @@ fn filter_golangci_json(output: &str) -> String {
|
||||
return format!(
|
||||
"golangci-lint (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, 500)
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -114,7 +118,7 @@ fn filter_golangci_json(output: &str) -> String {
|
||||
let issues = golangci_output.issues;
|
||||
|
||||
if issues.is_empty() {
|
||||
return "✓ golangci-lint: No issues found".to_string();
|
||||
return "golangci-lint: No issues found".to_string();
|
||||
}
|
||||
|
||||
let total_issues = issues.len();
|
||||
@@ -211,7 +215,7 @@ mod tests {
|
||||
fn test_filter_golangci_no_issues() {
|
||||
let output = r#"{"Issues":[]}"#;
|
||||
let result = filter_golangci_json(output);
|
||||
assert!(result.contains("✓ golangci-lint"));
|
||||
assert!(result.contains("golangci-lint"));
|
||||
assert!(result.contains("No issues found"));
|
||||
}
|
||||
|
||||
|
||||
+26
-18
@@ -1,9 +1,11 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(
|
||||
pattern: &str,
|
||||
path: &str,
|
||||
@@ -60,7 +62,7 @@ pub fn run(
|
||||
eprintln!("{}", stderr.trim());
|
||||
}
|
||||
}
|
||||
let msg = format!("🔍 0 for '{}'", pattern);
|
||||
let msg = format!("0 matches for '{}'", pattern);
|
||||
println!("{}", msg);
|
||||
timer.track(
|
||||
&format!("grep -rn '{}' {}", pattern, path),
|
||||
@@ -77,6 +79,13 @@ pub fn run(
|
||||
let mut by_file: HashMap<String, Vec<(usize, String)>> = HashMap::new();
|
||||
let mut total = 0;
|
||||
|
||||
// Compile context regex once (instead of per-line in clean_line)
|
||||
let context_re = if context_only {
|
||||
Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
for line in stdout.lines() {
|
||||
let parts: Vec<&str> = line.splitn(3, ':').collect();
|
||||
|
||||
@@ -91,12 +100,12 @@ pub fn run(
|
||||
};
|
||||
|
||||
total += 1;
|
||||
let cleaned = clean_line(content, max_line_len, context_only, pattern);
|
||||
let cleaned = clean_line(content, max_line_len, context_re.as_ref(), pattern);
|
||||
by_file.entry(file).or_default().push((line_num, cleaned));
|
||||
}
|
||||
|
||||
let mut rtk_output = String::new();
|
||||
rtk_output.push_str(&format!("🔍 {} in {}F:\n\n", total, by_file.len()));
|
||||
rtk_output.push_str(&format!("{} matches in {}F:\n\n", total, by_file.len()));
|
||||
|
||||
let mut shown = 0;
|
||||
let mut files: Vec<_> = by_file.iter().collect();
|
||||
@@ -108,9 +117,10 @@ pub fn run(
|
||||
}
|
||||
|
||||
let file_display = compact_path(file);
|
||||
rtk_output.push_str(&format!("📄 {} ({}):\n", file_display, matches.len()));
|
||||
rtk_output.push_str(&format!("[file] {} ({}):\n", file_display, matches.len()));
|
||||
|
||||
for (line_num, content) in matches.iter().take(10) {
|
||||
let per_file = config::limits().grep_max_per_file;
|
||||
for (line_num, content) in matches.iter().take(per_file) {
|
||||
rtk_output.push_str(&format!(" {:>4}: {}\n", line_num, content));
|
||||
shown += 1;
|
||||
if shown >= max_results {
|
||||
@@ -118,8 +128,8 @@ pub fn run(
|
||||
}
|
||||
}
|
||||
|
||||
if matches.len() > 10 {
|
||||
rtk_output.push_str(&format!(" +{}\n", matches.len() - 10));
|
||||
if matches.len() > per_file {
|
||||
rtk_output.push_str(&format!(" +{}\n", matches.len() - per_file));
|
||||
}
|
||||
rtk_output.push('\n');
|
||||
}
|
||||
@@ -143,16 +153,14 @@ pub fn run(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_line(line: &str, max_len: usize, context_only: bool, pattern: &str) -> String {
|
||||
fn clean_line(line: &str, max_len: usize, context_re: Option<&Regex>, pattern: &str) -> String {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if context_only {
|
||||
if let Ok(re) = Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))) {
|
||||
if let Some(m) = re.find(trimmed) {
|
||||
let matched = m.as_str();
|
||||
if matched.len() <= max_len {
|
||||
return matched.to_string();
|
||||
}
|
||||
if let Some(re) = context_re {
|
||||
if let Some(m) = re.find(trimmed) {
|
||||
let matched = m.as_str();
|
||||
if matched.len() <= max_len {
|
||||
return matched.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,7 +224,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_clean_line() {
|
||||
let line = " const result = someFunction();";
|
||||
let cleaned = clean_line(line, 50, false, "result");
|
||||
let cleaned = clean_line(line, 50, None, "result");
|
||||
assert!(!cleaned.starts_with(' '));
|
||||
assert!(cleaned.len() <= 50);
|
||||
}
|
||||
@@ -240,7 +248,7 @@ mod tests {
|
||||
fn test_clean_line_multibyte() {
|
||||
// Thai text that exceeds max_len in bytes
|
||||
let line = " สวัสดีครับ นี่คือข้อความที่ยาวมากสำหรับทดสอบ ";
|
||||
let cleaned = clean_line(line, 20, false, "ครับ");
|
||||
let cleaned = clean_line(line, 20, None, "ครับ");
|
||||
// Should not panic
|
||||
assert!(!cleaned.is_empty());
|
||||
}
|
||||
@@ -248,7 +256,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_clean_line_emoji() {
|
||||
let line = "🎉🎊🎈🎁🎂🎄 some text 🎃🎆🎇✨";
|
||||
let cleaned = clean_line(line, 15, false, "text");
|
||||
let cleaned = clean_line(line, 15, None, "text");
|
||||
assert!(!cleaned.is_empty());
|
||||
}
|
||||
|
||||
|
||||
+47
-48
@@ -507,7 +507,7 @@ pub fn uninstall(global: bool, verbose: u8) -> Result<()> {
|
||||
fs::write(&claude_md_path, cleaned).with_context(|| {
|
||||
format!("Failed to write CLAUDE.md: {}", claude_md_path.display())
|
||||
})?;
|
||||
removed.push(format!("CLAUDE.md: removed @RTK.md reference"));
|
||||
removed.push("CLAUDE.md: removed @RTK.md reference".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,7 +566,7 @@ fn patch_settings_json(
|
||||
};
|
||||
|
||||
// Check idempotency
|
||||
if hook_already_present(&root, &hook_command) {
|
||||
if hook_already_present(&root, hook_command) {
|
||||
if verbose > 0 {
|
||||
eprintln!("settings.json: hook already present");
|
||||
}
|
||||
@@ -591,7 +591,7 @@ fn patch_settings_json(
|
||||
}
|
||||
|
||||
// Deep-merge hook
|
||||
insert_hook_entry(&mut root, &hook_command);
|
||||
insert_hook_entry(&mut root, hook_command);
|
||||
|
||||
// Backup original
|
||||
if settings_path.exists() {
|
||||
@@ -637,7 +637,6 @@ fn clean_double_blanks(content: &str) -> String {
|
||||
if line.trim().is_empty() {
|
||||
// Count consecutive blank lines
|
||||
let mut blank_count = 0;
|
||||
let start = i;
|
||||
while i < lines.len() && lines[i].trim().is_empty() {
|
||||
blank_count += 1;
|
||||
i += 1;
|
||||
@@ -645,9 +644,7 @@ fn clean_double_blanks(content: &str) -> String {
|
||||
|
||||
// Keep at most 2 blank lines
|
||||
let keep = blank_count.min(2);
|
||||
for _ in 0..keep {
|
||||
result.push("");
|
||||
}
|
||||
result.extend(std::iter::repeat_n("", keep));
|
||||
} else {
|
||||
result.push(line);
|
||||
i += 1;
|
||||
@@ -725,7 +722,7 @@ fn run_default_mode(
|
||||
_verbose: u8,
|
||||
_install_opencode: bool,
|
||||
) -> Result<()> {
|
||||
eprintln!("⚠️ Hook-based mode requires Unix (macOS/Linux).");
|
||||
eprintln!("[warn] Hook-based mode requires Unix (macOS/Linux).");
|
||||
eprintln!(" Windows: use --claude-md mode for full injection.");
|
||||
eprintln!(" Falling back to --claude-md mode.");
|
||||
run_claude_md_mode(_global, _verbose, _install_opencode)
|
||||
@@ -782,7 +779,7 @@ fn run_default_mode(
|
||||
println!(" CLAUDE.md: @RTK.md reference added");
|
||||
|
||||
if migrated {
|
||||
println!("\n ✅ Migrated: removed 137-line RTK block from CLAUDE.md");
|
||||
println!("\n [ok] Migrated: removed 137-line RTK block from CLAUDE.md");
|
||||
println!(" replaced with @RTK.md (10 lines)");
|
||||
}
|
||||
|
||||
@@ -883,7 +880,7 @@ fn run_hook_only_mode(
|
||||
install_opencode: bool,
|
||||
) -> Result<()> {
|
||||
if !global {
|
||||
eprintln!("⚠️ Warning: --hook-only only makes sense with --global");
|
||||
eprintln!("[warn] Warning: --hook-only only makes sense with --global");
|
||||
eprintln!(" For local projects, use default mode or --claude-md");
|
||||
return Ok(());
|
||||
}
|
||||
@@ -966,22 +963,22 @@ fn run_claude_md_mode(global: bool, verbose: u8, install_opencode: bool) -> Resu
|
||||
match action {
|
||||
RtkBlockUpsert::Added => {
|
||||
fs::write(&path, new_content)?;
|
||||
println!("✅ Added rtk instructions to existing {}", path.display());
|
||||
println!("[ok] Added rtk instructions to existing {}", path.display());
|
||||
}
|
||||
RtkBlockUpsert::Updated => {
|
||||
fs::write(&path, new_content)?;
|
||||
println!("✅ Updated rtk instructions in {}", path.display());
|
||||
println!("[ok] Updated rtk instructions in {}", path.display());
|
||||
}
|
||||
RtkBlockUpsert::Unchanged => {
|
||||
println!(
|
||||
"✅ {} already contains up-to-date rtk instructions",
|
||||
"[ok] {} already contains up-to-date rtk instructions",
|
||||
path.display()
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
RtkBlockUpsert::Malformed => {
|
||||
eprintln!(
|
||||
"⚠️ Warning: Found '<!-- rtk-instructions' without closing marker in {}",
|
||||
"[warn] Warning: Found '<!-- rtk-instructions' without closing marker in {}",
|
||||
path.display()
|
||||
);
|
||||
|
||||
@@ -1004,7 +1001,7 @@ fn run_claude_md_mode(global: bool, verbose: u8, install_opencode: bool) -> Resu
|
||||
}
|
||||
} else {
|
||||
fs::write(&path, RTK_INSTRUCTIONS)?;
|
||||
println!("✅ Created {} with rtk instructions", path.display());
|
||||
println!("[ok] Created {} with rtk instructions", path.display());
|
||||
}
|
||||
|
||||
if global {
|
||||
@@ -1012,7 +1009,7 @@ fn run_claude_md_mode(global: bool, verbose: u8, install_opencode: bool) -> Resu
|
||||
let opencode_plugin_path = prepare_opencode_plugin_path()?;
|
||||
ensure_opencode_plugin_installed(&opencode_plugin_path, verbose)?;
|
||||
println!(
|
||||
"✅ OpenCode plugin installed: {}",
|
||||
"[ok] OpenCode plugin installed: {}",
|
||||
opencode_plugin_path.display()
|
||||
);
|
||||
}
|
||||
@@ -1154,7 +1151,7 @@ fn remove_rtk_block(content: &str) -> (String, bool) {
|
||||
|
||||
(result, true) // migrated
|
||||
} else if content.contains("<!-- rtk-instructions") {
|
||||
eprintln!("⚠️ Warning: Found '<!-- rtk-instructions' without closing marker.");
|
||||
eprintln!("[warn] Warning: Found '<!-- rtk-instructions' without closing marker.");
|
||||
eprintln!(" This can happen if CLAUDE.md was manually edited.");
|
||||
|
||||
// Find line number
|
||||
@@ -1241,7 +1238,7 @@ pub fn show_config() -> Result<()> {
|
||||
let global_claude_md = claude_dir.join("CLAUDE.md");
|
||||
let local_claude_md = PathBuf::from("CLAUDE.md");
|
||||
|
||||
println!("📋 rtk Configuration:\n");
|
||||
println!("rtk Configuration:\n");
|
||||
|
||||
// Check hook
|
||||
if hook_path.exists() {
|
||||
@@ -1260,12 +1257,12 @@ pub fn show_config() -> Result<()> {
|
||||
|
||||
if !is_executable {
|
||||
println!(
|
||||
"⚠️ Hook: {} (NOT executable - run: chmod +x)",
|
||||
"[warn] Hook: {} (NOT executable - run: chmod +x)",
|
||||
hook_path.display()
|
||||
);
|
||||
} else if !is_thin_delegator {
|
||||
println!(
|
||||
"⚠️ Hook: {} (outdated — inline logic, not thin delegator)",
|
||||
"[warn] Hook: {} (outdated — inline logic, not thin delegator)",
|
||||
hook_path.display()
|
||||
);
|
||||
println!(
|
||||
@@ -1273,47 +1270,50 @@ pub fn show_config() -> Result<()> {
|
||||
);
|
||||
} else if is_executable && has_guards {
|
||||
println!(
|
||||
"✅ Hook: {} (thin delegator, version {})",
|
||||
"[ok] Hook: {} (thin delegator, version {})",
|
||||
hook_path.display(),
|
||||
hook_version
|
||||
);
|
||||
} else {
|
||||
println!("⚠️ Hook: {} (no guards - outdated)", hook_path.display());
|
||||
println!(
|
||||
"[warn] Hook: {} (no guards - outdated)",
|
||||
hook_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
println!("✅ Hook: {} (exists)", hook_path.display());
|
||||
println!("[ok] Hook: {} (exists)", hook_path.display());
|
||||
}
|
||||
} else {
|
||||
println!("⚪ Hook: not found");
|
||||
println!("[--] Hook: not found");
|
||||
}
|
||||
|
||||
// Check RTK.md
|
||||
if rtk_md_path.exists() {
|
||||
println!("✅ RTK.md: {} (slim mode)", rtk_md_path.display());
|
||||
println!("[ok] RTK.md: {} (slim mode)", rtk_md_path.display());
|
||||
} else {
|
||||
println!("⚪ RTK.md: not found");
|
||||
println!("[--] RTK.md: not found");
|
||||
}
|
||||
|
||||
// Check hook integrity
|
||||
match integrity::verify_hook_at(&hook_path) {
|
||||
Ok(integrity::IntegrityStatus::Verified) => {
|
||||
println!("✅ Integrity: hook hash verified");
|
||||
println!("[ok] Integrity: hook hash verified");
|
||||
}
|
||||
Ok(integrity::IntegrityStatus::Tampered { .. }) => {
|
||||
println!("❌ Integrity: hook modified outside rtk init (run: rtk verify)");
|
||||
println!("[FAIL] Integrity: hook modified outside rtk init (run: rtk verify)");
|
||||
}
|
||||
Ok(integrity::IntegrityStatus::NoBaseline) => {
|
||||
println!("⚠️ Integrity: no baseline hash (run: rtk init -g to establish)");
|
||||
println!("[warn] Integrity: no baseline hash (run: rtk init -g to establish)");
|
||||
}
|
||||
Ok(integrity::IntegrityStatus::NotInstalled)
|
||||
| Ok(integrity::IntegrityStatus::OrphanedHash) => {
|
||||
// Don't show integrity line if hook isn't installed
|
||||
}
|
||||
Err(_) => {
|
||||
println!("⚠️ Integrity: check failed");
|
||||
println!("[warn] Integrity: check failed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1321,28 +1321,28 @@ pub fn show_config() -> Result<()> {
|
||||
if global_claude_md.exists() {
|
||||
let content = fs::read_to_string(&global_claude_md)?;
|
||||
if content.contains("@RTK.md") {
|
||||
println!("✅ Global (~/.claude/CLAUDE.md): @RTK.md reference");
|
||||
println!("[ok] Global (~/.claude/CLAUDE.md): @RTK.md reference");
|
||||
} else if content.contains("<!-- rtk-instructions") {
|
||||
println!(
|
||||
"⚠️ Global (~/.claude/CLAUDE.md): old RTK block (run: rtk init -g to migrate)"
|
||||
"[warn] Global (~/.claude/CLAUDE.md): old RTK block (run: rtk init -g to migrate)"
|
||||
);
|
||||
} else {
|
||||
println!("⚪ Global (~/.claude/CLAUDE.md): exists but rtk not configured");
|
||||
println!("[--] Global (~/.claude/CLAUDE.md): exists but rtk not configured");
|
||||
}
|
||||
} else {
|
||||
println!("⚪ Global (~/.claude/CLAUDE.md): not found");
|
||||
println!("[--] Global (~/.claude/CLAUDE.md): not found");
|
||||
}
|
||||
|
||||
// Check local CLAUDE.md
|
||||
if local_claude_md.exists() {
|
||||
let content = fs::read_to_string(&local_claude_md)?;
|
||||
if content.contains("rtk") {
|
||||
println!("✅ Local (./CLAUDE.md): rtk enabled");
|
||||
println!("[ok] Local (./CLAUDE.md): rtk enabled");
|
||||
} else {
|
||||
println!("⚪ Local (./CLAUDE.md): exists but rtk not configured");
|
||||
println!("[--] Local (./CLAUDE.md): exists but rtk not configured");
|
||||
}
|
||||
} else {
|
||||
println!("⚪ Local (./CLAUDE.md): not found");
|
||||
println!("[--] Local (./CLAUDE.md): not found");
|
||||
}
|
||||
|
||||
// Check settings.json
|
||||
@@ -1353,31 +1353,31 @@ pub fn show_config() -> Result<()> {
|
||||
if let Ok(root) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
let hook_command = hook_path.display().to_string();
|
||||
if hook_already_present(&root, &hook_command) {
|
||||
println!("✅ settings.json: RTK hook configured");
|
||||
println!("[ok] settings.json: RTK hook configured");
|
||||
} else {
|
||||
println!("⚠️ settings.json: exists but RTK hook not configured");
|
||||
println!("[warn] settings.json: exists but RTK hook not configured");
|
||||
println!(" Run: rtk init -g --auto-patch");
|
||||
}
|
||||
} else {
|
||||
println!("⚠️ settings.json: exists but invalid JSON");
|
||||
println!("[warn] settings.json: exists but invalid JSON");
|
||||
}
|
||||
} else {
|
||||
println!("⚪ settings.json: empty");
|
||||
println!("[--] settings.json: empty");
|
||||
}
|
||||
} else {
|
||||
println!("⚪ settings.json: not found");
|
||||
println!("[--] settings.json: not found");
|
||||
}
|
||||
|
||||
// Check OpenCode plugin
|
||||
if let Ok(opencode_dir) = resolve_opencode_dir() {
|
||||
let plugin = opencode_plugin_path(&opencode_dir);
|
||||
if plugin.exists() {
|
||||
println!("✅ OpenCode: plugin installed ({})", plugin.display());
|
||||
println!("[ok] OpenCode: plugin installed ({})", plugin.display());
|
||||
} else {
|
||||
println!("⚪ OpenCode: plugin not found");
|
||||
println!("[--] OpenCode: plugin not found");
|
||||
}
|
||||
} else {
|
||||
println!("⚪ OpenCode: config dir not found");
|
||||
println!("[--] OpenCode: config dir not found");
|
||||
}
|
||||
|
||||
println!("\nUsage:");
|
||||
@@ -1405,7 +1405,6 @@ fn run_opencode_only_mode(verbose: u8) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
@@ -1774,8 +1773,8 @@ More notes
|
||||
let serialized = serde_json::to_string(&parsed).unwrap();
|
||||
|
||||
// Keys should appear in same order
|
||||
let original_keys: Vec<&str> = original.split("\"").filter(|s| s.contains(":")).collect();
|
||||
let serialized_keys: Vec<&str> =
|
||||
let _original_keys: Vec<&str> = original.split("\"").filter(|s| s.contains(":")).collect();
|
||||
let _serialized_keys: Vec<&str> =
|
||||
serialized.split("\"").filter(|s| s.contains(":")).collect();
|
||||
|
||||
// Just check that keys exist (preserve_order doesn't guarantee exact order in nested objects)
|
||||
|
||||
@@ -5,6 +5,7 @@ use regex::Regex;
|
||||
pub enum ErrorType {
|
||||
UnknownFlag,
|
||||
CommandNotFound,
|
||||
#[allow(dead_code)]
|
||||
WrongSyntax,
|
||||
WrongPath,
|
||||
MissingArg,
|
||||
@@ -229,9 +230,7 @@ pub fn find_corrections(commands: &[CommandExecution]) -> Vec<CorrectionPair> {
|
||||
}
|
||||
|
||||
// Look ahead for correction within CORRECTION_WINDOW
|
||||
for j in (i + 1)..std::cmp::min(i + 1 + CORRECTION_WINDOW, commands.len()) {
|
||||
let candidate = &commands[j];
|
||||
|
||||
for candidate in commands.iter().skip(i + 1).take(CORRECTION_WINDOW) {
|
||||
let similarity = command_similarity(&cmd.command, &candidate.command);
|
||||
|
||||
// Must meet minimum similarity
|
||||
|
||||
+11
-8
@@ -1,3 +1,4 @@
|
||||
use crate::config;
|
||||
use crate::mypy_cmd;
|
||||
use crate::ruff_cmd;
|
||||
use crate::tracking;
|
||||
@@ -35,11 +36,13 @@ struct PylintDiagnostic {
|
||||
module: String,
|
||||
#[allow(dead_code)]
|
||||
obj: String,
|
||||
#[allow(dead_code)]
|
||||
line: usize,
|
||||
#[allow(dead_code)]
|
||||
column: usize,
|
||||
path: String,
|
||||
symbol: String, // rule code like "unused-variable"
|
||||
#[allow(dead_code)]
|
||||
message: String,
|
||||
#[serde(rename = "message-id")]
|
||||
message_id: String, // e.g., "W0612"
|
||||
@@ -169,7 +172,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
// Check if process was killed by signal (SIGABRT, SIGKILL, etc.)
|
||||
if !output.status.success() && output.status.code().is_none() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprintln!("⚠️ Linter process terminated abnormally (possibly out of memory)");
|
||||
eprintln!("[warn] Linter process terminated abnormally (possibly out of memory)");
|
||||
if !stderr.is_empty() {
|
||||
eprintln!(
|
||||
"stderr: {}",
|
||||
@@ -191,7 +194,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
if !stdout.trim().is_empty() {
|
||||
ruff_cmd::filter_ruff_check_json(&stdout)
|
||||
} else {
|
||||
"✓ Ruff: No issues found".to_string()
|
||||
"Ruff: No issues found".to_string()
|
||||
}
|
||||
}
|
||||
"pylint" => filter_pylint_json(&stdout),
|
||||
@@ -234,7 +237,7 @@ fn filter_eslint_json(output: &str) -> String {
|
||||
return format!(
|
||||
"ESLint output (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, 500)
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -245,7 +248,7 @@ fn filter_eslint_json(output: &str) -> String {
|
||||
let total_files = results.iter().filter(|r| !r.messages.is_empty()).count();
|
||||
|
||||
if total_errors == 0 && total_warnings == 0 {
|
||||
return "✓ ESLint: No issues found".to_string();
|
||||
return "ESLint: No issues found".to_string();
|
||||
}
|
||||
|
||||
// Group messages by rule
|
||||
@@ -326,13 +329,13 @@ fn filter_pylint_json(output: &str) -> String {
|
||||
return format!(
|
||||
"Pylint output (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, 500)
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if diagnostics.is_empty() {
|
||||
return "✓ Pylint: No issues found".to_string();
|
||||
return "Pylint: No issues found".to_string();
|
||||
}
|
||||
|
||||
// Count by type
|
||||
@@ -451,7 +454,7 @@ fn filter_generic_lint(output: &str) -> String {
|
||||
}
|
||||
|
||||
if errors == 0 && warnings == 0 {
|
||||
return "✓ Lint: No issues found".to_string();
|
||||
return "Lint: No issues found".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -553,7 +556,7 @@ mod tests {
|
||||
fn test_filter_pylint_json_no_issues() {
|
||||
let output = "[]";
|
||||
let result = filter_pylint_json(output);
|
||||
assert!(result.contains("✓ Pylint"));
|
||||
assert!(result.contains("Pylint"));
|
||||
assert!(result.contains("No issues found"));
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -105,23 +105,23 @@ fn analyze_logs(content: &str) -> String {
|
||||
let total_warnings: usize = warn_counts.values().sum();
|
||||
let total_info: usize = info_counts.values().sum();
|
||||
|
||||
result.push(format!("📊 Log Summary"));
|
||||
result.push("Log Summary".to_string());
|
||||
result.push(format!(
|
||||
" ❌ {} errors ({} unique)",
|
||||
" [error] {} errors ({} unique)",
|
||||
total_errors,
|
||||
error_counts.len()
|
||||
));
|
||||
result.push(format!(
|
||||
" ⚠️ {} warnings ({} unique)",
|
||||
" [warn] {} warnings ({} unique)",
|
||||
total_warnings,
|
||||
warn_counts.len()
|
||||
));
|
||||
result.push(format!(" ℹ️ {} info messages", total_info));
|
||||
result.push(format!(" [info] {} info messages", total_info));
|
||||
result.push(String::new());
|
||||
|
||||
// Errors with counts
|
||||
if !unique_errors.is_empty() {
|
||||
result.push("❌ ERRORS:".to_string());
|
||||
result.push("[ERRORS]".to_string());
|
||||
|
||||
// Sort by count
|
||||
let mut error_list: Vec<_> = error_counts.iter().collect();
|
||||
@@ -163,7 +163,7 @@ fn analyze_logs(content: &str) -> String {
|
||||
|
||||
// Warnings with counts
|
||||
if !unique_warnings.is_empty() {
|
||||
result.push("⚠️ WARNINGS:".to_string());
|
||||
result.push("[WARNINGS]".to_string());
|
||||
|
||||
let mut warn_list: Vec<_> = warn_counts.iter().collect();
|
||||
warn_list.sort_by(|a, b| b.1.cmp(a.1));
|
||||
|
||||
@@ -203,7 +203,7 @@ fn compact_ls(raw: &str, show_all: bool) -> String {
|
||||
|
||||
// Summary line
|
||||
out.push('\n');
|
||||
let mut summary = format!("📊 {} files, {} dirs", files.len(), dirs.len());
|
||||
let mut summary = format!("{} files, {} dirs", files.len(), dirs.len());
|
||||
if !by_ext.is_empty() {
|
||||
let mut ext_counts: Vec<_> = by_ext.iter().collect();
|
||||
ext_counts.sort_by(|a, b| b.1.cmp(a.1));
|
||||
@@ -291,7 +291,7 @@ mod tests {
|
||||
-rw-r--r-- 1 user staff 5678 Jan 1 12:00 lib.rs\n\
|
||||
-rw-r--r-- 1 user staff 100 Jan 1 12:00 Cargo.toml\n";
|
||||
let output = compact_ls(input, false);
|
||||
assert!(output.contains("📊 3 files, 1 dirs"));
|
||||
assert!(output.contains("3 files, 1 dirs"));
|
||||
assert!(output.contains(".rs"));
|
||||
assert!(output.contains(".toml"));
|
||||
}
|
||||
|
||||
+7
-7
@@ -306,7 +306,7 @@ enum Commands {
|
||||
#[arg(short = 'l', long, default_value = "80")]
|
||||
max_len: usize,
|
||||
/// Max results to show
|
||||
#[arg(short, long, default_value = "50")]
|
||||
#[arg(short, long, default_value = "200")]
|
||||
max: usize,
|
||||
/// Show only match context (not full line)
|
||||
#[arg(short, long)]
|
||||
@@ -691,25 +691,25 @@ enum GitCommands {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Add files → "ok ✓"
|
||||
/// Add files → "ok"
|
||||
Add {
|
||||
/// Files and flags to add (supports all git add flags like -A, -p, --all, etc)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Commit → "ok ✓ \<hash\>"
|
||||
/// Commit → "ok \<hash\>"
|
||||
Commit {
|
||||
/// Git commit arguments (supports -a, -m, --amend, --allow-empty, etc)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Push → "ok ✓ \<branch\>"
|
||||
/// Push → "ok \<branch\>"
|
||||
Push {
|
||||
/// Git push arguments (supports -u, remote, branch, etc.)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Pull → "ok ✓ \<stats\>"
|
||||
/// Pull → "ok \<stats\>"
|
||||
Pull {
|
||||
/// Git pull arguments (supports --rebase, remote, branch, etc.)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
@@ -1179,11 +1179,11 @@ enum GtCommands {
|
||||
fn shell_split(input: &str) -> Vec<String> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
let chars = input.chars();
|
||||
let mut in_single = false;
|
||||
let mut in_double = false;
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
for c in chars {
|
||||
match c {
|
||||
'\'' if !in_double => in_single = !in_single,
|
||||
'"' if !in_single => in_double = !in_double,
|
||||
|
||||
+5
-5
@@ -125,14 +125,14 @@ fn filter_next_build(output: &str) -> String {
|
||||
|
||||
// Build filtered output
|
||||
let mut result = String::new();
|
||||
result.push_str("⚡ Next.js Build\n");
|
||||
result.push_str("Next.js Build\n");
|
||||
result.push_str("═══════════════════════════════════════\n");
|
||||
|
||||
if already_built && routes_total == 0 {
|
||||
result.push_str("✓ Already built (using cache)\n\n");
|
||||
result.push_str("Already built (using cache)\n\n");
|
||||
} else if routes_total > 0 {
|
||||
result.push_str(&format!(
|
||||
"✓ {} routes ({} static, {} dynamic)\n\n",
|
||||
"{} routes ({} static, {} dynamic)\n\n",
|
||||
routes_total, routes_static, routes_dynamic
|
||||
));
|
||||
}
|
||||
@@ -146,7 +146,7 @@ fn filter_next_build(output: &str) -> String {
|
||||
for (route, size, pct_change) in bundles.iter().take(10) {
|
||||
let warning_marker = if let Some(pct) = pct_change {
|
||||
if *pct > 10.0 {
|
||||
format!(" ⚠️ (+{:.0}%)", pct)
|
||||
format!(" [warn] (+{:.0}%)", pct)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
@@ -219,7 +219,7 @@ Route (app) Size First Load JS
|
||||
✓ Built in 34.2s
|
||||
"#;
|
||||
let result = filter_next_build(output);
|
||||
assert!(result.contains("⚡ Next.js Build"));
|
||||
assert!(result.contains("Next.js Build"));
|
||||
assert!(result.contains("routes"));
|
||||
assert!(!result.contains("Creating an optimized")); // Should filter verbose logs
|
||||
}
|
||||
|
||||
+2
-2
@@ -160,7 +160,7 @@ fn filter_npm_output(output: &str) -> String {
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
} else {
|
||||
result.join("\n")
|
||||
}
|
||||
@@ -231,6 +231,6 @@ npm notice
|
||||
fn test_filter_npm_output_empty() {
|
||||
let output = "\n\n\n";
|
||||
let result = filter_npm_output(output);
|
||||
assert_eq!(result, "ok ✓");
|
||||
assert_eq!(result, "ok");
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ impl OutputParser for VitestParser {
|
||||
)
|
||||
} else {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
ParseResult::Passthrough(truncate_output(input, 2000))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,7 @@ For build tools (next, webpack, vite, cargo, etc.)
|
||||
- Human-readable
|
||||
|
||||
### Ultra (verbosity=2+)
|
||||
- Symbols: ✓✗⚠📦⬆️
|
||||
- Symbols: ✓✗⚠ pkg: ^
|
||||
- Ultra-compressed
|
||||
- 30-50% token reduction
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub enum ParseError {
|
||||
#[error("JSON parse failed at line {line}, column {col}: {msg}")]
|
||||
JsonError {
|
||||
|
||||
+10
-10
@@ -105,7 +105,7 @@ impl TokenFormatter for TestResult {
|
||||
|
||||
fn format_ultra(&self) -> String {
|
||||
format!(
|
||||
"✓{} ✗{} ⊘{} ({}ms)",
|
||||
"[ok]{} [x]{} [skip]{} ({}ms)",
|
||||
self.passed,
|
||||
self.failed,
|
||||
self.skipped,
|
||||
@@ -161,9 +161,9 @@ impl TokenFormatter for LintResult {
|
||||
lines.push("\nIssues:".to_string());
|
||||
for issue in self.issues.iter().take(20) {
|
||||
let severity_symbol = match issue.severity {
|
||||
LintSeverity::Error => "✗",
|
||||
LintSeverity::Warning => "⚠",
|
||||
LintSeverity::Info => "ℹ",
|
||||
LintSeverity::Error => "[x]",
|
||||
LintSeverity::Warning => "[!]",
|
||||
LintSeverity::Info => "[info]",
|
||||
};
|
||||
lines.push(format!(
|
||||
"{} {}:{}:{} [{}] {}",
|
||||
@@ -186,7 +186,7 @@ impl TokenFormatter for LintResult {
|
||||
|
||||
fn format_ultra(&self) -> String {
|
||||
format!(
|
||||
"✗{} ⚠{} 📁{}",
|
||||
"[x]{} [!]{} {}F",
|
||||
self.errors, self.warnings, self.files_with_issues
|
||||
)
|
||||
}
|
||||
@@ -195,7 +195,7 @@ impl TokenFormatter for LintResult {
|
||||
impl TokenFormatter for DependencyState {
|
||||
fn format_compact(&self) -> String {
|
||||
if self.outdated_count == 0 {
|
||||
return "All packages up-to-date ✓".to_string();
|
||||
return "All packages up-to-date".to_string();
|
||||
}
|
||||
|
||||
let mut lines = vec![format!(
|
||||
@@ -251,13 +251,13 @@ impl TokenFormatter for DependencyState {
|
||||
}
|
||||
|
||||
fn format_ultra(&self) -> String {
|
||||
format!("📦{} ⬆️{}", self.total_packages, self.outdated_count)
|
||||
format!("pkg:{} ^{}", self.total_packages, self.outdated_count)
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenFormatter for BuildOutput {
|
||||
fn format_compact(&self) -> String {
|
||||
let status = if self.success { "✓" } else { "✗" };
|
||||
let status = if self.success { "[ok]" } else { "[x]" };
|
||||
let mut lines = vec![format!(
|
||||
"{} Build: {} errors, {} warnings",
|
||||
status, self.errors, self.warnings
|
||||
@@ -324,9 +324,9 @@ impl TokenFormatter for BuildOutput {
|
||||
}
|
||||
|
||||
fn format_ultra(&self) -> String {
|
||||
let status = if self.success { "✓" } else { "✗" };
|
||||
let status = if self.success { "[ok]" } else { "[x]" };
|
||||
format!(
|
||||
"{} ✗{} ⚠{} ({}ms)",
|
||||
"{} [x]{} [!]{} ({}ms)",
|
||||
status,
|
||||
self.errors,
|
||||
self.warnings,
|
||||
|
||||
+13
-1
@@ -29,6 +29,7 @@ pub enum ParseResult<T> {
|
||||
|
||||
impl<T> ParseResult<T> {
|
||||
/// Unwrap the parsed data, panicking on Passthrough
|
||||
#[allow(dead_code)]
|
||||
pub fn unwrap(self) -> T {
|
||||
match self {
|
||||
ParseResult::Full(data) => data,
|
||||
@@ -38,6 +39,7 @@ impl<T> ParseResult<T> {
|
||||
}
|
||||
|
||||
/// Get the tier level (1 = Full, 2 = Degraded, 3 = Passthrough)
|
||||
#[allow(dead_code)]
|
||||
pub fn tier(&self) -> u8 {
|
||||
match self {
|
||||
ParseResult::Full(_) => 1,
|
||||
@@ -47,11 +49,13 @@ impl<T> ParseResult<T> {
|
||||
}
|
||||
|
||||
/// Check if parsing succeeded (Full or Degraded)
|
||||
#[allow(dead_code)]
|
||||
pub fn is_ok(&self) -> bool {
|
||||
!matches!(self, ParseResult::Passthrough(_))
|
||||
}
|
||||
|
||||
/// Map the parsed data while preserving tier
|
||||
#[allow(dead_code)]
|
||||
pub fn map<U, F>(self, f: F) -> ParseResult<U>
|
||||
where
|
||||
F: FnOnce(T) -> U,
|
||||
@@ -64,6 +68,7 @@ impl<T> ParseResult<T> {
|
||||
}
|
||||
|
||||
/// Get warnings if Degraded tier
|
||||
#[allow(dead_code)]
|
||||
pub fn warnings(&self) -> Vec<String> {
|
||||
match self {
|
||||
ParseResult::Degraded(_, warnings) => warnings.clone(),
|
||||
@@ -85,16 +90,23 @@ pub trait OutputParser: Sized {
|
||||
fn parse(input: &str) -> ParseResult<Self::Output>;
|
||||
|
||||
/// Parse with explicit tier preference (for testing/debugging)
|
||||
#[allow(dead_code)]
|
||||
fn parse_with_tier(input: &str, max_tier: u8) -> ParseResult<Self::Output> {
|
||||
let result = Self::parse(input);
|
||||
if result.tier() > max_tier {
|
||||
// Force degradation to passthrough if exceeds max tier
|
||||
return ParseResult::Passthrough(truncate_output(input, 500));
|
||||
return ParseResult::Passthrough(truncate_passthrough(input));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Truncate output using configured passthrough limit
|
||||
pub fn truncate_passthrough(output: &str) -> String {
|
||||
let max_chars = crate::config::limits().passthrough_max_chars;
|
||||
truncate_output(output, max_chars)
|
||||
}
|
||||
|
||||
/// Truncate output to max length with ellipsis
|
||||
pub fn truncate_output(output: &str, max_chars: usize) -> String {
|
||||
let chars: Vec<char> = output.chars().collect();
|
||||
|
||||
@@ -23,6 +23,7 @@ pub struct TestFailure {
|
||||
|
||||
/// Linting result (eslint, biome, tsc, etc.)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct LintResult {
|
||||
pub total_files: usize,
|
||||
pub files_with_issues: usize,
|
||||
@@ -33,6 +34,7 @@ pub struct LintResult {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct LintIssue {
|
||||
pub file_path: String,
|
||||
pub line: usize,
|
||||
@@ -43,6 +45,7 @@ pub struct LintIssue {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
pub enum LintSeverity {
|
||||
Error,
|
||||
Warning,
|
||||
@@ -68,6 +71,7 @@ pub struct Dependency {
|
||||
|
||||
/// Build output (next, webpack, vite, cargo, etc.)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct BuildOutput {
|
||||
pub success: bool,
|
||||
pub duration_ms: Option<u64>,
|
||||
@@ -78,6 +82,7 @@ pub struct BuildOutput {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct BundleInfo {
|
||||
pub name: String,
|
||||
pub size_bytes: u64,
|
||||
@@ -85,6 +90,7 @@ pub struct BundleInfo {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct RouteInfo {
|
||||
pub path: String,
|
||||
pub size_kb: f64,
|
||||
@@ -93,6 +99,7 @@ pub struct RouteInfo {
|
||||
|
||||
/// Git operation result
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct GitResult {
|
||||
pub operation: String,
|
||||
pub files_changed: usize,
|
||||
@@ -102,6 +109,7 @@ pub struct GitResult {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct GitCommit {
|
||||
pub hash: String,
|
||||
pub author: String,
|
||||
@@ -111,6 +119,7 @@ pub struct GitCommit {
|
||||
|
||||
/// Generic command output (for tools without specific types)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct GenericOutput {
|
||||
pub exit_code: i32,
|
||||
pub stdout: String,
|
||||
|
||||
+5
-12
@@ -33,10 +33,8 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
run_passthrough(base_cmd, args, verbose)?
|
||||
}
|
||||
_ => {
|
||||
anyhow::bail!(
|
||||
"rtk pip: unsupported subcommand '{}'\nSupported: list, outdated, install, uninstall, show",
|
||||
subcommand
|
||||
);
|
||||
// Unknown subcommand: passthrough to pip/uv
|
||||
run_passthrough(base_cmd, args, verbose)?
|
||||
}
|
||||
};
|
||||
|
||||
@@ -208,7 +206,7 @@ fn filter_pip_outdated(output: &str) -> String {
|
||||
};
|
||||
|
||||
if packages.is_empty() {
|
||||
return "✓ pip outdated: All packages up to date".to_string();
|
||||
return "pip outdated: All packages up to date".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -216,11 +214,7 @@ fn filter_pip_outdated(output: &str) -> String {
|
||||
result.push_str("═══════════════════════════════════════\n");
|
||||
|
||||
for (i, pkg) in packages.iter().take(20).enumerate() {
|
||||
let latest = pkg
|
||||
.latest_version
|
||||
.as_ref()
|
||||
.map(|v| v.as_str())
|
||||
.unwrap_or("unknown");
|
||||
let latest = pkg.latest_version.as_deref().unwrap_or("unknown");
|
||||
result.push_str(&format!(
|
||||
"{}. {} ({} → {})\n",
|
||||
i + 1,
|
||||
@@ -234,7 +228,7 @@ fn filter_pip_outdated(output: &str) -> String {
|
||||
result.push_str(&format!("\n... +{} more packages\n", packages.len() - 20));
|
||||
}
|
||||
|
||||
result.push_str("\n💡 Run `pip install --upgrade <package>` to update\n");
|
||||
result.push_str("\n[hint] Run `pip install --upgrade <package>` to update\n");
|
||||
|
||||
result.trim().to_string()
|
||||
}
|
||||
@@ -269,7 +263,6 @@ mod tests {
|
||||
fn test_filter_pip_outdated_none() {
|
||||
let output = "[]";
|
||||
let result = filter_pip_outdated(output);
|
||||
assert!(result.contains("✓"));
|
||||
assert!(result.contains("All packages up to date"));
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::parser::{
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_output, FormatMode, OutputParser,
|
||||
ParseResult, TestFailure, TestResult, TokenFormatter,
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, FormatMode,
|
||||
OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
|
||||
};
|
||||
|
||||
/// Matches real Playwright JSON reporter output (suites → specs → tests → results)
|
||||
@@ -110,7 +110,7 @@ impl OutputParser for PlaywrightParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-7
@@ -6,7 +6,7 @@ use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::parser::{
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_output, Dependency,
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, Dependency,
|
||||
DependencyState, FormatMode, OutputParser, ParseResult, TokenFormatter,
|
||||
};
|
||||
|
||||
@@ -75,7 +75,7 @@ impl OutputParser for PnpmListParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,7 +202,7 @@ impl OutputParser for PnpmOutdatedParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,7 +307,8 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("pnpm list failed: {}", stderr);
|
||||
eprint!("{}", stderr);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
@@ -388,7 +389,7 @@ fn run_outdated(args: &[String], verbose: u8) -> Result<()> {
|
||||
};
|
||||
|
||||
if filtered.trim().is_empty() {
|
||||
println!("All packages up-to-date ✓");
|
||||
println!("All packages up-to-date");
|
||||
} else {
|
||||
println!("{}", filtered);
|
||||
}
|
||||
@@ -431,7 +432,8 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!("pnpm install failed: {}", stderr);
|
||||
eprint!("{}", stderr);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let combined = format!("{}{}", stdout, stderr);
|
||||
@@ -482,7 +484,7 @@ fn filter_pnpm_install(output: &str) -> String {
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
"ok ✓".to_string()
|
||||
"ok".to_string()
|
||||
} else {
|
||||
result.join("\n")
|
||||
}
|
||||
|
||||
+5
-5
@@ -112,7 +112,7 @@ pub fn filter_prettier_output(output: &str) -> String {
|
||||
|
||||
// Check if all files are formatted
|
||||
if files_to_format.is_empty() && output.contains("All matched files use Prettier") {
|
||||
return "✓ Prettier: All files formatted correctly".to_string();
|
||||
return "Prettier: All files formatted correctly".to_string();
|
||||
}
|
||||
|
||||
// Check if files were written (write mode)
|
||||
@@ -125,7 +125,7 @@ pub fn filter_prettier_output(output: &str) -> String {
|
||||
if is_check_mode {
|
||||
// Check mode: show files that need formatting
|
||||
if files_to_format.is_empty() {
|
||||
result.push_str("✓ Prettier: All files formatted correctly\n");
|
||||
result.push_str("Prettier: All files formatted correctly\n");
|
||||
} else {
|
||||
result.push_str(&format!(
|
||||
"Prettier: {} files need formatting\n",
|
||||
@@ -146,7 +146,7 @@ pub fn filter_prettier_output(output: &str) -> String {
|
||||
|
||||
if files_checked > 0 {
|
||||
result.push_str(&format!(
|
||||
"\n✓ {} files already formatted\n",
|
||||
"\n{} files already formatted\n",
|
||||
files_checked - files_to_format.len()
|
||||
));
|
||||
}
|
||||
@@ -154,7 +154,7 @@ pub fn filter_prettier_output(output: &str) -> String {
|
||||
} else {
|
||||
// Write mode: show what was formatted
|
||||
result.push_str(&format!(
|
||||
"✓ Prettier: {} files formatted\n",
|
||||
"Prettier: {} files formatted\n",
|
||||
files_to_format.len()
|
||||
));
|
||||
}
|
||||
@@ -173,7 +173,7 @@ Checking formatting...
|
||||
All matched files use Prettier code style!
|
||||
"#;
|
||||
let result = filter_prettier_output(output);
|
||||
assert!(result.contains("✓ Prettier"));
|
||||
assert!(result.contains("Prettier"));
|
||||
assert!(result.contains("All files formatted correctly"));
|
||||
}
|
||||
|
||||
|
||||
+8
-8
@@ -221,7 +221,7 @@ fn filter_prisma_generate(output: &str) -> String {
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
result.push_str("✓ Prisma Client generated\n");
|
||||
result.push_str("Prisma Client generated\n");
|
||||
|
||||
if models > 0 || enums > 0 || types > 0 {
|
||||
result.push_str(&format!(
|
||||
@@ -283,7 +283,7 @@ fn filter_migrate_dev(output: &str) -> String {
|
||||
let mut result = String::new();
|
||||
|
||||
if !migration_name.is_empty() {
|
||||
result.push_str(&format!("🗃️ Migration: {}\n", migration_name));
|
||||
result.push_str(&format!("Migration: {}\n", migration_name));
|
||||
result.push_str("═══════════════════════════════════════\n");
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ fn filter_migrate_dev(output: &str) -> String {
|
||||
|
||||
result.push('\n');
|
||||
if applied {
|
||||
result.push_str("✓ Applied | Pending: 0\n");
|
||||
result.push_str("Applied | Pending: 0\n");
|
||||
}
|
||||
|
||||
result.trim().to_string()
|
||||
@@ -360,9 +360,9 @@ fn filter_migrate_deploy(output: &str) -> String {
|
||||
let mut result = String::new();
|
||||
|
||||
if errors.is_empty() {
|
||||
result.push_str(&format!("✓ {} migration(s) deployed\n", deployed));
|
||||
result.push_str(&format!("{} migration(s) deployed\n", deployed));
|
||||
} else {
|
||||
result.push_str("❌ Deployment failed:\n");
|
||||
result.push_str("[FAIL] Deployment failed:\n");
|
||||
for err in errors.iter().take(5) {
|
||||
result.push_str(&format!(" {}\n", err));
|
||||
}
|
||||
@@ -390,7 +390,7 @@ fn filter_db_push(output: &str) -> String {
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
result.push_str("✓ Schema pushed to database\n");
|
||||
result.push_str("Schema pushed to database\n");
|
||||
|
||||
if tables_added > 0 || columns_modified > 0 || dropped > 0 {
|
||||
result.push_str(&format!(
|
||||
@@ -460,7 +460,7 @@ import { PrismaClient } from '@prisma/client'
|
||||
42 models, 18 enums, 890 types generated
|
||||
"#;
|
||||
let result = filter_prisma_generate(output);
|
||||
assert!(result.contains("✓ Prisma Client generated"));
|
||||
assert!(result.contains("Prisma Client generated"));
|
||||
// Parser may not extract exact counts from this format, just check it doesn't crash
|
||||
assert!(!result.contains("Prisma schema loaded"));
|
||||
assert!(!result.contains("Start by importing"));
|
||||
@@ -484,7 +484,7 @@ CREATE INDEX "session_status_idx" ON "Session"("status");
|
||||
let result = filter_migrate_dev(output);
|
||||
assert!(result.contains("20260128_add_sessions"));
|
||||
assert!(result.contains("+ 1 table"));
|
||||
assert!(result.contains("✓ Applied"));
|
||||
assert!(result.contains("Applied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+4
-4
@@ -167,7 +167,7 @@ fn build_pytest_summary(summary: &str, _test_files: &[String], failures: &[Strin
|
||||
let (passed, failed, skipped) = parse_summary_line(summary);
|
||||
|
||||
if failed == 0 && passed > 0 {
|
||||
return format!("✓ Pytest: {} passed", passed);
|
||||
return format!("Pytest: {} passed", passed);
|
||||
}
|
||||
|
||||
if passed == 0 && failed == 0 {
|
||||
@@ -198,13 +198,13 @@ fn build_pytest_summary(summary: &str, _test_files: &[String], failures: &[Strin
|
||||
if first_line.starts_with("___") {
|
||||
// Extract test name between ___
|
||||
let test_name = first_line.trim_matches('_').trim();
|
||||
result.push_str(&format!("{}. ❌ {}\n", i + 1, test_name));
|
||||
result.push_str(&format!("{}. [FAIL] {}\n", i + 1, test_name));
|
||||
} else if first_line.starts_with("FAILED") {
|
||||
// Summary format: "FAILED tests/test_foo.py::test_bar - AssertionError"
|
||||
let parts: Vec<&str> = first_line.split(" - ").collect();
|
||||
if let Some(test_path) = parts.first() {
|
||||
let test_name = test_path.trim_start_matches("FAILED ");
|
||||
result.push_str(&format!("{}. ❌ {}\n", i + 1, test_name));
|
||||
result.push_str(&format!("{}. [FAIL] {}\n", i + 1, test_name));
|
||||
}
|
||||
if parts.len() > 1 {
|
||||
result.push_str(&format!(" {}\n", truncate(parts[1], 100)));
|
||||
@@ -288,7 +288,7 @@ tests/test_foo.py ..... [100%]
|
||||
=== 5 passed in 0.50s ==="#;
|
||||
|
||||
let result = filter_pytest_output(output);
|
||||
assert!(result.contains("✓ Pytest"));
|
||||
assert!(result.contains("Pytest"));
|
||||
assert!(result.contains("5 passed"));
|
||||
}
|
||||
|
||||
|
||||
+15
-10
@@ -1,3 +1,4 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::{resolved_command, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
@@ -6,7 +7,9 @@ use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RuffLocation {
|
||||
#[allow(dead_code)]
|
||||
row: usize,
|
||||
#[allow(dead_code)]
|
||||
column: usize,
|
||||
}
|
||||
|
||||
@@ -19,7 +22,9 @@ struct RuffFix {
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RuffDiagnostic {
|
||||
code: String,
|
||||
#[allow(dead_code)]
|
||||
message: String,
|
||||
#[allow(dead_code)]
|
||||
location: RuffLocation,
|
||||
#[allow(dead_code)]
|
||||
end_location: Option<RuffLocation>,
|
||||
@@ -121,13 +126,13 @@ pub fn filter_ruff_check_json(output: &str) -> String {
|
||||
return format!(
|
||||
"Ruff check (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, 500)
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if diagnostics.is_empty() {
|
||||
return "✓ Ruff: No issues found".to_string();
|
||||
return "Ruff: No issues found".to_string();
|
||||
}
|
||||
|
||||
let total_issues = diagnostics.len();
|
||||
@@ -204,7 +209,7 @@ pub fn filter_ruff_check_json(output: &str) -> String {
|
||||
|
||||
if fixable_count > 0 {
|
||||
result.push_str(&format!(
|
||||
"\n💡 Run `ruff check --fix` to auto-fix {} issues\n",
|
||||
"\n[hint] Run `ruff check --fix` to auto-fix {} issues\n",
|
||||
fixable_count
|
||||
));
|
||||
}
|
||||
@@ -237,7 +242,7 @@ pub fn filter_ruff_format(output: &str) -> String {
|
||||
for part in parts {
|
||||
let part_lower = part.to_lowercase();
|
||||
if part_lower.contains("left unchanged") {
|
||||
let words: Vec<&str> = part.trim().split_whitespace().collect();
|
||||
let words: Vec<&str> = part.split_whitespace().collect();
|
||||
// Look for number before "file" or "files"
|
||||
for (i, word) in words.iter().enumerate() {
|
||||
if (word == &"file" || word == &"files") && i > 0 {
|
||||
@@ -257,7 +262,7 @@ pub fn filter_ruff_format(output: &str) -> String {
|
||||
|
||||
// Check if all files are formatted
|
||||
if files_to_format.is_empty() && output_lower.contains("left unchanged") {
|
||||
return "✓ Ruff format: All files formatted correctly".to_string();
|
||||
return "Ruff format: All files formatted correctly".to_string();
|
||||
}
|
||||
|
||||
let mut result = String::new();
|
||||
@@ -265,7 +270,7 @@ pub fn filter_ruff_format(output: &str) -> String {
|
||||
if output_lower.contains("would reformat") {
|
||||
// Check mode: show files that need formatting
|
||||
if files_to_format.is_empty() {
|
||||
result.push_str("✓ Ruff format: All files formatted correctly\n");
|
||||
result.push_str("Ruff format: All files formatted correctly\n");
|
||||
} else {
|
||||
result.push_str(&format!(
|
||||
"Ruff format: {} files need formatting\n",
|
||||
@@ -285,10 +290,10 @@ pub fn filter_ruff_format(output: &str) -> String {
|
||||
}
|
||||
|
||||
if files_checked > 0 {
|
||||
result.push_str(&format!("\n✓ {} files already formatted\n", files_checked));
|
||||
result.push_str(&format!("\n{} files already formatted\n", files_checked));
|
||||
}
|
||||
|
||||
result.push_str("\n💡 Run `ruff format` to format these files\n");
|
||||
result.push_str("\n[hint] Run `ruff format` to format these files\n");
|
||||
}
|
||||
} else {
|
||||
// Write mode or other output - show summary
|
||||
@@ -323,7 +328,7 @@ mod tests {
|
||||
fn test_filter_ruff_check_no_issues() {
|
||||
let output = "[]";
|
||||
let result = filter_ruff_check_json(output);
|
||||
assert!(result.contains("✓ Ruff"));
|
||||
assert!(result.contains("Ruff"));
|
||||
assert!(result.contains("No issues found"));
|
||||
}
|
||||
|
||||
@@ -369,7 +374,7 @@ mod tests {
|
||||
fn test_filter_ruff_format_all_formatted() {
|
||||
let output = "5 files left unchanged";
|
||||
let result = filter_ruff_format(output);
|
||||
assert!(result.contains("✓ Ruff format"));
|
||||
assert!(result.contains("Ruff format"));
|
||||
assert!(result.contains("All files formatted correctly"));
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -34,10 +34,10 @@ pub fn run_err(command: &str, verbose: u8) -> Result<()> {
|
||||
|
||||
if filtered.is_empty() {
|
||||
if output.status.success() {
|
||||
rtk.push_str("✅ Command completed successfully (no errors)");
|
||||
rtk.push_str("[ok] Command completed successfully (no errors)");
|
||||
} else {
|
||||
rtk.push_str(&format!(
|
||||
"❌ Command failed (exit code: {:?})\n",
|
||||
"[FAIL] Command failed (exit code: {:?})\n",
|
||||
output.status.code()
|
||||
));
|
||||
let lines: Vec<&str> = raw.lines().collect();
|
||||
@@ -228,7 +228,7 @@ fn extract_test_summary(output: &str, command: &str) -> String {
|
||||
let mut output = String::new();
|
||||
|
||||
if !failures.is_empty() {
|
||||
output.push_str("❌ FAILURES:\n");
|
||||
output.push_str("[FAIL] FAILURES:\n");
|
||||
for f in failures.iter().take(10) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
@@ -239,13 +239,13 @@ fn extract_test_summary(output: &str, command: &str) -> String {
|
||||
}
|
||||
|
||||
if !result.is_empty() {
|
||||
output.push_str("📊 SUMMARY:\n");
|
||||
output.push_str("SUMMARY:\n");
|
||||
for r in &result {
|
||||
output.push_str(&format!(" {}\n", r));
|
||||
}
|
||||
} else {
|
||||
// Fallback: show last few lines
|
||||
output.push_str("📊 OUTPUT (last 5 lines):\n");
|
||||
output.push_str("OUTPUT (last 5 lines):\n");
|
||||
let start = lines.len().saturating_sub(5);
|
||||
for line in &lines[start..] {
|
||||
if !line.trim().is_empty() {
|
||||
|
||||
+23
-22
@@ -42,7 +42,7 @@ fn summarize_output(output: &str, command: &str, success: bool) -> String {
|
||||
let mut result = Vec::new();
|
||||
|
||||
// Status
|
||||
let status_icon = if success { "✅" } else { "❌" };
|
||||
let status_icon = if success { "[ok]" } else { "[FAIL]" };
|
||||
result.push(format!(
|
||||
"{} Command: {}",
|
||||
status_icon,
|
||||
@@ -96,10 +96,11 @@ fn detect_output_type(output: &str, command: &str) -> OutputType {
|
||||
OutputType::JsonOutput
|
||||
} else if output.lines().all(|l| {
|
||||
l.len() < 200
|
||||
&& !l
|
||||
.contains('\t')
|
||||
.then_some(true)
|
||||
.unwrap_or(l.split_whitespace().count() < 10)
|
||||
&& if l.contains('\t') {
|
||||
false
|
||||
} else {
|
||||
l.split_whitespace().count() < 10
|
||||
}
|
||||
}) {
|
||||
OutputType::ListOutput
|
||||
} else {
|
||||
@@ -108,7 +109,7 @@ fn detect_output_type(output: &str, command: &str) -> OutputType {
|
||||
}
|
||||
|
||||
fn summarize_tests(output: &str, result: &mut Vec<String>) {
|
||||
result.push("📋 Test Results:".to_string());
|
||||
result.push("Test Results:".to_string());
|
||||
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
@@ -125,7 +126,7 @@ fn summarize_tests(output: &str, result: &mut Vec<String>) {
|
||||
passed += 1;
|
||||
}
|
||||
}
|
||||
if lower.contains("failed") || lower.contains("✗") || lower.contains("fail") {
|
||||
if lower.contains("failed") || lower.contains("[x]") || lower.contains("fail") {
|
||||
if let Some(n) = extract_number(&lower, "failed") {
|
||||
failed = n;
|
||||
}
|
||||
@@ -141,12 +142,12 @@ fn summarize_tests(output: &str, result: &mut Vec<String>) {
|
||||
}
|
||||
}
|
||||
|
||||
result.push(format!(" ✅ {} passed", passed));
|
||||
result.push(format!(" [ok] {} passed", passed));
|
||||
if failed > 0 {
|
||||
result.push(format!(" ❌ {} failed", failed));
|
||||
result.push(format!(" [FAIL] {} failed", failed));
|
||||
}
|
||||
if skipped > 0 {
|
||||
result.push(format!(" ⏭️ {} skipped", skipped));
|
||||
result.push(format!(" skip {} skipped", skipped));
|
||||
}
|
||||
|
||||
if !failures.is_empty() {
|
||||
@@ -159,7 +160,7 @@ fn summarize_tests(output: &str, result: &mut Vec<String>) {
|
||||
}
|
||||
|
||||
fn summarize_build(output: &str, result: &mut Vec<String>) {
|
||||
result.push("🔨 Build Summary:".to_string());
|
||||
result.push("Build Summary:".to_string());
|
||||
|
||||
let mut errors = 0;
|
||||
let mut warnings = 0;
|
||||
@@ -183,16 +184,16 @@ fn summarize_build(output: &str, result: &mut Vec<String>) {
|
||||
}
|
||||
|
||||
if compiled > 0 {
|
||||
result.push(format!(" 📦 {} crates/files compiled", compiled));
|
||||
result.push(format!(" {} crates/files compiled", compiled));
|
||||
}
|
||||
if errors > 0 {
|
||||
result.push(format!(" ❌ {} errors", errors));
|
||||
result.push(format!(" [error] {} errors", errors));
|
||||
}
|
||||
if warnings > 0 {
|
||||
result.push(format!(" ⚠️ {} warnings", warnings));
|
||||
result.push(format!(" [warn] {} warnings", warnings));
|
||||
}
|
||||
if errors == 0 && warnings == 0 {
|
||||
result.push(" ✅ Build successful".to_string());
|
||||
result.push(" [ok] Build successful".to_string());
|
||||
}
|
||||
|
||||
if !error_msgs.is_empty() {
|
||||
@@ -205,7 +206,7 @@ fn summarize_build(output: &str, result: &mut Vec<String>) {
|
||||
}
|
||||
|
||||
fn summarize_logs_quick(output: &str, result: &mut Vec<String>) {
|
||||
result.push("📝 Log Summary:".to_string());
|
||||
result.push("Log Summary:".to_string());
|
||||
|
||||
let mut errors = 0;
|
||||
let mut warnings = 0;
|
||||
@@ -222,14 +223,14 @@ fn summarize_logs_quick(output: &str, result: &mut Vec<String>) {
|
||||
}
|
||||
}
|
||||
|
||||
result.push(format!(" ❌ {} errors", errors));
|
||||
result.push(format!(" ⚠️ {} warnings", warnings));
|
||||
result.push(format!(" ℹ️ {} info", info));
|
||||
result.push(format!(" [error] {} errors", errors));
|
||||
result.push(format!(" [warn] {} warnings", warnings));
|
||||
result.push(format!(" [info] {} info", info));
|
||||
}
|
||||
|
||||
fn summarize_list(output: &str, result: &mut Vec<String>) {
|
||||
let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
result.push(format!("📋 List ({} items):", lines.len()));
|
||||
result.push(format!("List ({} items):", lines.len()));
|
||||
|
||||
for line in lines.iter().take(10) {
|
||||
result.push(format!(" • {}", truncate(line, 70)));
|
||||
@@ -240,7 +241,7 @@ fn summarize_list(output: &str, result: &mut Vec<String>) {
|
||||
}
|
||||
|
||||
fn summarize_json(output: &str, result: &mut Vec<String>) {
|
||||
result.push("📋 JSON Output:".to_string());
|
||||
result.push("JSON Output:".to_string());
|
||||
|
||||
// Try to parse and show structure
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(output) {
|
||||
@@ -269,7 +270,7 @@ fn summarize_json(output: &str, result: &mut Vec<String>) {
|
||||
fn summarize_generic(output: &str, result: &mut Vec<String>) {
|
||||
let lines: Vec<&str> = output.lines().collect();
|
||||
|
||||
result.push("📋 Output:".to_string());
|
||||
result.push("Output:".to_string());
|
||||
|
||||
// First few lines
|
||||
for line in lines.iter().take(5) {
|
||||
|
||||
+2
-7
@@ -182,20 +182,15 @@ pub fn tee_and_hint(raw: &str, command_slug: &str, exit_code: i32) -> Option<Str
|
||||
}
|
||||
|
||||
/// TeeMode controls when tee writes files.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum TeeMode {
|
||||
#[default]
|
||||
Failures,
|
||||
Always,
|
||||
Never,
|
||||
}
|
||||
|
||||
impl Default for TeeMode {
|
||||
fn default() -> Self {
|
||||
Self::Failures
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for the tee feature.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TeeConfig {
|
||||
|
||||
+6
-6
@@ -574,7 +574,7 @@ pub fn run_filter_tests(filter_name_opt: Option<&str>) -> VerifyResults {
|
||||
.into_iter()
|
||||
.filter(|name| {
|
||||
// When a specific filter is requested, only report that one as missing tests
|
||||
filter_name_opt.map_or(true, |f| name == f)
|
||||
filter_name_opt.is_none_or(|f| name == f)
|
||||
})
|
||||
.filter(|name| !tested_filter_names.contains(name))
|
||||
.collect();
|
||||
@@ -1610,8 +1610,8 @@ match_command = "^make\\b"
|
||||
let filters = make_filters(BUILTIN_TOML);
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
47,
|
||||
"Expected exactly 47 built-in filters, got {}. \
|
||||
57,
|
||||
"Expected exactly 57 built-in filters, got {}. \
|
||||
Update this count when adding/removing filters in src/filters/.",
|
||||
filters.len()
|
||||
);
|
||||
@@ -1668,11 +1668,11 @@ expected = "output line 1\noutput line 2"
|
||||
let combined = format!("{}\n\n{}", BUILTIN_TOML, new_filter);
|
||||
let filters = make_filters(&combined);
|
||||
|
||||
// All 47 existing filters still present + 1 new = 48
|
||||
// All 57 existing filters still present + 1 new = 58
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
48,
|
||||
"Expected 48 filters after concat (47 built-in + 1 new)"
|
||||
58,
|
||||
"Expected 58 filters after concat (57 built-in + 1 new)"
|
||||
);
|
||||
|
||||
// New filter is discoverable
|
||||
|
||||
+14
-1
@@ -221,6 +221,9 @@ pub struct MonthStats {
|
||||
pub avg_time_ms: u64,
|
||||
}
|
||||
|
||||
/// Type alias for command statistics tuple: (command, count, saved_tokens, avg_savings_pct, avg_time_ms)
|
||||
type CommandStats = (String, usize, usize, f64, u64);
|
||||
|
||||
impl Tracker {
|
||||
/// Create a new tracker instance.
|
||||
///
|
||||
@@ -251,6 +254,12 @@ impl Tracker {
|
||||
}
|
||||
|
||||
let conn = Connection::open(&db_path)?;
|
||||
// WAL mode + busy_timeout for concurrent access (multiple Claude Code instances).
|
||||
// Non-fatal: NFS/read-only filesystems may not support WAL.
|
||||
let _ = conn.execute_batch(
|
||||
"PRAGMA journal_mode=WAL;
|
||||
PRAGMA busy_timeout=5000;",
|
||||
);
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS commands (
|
||||
id INTEGER PRIMARY KEY,
|
||||
@@ -488,6 +497,7 @@ impl Tracker {
|
||||
/// summary.total_saved, summary.avg_savings_pct);
|
||||
/// # Ok::<(), anyhow::Error>(())
|
||||
/// ```
|
||||
#[allow(dead_code)]
|
||||
pub fn get_summary(&self) -> Result<GainSummary> {
|
||||
self.get_summary_filtered(None) // delegate to filtered variant
|
||||
}
|
||||
@@ -560,7 +570,7 @@ impl Tracker {
|
||||
fn get_by_command(
|
||||
&self,
|
||||
project_path: Option<&str>, // added
|
||||
) -> Result<Vec<(String, usize, usize, f64, u64)>> {
|
||||
) -> Result<Vec<CommandStats>> {
|
||||
let (project_exact, project_glob) = project_filter_params(project_path); // added
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens), AVG(savings_pct), AVG(exec_time_ms)
|
||||
@@ -851,6 +861,7 @@ impl Tracker {
|
||||
/// }
|
||||
/// # Ok::<(), anyhow::Error>(())
|
||||
/// ```
|
||||
#[allow(dead_code)]
|
||||
pub fn get_recent(&self, limit: usize) -> Result<Vec<CommandRecord>> {
|
||||
self.get_recent_filtered(limit, None) // delegate to filtered variant
|
||||
}
|
||||
@@ -971,6 +982,7 @@ fn get_db_path() -> Result<PathBuf> {
|
||||
pub struct ParseFailureRecord {
|
||||
pub timestamp: String,
|
||||
pub raw_command: String,
|
||||
#[allow(dead_code)]
|
||||
pub error_message: String,
|
||||
pub fallback_succeeded: bool,
|
||||
}
|
||||
@@ -1175,6 +1187,7 @@ pub fn args_display(args: &[OsString]) -> String {
|
||||
/// timer.track("ls -la", "rtk ls", "input", "output");
|
||||
/// ```
|
||||
#[deprecated(note = "Use TimedExecution instead")]
|
||||
#[allow(dead_code)]
|
||||
pub fn track(original_cmd: &str, rtk_cmd: &str, input: &str, output: &str) {
|
||||
let input_tokens = estimate_tokens(input);
|
||||
let output_tokens = estimate_tokens(output);
|
||||
|
||||
+1
-1
@@ -125,7 +125,7 @@ fn filter_tree_output(raw: &str) -> String {
|
||||
}
|
||||
|
||||
// Remove trailing empty lines
|
||||
while filtered_lines.last().map_or(false, |l| l.trim().is_empty()) {
|
||||
while filtered_lines.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
filtered_lines.pop();
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -140,6 +140,7 @@ pub fn check_trust(filter_path: &Path) -> Result<TrustStatus> {
|
||||
}
|
||||
|
||||
/// Store current SHA-256 hash as trusted (computes hash from file).
|
||||
#[allow(dead_code)]
|
||||
pub fn trust_filter(filter_path: &Path) -> Result<()> {
|
||||
let hash = integrity::compute_hash(filter_path)
|
||||
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
|
||||
@@ -267,13 +268,13 @@ fn print_risk_summary(content: &str) {
|
||||
println!(" Filters: {}", filter_count);
|
||||
|
||||
if has_replace {
|
||||
println!(" ⚠ Contains 'replace' rules (can rewrite output)");
|
||||
println!(" [!] Contains 'replace' rules (can rewrite output)");
|
||||
}
|
||||
if has_match_output {
|
||||
println!(" ⚠ Contains 'match_output' rules (can replace entire output)");
|
||||
println!(" [!] Contains 'match_output' rules (can replace entire output)");
|
||||
}
|
||||
if has_dot_pattern {
|
||||
println!(" ⚠ Contains catch-all pattern '.' (matches everything)");
|
||||
println!(" [!] Contains catch-all pattern '.' (matches everything)");
|
||||
}
|
||||
if !has_replace && !has_match_output && !has_dot_pattern {
|
||||
println!(" No high-risk patterns detected.");
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ fn filter_tsc_output(output: &str) -> String {
|
||||
|
||||
if errors.is_empty() {
|
||||
if output.contains("Found 0 errors") {
|
||||
return "✓ TypeScript: No errors found".to_string();
|
||||
return "TypeScript: No errors found".to_string();
|
||||
}
|
||||
return "TypeScript compilation completed".to_string();
|
||||
}
|
||||
|
||||
+3
-3
@@ -3,7 +3,7 @@ use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::parser::{
|
||||
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_output,
|
||||
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_passthrough,
|
||||
FormatMode, OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
|
||||
};
|
||||
use crate::tracking;
|
||||
@@ -88,7 +88,7 @@ impl OutputParser for VitestParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,7 +182,7 @@ fn extract_failures_regex(output: &str) -> Vec<TestFailure> {
|
||||
|
||||
while i < lines.len() {
|
||||
let line = lines[i];
|
||||
if line.contains('✗') || line.contains("FAIL") {
|
||||
if line.contains("[x]") || line.contains("FAIL") {
|
||||
let mut error_lines = vec![line.to_string()];
|
||||
i += 1;
|
||||
|
||||
|
||||
+3
-3
@@ -167,7 +167,7 @@ fn format_single_line(line: &str, mode: &WcMode) -> String {
|
||||
WcMode::Mixed => {
|
||||
// Strip file path, keep numbers only
|
||||
if parts.len() >= 2 {
|
||||
let last_is_path = parts.last().map_or(false, |p| p.parse::<u64>().is_err());
|
||||
let last_is_path = parts.last().is_some_and(|p| p.parse::<u64>().is_err());
|
||||
if last_is_path {
|
||||
parts[..parts.len() - 1].join(" ")
|
||||
} else {
|
||||
@@ -202,7 +202,7 @@ fn format_multi_line(lines: &[&str], mode: &WcMode) -> String {
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_total = parts.last().map_or(false, |p| *p == "total");
|
||||
let is_total = parts.last().is_some_and(|p| *p == "total");
|
||||
|
||||
match mode {
|
||||
WcMode::Lines | WcMode::Words | WcMode::Bytes | WcMode::Chars => {
|
||||
@@ -236,7 +236,7 @@ fn format_multi_line(lines: &[&str], mode: &WcMode) -> String {
|
||||
let nums: Vec<&str> = parts[..parts.len() - 1].to_vec();
|
||||
result.push(format!("Σ {}", nums.join(" ")));
|
||||
} else if parts.len() >= 2 {
|
||||
let last_is_path = parts.last().map_or(false, |p| p.parse::<u64>().is_err());
|
||||
let last_is_path = parts.last().is_some_and(|p| p.parse::<u64>().is_err());
|
||||
if last_is_path {
|
||||
let name = strip_prefix(parts.last().unwrap_or(&""), &common_prefix);
|
||||
let nums: Vec<&str> = parts[..parts.len() - 1].to_vec();
|
||||
|
||||
+8
-5
@@ -33,7 +33,7 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
let filename = extract_filename_from_output(&stderr, url, args);
|
||||
let size = get_file_size(&filename);
|
||||
let msg = format!(
|
||||
"⬇️ {} ok | {} | {}",
|
||||
"{} ok | {} | {}",
|
||||
compact_url(url),
|
||||
filename,
|
||||
format_size(size)
|
||||
@@ -42,9 +42,10 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
|
||||
} else {
|
||||
let error = parse_error(&stderr, &stdout);
|
||||
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
|
||||
let msg = format!("{} FAILED: {}", compact_url(url), error);
|
||||
println!("{}", msg);
|
||||
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -78,7 +79,7 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
let mut rtk_output = String::new();
|
||||
if total > 20 {
|
||||
rtk_output.push_str(&format!(
|
||||
"⬇️ {} ok | {} lines | {}\n",
|
||||
"{} ok | {} lines | {}\n",
|
||||
compact_url(url),
|
||||
total,
|
||||
format_size(output.stdout.len() as u64)
|
||||
@@ -89,7 +90,7 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
}
|
||||
rtk_output.push_str(&format!("... +{} more lines", total - 10));
|
||||
} else {
|
||||
rtk_output.push_str(&format!("⬇️ {} ok | {} lines\n", compact_url(url), total));
|
||||
rtk_output.push_str(&format!("{} ok | {} lines\n", compact_url(url), total));
|
||||
for line in &lines {
|
||||
rtk_output.push_str(&format!("{}\n", line));
|
||||
}
|
||||
@@ -104,9 +105,10 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
} else {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let error = parse_error(&stderr, "");
|
||||
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
|
||||
let msg = format!("{} FAILED: {}", compact_url(url), error);
|
||||
println!("{}", msg);
|
||||
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -206,6 +208,7 @@ fn compact_url(url: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn parse_error(stderr: &str, stdout: &str) -> String {
|
||||
// Common wget error patterns
|
||||
let combined = format!("{}\n{}", stderr, stdout);
|
||||
|
||||
Reference in new issue
Block a user