Created
February 22, 2017 03:54
-
-
Save tmlbl/f16ab07a89cf1b96b011764e588a299e to your computer and use it in GitHub Desktop.
A Go utility to check that lines are less than 80 characters in source code
This file contains hidden or 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" | |
"errors" | |
"flag" | |
"fmt" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
var ( | |
glob string | |
maxlen int | |
passed = true | |
) | |
type longline struct { | |
lineno int | |
text string | |
fpath string | |
} | |
func (l longline) Show() { | |
fmt.Fprintf(os.Stderr, "%s:%d line length is %d\n", | |
l.fpath, l.lineno, len(l.text)) | |
} | |
func exitIfErr(err error) { | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
os.Exit(1) | |
} | |
} | |
func main() { | |
flag.StringVar(&glob, "g", "*.go,**/*.go", | |
"File globs to test, comma-separated") | |
flag.IntVar(&maxlen, "len", 80, "Maximum line length to allow") | |
flag.Parse() | |
var files []string | |
for _, g := range strings.Split(glob, ",") { | |
f, err := filepath.Glob(g) | |
exitIfErr(err) | |
files = append(files, f...) | |
} | |
for _, fpath := range files { | |
file, err := os.Open(fpath) | |
exitIfErr(err) | |
defer file.Close() | |
scanner := bufio.NewScanner(file) | |
var lineno int | |
for scanner.Scan() { | |
lineno++ | |
ln := scanner.Text() | |
if len(ln) > maxlen { | |
ll := longline{lineno, ln, fpath} | |
ll.Show() | |
passed = false | |
} | |
} | |
exitIfErr(scanner.Err()) | |
} | |
if !passed { | |
exitIfErr(errors.New("line length check failed")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment