mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
feat(ui): add Git Sync discard changes
Let users discard uncommitted source changes after confirmation, with dry-run support. Restore tracked files to HEAD and remove untracked files while preserving ignored files, nested repositories, and root-scope config.yaml. Guard against ancestor repositories and repositories without a first commit. Cover the API and confirmation flow with regression tests and sync all UI locales and Git Sync documentation.
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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"})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -25,6 +25,11 @@ export const gitApi = {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
gitDiscard: (opts: { dryRun?: boolean }) =>
|
||||
apiFetch<PushResponse>('/git/discard', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
}),
|
||||
push: (opts: { message?: string; dryRun?: boolean }) =>
|
||||
apiFetch<PushResponse>('/push', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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": "تغییرات حذف شدند"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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": "変更を破棄しました"
|
||||
}
|
||||
|
||||
@@ -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": "변경 사항을 버렸습니다"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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": "已放弃更改"
|
||||
}
|
||||
|
||||
@@ -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": "已捨棄變更"
|
||||
}
|
||||
|
||||
@@ -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<typeof import('../api/client')>();
|
||||
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(
|
||||
<MemoryRouter>
|
||||
<QueryClientProvider client={client}>
|
||||
<I18nProvider><ToastProvider><GitSyncPage /></ToastProvider></I18nProvider>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<PullResponse | null>(null);
|
||||
const [setup, setSetup] = useState<Setup | null>(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() {
|
||||
<div className="ss-sec !mb-0">
|
||||
<h2 className="ss-h2">{t('gitSync.changes.title')}</h2>
|
||||
<span className="ss-cnt">{files.length}</span>
|
||||
{status.isDirty && (
|
||||
<Button variant="ghost" size="sm" className="ml-auto" onClick={() => dryRun ? void discard() : setConfirmDiscard(true)} loading={busy === 'discard'} disabled={writing || !status.headHash} title={!status.headHash ? t('gitSync.discard.noCommit') : undefined}>
|
||||
{busy !== 'discard' && <Undo2 size={16} />}
|
||||
{t('gitSync.actions.discard')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="ss-list">
|
||||
{files.length === 0 ? (
|
||||
@@ -341,6 +356,17 @@ export default function GitSyncPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmDiscard}
|
||||
variant="danger"
|
||||
title={t('gitSync.discard.title')}
|
||||
message={t('gitSync.discard.message', { scope })}
|
||||
confirmText={t('gitSync.actions.discard')}
|
||||
loading={busy === 'discard'}
|
||||
onCancel={() => setConfirmDiscard(false)}
|
||||
onConfirm={() => { setConfirmDiscard(false); void discard(); }}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmForce}
|
||||
variant="danger"
|
||||
|
||||
@@ -99,6 +99,8 @@ Some pages show a count in the sidebar when they need attention. The counts refr
|
||||
| **Audit** | Security scan of skills and agents, with findings by severity. The **Rules** tab browses every rule by category: switch one off, change its severity, apply a severity to a whole category, pick the scan profile (`default`, `strict`, `permissive`), or open the editor for custom `audit-rules.yaml` |
|
||||
| **Settings** | Tabbed: **General** (source paths, sync mode, appearance), **Backup** (target folder snapshots, earlier versions of files such as `AGENTS.md`, and MCP config backups; see [`backup`](./backup.md#dashboard)), **Log** (operation history), **Health** (the same checks as [`doctor`](/docs/reference/commands/doctor)), **Extensions** (sync-time file transforms), **Files** (direct editors for `config.yaml`, `.skillignore`, and `.agentignore`) |
|
||||
|
||||
**Discard changes** beside the change list restores all tracked files and the index in the selected Git scope to the last commit and deletes untracked files and folders, after confirmation. Ignored files, nested Git repositories, and root-scope `config.yaml` are kept. It does not change commits or push; the action cannot be undone. **Dry run** previews without changing files. A first commit is required.
|
||||
|
||||
On the **Updates** tab, a progress bar tracks the update run and the active row is marked while it updates. Blocked or failed updates appear in a separate section.
|
||||
|
||||
Old links such as `/collect`, `/install`, `/search`, `/trash`, `/analyze`, `/backup`, `/log`, and `/doctor` redirect to their new place.
|
||||
@@ -160,6 +162,7 @@ The web dashboard exposes a REST API at `/api/`. All endpoints return JSON.
|
||||
| DELETE | `/api/targets/{name}` | Remove a target |
|
||||
| POST | `/api/sync` | Run sync (supports `dryRun`, `force`, `kind`, and `project`, a declared project root that limits the sync to that project's targets). Backs up targets first unless `dryRun` is set |
|
||||
| POST | `/api/git/commit` | Create a local git commit from the source repo without pushing |
|
||||
| POST | `/api/git/discard` | Discard uncommitted changes in the configured Git scope (global mode only; requires a first commit). Supports `dryRun`. Keeps ignored files, nested Git repositories, and root-scope `config.yaml` |
|
||||
| GET | `/api/git/status` | Source repo status, including commits not pushed yet (`ahead`) and upstream commits not pulled yet as of the last fetch (`behind`). Never fetches |
|
||||
| POST | `/api/push` | Commit any changes, then push. Sets the upstream on the first push. When the remote has commits this repo lacks, it fails with `409` and error code `push_rejected`; pull, then push again |
|
||||
| POST | `/api/pull` | Pull, then sync what the repo scope holds. Diverged history is merged; `.metadata.json` conflicts resolve automatically, and any other conflict fails with the merge undone. When a first pull can't merge, it fails with error code `merge_failed`; retry with `force: true` to replace local files with the remote branch |
|
||||
|
||||
@@ -99,6 +99,8 @@ skillshare ui start --clear-cache
|
||||
| **Audit** | Skill と Agent のセキュリティスキャン。重大度別の検出結果を表示。**Rules** タブでは、カテゴリごとにすべてのルールを閲覧できる: ルールをオフにする、重大度を変更する、カテゴリ全体に重大度を適用する、スキャンプロファイル(`default`、`strict`、`permissive`)を選ぶ、カスタム `audit-rules.yaml` のエディタを開く、のいずれかができる |
|
||||
| **Settings** | タブ分け: **General**(Source パス、sync モード、外観)、**Backup**(Target フォルダのスナップショット、`AGENTS.md` などのファイルの以前のバージョン、MCP 設定のバックアップ。[`backup`](./backup.md#dashboard) を参照)、**Log**(操作履歴)、**Health**([`doctor`](/docs/reference/commands/doctor) と同じチェック)、**Extensions**(sync 時のファイル変換)、**Files**(`config.yaml`、`.skillignore`、`.agentignore` の直接編集) |
|
||||
|
||||
変更一覧の横の **Discard changes** は、確認後に選択した Git scope の追跡中のファイルと index を最後の commit に戻し、未追跡のファイルとフォルダーを削除します。無視されたファイル、ネストした Git repositories、root scope の `config.yaml` は保持されます。commit の変更や push は行わず、この操作は元に戻せません。**Dry run** はファイルを変更せずプレビューします。最初の commit が必要です。
|
||||
|
||||
**Updates** タブでは、プログレスバーに更新の進行状況が表示され、更新中の行が示されます。ブロックされた更新や失敗した更新は別のセクションに表示されます。
|
||||
|
||||
`/collect`、`/install`、`/search`、`/trash`、`/analyze`、`/backup`、`/log`、`/doctor` などの古いリンクは、新しい場所にリダイレクトされます。
|
||||
@@ -160,6 +162,7 @@ Web ダッシュボードは `/api/` に REST API を公開しています。す
|
||||
| DELETE | `/api/targets/{name}` | Target を削除 |
|
||||
| POST | `/api/sync` | sync を実行(`dryRun`、`force`、`kind`、`project` に対応。`project` は宣言済みの project ルートで、sync をその project の Target に限定する)。`dryRun` が指定されていない限り、まず Target をバックアップする |
|
||||
| POST | `/api/git/commit` | Source リポジトリからプッシュせずにローカル git commit を作成 |
|
||||
| POST | `/api/git/discard` | 設定された Git scope の未 commit の変更を破棄(global mode のみ、最初の commit が必要)。`dryRun` に対応。無視されたファイル、ネストした Git repositories、root scope の `config.yaml` を保持 |
|
||||
| GET | `/api/git/status` | まだプッシュされていないコミット(`ahead`)と、最後の fetch 時点でまだプルしていない upstream のコミット(`behind`)を含む、Source リポジトリの状態。fetch は行わない |
|
||||
| POST | `/api/push` | 変更をコミットしてからプッシュ。初回プッシュ時は upstream を設定する。remote にこのリポジトリにないコミットがある場合、`409` とエラーコード `push_rejected` で失敗する。プルしてから再度プッシュする |
|
||||
| POST | `/api/pull` | プルしてから、リポジトリのスコープが保持するものを sync する。分岐した履歴はマージされる。`.metadata.json` の競合は自動で解決され、それ以外の競合ではマージを取り消して失敗する。最初のプルがマージできない場合、エラーコード `merge_failed` で失敗する。`force: true` で再試行すると、remote ブランチでローカルファイルを置き換える |
|
||||
|
||||
@@ -99,6 +99,8 @@ skillshare ui start --clear-cache
|
||||
| **Audit** | skill과 agent에 대한 보안 스캔이며, 심각도별로 findings를 표시합니다. **Rules** 탭에서는 카테고리별로 모든 rule을 탐색할 수 있습니다: rule을 끄거나, 심각도를 변경하거나, 카테고리 전체에 심각도를 적용하거나, 스캔 profile(`default`, `strict`, `permissive`)을 선택하거나, 사용자 지정 `audit-rules.yaml` 편집기를 엽니다 |
|
||||
| **Settings** | 탭으로 구성: **General**(source 경로, sync mode, 외관), **Backup**(대상 폴더 스냅샷, `AGENTS.md` 같은 파일의 이전 버전, MCP 설정 백업. [`backup`](./backup.md#dashboard) 참고), **Log**(작업 이력), **Health**([`doctor`](/docs/reference/commands/doctor)와 동일한 검사), **Extensions**(sync 시점의 파일 변환), **Files**(`config.yaml`, `.skillignore`, `.agentignore`를 위한 직접 편집기) |
|
||||
|
||||
변경 목록 옆의 **Discard changes**는 확인 후 선택한 Git scope의 추적 중인 파일과 index를 마지막 commit으로 복원하고 추적되지 않은 파일과 폴더를 삭제합니다. 무시된 파일, 중첩 Git repositories 및 root scope의 `config.yaml`은 유지됩니다. commit을 변경하거나 push하지 않으며, 이 작업은 되돌릴 수 없습니다. **Dry run**은 파일을 변경하지 않고 미리 봅니다. 첫 번째 commit이 필요합니다.
|
||||
|
||||
**Updates** 탭의 진행률 표시줄은 업데이트 진행 상황을 보여 주며 업데이트 중인 행도 표시됩니다. 차단되거나 실패한 업데이트는 별도 섹션에 표시됩니다.
|
||||
|
||||
`/collect`, `/install`, `/search`, `/trash`, `/analyze`, `/backup`, `/log`, `/doctor`와 같은 이전 링크는 새 위치로 리디렉션됩니다.
|
||||
@@ -160,6 +162,7 @@ project mode(`-p`)로 실행할 때 대시보드는 다음과 같이 달라집
|
||||
| DELETE | `/api/targets/{name}` | target 제거 |
|
||||
| POST | `/api/sync` | sync 실행(`dryRun`, `force`, `kind`, 그리고 sync를 해당 프로젝트의 target으로 제한하는 선언된 프로젝트 루트인 `project` 지원). `dryRun`이 설정되지 않은 한 먼저 target을 백업합니다 |
|
||||
| POST | `/api/git/commit` | push 없이 source repo에서 로컬 git commit 생성 |
|
||||
| POST | `/api/git/discard` | 설정된 Git scope의 commit되지 않은 변경 사항을 버립니다(global mode 전용, 첫 번째 commit 필요). `dryRun`을 지원합니다. 무시된 파일, 중첩 Git repositories 및 root scope의 `config.yaml`을 유지합니다 |
|
||||
| GET | `/api/git/status` | 아직 push되지 않은 커밋(`ahead`)과 마지막 fetch 기준으로 아직 pull하지 않은 upstream 커밋(`behind`)을 포함한 source repo 상태. fetch는 하지 않습니다 |
|
||||
| POST | `/api/push` | 변경 사항을 commit한 후 push합니다. 첫 push 시 upstream을 설정합니다. remote에 이 repo에 없는 커밋이 있으면 `409`와 오류 코드 `push_rejected`로 실패합니다. pull한 후 다시 push하세요 |
|
||||
| POST | `/api/pull` | pull한 후 repo scope가 담고 있는 것을 sync합니다. 갈라진 히스토리는 병합되며, `.metadata.json` 충돌은 자동으로 해결되고, 그 외의 충돌은 병합을 되돌린 채 실패합니다. 첫 pull이 병합에 실패하면 오류 코드 `merge_failed`로 실패합니다. 로컬 파일을 remote 브랜치로 교체하려면 `force: true`로 재시도하세요 |
|
||||
|
||||
@@ -99,6 +99,8 @@ skillshare ui start --clear-cache
|
||||
| **Audit** | 对 skills 和 agents 的安全扫描,按严重程度列出 findings。**Rules** 标签页按类别浏览每一条规则:可以关闭某一条、更改其严重程度、把某个严重程度应用到整个类别、选择扫描 profile(`default`、`strict`、`permissive`),或打开自定义 `audit-rules.yaml` 的编辑器 |
|
||||
| **Settings** | 带标签页:**General**(source 路径、sync 模式、外观)、**Backup**(target 文件夹快照、`AGENTS.md` 等文件的早期版本,以及 MCP 配置备份;参见 [`backup`](./backup.md#dashboard))、**Log**(操作历史)、**Health**(与 [`doctor`](/docs/reference/commands/doctor) 相同的检查)、**Extensions**(同步时的文件转换)、**Files**(`config.yaml`、`.skillignore` 和 `.agentignore` 的直接编辑器) |
|
||||
|
||||
更改列表旁的 **Discard changes** 会在确认后,将所选 Git scope 的所有已跟踪文件和 index 恢复至最后一次 commit,并删除未跟踪的文件和文件夹。忽略的文件、嵌套 Git repositories 和 root scope 的 `config.yaml` 会保留。此操作不会更改 commits 或 push,且无法撤销。**Dry run** 只会预览,不会更改文件。必须先有第一个 commit。
|
||||
|
||||
在 **Updates** 标签页中,进度条会显示更新进度,正在更新的行也会标记出来。被阻止或失败的更新会显示在单独的区域。
|
||||
|
||||
旧链接如 `/collect`、`/install`、`/search`、`/trash`、`/analyze`、`/backup`、`/log` 和 `/doctor` 会重定向到新位置。
|
||||
@@ -160,6 +162,7 @@ web dashboard 在 `/api/` 下暴露一个 REST API。所有端点都返回 JSON
|
||||
| DELETE | `/api/targets/{name}` | 移除一个 target |
|
||||
| POST | `/api/sync` | 运行 sync(支持 `dryRun`、`force`、`kind`,以及 `project`:一个已声明的项目根目录,用于将 sync 限定在该项目的 targets)。除非设置了 `dryRun`,否则会先备份 targets |
|
||||
| POST | `/api/git/commit` | 从 source 仓库创建一个本地 git commit,但不推送 |
|
||||
| POST | `/api/git/discard` | 放弃配置 Git scope 的未 commit 更改(仅 global mode,必须先有第一个 commit)。支持 `dryRun`,保留忽略的文件、嵌套 Git repositories 和 root scope 的 `config.yaml` |
|
||||
| GET | `/api/git/status` | source 仓库状态,包括尚未推送的提交(`ahead`),以及截至上次 fetch 尚未拉取的 upstream 提交(`behind`)。不会执行 fetch |
|
||||
| POST | `/api/push` | 提交任何变更,然后推送。首次推送时会设置 upstream。当 remote 有本仓库没有的提交时,会以 `409` 和错误码 `push_rejected` 失败;先 pull,再重新 push |
|
||||
| POST | `/api/pull` | 拉取,然后同步该仓库 scope 所涵盖的内容。分歧的历史会被合并;`.metadata.json` 的冲突会自动解决,其他冲突会失败并撤销合并。当首次 pull 无法合并时,会以错误码 `merge_failed` 失败;用 `force: true` 重试可用 remote 分支替换本地文件 |
|
||||
|
||||
@@ -99,6 +99,8 @@ skillshare ui start --clear-cache
|
||||
| **Audit** | 對 skills 與 agents 進行安全掃描,依嚴重程度列出發現項目。**Rules** 分頁可依分類瀏覽每一項規則:關閉某項、變更其嚴重程度、對整個分類套用嚴重程度、選擇掃描設定檔(`default`、`strict`、`permissive`),或開啟編輯器自訂 `audit-rules.yaml` |
|
||||
| **Settings** | 分頁式:**General**(source 路徑、同步模式、外觀)、**Backup**(target 資料夾快照、`AGENTS.md` 這類檔案的較早版本,以及 MCP 設定備份;參見 [`backup`](./backup.md#dashboard))、**Log**(操作歷史)、**Health**(與 [`doctor`](/docs/reference/commands/doctor) 相同的檢查)、**Extensions**(同步時的檔案轉換)、**Files**(直接編輯 `config.yaml`、`.skillignore` 與 `.agentignore`) |
|
||||
|
||||
變更清單旁的 **Discard changes** 會在確認後,將所選 Git scope 的所有已追蹤檔案與 index 還原至最後一次 commit,並刪除未追蹤的檔案與資料夾。忽略的檔案、巢狀 Git repositories 與 root scope 的 `config.yaml` 會保留。此操作不會變更 commits 或 push,且無法復原。**Dry run** 只會預覽,不會變更檔案。必須先有第一個 commit。
|
||||
|
||||
在 **Updates** 分頁中,進度列會顯示更新進度,正在更新的列也會標示出來。被阻擋或失敗的更新會顯示在獨立區塊。
|
||||
|
||||
舊連結如 `/collect`、`/install`、`/search`、`/trash`、`/analyze`、`/backup`、`/log` 與 `/doctor` 會重新導向至新的位置。
|
||||
@@ -160,6 +162,7 @@ Web dashboard 在 `/api/` 上提供 REST API。所有端點皆回傳 JSON。
|
||||
| DELETE | `/api/targets/{name}` | 移除一個 target |
|
||||
| POST | `/api/sync` | 執行同步(支援 `dryRun`、`force`、`kind`,以及 `project`:一個已宣告的 project 根目錄,會把同步範圍限定在該 project 的 targets)。除非設定 `dryRun`,否則會先備份 targets |
|
||||
| POST | `/api/git/commit` | 從 source repo 建立本機 git commit,但不 push |
|
||||
| POST | `/api/git/discard` | 捨棄設定 Git scope 的未 commit 變更(僅 global mode,必須先有第一個 commit)。支援 `dryRun`,保留忽略的檔案、巢狀 Git repositories 與 root scope 的 `config.yaml` |
|
||||
| GET | `/api/git/status` | Source repo 狀態,包含尚未 push 的 commits(`ahead`),以及截至上次 fetch 尚未 pull 的 upstream commits(`behind`)。不會執行 fetch |
|
||||
| POST | `/api/push` | Commit 所有變更後再 push。首次 push 時會設定 upstream。當 remote 有這個 repo 沒有的 commits 時,會以 `409` 與錯誤代碼 `push_rejected` 失敗;先 pull 再 push 即可 |
|
||||
| POST | `/api/pull` | Pull 之後同步 repo scope 所涵蓋的內容。已分歧的歷史會被合併;`.metadata.json` 的衝突會自動解決,其他衝突則會失敗並復原 merge。當第一次 pull 無法合併時,會以錯誤代碼 `merge_failed` 失敗;帶 `force: true` 重試可以本機檔案取代 remote 分支 |
|
||||
|
||||
Reference in New Issue
Block a user