Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8e5618e6a | ||
|
|
884e37edbf | ||
|
|
27b35d84a3 | ||
|
|
0a1bcb05e5 | ||
|
|
799f0856e4 | ||
|
|
093e431193 | ||
|
|
409aed6dbc | ||
|
|
85b0b3eb0b | ||
|
|
dbc950395e | ||
|
|
45f9344f03 | ||
|
|
f693e060c6 | ||
|
|
8953af0fc0 | ||
|
|
079ee9a4ea | ||
|
|
7ad291bab5 | ||
|
|
6c13d23436 | ||
|
|
3141fecf95 | ||
|
|
32ade38e0a | ||
|
|
6ad6ffecce | ||
|
|
a8d6106f73 | ||
|
|
baff6a2334 |
No files matched your search
@@ -0,0 +1,348 @@
|
||||
---
|
||||
description: >
|
||||
Issue triage: audit open issues, categorize, detect duplicates, cross-ref PRs, risk assessment, post comments.
|
||||
Args: "all" for deep analysis of all, issue numbers to focus (e.g. "42 57"), "en"/"fr" for language, no arg = audit only in French.
|
||||
---
|
||||
|
||||
# Issue Triage
|
||||
|
||||
## Quand utiliser
|
||||
|
||||
| Skill | Usage | Output |
|
||||
|-------|-------|--------|
|
||||
| `/issue-triage` | Trier, analyser, commenter les issues | Tableaux d'action + deep analysis + commentaires postés |
|
||||
| `/repo-recap` | Récap général pour partager avec l'équipe | Résumé Markdown (PRs + issues + releases) |
|
||||
|
||||
**Déclencheurs** :
|
||||
- Manuellement : `/issue-triage` ou `/issue-triage all` ou `/issue-triage 42 57`
|
||||
- Proactivement : quand >10 issues ouvertes sans triage, ou issue stale >30j détectée
|
||||
|
||||
---
|
||||
|
||||
## Langue
|
||||
|
||||
- Vérifier l'argument passé au skill
|
||||
- Si `en` ou `english` → tableaux et résumé en anglais
|
||||
- Si `fr`, `french`, ou pas d'argument → français (défaut)
|
||||
- Note : les commentaires GitHub (Phase 3) restent TOUJOURS en anglais (audience internationale)
|
||||
|
||||
---
|
||||
|
||||
Workflow en 3 phases : audit automatique → deep analysis opt-in → commentaires avec validation obligatoire.
|
||||
|
||||
## Préconditions
|
||||
|
||||
```bash
|
||||
git rev-parse --is-inside-work-tree
|
||||
gh auth status
|
||||
```
|
||||
|
||||
Si l'un échoue, stop et expliquer ce qui manque.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Audit (toujours exécutée)
|
||||
|
||||
### Data Gathering (commandes en parallèle)
|
||||
|
||||
```bash
|
||||
# Identité du repo
|
||||
gh repo view --json nameWithOwner -q .nameWithOwner
|
||||
|
||||
# Issues ouvertes avec métadonnées complètes
|
||||
gh issue list --state open --limit 100 \
|
||||
--json number,title,author,createdAt,updatedAt,labels,assignees,body,comments
|
||||
|
||||
# PRs ouvertes (pour cross-référence)
|
||||
gh pr list --state open --limit 50 --json number,title,body
|
||||
|
||||
# Issues fermées récemment (pour détection doublons)
|
||||
gh issue list --state closed --limit 20 \
|
||||
--json number,title,labels,closedAt
|
||||
|
||||
# Collaborateurs (pour protéger les issues des mainteneurs)
|
||||
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
|
||||
```
|
||||
|
||||
**Fallback collaborateurs** : si `gh api .../collaborators` échoue (403/404) :
|
||||
```bash
|
||||
gh pr list --state merged --limit 10 --json author --jq '.[].author.login' | sort -u
|
||||
```
|
||||
Si toujours ambigu, demander à l'utilisateur via `AskUserQuestion`.
|
||||
|
||||
**Note** : `author` est un objet `{login: "..."}` — toujours extraire `.author.login`.
|
||||
|
||||
### Analyse — 6 dimensions
|
||||
|
||||
**1. Catégorisation** (labels existants > inférence titre/body) :
|
||||
- **Bug** : mots-clés `crash`, `error`, `fail`, `broken`, `regression`, `wrong`, `unexpected`
|
||||
- **Feature** : `add`, `implement`, `support`, `new`, `feat:`
|
||||
- **Enhancement** : `improve`, `optimize`, `better`, `enhance`, `refactor`
|
||||
- **Question/Support** : `how`, `why`, `help`, `unclear`, `docs`, `documentation`
|
||||
- **Duplicate Candidate** : voir dimension 3 ci-dessous
|
||||
|
||||
**2. Cross-ref PRs** :
|
||||
- Scanner `body` de chaque PR ouverte pour `fixes #N`, `closes #N`, `resolves #N` (case-insensitive, regex)
|
||||
- Construire un map : `issue_number -> [PR numbers]`
|
||||
- Une issue liée à une PR mergée → recommander fermeture
|
||||
|
||||
**3. Détection doublons** :
|
||||
- Normaliser les titres : lowercase, strip préfixes (`bug:`, `feat:`, `[bug]`, `[feature]`, etc.)
|
||||
- **Jaccard sur mots des titres** : si score > 60% entre deux issues → candidat doublon
|
||||
- **Keywords body overlap** > 50% → renforcement du signal
|
||||
- Comparer aussi avec issues fermées récentes (20 dernières)
|
||||
- Un faux positif peut être confirmé/écarté en Phase 2
|
||||
|
||||
**4. Classification risque** :
|
||||
- **Rouge** : mots-clés `CVE`, `vulnerability`, `injection`, `auth bypass`, `security`, `exploit`, `unsafe`, `credentials`, `leak`, `RCE`, `XSS`
|
||||
- **Jaune** : `breaking change`, `migration`, `deprecation`, `remove API`, `breaking`, `incompatible`
|
||||
- **Vert** : tout le reste
|
||||
|
||||
**5. Staleness** :
|
||||
- >30j sans activité (updatedAt) → **Stale**
|
||||
- >90j sans activité → **Very Stale**
|
||||
- Calculer depuis la date actuelle
|
||||
|
||||
**6. Recommandations d'action** :
|
||||
- `Accept & Prioritize` : issue claire, reproducible, dans scope
|
||||
- `Label needed` : issue sans label
|
||||
- `Comment needed` : info manquante, body insuffisant
|
||||
- `Linked to PR` : une PR ouverte référence cette issue
|
||||
- `Duplicate candidate` : candidat doublon identifié (préciser avec `#N`)
|
||||
- `Close candidate` : stale + aucune activité récente, ou hors scope (jamais si auteur est collaborateur)
|
||||
- `PR merged → close` : PR liée est mergée, issue encore ouverte
|
||||
|
||||
### Output — 5 tableaux
|
||||
|
||||
```
|
||||
## Issues ouvertes ({count})
|
||||
|
||||
### Critiques (risque rouge)
|
||||
| # | Titre | Auteur | Âge | Labels | Action |
|
||||
| - | ----- | ------ | --- | ------ | ------ |
|
||||
|
||||
### Liées à une PR
|
||||
| # | Titre | Auteur | PR(s) liée(s) | Status PR | Action |
|
||||
| - | ----- | ------ | ------------- | --------- | ------ |
|
||||
|
||||
### Actives
|
||||
| # | Titre | Auteur | Catégorie | Âge | Labels | Action |
|
||||
| - | ----- | ------ | --------- | --- | ------ | ------ |
|
||||
|
||||
### Doublons candidats
|
||||
| # | Titre | Doublon de | Similarité | Action |
|
||||
| - | ----- | ---------- | ---------- | ------ |
|
||||
|
||||
### Stale
|
||||
| # | Titre | Auteur | Dernière activité | Action |
|
||||
| - | ----- | ------ | ----------------- | ------ |
|
||||
|
||||
### Résumé
|
||||
- Total : {N} issues ouvertes
|
||||
- Critiques : {N} (risque sécurité ou breaking)
|
||||
- Liées à PR : {N}
|
||||
- Doublons candidats : {N}
|
||||
- Stale (>30j) : {N} | Very Stale (>90j) : {N}
|
||||
- Sans labels : {N}
|
||||
- Quick wins (à fermer ou labeler rapidement) : {liste}
|
||||
```
|
||||
|
||||
0 issues → afficher `Aucune issue ouverte.` et terminer.
|
||||
|
||||
**Note** : `Âge` = jours depuis `createdAt`, format `{N}j`. Si >30j, afficher en **gras**.
|
||||
|
||||
### Copie automatique
|
||||
|
||||
Après affichage du tableau de triage, copier dans le presse-papier :
|
||||
```bash
|
||||
pbcopy <<'EOF'
|
||||
{tableau de triage complet}
|
||||
EOF
|
||||
```
|
||||
Confirmer : `Tableau copié dans le presse-papier.` (FR) / `Triage table copied to clipboard.` (EN)
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Deep Analysis (opt-in)
|
||||
|
||||
### Sélection des issues
|
||||
|
||||
**Si argument passé** :
|
||||
- `"all"` → toutes les issues ouvertes
|
||||
- Numéros (`"42 57"`) → uniquement ces issues
|
||||
- Pas d'argument → proposer via `AskUserQuestion`
|
||||
|
||||
**Si pas d'argument**, afficher :
|
||||
|
||||
```
|
||||
question: "Quelles issues voulez-vous analyser en profondeur ?"
|
||||
header: "Deep Analysis"
|
||||
multiSelect: true
|
||||
options:
|
||||
- label: "Toutes ({N} issues)"
|
||||
description: "Analyse approfondie de toutes les issues avec agents en parallèle"
|
||||
- label: "Critiques uniquement"
|
||||
description: "Focus sur les {M} issues à risque rouge/jaune"
|
||||
- label: "Doublons candidats"
|
||||
description: "Confirmer ou écarter les {K} doublons détectés"
|
||||
- label: "Stale uniquement"
|
||||
description: "Décision close/keep sur les {J} issues stale"
|
||||
- label: "Passer"
|
||||
description: "Terminer ici — juste l'audit"
|
||||
```
|
||||
|
||||
Si "Passer" → fin du workflow.
|
||||
|
||||
### Exécution de l'analyse
|
||||
|
||||
Pour chaque issue sélectionnée, lancer un agent via **Task tool en parallèle** :
|
||||
|
||||
```
|
||||
subagent_type: general-purpose
|
||||
model: sonnet
|
||||
prompt: |
|
||||
Analyze GitHub issue #{num}: "{title}" by @{author}
|
||||
|
||||
**Metadata**: Created {createdAt}, last updated {updatedAt}, labels: {labels}
|
||||
|
||||
**Body**:
|
||||
{body}
|
||||
|
||||
**Existing comments** ({comments_count} total, showing last 5):
|
||||
{last_5_comments}
|
||||
|
||||
**Context**:
|
||||
- Linked PRs: {linked_prs or "none"}
|
||||
- Duplicate candidate of: {duplicate_of or "none"}
|
||||
- Risk classification: {risk_color}
|
||||
|
||||
Analyze this issue and return a structured report:
|
||||
### Scope Assessment
|
||||
What is this issue actually asking for? Is it clearly defined?
|
||||
|
||||
### Missing Information
|
||||
What's needed to act on this? (reproduction steps, version, environment, etc.)
|
||||
|
||||
### Risk & Impact
|
||||
Security risk? Breaking change? Who's affected?
|
||||
|
||||
### Effort Estimate
|
||||
XS (<1h) / S (1-4h) / M (1-2d) / L (3-5d) / XL (>1 week)
|
||||
|
||||
### Priority
|
||||
P0 (critical, act now) / P1 (high, this sprint) / P2 (medium, backlog) / P3 (low, someday)
|
||||
|
||||
### Recommended Action
|
||||
One of: Accept & Prioritize, Request More Info, Mark Duplicate (#N), Close (Stale), Close (Out of Scope), Link to Existing PR
|
||||
|
||||
### Draft Comment
|
||||
Draft a GitHub comment in English using the appropriate template from templates/issue-comment.md.
|
||||
Be specific, helpful, and constructive.
|
||||
```
|
||||
|
||||
Si issue a >50 commentaires, résumer les 5 derniers uniquement.
|
||||
|
||||
Agréger tous les rapports. Afficher un résumé après toutes les analyses.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Actions (validation obligatoire)
|
||||
|
||||
### Types d'actions possibles
|
||||
|
||||
- **Commenter** : `gh issue comment {num} --body-file -`
|
||||
- **Labeler** : `gh issue edit {num} --add-label "{label}"` (skip si label déjà présent)
|
||||
- **Fermer** : `gh issue close {num} --reason "not planned"` (jamais sans validation)
|
||||
|
||||
### Génération des drafts
|
||||
|
||||
Pour chaque issue analysée, générer les actions (commentaire + labels + fermeture si applicable) en utilisant `templates/issue-comment.md`.
|
||||
|
||||
**Règles** :
|
||||
- Langue des commentaires : **anglais** (audience internationale)
|
||||
- Ton : professionnel, constructif, factuel
|
||||
- Ne jamais re-labeler une issue qui a déjà ce label
|
||||
- Ne jamais proposer "close" pour une issue d'un collaborateur
|
||||
- Toujours afficher le draft AVANT tout `gh issue comment`
|
||||
|
||||
### Affichage et validation
|
||||
|
||||
**Afficher TOUS les drafts** au format :
|
||||
|
||||
```
|
||||
---
|
||||
### Draft — Issue #{num}: {title}
|
||||
|
||||
**Actions proposées** : {Commentaire | Label: "bug" | Fermeture}
|
||||
|
||||
**Commentaire** :
|
||||
{commentaire complet}
|
||||
|
||||
---
|
||||
```
|
||||
|
||||
Puis demander validation via `AskUserQuestion` :
|
||||
|
||||
```
|
||||
question: "Ces actions sont prêtes. Lesquelles voulez-vous exécuter ?"
|
||||
header: "Exécuter"
|
||||
multiSelect: true
|
||||
options:
|
||||
- label: "Toutes ({N} actions)"
|
||||
description: "Commenter + labeler + fermer selon les drafts"
|
||||
- label: "Issue #{x} — {title_truncated}"
|
||||
description: "Exécuter uniquement les actions pour cette issue"
|
||||
- label: "Aucune"
|
||||
description: "Annuler — ne rien faire"
|
||||
```
|
||||
|
||||
(Générer une option par issue + "Toutes" + "Aucune")
|
||||
|
||||
### Exécution
|
||||
|
||||
Pour chaque action validée, exécuter dans l'ordre : commenter → labeler → fermer.
|
||||
|
||||
```bash
|
||||
# Commenter
|
||||
gh issue comment {num} --body-file - <<'COMMENT_EOF'
|
||||
{commentaire}
|
||||
COMMENT_EOF
|
||||
|
||||
# Labeler (si applicable)
|
||||
gh issue edit {num} --add-label "{label}"
|
||||
|
||||
# Fermer (si applicable)
|
||||
gh issue close {num} --reason "not planned"
|
||||
```
|
||||
|
||||
Confirmer chaque action : `Commentaire posté sur issue #{num}: {title}`
|
||||
|
||||
Si "Aucune" → `Aucune action exécutée. Workflow terminé.`
|
||||
|
||||
---
|
||||
|
||||
## Gestion des cas limites
|
||||
|
||||
| Situation | Comportement |
|
||||
|-----------|--------------|
|
||||
| 0 issues ouvertes | `Aucune issue ouverte.` + terminer |
|
||||
| Issue sans body | Catégoriser par titre, recommander `Comment needed` |
|
||||
| >50 commentaires | Résumer les 5 derniers uniquement |
|
||||
| Faux positif doublon | Phase 2 confirme/écarte — ne pas agir sur suspicion seule |
|
||||
| Labels déjà présents | Ne pas re-labeler, signaler "label déjà appliqué" |
|
||||
| Issue d'un collaborateur | Jamais `close candidate` automatique |
|
||||
| Rate limit GitHub API | Réduire `--limit`, notifier l'utilisateur |
|
||||
| PR mergée liée à issue ouverte | Recommander fermeture de l'issue |
|
||||
| Issue sans activité >90j | Very Stale — proposer fermeture avec message bienveillant |
|
||||
| Duplicate confirmed in Phase 2 | Poster commentaire + fermer en faveur de l'issue originale |
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- Toujours dériver owner/repo via `gh repo view`, jamais hardcoder
|
||||
- Utiliser `gh` CLI (pas `curl` GitHub API) sauf pour la liste des collaborateurs
|
||||
- `updatedAt` peut être null sur certaines issues → traiter comme `createdAt`
|
||||
- Ne jamais poster ou fermer sans validation explicite de l'utilisateur dans le chat
|
||||
- Les commentaires draftés doivent être visibles AVANT tout `gh issue comment`
|
||||
- Similarité Jaccard = |intersection mots| / |union mots| (exclure stop words : a, the, is, in, of, for, to, with, on, at, by)
|
||||
@@ -0,0 +1,134 @@
|
||||
# Issue Comment Templates
|
||||
|
||||
Use these templates to generate GitHub issue comments. Select the appropriate template based on the recommended action from Phase 2. Comments are posted in **English** (international audience).
|
||||
|
||||
---
|
||||
|
||||
## Template 1 — Acknowledgment + Request Info
|
||||
|
||||
Use when: issue is valid but missing information to act on it (reproduction steps, version, environment, context).
|
||||
|
||||
```markdown
|
||||
## Issue Triage
|
||||
|
||||
**Category**: {Bug | Feature | Enhancement | Question}
|
||||
**Priority**: {P0 | P1 | P2 | P3}
|
||||
**Effort estimate**: {XS | S | M | L | XL}
|
||||
|
||||
### Assessment
|
||||
|
||||
{1-2 sentences: what this issue is about and why it matters. Be direct.}
|
||||
|
||||
### Missing Information
|
||||
|
||||
To move forward, we need the following:
|
||||
|
||||
- {Specific missing info 1 — e.g., "RTK version (`rtk --version` output)"}
|
||||
- {Specific missing info 2 — e.g., "Full command used and raw output"}
|
||||
- {Specific missing info 3 — e.g., "OS and shell (macOS/Linux, zsh/bash)"}
|
||||
|
||||
### Next Steps
|
||||
|
||||
{What happens once the info is provided — e.g., "Once confirmed, we'll prioritize this for the next release."}
|
||||
|
||||
---
|
||||
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template 2 — Duplicate
|
||||
|
||||
Use when: this issue is a duplicate of an existing open (or recently closed) issue.
|
||||
|
||||
```markdown
|
||||
## Duplicate Issue
|
||||
|
||||
This issue covers the same problem as #{original_number}: **{original_title}**.
|
||||
|
||||
### Overlap
|
||||
|
||||
{1-2 sentences explaining the overlap — what's identical or nearly identical between the two issues.}
|
||||
|
||||
If your situation differs in an important way (different command, different OS, different error message), please reopen and add that context. Otherwise, follow the original issue for updates.
|
||||
|
||||
---
|
||||
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template 3 — Close (Stale)
|
||||
|
||||
Use when: issue has had no activity for >90 days and there's been no engagement.
|
||||
|
||||
```markdown
|
||||
## Closing: No Activity
|
||||
|
||||
This issue has been open for {N} days without activity. To keep the backlog actionable, we're closing it.
|
||||
|
||||
If this is still relevant:
|
||||
- Reopen and add context about your current setup
|
||||
- Or reference this issue in a new one if the problem has evolved
|
||||
|
||||
Thanks for taking the time to report it.
|
||||
|
||||
---
|
||||
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template 4 — Close (Out of Scope)
|
||||
|
||||
Use when: issue requests something that doesn't align with RTK's design goals (e.g., adding async runtime, platform-specific features outside scope, changing core behavior).
|
||||
|
||||
```markdown
|
||||
## Closing: Out of Scope
|
||||
|
||||
After review, this request falls outside RTK's current design goals.
|
||||
|
||||
### Rationale
|
||||
|
||||
{1-2 sentences explaining why — be specific. Reference design constraints if relevant, e.g., "RTK is intentionally single-threaded with zero async dependencies to maintain <10ms startup time."}
|
||||
|
||||
### Alternatives
|
||||
|
||||
{If applicable: what the user can do instead. E.g., "For this use case, `rtk proxy <cmd>` gives you raw output while still tracking usage metrics."}
|
||||
|
||||
If the use case evolves or the scope changes in a future version, feel free to reopen with updated context.
|
||||
|
||||
---
|
||||
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Formatting Rules
|
||||
|
||||
**Tone** : Professional, constructive, factual. Help the user move forward. Challenge the issue scope, not the person who filed it.
|
||||
|
||||
**Length** : 100-250 words per comment. Long enough to be useful, short enough to respect the reader's time.
|
||||
|
||||
**Specificity** : Always name the exact command, file, or behavior in question. Vague comments waste everyone's time.
|
||||
|
||||
**No superlatives** : Don't write "great issue", "excellent report", "amazing catch". Just address the substance.
|
||||
|
||||
**Priority labels** :
|
||||
- P0 — Critical: security vulnerability, data loss, broken core functionality
|
||||
- P1 — High: significant bug affecting common workflows, actionable this sprint
|
||||
- P2 — Medium: valid issue, queue for backlog
|
||||
- P3 — Low: nice-to-have, future consideration
|
||||
|
||||
**Effort labels** :
|
||||
- XS : <1 hour
|
||||
- S : 1-4 hours
|
||||
- M : 1-2 days
|
||||
- L : 3-5 days
|
||||
- XL : >1 week
|
||||
|
||||
**RTK-specific context to include when relevant** :
|
||||
- Mention `rtk --version` as the first diagnostic step for bug reports
|
||||
- Reference the relevant module (`src/git.rs`, `src/vitest_cmd.rs`, etc.) when known
|
||||
- Link to the filter development checklist in CLAUDE.md for feature requests that involve new commands
|
||||
- Note performance constraints (<10ms startup) when rejecting async/heavy dependency requests
|
||||
@@ -0,0 +1,315 @@
|
||||
---
|
||||
description: >
|
||||
PR triage: audit open PRs, deep review selected ones, draft and post review comments.
|
||||
Args: "all" to review all, PR numbers to focus (e.g. "42 57"), "en"/"fr" for language, no arg = audit only in French.
|
||||
---
|
||||
|
||||
# PR Triage
|
||||
|
||||
## Quand utiliser
|
||||
|
||||
| Skill | Usage | Output |
|
||||
|-------|-------|--------|
|
||||
| `/pr-triage` | Trier, reviewer, commenter les PRs | Tableau d'action + reviews + commentaires postés |
|
||||
| `/repo-recap` | Récap général pour partager avec l'équipe | Résumé Markdown (PRs + issues + releases) |
|
||||
|
||||
**Déclencheurs** :
|
||||
- Manuellement : `/pr-triage` ou `/pr-triage all` ou `/pr-triage 42 57`
|
||||
- Proactivement : quand >5 PRs ouvertes sans review, ou PR stale >14j détectée
|
||||
|
||||
---
|
||||
|
||||
## Langue
|
||||
|
||||
- Vérifier l'argument passé au skill
|
||||
- Si `en` ou `english` → tableaux et résumé en anglais
|
||||
- Si `fr`, `french`, ou pas d'argument → français (défaut)
|
||||
- Note : les commentaires GitHub (Phase 3) restent TOUJOURS en anglais (audience internationale)
|
||||
|
||||
---
|
||||
|
||||
Workflow en 3 phases : audit automatique → deep review opt-in → commentaires avec validation obligatoire.
|
||||
|
||||
## Préconditions
|
||||
|
||||
```bash
|
||||
git rev-parse --is-inside-work-tree
|
||||
gh auth status
|
||||
```
|
||||
|
||||
Si l'un échoue, stop et expliquer ce qui manque.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Audit (toujours exécutée)
|
||||
|
||||
### Data Gathering (commandes en parallèle)
|
||||
|
||||
```bash
|
||||
# Identité du repo
|
||||
gh repo view --json nameWithOwner -q .nameWithOwner
|
||||
|
||||
# PRs ouvertes avec métadonnées complètes (ajouter body pour cross-référence issues)
|
||||
gh pr list --state open --limit 50 \
|
||||
--json number,title,author,createdAt,updatedAt,additions,deletions,changedFiles,isDraft,mergeable,reviewDecision,statusCheckRollup,body
|
||||
|
||||
# Collaborateurs (pour distinguer "nos PRs" des externes)
|
||||
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
|
||||
```
|
||||
|
||||
**Fallback collaborateurs** : si `gh api .../collaborators` échoue (403/404) :
|
||||
```bash
|
||||
# Extraire les auteurs des 10 derniers PRs mergés
|
||||
gh pr list --state merged --limit 10 --json author --jq '.[].author.login' | sort -u
|
||||
```
|
||||
Si toujours ambigu, demander à l'utilisateur via `AskUserQuestion`.
|
||||
|
||||
Pour chaque PR, récupérer reviews existantes ET fichiers modifiés :
|
||||
|
||||
```bash
|
||||
gh api "repos/{owner}/{repo}/pulls/{num}/reviews" \
|
||||
--jq '[.[] | .user.login + ":" + .state] | join(", ")'
|
||||
|
||||
# Fichiers modifiés (nécessaire pour overlap detection)
|
||||
gh pr view {num} --json files --jq '[.files[].path] | join(",")'
|
||||
```
|
||||
|
||||
**Note rate-limiting** : la récupération des fichiers est N appels API (1 par PR). Pour repos avec 20+ PRs, prioriser les PRs candidates à l'overlap (même domaine fonctionnel, même auteur).
|
||||
|
||||
**Note** : `author` est un objet `{login: "..."}` — toujours extraire `.author.login`.
|
||||
|
||||
### Analyse
|
||||
|
||||
**Classification taille** :
|
||||
| Label | Additions |
|
||||
|-------|-----------|
|
||||
| XS | < 50 |
|
||||
| S | 50–200 |
|
||||
| M | 200–500 |
|
||||
| L | 500–1000 |
|
||||
| XL | > 1000 |
|
||||
|
||||
Format taille : `+{additions}/-{deletions}, {files} files ({label})`
|
||||
|
||||
**Détections** :
|
||||
- **Overlaps** : comparer les listes de fichiers entre PRs — si >50% de fichiers en commun → cross-reference
|
||||
- **Clusters** : auteur avec 3+ PRs ouvertes → suggérer ordre de review (plus petite en premier)
|
||||
- **Staleness** : aucune activité depuis >14j → flag "stale"
|
||||
- **CI status** : via `statusCheckRollup` → `clean` / `unstable` / `dirty`
|
||||
- **Reviews** : approved / changes_requested / aucune
|
||||
|
||||
**Liens PR ↔ Issues** :
|
||||
- Scanner le `body` de chaque PR pour `fixes #N`, `closes #N`, `resolves #N` (case-insensitive)
|
||||
- Si trouvé, afficher dans le tableau : `Fixes #42` dans la colonne Action/Status
|
||||
|
||||
**Catégorisation** :
|
||||
|
||||
_Nos PRs_ : auteur dans la liste des collaborateurs
|
||||
|
||||
_Externes — Prêtes_ : additions ≤ 1000 ET files ≤ 10 ET `mergeable` ≠ `CONFLICTING` ET CI clean/unstable
|
||||
|
||||
_Externes — Problématiques_ : un des critères suivants :
|
||||
- additions > 1000 OU files > 10
|
||||
- OU `mergeable` == `CONFLICTING` (conflit de merge)
|
||||
- OU CI dirty (statusCheckRollup contient des échecs)
|
||||
- OU overlap avec une autre PR ouverte (>50% fichiers communs)
|
||||
|
||||
### Output — Tableau de triage
|
||||
|
||||
```
|
||||
## PRs ouvertes ({count})
|
||||
|
||||
### Nos PRs
|
||||
| PR | Titre | Taille | CI | Status |
|
||||
| -- | ----- | ------ | -- | ------ |
|
||||
|
||||
### Externes — Prêtes pour review
|
||||
| PR | Auteur | Titre | Taille | CI | Reviews | Action |
|
||||
| -- | ------ | ----- | ------ | -- | ------- | ------ |
|
||||
|
||||
### Externes — Problématiques
|
||||
| PR | Auteur | Titre | Taille | Problème | Action recommandée |
|
||||
| -- | ------ | ----- | ------ | -------- | ------------------ |
|
||||
|
||||
### Résumé
|
||||
- Quick wins : {PRs XS/S prêtes à merger}
|
||||
- Risques : {overlaps, tailles XL, CI dirty}
|
||||
- Clusters : {auteurs avec 3+ PRs}
|
||||
- Stale : {PRs sans activité >14j}
|
||||
- Overlaps : {PRs qui touchent les mêmes fichiers}
|
||||
```
|
||||
|
||||
0 PRs → afficher `Aucune PR ouverte.` et terminer.
|
||||
|
||||
### Copie automatique
|
||||
|
||||
Après affichage du tableau de triage, copier dans le presse-papier :
|
||||
```bash
|
||||
pbcopy <<'EOF'
|
||||
{tableau de triage complet}
|
||||
EOF
|
||||
```
|
||||
Confirmer : `Tableau copié dans le presse-papier.` (FR) / `Triage table copied to clipboard.` (EN)
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Deep Review (opt-in)
|
||||
|
||||
### Sélection des PRs
|
||||
|
||||
**Si argument passé** :
|
||||
- `"all"` → toutes les PRs externes
|
||||
- Numéros (`"42 57"`) → uniquement ces PRs
|
||||
- Pas d'argument → proposer via `AskUserQuestion`
|
||||
|
||||
**Si pas d'argument**, afficher :
|
||||
|
||||
```
|
||||
question: "Quelles PRs voulez-vous reviewer en profondeur ?"
|
||||
header: "Deep Review"
|
||||
multiSelect: true
|
||||
options:
|
||||
- label: "Toutes les externes"
|
||||
description: "Review {N} PRs externes avec agents code-reviewer en parallèle"
|
||||
- label: "Problématiques uniquement"
|
||||
description: "Focus sur les {M} PRs à risque (CI dirty, trop large, overlaps)"
|
||||
- label: "Prêtes uniquement"
|
||||
description: "Review {K} PRs prêtes à merger"
|
||||
- label: "Passer"
|
||||
description: "Terminer ici — juste l'audit"
|
||||
```
|
||||
|
||||
**Note sur les drafts** :
|
||||
- Les PRs en draft sont EXCLUES des options "Toutes les externes" et "Prêtes uniquement"
|
||||
- Les PRs en draft sont INCLUSES dans "Problématiques uniquement" (car elles nécessitent attention)
|
||||
- Pour reviewer un draft : taper son numéro explicitement (ex: `42`)
|
||||
|
||||
Si "Passer" → fin du workflow.
|
||||
|
||||
### Exécution des Reviews
|
||||
|
||||
Pour chaque PR sélectionnée, lancer un agent `code-reviewer` via **Task tool en parallèle** :
|
||||
|
||||
```
|
||||
subagent_type: code-reviewer
|
||||
model: sonnet
|
||||
prompt: |
|
||||
Review PR #{num}: "{title}" by @{author}
|
||||
|
||||
**Metadata**: +{additions}/-{deletions}, {changedFiles} files ({size_label})
|
||||
**CI**: {ci_status} | **Reviews**: {existing_reviews} | **Draft**: {isDraft}
|
||||
|
||||
**PR Body**:
|
||||
{body}
|
||||
|
||||
**Diff**:
|
||||
{gh pr diff {num} output}
|
||||
|
||||
Apply your security-guardian and backend-architect skills for this review.
|
||||
Additionally, apply the RTK-specific checklist:
|
||||
- lazy_static! regex (no inline Regex::new())
|
||||
- anyhow::Result + .context() (no unwrap())
|
||||
- Fallback to raw command on filter failure
|
||||
- Exit code propagation
|
||||
- Token savings ≥60% in tests with real fixtures
|
||||
- No async/tokio dependencies
|
||||
|
||||
Return structured review:
|
||||
### Critical Issues 🔴
|
||||
### Important Issues 🟡
|
||||
### Suggestions 🟢
|
||||
### What's Good ✅
|
||||
|
||||
Be specific: quote the file:line, explain why it's an issue, suggest the fix.
|
||||
```
|
||||
|
||||
Récupérer le diff via :
|
||||
```bash
|
||||
gh pr diff {num}
|
||||
gh pr view {num} --json body,title,author -q '{body: .body, title: .title, author: .author.login}'
|
||||
```
|
||||
|
||||
Agréger tous les rapports. Afficher un résumé après toutes les reviews.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Commentaires (validation obligatoire)
|
||||
|
||||
### Génération des drafts
|
||||
|
||||
Pour chaque PR reviewée, générer un commentaire GitHub en utilisant le template `templates/review-comment.md`.
|
||||
|
||||
**Règles** :
|
||||
- Langue : **anglais** (audience internationale)
|
||||
- Ton : professionnel, constructif, factuel
|
||||
- Toujours inclure au moins 1 point positif
|
||||
- Citer les lignes de code quand pertinent (format `file.rs:42`)
|
||||
|
||||
### Affichage et validation
|
||||
|
||||
**Afficher TOUS les commentaires draftés** au format :
|
||||
|
||||
```
|
||||
---
|
||||
### Draft — PR #{num}: {title}
|
||||
|
||||
{commentaire complet}
|
||||
|
||||
---
|
||||
```
|
||||
|
||||
Puis demander validation via `AskUserQuestion` :
|
||||
|
||||
```
|
||||
question: "Ces commentaires sont prêts. Lesquels voulez-vous poster ?"
|
||||
header: "Poster"
|
||||
multiSelect: true
|
||||
options:
|
||||
- label: "Tous ({N} commentaires)"
|
||||
description: "Poster sur toutes les PRs reviewées"
|
||||
- label: "PR #{x} — {title_truncated}"
|
||||
description: "Poster uniquement sur cette PR"
|
||||
- label: "Aucun"
|
||||
description: "Annuler — ne rien poster"
|
||||
```
|
||||
|
||||
(Générer une option par PR + "Tous" + "Aucun")
|
||||
|
||||
### Posting
|
||||
|
||||
Pour chaque commentaire validé :
|
||||
|
||||
```bash
|
||||
gh pr comment {num} --body-file - <<'REVIEW_EOF'
|
||||
{commentaire}
|
||||
REVIEW_EOF
|
||||
```
|
||||
|
||||
Confirmer chaque post : `✅ Commentaire posté sur PR #{num}: {title}`
|
||||
|
||||
Si "Aucun" → `Aucun commentaire posté. Workflow terminé.`
|
||||
|
||||
---
|
||||
|
||||
## Gestion des cas limites
|
||||
|
||||
| Situation | Comportement |
|
||||
|-----------|--------------|
|
||||
| 0 PRs ouvertes | `Aucune PR ouverte.` + terminer |
|
||||
| PR en draft | Indiquer dans tableau, skip pour review sauf si sélectionnée explicitement |
|
||||
| CI inconnu | Afficher `?` dans colonne CI |
|
||||
| Review agent timeout | Afficher erreur partielle, continuer avec les autres |
|
||||
| `gh pr diff` vide | Skip cette PR, notifier l'utilisateur |
|
||||
| PR très large (>5000 additions) | Avertir : "Review partielle, diff tronqué" |
|
||||
| Collaborateurs API 403/404 | Fallback sur auteurs des 10 derniers PRs mergés |
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- Toujours dériver owner/repo via `gh repo view`, jamais hardcoder
|
||||
- Utiliser `gh` CLI (pas `curl` GitHub API) sauf pour la liste des collaborateurs
|
||||
- `statusCheckRollup` peut être null → traiter comme `?`
|
||||
- `mergeable` peut être `MERGEABLE`, `CONFLICTING`, ou `UNKNOWN` → traiter `UNKNOWN` comme `?`
|
||||
- Ne jamais poster sans validation explicite de l'utilisateur dans le chat
|
||||
- Les commentaires draftés doivent être visibles AVANT tout `gh pr comment`
|
||||
@@ -0,0 +1,71 @@
|
||||
# Review Comment Template
|
||||
|
||||
Use this template to generate GitHub PR review comments. Fill in each section based on the code-reviewer agent output. Comments are posted in **English** (international audience).
|
||||
|
||||
---
|
||||
|
||||
## Template
|
||||
|
||||
```markdown
|
||||
## Review
|
||||
|
||||
**Scope**: Security, code quality, performance, test coverage, architecture
|
||||
|
||||
### Summary
|
||||
|
||||
{1–2 sentences: overall assessment. Be direct — what's the main takeaway?}
|
||||
|
||||
### Critical Issues 🔴
|
||||
|
||||
{List blocking issues that must be fixed before merge. For each:}
|
||||
{- `file.rs:42` — Description of the problem. Why it matters. Suggested fix.}
|
||||
|
||||
{If none: "None found."}
|
||||
|
||||
### Important Issues 🟡
|
||||
|
||||
{List significant issues that should be fixed. For each:}
|
||||
{- `file.rs:42` — Description. Why it matters. Suggested fix.}
|
||||
|
||||
{If none: "None found."}
|
||||
|
||||
### Suggestions 🟢
|
||||
|
||||
{List nice-to-haves and minor improvements. For each:}
|
||||
{- Description. Context. Optional fix.}
|
||||
|
||||
{If none: omit this section.}
|
||||
|
||||
### What's Good ✅
|
||||
|
||||
{Always include at least 1 positive point. Be specific — what works well and why.}
|
||||
{- Description of what's done right.}
|
||||
|
||||
---
|
||||
*Automated review via [rtk](https://github.com/rtk-ai/rtk) `/pr-triage`*
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Formatting Rules
|
||||
|
||||
**Citation format** : `file.rs:42` or `` `code snippet` `` for inline references
|
||||
|
||||
**Issue severity** :
|
||||
- 🔴 Critical : security vulnerability, data loss risk, broken functionality, test missing for new feature
|
||||
- 🟡 Important : error handling gap, performance regression, scope creep, missing token savings assertion
|
||||
- 🟢 Suggestion : naming, DRY opportunity, documentation, style
|
||||
|
||||
**RTK-specific checks to mention if relevant** :
|
||||
- `lazy_static!` for regex (not inline `Regex::new()`)
|
||||
- `anyhow::Result` + `.context("msg")` (no bare `?`, no `.unwrap()`)
|
||||
- Fallback to raw command on filter failure
|
||||
- Exit code propagation (`std::process::exit(code)`)
|
||||
- Token savings assertion ≥60% in tests
|
||||
- Real fixtures (not synthetic test data)
|
||||
- No async/tokio dependencies (startup time)
|
||||
|
||||
**Tone** : Professional, constructive, factual. Challenge the code, not the person.
|
||||
No superlatives ("great", "amazing", "perfect"). No filler ("as mentioned", "it's worth noting").
|
||||
|
||||
**Length** : Aim for 200–400 words. Long enough to be useful, short enough to be read.
|
||||
@@ -72,6 +72,9 @@ jobs:
|
||||
|
||||
- name: Build
|
||||
run: cargo build --release --target ${{ matrix.target }}
|
||||
env:
|
||||
RTK_TELEMETRY_URL: ${{ vars.RTK_TELEMETRY_URL }}
|
||||
RTK_TELEMETRY_TOKEN: ${{ secrets.RTK_TELEMETRY_TOKEN }}
|
||||
|
||||
- name: Package (Unix)
|
||||
if: matrix.os != 'windows-latest'
|
||||
@@ -108,6 +111,9 @@ jobs:
|
||||
|
||||
- name: Build DEB
|
||||
run: cargo deb
|
||||
env:
|
||||
RTK_TELEMETRY_URL: ${{ vars.RTK_TELEMETRY_URL }}
|
||||
RTK_TELEMETRY_TOKEN: ${{ secrets.RTK_TELEMETRY_TOKEN }}
|
||||
|
||||
- name: Upload DEB
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -132,6 +138,9 @@ jobs:
|
||||
|
||||
- name: Build release
|
||||
run: cargo build --release
|
||||
env:
|
||||
RTK_TELEMETRY_URL: ${{ vars.RTK_TELEMETRY_URL }}
|
||||
RTK_TELEMETRY_TOKEN: ${{ secrets.RTK_TELEMETRY_TOKEN }}
|
||||
|
||||
- name: Generate RPM
|
||||
run: cargo generate-rpm
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.25.0"
|
||||
".": "0.27.1"
|
||||
}
|
||||
+2
-2
@@ -293,7 +293,7 @@ SHARED utils.rs Helpers N/A ✓
|
||||
tee.rs Full output recovery N/A ✓
|
||||
```
|
||||
|
||||
**Total: 55 modules** (37 command modules + 18 infrastructure modules)
|
||||
**Total: 57 modules** (38 command modules + 19 infrastructure modules)
|
||||
|
||||
### Module Count Breakdown
|
||||
|
||||
@@ -1488,4 +1488,4 @@ When implementing a new command, consider:
|
||||
|
||||
**Last Updated**: 2026-02-22
|
||||
**Architecture Version**: 2.2
|
||||
**rtk Version**: 0.24.0
|
||||
**rtk Version**: 0.26.0
|
||||
@@ -5,6 +5,53 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.27.1](https://github.com/rtk-ai/rtk/compare/v0.27.0...v0.27.1) (2026-03-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* only rewrite docker compose ps/logs/build, skip unsupported subcommands ([#336](https://github.com/rtk-ai/rtk/issues/336)) ([#363](https://github.com/rtk-ai/rtk/issues/363)) ([dbc9503](https://github.com/rtk-ai/rtk/commit/dbc950395e31b4b0bc48710dc52ad01d4d73f9ba))
|
||||
* preserve -- separator for cargo commands and silence fallback ([#326](https://github.com/rtk-ai/rtk/issues/326)) ([45f9344](https://github.com/rtk-ai/rtk/commit/45f9344f033d27bc370ff54c4fc0c61e52446076)), closes [#286](https://github.com/rtk-ai/rtk/issues/286) [#287](https://github.com/rtk-ai/rtk/issues/287)
|
||||
* prettier false positive when not installed ([#221](https://github.com/rtk-ai/rtk/issues/221)) ([#359](https://github.com/rtk-ai/rtk/issues/359)) ([85b0b3e](https://github.com/rtk-ai/rtk/commit/85b0b3eb0bad9cbacdc32d2e9ba525728acd7cbe))
|
||||
* support git commit -am, --amend and other flags ([#327](https://github.com/rtk-ai/rtk/issues/327)) ([#360](https://github.com/rtk-ai/rtk/issues/360)) ([409aed6](https://github.com/rtk-ai/rtk/commit/409aed6dbcdd7cac2a48ec5655e6f1fd8d5248e3))
|
||||
|
||||
## [0.27.0](https://github.com/rtk-ai/rtk/compare/v0.26.0...v0.27.0) (2026-03-05)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* warn when installed hook is outdated ([#344](https://github.com/rtk-ai/rtk/issues/344)) ([#350](https://github.com/rtk-ai/rtk/issues/350)) ([3141fec](https://github.com/rtk-ai/rtk/commit/3141fecf958af5ae98c232543b913f3ca388254f))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* bugs [#196](https://github.com/rtk-ai/rtk/issues/196) [#344](https://github.com/rtk-ai/rtk/issues/344) [#345](https://github.com/rtk-ai/rtk/issues/345) [#346](https://github.com/rtk-ai/rtk/issues/346) [#347](https://github.com/rtk-ai/rtk/issues/347) — gh --json, hook check, RTK_DISABLED, 2>&1, json TOML ([8953af0](https://github.com/rtk-ai/rtk/commit/8953af0fc06759b37f16743ef383af0a52af2bed))
|
||||
* RTK_DISABLED ignored, 2>&1 broken, json TOML error ([#345](https://github.com/rtk-ai/rtk/issues/345), [#346](https://github.com/rtk-ai/rtk/issues/346), [#347](https://github.com/rtk-ai/rtk/issues/347)) ([6c13d23](https://github.com/rtk-ai/rtk/commit/6c13d234364d314f53b6698c282a621019635fd6))
|
||||
* skip rewrite for gh --json/--jq/--template ([#196](https://github.com/rtk-ai/rtk/issues/196)) ([079ee9a](https://github.com/rtk-ai/rtk/commit/079ee9a4ea868ecf4e7beffcbc681ca1ba8b165c))
|
||||
|
||||
## [0.26.0](https://github.com/rtk-ai/rtk/compare/v0.25.0...v0.26.0) (2026-03-05)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add Claude Code skills for PR and issue triage ([#343](https://github.com/rtk-ai/rtk/issues/343)) ([6ad6ffe](https://github.com/rtk-ai/rtk/commit/6ad6ffeccee9b622013f8e1357b6ca4c94aacb59))
|
||||
* anonymous telemetry ping (1/day, opt-out) ([#334](https://github.com/rtk-ai/rtk/issues/334)) ([baff6a2](https://github.com/rtk-ai/rtk/commit/baff6a2334b155c0d68f38dba85bd8d6fe9e20af))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* curl JSON size guard ([#297](https://github.com/rtk-ai/rtk/issues/297)) + exclude_commands config ([#243](https://github.com/rtk-ai/rtk/issues/243)) ([#342](https://github.com/rtk-ai/rtk/issues/342)) ([a8d6106](https://github.com/rtk-ai/rtk/commit/a8d6106f736e049013ecb77f0f413167266dd40e))
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Features
|
||||
|
||||
* **hooks:** `exclude_commands` config — exclude specific commands from auto-rewrite ([#243](https://github.com/rtk-ai/rtk/issues/243))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **curl:** skip JSON schema replacement when schema is larger than original payload ([#297](https://github.com/rtk-ai/rtk/issues/297))
|
||||
|
||||
## [0.25.0](https://github.com/rtk-ai/rtk/compare/v0.24.0...v0.25.0) (2026-03-05)
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ This is a fork with critical fixes for git argument parsing and modern JavaScrip
|
||||
|
||||
**Verify correct installation:**
|
||||
```bash
|
||||
rtk --version # Should show "rtk 0.24.0" (or newer)
|
||||
rtk --version # Should show "rtk 0.26.0" (or newer)
|
||||
rtk gain # Should show token savings stats (NOT "command not found")
|
||||
```
|
||||
|
||||
|
||||
Generated
+442
-1
@@ -2,6 +2,12 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
@@ -94,6 +100,12 @@ version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.10.0"
|
||||
@@ -225,6 +237,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.6"
|
||||
@@ -291,6 +312,17 @@ dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -331,6 +363,25 @@ version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -407,6 +458,17 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hostname"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.64"
|
||||
@@ -431,6 +493,108 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_normalizer_data",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"smallvec",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer_data"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_properties_data",
|
||||
"icu_provider",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties_data"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
|
||||
dependencies = [
|
||||
"idna_adapter",
|
||||
"smallvec",
|
||||
"utf8_iter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna_adapter"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
|
||||
dependencies = [
|
||||
"icu_normalizer",
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ignore"
|
||||
version = "0.4.25"
|
||||
@@ -518,6 +682,12 @@ version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.29"
|
||||
@@ -530,6 +700,16 @@ version = "2.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -557,12 +737,27 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"
|
||||
dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
@@ -627,15 +822,30 @@ version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rtk"
|
||||
version = "0.25.0"
|
||||
version = "0.27.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"clap",
|
||||
"colored",
|
||||
"dirs",
|
||||
"hostname",
|
||||
"ignore",
|
||||
"lazy_static",
|
||||
"regex",
|
||||
@@ -646,6 +856,7 @@ dependencies = [
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"toml",
|
||||
"ureq",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
@@ -676,6 +887,41 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.22"
|
||||
@@ -761,18 +1007,36 @@ version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.114"
|
||||
@@ -784,6 +1048,17 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.24.0"
|
||||
@@ -817,6 +1092,16 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.8.23"
|
||||
@@ -870,6 +1155,46 @@ version = "1.0.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"flate2",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"url",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
@@ -958,6 +1283,24 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
@@ -1035,6 +1378,15 @@ dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
@@ -1189,6 +1541,35 @@ version = "0.51.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
"yoke-derive",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.33"
|
||||
@@ -1209,6 +1590,66 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"
|
||||
dependencies = [
|
||||
"zerofrom-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom-derive"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"
|
||||
dependencies = [
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.16"
|
||||
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rtk"
|
||||
version = "0.25.0"
|
||||
version = "0.27.1"
|
||||
edition = "2021"
|
||||
authors = ["Patrick Szymkowiak"]
|
||||
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
|
||||
@@ -28,6 +28,8 @@ chrono = "0.4"
|
||||
thiserror = "1.0"
|
||||
tempfile = "3"
|
||||
sha2 = "0.10"
|
||||
ureq = "2"
|
||||
hostname = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ rtk filters and compresses command outputs before they reach your LLM context, s
|
||||
|
||||
**How to verify you have the correct rtk:**
|
||||
```bash
|
||||
rtk --version # Should show "rtk 0.24.0"
|
||||
rtk --version # Should show "rtk 0.26.0"
|
||||
rtk gain # Should show token savings stats
|
||||
```
|
||||
|
||||
@@ -103,7 +103,7 @@ cargo install rtk
|
||||
|
||||
Download from [rtk-ai/releases](https://github.com/rtk-ai/rtk/releases):
|
||||
- macOS: `rtk-x86_64-apple-darwin.tar.gz` / `rtk-aarch64-apple-darwin.tar.gz`
|
||||
- Linux: `rtk-x86_64-unknown-linux-gnu.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz`
|
||||
- Linux: `rtk-x86_64-unknown-linux-musl.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz`
|
||||
- Windows: `rtk-x86_64-pc-windows-msvc.zip`
|
||||
|
||||
## Quick Start
|
||||
@@ -455,6 +455,18 @@ database_path = "/path/to/custom.db"
|
||||
|
||||
Priority: `RTK_DB_PATH` env var > `config.toml` > default location.
|
||||
|
||||
### Excluding Commands from Auto-Rewrite
|
||||
|
||||
By default, the hook rewrites all supported commands automatically. To exclude specific commands (e.g., keep raw `curl` output without schema extraction), add to your config:
|
||||
|
||||
**Config file** (`~/.config/rtk/config.toml`, macOS: `~/Library/Application Support/rtk/config.toml`):
|
||||
```toml
|
||||
[hooks]
|
||||
exclude_commands = ["curl", "playwright"]
|
||||
```
|
||||
|
||||
Excluded commands pass through the hook unchanged — no RTK filtering. This survives `rtk init -g` re-runs since the config file is user-owned.
|
||||
|
||||
### Tee: Full Output Recovery
|
||||
|
||||
When RTK filters command output, LLM agents lose failure details (stack traces, assertion messages) and may re-run the same command 2-3 times. The **tee** feature saves raw output to a file so the agent can read it without re-executing.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# rtk-hook-version: 2
|
||||
# RTK Claude Code hook — rewrites commands to use rtk for token savings.
|
||||
# Requires: rtk >= 0.23.0, jq
|
||||
#
|
||||
|
||||
@@ -239,6 +239,44 @@ test_rewrite "kubectl apply -f deploy.yaml" \
|
||||
|
||||
echo ""
|
||||
|
||||
# ---- SECTION 3b: RTK_DISABLED and redirect fixes (#345, #346) ----
|
||||
echo "--- RTK_DISABLED (#345) ---"
|
||||
test_rewrite "RTK_DISABLED=1 git status (no rewrite)" \
|
||||
"RTK_DISABLED=1 git status" \
|
||||
""
|
||||
|
||||
test_rewrite "RTK_DISABLED=1 cargo test (no rewrite)" \
|
||||
"RTK_DISABLED=1 cargo test" \
|
||||
""
|
||||
|
||||
test_rewrite "FOO=1 RTK_DISABLED=1 git status (no rewrite)" \
|
||||
"FOO=1 RTK_DISABLED=1 git status" \
|
||||
""
|
||||
|
||||
echo ""
|
||||
echo "--- Redirect operators (#346) ---"
|
||||
test_rewrite "cargo test 2>&1 | head" \
|
||||
"cargo test 2>&1 | head" \
|
||||
"rtk cargo test 2>&1 | head"
|
||||
|
||||
test_rewrite "cargo test 2>&1" \
|
||||
"cargo test 2>&1" \
|
||||
"rtk cargo test 2>&1"
|
||||
|
||||
test_rewrite "cargo test &>/dev/null" \
|
||||
"cargo test &>/dev/null" \
|
||||
"rtk cargo test &>/dev/null"
|
||||
|
||||
# Note: the bash hook rewrites only the first command segment (sed-based);
|
||||
# full compound rewriting (both sides of &) is handled by `rtk rewrite` (Rust).
|
||||
# The critical behavior tested here: `&` after `cargo test` is NOT mistaken for
|
||||
# a redirect — the hook still rewrites cargo test, no crash.
|
||||
test_rewrite "cargo test & git status (bash hook rewrites first segment only)" \
|
||||
"cargo test & git status" \
|
||||
"rtk cargo test & git status"
|
||||
|
||||
echo ""
|
||||
|
||||
# ---- SECTION 4: Vitest edge case (fixed double "run" bug) ----
|
||||
echo "--- Vitest run dedup ---"
|
||||
test_rewrite "vitest (no args)" \
|
||||
|
||||
+60
-6
@@ -1,8 +1,16 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
RTK="$(cd "$(dirname ./target/release/rtk)" && pwd)/$(basename ./target/release/rtk)"
|
||||
BENCH_DIR="./scripts/benchmark"
|
||||
# Use local release build if available, otherwise fall back to installed rtk
|
||||
if [ -f "./target/release/rtk" ]; then
|
||||
RTK="$(cd "$(dirname ./target/release/rtk)" && pwd)/$(basename ./target/release/rtk)"
|
||||
elif command -v rtk &> /dev/null; then
|
||||
RTK="$(command -v rtk)"
|
||||
else
|
||||
echo "Error: rtk not found. Run 'cargo build --release' or install rtk."
|
||||
exit 1
|
||||
fi
|
||||
BENCH_DIR="$(pwd)/scripts/benchmark"
|
||||
|
||||
# Mode local : générer les fichiers debug
|
||||
if [ -z "$CI" ]; then
|
||||
@@ -258,6 +266,50 @@ section "summary"
|
||||
bench "summary cargo --help" "cargo --help" "$RTK summary cargo --help"
|
||||
bench "summary rustc --help" "rustc --help 2>/dev/null || echo 'rustc not found'" "$RTK summary rustc --help"
|
||||
|
||||
# ===================
|
||||
# cargo
|
||||
# ===================
|
||||
section "cargo"
|
||||
bench "cargo build" "cargo build 2>&1 || true" "$RTK cargo build"
|
||||
bench "cargo test" "cargo test 2>&1 || true" "$RTK cargo test"
|
||||
bench "cargo clippy" "cargo clippy 2>&1 || true" "$RTK cargo clippy"
|
||||
bench "cargo check" "cargo check 2>&1 || true" "$RTK cargo check"
|
||||
|
||||
# ===================
|
||||
# diff
|
||||
# ===================
|
||||
section "diff"
|
||||
bench "diff" "diff Cargo.toml LICENSE 2>&1 || true" "$RTK diff Cargo.toml LICENSE"
|
||||
|
||||
# ===================
|
||||
# smart
|
||||
# ===================
|
||||
section "smart"
|
||||
bench "smart main.rs" "cat src/main.rs" "$RTK smart src/main.rs"
|
||||
|
||||
# ===================
|
||||
# wc
|
||||
# ===================
|
||||
section "wc"
|
||||
bench "wc" "wc Cargo.toml src/main.rs" "$RTK wc Cargo.toml src/main.rs"
|
||||
|
||||
# ===================
|
||||
# curl
|
||||
# ===================
|
||||
section "curl"
|
||||
if command -v curl &> /dev/null; then
|
||||
bench "curl json" "curl -s https://httpbin.org/json" "$RTK curl https://httpbin.org/json"
|
||||
bench "curl text" "curl -s https://httpbin.org/robots.txt" "$RTK curl https://httpbin.org/robots.txt"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# wget
|
||||
# ===================
|
||||
if command -v wget &> /dev/null; then
|
||||
section "wget"
|
||||
bench "wget" "wget -qO- https://httpbin.org/robots.txt" "$RTK wget https://httpbin.org/robots.txt -O"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# Modern JavaScript Stack (skip si pas de package.json)
|
||||
# ===================
|
||||
@@ -381,8 +433,8 @@ def test_process_data_none():
|
||||
assert process_data(None) == []
|
||||
PYEOF
|
||||
|
||||
bench "ruff check" "ruff check . 2>&1 || true" "$RTK test ruff check ."
|
||||
bench "pytest" "pytest -v 2>&1 || true" "$RTK test pytest -v"
|
||||
bench "ruff check" "ruff check . 2>&1 || true" "$RTK ruff check ."
|
||||
bench "pytest" "pytest -v 2>&1 || true" "$RTK pytest -v"
|
||||
|
||||
cd - > /dev/null
|
||||
rm -rf "$PYTHON_FIXTURE"
|
||||
@@ -445,8 +497,10 @@ func TestMultiply(t *testing.T) {
|
||||
}
|
||||
GOEOF
|
||||
|
||||
bench "golangci-lint" "golangci-lint run 2>&1 || true" "$RTK test golangci-lint run"
|
||||
bench "go test" "go test -v 2>&1 || true" "$RTK test go test -v"
|
||||
bench "golangci-lint" "golangci-lint run 2>&1 || true" "$RTK golangci-lint run"
|
||||
bench "go test" "go test -v 2>&1 || true" "$RTK go test -v"
|
||||
bench "go build" "go build ./... 2>&1 || true" "$RTK go build ./..."
|
||||
bench "go vet" "go vet ./... 2>&1 || true" "$RTK go vet ./..."
|
||||
|
||||
cd - > /dev/null
|
||||
rm -rf "$GO_FIXTURE"
|
||||
|
||||
@@ -68,6 +68,19 @@ assert_exit_ok() {
|
||||
fi
|
||||
}
|
||||
|
||||
assert_fails() {
|
||||
local name="$1"
|
||||
shift
|
||||
if "$@" >/dev/null 2>&1; then
|
||||
FAIL=$((FAIL + 1))
|
||||
FAILURES+=("$name (expected failure, got success)")
|
||||
printf " ${RED}FAIL${NC} %s (expected failure)\n" "$name"
|
||||
else
|
||||
PASS=$((PASS + 1))
|
||||
printf " ${GREEN}PASS${NC} %s\n" "$name"
|
||||
fi
|
||||
}
|
||||
|
||||
assert_help() {
|
||||
local name="$1"
|
||||
shift
|
||||
@@ -433,6 +446,91 @@ section "Learn"
|
||||
assert_ok "rtk learn --help" rtk learn --help
|
||||
assert_ok "rtk learn (no sessions)" rtk learn --since 0 2>&1 || true
|
||||
|
||||
# ── 32. Rewrite ───────────────────────────────────────
|
||||
|
||||
section "Rewrite"
|
||||
|
||||
assert_contains "rewrite git status" "rtk git status" rtk rewrite "git status"
|
||||
assert_contains "rewrite cargo test" "rtk cargo test" rtk rewrite "cargo test"
|
||||
assert_contains "rewrite compound &&" "rtk git status" rtk rewrite "git status && cargo test"
|
||||
assert_contains "rewrite pipe preserves" "| head" rtk rewrite "git log | head"
|
||||
|
||||
section "Rewrite (#345: RTK_DISABLED skip)"
|
||||
|
||||
assert_fails "rewrite RTK_DISABLED=1 skip" rtk rewrite "RTK_DISABLED=1 git status"
|
||||
assert_fails "rewrite env RTK_DISABLED skip" rtk rewrite "FOO=1 RTK_DISABLED=1 cargo test"
|
||||
|
||||
section "Rewrite (#346: 2>&1 preserved)"
|
||||
|
||||
assert_contains "rewrite 2>&1 preserved" "2>&1" rtk rewrite "cargo test 2>&1 | head"
|
||||
|
||||
section "Rewrite (#196: gh --json skip)"
|
||||
|
||||
assert_fails "rewrite gh --json skip" rtk rewrite "gh pr list --json number"
|
||||
assert_fails "rewrite gh --jq skip" rtk rewrite "gh api /repos --jq .name"
|
||||
assert_fails "rewrite gh --template skip" rtk rewrite "gh pr view 1 --template '{{.title}}'"
|
||||
assert_contains "rewrite gh normal works" "rtk gh pr list" rtk rewrite "gh pr list"
|
||||
|
||||
# ── 33. Verify ────────────────────────────────────────
|
||||
|
||||
section "Verify"
|
||||
|
||||
assert_ok "rtk verify" rtk verify
|
||||
|
||||
# ── 34. Proxy ─────────────────────────────────────────
|
||||
|
||||
section "Proxy"
|
||||
|
||||
assert_ok "rtk proxy echo hello" rtk proxy echo hello
|
||||
assert_contains "rtk proxy passthrough" "hello" rtk proxy echo hello
|
||||
|
||||
# ── 35. Discover ──────────────────────────────────────
|
||||
|
||||
section "Discover"
|
||||
|
||||
assert_ok "rtk discover" rtk discover
|
||||
|
||||
# ── 36. Diff ──────────────────────────────────────────
|
||||
|
||||
section "Diff"
|
||||
|
||||
assert_ok "rtk diff two files" rtk diff Cargo.toml LICENSE
|
||||
|
||||
# ── 37. Wc ────────────────────────────────────────────
|
||||
|
||||
section "Wc"
|
||||
|
||||
assert_ok "rtk wc Cargo.toml" rtk wc Cargo.toml
|
||||
|
||||
# ── 38. Smart ─────────────────────────────────────────
|
||||
|
||||
section "Smart"
|
||||
|
||||
assert_ok "rtk smart src/main.rs" rtk smart src/main.rs
|
||||
|
||||
# ── 39. Json edge cases ──────────────────────────────
|
||||
|
||||
section "Json (edge cases)"
|
||||
|
||||
assert_fails "rtk json on TOML (#347)" rtk json Cargo.toml
|
||||
|
||||
# ── 40. Docker (conditional) ─────────────────────────
|
||||
|
||||
section "Docker (conditional)"
|
||||
|
||||
if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
|
||||
assert_ok "rtk docker ps" rtk docker ps
|
||||
assert_ok "rtk docker images" rtk docker images
|
||||
else
|
||||
skip_test "rtk docker" "docker not running"
|
||||
fi
|
||||
|
||||
# ── 41. Hook check ───────────────────────────────────
|
||||
|
||||
section "Hook check (#344)"
|
||||
|
||||
assert_contains "rtk init --show hook version" "version" rtk init --show
|
||||
|
||||
# ══════════════════════════════════════════════════════
|
||||
# Report
|
||||
# ══════════════════════════════════════════════════════
|
||||
|
||||
+109
-4
@@ -27,6 +27,40 @@ pub fn run(cmd: CargoCommand, args: &[String], verbose: u8) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconstruct args with `--` separator preserved from the original command line.
|
||||
/// Clap strips `--` from parsed args, but cargo subcommands need it to separate
|
||||
/// their own flags from test runner flags (e.g. `cargo test -- --nocapture`).
|
||||
fn restore_double_dash(args: &[String]) -> Vec<String> {
|
||||
let raw_args: Vec<String> = std::env::args().collect();
|
||||
restore_double_dash_with_raw(args, &raw_args)
|
||||
}
|
||||
|
||||
/// Testable version that takes raw_args explicitly.
|
||||
fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<String> {
|
||||
if args.is_empty() {
|
||||
return args.to_vec();
|
||||
}
|
||||
|
||||
// Find `--` in the original command line
|
||||
let sep_pos = match raw_args.iter().position(|a| a == "--") {
|
||||
Some(pos) => pos,
|
||||
None => return args.to_vec(),
|
||||
};
|
||||
|
||||
// Count how many of our parsed args appeared before `--` in the original.
|
||||
// Args before `--` are positional (e.g. test name), args after are flags.
|
||||
let args_before_sep = raw_args[..sep_pos]
|
||||
.iter()
|
||||
.filter(|a| args.contains(a))
|
||||
.count();
|
||||
|
||||
let mut result = Vec::with_capacity(args.len() + 1);
|
||||
result.extend_from_slice(&args[..args_before_sep]);
|
||||
result.push("--".to_string());
|
||||
result.extend_from_slice(&args[args_before_sep..]);
|
||||
result
|
||||
}
|
||||
|
||||
/// Generic cargo command runner with filtering
|
||||
fn run_cargo_filtered<F>(subcommand: &str, args: &[String], verbose: u8, filter_fn: F) -> Result<()>
|
||||
where
|
||||
@@ -36,12 +70,14 @@ where
|
||||
|
||||
let mut cmd = Command::new("cargo");
|
||||
cmd.arg(subcommand);
|
||||
for arg in args {
|
||||
|
||||
let restored_args = restore_double_dash(args);
|
||||
for arg in &restored_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("Running: cargo {} {}", subcommand, args.join(" "));
|
||||
eprintln!("Running: cargo {} {}", subcommand, restored_args.join(" "));
|
||||
}
|
||||
|
||||
let output = cmd
|
||||
@@ -65,8 +101,8 @@ where
|
||||
}
|
||||
|
||||
timer.track(
|
||||
&format!("cargo {} {}", subcommand, args.join(" ")),
|
||||
&format!("rtk cargo {} {}", subcommand, args.join(" ")),
|
||||
&format!("cargo {} {}", subcommand, restored_args.join(" ")),
|
||||
&format!("rtk cargo {} {}", subcommand, restored_args.join(" ")),
|
||||
&raw,
|
||||
&filtered,
|
||||
);
|
||||
@@ -950,6 +986,75 @@ pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_restore_double_dash_with_separator() {
|
||||
// rtk cargo test -- --nocapture → clap gives ["--nocapture"]
|
||||
let args: Vec<String> = vec!["--nocapture".into()];
|
||||
let raw = vec![
|
||||
"rtk".into(),
|
||||
"cargo".into(),
|
||||
"test".into(),
|
||||
"--".into(),
|
||||
"--nocapture".into(),
|
||||
];
|
||||
let result = restore_double_dash_with_raw(&args, &raw);
|
||||
assert_eq!(result, vec!["--", "--nocapture"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_double_dash_with_test_name() {
|
||||
// rtk cargo test my_test -- --nocapture → clap gives ["my_test", "--nocapture"]
|
||||
let args: Vec<String> = vec!["my_test".into(), "--nocapture".into()];
|
||||
let raw = vec![
|
||||
"rtk".into(),
|
||||
"cargo".into(),
|
||||
"test".into(),
|
||||
"my_test".into(),
|
||||
"--".into(),
|
||||
"--nocapture".into(),
|
||||
];
|
||||
let result = restore_double_dash_with_raw(&args, &raw);
|
||||
assert_eq!(result, vec!["my_test", "--", "--nocapture"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_double_dash_without_separator() {
|
||||
// rtk cargo test my_test → no --, args unchanged
|
||||
let args: Vec<String> = vec!["my_test".into()];
|
||||
let raw = vec![
|
||||
"rtk".into(),
|
||||
"cargo".into(),
|
||||
"test".into(),
|
||||
"my_test".into(),
|
||||
];
|
||||
let result = restore_double_dash_with_raw(&args, &raw);
|
||||
assert_eq!(result, vec!["my_test"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_double_dash_empty_args() {
|
||||
let args: Vec<String> = vec![];
|
||||
let raw = vec!["rtk".into(), "cargo".into(), "test".into()];
|
||||
let result = restore_double_dash_with_raw(&args, &raw);
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_double_dash_clippy() {
|
||||
// rtk cargo clippy -- -D warnings → clap gives ["-D", "warnings"]
|
||||
let args: Vec<String> = vec!["-D".into(), "warnings".into()];
|
||||
let raw = vec![
|
||||
"rtk".into(),
|
||||
"cargo".into(),
|
||||
"clippy".into(),
|
||||
"--".into(),
|
||||
"-D".into(),
|
||||
"warnings".into(),
|
||||
];
|
||||
let result = restore_double_dash_with_raw(&args, &raw);
|
||||
assert_eq!(result, vec!["--", "-D", "warnings"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_cargo_build_success() {
|
||||
let output = r#" Compiling libc v0.2.153
|
||||
|
||||
@@ -12,6 +12,18 @@ pub struct Config {
|
||||
pub filters: FilterConfig,
|
||||
#[serde(default)]
|
||||
pub tee: crate::tee::TeeConfig,
|
||||
#[serde(default)]
|
||||
pub telemetry: TelemetryConfig,
|
||||
#[serde(default)]
|
||||
pub hooks: HooksConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct HooksConfig {
|
||||
/// Commands to exclude from auto-rewrite (e.g. ["curl", "playwright"]).
|
||||
/// Survives `rtk init -g` re-runs since config.toml is user-owned.
|
||||
#[serde(default)]
|
||||
pub exclude_commands: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -71,6 +83,22 @@ impl Default for FilterConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct TelemetryConfig {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for TelemetryConfig {
|
||||
fn default() -> Self {
|
||||
Self { enabled: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> Result<Self> {
|
||||
let path = get_config_path()?;
|
||||
@@ -125,3 +153,35 @@ pub fn show_config() -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_hooks_config_deserialize() {
|
||||
let toml = r#"
|
||||
[hooks]
|
||||
exclude_commands = ["curl", "gh"]
|
||||
"#;
|
||||
let config: Config = toml::from_str(toml).expect("valid toml");
|
||||
assert_eq!(config.hooks.exclude_commands, vec!["curl", "gh"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hooks_config_default_empty() {
|
||||
let config = Config::default();
|
||||
assert!(config.hooks.exclude_commands.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_without_hooks_section_is_valid() {
|
||||
let toml = r#"
|
||||
[tracking]
|
||||
enabled = true
|
||||
history_days = 90
|
||||
"#;
|
||||
let config: Config = toml::from_str(toml).expect("valid toml");
|
||||
assert!(config.hooks.exclude_commands.is_empty());
|
||||
}
|
||||
}
|
||||
+16
-2
@@ -55,7 +55,10 @@ fn filter_curl_output(output: &str) -> String {
|
||||
&& (trimmed.ends_with('}') || trimmed.ends_with(']'))
|
||||
{
|
||||
if let Ok(schema) = json_cmd::filter_json_string(trimmed, 5) {
|
||||
return schema;
|
||||
// Only use schema if it's actually shorter than the original (#297)
|
||||
if schema.len() <= trimmed.len() {
|
||||
return schema;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +89,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_json() {
|
||||
let output = r#"{"name": "test", "count": 42, "items": [1, 2, 3]}"#;
|
||||
// Large JSON where schema is shorter than original — schema should be returned
|
||||
let output = r#"{"name": "a very long user name here", "count": 42, "items": [1, 2, 3], "description": "a very long description that takes up many characters in the original JSON payload", "status": "active", "url": "https://example.com/api/v1/users/123"}"#;
|
||||
let result = filter_curl_output(output);
|
||||
assert!(result.contains("name"));
|
||||
assert!(result.contains("string"));
|
||||
@@ -108,6 +112,16 @@ mod tests {
|
||||
assert!(result.contains("plain text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_json_small_returns_original() {
|
||||
// Small JSON where schema would be larger than original (issue #297)
|
||||
let output = r#"{"r2Ready":true,"status":"ok"}"#;
|
||||
let result = filter_curl_output(output);
|
||||
// Schema would be "{\n r2Ready: bool,\n status: string\n}" which is longer
|
||||
// Should return the original JSON unchanged
|
||||
assert_eq!(result.trim(), output.trim());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_long_output() {
|
||||
let lines: Vec<String> = (0..50).map(|i| format!("Line {}", i)).collect();
|
||||
|
||||
+352
-83
@@ -249,7 +249,7 @@ pub fn split_command_chain(cmd: &str) -> Vec<&str> {
|
||||
///
|
||||
/// Handles compound commands (`&&`, `||`, `;`) by rewriting each segment independently.
|
||||
/// For pipes (`|`), only rewrites the first command (the filter stays raw).
|
||||
pub fn rewrite_command(cmd: &str) -> Option<String> {
|
||||
pub fn rewrite_command(cmd: &str, excluded: &[String]) -> Option<String> {
|
||||
let trimmed = cmd.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
@@ -272,11 +272,11 @@ pub fn rewrite_command(cmd: &str) -> Option<String> {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
|
||||
rewrite_compound(trimmed)
|
||||
rewrite_compound(trimmed, excluded)
|
||||
}
|
||||
|
||||
/// Rewrite a compound command (with `&&`, `||`, `;`, `|`) by rewriting each segment.
|
||||
fn rewrite_compound(cmd: &str) -> Option<String> {
|
||||
fn rewrite_compound(cmd: &str, excluded: &[String]) -> Option<String> {
|
||||
let bytes = cmd.as_bytes();
|
||||
let len = bytes.len();
|
||||
let mut result = String::with_capacity(len + 32);
|
||||
@@ -301,7 +301,8 @@ fn rewrite_compound(cmd: &str) -> Option<String> {
|
||||
if i + 1 < len && bytes[i + 1] == b'|' {
|
||||
// `||` operator — rewrite left, continue
|
||||
let seg = cmd[seg_start..i].trim();
|
||||
let rewritten = rewrite_segment(seg).unwrap_or_else(|| seg.to_string());
|
||||
let rewritten =
|
||||
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
@@ -315,7 +316,8 @@ fn rewrite_compound(cmd: &str) -> 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).unwrap_or_else(|| seg.to_string());
|
||||
let rewritten =
|
||||
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
@@ -329,7 +331,7 @@ fn rewrite_compound(cmd: &str) -> Option<String> {
|
||||
b'&' if !in_single && !in_double && i + 1 < len && bytes[i + 1] == b'&' => {
|
||||
// `&&` operator — rewrite left, continue
|
||||
let seg = cmd[seg_start..i].trim();
|
||||
let rewritten = rewrite_segment(seg).unwrap_or_else(|| seg.to_string());
|
||||
let rewritten = rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
@@ -342,24 +344,32 @@ fn rewrite_compound(cmd: &str) -> Option<String> {
|
||||
seg_start = i;
|
||||
}
|
||||
b'&' if !in_single && !in_double => {
|
||||
// single `&` background execution operator
|
||||
let seg = cmd[seg_start..i].trim();
|
||||
let rewritten = rewrite_segment(seg).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
result.push_str(&rewritten);
|
||||
result.push_str(" & ");
|
||||
i += 1;
|
||||
while i < len && bytes[i] == b' ' {
|
||||
// #346: redirect detection — 2>&1 / >&2 (> before &) or &>file / &>>file (> after &)
|
||||
let is_redirect =
|
||||
(i > 0 && bytes[i - 1] == b'>') || (i + 1 < len && bytes[i + 1] == b'>');
|
||||
if is_redirect {
|
||||
i += 1;
|
||||
} else {
|
||||
// single `&` background execution operator
|
||||
let seg = cmd[seg_start..i].trim();
|
||||
let rewritten =
|
||||
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
result.push_str(&rewritten);
|
||||
result.push_str(" & ");
|
||||
i += 1;
|
||||
while i < len && bytes[i] == b' ' {
|
||||
i += 1;
|
||||
}
|
||||
seg_start = i;
|
||||
}
|
||||
seg_start = i;
|
||||
}
|
||||
b';' if !in_single && !in_double => {
|
||||
// `;` separator
|
||||
let seg = cmd[seg_start..i].trim();
|
||||
let rewritten = rewrite_segment(seg).unwrap_or_else(|| seg.to_string());
|
||||
let rewritten = rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
@@ -382,7 +392,7 @@ fn rewrite_compound(cmd: &str) -> Option<String> {
|
||||
|
||||
// Last (or only) segment
|
||||
let seg = cmd[seg_start..len].trim();
|
||||
let rewritten = rewrite_segment(seg).unwrap_or_else(|| seg.to_string());
|
||||
let rewritten = rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
@@ -424,7 +434,7 @@ fn rewrite_head_numeric(cmd: &str) -> Option<String> {
|
||||
/// Rewrite a single (non-compound) command segment.
|
||||
/// Returns `Some(rewritten)` if matched (including already-RTK pass-through).
|
||||
/// Returns `None` if no match (caller uses original segment).
|
||||
fn rewrite_segment(seg: &str) -> Option<String> {
|
||||
fn rewrite_segment(seg: &str, excluded: &[String]) -> Option<String> {
|
||||
let trimmed = seg.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
@@ -445,7 +455,14 @@ fn rewrite_segment(seg: &str) -> Option<String> {
|
||||
|
||||
// Use classify_command for correct ignore/prefix handling
|
||||
let rtk_equivalent = match classify_command(trimmed) {
|
||||
Classification::Supported { rtk_equivalent, .. } => rtk_equivalent,
|
||||
Classification::Supported { rtk_equivalent, .. } => {
|
||||
// Check if the base command is excluded from rewriting (#243)
|
||||
let base = trimmed.split_whitespace().next().unwrap_or("");
|
||||
if excluded.iter().any(|e| e == base) {
|
||||
return None;
|
||||
}
|
||||
rtk_equivalent
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
@@ -458,6 +475,23 @@ fn rewrite_segment(seg: &str) -> Option<String> {
|
||||
let env_prefix = &trimmed[..env_prefix_len];
|
||||
let cmd_clean = stripped_cow.trim();
|
||||
|
||||
// #345: RTK_DISABLED=1 in env prefix → skip rewrite entirely
|
||||
if env_prefix.contains("RTK_DISABLED=") {
|
||||
return None;
|
||||
}
|
||||
|
||||
// #196: gh with --json/--jq/--template produces structured output that
|
||||
// rtk gh would corrupt — skip rewrite so the caller gets raw JSON.
|
||||
if rule.rtk_cmd == "rtk gh" {
|
||||
let args_lower = cmd_clean.to_lowercase();
|
||||
if args_lower.contains("--json")
|
||||
|| args_lower.contains("--jq")
|
||||
|| args_lower.contains("--template")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
// Try each rewrite prefix (longest first) with word-boundary check
|
||||
for &prefix in rule.rewrite_prefixes {
|
||||
if let Some(rest) = strip_word_prefix(cmd_clean, prefix) {
|
||||
@@ -792,26 +826,32 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_git_status() {
|
||||
assert_eq!(rewrite_command("git status"), Some("rtk git status".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("git status", &[]),
|
||||
Some("rtk git status".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_git_log() {
|
||||
assert_eq!(
|
||||
rewrite_command("git log -10"),
|
||||
rewrite_command("git log -10", &[]),
|
||||
Some("rtk git log -10".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_cargo_test() {
|
||||
assert_eq!(rewrite_command("cargo test"), Some("rtk cargo test".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test", &[]),
|
||||
Some("rtk cargo test".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_compound_and() {
|
||||
assert_eq!(
|
||||
rewrite_command("git add . && cargo test"),
|
||||
rewrite_command("git add . && cargo test", &[]),
|
||||
Some("rtk git add . && rtk cargo test".into())
|
||||
);
|
||||
}
|
||||
@@ -819,7 +859,10 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_compound_three_segments() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo fmt --all && cargo clippy --all-targets && cargo test"),
|
||||
rewrite_command(
|
||||
"cargo fmt --all && cargo clippy --all-targets && cargo test",
|
||||
&[]
|
||||
),
|
||||
Some("rtk cargo fmt --all && rtk cargo clippy --all-targets && rtk cargo test".into())
|
||||
);
|
||||
}
|
||||
@@ -827,7 +870,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_already_rtk() {
|
||||
assert_eq!(
|
||||
rewrite_command("rtk git status"),
|
||||
rewrite_command("rtk git status", &[]),
|
||||
Some("rtk git status".into())
|
||||
);
|
||||
}
|
||||
@@ -835,7 +878,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_background_single_amp() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test & git status"),
|
||||
rewrite_command("cargo test & git status", &[]),
|
||||
Some("rtk cargo test & rtk git status".into())
|
||||
);
|
||||
}
|
||||
@@ -843,7 +886,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_background_unsupported_right() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test & terraform plan"),
|
||||
rewrite_command("cargo test & terraform plan", &[]),
|
||||
Some("rtk cargo test & terraform plan".into())
|
||||
);
|
||||
}
|
||||
@@ -852,25 +895,25 @@ mod tests {
|
||||
fn test_rewrite_background_does_not_affect_double_amp() {
|
||||
// `&&` must still work after adding `&` support
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test && git status"),
|
||||
rewrite_command("cargo test && git status", &[]),
|
||||
Some("rtk cargo test && rtk git status".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_unsupported_returns_none() {
|
||||
assert_eq!(rewrite_command("terraform plan"), None);
|
||||
assert_eq!(rewrite_command("terraform plan", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_ignored_cd() {
|
||||
assert_eq!(rewrite_command("cd /tmp"), None);
|
||||
assert_eq!(rewrite_command("cd /tmp", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_with_env_prefix() {
|
||||
assert_eq!(
|
||||
rewrite_command("GIT_SSH_COMMAND=ssh git push"),
|
||||
rewrite_command("GIT_SSH_COMMAND=ssh git push", &[]),
|
||||
Some("GIT_SSH_COMMAND=ssh rtk git push".into())
|
||||
);
|
||||
}
|
||||
@@ -878,7 +921,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_npx_tsc() {
|
||||
assert_eq!(
|
||||
rewrite_command("npx tsc --noEmit"),
|
||||
rewrite_command("npx tsc --noEmit", &[]),
|
||||
Some("rtk tsc --noEmit".into())
|
||||
);
|
||||
}
|
||||
@@ -886,7 +929,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_pnpm_tsc() {
|
||||
assert_eq!(
|
||||
rewrite_command("pnpm tsc --noEmit"),
|
||||
rewrite_command("pnpm tsc --noEmit", &[]),
|
||||
Some("rtk tsc --noEmit".into())
|
||||
);
|
||||
}
|
||||
@@ -894,7 +937,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_cat_file() {
|
||||
assert_eq!(
|
||||
rewrite_command("cat src/main.rs"),
|
||||
rewrite_command("cat src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs".into())
|
||||
);
|
||||
}
|
||||
@@ -902,7 +945,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_rg_pattern() {
|
||||
assert_eq!(
|
||||
rewrite_command("rg \"fn main\""),
|
||||
rewrite_command("rg \"fn main\"", &[]),
|
||||
Some("rtk grep \"fn main\"".into())
|
||||
);
|
||||
}
|
||||
@@ -910,7 +953,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_npx_playwright() {
|
||||
assert_eq!(
|
||||
rewrite_command("npx playwright test"),
|
||||
rewrite_command("npx playwright test", &[]),
|
||||
Some("rtk playwright test".into())
|
||||
);
|
||||
}
|
||||
@@ -918,7 +961,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_next_build() {
|
||||
assert_eq!(
|
||||
rewrite_command("next build --turbo"),
|
||||
rewrite_command("next build --turbo", &[]),
|
||||
Some("rtk next --turbo".into())
|
||||
);
|
||||
}
|
||||
@@ -927,38 +970,121 @@ mod tests {
|
||||
fn test_rewrite_pipe_first_only() {
|
||||
// After a pipe, the filter command stays raw
|
||||
assert_eq!(
|
||||
rewrite_command("git log -10 | grep feat"),
|
||||
rewrite_command("git log -10 | grep feat", &[]),
|
||||
Some("rtk git log -10 | grep feat".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_heredoc_returns_none() {
|
||||
assert_eq!(rewrite_command("cat <<'EOF'\nfoo\nEOF"), None);
|
||||
assert_eq!(rewrite_command("cat <<'EOF'\nfoo\nEOF", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_empty_returns_none() {
|
||||
assert_eq!(rewrite_command(""), None);
|
||||
assert_eq!(rewrite_command(" "), None);
|
||||
assert_eq!(rewrite_command("", &[]), None);
|
||||
assert_eq!(rewrite_command(" ", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_mixed_compound_partial() {
|
||||
// First segment already RTK, second gets rewritten
|
||||
assert_eq!(
|
||||
rewrite_command("rtk git add . && cargo test"),
|
||||
rewrite_command("rtk git add . && cargo test", &[]),
|
||||
Some("rtk git add . && rtk cargo test".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- #345: RTK_DISABLED ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_rtk_disabled_curl() {
|
||||
assert_eq!(
|
||||
rewrite_command("RTK_DISABLED=1 curl https://example.com", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_rtk_disabled_git_status() {
|
||||
assert_eq!(rewrite_command("RTK_DISABLED=1 git status", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_rtk_disabled_multi_env() {
|
||||
assert_eq!(
|
||||
rewrite_command("FOO=1 RTK_DISABLED=1 git status", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_non_rtk_disabled_env_still_rewrites() {
|
||||
assert_eq!(
|
||||
rewrite_command("SOME_VAR=1 git status", &[]),
|
||||
Some("SOME_VAR=1 rtk git status".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- #346: 2>&1 and &> redirect detection ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_redirect_2_gt_amp_1_with_pipe() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test 2>&1 | head", &[]),
|
||||
Some("rtk cargo test 2>&1 | head".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_redirect_2_gt_amp_1_trailing() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test 2>&1", &[]),
|
||||
Some("rtk cargo test 2>&1".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_redirect_plain_2_devnull() {
|
||||
// 2>/dev/null has no `&`, never broken — non-regression
|
||||
assert_eq!(
|
||||
rewrite_command("git status 2>/dev/null", &[]),
|
||||
Some("rtk git status 2>/dev/null".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_redirect_2_gt_amp_1_with_and() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test 2>&1 && echo done", &[]),
|
||||
Some("rtk cargo test 2>&1 && echo done".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_redirect_amp_gt_devnull() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test &>/dev/null", &[]),
|
||||
Some("rtk cargo test &>/dev/null".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_background_amp_non_regression() {
|
||||
// background `&` must still work after redirect fix
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test & git status", &[]),
|
||||
Some("rtk cargo test & rtk git status".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- P0.2: head -N rewrite ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_numeric_flag() {
|
||||
// head -20 file → rtk read file --max-lines 20 (not rtk read -20 file)
|
||||
assert_eq!(
|
||||
rewrite_command("head -20 src/main.rs"),
|
||||
rewrite_command("head -20 src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs --max-lines 20".into())
|
||||
);
|
||||
}
|
||||
@@ -966,7 +1092,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_head_lines_long_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command("head --lines=50 src/lib.rs"),
|
||||
rewrite_command("head --lines=50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --max-lines 50".into())
|
||||
);
|
||||
}
|
||||
@@ -975,7 +1101,7 @@ mod tests {
|
||||
fn test_rewrite_head_no_flag_still_rewrites() {
|
||||
// plain `head file` → `rtk read file` (no numeric flag)
|
||||
assert_eq!(
|
||||
rewrite_command("head src/main.rs"),
|
||||
rewrite_command("head src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs".into())
|
||||
);
|
||||
}
|
||||
@@ -983,7 +1109,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_head_other_flag_skipped() {
|
||||
// head -c 100 file: unsupported flag, skip rewriting
|
||||
assert_eq!(rewrite_command("head -c 100 src/main.rs"), None);
|
||||
assert_eq!(rewrite_command("head -c 100 src/main.rs", &[]), None);
|
||||
}
|
||||
|
||||
// --- New registry entries ---
|
||||
@@ -1089,13 +1215,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tree() {
|
||||
assert_eq!(rewrite_command("tree src/"), Some("rtk tree src/".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("tree src/", &[]),
|
||||
Some("rtk tree src/".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_diff() {
|
||||
assert_eq!(
|
||||
rewrite_command("diff file1.txt file2.txt"),
|
||||
rewrite_command("diff file1.txt file2.txt", &[]),
|
||||
Some("rtk diff file1.txt file2.txt".into())
|
||||
);
|
||||
}
|
||||
@@ -1103,7 +1232,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_gh_release() {
|
||||
assert_eq!(
|
||||
rewrite_command("gh release list"),
|
||||
rewrite_command("gh release list", &[]),
|
||||
Some("rtk gh release list".into())
|
||||
);
|
||||
}
|
||||
@@ -1111,7 +1240,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_cargo_install() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo install rtk"),
|
||||
rewrite_command("cargo install rtk", &[]),
|
||||
Some("rtk cargo install rtk".into())
|
||||
);
|
||||
}
|
||||
@@ -1119,7 +1248,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_kubectl_describe() {
|
||||
assert_eq!(
|
||||
rewrite_command("kubectl describe pod mypod"),
|
||||
rewrite_command("kubectl describe pod mypod", &[]),
|
||||
Some("rtk kubectl describe pod mypod".into())
|
||||
);
|
||||
}
|
||||
@@ -1127,11 +1256,55 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_docker_run() {
|
||||
assert_eq!(
|
||||
rewrite_command("docker run --rm ubuntu bash"),
|
||||
rewrite_command("docker run --rm ubuntu bash", &[]),
|
||||
Some("rtk docker run --rm ubuntu bash".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- #336: docker compose supported subcommands rewritten, unsupported skipped ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_docker_compose_ps() {
|
||||
assert_eq!(
|
||||
rewrite_command("docker compose ps", &[]),
|
||||
Some("rtk docker compose ps".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_docker_compose_logs() {
|
||||
assert_eq!(
|
||||
rewrite_command("docker compose logs web", &[]),
|
||||
Some("rtk docker compose logs web".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_docker_compose_build() {
|
||||
assert_eq!(
|
||||
rewrite_command("docker compose build", &[]),
|
||||
Some("rtk docker compose build".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_docker_compose_up_skipped() {
|
||||
assert_eq!(rewrite_command("docker compose up -d", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_docker_compose_down_skipped() {
|
||||
assert_eq!(rewrite_command("docker compose down", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_docker_compose_config_skipped() {
|
||||
assert_eq!(
|
||||
rewrite_command("docker compose -f foo.yaml config --services", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// --- AWS / psql (PR #216) ---
|
||||
|
||||
#[test]
|
||||
@@ -1180,13 +1353,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_aws() {
|
||||
assert_eq!(rewrite_command("aws s3 ls"), Some("rtk aws s3 ls".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("aws s3 ls", &[]),
|
||||
Some("rtk aws s3 ls".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_aws_ec2() {
|
||||
assert_eq!(
|
||||
rewrite_command("aws ec2 describe-instances --region us-east-1"),
|
||||
rewrite_command("aws ec2 describe-instances --region us-east-1", &[]),
|
||||
Some("rtk aws ec2 describe-instances --region us-east-1".into())
|
||||
);
|
||||
}
|
||||
@@ -1194,7 +1370,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_psql() {
|
||||
assert_eq!(
|
||||
rewrite_command("psql -U postgres -d mydb"),
|
||||
rewrite_command("psql -U postgres -d mydb", &[]),
|
||||
Some("rtk psql -U postgres -d mydb".into())
|
||||
);
|
||||
}
|
||||
@@ -1270,7 +1446,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_ruff_check() {
|
||||
assert_eq!(
|
||||
rewrite_command("ruff check ."),
|
||||
rewrite_command("ruff check .", &[]),
|
||||
Some("rtk ruff check .".into())
|
||||
);
|
||||
}
|
||||
@@ -1278,7 +1454,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_ruff_format() {
|
||||
assert_eq!(
|
||||
rewrite_command("ruff format src/"),
|
||||
rewrite_command("ruff format src/", &[]),
|
||||
Some("rtk ruff format src/".into())
|
||||
);
|
||||
}
|
||||
@@ -1286,7 +1462,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_pytest() {
|
||||
assert_eq!(
|
||||
rewrite_command("pytest tests/"),
|
||||
rewrite_command("pytest tests/", &[]),
|
||||
Some("rtk pytest tests/".into())
|
||||
);
|
||||
}
|
||||
@@ -1294,27 +1470,33 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_python_m_pytest() {
|
||||
assert_eq!(
|
||||
rewrite_command("python -m pytest -x tests/"),
|
||||
rewrite_command("python -m pytest -x tests/", &[]),
|
||||
Some("rtk pytest -x tests/".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pip_list() {
|
||||
assert_eq!(rewrite_command("pip list"), Some("rtk pip list".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("pip list", &[]),
|
||||
Some("rtk pip list".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pip_outdated() {
|
||||
assert_eq!(
|
||||
rewrite_command("pip outdated"),
|
||||
rewrite_command("pip outdated", &[]),
|
||||
Some("rtk pip outdated".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_uv_pip_list() {
|
||||
assert_eq!(rewrite_command("uv pip list"), Some("rtk pip list".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("uv pip list", &[]),
|
||||
Some("rtk pip list".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- Go tooling ---
|
||||
@@ -1366,7 +1548,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_go_test() {
|
||||
assert_eq!(
|
||||
rewrite_command("go test ./..."),
|
||||
rewrite_command("go test ./...", &[]),
|
||||
Some("rtk go test ./...".into())
|
||||
);
|
||||
}
|
||||
@@ -1374,7 +1556,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_go_build() {
|
||||
assert_eq!(
|
||||
rewrite_command("go build ./..."),
|
||||
rewrite_command("go build ./...", &[]),
|
||||
Some("rtk go build ./...".into())
|
||||
);
|
||||
}
|
||||
@@ -1382,7 +1564,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_go_vet() {
|
||||
assert_eq!(
|
||||
rewrite_command("go vet ./..."),
|
||||
rewrite_command("go vet ./...", &[]),
|
||||
Some("rtk go vet ./...".into())
|
||||
);
|
||||
}
|
||||
@@ -1390,7 +1572,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_golangci_lint() {
|
||||
assert_eq!(
|
||||
rewrite_command("golangci-lint run ./..."),
|
||||
rewrite_command("golangci-lint run ./...", &[]),
|
||||
Some("rtk golangci-lint run ./...".into())
|
||||
);
|
||||
}
|
||||
@@ -1410,13 +1592,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_vitest() {
|
||||
assert_eq!(rewrite_command("vitest run"), Some("rtk vitest run".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("vitest run", &[]),
|
||||
Some("rtk vitest run".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pnpm_vitest() {
|
||||
assert_eq!(
|
||||
rewrite_command("pnpm vitest run"),
|
||||
rewrite_command("pnpm vitest run", &[]),
|
||||
Some("rtk vitest run".into())
|
||||
);
|
||||
}
|
||||
@@ -1435,7 +1620,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_prisma() {
|
||||
assert_eq!(
|
||||
rewrite_command("npx prisma migrate dev"),
|
||||
rewrite_command("npx prisma migrate dev", &[]),
|
||||
Some("rtk prisma migrate dev".into())
|
||||
);
|
||||
}
|
||||
@@ -1443,14 +1628,17 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_prettier() {
|
||||
assert_eq!(
|
||||
rewrite_command("npx prettier --check src/"),
|
||||
rewrite_command("npx prettier --check src/", &[]),
|
||||
Some("rtk prettier --check src/".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pnpm_list() {
|
||||
assert_eq!(rewrite_command("pnpm list"), Some("rtk pnpm list".into()));
|
||||
assert_eq!(
|
||||
rewrite_command("pnpm list", &[]),
|
||||
Some("rtk pnpm list".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- Compound operator edge cases ---
|
||||
@@ -1459,7 +1647,7 @@ mod tests {
|
||||
fn test_rewrite_compound_or() {
|
||||
// `||` fallback: left rewritten, right rewritten
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test || cargo build"),
|
||||
rewrite_command("cargo test || cargo build", &[]),
|
||||
Some("rtk cargo test || rtk cargo build".into())
|
||||
);
|
||||
}
|
||||
@@ -1467,7 +1655,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_compound_semicolon() {
|
||||
assert_eq!(
|
||||
rewrite_command("git status; cargo test"),
|
||||
rewrite_command("git status; cargo test", &[]),
|
||||
Some("rtk git status; rtk cargo test".into())
|
||||
);
|
||||
}
|
||||
@@ -1476,7 +1664,7 @@ mod tests {
|
||||
fn test_rewrite_compound_pipe_raw_filter() {
|
||||
// Pipe: rewrite first segment only, pass through rest unchanged
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test | grep FAILED"),
|
||||
rewrite_command("cargo test | grep FAILED", &[]),
|
||||
Some("rtk cargo test | grep FAILED".into())
|
||||
);
|
||||
}
|
||||
@@ -1484,7 +1672,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_compound_pipe_git_grep() {
|
||||
assert_eq!(
|
||||
rewrite_command("git log -10 | grep feat"),
|
||||
rewrite_command("git log -10 | grep feat", &[]),
|
||||
Some("rtk git log -10 | grep feat".into())
|
||||
);
|
||||
}
|
||||
@@ -1492,7 +1680,10 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_compound_four_segments() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo fmt --all && cargo clippy && cargo test && git status"),
|
||||
rewrite_command(
|
||||
"cargo fmt --all && cargo clippy && cargo test && git status",
|
||||
&[]
|
||||
),
|
||||
Some(
|
||||
"rtk cargo fmt --all && rtk cargo clippy && rtk cargo test && rtk git status"
|
||||
.into()
|
||||
@@ -1504,7 +1695,7 @@ mod tests {
|
||||
fn test_rewrite_compound_mixed_supported_unsupported() {
|
||||
// unsupported segments stay raw
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test && terraform plan"),
|
||||
rewrite_command("cargo test && terraform plan", &[]),
|
||||
Some("rtk cargo test && terraform plan".into())
|
||||
);
|
||||
}
|
||||
@@ -1512,7 +1703,10 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_compound_all_unsupported_returns_none() {
|
||||
// No rewrite at all: returns None
|
||||
assert_eq!(rewrite_command("terraform plan && terraform apply"), None);
|
||||
assert_eq!(
|
||||
rewrite_command("terraform plan && terraform apply", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// --- sudo / env prefix + rewrite ---
|
||||
@@ -1520,7 +1714,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_sudo_docker() {
|
||||
assert_eq!(
|
||||
rewrite_command("sudo docker ps"),
|
||||
rewrite_command("sudo docker ps", &[]),
|
||||
Some("sudo rtk docker ps".into())
|
||||
);
|
||||
}
|
||||
@@ -1528,7 +1722,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_env_var_prefix() {
|
||||
assert_eq!(
|
||||
rewrite_command("GIT_SSH_COMMAND=ssh git push origin main"),
|
||||
rewrite_command("GIT_SSH_COMMAND=ssh git push origin main", &[]),
|
||||
Some("GIT_SSH_COMMAND=ssh rtk git push origin main".into())
|
||||
);
|
||||
}
|
||||
@@ -1538,7 +1732,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_find_with_flags() {
|
||||
assert_eq!(
|
||||
rewrite_command("find . -name '*.rs' -type f"),
|
||||
rewrite_command("find . -name '*.rs' -type f", &[]),
|
||||
Some("rtk find . -name '*.rs' -type f".into())
|
||||
);
|
||||
}
|
||||
@@ -1576,6 +1770,42 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// --- exclude_commands (#243) ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_excludes_curl() {
|
||||
let excluded = vec!["curl".to_string()];
|
||||
assert_eq!(
|
||||
rewrite_command("curl https://api.example.com/health", &excluded),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_exclude_does_not_affect_other_commands() {
|
||||
let excluded = vec!["curl".to_string()];
|
||||
assert_eq!(
|
||||
rewrite_command("git status", &excluded),
|
||||
Some("rtk git status".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_empty_excludes_rewrites_curl() {
|
||||
let excluded: Vec<String> = vec![];
|
||||
assert!(rewrite_command("curl https://api.example.com", &excluded).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_compound_partial_exclude() {
|
||||
// curl excluded but git still rewrites
|
||||
let excluded = vec!["curl".to_string()];
|
||||
assert_eq!(
|
||||
rewrite_command("git status && curl https://api.example.com", &excluded),
|
||||
Some("rtk git status && curl https://api.example.com".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- Every PATTERN compiles to a valid Regex ---
|
||||
|
||||
#[test]
|
||||
@@ -1588,4 +1818,43 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- #196: gh --json/--jq/--template passthrough ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_gh_json_skipped() {
|
||||
assert_eq!(rewrite_command("gh pr list --json number,title", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_gh_jq_skipped() {
|
||||
assert_eq!(
|
||||
rewrite_command("gh pr list --json number --jq '.[].number'", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_gh_template_skipped() {
|
||||
assert_eq!(
|
||||
rewrite_command("gh pr view 42 --template '{{.title}}'", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_gh_api_json_skipped() {
|
||||
assert_eq!(
|
||||
rewrite_command("gh api repos/owner/repo --jq '.name'", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_gh_without_json_still_works() {
|
||||
assert_eq!(
|
||||
rewrite_command("gh pr list", &[]),
|
||||
Some("rtk gh pr list".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ pub const PATTERNS: &[&str] = &[
|
||||
r"^(pnpm\s+|npx\s+)?(vitest|jest|test)(\s|$)",
|
||||
r"^(npx\s+|pnpm\s+)?playwright",
|
||||
r"^(npx\s+|pnpm\s+)?prisma",
|
||||
r"^docker\s+(ps|images|logs|run|exec|build)",
|
||||
r"^docker\s+(ps|images|logs|run|exec|build|compose\s+(ps|logs|build))",
|
||||
r"^kubectl\s+(get|logs|describe|apply)",
|
||||
r"^tree(\s|$)",
|
||||
r"^diff\s+",
|
||||
|
||||
+164
-37
@@ -108,8 +108,58 @@ fn filter_markdown_segment(text: &str) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// Check if args contain --json flag (user wants specific JSON fields, not RTK filtering)
|
||||
fn has_json_flag(args: &[String]) -> bool {
|
||||
args.iter().any(|a| a == "--json")
|
||||
}
|
||||
|
||||
/// Extract a positional identifier (PR/issue number) from args, returning it
|
||||
/// separately from the remaining extra flags (like -R, --repo, etc.).
|
||||
/// Handles both `view 123 -R owner/repo` and `view -R owner/repo 123`.
|
||||
fn extract_identifier_and_extra_args(args: &[String]) -> Option<(String, Vec<String>)> {
|
||||
if args.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Known gh flags that take a value — skip these and their values
|
||||
let flags_with_value = ["-R", "--repo", "-q", "--jq", "-t", "--template"];
|
||||
let mut identifier = None;
|
||||
let mut extra = Vec::new();
|
||||
let mut skip_next = false;
|
||||
|
||||
for arg in args {
|
||||
if skip_next {
|
||||
extra.push(arg.clone());
|
||||
skip_next = false;
|
||||
continue;
|
||||
}
|
||||
if flags_with_value.contains(&arg.as_str()) {
|
||||
extra.push(arg.clone());
|
||||
skip_next = true;
|
||||
continue;
|
||||
}
|
||||
if arg.starts_with('-') {
|
||||
extra.push(arg.clone());
|
||||
continue;
|
||||
}
|
||||
// First non-flag arg is the identifier (number/URL)
|
||||
if identifier.is_none() {
|
||||
identifier = Some(arg.clone());
|
||||
} else {
|
||||
extra.push(arg.clone());
|
||||
}
|
||||
}
|
||||
|
||||
identifier.map(|id| (id, extra))
|
||||
}
|
||||
|
||||
/// Run a gh command with token-optimized output
|
||||
pub fn run(subcommand: &str, args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
// When user explicitly passes --json, they want raw gh JSON output, not RTK filtering
|
||||
if has_json_flag(args) {
|
||||
return run_passthrough("gh", subcommand, args);
|
||||
}
|
||||
|
||||
match subcommand {
|
||||
"pr" => run_pr(args, verbose, ultra_compact),
|
||||
"issue" => run_issue(args, verbose, ultra_compact),
|
||||
@@ -136,8 +186,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[1..], verbose),
|
||||
"edit" => pr_action("edited", &args[1..], verbose),
|
||||
"comment" => pr_action("commented", &args, verbose),
|
||||
"edit" => pr_action("edited", &args, verbose),
|
||||
_ => run_passthrough("gh", "pr", args),
|
||||
}
|
||||
}
|
||||
@@ -229,20 +279,22 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if args.is_empty() {
|
||||
return Err(anyhow::anyhow!("PR number required"));
|
||||
}
|
||||
|
||||
let pr_number = &args[0];
|
||||
let (pr_number, extra_args) = match extract_identifier_and_extra_args(args) {
|
||||
Some(result) => result,
|
||||
None => return Err(anyhow::anyhow!("PR number required")),
|
||||
};
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args([
|
||||
"pr",
|
||||
"view",
|
||||
pr_number,
|
||||
&pr_number,
|
||||
"--json",
|
||||
"number,title,state,author,body,url,mergeable,reviews,statusCheckRollup",
|
||||
]);
|
||||
for arg in &extra_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run gh pr view")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
@@ -398,14 +450,16 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if args.is_empty() {
|
||||
return Err(anyhow::anyhow!("PR number required"));
|
||||
}
|
||||
|
||||
let pr_number = &args[0];
|
||||
let (pr_number, extra_args) = match extract_identifier_and_extra_args(args) {
|
||||
Some(result) => result,
|
||||
None => return Err(anyhow::anyhow!("PR number required")),
|
||||
};
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args(["pr", "checks", pr_number]);
|
||||
cmd.args(["pr", "checks", &pr_number]);
|
||||
for arg in &extra_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run gh pr checks")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
@@ -607,20 +661,22 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
|
||||
fn view_issue(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if args.is_empty() {
|
||||
return Err(anyhow::anyhow!("Issue number required"));
|
||||
}
|
||||
|
||||
let issue_number = &args[0];
|
||||
let (issue_number, extra_args) = match extract_identifier_and_extra_args(args) {
|
||||
Some(result) => result,
|
||||
None => return Err(anyhow::anyhow!("Issue number required")),
|
||||
};
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args([
|
||||
"issue",
|
||||
"view",
|
||||
issue_number,
|
||||
&issue_number,
|
||||
"--json",
|
||||
"number,title,state,author,body,url",
|
||||
]);
|
||||
for arg in &extra_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run gh issue view")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
@@ -796,22 +852,23 @@ fn should_passthrough_run_view(extra_args: &[String]) -> bool {
|
||||
}
|
||||
|
||||
fn view_run(args: &[String], _verbose: u8) -> Result<()> {
|
||||
if args.is_empty() {
|
||||
return Err(anyhow::anyhow!("Run ID required"));
|
||||
}
|
||||
|
||||
let run_id = &args[0];
|
||||
let extra_args = &args[1..];
|
||||
let (run_id, extra_args) = match extract_identifier_and_extra_args(args) {
|
||||
Some(result) => result,
|
||||
None => return Err(anyhow::anyhow!("Run ID required")),
|
||||
};
|
||||
|
||||
// Pass through when user requests logs or JSON — the filter would strip them
|
||||
if should_passthrough_run_view(extra_args) {
|
||||
return run_passthrough_with_extra("gh", &["run", "view", run_id], extra_args);
|
||||
if should_passthrough_run_view(&extra_args) {
|
||||
return run_passthrough_with_extra("gh", &["run", "view", &run_id], &extra_args);
|
||||
}
|
||||
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args(["run", "view", run_id]);
|
||||
cmd.args(["run", "view", &run_id]);
|
||||
for arg in &extra_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run gh run view")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
@@ -1070,23 +1127,24 @@ fn pr_diff(args: &[String], _verbose: u8) -> Result<()> {
|
||||
/// Generic PR action handler for comment/edit
|
||||
fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
let subcmd = &args[0];
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args(["pr", action]);
|
||||
cmd.arg("pr");
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let output = cmd
|
||||
.output()
|
||||
.context(format!("Failed to run gh pr {}", action))?;
|
||||
.context(format!("Failed to run gh pr {}", subcmd))?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
|
||||
timer.track(
|
||||
&format!("gh pr {}", action),
|
||||
&format!("rtk gh pr {}", action),
|
||||
&format!("gh pr {}", subcmd),
|
||||
&format!("rtk gh pr {}", subcmd),
|
||||
&stderr,
|
||||
&stderr,
|
||||
);
|
||||
@@ -1094,8 +1152,8 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
// Extract PR number from args
|
||||
let pr_num = args
|
||||
// Extract PR number from args (skip args[0] which is the subcommand)
|
||||
let pr_num = args[1..]
|
||||
.iter()
|
||||
.find(|a| !a.starts_with('-'))
|
||||
.map(|s| format!("#{}", s))
|
||||
@@ -1112,8 +1170,8 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
|
||||
};
|
||||
|
||||
timer.track(
|
||||
&format!("gh pr {}", action),
|
||||
&format!("rtk gh pr {}", action),
|
||||
&format!("gh pr {}", subcmd),
|
||||
&format!("rtk gh pr {}", subcmd),
|
||||
&raw,
|
||||
&filtered,
|
||||
);
|
||||
@@ -1277,6 +1335,75 @@ mod tests {
|
||||
assert_eq!(result, "ok edited #42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_json_flag_present() {
|
||||
assert!(has_json_flag(&[
|
||||
"view".into(),
|
||||
"--json".into(),
|
||||
"number,url".into()
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_json_flag_absent() {
|
||||
assert!(!has_json_flag(&["view".into(), "42".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_simple() {
|
||||
let args: Vec<String> = vec!["123".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "123");
|
||||
assert!(extra.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_repo_flag_after() {
|
||||
// gh issue view 185 -R rtk-ai/rtk
|
||||
let args: Vec<String> = vec!["185".into(), "-R".into(), "rtk-ai/rtk".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "185");
|
||||
assert_eq!(extra, vec!["-R", "rtk-ai/rtk"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_repo_flag_before() {
|
||||
// gh issue view -R rtk-ai/rtk 185
|
||||
let args: Vec<String> = vec!["-R".into(), "rtk-ai/rtk".into(), "185".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "185");
|
||||
assert_eq!(extra, vec!["-R", "rtk-ai/rtk"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_long_repo_flag() {
|
||||
let args: Vec<String> = vec!["42".into(), "--repo".into(), "owner/repo".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "42");
|
||||
assert_eq!(extra, vec!["--repo", "owner/repo"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_empty() {
|
||||
let args: Vec<String> = vec![];
|
||||
assert!(extract_identifier_and_extra_args(&args).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_only_flags() {
|
||||
// No positional identifier, only flags
|
||||
let args: Vec<String> = vec!["-R".into(), "rtk-ai/rtk".into()];
|
||||
assert!(extract_identifier_and_extra_args(&args).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_web_flag() {
|
||||
let args: Vec<String> = vec!["123".into(), "--web".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "123");
|
||||
assert_eq!(extra, vec!["--web"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_view_passthrough_log_failed() {
|
||||
assert!(should_passthrough_run_view(&["--log-failed".into()]));
|
||||
|
||||
+39
-41
@@ -10,7 +10,7 @@ pub enum GitCommand {
|
||||
Status,
|
||||
Show,
|
||||
Add,
|
||||
Commit { messages: Vec<String> },
|
||||
Commit,
|
||||
Push,
|
||||
Pull,
|
||||
Branch,
|
||||
@@ -42,7 +42,7 @@ pub fn run(
|
||||
GitCommand::Status => run_status(args, verbose, global_args),
|
||||
GitCommand::Show => run_show(args, max_lines, verbose, global_args),
|
||||
GitCommand::Add => run_add(args, verbose, global_args),
|
||||
GitCommand::Commit { messages } => run_commit(&messages, verbose, global_args),
|
||||
GitCommand::Commit => run_commit(args, verbose, global_args),
|
||||
GitCommand::Push => run_push(args, verbose, global_args),
|
||||
GitCommand::Pull => run_pull(args, verbose, global_args),
|
||||
GitCommand::Branch => run_branch(args, verbose, global_args),
|
||||
@@ -703,30 +703,25 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_commit_command(messages: &[String], global_args: &[String]) -> Command {
|
||||
fn build_commit_command(args: &[String], global_args: &[String]) -> Command {
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.arg("commit");
|
||||
for msg in messages {
|
||||
cmd.args(["-m", msg]);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn run_commit(messages: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
|
||||
fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let original_cmd = messages
|
||||
.iter()
|
||||
.map(|m| format!("-m \"{}\"", m))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let original_cmd = format!("git commit {}", original_cmd);
|
||||
let original_cmd = format!("git commit {}", args.join(" "));
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("{}", original_cmd);
|
||||
}
|
||||
|
||||
let output = build_commit_command(messages, global_args)
|
||||
let output = build_commit_command(args, global_args)
|
||||
.output()
|
||||
.context("Failed to run git commit")?;
|
||||
|
||||
@@ -1721,28 +1716,30 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
|
||||
#[test]
|
||||
fn test_commit_single_message() {
|
||||
let messages = vec!["fix: typo".to_string()];
|
||||
let cmd = build_commit_command(&messages, &[]);
|
||||
let args: Vec<_> = cmd
|
||||
let args = vec!["-m".to_string(), "fix: typo".to_string()];
|
||||
let cmd = build_commit_command(&args, &[]);
|
||||
let cmd_args: Vec<_> = cmd
|
||||
.get_args()
|
||||
.map(|a| a.to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(args, vec!["commit", "-m", "fix: typo"]);
|
||||
assert_eq!(cmd_args, vec!["commit", "-m", "fix: typo"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_commit_multiple_messages() {
|
||||
let messages = vec![
|
||||
let args = vec![
|
||||
"-m".to_string(),
|
||||
"feat: add multi-paragraph support".to_string(),
|
||||
"-m".to_string(),
|
||||
"This allows git commit -m \"title\" -m \"body\".".to_string(),
|
||||
];
|
||||
let cmd = build_commit_command(&messages, &[]);
|
||||
let args: Vec<_> = cmd
|
||||
let cmd = build_commit_command(&args, &[]);
|
||||
let cmd_args: Vec<_> = cmd
|
||||
.get_args()
|
||||
.map(|a| a.to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
args,
|
||||
cmd_args,
|
||||
vec![
|
||||
"commit",
|
||||
"-m",
|
||||
@@ -1753,29 +1750,30 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
);
|
||||
}
|
||||
|
||||
// #327: git commit -am "msg" must pass -am through to git
|
||||
#[test]
|
||||
fn test_commit_three_messages() {
|
||||
let messages = vec![
|
||||
"title".to_string(),
|
||||
"body".to_string(),
|
||||
"footer: refs #202".to_string(),
|
||||
];
|
||||
let cmd = build_commit_command(&messages, &[]);
|
||||
let args: Vec<_> = cmd
|
||||
fn test_commit_am_flag() {
|
||||
let args = vec!["-am".to_string(), "quick fix".to_string()];
|
||||
let cmd = build_commit_command(&args, &[]);
|
||||
let cmd_args: Vec<_> = cmd
|
||||
.get_args()
|
||||
.map(|a| a.to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"commit",
|
||||
"-m",
|
||||
"title",
|
||||
"-m",
|
||||
"body",
|
||||
"-m",
|
||||
"footer: refs #202"
|
||||
]
|
||||
);
|
||||
assert_eq!(cmd_args, vec!["commit", "-am", "quick fix"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_commit_amend() {
|
||||
let args = vec![
|
||||
"--amend".to_string(),
|
||||
"-m".to_string(),
|
||||
"new msg".to_string(),
|
||||
];
|
||||
let cmd = build_commit_command(&args, &[]);
|
||||
let cmd_args: Vec<_> = cmd
|
||||
.get_args()
|
||||
.map(|a| a.to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(cmd_args, vec!["commit", "--amend", "-m", "new msg"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
const CURRENT_HOOK_VERSION: u8 = 2;
|
||||
const WARN_INTERVAL_SECS: u64 = 24 * 3600;
|
||||
|
||||
/// Check if the installed hook is outdated, warn once per day.
|
||||
pub fn maybe_warn() {
|
||||
// Don't block startup — fail silently on any error
|
||||
let _ = check_and_warn();
|
||||
}
|
||||
|
||||
fn check_and_warn() -> Option<()> {
|
||||
let hook_path = hook_installed_path()?;
|
||||
let content = std::fs::read_to_string(&hook_path).ok()?;
|
||||
|
||||
let installed_version = parse_hook_version(&content);
|
||||
|
||||
if installed_version >= CURRENT_HOOK_VERSION {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// Rate limit: warn once per day
|
||||
let marker = warn_marker_path()?;
|
||||
if let Ok(meta) = std::fs::metadata(&marker) {
|
||||
if let Ok(elapsed) = meta.modified().ok()?.elapsed() {
|
||||
if elapsed.as_secs() < WARN_INTERVAL_SECS {
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Touch marker
|
||||
let _ = std::fs::create_dir_all(marker.parent()?);
|
||||
let _ = std::fs::write(&marker, b"");
|
||||
|
||||
eprintln!("[rtk] Hook outdated — run `rtk init -g` to update");
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub fn parse_hook_version(content: &str) -> u8 {
|
||||
for line in content.lines().take(5) {
|
||||
if let Some(rest) = line.strip_prefix("# rtk-hook-version:") {
|
||||
if let Ok(v) = rest.trim().parse::<u8>() {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
}
|
||||
0 // No version tag = version 0 (outdated)
|
||||
}
|
||||
|
||||
fn hook_installed_path() -> Option<PathBuf> {
|
||||
let home = dirs::home_dir()?;
|
||||
let path = home.join(".claude").join("hooks").join("rtk-rewrite.sh");
|
||||
if path.exists() {
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn warn_marker_path() -> Option<PathBuf> {
|
||||
let data_dir = dirs::data_local_dir()?.join("rtk");
|
||||
Some(data_dir.join(".hook_warn_last"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_hook_version_present() {
|
||||
let content = "#!/usr/bin/env bash\n# rtk-hook-version: 2\n# some comment\n";
|
||||
assert_eq!(parse_hook_version(content), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_hook_version_missing() {
|
||||
let content = "#!/usr/bin/env bash\n# old hook without version\n";
|
||||
assert_eq!(parse_hook_version(content), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_hook_version_future() {
|
||||
let content = "#!/usr/bin/env bash\n# rtk-hook-version: 5\n";
|
||||
assert_eq!(parse_hook_version(content), 5);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -1029,6 +1029,7 @@ pub fn show_config() -> Result<()> {
|
||||
let has_guards =
|
||||
hook_content.contains("command -v rtk") && hook_content.contains("command -v jq");
|
||||
let is_thin_delegator = hook_content.contains("rtk rewrite");
|
||||
let hook_version = crate::hook_check::parse_hook_version(&hook_content);
|
||||
|
||||
if !is_executable {
|
||||
println!(
|
||||
@@ -1045,8 +1046,9 @@ pub fn show_config() -> Result<()> {
|
||||
);
|
||||
} else if is_executable && has_guards {
|
||||
println!(
|
||||
"✅ Hook: {} (thin delegator, up to date)",
|
||||
hook_path.display()
|
||||
"✅ Hook: {} (thin delegator, version {})",
|
||||
hook_path.display(),
|
||||
hook_version
|
||||
);
|
||||
} else {
|
||||
println!("⚠️ Hook: {} (no guards - outdated)", hook_path.display());
|
||||
|
||||
+66
-1
@@ -1,12 +1,41 @@
|
||||
use crate::tracking;
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::io::{self, Read};
|
||||
use std::path::Path;
|
||||
|
||||
/// Reject non-JSON files with a clear error before doing any I/O.
|
||||
fn validate_json_extension(file: &Path) -> Result<()> {
|
||||
if let Some(ext) = file.extension().and_then(|e| e.to_str()) {
|
||||
let format_name = match ext {
|
||||
"toml" => Some("TOML"),
|
||||
"yaml" | "yml" => Some("YAML"),
|
||||
"xml" => Some("XML"),
|
||||
"csv" => Some("CSV"),
|
||||
"ini" => Some("INI"),
|
||||
"env" => Some("env"),
|
||||
"txt" => Some("plain text"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(fmt) = format_name {
|
||||
let mut msg = format!(
|
||||
"{} is not a JSON file (detected {}). Use `rtk read` for non-JSON files.",
|
||||
file.display(),
|
||||
fmt
|
||||
);
|
||||
if ext == "toml" && file.file_name().is_some_and(|n| n == "Cargo.toml") {
|
||||
msg.push_str(" Tip: use `rtk deps` for Cargo.toml.");
|
||||
}
|
||||
bail!("{}", msg);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Show JSON structure without values
|
||||
pub fn run(file: &Path, max_depth: usize, verbose: u8) -> Result<()> {
|
||||
validate_json_extension(file)?;
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if verbose > 0 {
|
||||
@@ -147,6 +176,42 @@ fn extract_schema(value: &Value, depth: usize, max_depth: usize) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// --- #347: validate_json_extension ---
|
||||
|
||||
#[test]
|
||||
fn test_toml_file_rejected() {
|
||||
let err = validate_json_extension(Path::new("config.toml")).unwrap_err();
|
||||
assert!(err.to_string().contains("not a JSON file"));
|
||||
assert!(err.to_string().contains("TOML"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cargo_toml_suggests_deps() {
|
||||
let err = validate_json_extension(Path::new("Cargo.toml")).unwrap_err();
|
||||
assert!(err.to_string().contains("rtk deps"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_yaml_file_rejected() {
|
||||
let err = validate_json_extension(Path::new("config.yaml")).unwrap_err();
|
||||
assert!(err.to_string().contains("YAML"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_json_file_accepted() {
|
||||
assert!(validate_json_extension(Path::new("data.json")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_extension_accepted() {
|
||||
assert!(validate_json_extension(Path::new("data.xyz")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_extension_accepted() {
|
||||
assert!(validate_json_extension(Path::new("Makefile")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_schema_simple() {
|
||||
let json: Value = serde_json::from_str(r#"{"name": "test", "count": 42}"#).unwrap();
|
||||
|
||||
+112
-11
@@ -52,16 +52,43 @@ fn is_python_linter(linter: &str) -> bool {
|
||||
matches!(linter, "ruff" | "pylint" | "mypy" | "flake8")
|
||||
}
|
||||
|
||||
pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
/// Strip package manager prefixes (npx, bunx, pnpm, pnpm exec, yarn) from args.
|
||||
/// Returns the number of args to skip.
|
||||
fn strip_pm_prefix(args: &[String]) -> usize {
|
||||
let pm_names = ["npx", "bunx", "pnpm", "yarn"];
|
||||
let mut skip = 0;
|
||||
for arg in args {
|
||||
if pm_names.contains(&arg.as_str()) || arg == "exec" {
|
||||
skip += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
skip
|
||||
}
|
||||
|
||||
// Detect linter name (first arg if not a path/flag, else default to eslint)
|
||||
/// Detect the linter name from args (after stripping PM prefixes).
|
||||
/// Returns the linter name and whether it was explicitly specified.
|
||||
fn detect_linter(args: &[String]) -> (&str, bool) {
|
||||
let is_path_or_flag = args.is_empty()
|
||||
|| args[0].starts_with('-')
|
||||
|| args[0].contains('/')
|
||||
|| args[0].contains('.');
|
||||
|
||||
let linter = if is_path_or_flag { "eslint" } else { &args[0] };
|
||||
if is_path_or_flag {
|
||||
("eslint", false)
|
||||
} else {
|
||||
(&args[0], true)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let skip = strip_pm_prefix(args);
|
||||
let effective_args = &args[skip..];
|
||||
|
||||
let (linter, explicit) = detect_linter(effective_args);
|
||||
|
||||
// Python linters use Command::new() directly (they're on PATH via pip/pipx)
|
||||
// JS linters use package_manager_exec (npx/pnpm exec)
|
||||
@@ -78,13 +105,13 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
}
|
||||
"ruff" => {
|
||||
// Force JSON output for ruff check
|
||||
if !args.contains(&"--output-format".to_string()) {
|
||||
if !effective_args.contains(&"--output-format".to_string()) {
|
||||
cmd.arg("check").arg("--output-format=json");
|
||||
}
|
||||
}
|
||||
"pylint" => {
|
||||
// Force JSON2 output for pylint
|
||||
if !args.contains(&"--output-format".to_string()) {
|
||||
if !effective_args.contains(&"--output-format".to_string()) {
|
||||
cmd.arg("--output-format=json2");
|
||||
}
|
||||
}
|
||||
@@ -97,11 +124,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
}
|
||||
|
||||
// Add user arguments (skip first if it was the linter name, and skip "check" for ruff if we added it)
|
||||
let start_idx = if is_path_or_flag {
|
||||
let start_idx = if !explicit {
|
||||
0
|
||||
} else if linter == "ruff" && !args.is_empty() && args[0] == "ruff" {
|
||||
} else if linter == "ruff" && !effective_args.is_empty() && effective_args[0] == "ruff" {
|
||||
// Skip "ruff" and "check" if we already added "check"
|
||||
if args.len() > 1 && args[1] == "check" {
|
||||
if effective_args.len() > 1 && effective_args[1] == "check" {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
@@ -110,7 +137,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
1
|
||||
};
|
||||
|
||||
for arg in &args[start_idx..] {
|
||||
for arg in &effective_args[start_idx..] {
|
||||
// Skip --output-format if we already added it
|
||||
if linter == "ruff" && arg.starts_with("--output-format") {
|
||||
continue;
|
||||
@@ -123,7 +150,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
|
||||
// Default to current directory if no path specified (for ruff/pylint/mypy/eslint)
|
||||
if matches!(linter, "ruff" | "pylint" | "mypy" | "eslint") {
|
||||
let has_path = args
|
||||
let has_path = effective_args
|
||||
.iter()
|
||||
.skip(start_idx)
|
||||
.any(|a| !a.starts_with('-') && !a.contains('='));
|
||||
@@ -580,6 +607,80 @@ mod tests {
|
||||
assert!(result.contains("utils.py"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_pm_prefix_npx() {
|
||||
let args: Vec<String> = vec!["npx".into(), "eslint".into(), "src/".into()];
|
||||
assert_eq!(strip_pm_prefix(&args), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_pm_prefix_bunx() {
|
||||
let args: Vec<String> = vec!["bunx".into(), "eslint".into(), ".".into()];
|
||||
assert_eq!(strip_pm_prefix(&args), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_pm_prefix_pnpm_exec() {
|
||||
let args: Vec<String> = vec!["pnpm".into(), "exec".into(), "eslint".into()];
|
||||
assert_eq!(strip_pm_prefix(&args), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_pm_prefix_none() {
|
||||
let args: Vec<String> = vec!["eslint".into(), "src/".into()];
|
||||
assert_eq!(strip_pm_prefix(&args), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_pm_prefix_empty() {
|
||||
let args: Vec<String> = vec![];
|
||||
assert_eq!(strip_pm_prefix(&args), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_linter_eslint() {
|
||||
let args: Vec<String> = vec!["eslint".into(), "src/".into()];
|
||||
let (linter, explicit) = detect_linter(&args);
|
||||
assert_eq!(linter, "eslint");
|
||||
assert!(explicit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_linter_default_on_path() {
|
||||
let args: Vec<String> = vec!["src/".into()];
|
||||
let (linter, explicit) = detect_linter(&args);
|
||||
assert_eq!(linter, "eslint");
|
||||
assert!(!explicit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_linter_default_on_flag() {
|
||||
let args: Vec<String> = vec!["--max-warnings=0".into()];
|
||||
let (linter, explicit) = detect_linter(&args);
|
||||
assert_eq!(linter, "eslint");
|
||||
assert!(!explicit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_linter_after_npx_strip() {
|
||||
// Simulates: rtk lint npx eslint src/ → after strip_pm_prefix, args = ["eslint", "src/"]
|
||||
let full_args: Vec<String> = vec!["npx".into(), "eslint".into(), "src/".into()];
|
||||
let skip = strip_pm_prefix(&full_args);
|
||||
let effective = &full_args[skip..];
|
||||
let (linter, _) = detect_linter(effective);
|
||||
assert_eq!(linter, "eslint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_linter_after_pnpm_exec_strip() {
|
||||
let full_args: Vec<String> =
|
||||
vec!["pnpm".into(), "exec".into(), "biome".into(), "check".into()];
|
||||
let skip = strip_pm_prefix(&full_args);
|
||||
let effective = &full_args[skip..];
|
||||
let (linter, _) = detect_linter(effective);
|
||||
assert_eq!(linter, "biome");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_python_linter() {
|
||||
assert!(is_python_linter("ruff"));
|
||||
|
||||
+132
-25
@@ -20,6 +20,7 @@ mod go_cmd;
|
||||
mod golangci_cmd;
|
||||
mod grep_cmd;
|
||||
mod hook_audit_cmd;
|
||||
mod hook_check;
|
||||
mod init;
|
||||
mod integrity;
|
||||
mod json_cmd;
|
||||
@@ -45,6 +46,7 @@ mod ruff_cmd;
|
||||
mod runner;
|
||||
mod summary;
|
||||
mod tee;
|
||||
mod telemetry;
|
||||
mod tracking;
|
||||
mod tree;
|
||||
mod tsc_cmd;
|
||||
@@ -647,9 +649,9 @@ enum GitCommands {
|
||||
},
|
||||
/// Commit → "ok ✓ \<hash\>"
|
||||
Commit {
|
||||
/// Commit message (can be repeated for multi-paragraph)
|
||||
#[arg(short, long)]
|
||||
message: Vec<String>,
|
||||
/// 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 {
|
||||
@@ -953,8 +955,6 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
|
||||
parse_error.exit();
|
||||
}
|
||||
|
||||
eprintln!("[rtk: parse failed, running raw]");
|
||||
|
||||
let raw_command = args.join(" ");
|
||||
let error_message = utils::strip_ansi(&parse_error.to_string());
|
||||
|
||||
@@ -990,6 +990,12 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// Fire-and-forget telemetry ping (1/day, non-blocking)
|
||||
telemetry::maybe_ping();
|
||||
|
||||
// Warn if installed hook is outdated (1/day, non-blocking)
|
||||
hook_check::maybe_warn();
|
||||
|
||||
let cli = match Cli::try_parse() {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
@@ -1113,10 +1119,10 @@ fn main() -> Result<()> {
|
||||
GitCommands::Add { args } => {
|
||||
git::run(git::GitCommand::Add, &args, None, cli.verbose, &global_args)?;
|
||||
}
|
||||
GitCommands::Commit { message } => {
|
||||
GitCommands::Commit { args } => {
|
||||
git::run(
|
||||
git::GitCommand::Commit { messages: message },
|
||||
&[],
|
||||
git::GitCommand::Commit,
|
||||
&args,
|
||||
None,
|
||||
cli.verbose,
|
||||
&global_args,
|
||||
@@ -1692,7 +1698,9 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
Commands::Proxy { args } => {
|
||||
use std::process::Command;
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
|
||||
if args.is_empty() {
|
||||
anyhow::bail!(
|
||||
@@ -1712,18 +1720,74 @@ fn main() -> Result<()> {
|
||||
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
|
||||
}
|
||||
|
||||
let output = Command::new(cmd_name.as_ref())
|
||||
let mut child = Command::new(cmd_name.as_ref())
|
||||
.args(&cmd_args)
|
||||
.output()
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.context(format!("Failed to execute command: {}", cmd_name))?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let full_output = format!("{}{}", stdout, stderr);
|
||||
let stdout_pipe = child
|
||||
.stdout
|
||||
.take()
|
||||
.context("Failed to capture child stdout")?;
|
||||
let stderr_pipe = child
|
||||
.stderr
|
||||
.take()
|
||||
.context("Failed to capture child stderr")?;
|
||||
|
||||
// Print output
|
||||
print!("{}", stdout);
|
||||
eprint!("{}", stderr);
|
||||
let stdout_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
|
||||
let mut reader = stdout_pipe;
|
||||
let mut captured = Vec::new();
|
||||
let mut buf = [0u8; 8192];
|
||||
|
||||
loop {
|
||||
let count = reader.read(&mut buf)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
captured.extend_from_slice(&buf[..count]);
|
||||
let mut out = std::io::stdout().lock();
|
||||
out.write_all(&buf[..count])?;
|
||||
out.flush()?;
|
||||
}
|
||||
|
||||
Ok(captured)
|
||||
});
|
||||
|
||||
let stderr_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
|
||||
let mut reader = stderr_pipe;
|
||||
let mut captured = Vec::new();
|
||||
let mut buf = [0u8; 8192];
|
||||
|
||||
loop {
|
||||
let count = reader.read(&mut buf)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
captured.extend_from_slice(&buf[..count]);
|
||||
let mut err = std::io::stderr().lock();
|
||||
err.write_all(&buf[..count])?;
|
||||
err.flush()?;
|
||||
}
|
||||
|
||||
Ok(captured)
|
||||
});
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.context(format!("Failed waiting for command: {}", cmd_name))?;
|
||||
|
||||
let stdout_bytes = stdout_handle
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("stdout streaming thread panicked"))??;
|
||||
let stderr_bytes = stderr_handle
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("stderr streaming thread panicked"))??;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&stdout_bytes);
|
||||
let stderr = String::from_utf8_lossy(&stderr_bytes);
|
||||
let full_output = format!("{}{}", stdout, stderr);
|
||||
|
||||
// Track usage (input = output since no filtering)
|
||||
timer.track(
|
||||
@@ -1734,8 +1798,8 @@ fn main() -> Result<()> {
|
||||
);
|
||||
|
||||
// Exit with same code as child process
|
||||
if !output.status.success() {
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
if !status.success() {
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1809,10 +1873,10 @@ mod tests {
|
||||
let cli = Cli::try_parse_from(["rtk", "git", "commit", "-m", "fix: typo"]).unwrap();
|
||||
match cli.command {
|
||||
Commands::Git {
|
||||
command: GitCommands::Commit { message },
|
||||
command: GitCommands::Commit { args },
|
||||
..
|
||||
} => {
|
||||
assert_eq!(message, vec!["fix: typo"]);
|
||||
assert_eq!(args, vec!["-m", "fix: typo"]);
|
||||
}
|
||||
_ => panic!("Expected Git Commit command"),
|
||||
}
|
||||
@@ -1832,10 +1896,43 @@ mod tests {
|
||||
.unwrap();
|
||||
match cli.command {
|
||||
Commands::Git {
|
||||
command: GitCommands::Commit { message },
|
||||
command: GitCommands::Commit { args },
|
||||
..
|
||||
} => {
|
||||
assert_eq!(message, vec!["feat: add support", "Body paragraph here."]);
|
||||
assert_eq!(
|
||||
args,
|
||||
vec!["-m", "feat: add support", "-m", "Body paragraph here."]
|
||||
);
|
||||
}
|
||||
_ => panic!("Expected Git Commit command"),
|
||||
}
|
||||
}
|
||||
|
||||
// #327: git commit -am "msg" was rejected by Clap
|
||||
#[test]
|
||||
fn test_git_commit_am_flag() {
|
||||
let cli = Cli::try_parse_from(["rtk", "git", "commit", "-am", "quick fix"]).unwrap();
|
||||
match cli.command {
|
||||
Commands::Git {
|
||||
command: GitCommands::Commit { args },
|
||||
..
|
||||
} => {
|
||||
assert_eq!(args, vec!["-am", "quick fix"]);
|
||||
}
|
||||
_ => panic!("Expected Git Commit command"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_git_commit_amend() {
|
||||
let cli =
|
||||
Cli::try_parse_from(["rtk", "git", "commit", "--amend", "-m", "new msg"]).unwrap();
|
||||
match cli.command {
|
||||
Commands::Git {
|
||||
command: GitCommands::Commit { args },
|
||||
..
|
||||
} => {
|
||||
assert_eq!(args, vec!["--amend", "-m", "new msg"]);
|
||||
}
|
||||
_ => panic!("Expected Git Commit command"),
|
||||
}
|
||||
@@ -1879,10 +1976,20 @@ mod tests {
|
||||
.unwrap();
|
||||
match cli.command {
|
||||
Commands::Git {
|
||||
command: GitCommands::Commit { message },
|
||||
command: GitCommands::Commit { args },
|
||||
..
|
||||
} => {
|
||||
assert_eq!(message, vec!["title", "body", "footer"]);
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"--message",
|
||||
"title",
|
||||
"--message",
|
||||
"body",
|
||||
"--message",
|
||||
"footer"
|
||||
]
|
||||
);
|
||||
}
|
||||
_ => panic!("Expected Git Commit command"),
|
||||
}
|
||||
|
||||
@@ -24,6 +24,25 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
// #221: If prettier is not installed or produced no meaningful output,
|
||||
// show stderr as-is instead of a misleading "All files formatted" message.
|
||||
let has_output = stdout.lines().any(|l| !l.trim().is_empty());
|
||||
if !has_output && !output.status.success() {
|
||||
let msg = stderr.trim();
|
||||
if msg.is_empty() {
|
||||
eprintln!("Error: prettier not found or produced no output");
|
||||
} else {
|
||||
eprintln!("{}", msg);
|
||||
}
|
||||
timer.track(
|
||||
&format!("prettier {}", args.join(" ")),
|
||||
&format!("rtk prettier {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let filtered = filter_prettier_output(&raw);
|
||||
|
||||
println!("{}", filtered);
|
||||
@@ -45,6 +64,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
|
||||
/// Filter Prettier output - show only files that need formatting
|
||||
pub fn filter_prettier_output(output: &str) -> String {
|
||||
// #221: empty or whitespace-only output means prettier didn't run
|
||||
if output.trim().is_empty() {
|
||||
return "Error: prettier produced no output".to_string();
|
||||
}
|
||||
|
||||
let mut files_to_format: Vec<String> = Vec::new();
|
||||
let mut files_checked = 0;
|
||||
let mut is_check_mode = true;
|
||||
@@ -178,4 +202,20 @@ Code style issues found in the above file(s). Forgot to run Prettier?
|
||||
assert!(result.contains("15 files need formatting"));
|
||||
assert!(result.contains("... +5 more files"));
|
||||
}
|
||||
|
||||
// --- #221: empty output should not say "All files formatted" ---
|
||||
|
||||
#[test]
|
||||
fn test_filter_empty_output() {
|
||||
let result = filter_prettier_output("");
|
||||
assert!(result.contains("Error"));
|
||||
assert!(!result.contains("All files formatted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_whitespace_only_output() {
|
||||
let result = filter_prettier_output(" \n\n ");
|
||||
assert!(result.contains("Error"));
|
||||
assert!(!result.contains("All files formatted"));
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -11,7 +11,11 @@ use crate::discover::registry;
|
||||
/// [ "$CMD" = "$REWRITTEN" ] && exit 0 # already RTK, skip
|
||||
/// ```
|
||||
pub fn run(cmd: &str) -> anyhow::Result<()> {
|
||||
match registry::rewrite_command(cmd) {
|
||||
let excluded = crate::config::Config::load()
|
||||
.map(|c| c.hooks.exclude_commands)
|
||||
.unwrap_or_default();
|
||||
|
||||
match registry::rewrite_command(cmd, &excluded) {
|
||||
Some(rewritten) => {
|
||||
print!("{}", rewritten);
|
||||
Ok(())
|
||||
@@ -28,19 +32,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_run_supported_command_succeeds() {
|
||||
// We can't easily test exit code here, but we can test the registry directly
|
||||
assert!(registry::rewrite_command("git status").is_some());
|
||||
assert!(registry::rewrite_command("git status", &[]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_unsupported_returns_none() {
|
||||
assert!(registry::rewrite_command("terraform plan").is_none());
|
||||
assert!(registry::rewrite_command("terraform plan", &[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_already_rtk_returns_some() {
|
||||
assert_eq!(
|
||||
registry::rewrite_command("rtk git status"),
|
||||
registry::rewrite_command("rtk git status", &[]),
|
||||
Some("rtk git status".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::PathBuf;
|
||||
|
||||
const TELEMETRY_URL: Option<&str> = option_env!("RTK_TELEMETRY_URL");
|
||||
const TELEMETRY_TOKEN: Option<&str> = option_env!("RTK_TELEMETRY_TOKEN");
|
||||
const PING_INTERVAL_SECS: u64 = 23 * 3600; // 23 hours
|
||||
|
||||
/// Send a telemetry ping if enabled and not already sent today.
|
||||
/// Fire-and-forget: errors are silently ignored.
|
||||
pub fn maybe_ping() {
|
||||
// No URL compiled in → telemetry disabled
|
||||
if TELEMETRY_URL.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check opt-out: env var
|
||||
if std::env::var("RTK_TELEMETRY_DISABLED").unwrap_or_default() == "1" {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check opt-out: config.toml
|
||||
if let Some(false) = config::telemetry_enabled() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check last ping time
|
||||
let marker = telemetry_marker_path();
|
||||
if let Ok(metadata) = std::fs::metadata(&marker) {
|
||||
if let Ok(modified) = metadata.modified() {
|
||||
if let Ok(elapsed) = modified.elapsed() {
|
||||
if elapsed.as_secs() < PING_INTERVAL_SECS {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Touch marker file immediately (before sending) to avoid double-ping
|
||||
touch_marker(&marker);
|
||||
|
||||
// Spawn thread so we never block the CLI
|
||||
std::thread::spawn(|| {
|
||||
let _ = send_ping();
|
||||
});
|
||||
}
|
||||
|
||||
fn send_ping() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let url = TELEMETRY_URL.ok_or("no telemetry URL")?;
|
||||
let device_hash = generate_device_hash();
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
let os = std::env::consts::OS.to_string();
|
||||
let arch = std::env::consts::ARCH.to_string();
|
||||
|
||||
// Get stats from tracking DB
|
||||
let (commands_24h, top_commands, savings_pct) = get_stats();
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"device_hash": device_hash,
|
||||
"version": version,
|
||||
"os": os,
|
||||
"arch": arch,
|
||||
"commands_24h": commands_24h,
|
||||
"top_commands": top_commands,
|
||||
"savings_pct": savings_pct,
|
||||
});
|
||||
|
||||
let mut req = ureq::post(url).set("Content-Type", "application/json");
|
||||
|
||||
if let Some(token) = TELEMETRY_TOKEN {
|
||||
req = req.set("X-RTK-Token", token);
|
||||
}
|
||||
|
||||
// 2 second timeout — if server is down, we move on
|
||||
req.timeout(std::time::Duration::from_secs(2))
|
||||
.send_string(&payload.to_string())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_device_hash() -> String {
|
||||
let hostname = hostname::get()
|
||||
.map(|h| h.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let username = std::env::var("USER")
|
||||
.or_else(|_| std::env::var("USERNAME"))
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(hostname.as_bytes());
|
||||
hasher.update(b":");
|
||||
hasher.update(username.as_bytes());
|
||||
format!("{:x}", hasher.finalize())
|
||||
}
|
||||
|
||||
fn get_stats() -> (i64, Vec<String>, Option<f64>) {
|
||||
let tracker = match tracking::Tracker::new() {
|
||||
Ok(t) => t,
|
||||
Err(_) => return (0, vec![], None),
|
||||
};
|
||||
|
||||
// Get 24h command count and top commands from tracking DB
|
||||
let commands_24h = tracker
|
||||
.count_commands_since(chrono::Utc::now() - chrono::Duration::hours(24))
|
||||
.unwrap_or(0);
|
||||
|
||||
let top_commands = tracker.top_commands(5).unwrap_or_default();
|
||||
|
||||
let savings_pct = tracker.overall_savings_pct().ok();
|
||||
|
||||
(commands_24h, top_commands, savings_pct)
|
||||
}
|
||||
|
||||
fn telemetry_marker_path() -> PathBuf {
|
||||
let data_dir = dirs::data_local_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("/tmp"))
|
||||
.join("rtk");
|
||||
let _ = std::fs::create_dir_all(&data_dir);
|
||||
data_dir.join(".telemetry_last_ping")
|
||||
}
|
||||
|
||||
fn touch_marker(path: &PathBuf) {
|
||||
let _ = std::fs::write(path, b"");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_device_hash_is_stable() {
|
||||
let h1 = generate_device_hash();
|
||||
let h2 = generate_device_hash();
|
||||
assert_eq!(h1, h2);
|
||||
assert_eq!(h1.len(), 64); // SHA-256 hex
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_marker_path_exists() {
|
||||
let path = telemetry_marker_path();
|
||||
assert!(path.to_string_lossy().contains("rtk"));
|
||||
}
|
||||
}
|
||||
@@ -886,6 +886,45 @@ impl Tracker {
|
||||
|
||||
Ok(rows.collect::<Result<Vec<_>, _>>()?)
|
||||
}
|
||||
|
||||
/// Count commands since a given timestamp (for telemetry).
|
||||
pub fn count_commands_since(&self, since: chrono::DateTime<chrono::Utc>) -> Result<i64> {
|
||||
let ts = since.format("%Y-%m-%dT%H:%M:%S").to_string();
|
||||
let count: i64 = self.conn.query_row(
|
||||
"SELECT COUNT(*) FROM commands WHERE timestamp >= ?1",
|
||||
params![ts],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Get top N commands by frequency (for telemetry).
|
||||
pub fn top_commands(&self, limit: usize) -> Result<Vec<String>> {
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT rtk_cmd, COUNT(*) as cnt FROM commands
|
||||
GROUP BY rtk_cmd ORDER BY cnt DESC LIMIT ?1",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![limit as i64], |row| {
|
||||
let cmd: String = row.get(0)?;
|
||||
// Extract just the command name (e.g. "rtk git status" → "git")
|
||||
Ok(cmd.split_whitespace().nth(1).unwrap_or(&cmd).to_string())
|
||||
})?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
/// Get overall savings percentage (for telemetry).
|
||||
pub fn overall_savings_pct(&self) -> Result<f64> {
|
||||
let (total_input, total_saved): (i64, i64) = self.conn.query_row(
|
||||
"SELECT COALESCE(SUM(input_tokens), 0), COALESCE(SUM(saved_tokens), 0) FROM commands",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
if total_input > 0 {
|
||||
Ok((total_saved as f64 / total_input as f64) * 100.0)
|
||||
} else {
|
||||
Ok(0.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_db_path() -> Result<PathBuf> {
|
||||
|
||||
Reference in new issue
Block a user