Skip to content

Commit

Permalink
use digest to check if a file is modified
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmood committed Jan 13, 2024
1 parent 7129cd3 commit 36b5aa9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 21 deletions.
44 changes: 24 additions & 20 deletions batch.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package main

import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
Expand Down Expand Up @@ -80,8 +83,6 @@ func (b *Batch) getMembers(group string, visited []string) ([]string, error) {
}
}

slices.Sort(members)

return members, nil
}

Expand Down Expand Up @@ -194,12 +195,12 @@ func (b *Batch) Encrypt() error {
Public: getPublicKeys(members),
}

same, err := b.sameRecipients(conf, outPath)
same, err := b.same(conf, inPath, outPath)
if err != nil {
return err
}
if same {
fmt.Fprintf(os.Stderr, "[skip] recipients not changed: %s\n", inPath)
fmt.Fprintf(os.Stderr, "[skip] not changed: %s\n", inPath)
return nil
}

Expand Down Expand Up @@ -272,34 +273,37 @@ func (b *Batch) Decrypt(privateKeyPath string) error {
return eg.Wait()
}

func (b *Batch) sameRecipients(conf whisper.Config, out string) (bool, error) {
if _, err := os.Stat(out); os.IsNotExist(err) {
return false, nil
}
func (b *Batch) same(conf whisper.Config, inPath, outPath string) (bool, error) {
hash := sha256.New()

input, err := os.Open(out)
err := json.NewEncoder(hash).Encode(conf)
if err != nil {
return false, err
}

defer func() { _ = input.Close() }()
inFile, err := os.Open(inPath)
if err != nil {
return false, err
}
defer func() { _ = inFile.Close() }()

_, hashList, err := conf.Recipients()
_, err = io.Copy(hash, inFile)
if err != nil {
return false, err
}

meta, _ := getMeta(input)
digest := hash.Sum(nil)

if len(hashList) != len(meta.Recipients) {
return false, nil
}
digestPath := outPath + WHISPER_DIGEST_EXT

for _, h := range hashList {
if _, has := meta.Recipients[string(h[:meta.HashSize()])]; !has {
return false, nil
}
defer func() {
_ = os.WriteFile(digestPath, digest, 0o644)
}()

previousDigest, err := os.ReadFile(digestPath)
if err != nil {
return false, nil //nolint: nilerr
}

return true, nil
return bytes.Equal(digest, previousDigest), nil
}
2 changes: 2 additions & 0 deletions constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ const WHISPER_AGENT_ADDR_DEFAULT = "127.0.0.1:57217"
const AS_AGENT_FLAG = "run-as-agent"

const WHISPER_FILE_EXT = ".wsp"

const WHISPER_DIGEST_EXT = ".digest"
2 changes: 1 addition & 1 deletion lib/whisper.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

const (
APIVersion = "v0.8.11"
APIVersion = "v0.8.12"
WireFormatVersion = byte(8)
)

Expand Down

0 comments on commit 36b5aa9

Please sign in to comment.