Last active
February 14, 2022 01:49
-
-
Save Prendo93/9046c08c973faf7a58d6477a19c5eea6 to your computer and use it in GitHub Desktop.
A go program to convert all relative imports to absolute imports in a Typescript/Javascript codebase
This file contains 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 ( | |
"bufio" | |
"bytes" | |
"errors" | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"path/filepath" | |
"regexp" | |
) | |
var filename = flag.String("f", "", "filename") | |
var overwrite = flag.Bool("w", false, "overwrite") | |
var out io.Writer | |
func main() { | |
flag.Parse() | |
f, err := os.Open(*filename) | |
if os.IsNotExist(err) { | |
panic(err) | |
} | |
defer f.Close() | |
b := &bytes.Buffer{} | |
if *overwrite { | |
out = b | |
} else { | |
out = os.Stdout | |
} | |
scanner := bufio.NewScanner(f) | |
// optionally, resize scanner's capacity for lines over 64K, see next example | |
for scanner.Scan() { | |
_, err := out.Write([]byte(HandleLine(scanner.Text(), *filename) + "\n")) | |
if err != nil { | |
panic(err) | |
} | |
} | |
if err := scanner.Err(); err != nil { | |
log.Fatal(err) | |
} | |
if *overwrite { | |
f2, err := os.OpenFile(*filename, os.O_WRONLY, 0) | |
if err != nil { | |
panic(err) | |
} | |
err = f2.Truncate(0) | |
if err != nil { | |
panic(err) | |
} | |
_, err = f2.Write(b.Bytes()) | |
if err != nil { | |
panic(err) | |
} | |
} | |
} | |
var matchLine = regexp.MustCompile("(?P<prefix>.* from )[\"'](?P<path>.*)[\"'];") | |
var matchLine2 = regexp.MustCompile("(?P<prefix>import )[\"'](?P<path>.*)[\"'];") | |
var suffix = regexp.MustCompile("\\.[tj]sx?|\\.css|\\.gif|\\.png|\\.svg$") | |
func HandleLine(in, filename string) string { | |
if !matchLine.MatchString(in) && !matchLine2.MatchString(in) { | |
return in | |
} | |
subMatches := []string{} | |
if matchLine.MatchString(in) { | |
subMatches = matchLine.FindStringSubmatch(in) | |
} | |
if matchLine2.MatchString(in) { | |
subMatches = matchLine2.FindStringSubmatch(in) | |
} | |
absPath := filepath.Join(filename, "../"+subMatches[2]) | |
if suffix.MatchString(absPath) && exists(absPath) { | |
return fmt.Sprintf("%s\"%s\";", subMatches[1], absPath) | |
} | |
//add suffix and see if it exists | |
for _, tSuffix := range []string{"ts", "js", "tsx", "jsx", "css", "png", "gif", "svg"} { | |
if exists(absPath + "." + tSuffix) { | |
return fmt.Sprintf("%s\"%s\";", subMatches[1], absPath) | |
} | |
} | |
//Couldn't find the file | |
return in | |
} | |
func exists(path string) bool { | |
_, err := os.Stat(path) | |
return !errors.Is(err, os.ErrNotExist) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment