Implement ls command with alpha sorting and column alignment

pull/13/head
Chris Bednarski 9 years ago
parent ac92906cfc
commit 62832cd57b

@ -91,6 +91,12 @@ func main() {
Action: hostess.Fix,
Flags: app.Flags,
},
{
Name: "ls",
// Usage: "add a task to the list",
Action: hostess.Ls,
Flags: app.Flags,
},
}
// switch flag.Arg(0) {

@ -1,10 +1,10 @@
package hostess
import (
// "errors"
"fmt"
"github.com/codegangsta/cli"
"os"
"strings"
)
func MaybeErrorln(c *cli.Context, message string) {
@ -35,7 +35,7 @@ func MaybeLoadHostFile(c *cli.Context) *Hostfile {
return hostsfile
}
func SprintEnabled(on bool) string {
func ShowEnabled(on bool) string {
if on {
return "(On)"
} else {
@ -43,6 +43,14 @@ func SprintEnabled(on bool) string {
}
}
func ShowHostname(hostname Hostname) string {
return fmt.Sprintf("%s -> %s %s", hostname.Domain, hostname.Ip, ShowEnabled(hostname.Enabled))
}
func StrPadRight(s string, l int) string {
return s + strings.Repeat(" ", l-len(s))
}
func Add(c *cli.Context) {
if len(c.Args()) != 2 {
MaybeError(c, "expected <hostname> <ip>")
@ -55,7 +63,7 @@ func Add(c *cli.Context) {
if c.Bool("n") {
fmt.Println(hostsfile.Format())
} else {
MaybePrintln(c, fmt.Sprintf("Added %s -> %s %s", hostname.Domain, hostname.Ip, SprintEnabled(hostname.Enabled)))
MaybePrintln(c, fmt.Sprintf("Added %s", ShowHostname(hostname)))
hostsfile.Save()
}
} else {
@ -79,8 +87,28 @@ func On(c *cli.Context) error {
return nil
}
func Ls(c *cli.Context) error {
return nil
func Ls(c *cli.Context) {
hostfile := MaybeLoadHostFile(c)
maxdomain := 0
maxip := 0
for _, hostname := range hostfile.Hosts {
dlen := len(hostname.Domain)
if dlen > maxdomain {
maxdomain = dlen
}
ilen := len(hostname.Ip)
if ilen > maxip {
maxip = ilen
}
}
for _, domain := range hostfile.ListDomains() {
hostname := hostfile.Hosts[domain]
fmt.Printf("%s -> %s %s\n",
StrPadRight(hostname.Domain, maxdomain),
StrPadRight(hostname.Ip, maxip),
ShowEnabled(hostname.Enabled))
}
}
const fix_help = `Programmatically rewrite your hostsfile.

@ -223,6 +223,16 @@ func (h *Hostfile) ListDomainsByIp(ip string) []string {
return names
}
// ListDomains will return a list of domains in alphabetical order.
func (h *Hostfile) ListDomains() []string {
var names []string
for _, v := range h.Hosts {
names = append(names, v.Domain)
}
sort.Strings(names)
return names
}
// Format takes the current list of Hostnames in this Hostfile and turns it
// into a string suitable for use as an /etc/hosts file.
// Sorting uses the following logic:

Loading…
Cancel
Save