Skip to content

Instantly share code, notes, and snippets.

@eyasuyuki
Last active February 15, 2023 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyasuyuki/710ce837c866862ec7ccd35d47cfecc2 to your computer and use it in GitHub Desktop.
Save eyasuyuki/710ce837c866862ec7ccd35d47cfecc2 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
)
func read(path string) (bool, []byte) {
content, err := os.ReadFile(path)
if err != nil {
panic(err)
}
bom := []byte{0xEF, 0xBB, 0xBF}
if bytes.HasPrefix(content, bom) {
fmt.Printf("Removing BOM from %s\n", path)
newContents := content[len(bom):]
return true, newContents
} else {
return false, content
}
}
func main() {
root := "/path/to/dir"
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || filepath.Ext(path) != ".java" {
return nil
}
isbom, newContents := read(path)
if isbom {
fmt.Printf("Removing BOM from %s\n", path)
err := os.Remove(path)
if err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(newContents)
if err != nil {
return err
}
}
return nil
})
if err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment