Add regex command implementation

This commit is contained in:
Rogee
2025-10-31 10:12:02 +08:00
parent a0d7084c28
commit d436970848
55 changed files with 2115 additions and 9 deletions

View File

@@ -0,0 +1,116 @@
package contract
import (
"bytes"
"context"
"io/fs"
"os"
"path/filepath"
"testing"
"github.com/rogeecn/renamer/internal/regex"
)
func TestRegexPreviewUsesCaptureGroups(t *testing.T) {
tmp := t.TempDir()
copyRegexFixture(t, "baseline", tmp)
req := regex.NewRequest(tmp)
req.Pattern = "^(\\w+)-(\\d+)"
req.Template = "@2_@1"
req.IncludeDirectories = false
req.Recursive = false
var buf bytes.Buffer
summary, planned, err := regex.Preview(context.Background(), req, &buf)
if err != nil {
t.Fatalf("regex preview returned error: %v", err)
}
if summary.TotalCandidates != len(summary.Entries) {
t.Fatalf("expected summary entries to equal candidates: %d vs %d", summary.TotalCandidates, len(summary.Entries))
}
expected := map[string]string{
"alpha-123.log": "123_alpha.log",
"beta-456.log": "456_beta.log",
"gamma-789.log": "789_gamma.log",
}
if summary.Changed != len(planned) {
t.Fatalf("expected changed count %d to equal plan length %d", summary.Changed, len(planned))
}
for _, entry := range summary.Entries {
target, ok := expected[filepath.Base(entry.OriginalPath)]
if !ok {
t.Fatalf("unexpected candidate in preview: %s", entry.OriginalPath)
}
if entry.ProposedPath != filepath.Join(filepath.Dir(entry.OriginalPath), target) {
t.Fatalf("expected proposed path %s, got %s", target, entry.ProposedPath)
}
if entry.Status != regex.EntryChanged {
t.Fatalf("expected entry status 'changed', got %s", entry.Status)
}
}
if len(planned) != len(expected) {
t.Fatalf("expected plan length %d, got %d", len(expected), len(planned))
}
for _, plan := range planned {
base := filepath.Base(plan.SourceRelative)
target, ok := expected[base]
if !ok {
t.Fatalf("unexpected plan entry: %s", base)
}
if plan.TargetRelative != filepath.Join(filepath.Dir(plan.SourceRelative), target) {
t.Fatalf("expected planned target %s, got %s", target, plan.TargetRelative)
}
if len(plan.MatchGroups) != 2 {
t.Fatalf("expected 2 match groups in plan, got %d", len(plan.MatchGroups))
}
}
output := buf.String()
for _, target := range expected {
if !bytes.Contains([]byte(output), []byte(target)) {
t.Fatalf("expected preview output to contain %s, got %s", target, output)
}
}
}
func copyRegexFixture(t *testing.T, name, dest string) {
t.Helper()
src := filepath.Join("..", "fixtures", "regex", name)
if err := filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
targetPath := filepath.Join(dest, rel)
if err := os.MkdirAll(filepath.Dir(targetPath), 0o755); err != nil {
return err
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
if err := os.WriteFile(targetPath, content, 0o644); err != nil {
return err
}
return nil
}); err != nil {
t.Fatalf("copy fixture: %v", err)
}
}

View File

@@ -0,0 +1,62 @@
package contract
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"
renamercmd "github.com/rogeecn/renamer/cmd"
"github.com/rogeecn/renamer/internal/history"
)
func TestRegexCommandLedgerMetadata(t *testing.T) {
tmp := t.TempDir()
copyRegexFixture(t, "mixed", tmp)
cmd := renamercmd.NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"regex", "^build_(\\d+)_(.*)$", "release-@1-@2", "--yes", "--path", tmp})
if err := cmd.Execute(); err != nil {
t.Fatalf("regex apply command failed: %v\noutput: %s", err, out.String())
}
ledgerPath := filepath.Join(tmp, ".renamer")
data, err := os.ReadFile(ledgerPath)
if err != nil {
t.Fatalf("read ledger: %v", err)
}
lines := bytes.Split(bytes.TrimSpace(data), []byte("\n"))
if len(lines) == 0 {
t.Fatalf("expected ledger entries written")
}
var entry history.Entry
if err := json.Unmarshal(lines[len(lines)-1], &entry); err != nil {
t.Fatalf("decode ledger entry: %v", err)
}
if entry.Command != "regex" {
t.Fatalf("expected regex command recorded, got %q", entry.Command)
}
if entry.Metadata["pattern"] != "^build_(\\d+)_(.*)$" {
t.Fatalf("unexpected pattern metadata: %#v", entry.Metadata["pattern"])
}
if entry.Metadata["template"] != "release-@1-@2" {
t.Fatalf("unexpected template metadata: %#v", entry.Metadata["template"])
}
if toFloat(entry.Metadata["matched"]) != 2 || toFloat(entry.Metadata["changed"]) != 2 {
t.Fatalf("unexpected match/change counts: %#v", entry.Metadata)
}
if len(entry.Operations) != 2 {
t.Fatalf("expected 2 operations, got %d", len(entry.Operations))
}
}

