Skip to content

Commit

Permalink
Fix #9 Add support for loading default config from a file
Browse files Browse the repository at this point in the history
  • Loading branch information
juhasipo committed Mar 3, 2019
1 parent bc170da commit 92f7fc7
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 13 deletions.
47 changes: 39 additions & 8 deletions src/main/java/com/vincit/go/task/slack/SlackTaskPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@
import com.vincit.go.task.slack.model.Config;
import com.vincit.go.task.slack.model.Context;
import com.vincit.go.task.slack.model.TaskConfig;
import com.vincit.go.task.slack.utils.EnvReader;
import com.vincit.go.task.slack.utils.EnvVarReplacer;
import com.vincit.go.task.slack.utils.FileReader;
import com.vincit.go.task.slack.utils.JsonUtil;
import com.vincit.go.task.slack.utils.EnvVarReplacer;

import java.io.IOException;
import java.util.HashMap;
Expand All @@ -40,24 +41,54 @@
@Extension
public class SlackTaskPlugin extends AbstractTaskPlugin {

private static final String CONFIG_FILE_PATH = "gocd-slack-task-config.json";
private static final String HOME_DIR = System.getProperty("user.home");
private static final String CRUISE_SERVER_DIR_ENV_VAR_NAME = "CRUISE_SERVER_DIR";
private static final String CONFIG_DIR_ENV_VAR_NAME = "GOCD_SLACK_TASK_CONFIG_DIR";
private Logger logger = Logger.getLoggerFor(SlackTaskPlugin.class);

private JsonUtil jsonUtil;
private FileReader fileReader;
private SlackExecutorFactory slackExecutorFactory;
private Config defaultConfig;
private EnvReader envReader;

public SlackTaskPlugin() {
super("task", "1.0");
jsonUtil = new JsonUtil();
fileReader = new FileReader();
slackExecutorFactory = new SlackExecutorFactory();
this(
new JsonUtil(),
new FileReader(),
new SlackExecutorFactory(),
new EnvReader()
);
}

public SlackTaskPlugin(JsonUtil jsonUtil, FileReader fileReader, SlackExecutorFactory slackExecutorFactory) {
this();
public SlackTaskPlugin(JsonUtil jsonUtil, FileReader fileReader, SlackExecutorFactory slackExecutorFactory,
EnvReader envReader) {
super("task", "1.0");
this.jsonUtil = jsonUtil;
this.fileReader = fileReader;
this.slackExecutorFactory = slackExecutorFactory;
this.envReader = envReader;

final String configFileContent = this.fileReader.getFileContents(
joinPath(this.envReader.get(CONFIG_DIR_ENV_VAR_NAME), CONFIG_FILE_PATH),
joinPath(HOME_DIR, CONFIG_FILE_PATH),
joinPath(this.envReader.get(CRUISE_SERVER_DIR_ENV_VAR_NAME), CONFIG_FILE_PATH)
);
defaultConfig = jsonUtil.fromJSON(configFileContent, Config.class);
}

private String joinPath(String base, String file) {
if (base != null) {
final String pathSeparator = System.getProperty("file.separator");
if (base.endsWith(pathSeparator)) {
return base + file;
} else {
return base + pathSeparator + file;
}
} else {
return null;
}
}

@Override
Expand All @@ -78,13 +109,13 @@ protected GoPluginApiResponse handleTaskView(GoPluginApiRequest request) {

@Override
protected GoPluginApiResponse handleTaskExecution(GoPluginApiRequest request) {

TaskConfig executionRequest = jsonUtil.fromJSON(request.requestBody(), TaskConfig.class);
Context context = executionRequest.getContext();

EnvVarReplacer envVarReplacer = new EnvVarReplacer(context.getEnvironmentVariables());

Config config = executionRequest.getConfig()
.or(defaultConfig)
.replace(envVarReplacer);

String webhookUrl = config.getWebhookUrl();
Expand Down
20 changes: 20 additions & 0 deletions src/main/java/com/vincit/go/task/slack/model/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,24 @@ public Config replace(EnvVarReplacer envVarReplacer) {
failOnError
);
}

public Config or(Config defaultConfig) {
if (defaultConfig == null) {
return this;
} else {
return new Config(
webhookUrl.or(defaultConfig.webhookUrl),
channel.or(defaultConfig.channel),
channelType.or(defaultConfig.channelType),
displayName.or(defaultConfig.displayName),
title.or(defaultConfig.title),
message.or(defaultConfig.message),
iconOrEmoji.or(defaultConfig.iconOrEmoji),
colorType.or(defaultConfig.colorType),
color.or(defaultConfig.color),
markdownInText,
failOnError
);
}
}
}
8 changes: 8 additions & 0 deletions src/main/java/com/vincit/go/task/slack/model/Property.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,12 @@ public Property replace(EnvVarReplacer envVarReplacer) {
this.required
);
}

public Property or(Property defaultValue) {
if (isPresent()) {
return this;
} else {
return defaultValue;
}
}
}
21 changes: 21 additions & 0 deletions src/main/java/com/vincit/go/task/slack/utils/EnvReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.vincit.go.task.slack.utils;

import in.ashwanthkumar.utils.lang.StringUtils;

public class EnvReader {

public EnvReader() {}

public String get(String name, String defaultValue) {
final String value = System.getenv(name);
if (StringUtils.isNotEmpty(value)) {
return value;
} else {
return defaultValue;
}
}

public String get(String name) {
return get(name, null);
}
}
20 changes: 20 additions & 0 deletions src/main/java/com/vincit/go/task/slack/utils/FileReader.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
package com.vincit.go.task.slack.utils;

import com.thoughtworks.go.plugin.api.logging.Logger;
import in.ashwanthkumar.utils.lang.StringUtils;
import org.apache.commons.io.IOUtils;

import java.io.IOException;

public class FileReader {

public static final String FILE_ENCODING = "UTF-8";

private Logger logger = Logger.getLoggerFor(FileReader.class);

public String getFileContents(String filePath) throws IOException {
return IOUtils.toString(getClass().getResourceAsStream(filePath), FILE_ENCODING);
}

public String getFileContents(String... filePaths) {
for (String filePath : filePaths) {
try {
if (StringUtils.isNotEmpty(filePath)) {
logger.debug("Reading file '" + filePath + "'");
return getFileContents(filePath);
} else {
logger.debug("Null/empty path, ignore");
}
} catch (IOException e) {
logger.debug("Could not read file '" + filePath + "'");
}
}
return null;
}

}
11 changes: 6 additions & 5 deletions src/test/java/com/vincit/go/task/slack/SlackTaskPluginTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.vincit.go.task.slack.executor.TaskSlackDestination;
import com.vincit.go.task.slack.executor.TaskSlackMessage;
import com.vincit.go.task.slack.model.*;
import com.vincit.go.task.slack.utils.EnvReader;
import com.vincit.go.task.slack.utils.FileReader;
import com.vincit.go.task.slack.utils.JsonUtil;
import org.junit.Test;
Expand Down Expand Up @@ -82,7 +83,7 @@ public void testHandleTaskExecution() throws Exception {
FileReader fileReader = mock(FileReader.class);
MockSlackContainer slack = mockSlack(false);

SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory);
SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory, new EnvReader());

DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("task", "1.0", "execute");
request.setRequestBody("test-request");
Expand Down Expand Up @@ -125,7 +126,7 @@ public void testHandleValidation() throws Exception {
FileReader fileReader = mock(FileReader.class);
MockSlackContainer slack = mockSlack(false);

SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory);
SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory, new EnvReader());

DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("task", "1.0", "validate");
request.setRequestBody("test-request");
Expand Down Expand Up @@ -157,7 +158,7 @@ public void testHandleValidationRequiredErrors() throws Exception {
FileReader fileReader = mock(FileReader.class);
MockSlackContainer slack = mockSlack(false);

SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory);
SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory, new EnvReader());

DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("task", "1.0", "validate");
request.setRequestBody("test-request");
Expand All @@ -181,7 +182,7 @@ public void testConfig() throws Exception {
FileReader fileReader = mock(FileReader.class);
MockSlackContainer slack = mockSlack(false);

SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory);
SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory, new EnvReader());

DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("task", "1.0", "configuration");
request.setRequestBody("test-request");
Expand Down Expand Up @@ -226,7 +227,7 @@ public void testHandleFailedSlackMessage() throws Exception {
FileReader fileReader = mock(FileReader.class);
MockSlackContainer slack = mockSlack(true);

SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory);
SlackTaskPlugin plugin = new SlackTaskPlugin(jsonUtil, fileReader, slack.slackExecutorFactory, new EnvReader());

DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("task", "1.0", "execute");
request.setRequestBody("test-request");
Expand Down
28 changes: 28 additions & 0 deletions src/test/java/com/vincit/go/task/slack/model/ConfigTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,35 @@ public void parseTargetConfig() throws Exception {
assertThat(taskConfig.getContext(), notNullValue());
assertThat(taskConfig.getContext().getEnvironmentVariables(), hasKey("VAR1"));
assertThat(taskConfig.getContext().getEnvironmentVariables(), hasKey("VAR2"));
}

@Test
public void orDefaultConfig() throws Exception {
TaskConfig emptyConfig = new JsonUtil().fromJSON(
new FileReader().getFileContents("/json/empty_task_config.json"),
TaskConfig.class
);
TaskConfig defaultConfig = new JsonUtil().fromJSON(
new FileReader().getFileContents("/json/task_config.json"),
TaskConfig.class
);

final Config config = emptyConfig.getConfig().or(defaultConfig.getConfig());

assertThat(config, notNullValue());
assertThat(config.getWebhookUrl(), is("https://example.org"));
assertThat(config.getChannel(), is("channel"));
assertThat(config.getChannelType(), is(ChannelType.CHANNEL));
assertThat(config.getDisplayName(), is("display-name"));
assertThat(config.getTitle(), is("title"));
assertThat(config.getMessage(), is("message"));
assertThat(config.getIconOrEmoji(), is(":tada:"));
assertThat(config.getColorType(), is(ColorType.CUSTOM));
assertThat(config.getColor(), is("f00f00"));

assertThat(defaultConfig.getContext(), notNullValue());
assertThat(defaultConfig.getContext().getEnvironmentVariables(), hasKey("VAR1"));
assertThat(defaultConfig.getContext().getEnvironmentVariables(), hasKey("VAR2"));
}

@Test
Expand Down
49 changes: 49 additions & 0 deletions src/test/resources/json/empty_task_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"config": {
"Message": {
"secure": false,
"required": false,
"value": ""
},
"Title": {
"secure": false,
"required": false,
"value": ""
},
"IconOrEmoji": {
"secure": false,
"required": false,
"value": ""
},
"Channel": {
"secure": false,
"required": false,
"value": ""
},
"ChannelType": {
"secure": false,
"required": false,
"value": ""
},
"WebhookUrl": {
"secure": false,
"required": false,
"value": ""
},
"DisplayName": {
"secure": false,
"required": false,
"value": ""
},
"ColorType": {
"secure": false,
"required": false,
"value": ""
},
"Color": {
"secure": false,
"required": false,
"value": ""
}
}
}

0 comments on commit 92f7fc7

Please sign in to comment.