Created
March 13, 2016 19:26
-
-
Save andreinechaev/35a77fa8ddc9c60a1958 to your computer and use it in GitHub Desktop.
Go tool for correcting text in your go projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io/ioutil" | |
"os" | |
"log" | |
"strings" | |
"sync" | |
"flag" | |
) | |
var ( | |
files []string | |
wg sync.WaitGroup | |
) | |
//const ( | |
// LINE_TO_FIX = "github.com/c-darwin/dcoin-go/vendor/src/" | |
//) | |
func parseDir(path string) ([]os.FileInfo, error) { | |
fInfo, err := ioutil.ReadDir(path) | |
if err != nil { | |
return nil, err | |
} | |
for _, f := range fInfo { | |
if strings.Contains(f.Name(), ".go") { | |
files = append(files, path + "/" + f.Name()) | |
} else if f.IsDir() { | |
fInfo, err = parseDir(path + "/" + f.Name()) | |
if err != nil { | |
panic(err) | |
} | |
} | |
} | |
return fInfo, err | |
} | |
func parseFileAt(path, old, new string) error { | |
b, err := ioutil.ReadFile(path) | |
if err != nil { | |
log.Fatalln(err) | |
return err | |
} | |
defer func() { | |
wg.Done() | |
}() | |
lines := strings.Split(string(b), "\n") | |
for i, l := range lines { | |
lines[i] = fixImport(l, old, new) | |
} | |
out := strings.Join(lines, "\n") | |
err = ioutil.WriteFile(path, []byte(out), 0644) | |
if err != nil { | |
panic(err) | |
} | |
return err | |
} | |
func fixImport(s, old, new string) string { | |
if strings.Contains(s, old) { | |
result := strings.Replace(s, old, new, -1) | |
log.Println("\noriginal: " + s + | |
"\nresult: " + result + "\n") | |
return result | |
} | |
return s | |
} | |
func main() { | |
path := flag.String("p", "", "Path to a project") | |
src := flag.String("s", "", "Original line to change") | |
res := flag.String("f", "", "Final result") | |
flag.Parse() | |
goPath := os.Getenv("GOPATH") | |
rootPath := goPath + *path | |
_, err := parseDir(rootPath) | |
if err != nil { | |
panic(err) | |
} | |
wg.Add(len(files)) | |
for _, p := range files { | |
parseFileAt(p, *src, *res) | |
} | |
wg.Wait() | |
log.Println("len files:", len(files)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment