Skip to content

Commit

Permalink
Merge pull request #6 from rhysd/sort-uniq
Browse files Browse the repository at this point in the history
Sort and uniq package lines
  • Loading branch information
haya14busa authored Oct 24, 2018
2 parents baf4513 + 23e5c77 commit 29d3292
Showing 1 changed file with 72 additions and 1 deletion.
73 changes: 72 additions & 1 deletion cmd/gopkgs/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"flag"
"fmt"
"os"
"sort"
"strings"
"text/template"

"github.com/haya14busa/gopkgs"
Expand Down Expand Up @@ -39,6 +41,62 @@ func init() {
flag.Usage = usage
}

type ByPath []*gopkgs.Pkg

func (pkgs ByPath) Len() int {
return len(pkgs)
}
func (pkgs ByPath) Swap(i, j int) {
pkgs[i], pkgs[j] = pkgs[j], pkgs[i]
}
func (pkgs ByPath) Less(i, j int) bool {
return strings.Compare(pkgs[i].ImportPath, pkgs[j].ImportPath) < 0
}

type ByShortPath []*gopkgs.Pkg

func (pkgs ByShortPath) Len() int {
return len(pkgs)
}
func (pkgs ByShortPath) Swap(i, j int) {
pkgs[i], pkgs[j] = pkgs[j], pkgs[i]
}
func (pkgs ByShortPath) Less(i, j int) bool {
return strings.Compare(pkgs[i].ImportPathShort, pkgs[j].ImportPathShort) < 0
}

type ByFullPath []*gopkgs.Pkg

func (pkgs ByFullPath) Len() int {
return len(pkgs)
}
func (pkgs ByFullPath) Swap(i, j int) {
pkgs[i], pkgs[j] = pkgs[j], pkgs[i]
}
func (pkgs ByFullPath) Less(i, j int) bool {
return strings.Compare(pkgs[i].Dir, pkgs[j].Dir) < 0
}

func uniq(s []*gopkgs.Pkg, f func(*gopkgs.Pkg) string) []*gopkgs.Pkg {
l := len(s)
if l == 0 || l == 1 {
return s
}

u := make([]*gopkgs.Pkg, 0, l)
prev := f(s[0])
for _, p := range s[1:] {
cur := f(p)
if prev == cur {
continue
}
u = append(u, p)
prev = cur
}

return u
}

func main() {
flag.Parse()

Expand Down Expand Up @@ -67,7 +125,20 @@ func main() {

opt := gopkgs.DefaultOption()
opt.IncludeName = *includeName
for _, pkg := range gopkgs.Packages(opt) {
pkgs := gopkgs.Packages(opt)

if *fullpath {
sort.Sort(ByFullPath(pkgs))
// Fullpaths is already unique
} else if *short {
sort.Sort(ByShortPath(pkgs))
pkgs = uniq(pkgs, func(p *gopkgs.Pkg) string { return p.ImportPathShort })
} else {
sort.Sort(ByPath(pkgs))
pkgs = uniq(pkgs, func(p *gopkgs.Pkg) string { return p.ImportPath })
}

for _, pkg := range pkgs {
tpl.Execute(w, pkg)
fmt.Fprintln(w)
}
Expand Down

0 comments on commit 29d3292

Please sign in to comment.