Add option to enable scalafmt for code formatting (#1032)

* add option to enable scalafmt for code formatting

* fix typo
This commit is contained in:
William Cheng
2018-09-14 16:58:27 +08:00
committed by GitHub
parent 48e66ed627
commit fc35bb17d0
17 changed files with 747 additions and 543 deletions

View File

@@ -21,6 +21,7 @@ import com.samskivert.mustache.Escapers;
import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
@@ -113,6 +114,10 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("SCALAFMT_PATH"))) {
LOGGER.info("Environment variable SCALAFMT_PATH not defined so the Scala code may not be properly formatted. To define it, try 'export SCALAFMT_PATH=/usr/local/bin/scalafmt' (Linux/Mac)");
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
@@ -298,4 +303,31 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
return input.replace("\"", "");
}
@Override
public void postProcessFile(File file, String fileType) {
if (file == null) {
return;
}
String scalafmtPath = System.getenv("SCALAFMT_PATH");
if (StringUtils.isEmpty(scalafmtPath)) {
return; // skip if SCALAFMT_PATH env variable is not defined
}
// only process files with scala extension
if ("scala".equals(FilenameUtils.getExtension(file.toString()))) {
String command = scalafmtPath + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
if (p.exitValue() != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, p.exitValue());
}
LOGGER.info("Successfully executed: " + command);
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
}