github.com/ernestokarim/closurer@v0.0.0-20130119214741-f245d086c750/soy/compile.go (about)

     1  package soy
     2  
     3  import (
     4  	"log"
     5  	"os"
     6  	"os/exec"
     7  	"path"
     8  	"path/filepath"
     9  
    10  	"github.com/ernestokarim/closurer/app"
    11  	"github.com/ernestokarim/closurer/cache"
    12  	"github.com/ernestokarim/closurer/config"
    13  	"github.com/ernestokarim/closurer/scan"
    14  )
    15  
    16  // Compile all modified templates
    17  func Compile() error {
    18  	conf := config.Current()
    19  
    20  	if conf.Soy == nil || conf.Soy.Root == "" {
    21  		return nil
    22  	}
    23  
    24  	if err := os.MkdirAll(path.Join(conf.Build, "templates"), 0755); err != nil {
    25  		return app.Error(err)
    26  	}
    27  
    28  	buildPrefix := filepath.Join(conf.Build, "templates")
    29  	oldSoy, err := scan.Do(buildPrefix, ".js")
    30  	if err != nil {
    31  		return err
    32  	}
    33  
    34  	soy, err := scan.Do(conf.Soy.Root, ".soy")
    35  	if err != nil {
    36  		return err
    37  	}
    38  
    39  	indexed := map[string]bool{}
    40  	for _, f := range soy {
    41  		f = f[len(conf.Soy.Root):]
    42  		indexed[f] = true
    43  	}
    44  
    45  	// Delete compiled templates no longer present in the sources
    46  	for _, f := range oldSoy {
    47  		compare := f[len(buildPrefix) : len(f)-3]
    48  		if _, ok := indexed[compare]; !ok {
    49  			if err := os.Remove(f); err != nil {
    50  				return app.Error(err)
    51  			}
    52  		}
    53  	}
    54  
    55  	if len(soy) == 0 {
    56  		return nil
    57  	}
    58  
    59  	for _, t := range soy {
    60  		if modified, err := cache.Modified("compile", t); err != nil {
    61  			return err
    62  		} else if !modified {
    63  			continue
    64  		}
    65  
    66  		prel, err := filepath.Rel(conf.Soy.Root, t)
    67  		if err != nil {
    68  			return app.Error(err)
    69  		}
    70  
    71  		out := path.Join(conf.Build, "templates", prel+".js")
    72  		if err := os.MkdirAll(path.Dir(out), 0755); err != nil {
    73  			return app.Error(err)
    74  		}
    75  
    76  		log.Println("Compiling template", t, "...")
    77  
    78  		// Run the compiler command
    79  		cmd := exec.Command(
    80  			"java",
    81  			"-jar", path.Join(conf.Soy.Compiler, "build", "SoyToJsSrcCompiler.jar"),
    82  			"--outputPathFormat", out,
    83  			"--shouldGenerateJsdoc",
    84  			"--shouldProvideRequireSoyNamespaces",
    85  			"--cssHandlingScheme", "goog",
    86  			t)
    87  
    88  		output, err := cmd.CombinedOutput()
    89  		if err != nil {
    90  			return app.Errorf("exec error with %s: %s\n%s", t, err, string(output))
    91  		}
    92  
    93  		log.Println("Done compiling template!")
    94  	}
    95  
    96  	return nil
    97  }