View File

@@ -0,0 +1,45 @@
package contract
import (
"context"
"testing"
"github.com/rogeecn/renamer/internal/regex"
)
func TestRegexTemplateRejectsUndefinedGroup(t *testing.T) {
req := regex.NewRequest(t.TempDir())
req.Pattern = "^(\\w+)-(\\d+)"
req.Template = "@3"
_, _, err := regex.Preview(context.Background(), req, nil)
if err == nil {
t.Fatalf("expected error for undefined capture group")
}
}
func TestRegexPreviewHandlesInvalidPattern(t *testing.T) {
req := regex.NewRequest(t.TempDir())
req.Pattern = "(([" // invalid pattern
req.Template = "@1"
_, _, err := regex.Preview(context.Background(), req, nil)
if err == nil {
t.Fatalf("expected error for invalid pattern")
}
}
func TestRegexPreviewSkipsUnmatchedOptionalGroup(t *testing.T) {
req := regex.NewRequest(t.TempDir())
req.Pattern = "^(\\w+)(?:-(\\d+))?"
req.Template = "@1_@2"
summary, _, err := regex.Preview(context.Background(), req, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if summary.TotalCandidates != 0 {
t.Fatalf("expected no candidates without files, got %d", summary.TotalCandidates)
}
}

14
tests/fixtures/regex/README.md vendored Normal file
View File

@@ -0,0 +1,14 @@
# Regex Command Fixtures
These fixtures support contract and integration testing for the `renamer regex` command. Each
subdirectory contains representative filenames used across preview, apply, conflict, and
validation scenarios.
- `baseline/` — ASCII word + digit combinations (e.g., `alpha-123.log`) used to validate basic
capture group substitution.
- `unicode/` — Multilingual filenames to verify RE2 Unicode handling and ledger persistence.
- `mixed/` — Build-style artifacts with underscores/dashes for automation-style rename flows.
- `case-fold/` — Differing only by case to simulate case-insensitive duplicate conflicts.
Tests should copy these directories to temporary working paths before mutation to keep fixtures
idempotent.

View File

@@ -0,0 +1 @@
baseline fixture alpha-123

View File

@@ -0,0 +1 @@
baseline fixture beta-456

View File

@@ -0,0 +1 @@
test fixture gamma-789

View File

@@ -0,0 +1 @@
case fold fixture upper sample

View File

@@ -0,0 +1 @@
case fold fixture upper-lower sample

View File

@@ -0,0 +1 @@
case fold fixture lower sample

View File

@@ -0,0 +1 @@
placeholder archive fixture 101

View File

@@ -0,0 +1 @@
placeholder archive fixture 102

View File

@@ -0,0 +1 @@
feature demo placeholder file

View File

@@ -0,0 +1 @@
Markdown résumé placeholder for Unicode accent coverage.

View File

@@ -0,0 +1 @@
示例文件用于验证Unicode处理。

View File

@@ -0,0 +1,8 @@
package integration
import "os"
func fileExistsTestHelper(path string) bool {
_, err := os.Stat(path)
return err == nil
}

View File

@@ -0,0 +1,26 @@
package integration
import (
"bytes"
"testing"
renamercmd "github.com/rogeecn/renamer/cmd"
)
func TestRegexApplyBlocksConflicts(t *testing.T) {
t.Parallel()
tmp := t.TempDir()
copyRegexFixtureIntegration(t, "case-fold", tmp)
cmd := renamercmd.NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"regex", "^(.*)$", "conflict", "--yes", "--path", tmp})
err := cmd.Execute()
if err == nil {
t.Fatalf("expected error when conflicts are present")
}
}

View File

