github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/resource/content.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package resource
     5  
     6  // TODO(ericsnow) Move this file to the charm repo?
     7  
     8  import (
     9  	"io"
    10  	"os"
    11  
    12  	"github.com/juju/errors"
    13  	"github.com/juju/utils"
    14  	charmresource "gopkg.in/juju/charm.v6-unstable/resource"
    15  )
    16  
    17  // Content holds a reader for the content of a resource along
    18  // with details about that content.
    19  type Content struct {
    20  	// Data holds the resouce content, ready to be read (once).
    21  	Data io.Reader
    22  
    23  	// Size is the byte count of the data.
    24  	Size int64
    25  
    26  	// Fingerprint holds the checksum of the data.
    27  	Fingerprint charmresource.Fingerprint
    28  }
    29  
    30  // GenerateContent returns a new Content for the given data stream.
    31  func GenerateContent(reader io.ReadSeeker) (Content, error) {
    32  	var sizer utils.SizeTracker
    33  	sizingReader := io.TeeReader(reader, &sizer)
    34  	fp, err := charmresource.GenerateFingerprint(sizingReader)
    35  	if err != nil {
    36  		return Content{}, errors.Trace(err)
    37  	}
    38  	if _, err := reader.Seek(0, os.SEEK_SET); err != nil {
    39  		return Content{}, errors.Trace(err)
    40  	}
    41  	size := sizer.Size()
    42  
    43  	content := Content{
    44  		Data:        reader,
    45  		Size:        size,
    46  		Fingerprint: fp,
    47  	}
    48  	return content, nil
    49  }