View Javadoc
1   package com.github.searls.jasmine.runner;
2   
3   import com.github.searls.jasmine.config.JasmineConfiguration;
4   import com.github.searls.jasmine.io.scripts.BasicScriptResolver;
5   import com.github.searls.jasmine.io.scripts.ContextPathScriptResolver;
6   import com.github.searls.jasmine.io.scripts.ScriptResolver;
7   import org.apache.commons.io.FileUtils;
8   import org.apache.commons.lang3.StringUtils;
9   import org.apache.maven.plugin.logging.Log;
10  
11  import java.io.File;
12  import java.io.IOException;
13  
14  public class CreatesRunner {
15  
16    private final JasmineConfiguration config;
17  
18    private final Log log;
19    private final String runnerFileName;
20    private final ReporterType reporterType;
21  
22    public CreatesRunner(JasmineConfiguration config, Log log, String runnerFileName, ReporterType reporterType) {
23      this.config = config;
24      this.runnerFileName = runnerFileName;
25      this.reporterType = reporterType;
26      this.log = log;
27    }
28  
29    public String getRunnerFile() {
30      return this.runnerFileName;
31    }
32  
33    public void create() throws IOException {
34      File runnerDestination = new File(this.config.getJasmineTargetDir(), this.runnerFileName);
35      ScriptResolver resolver = new BasicScriptResolver(
36        config.getBasedir(),
37        config.getSources(),
38        config.getSpecs(),
39        config.getPreloadSources());
40      resolver = new ContextPathScriptResolver(
41        resolver,
42        config.getSrcDirectoryName(),
43        config.getSpecDirectoryName());
44  
45      SpecRunnerHtmlGenerator generator = new SpecRunnerHtmlGeneratorFactory().create(this.reporterType, this.config, resolver);
46  
47      String newRunnerHtml = generator.generate();
48      if (this.newRunnerDiffersFromOldRunner(runnerDestination, newRunnerHtml)) {
49        this.saveRunner(runnerDestination, newRunnerHtml);
50      } else {
51        this.log.info("Skipping spec runner generation, because an identical spec runner already exists.");
52      }
53    }
54  
55    private String existingRunner(File destination) throws IOException {
56      String existingRunner = null;
57      try {
58        if (destination.exists()) {
59          existingRunner = FileUtils.readFileToString(destination);
60        }
61      } catch (IOException e) {
62        this.log.warn("An error occurred while trying to open an existing manual spec runner. Continuing.");
63      }
64      return existingRunner;
65    }
66  
67    private boolean newRunnerDiffersFromOldRunner(File runnerDestination, String newRunner) throws IOException {
68      return !StringUtils.equals(newRunner, this.existingRunner(runnerDestination));
69    }
70  
71    private void saveRunner(File runnerDestination, String newRunner) throws IOException {
72      FileUtils.writeStringToFile(runnerDestination, newRunner, this.config.getSourceEncoding());
73    }
74  }