@@ -0,0 +1,74 @@
package integration
import (
"bytes"
"io/fs"
"os"
"path/filepath"
"testing"
renamercmd "github.com/rogeecn/renamer/cmd"
)
func TestRegexPreviewCommand(t *testing.T) {
t.Parallel()
tmp := t.TempDir()
copyRegexFixtureIntegration(t, "baseline", tmp)
var out bytes.Buffer
cmd := renamercmd.NewRootCommand()
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"regex", "^(\\w+)-(\\d+)", "@2_@1", "--dry-run", "--path", tmp})
if err := cmd.Execute(); err != nil {
t.Fatalf("regex preview command failed: %v\noutput: %s", err, out.String())
}
expected := []string{
"alpha-123.log -> 123_alpha.log",
"beta-456.log -> 456_beta.log",
"gamma-789.log -> 789_gamma.log",
"Preview complete: 3 matched, 3 changed, 0 skipped.",
"Preview complete. Re-run with --yes to apply.",
}
for _, token := range expected {
if !bytes.Contains(out.Bytes(), []byte(token)) {
t.Fatalf("expected output to contain %q, got: %s", token, out.String())
}
}
}
func copyRegexFixtureIntegration(t *testing.T, name, dest string) {
t.Helper()
src := filepath.Join("..", "fixtures", "regex", name)
if err := filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
targetPath := filepath.Join(dest, rel)
if err := os.MkdirAll(filepath.Dir(targetPath), 0o755); err != nil {
return err
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
return os.WriteFile(targetPath, content, 0o644)
}); err != nil {
t.Fatalf("copy regex fixture: %v", err)
}
}

View File

@@ -0,0 +1,42 @@
package integration
import (
"bytes"
"path/filepath"
"testing"
renamercmd "github.com/rogeecn/renamer/cmd"
)
func TestRegexUndoRestoresAutomationRun(t *testing.T) {
t.Parallel()
tmp := t.TempDir()
copyRegexFixtureIntegration(t, "mixed", tmp)
apply := renamercmd.NewRootCommand()
var applyOut bytes.Buffer
apply.SetOut(&applyOut)
apply.SetErr(&applyOut)
apply.SetArgs([]string{"regex", "^build_(\\d+)_(.*)$", "release-@1-@2", "--yes", "--path", tmp})
if err := apply.Execute(); err != nil {
t.Fatalf("regex apply failed: %v\noutput: %s", err, applyOut.String())
}
if !fileExistsTestHelper(filepath.Join(tmp, "release-101-release.tar.gz")) || !fileExistsTestHelper(filepath.Join(tmp, "release-102-hotfix.tar.gz")) {
t.Fatalf("expected renamed files after apply")
}
undo := renamercmd.NewRootCommand()
var undoOut bytes.Buffer
undo.SetOut(&undoOut)
undo.SetErr(&undoOut)
undo.SetArgs([]string{"undo", "--path", tmp})
if err := undo.Execute(); err != nil {
t.Fatalf("undo failed: %v\noutput: %s", err, undoOut.String())
}
if !fileExistsTestHelper(filepath.Join(tmp, "build_101_release.tar.gz")) || !fileExistsTestHelper(filepath.Join(tmp, "build_102_hotfix.tar.gz")) {
t.Fatalf("expected originals restored after undo")
}
}

View File

@@ -2,7 +2,6 @@ package integration
import (
"bytes"
"os"
"path/filepath"
"testing"
@@ -33,7 +32,7 @@ func TestRemoveCommandAutomationUndo(t *testing.T) {
t.Fatalf("apply failed: %v\noutput: %s", err, applyOut.String())
}
if !fileExists(filepath.Join(tmp, "alpha.txt")) || !fileExists(filepath.Join(tmp, "nested", "beta.txt")) {
if !fileExistsTestHelper(filepath.Join(tmp, "alpha.txt")) || !fileExistsTestHelper(filepath.Join(tmp, "nested", "beta.txt")) {
t.Fatalf("expected files renamed after apply")
}
@@ -46,12 +45,7 @@ func TestRemoveCommandAutomationUndo(t *testing.T) {
t.Fatalf("undo failed: %v\noutput: %s", err, undoOut.String())
}
if !fileExists(filepath.Join(tmp, "alpha copy.txt")) || !fileExists(filepath.Join(tmp, "nested", "beta draft.txt")) {
if !fileExistsTestHelper(filepath.Join(tmp, "alpha copy.txt")) || !fileExistsTestHelper(filepath.Join(tmp, "nested", "beta draft.txt")) {
t.Fatalf("expected originals restored after undo")
}
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}