From b69cb9166eb5f1a401492f5aa8dcb83cb79170da Mon Sep 17 00:00:00 2001 From: phamnazage-jpg Date: Tue, 2 Jun 2026 06:57:13 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20M-02=20=E6=B7=BB=E5=8A=A0=20errs=20?= =?UTF-8?q?=E5=8C=85=E6=8F=90=E4=BE=9B=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86?= =?UTF-8?q?=E5=9F=BA=E7=A1=80=E8=AE=BE=E6=96=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/errs/common.go | 33 +++++++++++++++++++++++++++++++++ internal/errs/test_helpers.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 internal/errs/common.go create mode 100644 internal/errs/test_helpers.go diff --git a/internal/errs/common.go b/internal/errs/common.go new file mode 100644 index 00000000..e42e3175 --- /dev/null +++ b/internal/errs/common.go @@ -0,0 +1,33 @@ +package errs + +import "errors" + +// 通用错误 +var ( + ErrNotFound = errors.New("not found") + ErrInvalidInput = errors.New("invalid input") + ErrUnauthorized = errors.New("unauthorized") + ErrDuplicate = errors.New("duplicate") +) + +// CLI 错误 +var ( + ErrMissingRequiredFlag = errors.New("missing required flag") + ErrInvalidFlagValue = errors.New("invalid flag value") +) + +// Repository 错误 +var ( + ErrExecFailed = errors.New("database exec failed") + ErrQueryFailed = errors.New("database query failed") +) + +// Overlay 错误 +var ( + ErrOverlayNotMatched = errors.New("overlay did not match") + ErrNestedOutput = errors.New("output directory must not be nested inside source directory") + ErrOutputExists = errors.New("output directory already exists") + ErrSourceNotDir = errors.New("source must be a directory") + ErrPatchFileNotFound = errors.New("patch file not found") + ErrPatchApplyFailed = errors.New("failed to apply patch") +) diff --git a/internal/errs/test_helpers.go b/internal/errs/test_helpers.go new file mode 100644 index 00000000..57f6e109 --- /dev/null +++ b/internal/errs/test_helpers.go @@ -0,0 +1,28 @@ +package errs + +import "testing" + +// AssertErrorContains 检查错误是否包含预期子字符串 +// 用于替代脆弱的直接字符串匹配 +func AssertErrorContains(t *testing.T, err error, wantSubstring string) { + t.Helper() + if err == nil { + t.Fatalf("expected error containing %q, got nil", wantSubstring) + } + if !containsSubstring(err.Error(), wantSubstring) { + t.Fatalf("error = %q, want containing %q", err.Error(), wantSubstring) + } +} + +func containsSubstring(s, substr string) bool { + return len(substr) <= len(s) && containsAt(s, substr, 0) +} + +func containsAt(s, substr string, start int) bool { + for i := start; i <= len(s)-len(substr); i++ { + if s[i:i+len(substr)] == substr { + return true + } + } + return false +}