Skip to content

Commit

Permalink
feature comment filtering list
Browse files Browse the repository at this point in the history
  • Loading branch information
ShuheiKubota committed Oct 4, 2019
1 parent 4999430 commit c0f9856
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 12 deletions.
35 changes: 23 additions & 12 deletions cmd_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@ package main

import (
"errors"
"strings"

"github.com/shu-go/clise"
)

type deleteCmd struct {
_ struct{} `help:"delete an entry with --ip 192.168.1.200 and/or --host oldserver"`
IP *string
Host *string
_ struct{} `help:"delete an entry with --ip 192.168.1.200 and/or --host oldserver"`

IP *string
Host *string
Comment *string
}

func (c deleteCmd) Run(g globalCmd) error {
if c.IP == nil && c.Host == nil {
return errors.New("IP or Host is required")
if c.IP == nil && c.Host == nil && c.Comment == nil {
return errors.New("IP or Host or Comment is required")
}

el, err := readEntries(g.Hosts)
Expand All @@ -33,14 +36,22 @@ func (c deleteCmd) Run(g globalCmd) error {

func (c deleteCmd) deleteFrom(el []entry) ([]entry, bool) {
changed := false

clise.Filter(&el, func(i int) bool {
if c.IP != nil && c.Host != nil && el[i].IP == *c.IP && el[i].Host == *c.Host {
changed = true
return false
} else if c.IP != nil && el[i].IP == *c.IP {
changed = true
return false
} else if c.Host != nil && el[i].Host == *c.Host {
e := el[i]

deleting := true
if c.IP != nil {
deleting = deleting && (e.IP == *c.IP)
}
if c.Host != nil {
deleting = deleting && (e.Host == *c.Host)
}
if c.Comment != nil {
deleting = deleting && strings.Contains(e.Comment, *c.Comment)
}

if deleting {
changed = true
return false
}
Expand Down
36 changes: 36 additions & 0 deletions cmd_delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,42 @@ func TestCmdDelete(t *testing.T) {
::1 localhost
# 118.151.235.191 example.com
# 192.168.1.201 server01 # new server
`)
})

t.Run("Comment", func(t *testing.T) {
el := read(hosts)
comment := "server"
del := deleteCmd{
Comment: &comment,
}
el, changed := del.deleteFrom(el)

gotwant.Test(t, changed, true)

result := list(el)
gotwant.Test(t, result, `# 38.25.63.10 x.acme.com # x client host
127.0.0.1 localhost # THIS IS LOCALHOST
::1 localhost
# 118.151.235.191 example.com
`)

el = read(hosts)
comment = "hgoehgoelocalhost"
del = deleteCmd{
Comment: &comment,
}
el, changed = del.deleteFrom(el)

gotwant.Test(t, changed, false)

result = list(el)
gotwant.Test(t, result, `# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
127.0.0.1 localhost # THIS IS LOCALHOST
::1 localhost
# 118.151.235.191 example.com
# 192.168.1.201 server01 # new server
`)
})
}

0 comments on commit c0f9856

Please sign in to comment.