Exemplo n.º 1
0
func rewriteImports(importSites []string) (rewritten bool) {
	filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
		if err != nil || info.IsDir() {
			return nil
		}
		fset := token.NewFileSet()
		f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
		if err != nil {
			return nil
		}
		for _, im := range f.Imports {
			for _, site := range importSites {
				v, err := strconv.Unquote(im.Path.Value)
				if err != nil {
					log.Fatal(err)
				}
				// don't replace ourself
				if v == relpath || strings.HasPrefix(v, relpath+"/") {
					if *verbose {
						log.Printf("skipping %s because it is in %s\n", v, relpath)
					}
					continue
				}
				if strings.HasPrefix(v, site+"/") {
					target := ThirdParty + "/" + v
					if !*relative {
						target = filepath.ToSlash(relpath) + "/" + target
					}
					if *verbose {
						log.Printf("rewrite %s: %s -> %s\n", path, v, target)
					}
					if *dryrun {
						break
					}
					if !astutil.RewriteImport(fset, f, v, target) {
						log.Fatalf("%s: could not rewrite %s", path, im.Path.Value)
					}
					rewritten = true
					break
				}
			}
		}
		var buf bytes.Buffer
		if err := printer.Fprint(&buf, fset, f); err != nil {
			log.Fatal(err)
		}
		fb, err := format.Source(buf.Bytes())
		if err != nil {
			log.Fatal(err)
		}
		if err := ioutil.WriteFile(path, fb, info.Mode()); err != nil {
			log.Fatal(err)
		}
		return nil
	})
	return
}
Exemplo n.º 2
0
// rewritePath rewrites import paths in file from oldPath to newPath
func rewritePath(file, oldPath, newPath string) error {
	stat, err := os.Stat(file)
	if err != nil {
		return err
	}
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, file, nil, 0)
	if err != nil {
		return err
	}
	for _, imp := range f.Imports {
		impPath, _ := strconv.Unquote(imp.Path.Value)
		if strings.HasPrefix(impPath, oldPath) {
			subpackage := strings.TrimPrefix(impPath, oldPath)
			astutil.RewriteImport(fset, f, impPath, newPath+subpackage)
		}
	}
	ofile, err := os.OpenFile(file, os.O_RDWR|os.O_TRUNC, stat.Mode())
	if err != nil {
		return err
	}
	defer ofile.Close()
	return printer.Fprint(ofile, fset, f)
}