Skip to content

Commit

Permalink
chore: clean codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
gkampitakis committed Jun 5, 2022
1 parent 69457cd commit 03e11f8
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 135 deletions.
119 changes: 60 additions & 59 deletions snaps/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func Clean() {
obsoleteTests, err := examineSnaps(testsRegistry.values, usedFiles, runOnly, shouldUpdate)
if err != nil {
fmt.Println(err)
return
}

summary(fmt.Printf, obsoleteFiles, obsoleteTests, shouldUpdate)
Expand All @@ -41,7 +42,7 @@ func Clean() {
If a file exists but is not registered in the map we check if the file is
skipped. (We do that by checking if the mod is imported and there is a call to
`Matchsnapshot`). If not skipped and not registed means it's an obsolete snap file
`MatchSnapshot`). If not skipped and not registered means it's an obsolete snap file
and we mark it as one.
*/
func examineFiles(
Expand All @@ -65,25 +66,24 @@ func examineFiles(
}

snapPath := filepath.Join(dir, content.Name())
if _, called := registry[snapPath]; called {
used = append(used, snapPath)
continue
}

if _, called := registry[snapPath]; !called {
isSkipped := isFileSkipped(dir, content.Name(), runOnly)
if isSkipped {
continue
}
if isFileSkipped(dir, content.Name(), runOnly) {
continue
}

if shouldUpdate {
err := os.Remove(snapPath)
if err != nil {
fmt.Println(err)
}
}
obsolete = append(obsolete, snapPath)

obsolete = append(obsolete, snapPath)
if !shouldUpdate {
continue
}

used = append(used, snapPath)
if err := os.Remove(snapPath); err != nil {
fmt.Println(err)
}
}
}

Expand All @@ -96,6 +96,26 @@ func examineSnaps(
runOnly string,
shouldUpdate bool,
) ([]string, error) {
removeSnapshot := func(s *bufio.Scanner) {
for s.Scan() {
// skip until ---
if s.Text() == "---" {
break
}
}
}
getSnapshot := func(s *bufio.Scanner) (snapshot string) {
for s.Scan() {
line := s.Text()
// reached end char
if s.Text() == "---" {
break
}
snapshot += line + newLine
}

return snapshot
}
obsoleteTests := []string{}

for _, snapPath := range used {
Expand Down Expand Up @@ -123,37 +143,20 @@ func examineSnaps(
obsoleteTests = append(obsoleteTests, testID)
hasDiffs = true

for s.Scan() {
// skip until ---
if s.Text() == "---" {
break
}
}
removeSnapshot(s)

continue
}

snapshot := ""

for s.Scan() {
line := s.Text()
// reached end char
if s.Text() == "---" {
break
}
snapshot += line + "\n"
}

updatedFile += fmt.Sprintf("\n[%s]\n%s---\n", testID, snapshot)
updatedFile += fmt.Sprintf("\n[%s]\n%s---\n", testID, getSnapshot(s))
}

f.Close()
if !hasDiffs || !shouldUpdate {
continue
}

err = os.WriteFile(snapPath, []byte(updatedFile), os.ModePerm)
if err != nil {
if err = stringToSnapshotFile(updatedFile, snapPath); err != nil {
fmt.Println(err)
}
}
Expand All @@ -166,34 +169,29 @@ func summary(print printerF, obsoleteFiles []string, obsoleteTests []string, sho
return
}

print("\n%s\n\n", greenBG("Snapshot Summary"))

if len(obsoleteFiles) > 0 {
objectSummaryList := func(objects []string, name string) {
plural := name + "s"
print(summaryMsg(
len(obsoleteFiles),
stringTernary("files", "file", len(obsoleteFiles) > 1),
len(objects),
stringTernary(len(objects) > 1, plural, name),
shouldUpdate),
)

for _, file := range obsoleteFiles {
print(dimText(fmt.Sprintf(" %s%s\n", bulletPoint, file)))
for _, object := range objects {
print(dimText(fmt.Sprintf(" %s%s\n", bulletPoint, object)))
}

print("\n")
print(newLine)
}

if len(obsoleteTests) > 0 {
print(summaryMsg(
len(obsoleteTests),
stringTernary("tests", "test", len(obsoleteTests) > 1),
shouldUpdate),
)
print("\n%s\n\n", greenBG("Snapshot Summary"))

for _, test := range obsoleteTests {
print(dimText(fmt.Sprintf(" %s%s\n", bulletPoint, test)))
}
if len(obsoleteFiles) > 0 {
objectSummaryList(obsoleteFiles, "file")
}

print("\n")
if len(obsoleteTests) > 0 {
objectSummaryList(obsoleteTests, "test")
}

if !shouldUpdate {
Expand All @@ -206,13 +204,13 @@ func summary(print printerF, obsoleteFiles []string, obsoleteTests []string, sho
}

func summaryMsg(files int, subject string, updated bool) string {
action := stringTernary("removed", "obsolete", updated)
color := colorTernary(greenText, yellowText, updated)
action := stringTernary(updated, "removed", "obsolete")
color := colorTernary(updated, greenText, yellowText)

return color(fmt.Sprintf("%s%d snapshot %s %s.\n", arrowPoint, files, subject, action))
}

func stringTernary(trueBranch string, falseBranch string, assertion bool) string {
func stringTernary(assertion bool, trueBranch string, falseBranch string) string {
if !assertion {
return falseBranch
}
Expand All @@ -221,9 +219,9 @@ func stringTernary(trueBranch string, falseBranch string, assertion bool) string
}

func colorTernary(
assertion bool,
colorFuncTrue func(string) string,
colorFuncFalse func(string) string,
assertion bool,
) func(string) string {
if !assertion {
return colorFuncFalse
Expand All @@ -236,16 +234,19 @@ func colorTernary(
Builds a Set with all snapshot ids registered inside a snap file
Form: testname - number id
tests have the form map[filepath]: map[testname]: <number of snapshots>
e.g ./path/__snapshots__/add_test.snap map[TestAdd] 3
tests have the form
map[filepath]: map[testname]: <number of snapshots>
e.g
./path/__snapshots__/add_test.snap map[TestAdd] 3
will result to
TestAdd - 1
TestAdd - 2
TestAdd - 3
as it means there are 3 snapshots registered with that test
as it means there are 3 snapshots created inside TestAdd
*/
func occurrences(tests map[string]int) set {
result := make(set)
Expand Down
48 changes: 26 additions & 22 deletions snaps/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,46 @@ package snaps

import (
"bytes"

"github.com/sergi/go-diff/diffmatchpatch"
)

const (
DiffEqual diffmatchpatch.Operation = 0
DiffInsert diffmatchpatch.Operation = 1
DiffDelete diffmatchpatch.Operation = -1
)

func prettyDiff(expected, received string) string {
diffs := dmp.DiffCleanupSemantic(dmp.DiffMain(expected, received, false))

buff := bytes.Buffer{}

if len(diffs) == 1 && diffs[0].Type == 0 {
if len(diffs) == 1 && diffs[0].Type == DiffEqual {
return ""
}

buff.WriteString("\n")
var buff bytes.Buffer

buff.WriteString(newLine)
buff.WriteString(redBG(" Snapshot "))
buff.WriteString("\n")
buff.WriteString(newLine)
buff.WriteString(greenBG(" Received "))
buff.WriteString("\n\n")
buff.WriteString(newLine + newLine)

for _, diff := range diffs {
text := diff.Text

switch diff.Type {
case 0:
buff.WriteString(dimText(diff.Text))
case -1:
if spacesRegexp.MatchString(diff.Text) {
buff.WriteString(redBG(diff.Text))
} else {
buff.WriteString(redText(diff.Text))
}
case 1:
if spacesRegexp.MatchString(diff.Text) {
buff.WriteString(greenBG(diff.Text))
} else {
buff.WriteString(greenText(diff.Text))
}
case DiffEqual:
buff.WriteString(dimText(text))
case DiffDelete:
str := stringTernary(spacesRegexp.MatchString(text), redBG(text), redText(text))
buff.WriteString(str)
case DiffInsert:
str := stringTernary(spacesRegexp.MatchString(text), greenBG(text), greenText(text))
buff.WriteString(str)
}
}

buff.WriteString("\n")
buff.WriteString(newLine)

return buff.String()
}
29 changes: 16 additions & 13 deletions snaps/skip.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,29 @@ import (

var skippedTests = newSyncSlice()

// Wrapper of testing.Skip.
// Keeps track which snapshots should be skipped
// and not marked as obsolete
// Wrapper of testing.Skip
//
// Keeps track which snapshots are getting skipped and not marked as obsolete.
func Skip(t testingT, args ...interface{}) {
t.Helper()

skippedTests.append(t.Name())
t.Skip(args...)
}

// Wrapper of testing.Skipf.
// Helps `go-snaps` keep track which snapshots should be skipped
// and not marked as obsolete
// Wrapper of testing.Skipf
//
// Keeps track which snapshots are getting skipped and not marked as obsolete.
func Skipf(t testingT, format string, args ...interface{}) {
t.Helper()

skippedTests.append(t.Name())
t.Skipf(format, args...)
}

// Wrapper of testing.SkipNow.
// Keeps track which snapshots should be skipped
// and not marked as obsolete
// Wrapper of testing.SkipNow
//
// Keeps track which snapshots are getting skipped and not marked as obsolete.
func SkipNow(t testingT) {
t.Helper()

Expand All @@ -44,11 +44,14 @@ func SkipNow(t testingT) {
/*
This checks if the parent test is skipped,
or provided a 'runOnly' the testID is part of it
e.g
func TestParallel (t *testing.T) {
snaps.Skip()
...
}
func TestParallel (t *testing.T) {
snaps.Skip()
...
}
Then every "child" test should be skipped
*/
func testSkipped(testID, runOnly string) bool {
Expand Down
Loading

0 comments on commit 03e11f8

Please sign in to comment.