forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-vanity.go
More file actions
77 lines (64 loc) · 1.65 KB
/
migrate-vanity.go
File metadata and controls
77 lines (64 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
// This is a temporary script to migrate our go import paths from
// sourcegraph.com to github.com
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"golang.org/x/tools/imports"
"github.com/fatih/astrewrite"
)
var vendorRe = regexp.MustCompile(`(/|^)vendor/`)
func main() {
rewriteFunc := func(n ast.Node) (ast.Node, bool) {
x, ok := n.(*ast.ImportSpec)
if !ok {
return n, true
}
if strings.HasPrefix(x.Path.Value, "\"sourcegraph.com/sourcegraph/") && !strings.Contains(x.Path.Value, "go-diff") {
x.Path.Value = "\"github.com" + x.Path.Value[len("\"sourcegraph.com"):]
}
return x, true
}
err := filepath.Walk(os.Args[1], func(path string, f os.FileInfo, err error) error {
if err != nil || !strings.HasSuffix(path, ".go") || vendorRe.MatchString(path) {
return err
}
src, err := ioutil.ReadFile(path)
if err != nil {
return err
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, path, src, parser.ParseComments)
if err != nil {
return err
}
// Rewrite imports
rewritten := astrewrite.Walk(file, rewriteFunc)
// Import order may need changing. So format with goimports which will
// sort imports.
var buf bytes.Buffer
printer.Fprint(&buf, fset, rewritten)
res, err := imports.Process(path, buf.Bytes(), &imports.Options{Comments: true, TabIndent: true, TabWidth: 8, FormatOnly: true})
if err != nil {
return err
}
if !bytes.Equal(src, res) {
fmt.Printf("updating %s\n", path)
return ioutil.WriteFile(path, res, f.Mode().Perm())
}
return nil
})
if err != nil {
log.Fatal(err)
}
}