Skip to content

Commit

Permalink
refactor: extract RemoveHosts to the blocker pkg and improve outputs
Browse files Browse the repository at this point in the history
  • Loading branch information
kauefraga committed Sep 29, 2024
1 parent 5a092a9 commit fa77797
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 26 deletions.
31 changes: 31 additions & 0 deletions internal/blocker/blocker.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,34 @@ func WriteHosts(hosts []string) error {

return os.WriteFile(HOSTS_PATH, []byte(newHostsFile), 0666)
}

// restore /etc/hosts
func RemoveHosts() error {
currentHostsFile, err := os.ReadFile(HOSTS_PATH)
if err != nil {
return err
}

var newHostsFile []string
isTsurugiBlockList := false

lines := strings.Split(string(currentHostsFile), "\n")
for _, line := range lines {
if strings.Contains(line, "# tsurugi blocks start") {
isTsurugiBlockList = true
}

if strings.Contains(line, "# tsurugi blocks end") {
isTsurugiBlockList = false
continue
}

if !isTsurugiBlockList {
newHostsFile = append(newHostsFile, line)
}
}

newHostsFileContent := strings.Join(newHostsFile, "\n")

return os.WriteFile(HOSTS_PATH, []byte(newHostsFileContent), 0666)
}
35 changes: 9 additions & 26 deletions internal/cmd/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package cmd
import (
"fmt"
"os"
"strings"

"github.com/fatih/color"
"github.com/kauefraga/tsurugi/internal/blocker"
"github.com/spf13/cobra"
)
Expand All @@ -14,34 +14,17 @@ var stopCmd = &cobra.Command{
Short: "Unblock websites",
Aliases: []string{"unblock", "allow"},
Run: func(cmd *cobra.Command, args []string) {
currentHostsFile, err := os.ReadFile(blocker.HOSTS_PATH)
err := blocker.RemoveHosts()
if err != nil {
fmt.Println(err)
color.Red("Error: could not unblock hosts")
fmt.Println("Might be lack of permissions, try again with sudo")
fmt.Println(
color.MagentaString("$"),
color.HiBlackString("sudo tsurugi stop"),
)
os.Exit(1)
}

var newHostsFile []string
isTsurugiBlockList := false

lines := strings.Split(string(currentHostsFile), "\n")
for _, line := range lines {
if strings.Contains(line, "# tsurugi blocks start") {
isTsurugiBlockList = true
}

if strings.Contains(line, "# tsurugi blocks end") {
isTsurugiBlockList = false
continue
}

if !isTsurugiBlockList {
newHostsFile = append(newHostsFile, line)
}
}

os.WriteFile(
blocker.HOSTS_PATH,
[]byte(strings.Join(newHostsFile, "\n")),
0666)
color.Green("You can access the websites again, enjoy!")
},
}

0 comments on commit fa77797

Please sign in to comment.