diff --git a/cmd/skillshare/check.go b/cmd/skillshare/check.go index ff22c391b..2b18cd172 100644 --- a/cmd/skillshare/check.go +++ b/cmd/skillshare/check.go @@ -2,7 +2,6 @@ package main import ( "context" - "encoding/json" "errors" "fmt" "os" @@ -44,6 +43,8 @@ type checkOutput struct { Skills []checkSkillResult `json:"skills"` // Agents is set only by --all, so check --json keeps its shape. Agents *[]check.AgentCheckResult `json:"agents,omitempty"` + // Warnings names the requested names and groups that were skipped. + Warnings []string `json:"warnings,omitempty"` } // checkOptions holds parsed arguments for check command @@ -177,6 +178,17 @@ func splitURLBranch(key string) (url, branch string) { } func cmdCheck(args []string) error { + err := runCheckCommand(args) + // With --json every failure is a JSON object on stdout, including the + // ones found before any check ran (bad flags, missing config). + var silent *jsonSilentError + if err != nil && isStructuredOutput(args) && !errors.As(err, &silent) { + return writeJSONError(err) + } + return err +} + +func runCheckCommand(args []string) error { start := time.Now() mode, rest, err := parseModeArgs(args, "--group", "-G") @@ -590,7 +602,9 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks . resolveWarnings = append(resolveWarnings, fmt.Sprintf("%s: no updatable skills in group", name)) continue } - ui.Note(fmt.Sprintf("'%s' is a group — expanding to %s", name, plural(len(groupMatches), "updatable skill"))) + if !opts.json { + ui.Note(fmt.Sprintf("'%s' is a group — expanding to %s", name, plural(len(groupMatches), "updatable skill"))) + } for _, m := range groupMatches { if !seen[m.name] { seen[m.name] = true @@ -633,23 +647,27 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks . resolveSpinner.Stop() } - for _, w := range resolveWarnings { - ui.Warning("%s", w) + // With --json stdout carries the result only: skipped names go in its + // warnings field, or in the error when nothing is left to check. + if !opts.json { + for _, w := range resolveWarnings { + ui.Warning("%s", w) + } } if len(targets) == 0 { - if opts.json { - out, _ := json.MarshalIndent(checkOutput{ - TrackedRepos: []checkRepoResult{}, - Skills: []checkSkillResult{}, - }, "", " ") - fmt.Println(string(out)) - return nil - } + err := fmt.Errorf("no skills found") if len(resolveWarnings) > 0 { - return fmt.Errorf("no valid skills to check") + err = fmt.Errorf("no valid skills to check") } - return fmt.Errorf("no skills found") + if opts.json { + // An empty result would read as "all clear". + if len(resolveWarnings) > 0 { + err = fmt.Errorf("%w: %s", err, strings.Join(resolveWarnings, "; ")) + } + return writeJSONError(err) + } + return err } var follow *sourcewalk.Follow @@ -709,6 +727,7 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks . output := checkOutput{ TrackedRepos: repoResults, Skills: skillResults, + Warnings: resolveWarnings, } if output.TrackedRepos == nil { output.TrackedRepos = []checkRepoResult{} diff --git a/skills/skillshare/references/install.md b/skills/skillshare/references/install.md index 42654dfa6..96255aaa7 100644 --- a/skills/skillshare/references/install.md +++ b/skills/skillshare/references/install.md @@ -180,6 +180,11 @@ skillshare check -p # Check project skills skillshare check my-skill --diff # Show local edits vs the installed version ``` +With `--json`, a failure is one object on stdout, `{"error": "..."}`, with exit +code 1: a name or group that matches nothing to check, an invalid flag +combination, or a missing config. When some names match and others do not, the +result lists the skipped ones in `warnings`. + - **Tracked repos:** Fetches from origin, shows commits behind - **Remote skills:** Compares installed version with remote HEAD - **Modified skills:** Remote skills edited since install are `modified`; `update` skips them until `--force`. `check --diff` shows the edits diff --git a/tests/integration/check_test.go b/tests/integration/check_test.go index e2b096411..c88fdeabc 100644 --- a/tests/integration/check_test.go +++ b/tests/integration/check_test.go @@ -318,6 +318,143 @@ func TestCheckProject_All_ChecksAgentsWithoutSkillsDir(t *testing.T) { result.AssertAnyOutputContains(t, "reviewer") } +func TestCheck_UnknownName_JSON_Fails(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + + assertJSONError(t, sb.RunCLI("check", "no-such-skill", "--json"), "no-such-skill") +} + +// assertJSONError fails unless the command exited 1 with stdout holding one +// JSON object whose error names want. +func assertJSONError(t *testing.T, result *testutil.Result, want string) { + t.Helper() + result.AssertExitCode(t, 1) + var out struct { + Error string `json:"error"` + } + if err := json.Unmarshal([]byte(result.Stdout), &out); err != nil { + t.Fatalf("stdout is not one JSON object: %v\n%s", err, result.Stdout) + } + if !strings.Contains(out.Error, want) { + t.Errorf("error = %q, want it to contain %q", out.Error, want) + } +} + +func TestCheck_JSON_TwoUnknownNames_NamesBoth(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + + result := sb.RunCLI("check", "first-typo", "second-typo", "--json") + assertJSONError(t, result, "first-typo") + assertJSONError(t, result, "second-typo") +} + +func TestCheck_JSON_UnknownGroup_Fails(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + + assertJSONError(t, sb.RunCLI("check", "--group", "no-such-group", "--json"), "no-such-group") +} + +func TestCheck_JSON_GroupOfLocalSkillsOnly_Fails(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + localSkill := filepath.Join(sb.SourcePath, "mine", "notes") + os.MkdirAll(localSkill, 0755) + os.WriteFile(filepath.Join(localSkill, "SKILL.md"), []byte("---\nname: notes\n---\n# Notes"), 0644) + + for _, args := range [][]string{{"check", "mine", "--json"}, {"check", "--group", "mine", "--json"}} { + assertJSONError(t, sb.RunCLI(args...), "no updatable skills in group") + } +} + +func TestCheck_JSON_UnknownName_ExitCodeFlag_Fails(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + + assertJSONError(t, sb.RunCLI("check", "no-such-skill", "--json", "--exit-code"), "no-such-skill") +} + +func TestCheck_JSON_InvalidFlagCombination_IsJSON(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + + assertJSONError(t, sb.RunCLI("check", "--all", "_test-repo", "--json"), "--all cannot be combined") +} + +func TestCheckProject_JSON_UnknownName_Fails(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + projectRoot := sb.SetupProjectDir("claude") + + assertJSONError(t, sb.RunCLIInDir(projectRoot, "check", "-p", "no-such-skill", "--json"), "no-such-skill") +} + +func TestCheckProject_JSON_NoProjectConfig_IsJSON(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + emptyDir := filepath.Join(sb.Root, "not-a-project") + os.MkdirAll(emptyDir, 0755) + + assertJSONError(t, sb.RunCLIInDir(emptyDir, "check", "-p", "--json"), "no project config") +} + +func TestCheck_GroupName_JSON_KeepsStdoutJSON(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + groupSkill := filepath.Join(sb.SourcePath, "frontend", "ui-kit") + os.MkdirAll(groupSkill, 0755) + os.WriteFile(filepath.Join(groupSkill, "SKILL.md"), []byte("---\nname: ui-kit\n---\n# UI"), 0644) + store, err := install.LoadMetadata(sb.SourcePath) + if err != nil { + t.Fatalf("load metadata: %v", err) + } + store.Set("frontend/ui-kit", &install.MetadataEntry{Source: "owner/repo", Group: "frontend"}) + if err := store.Save(sb.SourcePath); err != nil { + t.Fatalf("save metadata: %v", err) + } + + result := sb.RunCLI("check", "frontend", "--json") + if !json.Valid([]byte(result.Stdout)) { + t.Errorf("stdout is not JSON:\n%s", result.Stdout) + } + if !strings.Contains(result.Stdout, "ui-kit") { + t.Errorf("the group should expand to ui-kit, got:\n%s", result.Stdout) + } +} + +func TestCheck_UnknownNameBesideKnown_JSON_KeepsStdoutJSON(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + behindTrackedRepo(t, sb) + + result := sb.RunCLI("check", "_test-repo", "no-such-skill", "--json") + result.AssertSuccess(t) + var out struct { + TrackedRepos []struct { + Name string `json:"name"` + } `json:"tracked_repos"` + Warnings []string `json:"warnings"` + } + if err := json.Unmarshal([]byte(result.Stdout), &out); err != nil { + t.Fatalf("stdout is not one JSON object: %v\n%s", err, result.Stdout) + } + if len(out.TrackedRepos) != 1 { + t.Errorf("tracked_repos = %+v, want _test-repo", out.TrackedRepos) + } + if len(out.Warnings) != 1 || !strings.Contains(out.Warnings[0], "no-such-skill") { + t.Errorf("warnings = %q, want one naming no-such-skill", out.Warnings) + } +} + func TestCheck_ExitCode_RejectsDiff(t *testing.T) { sb := testutil.NewSandbox(t) defer sb.Cleanup() diff --git a/website/docs/reference/commands/check.md b/website/docs/reference/commands/check.md index 5025e19da..989be97fb 100644 --- a/website/docs/reference/commands/check.md +++ b/website/docs/reference/commands/check.md @@ -39,7 +39,7 @@ result=$(skillshare check --json) ## Exit Status -`check` exits with code `1` if any checked item has status `error` (for example, an unreachable remote or a missing local source). Available updates, stale items, and local modifications alone do not cause failure. With `--json`, stdout still contains the complete results; inspect each item's `status` and `message` for details. +`check` exits with code `1` if any checked item has status `error` (for example, an unreachable remote or a missing local source). Available updates, stale items, and local modifications alone do not cause failure. With `--json`, stdout still contains the complete results; inspect each item's `status` and `message` for details. When the names or groups you pass match nothing to check, `check` exits with code `1`; with `--json` it prints `{"error": "..."}` in place of the results. With `--json`, a name that is skipped while others are checked is listed in a `warnings` array in the result. Any other failure with `--json`, such as an invalid flag combination or a missing config, is reported as the same `error` object. Pass `--exit-code` to also exit with code `1` when every item could be checked but something is not up to date: an available update, a stale or locally modified skill, or a tracked repository that is behind, has uncommitted changes, or is missing. Only items whose status is `local` (nothing to compare) are left out; a skill installed from a local path whose source has changed is an available update and does count. The same applies to `check agents` and `check --all`, where an agent whose file changed since install also counts. It works with `--json` and cannot be combined with `--diff`. diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md index 4e907eca1..31a67ba02 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -39,7 +39,7 @@ result=$(skillshare check --json) ## 終了ステータス -確認した項目のいずれかが `error` の場合(リモートに接続できない、ローカルのソースが存在しないなど)、`check` はコード `1` で終了します。更新あり、Stale、ローカルの変更だけでは失敗になりません。`--json` 使用時も stdout にすべての結果を出力します。各項目の `status` と `message` を確認してください。 +確認した項目のいずれかが `error` の場合(リモートに接続できない、ローカルのソースが存在しないなど)、`check` はコード `1` で終了します。更新あり、Stale、ローカルの変更だけでは失敗になりません。`--json` 使用時も stdout にすべての結果を出力します。各項目の `status` と `message` を確認してください。指定した名前やグループに確認対象がひとつもない場合、`check` はコード `1` で終了し、`--json` では結果の代わりに `{"error": "..."}` を出力します。`--json` 使用時、一部の名前だけがスキップされた場合、その名前は結果の `warnings` 配列に含まれます。`--json` 使用時のその他の失敗(無効なフラグの組み合わせや設定ファイルがない場合など)も、同じ `error` オブジェクトで報告されます。 `--exit-code` を指定すると、すべての項目を確認できた場合でも、最新でないものがあれば終了コード `1` で終了します。対象は、利用可能な更新、stale またはローカルで変更された Skill、遅れている・未コミットの変更がある・存在しない追跡リポジトリです。除外されるのは状態が `local`(比較対象なし)の項目だけです。ローカルパスからインストールした Skill のソースが変更された場合は利用可能な更新として数えます。`check agents` と `check --all` でも同様で、インストール後にファイルが変更された agent も対象です。`--json` と併用でき、`--diff` とは併用できません。 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md index f4e79a35f..61623670e 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -39,7 +39,7 @@ result=$(skillshare check --json) ## 종료 상태 -검사한 항목 중 하나라도 상태가 `error`이면(예: 원격 저장소에 연결할 수 없거나 로컬 소스가 없음) `check`는 코드 `1`로 종료합니다. 사용 가능한 업데이트, 오래된 항목, 로컬 수정만으로는 실패하지 않습니다. `--json`을 사용해도 stdout에 전체 결과가 출력됩니다. 각 항목의 `status`와 `message`를 확인하세요. +검사한 항목 중 하나라도 상태가 `error`이면(예: 원격 저장소에 연결할 수 없거나 로컬 소스가 없음) `check`는 코드 `1`로 종료합니다. 사용 가능한 업데이트, 오래된 항목, 로컬 수정만으로는 실패하지 않습니다. `--json`을 사용해도 stdout에 전체 결과가 출력됩니다. 각 항목의 `status`와 `message`를 확인하세요. 지정한 이름이나 group에 확인할 대상이 하나도 없으면 `check`는 코드 `1`로 종료하며, `--json`에서는 결과 대신 `{"error": "..."}`를 출력합니다. `--json`을 사용할 때 일부 이름만 건너뛰면 해당 이름은 결과의 `warnings` 배열에 포함됩니다. `--json`을 사용할 때의 다른 실패(잘못된 플래그 조합이나 설정 파일 없음 등)도 같은 `error` 객체로 보고됩니다. `--exit-code`를 지정하면 모든 항목을 확인할 수 있었더라도 최신이 아닌 항목이 있을 때 종료 코드 `1`로 종료합니다. 사용 가능한 업데이트, stale이거나 로컬에서 수정된 skill, 뒤처졌거나 커밋되지 않은 변경이 있거나 없어진 추적 저장소가 해당합니다. 제외되는 것은 상태가 `local`(비교 대상 없음)인 항목뿐입니다. 로컬 경로에서 설치한 skill의 소스가 변경되면 사용 가능한 업데이트로 셉니다. `check agents`와 `check --all`에도 동일하게 적용되며, 설치 이후 파일이 변경된 agent도 해당합니다. `--json`과 함께 사용할 수 있으며 `--diff`와는 함께 사용할 수 없습니다. diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md index 720334232..2e4eaa102 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -39,7 +39,7 @@ result=$(skillshare check --json) ## 退出状态 -只要任一检查项的状态为 `error`(例如无法连接远程仓库或本地来源不存在),`check` 就会以代码 `1` 退出。仅有可用更新、过时项目或本地修改不会导致失败。使用 `--json` 时,stdout 仍包含完整结果;请查看各项的 `status` 和 `message`。 +只要任一检查项的状态为 `error`(例如无法连接远程仓库或本地来源不存在),`check` 就会以代码 `1` 退出。仅有可用更新、过时项目或本地修改不会导致失败。使用 `--json` 时,stdout 仍包含完整结果;请查看各项的 `status` 和 `message`。指定的名称或 group 没有任何可检查的对象时,`check` 以代码 `1` 退出;使用 `--json` 时输出 `{"error": "..."}` 而不是结果。使用 `--json` 且只有部分名称被跳过时,这些名称会列在结果的 `warnings` 数组中。使用 `--json` 时的其他失败(例如无效的参数组合或缺少配置)也以同样的 `error` 对象报告。 传入 `--exit-code` 后,即使所有项目都能完成检查,只要有项目不是最新,也会以退出码 `1` 结束:有可用更新、stale 或本地被修改的 skill,或者落后、有未提交更改、缺失的追踪仓库。只有状态为 `local`(没有可比较的对象)的项目不计入;从本地路径安装的 skill 若来源已变更,属于可用更新,会计入。`check agents` 与 `check --all` 同样适用,安装后文件被修改的 agent 也计入。可与 `--json` 一起使用,不能与 `--diff` 同时使用。 diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md index 0aac572b9..177a0237d 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -39,7 +39,7 @@ result=$(skillshare check --json) ## 結束狀態 -只要任一受檢項目的狀態為 `error`(例如無法連線遠端或本機來源不存在),`check` 就會以代碼 `1` 結束。僅有可用更新、過期項目或本機修改不會造成失敗。使用 `--json` 時,stdout 仍會包含完整結果;請查看各項目的 `status` 與 `message`。 +只要任一受檢項目的狀態為 `error`(例如無法連線遠端或本機來源不存在),`check` 就會以代碼 `1` 結束。僅有可用更新、過期項目或本機修改不會造成失敗。使用 `--json` 時,stdout 仍會包含完整結果;請查看各項目的 `status` 與 `message`。指定的名稱或群組沒有任何可檢查的對象時,`check` 以代碼 `1` 結束;使用 `--json` 時輸出 `{"error": "..."}` 而不是結果。使用 `--json` 且只有部分名稱被略過時,這些名稱會列在結果的 `warnings` 陣列中。使用 `--json` 時的其他失敗(例如無效的旗標組合或缺少設定檔)也以同樣的 `error` 物件回報。 傳入 `--exit-code` 後,即使所有項目都能完成檢查,只要有項目不是最新,也會以結束代碼 `1` 結束:有可用更新、stale 或本地被修改的 skill,或者落後、有未提交變更、遺失的追蹤儲存庫。只有狀態為 `local`(沒有可比較的對象)的項目不計入;從本地路徑安裝的 skill 若來源已變更,屬於可用更新,會計入。`check agents` 與 `check --all` 同樣適用,安裝後檔案被修改的 agent 也計入。可與 `--json` 一起使用,不能與 `--diff` 同時使用。