github.com/leowmjw/otto@v0.2.1-0.20160126165905-6400716cf085/app/dev.go (about)

     1  package app
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"path/filepath"
    10  )
    11  
    12  // DevDep has information about an upstream dependency that should be
    13  // used by the Dev function in order to build a complete development
    14  // environment.
    15  type DevDep struct {
    16  	// Files is a list of files that this dependency created or uses.
    17  	// If these files already exist, then future DevDep calls won't be
    18  	// called and the cached data will be used.
    19  	//
    20  	// All files in this must be in the Context.CacheDir. Relative paths
    21  	// will be expanded relative to the CacheDir. If the file is not
    22  	// in the CacheDir, no caching will occur. The log will note if this
    23  	// is happening.
    24  	Files []string `json:"files"`
    25  }
    26  
    27  // RelFiles makes all the Files values relative to the given directory.
    28  func (d *DevDep) RelFiles(dir string) error {
    29  	for i, f := range d.Files {
    30  		// If the path is already relative, ignore it
    31  		if !filepath.IsAbs(f) {
    32  			continue
    33  		}
    34  
    35  		// Make the path relative
    36  		f, err := filepath.Rel(dir, f)
    37  		if err != nil {
    38  			return fmt.Errorf(
    39  				"couldn't make directory relative: %s\n\n%s",
    40  				d.Files[i], err)
    41  		}
    42  
    43  		d.Files[i] = f
    44  	}
    45  
    46  	return nil
    47  }
    48  
    49  // ReadDevDep reads a marshalled DevDep from disk.
    50  func ReadDevDep(path string) (*DevDep, error) {
    51  	f, err := os.Open(path)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	defer f.Close()
    56  
    57  	var result DevDep
    58  	dec := json.NewDecoder(f)
    59  	if err := dec.Decode(&result); err != nil {
    60  		return nil, err
    61  	}
    62  
    63  	return &result, nil
    64  }
    65  
    66  // WriteDevDep writes a DevDep out to disk.
    67  func WriteDevDep(path string, dep *DevDep) error {
    68  	// Pretty-print the JSON data so that it can be more easily inspected
    69  	data, err := json.MarshalIndent(dep, "", "    ")
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	// Write it out
    75  	f, err := os.Create(path)
    76  	if err != nil {
    77  		return err
    78  	}
    79  	defer f.Close()
    80  
    81  	_, err = io.Copy(f, bytes.NewReader(data))
    82  	return err
    83  }