Repository: appleboy/drone-telegram
Pull request #98 (2020-09-16 19:29:20)

Option to load tempate variables from json file
This implements the feature I was talking about in #97


Patch:
diff --git a/DOCS.md b/DOCS.md
index 23d4a5f..1f73428 100644
--- a/DOCS.md
+++ b/DOCS.md
@@ -186,6 +186,33 @@ Build finished for *{{tpl.app}}* - *{{tpl.env}}*
 {{/success}}
 ```
 
+Example configuration with a custom message template, with extra vars loaded from file (e.g. from previous build steps):
+
+```diff
+  - name: send telegram notification
+    image: appleboy/drone-telegram
+    settings:
+      token: xxxxxxxxxx
+      to: telegram_user_id
++     template_vars_file: build_report.json
++     message: >
++       {{#success build.status}}
++         build {{build.number}} succeeded, artefact version = {{tpl.artefact_version}}.
++       {{else}}
++         build {{build.number}} failed. Fix me please.
++       {{/success}}
+```
+
+Where `build_report.json` is:
+
+```
+{
+  ...
+  "artefact_version": "0.2.3452"
+  ...
+}
+```
+
 Example configuration with a custom socks5 URL:
 
 ```diff
@@ -215,6 +242,9 @@ message_file
 template_vars
 : define additional template vars. Example: `var1: hello` can be used within the template as `tpl.var1`
 
+template_vars_file
+: load additional template vars from json file. Example: given file content `{"var1":"hello"}`, variable can be used within the template as `tpl.var1`
+
 photo
 : local file path
 
diff --git a/main.go b/main.go
index 6c2763e..c6674a9 100644
--- a/main.go
+++ b/main.go
@@ -54,6 +54,11 @@ func main() {
 			Usage:  "additional template vars to be used in message, as JSON string",
 			EnvVar: "PLUGIN_TEMPLATE_VARS,TELEGRAM_TEMPLATE_VARS,INPUT_TEMPLATE_VARS",
 		},
+		cli.StringFlag{
+			Name:   "template.vars.file",
+			Usage:  "load additional template vars to be used in message, from json file",
+			EnvVar: "PLUGIN_TEMPLATE_VARS_FILE,TELEGRAM_TEMPLATE_VARS_FILE",
+		},
 		cli.StringSliceFlag{
 			Name:   "photo",
 			Usage:  "send photo message",
@@ -296,25 +301,26 @@ func run(c *cli.Context) error {
 			DeployTo: c.String("deploy.to"),
 		},
 		Config: Config{
-			Token:        c.String("token"),
-			Debug:        c.Bool("debug"),
-			MatchEmail:   c.Bool("match.email"),
-			WebPreview:   c.Bool("webpage.preview"),
-			To:           c.StringSlice("to"),
-			Message:      c.String("message"),
-			MessageFile:  c.String("message.file"),
-			TemplateVars: c.String("template.vars"),
-			Photo:        c.StringSlice("photo"),
-			Document:     c.StringSlice("document"),
-			Sticker:      c.StringSlice("sticker"),
-			Audio:        c.StringSlice("audio"),
-			Voice:        c.StringSlice("voice"),
-			Location:     c.StringSlice("location"),
-			Video:        c.StringSlice("video"),
-			Venue:        c.StringSlice("venue"),
-			Format:       c.String("format"),
-			GitHub:       c.Bool("github"),
-			Socks5:       c.String("socks5"),
+			Token:            c.String("token"),
+			Debug:            c.Bool("debug"),
+			MatchEmail:       c.Bool("match.email"),
+			WebPreview:       c.Bool("webpage.preview"),
+			To:               c.StringSlice("to"),
+			Message:          c.String("message"),
+			MessageFile:      c.String("message.file"),
+			TemplateVars:     c.String("template.vars"),
+			TemplateVarsFile: c.String("template.vars.file"),
+			Photo:            c.StringSlice("photo"),
+			Document:         c.StringSlice("document"),
+			Sticker:          c.StringSlice("sticker"),
+			Audio:            c.StringSlice("audio"),
+			Voice:            c.StringSlice("voice"),
+			Location:         c.StringSlice("location"),
+			Video:            c.StringSlice("video"),
+			Venue:            c.StringSlice("venue"),
+			Format:           c.String("format"),
+			GitHub:           c.Bool("github"),
+			Socks5:           c.String("socks5"),
 		},
 	}
 
diff --git a/plugin.go b/plugin.go
index 0ed0458..7e9cc05 100644
--- a/plugin.go
+++ b/plugin.go
@@ -67,25 +67,26 @@ type (
 
 	// Config for the plugin.
 	Config struct {
-		Token        string
-		Debug        bool
-		MatchEmail   bool
-		WebPreview   bool
-		To           []string
-		Message      string
-		MessageFile  string
-		TemplateVars string
-		Photo        []string
-		Document     []string
-		Sticker      []string
-		Audio        []string
-		Voice        []string
-		Location     []string
-		Video        []string
-		Venue        []string
-		Format       string
-		GitHub       bool
-		Socks5       string
+		Token            string
+		Debug            bool
+		MatchEmail       bool
+		WebPreview       bool
+		To               []string
+		Message          string
+		MessageFile      string
+		TemplateVarsFile string
+		TemplateVars     string
+		Photo            []string
+		Document         []string
+		Sticker          []string
+		Audio            []string
+		Voice            []string
+		Location         []string
+		Video            []string
+		Venue            []string
+		Format           string
+		GitHub           bool
+		Socks5           string
 	}
 
 	// Plugin values.
@@ -283,6 +284,25 @@ func (p Plugin) Exec() (err error) {
 		}
 	}
 
+	if p.Config.TemplateVarsFile != "" {
+		content, err := ioutil.ReadFile(p.Config.TemplateVarsFile)
+		if err != nil {
+			return fmt.Errorf("unable to read file with template vars '%s': %v", p.Config.TemplateVarsFile, err)
+		}
+		var vars = make(map[string]string)
+		if err = json.Unmarshal(content, &vars); err != nil {
+			return fmt.Errorf("unable to unmarshall template vars from JSON file '%s': %v", p.Config.TemplateVarsFile, err)
+		}
+		// Merging templates variables from file to the variables form plugin settings (variables from file takes precedence)
+		if p.Tpl == nil {
+			p.Tpl = vars
+		} else {
+			for k, v := range vars {
+				p.Tpl[k] = v
+			}
+		}
+	}
+
 	var proxyURL *url.URL
 	if proxyURL, err = url.Parse(p.Config.Socks5); err != nil {
 		return fmt.Errorf("unable to unmarshall socks5 proxy url from string '%s': %v", p.Config.Socks5, err)


Test patch:
diff --git a/plugin_test.go b/plugin_test.go
index e9c0fa6..290d2d7 100644
--- a/plugin_test.go
+++ b/plugin_test.go
@@ -387,6 +387,37 @@ func TestTemplateVars(t *testing.T) {
 	assert.Nil(t, err)
 }
 
+func TestTemplateVarsFile(t *testing.T) {
+	plugin := Plugin{
+		Repo: Repo{
+			Name:      "go-hello",
+			Namespace: "appleboy",
+		},
+		Commit: Commit{
+			Sha:     "e7c4f0a63ceeb42a39ac7806f7b51f3f0d204fd2",
+			Author:  "Bo-Yi Wu",
+			Branch:  "master",
+			Message: "This is a test commit msg",
+		},
+		Build: Build{
+			Number: 101,
+			Status: "success",
+			Link:   "https://github.com/appleboy/go-hello",
+		},
+
+		Config: Config{
+			Token:            os.Getenv("TELEGRAM_TOKEN"),
+			To:               []string{os.Getenv("TELEGRAM_TO")},
+			Format:           formatMarkdown,
+			MessageFile:      "tests/message_template.txt",
+			TemplateVarsFile: "tests/vars.json",
+		},
+	}
+
+	err := plugin.Exec()
+	assert.Nil(t, err)
+}
+
 func TestProxySendMessage(t *testing.T) {
 	plugin := Plugin{
 		Repo: Repo{
diff --git a/tests/vars.json b/tests/vars.json
new file mode 100644
index 0000000..03b8733
--- /dev/null
+++ b/tests/vars.json
@@ -0,0 +1,1 @@
+{"env":"testing","version":"1.2.0-SNAPSHOT"}