Created
February 13, 2019 07:17
-
-
Save mhama/3f095e6695d940595263dd917594fcc2 to your computer and use it in GitHub Desktop.
line ending checker
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" | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
const BUFSIZE = 1024 | |
func getPathFromArgs() string { | |
if len(os.Args) == 1 { | |
return "" | |
} | |
return os.Args[1] | |
} | |
type Stat struct { | |
lfCount int | |
crlfCount int | |
} | |
func (s *Stat) MajorType() string { | |
if s.crlfCount > s.lfCount { | |
return "crlf" | |
} else { | |
return "lf" | |
} | |
} | |
func (s *Stat) MinorType() string { | |
if s.crlfCount > s.lfCount { | |
return "lf" | |
} else { | |
return "crlf" | |
} | |
} | |
func aggregateCrLfFromFile(f *os.File) (stat Stat) { | |
reader := bufio.NewReader(f) | |
lfCount := 0 | |
crlfCount := 0 | |
for { | |
line, err := reader.ReadString('\n') | |
lineBody := strings.TrimRight(line, "\r\n") | |
if line == lineBody { | |
break | |
} | |
isCrLf := strings.TrimSuffix(line, "\r\n") != line | |
if isCrLf { | |
crlfCount++ | |
} else { | |
lfCount++ | |
} | |
//fmt.Println(isCrLf, lineBody) | |
if err == io.EOF { | |
break | |
} | |
} | |
return Stat{lfCount, crlfCount} | |
} | |
func showSpecificLineEndingFromFile(f *os.File, lineEnding string) { | |
reader := bufio.NewReader(f) | |
lineNo := 1 | |
for { | |
line, err := reader.ReadString('\n') | |
lineBody := strings.TrimRight(line, "\r\n") | |
if line == lineBody { | |
break | |
} | |
isCrLf := strings.TrimSuffix(line, "\r\n") != line | |
if (isCrLf && lineEnding == "crlf") || (!isCrLf && lineEnding == "lf") { | |
fmt.Println(lineNo, ":", lineEnding, lineBody) | |
} | |
if err == io.EOF { | |
break | |
} | |
lineNo++ | |
} | |
} | |
func main() { | |
inputPath := getPathFromArgs() | |
if inputPath == "" { | |
return | |
} | |
fmt.Println("path:", inputPath) | |
f, err := os.Open(inputPath) | |
if err != nil { | |
fmt.Println("Error!", err) | |
} | |
defer f.Close() | |
stat := aggregateCrLfFromFile(f) | |
fmt.Printf("(lf, crlf) = (%d, %d)\n", stat.lfCount, stat.crlfCount) | |
fmt.Println("MajorType:", stat.MajorType()) | |
f.Seek(0, 0) | |
showSpecificLineEndingFromFile(f, stat.MinorType()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment