diff --git a/cmd/root.go b/cmd/root.go index f1737f8..3a0dade 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -78,7 +78,20 @@ It reads the configuration file and sends the message to the specified webhook.` } if withCodeBlock { - message = fmt.Sprintf("```%s\n%s\n```", codeBlockLang, message) + leadingBackQuoteCountMax := 0 + + for _, line := range strings.Split(message, "\n") { + if !strings.HasPrefix(line, "```") { + continue + } + noLeadingBackQuoteLine := strings.TrimLeft(line, "`") + leadingBackQuoteCount := len(line) - len(noLeadingBackQuoteLine) + leadingBackQuoteCountMax = max(leadingBackQuoteCountMax, leadingBackQuoteCount) + } + + codeBlockBackQuote := strings.Repeat("`", max(leadingBackQuoteCountMax+1, 3)) + + message = fmt.Sprintf("%s%s\n%s\n%s", codeBlockBackQuote, codeBlockLang, message, codeBlockBackQuote) } if cl != nil { diff --git a/cmd/root_test.go b/cmd/root_test.go index e2de575..f3ba0e3 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -36,11 +36,12 @@ func TestRoot(t *testing.T) { isError bool }{ "ok": {defaultWebhookConfig, input{false, "", "", []string{"test"}}, nil, "test", false}, - "コードブロックがあっても問題なし": {defaultWebhookConfig, input{true, "", "", []string{"print('Hello, World!')"}}, nil, "```\nprint('Hello, World!')\n```", false}, - "コードブロックと言語指定があっても問題なし": {defaultWebhookConfig, input{true, "python", "", []string{"print('Hello, World!')"}}, nil, "```python\nprint('Hello, World!')\n```", false}, - "メッセージがない場合は標準入力から": {defaultWebhookConfig, input{false, "", "stdin test", nil}, nil, "stdin test", false}, - "メッセージがあったら標準入力は無視": {defaultWebhookConfig, input{false, "", "stdin test", []string{"test"}}, nil, "test", false}, - "SendMessageがErrEmptyMessageを返す": {defaultWebhookConfig, input{false, "", "", nil}, client.ErrEmptyMessage, "", true}, + "コードブロックがあっても問題なし": {defaultWebhookConfig, input{true, "", "", []string{"print('Hello, World!')"}}, nil, "```\nprint('Hello, World!')\n```", false}, + "コードブロックと言語指定があっても問題なし": {defaultWebhookConfig, input{true, "python", "", []string{"print('Hello, World!')"}}, nil, "```python\nprint('Hello, World!')\n```", false}, + "メッセージがない場合は標準入力から": {defaultWebhookConfig, input{false, "", "stdin test", nil}, nil, "stdin test", false}, + "メッセージがあったら標準入力は無視": {defaultWebhookConfig, input{false, "", "stdin test", []string{"test"}}, nil, "test", false}, + "SendMessageがErrEmptyMessageを返す": {defaultWebhookConfig, input{false, "", "", nil}, client.ErrEmptyMessage, "", true}, + "メッセージにコードブロックが含まれていて、そこにコードブロックを付けても問題なし": {defaultWebhookConfig, input{true, "", "```python\nprint('Hello, World!')\n```", nil}, nil, "````\n```python\nprint('Hello, World!')\n```\n````", false}, } for description, tt := range test {