Skip to content

Instantly share code, notes, and snippets.

@mindon
Created June 26, 2017 01:33
Show Gist options
  • Select an option

  • Save mindon/55df1019f67e0ff662f8c4257cadfa0a to your computer and use it in GitHub Desktop.

Select an option

Save mindon/55df1019f67e0ff662f8c4257cadfa0a to your computer and use it in GitHub Desktop.
gohtml-cli command tool to format html files using yosssi's gohtml
// gohtml-cli command tool to format html files using yosssi's gohtml
// [NOTICE] some issues are in yosssi's gohtml - which has not updated for years <https://github.com/yosssi/gohtml/issues>
// DO MAKE BACKUPs before you trying this
// it's recommended using js-beautify instead: <https://github.com/beautify-web/js-beautify>
// Jun. 25, 2017 - Mindon <mindon@gmail.com>
package main
import (
"fmt"
"github.com/yosssi/gohtml"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sync"
)
var htmlExts = regexp.MustCompile(`(?i)(\.(htm|html|xhtml))$`)
func main() {
args := os.Args
usage := "gohtml-cli - html formatter\n\nUsage: gohtml-cli [-w] demo.html\n gohtml -d htmldir/"
if len(args) < 2 {
fmt.Println(usage)
return
}
flag := "-w"
flpath := args[1]
if flpath == "-w" || flpath == "-d" {
if len(args) > 2 {
flpath = args[2]
} else {
flag = flpath
flpath = ""
}
}
if len(flpath) == 0 {
fmt.Println(usage)
return
}
var mode os.FileMode = 0666
if info, err := os.Stat(flpath); os.IsNotExist(err) {
fmt.Println(flpath, "NOT FOUND!")
return
} else if err == nil && info.IsDir() && flag != "-d" {
fmt.Println(usage)
return
} else {
mode = info.Mode()
}
if flag == "-w" {
if len(args) < 3 {
prettyHtmlLines(flpath)
return
}
body, err := prettyHtml(flpath)
if err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(flpath, body, mode)
if err != nil {
fmt.Println(err)
return
}
return
}
prettyDir(flpath)
}
func prettyHtml(flpath string) ([]byte, error) {
body, err := ioutil.ReadFile(flpath)
if err != nil {
return nil, err
}
return gohtml.FormatBytes(body), nil
}
func prettyDir(fldir string) {
var wg sync.WaitGroup
filepath.Walk(fldir, func(flpath string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return err
}
if info.IsDir() {
prettyDir(flpath)
return nil
}
if len(flpath) < 4 {
return nil
}
if htmlExts.MatchString(flpath) {
wg.Add(1)
go func(flpath string) {
defer wg.Done()
if err != nil {
fmt.Println(err)
return
}
body, err := prettyHtml(flpath)
if err != nil {
fmt.Println(err)
return
}
info, err := os.Stat(flpath)
err = ioutil.WriteFile(flpath, body, info.Mode())
if err != nil {
fmt.Println(err)
return
}
}(flpath)
}
return nil
})
wg.Wait()
}
func prettyHtmlLines(flpath string) {
body, err := ioutil.ReadFile(flpath)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(gohtml.FormatWithLineNo(string(body)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment