diff --git a/internal/git/discard.go b/internal/git/discard.go new file mode 100644 index 000000000..fff5b3008 --- /dev/null +++ b/internal/git/discard.go @@ -0,0 +1,44 @@ +package git + +import ( + "fmt" + "os/exec" +) + +// DiscardChanges restores tracked files and the index to HEAD, and removes +// untracked files. Ignored files and nested repositories are kept. At root +// scope, the machine-specific config.yaml is also kept, even if tracked. +func DiscardChanges(dir string, preserveConfig bool) error { + paths := []string{"."} + cleanArgs := []string{"clean", "-fd"} + if preserveConfig { + paths = append(paths, ":(top,exclude)config.yaml") + cleanArgs = append(cleanArgs, "-e", "/config.yaml") + } + changed := false + // Check both diffs: staged and unstaged edits can cancel each other out. + // Skip restore when neither has changes, including an empty initial commit. + for _, args := range [][]string{{"diff", "--name-only", "HEAD"}, {"diff", "--cached", "--name-only", "HEAD"}} { + cmd := exec.Command("git", append(append(args, "--"), paths...)...) + cmd.Dir = dir + out, err := cmd.Output() + if err != nil { + return fmt.Errorf("failed to check changes: %w", err) + } + changed = changed || len(out) > 0 + } + // Clean first, while the local .gitignore still defines ignored files. + // A single -f deliberately preserves nested repositories. + commands := [][]string{append(cleanArgs, "--", ".")} + if changed { + commands = append(commands, append([]string{"restore", "--source=HEAD", "--staged", "--worktree", "--no-recurse-submodules", "--"}, paths...)) + } + for _, args := range commands { + cmd := exec.Command("git", args...) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("failed to discard changes: %w: %s", err, out) + } + } + return nil +} diff --git a/internal/server/handler_git_discard.go b/internal/server/handler_git_discard.go new file mode 100644 index 000000000..c177b6767 --- /dev/null +++ b/internal/server/handler_git_discard.go @@ -0,0 +1,56 @@ +package server + +import ( + "errors" + "net/http" + "os" + "path/filepath" + "time" + + "skillshare/internal/git" +) + +func (s *Server) handleGitDiscard(w http.ResponseWriter, r *http.Request) { + start := time.Now() + if s.IsProjectMode() { + writeError(w, http.StatusBadRequest, "Git Sync is only available in global mode") + return + } + var body struct { + DryRun bool `json:"dryRun"` + } + if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil { + if !errors.Is(err, errBodyTooLarge) { + writeError(w, http.StatusBadRequest, "invalid JSON body") + } + return + } + s.mu.Lock() + defer s.mu.Unlock() + src, ok := s.gitSource(w) + if !ok { + return + } + // Never discover an ancestor repo and discard outside the configured source. + if _, err := os.Stat(filepath.Join(src, ".git")); err != nil || !git.IsRepo(src) { + writeError(w, http.StatusBadRequest, "source directory is not a git repository root") + return + } + if _, err := git.GetCurrentHash(src); err != nil { + writeError(w, http.StatusBadRequest, "cannot discard changes before the first commit") + return + } + args := map[string]any{"dry_run": body.DryRun, "scope": "ui", "git_root": s.cfg.GitRoot} + if body.DryRun { + s.writeOpsLog("discard", "ok", start, args, "") + writeJSON(w, pushResponse{Success: true, Message: "dry run: would restore tracked files to HEAD and remove untracked files", DryRun: true}) + return + } + if err := git.DiscardChanges(src, s.cfg.GitRoot == "root"); err != nil { + s.writeOpsLog("discard", "error", start, args, err.Error()) + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + s.writeOpsLog("discard", "ok", start, args, "") + writeJSON(w, pushResponse{Success: true, Message: "changes discarded"}) +} diff --git a/internal/server/handler_git_discard_test.go b/internal/server/handler_git_discard_test.go new file mode 100644 index 000000000..84dc60298 --- /dev/null +++ b/internal/server/handler_git_discard_test.go @@ -0,0 +1,200 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/testutil" +) + +func discardRequest(s *Server, body string) *httptest.ResponseRecorder { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/git/discard", strings.NewReader(body))) + return rr +} + +func TestHandleGitDiscard_Changes(t *testing.T) { + for _, dryRun := range []bool{false, true} { + t.Run(map[bool]string{false: "discard", true: "dry run"}[dryRun], func(t *testing.T) { + s, src := newTestServer(t) + initServerGitRepo(t, src) + write := func(name, content string) { + t.Helper() + if err := os.WriteFile(filepath.Join(src, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + for _, name := range []string{"modified", "deleted", "renamed", ".gitignore"} { + write(name, "ignored\n") + } + testutil.RunGit(t, src, "add", ".") + testutil.RunGit(t, src, "commit", "-m", "baseline") + head := testutil.RunGit(t, src, "rev-parse", "HEAD") + write("modified", "staged") + testutil.RunGit(t, src, "add", "modified") + write("modified", "unstaged") + if err := os.Remove(filepath.Join(src, "deleted")); err != nil { + t.Fatal(err) + } + testutil.RunGit(t, src, "mv", "renamed", "new-name") + write("added", "staged addition") + testutil.RunGit(t, src, "add", "added") + write("untracked", "new") + write("ignored", "keep") + before := testutil.RunGit(t, src, "status", "--porcelain") + body := `{}` + if dryRun { + body = `{"dryRun":true}` + } + rr := discardRequest(s, body) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rr.Code, rr.Body.String()) + } + after := testutil.RunGit(t, src, "status", "--porcelain") + if dryRun { + if after != before { + t.Fatalf("dry run changed status: %q -> %q", before, after) + } + if content, err := os.ReadFile(filepath.Join(src, "modified")); err != nil || string(content) != "unstaged" { + t.Fatalf("dry run changed file: %q, %v", content, err) + } + } else { + if after != "" { + t.Fatalf("working tree still dirty: %q", after) + } + for _, name := range []string{"modified", "deleted", "renamed"} { + content, err := os.ReadFile(filepath.Join(src, name)) + if err != nil || string(content) != "ignored\n" { + t.Fatalf("%s not restored: %q, %v", name, content, err) + } + } + for _, name := range []string{"added", "untracked", "new-name"} { + if _, err := os.Stat(filepath.Join(src, name)); !os.IsNotExist(err) { + t.Fatalf("%s was not removed: %v", name, err) + } + } + } + if got := testutil.RunGit(t, src, "rev-parse", "HEAD"); got != head { + t.Fatalf("HEAD changed: %s -> %s", head, got) + } + if content, err := os.ReadFile(filepath.Join(src, "ignored")); err != nil || string(content) != "keep" { + t.Fatalf("ignored file changed: %q, %v", content, err) + } + }) + } +} + +func TestHandleGitDiscard_EmptyCommitAndCleanTree(t *testing.T) { + s, src := newTestServer(t) + initServerGitRepo(t, src) + addSkill(t, src, "untracked-skill") + for i := 0; i < 2; i++ { + rr := discardRequest(s, `{}`) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rr.Code, rr.Body.String()) + } + if got := testutil.RunGit(t, src, "status", "--porcelain"); got != "" { + t.Fatalf("working tree still dirty: %s", got) + } + } +} + +func TestHandleGitDiscard_KeepsLocallyIgnoredFiles(t *testing.T) { + s, src := newTestServer(t) + initServerGitRepo(t, src) + ignorePath := filepath.Join(src, ".gitignore") + if err := os.WriteFile(ignorePath, []byte("\n"), 0o644); err != nil { + t.Fatal(err) + } + testutil.RunGit(t, src, "add", ".gitignore") + testutil.RunGit(t, src, "commit", "-m", "ignore baseline") + if err := os.WriteFile(ignorePath, []byte("keep\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(src, "keep"), []byte("local ignored file"), 0o644); err != nil { + t.Fatal(err) + } + rr := discardRequest(s, `{}`) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rr.Code, rr.Body.String()) + } + if content, err := os.ReadFile(filepath.Join(src, "keep")); err != nil || string(content) != "local ignored file" { + t.Fatalf("ignored file lost: %q, %v", content, err) + } + if content, err := os.ReadFile(ignorePath); err != nil || string(content) != "\n" { + t.Fatalf(".gitignore not restored: %q, %v", content, err) + } +} + +func TestHandleGitDiscard_RootPreservesConfigAndNestedRepo(t *testing.T) { + s, src := newTestServer(t) + setServerGitRoot(t, "root", src) + root := config.BaseDir() + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("SKILLSHARE_CONFIG", filepath.Join(root, "config.yaml")) + src = filepath.Join(root, "skills") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + setServerGitRoot(t, "root", src) + initServerGitRepo(t, root) + testutil.RunGit(t, root, "add", "config.yaml") + testutil.RunGit(t, root, "commit", "-m", "tracked config") + setServerGitRoot(t, "root", src) + f, err := os.OpenFile(config.ConfigPath(), os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + t.Fatal(err) + } + _, _ = f.WriteString("# keep local config\n") + _ = f.Close() + before, _ := os.ReadFile(config.ConfigPath()) + initServerGitRepo(t, src) + addSkill(t, src, "nested-skill") + rr := discardRequest(s, `{}`) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rr.Code, rr.Body.String()) + } + after, err := os.ReadFile(config.ConfigPath()) + if err != nil || string(before) != string(after) { + t.Fatalf("config changed: %v", err) + } + if _, err := os.Stat(filepath.Join(src, "nested-skill", "SKILL.md")); err != nil { + t.Fatalf("nested repo file lost: %v", err) + } +} + +func TestHandleGitDiscard_RejectsUnsafeSource(t *testing.T) { + for _, scenario := range []string{"not a repo", "ancestor repo", "no commits", "project mode", "invalid scope", "invalid JSON"} { + t.Run(scenario, func(t *testing.T) { + s, src := newTestServer(t) + body := `{}` + switch scenario { + case "ancestor repo": + initServerGitRepo(t, filepath.Dir(src)) + case "no commits": + testutil.RunGit(t, src, "init") + case "project mode": + s, _ = newProjectTargetServer(t, nil) + case "invalid scope": + setServerGitRoot(t, "invalid", src) + case "invalid JSON": + body = `{` + } + addSkill(t, src, "keep-skill") + rr := discardRequest(s, body) + if rr.Code != http.StatusBadRequest { + t.Fatalf("status = %d: %s", rr.Code, rr.Body.String()) + } + if _, err := os.Stat(filepath.Join(src, "keep-skill", "SKILL.md")); err != nil { + t.Fatalf("file lost after rejected request: %v", err) + } + }) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 8e8926b0e..26c82afd7 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -579,6 +579,7 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("GET /api/git/branches", s.handleGitBranches) s.mux.HandleFunc("POST /api/git/checkout", s.handleGitCheckout) s.mux.HandleFunc("POST /api/git/commit", s.handleGitCommit) + s.mux.HandleFunc("POST /api/git/discard", s.handleGitDiscard) s.mux.HandleFunc("POST /api/git/absorb-nested", s.handleAbsorbNested) s.mux.HandleFunc("POST /api/push", s.handlePush) s.mux.HandleFunc("POST /api/pull", s.handlePull) diff --git a/ui/src/api/git.ts b/ui/src/api/git.ts index 6690be1b9..3b2813121 100644 --- a/ui/src/api/git.ts +++ b/ui/src/api/git.ts @@ -25,6 +25,11 @@ export const gitApi = { method: 'POST', body: JSON.stringify(opts), }), + gitDiscard: (opts: { dryRun?: boolean }) => + apiFetch('/git/discard', { + method: 'POST', + body: JSON.stringify(opts), + }), push: (opts: { message?: string; dryRun?: boolean }) => apiFetch('/push', { method: 'POST', diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index 3f728d8da..445084cb2 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "Nach einem Denkblock", "hooks.events.workspaceopen": "Wenn ein Arbeitsbereich geöffnet wird", "hooks.events.preinvocation": "Bevor das Modell aufgerufen wird", - "hooks.events.postinvocation": "Nach jedem Modellaufruf" + "hooks.events.postinvocation": "Nach jedem Modellaufruf", + "gitSync.actions.discard": "Änderungen verwerfen", + "gitSync.discard.title": "Alle Änderungen verwerfen?", + "gitSync.discard.message": "Alle nicht committeten Änderungen im Repository {scope} verwerfen? Erfasste Dateien werden auf den letzten Commit zurückgesetzt, nicht erfasste Dateien und Ordner werden gelöscht. Ignorierte Dateien, verschachtelte Repositories und config.yaml im root bleiben erhalten. Dies kann nicht rückgängig gemacht werden.", + "gitSync.discard.preview": "Dry run: Erfasste Dateien würden auf den letzten Commit zurückgesetzt und nicht erfasste Dateien entfernt.", + "gitSync.discard.noCommit": "Erstelle vor dem Verwerfen einen ersten Commit.", + "gitSync.toast.discarded": "Änderungen verworfen" } diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index 7bd5b09c4..3037ab642 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "After a thinking block completes", "hooks.events.workspaceopen": "When a workspace opens", "hooks.events.preinvocation": "Before the model is called", - "hooks.events.postinvocation": "After each model call" + "hooks.events.postinvocation": "After each model call", + "gitSync.actions.discard": "Discard changes", + "gitSync.discard.title": "Discard all changes?", + "gitSync.discard.message": "Discard all uncommitted changes in the {scope} repository? Tracked files will be restored to the last commit, and untracked files and folders will be deleted. Ignored files, nested repositories, and root config.yaml are kept. This cannot be undone.", + "gitSync.discard.preview": "Dry run: would restore tracked files to the last commit and remove untracked files.", + "gitSync.discard.noCommit": "Create a first commit before discarding changes.", + "gitSync.toast.discarded": "Changes discarded" } diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index 3ce7f4b97..b9f4adeae 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "Después de un bloque de razonamiento", "hooks.events.workspaceopen": "Al abrir un espacio de trabajo", "hooks.events.preinvocation": "Antes de llamar al modelo", - "hooks.events.postinvocation": "Después de cada llamada al modelo" + "hooks.events.postinvocation": "Después de cada llamada al modelo", + "gitSync.actions.discard": "Descartar cambios", + "gitSync.discard.title": "¿Descartar todos los cambios?", + "gitSync.discard.message": "¿Descartar todos los cambios sin confirmar del repositorio {scope}? Los archivos rastreados volverán al último commit y los archivos y carpetas no rastreados se eliminarán. Se conservarán los archivos ignorados, los repositorios anidados y config.yaml de root. Esta acción no se puede deshacer.", + "gitSync.discard.preview": "Dry run: se restaurarían los archivos rastreados al último commit y se eliminarían los archivos no rastreados.", + "gitSync.discard.noCommit": "Crea un primer commit antes de descartar cambios.", + "gitSync.toast.discarded": "Cambios descartados" } diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index 4967c0d80..8d30e52d6 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "پس از پایان بخش تفکر", "hooks.events.workspaceopen": "هنگام باز شدن فضای کار", "hooks.events.preinvocation": "پیش از فراخوانی مدل", - "hooks.events.postinvocation": "پس از هر فراخوانی مدل" + "hooks.events.postinvocation": "پس از هر فراخوانی مدل", + "gitSync.actions.discard": "حذف تغییرات", + "gitSync.discard.title": "همه تغییرات حذف شوند؟", + "gitSync.discard.message": "همه تغییرات commit نشده در مخزن {scope} حذف شوند؟ فایل‌های ردیابی‌شده به آخرین commit برمی‌گردند و فایل‌ها و پوشه‌های ردیابی‌نشده حذف می‌شوند. فایل‌های نادیده‌گرفته‌شده، مخزن‌های تو در تو و config.yaml در root حفظ می‌شوند. این عمل قابل بازگشت نیست.", + "gitSync.discard.preview": "Dry run: فایل‌های ردیابی‌شده به آخرین commit بازمی‌گردند و فایل‌های ردیابی‌نشده حذف می‌شوند.", + "gitSync.discard.noCommit": "پیش از حذف تغییرات، اولین commit را ایجاد کنید.", + "gitSync.toast.discarded": "تغییرات حذف شدند" } diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index 5f9d16623..1f38b59de 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "Après un bloc de réflexion", "hooks.events.workspaceopen": "À l'ouverture d'un espace de travail", "hooks.events.preinvocation": "Avant l'appel au modèle", - "hooks.events.postinvocation": "Après chaque appel au modèle" + "hooks.events.postinvocation": "Après chaque appel au modèle", + "gitSync.actions.discard": "Abandonner les modifications", + "gitSync.discard.title": "Abandonner toutes les modifications ?", + "gitSync.discard.message": "Abandonner toutes les modifications non committées du dépôt {scope} ? Les fichiers suivis seront restaurés au dernier commit et les fichiers et dossiers non suivis seront supprimés. Les fichiers ignorés, les dépôts imbriqués et config.yaml de root seront conservés. Cette action est irréversible.", + "gitSync.discard.preview": "Dry run : les fichiers suivis seraient restaurés au dernier commit et les fichiers non suivis seraient supprimés.", + "gitSync.discard.noCommit": "Créez un premier commit avant d’abandonner les modifications.", + "gitSync.toast.discarded": "Modifications abandonnées" } diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index 02adf5a03..c9a6bce19 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "Setelah blok pemikiran selesai", "hooks.events.workspaceopen": "Saat ruang kerja dibuka", "hooks.events.preinvocation": "Sebelum model dipanggil", - "hooks.events.postinvocation": "Setelah setiap panggilan model" + "hooks.events.postinvocation": "Setelah setiap panggilan model", + "gitSync.actions.discard": "Buang perubahan", + "gitSync.discard.title": "Buang semua perubahan?", + "gitSync.discard.message": "Buang semua perubahan yang belum di-commit di repositori {scope}? File yang dilacak akan dipulihkan ke commit terakhir, dan file serta folder yang tidak dilacak akan dihapus. File yang diabaikan, repositori bersarang, dan config.yaml di root tetap disimpan. Tindakan ini tidak dapat dibatalkan.", + "gitSync.discard.preview": "Dry run: akan memulihkan file yang dilacak ke commit terakhir dan menghapus file yang tidak dilacak.", + "gitSync.discard.noCommit": "Buat commit pertama sebelum membuang perubahan.", + "gitSync.toast.discarded": "Perubahan dibuang" } diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index d2a0898e1..b7ae013c7 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "思考ブロックの完了後", "hooks.events.workspaceopen": "ワークスペースを開いたとき", "hooks.events.preinvocation": "モデルを呼び出す前", - "hooks.events.postinvocation": "各モデル呼び出しの後" + "hooks.events.postinvocation": "各モデル呼び出しの後", + "gitSync.actions.discard": "変更を破棄", + "gitSync.discard.title": "すべての変更を破棄しますか?", + "gitSync.discard.message": "{scope} リポジトリの未コミットの変更をすべて破棄しますか?追跡中のファイルは最後のコミットに戻り、未追跡のファイルとフォルダーは削除されます。無視されたファイル、ネストしたリポジトリ、root の config.yaml は保持されます。この操作は元に戻せません。", + "gitSync.discard.preview": "Dry run: 追跡中のファイルを最後のコミットに戻し、未追跡のファイルを削除します。", + "gitSync.discard.noCommit": "変更を破棄する前に最初のコミットを作成してください。", + "gitSync.toast.discarded": "変更を破棄しました" } diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index ec7719fb6..4c385b982 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "생각 블록이 끝난 후", "hooks.events.workspaceopen": "작업 공간을 열 때", "hooks.events.preinvocation": "모델을 호출하기 전", - "hooks.events.postinvocation": "모델 호출이 끝날 때마다" + "hooks.events.postinvocation": "모델 호출이 끝날 때마다", + "gitSync.actions.discard": "변경 사항 버리기", + "gitSync.discard.title": "모든 변경 사항을 버릴까요?", + "gitSync.discard.message": "{scope} 저장소의 커밋되지 않은 모든 변경 사항을 버릴까요? 추적 중인 파일은 마지막 커밋으로 복원되고, 추적되지 않은 파일과 폴더는 삭제됩니다. 무시된 파일, 중첩 저장소 및 root의 config.yaml은 유지됩니다. 이 작업은 되돌릴 수 없습니다.", + "gitSync.discard.preview": "Dry run: 추적 중인 파일을 마지막 커밋으로 복원하고 추적되지 않은 파일을 삭제합니다.", + "gitSync.discard.noCommit": "변경 사항을 버리기 전에 첫 번째 커밋을 만드세요.", + "gitSync.toast.discarded": "변경 사항을 버렸습니다" } diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index 92376af31..1852ebcf8 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "Depois de um bloco de raciocínio", "hooks.events.workspaceopen": "Ao abrir um espaço de trabalho", "hooks.events.preinvocation": "Antes de chamar o modelo", - "hooks.events.postinvocation": "Depois de cada chamada ao modelo" + "hooks.events.postinvocation": "Depois de cada chamada ao modelo", + "gitSync.actions.discard": "Descartar alterações", + "gitSync.discard.title": "Descartar todas as alterações?", + "gitSync.discard.message": "Descartar todas as alterações não commitadas no repositório {scope}? Os arquivos rastreados serão restaurados ao último commit, e os arquivos e pastas não rastreados serão excluídos. Arquivos ignorados, repositórios aninhados e config.yaml de root serão mantidos. Esta ação não pode ser desfeita.", + "gitSync.discard.preview": "Dry run: restauraria os arquivos rastreados ao último commit e removeria os arquivos não rastreados.", + "gitSync.discard.noCommit": "Crie um primeiro commit antes de descartar alterações.", + "gitSync.toast.discarded": "Alterações descartadas" } diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index 9e5ecba68..f15fd61ac 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "思考段落完成后", "hooks.events.workspaceopen": "打开工作区时", "hooks.events.preinvocation": "调用模型前", - "hooks.events.postinvocation": "每次调用模型后" + "hooks.events.postinvocation": "每次调用模型后", + "gitSync.actions.discard": "放弃更改", + "gitSync.discard.title": "放弃所有更改?", + "gitSync.discard.message": "要放弃 {scope} 仓库中所有尚未 commit 的更改吗?已跟踪的文件会恢复至最后一次 commit,未跟踪的文件和文件夹会被删除。忽略的文件、嵌套仓库及 root 的 config.yaml 会保留。此操作无法撤销。", + "gitSync.discard.preview": "Dry run:将恢复已跟踪的文件至最后一次 commit,并删除未跟踪的文件。", + "gitSync.discard.noCommit": "请先创建第一个 commit,才能放弃更改。", + "gitSync.toast.discarded": "已放弃更改" } diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 57db065e9..c57445ae9 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -2734,5 +2734,11 @@ "hooks.events.afteragentthought": "思考段落完成後", "hooks.events.workspaceopen": "開啟工作區時", "hooks.events.preinvocation": "呼叫模型前", - "hooks.events.postinvocation": "每次呼叫模型後" + "hooks.events.postinvocation": "每次呼叫模型後", + "gitSync.actions.discard": "捨棄變更", + "gitSync.discard.title": "捨棄所有變更?", + "gitSync.discard.message": "要捨棄 {scope} 儲存庫中所有尚未 commit 的變更嗎?已追蹤的檔案會還原至最後一次 commit,未追蹤的檔案與資料夾會被刪除。忽略的檔案、巢狀儲存庫與 root 的 config.yaml 會保留。此操作無法復原。", + "gitSync.discard.preview": "Dry run:將還原已追蹤的檔案至最後一次 commit,並刪除未追蹤的檔案。", + "gitSync.discard.noCommit": "請先建立第一個 commit,才能捨棄變更。", + "gitSync.toast.discarded": "已捨棄變更" } diff --git a/ui/src/pages/GitSyncPage.test.tsx b/ui/src/pages/GitSyncPage.test.tsx new file mode 100644 index 000000000..3807f1485 --- /dev/null +++ b/ui/src/pages/GitSyncPage.test.tsx @@ -0,0 +1,93 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { api, type GitStatus } from '../api/client'; +import { ToastProvider } from '../components/Toast'; +import { I18nProvider } from '../i18n'; +import GitSyncPage from './GitSyncPage'; + +vi.mock('../context/AppContext', () => ({ useAppContext: () => ({ isProjectMode: false }) })); +vi.mock('../api/client', async (load) => { + const actual = await load(); + return { ...actual, api: { ...actual.api, gitStatus: vi.fn(), gitBranches: vi.fn(), gitDiscard: vi.fn() } }; +}); + +const status: GitStatus = { + gitInstalled: true, isRepo: true, hasRemote: false, branch: 'main', isDirty: true, + files: [' M .metadata.json', '?? new-skill/'], sourceDir: '/source', scope: 'skills', + scopeMismatch: false, headHash: 'abc123', ahead: 0, behind: 0, nestedRepos: [], configTracked: false, +}; + +function mount() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + + + , + ); + return client; +} + +beforeEach(() => { + vi.clearAllMocks(); + localStorage.setItem('skillshare:locale', 'en'); + vi.mocked(api.gitStatus).mockResolvedValue(status); + vi.mocked(api.gitBranches).mockResolvedValue({ current: 'main', local: ['main'], remote: [], isDirty: true, dirtyFiles: status.files }); + vi.mocked(api.gitDiscard).mockResolvedValue({ success: true, message: 'changes discarded' }); +}); + +describe('discard changes', () => { + it('requires confirmation, supports cancel, and refreshes after discarding', async () => { + const client = mount(); + fireEvent.click(await screen.findByRole('button', { name: 'Discard changes' })); + const dialog = screen.getByRole('dialog', { name: 'Discard all changes?' }); + expect(within(dialog).getByText(/untracked files and folders will be deleted/)).toBeTruthy(); + expect(api.gitDiscard).not.toHaveBeenCalled(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(api.gitDiscard).not.toHaveBeenCalled(); + + const invalidate = vi.spyOn(client, 'invalidateQueries'); + vi.mocked(api.gitDiscard).mockImplementation(async () => { + vi.mocked(api.gitStatus).mockResolvedValue({ ...status, isDirty: false, files: [] }); + return { success: true, message: 'changes discarded' }; + }); + fireEvent.click(screen.getByRole('button', { name: 'Discard changes' })); + fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Discard changes' })); + await waitFor(() => expect(api.gitDiscard).toHaveBeenCalledWith({ dryRun: false })); + expect(await screen.findByText('Changes discarded')).toBeTruthy(); + await waitFor(() => expect(screen.queryByRole('button', { name: 'Discard changes' })).toBeNull()); + expect(invalidate).toHaveBeenCalledWith(); + }); + + it('previews without opening the destructive confirmation when dry run is on', async () => { + mount(); + const button = await screen.findByRole('button', { name: 'Discard changes' }); + fireEvent.click(screen.getByRole('switch', { name: 'Dry run' })); + fireEvent.click(button); + await waitFor(() => expect(api.gitDiscard).toHaveBeenCalledWith({ dryRun: true })); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(await screen.findByText(/Dry run: would restore/)).toBeTruthy(); + }); + + it('shows failure and leaves the changes available to retry', async () => { + vi.mocked(api.gitDiscard).mockRejectedValue(new Error('permission denied')); + mount(); + fireEvent.click(await screen.findByRole('button', { name: 'Discard changes' })); + fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Discard changes' })); + expect(await screen.findByText('permission denied')).toBeTruthy(); + expect(screen.queryByRole('dialog')).toBeNull(); + expect((screen.getByRole('button', { name: 'Discard changes' }) as HTMLButtonElement).disabled).toBe(false); + }); + + it('disables discard before the first commit', async () => { + vi.mocked(api.gitStatus).mockResolvedValue({ ...status, headHash: undefined }); + mount(); + const button = await screen.findByRole('button', { name: 'Discard changes' }); + expect((button as HTMLButtonElement).disabled).toBe(true); + expect(api.gitDiscard).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/pages/GitSyncPage.tsx b/ui/src/pages/GitSyncPage.tsx index 63ef59aad..e091da85b 100644 --- a/ui/src/pages/GitSyncPage.tsx +++ b/ui/src/pages/GitSyncPage.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { AlertCircle, AlertTriangle, ArrowDownToLine, ArrowUpFromLine, CircleCheck, CloudUpload, ExternalLink, FolderGit2, GitBranch, GitCommitHorizontal, Info, RefreshCw, X } from 'lucide-react'; +import { AlertCircle, AlertTriangle, ArrowDownToLine, ArrowUpFromLine, CircleCheck, CloudUpload, ExternalLink, FolderGit2, GitBranch, GitCommitHorizontal, Info, RefreshCw, Undo2, X } from 'lucide-react'; import { api, ApiError, type GitStatus, type PullResponse } from '../api/client'; import Button from '../components/Button'; import ConfirmDialog from '../components/ConfirmDialog'; @@ -46,7 +46,7 @@ export default function GitSyncPage() { const [message, setMessage] = useState(''); const [dryRun, setDryRun] = useState(false); - const [busy, setBusy] = useState<'commit' | 'push' | 'upload' | 'pull' | 'branch' | 'fetch' | 'nested' | 'scope' | null>(null); + const [busy, setBusy] = useState<'commit' | 'push' | 'upload' | 'pull' | 'branch' | 'fetch' | 'nested' | 'scope' | 'discard' | null>(null); const [runError, setRunError] = useState(''); // A first pull whose history cannot merge; the error note then offers a force pull. const [mergeFailed, setMergeFailed] = useState(false); @@ -55,6 +55,7 @@ export default function GitSyncPage() { // The source folder a pull could not write into; set with a permission error. const [lockedPath, setLockedPath] = useState(''); const [confirmForce, setConfirmForce] = useState(false); + const [confirmDiscard, setConfirmDiscard] = useState(false); const [note, setNote] = useState(''); const [pulled, setPulled] = useState(null); const [setup, setSetup] = useState(null); @@ -91,6 +92,14 @@ export default function GitSyncPage() { setMessage(''); toast(t(push ? 'gitSync.toast.pushed' : 'gitSync.toast.committed'), 'success'); }); + const discard = () => run('discard', async () => { + await api.gitDiscard({ dryRun }); + if (dryRun) return setNote(t('gitSync.discard.preview')); + setPulled(null); + // Root scope can change any of the source resources shown elsewhere. + void queryClient.invalidateQueries(); + toast(t('gitSync.toast.discarded'), 'success'); + }); // A clean tree with commits the remote lacks: push them as they are. const upload = (count: number) => run('upload', async () => { await api.push({}); @@ -235,6 +244,12 @@ export default function GitSyncPage() {

{t('gitSync.changes.title')}

{files.length} + {status.isDirty && ( + + )}
{files.length === 0 ? ( @@ -341,6 +356,17 @@ export default function GitSyncPage() {
)} + setConfirmDiscard(false)} + onConfirm={() => { setConfirmDiscard(false); void discard(); }} + /> +