Skip to content

Commit

Permalink
feat: add update rules file command
Browse files Browse the repository at this point in the history
  • Loading branch information
doron-cohen committed Oct 15, 2020
1 parent 7f6d912 commit 43fee94
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 1 deletion.
28 changes: 28 additions & 0 deletions cmd/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package cmd

import (
"log"

"github.com/doron-cohen/antidot/internal/utils"
"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(updateCmd)
}

var rulesSource = "https://raw.githubusercontent.com/doron-cohen/antidot/master/rules.yaml"

var updateCmd = &cobra.Command{
Use: "update",
Short: "Update rules file",
Run: func(cmd *cobra.Command, args []string) {
log.Printf("Updating rules...")
err := utils.Download(rulesSource, rulesFilePath)
if err != nil {
log.Fatalf("Failed to update rules: %v", err)
}

log.Printf("Rules updated")
},
}
36 changes: 36 additions & 0 deletions internal/utils/fetch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package utils

import (
"io"
"io/ioutil"
"log"
"net/http"
"os"
)

func Download(src, dest string) error {
resp, err := http.Get(src)
if err != nil {
return err
}
// TODO: check for close() errors (across the code)
defer resp.Body.Close()

tempFile, err := ioutil.TempFile("", "rules.*.yaml")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tempFile.Name())

_, err = io.Copy(tempFile, resp.Body)
if err != nil {
return err
}

err = MoveFile(tempFile.Name(), dest)
if err != nil {
return err
}

return nil
}
32 changes: 31 additions & 1 deletion internal/utils/files.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package utils

import "os"
import (
"fmt"
"io"
"os"
)

func FileExists(filename string) bool {
_, err := os.Stat(filename)
Expand All @@ -9,3 +13,29 @@ func FileExists(filename string) bool {
}
return true
}

func MoveFile(sourcePath, destPath string) error {
inputFile, err := os.Open(sourcePath)
if err != nil {
return fmt.Errorf("Couldn't open source file: %s", err)
}

outputFile, err := os.Create(destPath)
if err != nil {
inputFile.Close()
return fmt.Errorf("Couldn't open dest file: %s", err)
}
defer outputFile.Close()

_, err = io.Copy(outputFile, inputFile)
inputFile.Close()
if err != nil {
return fmt.Errorf("Writing to output file failed: %s", err)
}

err = os.Remove(sourcePath)
if err != nil {
return fmt.Errorf("Failed removing original file: %s", err)
}
return nil
}

0 comments on commit 43fee94

Please sign in to comment.