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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
package main
import ( "bufio" "fmt" "os" "path" "path/filepath" "time" )
func isSourceFile(ext string) bool { var kSourceFileExts = []string{".c", ".cc", ".cpp", ".h", ".hpp", ".go", ".java"} for _, r := range kSourceFileExts { if r == ext { return true } } return false }
func main() { if len(os.Args) < 2 { fmt.Println("Usage: ", os.Args[0], "[file or folder]...") return }
start := time.Now() files := make(map[string]struct{}) lines := 0
for _, r := range os.Args { fi, err := os.Stat(r) if err == nil || os.IsExist(err) { if fi.IsDir() { AddDirectory(r, files) } else { AddFile(r, files) } } }
for file, _ := range files { l := CountLine(file) lines += l fmt.Println(file, l) } fmt.Printf("Total lines: %d, cost %fs\n", lines, timeElapsed(start)) }
func AddDirectory(name string, files map[string]struct{}) { filepath.Walk(name, func(path string, fi os.FileInfo, err error) error { if nil == fi { return err } if fi.IsDir() { return nil } AddFile(path, files) return nil }) }
func AddFile(name string, files map[string]struct{}) { ext := path.Ext(name) if isSourceFile(ext) { path, err := filepath.Abs(name) if err == nil { _, exists := files[path] if exists { fmt.Println("Duplicated", path) } else { files[path] = struct{}{} fmt.Println("Add", path) } } } }
func CountLine(path string) (num int) { f, err := os.Open(path) if nil != err { return } defer f.Close()
s := bufio.NewScanner(f) for s.Scan() { num += 1 } return }
func timeElapsed(start time.Time) float64 { dis := time.Since(start).Seconds() return dis }
|