Handle file import digest

This commit is contained in:
nemunaire 2017-01-04 01:30:24 +01:00
parent 0b4e8a233c
commit 1bd403cd8c
4 changed files with 43 additions and 10 deletions

View file

@ -3,6 +3,8 @@ package fic
import (
"bufio"
"crypto/sha1"
"encoding/hex"
"errors"
"io"
"os"
"path"
@ -10,6 +12,7 @@ import (
)
var FilesDir string
var OptionalDigest bool
type EFile struct {
Id int64 `json:"id"`
@ -66,8 +69,10 @@ func (e Exercice) GetFiles() ([]EFile, error) {
}
}
func (e Exercice) ImportFile(filePath string, origin string) (EFile, error) {
if fi, err := os.Stat(filePath); err != nil {
func (e Exercice) ImportFile(filePath string, origin string, digest []byte) (EFile, error) {
if digest == nil && !OptionalDigest {
return EFile{}, errors.New("No digest given.")
} else if fi, err := os.Stat(filePath); err != nil {
return EFile{}, err
} else if fd, err := os.Open(filePath); err != nil {
return EFile{}, err
@ -80,8 +85,19 @@ func (e Exercice) ImportFile(filePath string, origin string) (EFile, error) {
return EFile{}, err
}
var result []byte
return e.AddFile(strings.TrimPrefix(filePath, FilesDir), origin, path.Base(filePath), hash.Sum(result), fi.Size())
result := hash.Sum(nil)
if len(digest) != len(result) {
return EFile{}, errors.New("Digests doesn't match: calculated: " + hex.EncodeToString(result) + " vs. given: " + hex.EncodeToString(digest))
}
for k := range result {
if result[k] != digest[k] {
return EFile{}, errors.New("Digests doesn't match: calculated: " + hex.EncodeToString(result) + " vs. given: " + hex.EncodeToString(digest))
}
}
return e.AddFile(strings.TrimPrefix(filePath, FilesDir), origin, path.Base(filePath), result, fi.Size())
}
}