-
Notifications
You must be signed in to change notification settings - Fork 16
/
line_count.go
44 lines (38 loc) · 876 Bytes
/
line_count.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main
import (
"bytes"
"io"
"os"
)
func estimateFileTimesByLineCount(currentFileSet map[string]bool, fileTimes map[string]float64) {
for fileName := range currentFileSet {
file, err := os.Open(fileName)
if err != nil {
printMsg("failed to count lines in file %s: %v\n", fileName, err)
continue
}
defer file.Close()
lineCount, err := lineCounter(file)
if err != nil {
printMsg("failed to count lines in file %s: %v\n", fileName, err)
continue
}
fileTimes[fileName] = float64(lineCount)
}
}
// Credit to http://stackoverflow.com/a/24563853/6678
func lineCounter(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}