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
|
package main
import ( "bufio" "fmt" "os" "path" "path/filepath" )
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 }
files := make(map[string]bool) 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.Println("Total lines:", lines) }
func AddDirectory(name string, files map[string]bool) { 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 }) return }
func AddFile(name string, files map[string]bool) { 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] = true 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 }
|