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

     1  package otto
     2  
     3  import (
     4  	"encoding/json"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/hashicorp/otto/app"
     9  	"github.com/hashicorp/otto/foundation"
    10  	"github.com/hashicorp/otto/infrastructure"
    11  )
    12  
    13  // CompileMetadata is the stored metadata about a successful compilation.
    14  //
    15  // Failures during compilation result in no metadata at all being stored.
    16  // This metadata can be used to access various information about the resulting
    17  // compilation.
    18  type CompileMetadata struct {
    19  	// App is the result of compiling the main application
    20  	App *app.CompileResult `json:"app"`
    21  
    22  	// Deps are the results of compiling the dependencies, keyed by their
    23  	// unique Otto ID. If you want the tree structure then use the Appfile
    24  	// itself to search the dependency tree, then the ID of that dep
    25  	// to key into this map.
    26  	AppDeps map[string]*app.CompileResult `json:"app_deps"`
    27  
    28  	// Infra is the result of compiling the infrastructure for this application
    29  	Infra *infrastructure.CompileResult `json:"infra"`
    30  
    31  	// Foundations is the listing of top-level foundation compilation results.
    32  	Foundations map[string]*foundation.CompileResult `json:"foundations"`
    33  }
    34  
    35  func (c *Core) resetCompileMetadata() {
    36  	c.metadataCache = nil
    37  }
    38  
    39  func (c *Core) compileMetadata() (*CompileMetadata, error) {
    40  	if c.metadataCache != nil {
    41  		return c.metadataCache, nil
    42  	}
    43  
    44  	f, err := os.Open(filepath.Join(c.compileDir, "metadata.json"))
    45  	if err != nil {
    46  		if os.IsNotExist(err) {
    47  			return nil, nil
    48  		}
    49  
    50  		return nil, err
    51  	}
    52  	defer f.Close()
    53  
    54  	var result CompileMetadata
    55  	dec := json.NewDecoder(f)
    56  	if err := dec.Decode(&result); err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	c.metadataCache = &result
    61  	return &result, nil
    62  }
    63  
    64  func (c *Core) saveCompileMetadata(md *CompileMetadata) error {
    65  	if err := os.MkdirAll(c.compileDir, 0755); err != nil {
    66  		return err
    67  	}
    68  
    69  	f, err := os.Create(filepath.Join(c.compileDir, "metadata.json"))
    70  	if err != nil {
    71  		return err
    72  	}
    73  	defer f.Close()
    74  
    75  	enc := json.NewEncoder(f)
    76  	return enc.Encode(md)
    77  }