Skip to content

Instantly share code, notes, and snippets.

@jecolasurdo
Created October 27, 2017 16:57
Show Gist options
  • Save jecolasurdo/1345ce62de97c7bb9030e693bd2b6bc4 to your computer and use it in GitHub Desktop.
Save jecolasurdo/1345ce62de97c7bb9030e693bd2b6bc4 to your computer and use it in GitHub Desktop.
Needed to make some replacements that were a bit much for sed, and didn't want to use awk, perl, or python.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
func main() {
filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if strings.Contains(path, "/vendor/") {
return nil
}
if filepath.Ext(path) != ".go" {
return nil
}
if info.Name() == "fixtests.go" {
return nil
}
rawSrc, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
src := string(rawSrc)
regexOne := regexp.MustCompile(`mockController := gomock\.NewController\(t\)`)
if !regexOne.MatchString(src) {
return nil
}
log.Println(path)
firstReplacementSrc := regexOne.ReplaceAllLiteralString(
src,
fmt.Sprintf("mockController := gomock.NewController(t)\n\tdefer mockController.Finish()"))
regexTwo := regexp.MustCompile(`defer mockController\.Finish\(\)\n\tdefer mockController.Finish\(\)`)
secondReplacementSrc := regexTwo.ReplaceAllLiteralString(
firstReplacementSrc,
fmt.Sprintf("defer mockController.Finish()"))
err = ioutil.WriteFile(path, []byte(secondReplacementSrc), 0777)
if err != nil {
panic(err)
}
return nil
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment