github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/misc/sortac/sortac.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Sortac sorts the AUTHORS and CONTRIBUTORS files. 6 // 7 // Usage: 8 // 9 // sortac [file...] 10 // 11 // Sortac sorts the named files in place. 12 // If given no arguments, it sorts standard input to standard output. 13 package main 14 15 import ( 16 "bufio" 17 "bytes" 18 "flag" 19 "fmt" 20 "io" 21 "io/ioutil" 22 "log" 23 "os" 24 25 "golang.org/x/text/collate" 26 "golang.org/x/text/language" 27 ) 28 29 func main() { 30 log.SetFlags(0) 31 log.SetPrefix("sortac: ") 32 flag.Parse() 33 34 args := flag.Args() 35 if len(args) == 0 { 36 os.Stdout.Write(sortAC(os.Stdin)) 37 } else { 38 for _, arg := range args { 39 f, err := os.Open(arg) 40 if err != nil { 41 log.Fatal(err) 42 } 43 sorted := sortAC(f) 44 f.Close() 45 if err := ioutil.WriteFile(arg, sorted, 0644); err != nil { 46 log.Fatal(err) 47 } 48 } 49 } 50 } 51 52 func sortAC(r io.Reader) []byte { 53 bs := bufio.NewScanner(r) 54 var header []string 55 var lines []string 56 for bs.Scan() { 57 t := bs.Text() 58 lines = append(lines, t) 59 if t == "# Please keep the list sorted." { 60 header = lines 61 lines = nil 62 continue 63 } 64 } 65 if err := bs.Err(); err != nil { 66 log.Fatal(err) 67 } 68 69 var out bytes.Buffer 70 c := collate.New(language.Und, collate.Loose) 71 c.SortStrings(lines) 72 for _, l := range header { 73 fmt.Fprintln(&out, l) 74 } 75 for _, l := range lines { 76 fmt.Fprintln(&out, l) 77 } 78 return out.Bytes() 79 }