Skip to content

Commit

Permalink
Refresh and refresh interval support
Browse files Browse the repository at this point in the history
Closes #1.  This allows unresolved hosts to be refreshed at specific durations.
  • Loading branch information
rcaught committed Oct 19, 2019
1 parent c2e3815 commit ea9f5ae
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import (
)

func overrideCmd() *cobra.Command {
var refresh bool
var refreshInterval time.Duration

rootCmd := &cobra.Command{
Use: "hosts-override [(IP|HOST_NAME),IP...]",
Short: "Override hosts file entries for the lifetime of the process",
Expand All @@ -27,23 +30,50 @@ func overrideCmd() *cobra.Command {
hostsFileLocation := hostsFileLocation()
createHostsBackup(hostsFileLocation)
removeOverrides(hostsFileLocation) // Fixes unclean shutdown
parsedOverrides := parsedOverrides(hosts, values)
parsedOverridesForHosts := parsedOverridesForHosts(parsedOverrides)
appendOverrides(hostsFileLocation, parsedOverridesForHosts)
fmt.Println("\nAdding the following hosts file entries for the lifetime of this process:")
fmt.Println("\n" + *parsedOverridesAsHosts(parsedOverrides) + "\n")

fmt.Println("\nOverriding hosts file entries for the lifetime of the process:")
parseAndAppend(hosts, values, hostsFileLocation, &refresh, &refreshInterval)

if refresh == true {
refreshTicker := time.NewTicker(refreshInterval)

go func() {
for {
select {
case <-refreshTicker.C:
removeOverrides(hostsFileLocation)
parseAndAppend(hosts, values, hostsFileLocation, &refresh, &refreshInterval)
}
}
}()
}

waitUntilExit()
removeOverrides(hostsFileLocation)
},
}

rootCmd.Flags().BoolVarP(&refresh, "refresh", "r", false, "Refresh unresolved hosts")
rootCmd.Flags().DurationVarP(&refreshInterval, "refresh-interval", "i", time.Duration(300)*time.Second, "Refresh Interval")

return rootCmd
}

func main() {
overrideCmd().Execute()
}

func parseAndAppend(hosts *[]string, values *[]string, hostsFileLocation *string, refresh *bool, refreshInterval *time.Duration) {
parsedOverrides := parsedOverrides(hosts, values)
parsedOverridesForHosts := parsedOverridesForHosts(parsedOverrides)
appendOverrides(hostsFileLocation, parsedOverridesForHosts)
if *refresh == true {
fmt.Println("\n(Refreshing in " + refreshInterval.String() + ")...")
}
fmt.Println("\n" + *parsedOverridesAsHosts(parsedOverrides) + "\n")
fmt.Println("\nPress CTRL-C to exit")
}

func parseArgs(args *[]string) (*[]string, *[]string) {
var hosts []string
var values []string
Expand Down Expand Up @@ -209,6 +239,5 @@ func waitUntilExit() {
done <- true
}()

fmt.Println("\nPress CTRL-C to exit")
<-done
}

0 comments on commit ea9f5ae

Please sign in to comment.