github.com/jameswoolfenden/terraform@v0.11.12-beta1/state/remote/file.go (about)

     1  package remote
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/md5"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  )
    10  
    11  func fileFactory(conf map[string]string) (Client, error) {
    12  	path, ok := conf["path"]
    13  	if !ok {
    14  		return nil, fmt.Errorf("missing 'path' configuration")
    15  	}
    16  
    17  	return &FileClient{
    18  		Path: path,
    19  	}, nil
    20  }
    21  
    22  // FileClient is a remote client that stores data locally on disk.
    23  // This is only used for development reasons to test remote state... locally.
    24  type FileClient struct {
    25  	Path string
    26  }
    27  
    28  func (c *FileClient) Get() (*Payload, error) {
    29  	var buf bytes.Buffer
    30  	f, err := os.Open(c.Path)
    31  	if err != nil {
    32  		if os.IsNotExist(err) {
    33  			return nil, nil
    34  		}
    35  
    36  		return nil, err
    37  	}
    38  	defer f.Close()
    39  
    40  	if _, err := io.Copy(&buf, f); err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	md5 := md5.Sum(buf.Bytes())
    45  	return &Payload{
    46  		Data: buf.Bytes(),
    47  		MD5:  md5[:],
    48  	}, nil
    49  }
    50  
    51  func (c *FileClient) Put(data []byte) error {
    52  	f, err := os.Create(c.Path)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	defer f.Close()
    57  
    58  	_, err = f.Write(data)
    59  	return err
    60  }
    61  
    62  func (c *FileClient) Delete() error {
    63  	return os.Remove(c.Path)
    64  }