2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-22 04:45:15 +00:00
restic/object.go

67 lines
1.0 KiB
Go
Raw Normal View History

2014-08-04 18:47:04 +00:00
package khepri
2014-08-04 20:46:14 +00:00
import (
"io"
"os"
)
2014-08-04 18:47:04 +00:00
2014-08-04 20:46:14 +00:00
type createObject struct {
2014-08-04 18:47:04 +00:00
repo *Repository
tpe Type
hw HashingWriter
file *os.File
2014-08-04 20:46:14 +00:00
ch chan ID
2014-08-04 18:47:04 +00:00
}
2014-08-04 20:46:14 +00:00
func (repo *Repository) Create(t Type) (io.WriteCloser, <-chan ID, error) {
obj := &createObject{
2014-08-04 18:47:04 +00:00
repo: repo,
tpe: t,
2014-08-04 20:46:14 +00:00
ch: make(chan ID, 1),
2014-08-04 18:47:04 +00:00
}
2014-08-04 20:46:14 +00:00
// save contents to tempfile in repository, hash while writing
var err error
obj.file, err = obj.repo.tempFile()
if err != nil {
return nil, nil, err
2014-08-04 18:47:04 +00:00
}
2014-08-04 20:46:14 +00:00
// create hashing writer
obj.hw = NewHashingWriter(obj.file, obj.repo.hash)
2014-08-04 18:47:04 +00:00
2014-08-04 20:46:14 +00:00
return obj, obj.ch, nil
2014-08-04 18:47:04 +00:00
}
2014-08-04 20:46:14 +00:00
func (obj *createObject) Write(data []byte) (int, error) {
if obj.hw == nil {
panic("createObject: already closed!")
2014-08-04 18:47:04 +00:00
}
return obj.hw.Write(data)
}
2014-08-04 20:46:14 +00:00
func (obj *createObject) Close() error {
if obj.hw == nil {
panic("createObject: already closed!")
2014-08-04 18:47:04 +00:00
}
obj.file.Close()
2014-08-04 20:46:14 +00:00
id := ID(obj.hw.Hash())
obj.ch <- id
2014-08-04 18:47:04 +00:00
// move file to final name using hash of contents
err := obj.repo.renameFile(obj.file, obj.tpe, id)
if err != nil {
return err
}
obj.hw = nil
obj.file = nil
return nil
}