Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Helper functions for update feature #22

Open
wants to merge 2 commits into
base: updater
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions cmd/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package cmd

import (
"bytes"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"

"lukechampine.com/blake3"
)

func CreateCheckSumFile(writePath string, filename string, reader io.ReadCloser) {
fileExtBlake3 := addBlakeExtension(filename)
file, _ := os.Create(filepath.Join(writePath, fileExtBlake3))
var fileBytes []byte
fileBytes, _ = ioutil.ReadAll(reader)
byteHash := blake3.Sum256(fileBytes)

hashReader := bytes.NewReader(byteHash[:])

if _, err := io.Copy(file, hashReader); err != nil { // that side effect I mentioned in the above for loop makes this possible to do out of loop.
log.Fatal(err)
}
}

func isEqualFiles(writePath string, filename string, reader io.ReadCloser) bool {
fileExtBlake3 := addBlakeExtension(filename)
previousHash, _ := ioutil.ReadFile(filepath.Join(writePath, fileExtBlake3))
var fileBytes []byte
fileBytes, _ = ioutil.ReadAll(reader)
newHash := blake3.Sum256(fileBytes)
return bytes.Equal(previousHash, newHash[:])
}

func addBlakeExtension(fileName string) string {
if pos := strings.LastIndexByte(fileName, '.'); pos != -1 {
return fileName[:pos] + ".blake3"
}
return fileName + ".blake3"
}
19 changes: 19 additions & 0 deletions cmd/update_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package cmd

import (
"fmt"
"log"
"net/http"
)

func ExampleIsEqualFiles() {
response, err := http.Get("https://ftp.expasy.org/databases/rhea/rdf/rhea.rdf.gz")

if err != nil {
log.Fatal(err)
}

defer response.Body.Close()
fmt.Println(isEqualFiles("../data/build", "rhea.rdf.gz", response.Body))
//Output: true
}
2 changes: 2 additions & 0 deletions data/build/rhea.rdf.blake3
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
�䊰*Mg�T5p2
k�-��||">�T�!�ro:
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ require (
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
lukechampine.com/blake3 v1.0.0 // indirect
)