-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
335 lines (288 loc) · 7.81 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path"
"path/filepath"
"runtime/debug"
"strings"
"time"
"github.com/pkg/errors"
"github.com/slack-go/slack"
flag "github.com/spf13/pflag"
)
func version() string {
info, ok := debug.ReadBuildInfo()
if !ok {
// Goモジュールが無効など
return "(devel)"
}
return info.Main.Version
}
type CliOutput struct {
Channel string `json:"channel"`
Timestamp string `json:"timestamp"`
}
type Options struct {
slackClient SlackClient
token string
text string
filepath string
blocks string
mode string
snippetMode bool
postOpts *PostOptions
}
type PostOptions struct {
username string
channel string
iconEmoji string
iconUrl string
threadTs string
}
func strGetFirstOne(vars ...string) string {
for _, v := range vars {
if v != "" {
return v
}
}
return ""
}
func main() {
var (
// mode: print version
printVersion = flag.Bool("version", false, "print version")
// mode: post text
optText = flag.String("text", "", "post text")
optTextFile = flag.String("textfile", "", "post text file path")
snippetMode = flag.Bool("snippet", false, "post text as snippet")
// mode: post file
filepath = flag.String("file", "", "post file path")
// mode: post blocks json
optBlocks = flag.String("blocks", "", "post BlockKit json")
// must options
envToken = os.Getenv("SLACK_TOKEN")
optToken = flag.String("token", "", "slack app OAuth token")
optChannel = flag.String("channel", "", "post slack channel id")
// optional
envProfile = os.Getenv("SLACK_QUICKPOST_PROFILE")
optProfile = flag.String("profile", "", "slack quickpost profile name")
threadTs = flag.String("thread-ts", "", "post under thread")
iconEmoji = flag.String("icon", "", "icon emoji")
iconUrl = flag.String("icon-url", "", "icon image url")
username = flag.String("username", "", "user name")
noFail = flag.Bool("nofail", false, "always return success code(0)")
errText []string
)
flag.Parse()
if *printVersion {
fmt.Println(version())
os.Exit(0)
}
opts := &Options{
snippetMode: *snippetMode,
filepath: *filepath,
postOpts: &PostOptions{
username: *username,
iconEmoji: *iconEmoji,
iconUrl: *iconUrl,
threadTs: *threadTs,
},
}
usr, err := user.Current()
if err != nil {
log.Printf("error: user.Current(). %s", err)
os.Exit(1)
}
profileName := strGetFirstOne(*optProfile, envProfile)
var profile = &Profile{}
if profileName != "" {
profPath := path.Join(usr.HomeDir, ".config", "slack-quickpost", profileName+".yaml")
profile, err = parseProfile(profPath)
if err != nil {
errText = append(errText, fmt.Sprintf("error: failed read profile %s. %s", profPath, err.Error()))
}
}
opts.token = strGetFirstOne(*optToken, envToken, profile.Token)
if opts.token == "" {
errText = append(errText, "error: slack token is required")
}
opts.postOpts.channel = strGetFirstOne(*optChannel, profile.Channel)
if opts.postOpts.channel == "" {
errText = append(errText, "error: channel is required")
}
// post mode
switch {
case *optText != "":
opts.text = strings.Replace(*optText, "\\n", "\n", -1)
opts.mode = "text"
case *optBlocks != "":
opts.blocks = *optBlocks
opts.mode = "blocks"
case *optTextFile != "":
bytes, err := ioutil.ReadFile(*optTextFile)
if err != nil {
errText = append(errText, fmt.Sprintf("error: failed read text file: %s", err))
}
opts.text = string(bytes)
opts.mode = "text"
case *filepath != "":
opts.filepath = *filepath
opts.mode = "file"
default:
errText = append(errText, "error: --text option is required")
}
if 0 < len(errText) {
fmt.Println(strings.Join(errText, "\n"))
if *noFail {
os.Exit(0)
}
os.Exit(1)
}
opts.slackClient = slack.New(opts.token)
output, err := Do(opts)
if err != nil {
fmt.Println(err.Error())
if *noFail {
os.Exit(0)
}
os.Exit(1)
}
b, err := json.Marshal(output)
if err != nil {
fmt.Println(err.Error())
if *noFail {
os.Exit(0)
}
os.Exit(1)
}
fmt.Printf("%s", b)
return
}
func Do(opts *Options) (*CliOutput, error) {
var err error
var output *CliOutput
switch opts.mode {
case "text":
// 3000文字以上は自動でスニペットにする
// https://api.slack.com/reference/block-kit/blocks#section_fields
if 3000 < len(opts.text) {
opts.snippetMode = true
fmt.Println("[INFO] text length exceed limits (3000 characters), upload snippets.")
}
if opts.snippetMode {
output, err = postFile(opts.slackClient, opts.postOpts, strings.NewReader(opts.text), "", "", len(opts.text))
if err != nil {
return nil, errors.Wrap(err, "error postFile")
}
} else {
output, err = postMessage(opts.slackClient, opts.postOpts, opts.text)
if err != nil {
return nil, errors.Wrap(err, "error: postMessage")
}
}
case "blocks":
blocks := slack.Blocks{}
if err := blocks.UnmarshalJSON([]byte(opts.blocks)); err != nil {
return nil, errors.Wrap(err, "error: failed blocks.UnmarshalJSON")
}
output, err = postBlocks(opts.slackClient, opts.postOpts, blocks)
if err != nil {
return nil, errors.Wrapf(err, "error postBlocks %s", opts.filepath)
}
case "file":
if opts.filepath != "" {
file, err := os.Open(opts.filepath)
if err != nil {
return nil, errors.Wrapf(err, "error open file: %s", opts.filepath)
}
filename := filepath.Base(opts.filepath)
st, err := os.Stat(opts.filepath)
if err != nil {
return nil, errors.Wrapf(err, "error stat file: %s", opts.filepath)
}
output, err = postFile(opts.slackClient, opts.postOpts, file, filename, "", int(st.Size()))
if err != nil {
return nil, errors.Wrapf(err, "error postFile %s", opts.filepath)
}
}
}
return output, nil
}
func (p *PostOptions) getMsgOptions() []slack.MsgOption {
var opts []slack.MsgOption
if p.threadTs != "" {
opts = append(opts, slack.MsgOptionTS(p.threadTs))
}
switch {
case p.iconEmoji != "":
opts = append(opts, slack.MsgOptionIconEmoji(p.iconEmoji))
case p.iconUrl != "":
opts = append(opts, slack.MsgOptionIconURL(p.iconUrl))
}
if p.username != "" {
opts = append(opts, slack.MsgOptionUsername(p.username))
}
return opts
}
func postMessage(client SlackClient, postOpts *PostOptions, text string) (*CliOutput, error) {
opts := []slack.MsgOption{}
opts = append(opts, postOpts.getMsgOptions()...)
opts = append(opts, slack.MsgOptionText(text, false))
postedChannel, ts, err := client.PostMessage(
postOpts.channel,
opts...,
)
if err != nil {
return nil, errors.Wrap(err, "error postMessage")
}
output := &CliOutput{
Channel: postedChannel,
Timestamp: ts,
}
return output, nil
}
func postBlocks(client SlackClient, postOpts *PostOptions, blocks slack.Blocks) (*CliOutput, error) {
opts := []slack.MsgOption{}
opts = append(opts, postOpts.getMsgOptions()...)
opts = append(opts, slack.MsgOptionBlocks(blocks.BlockSet...))
postedChannel, ts, err := client.PostMessage(
postOpts.channel,
opts...,
)
if err != nil {
return nil, errors.Wrap(err, "error postMessage")
}
output := &CliOutput{
Channel: postedChannel,
Timestamp: ts,
}
return output, nil
}
func postFile(client SlackClient, postOpts *PostOptions, fileReader io.Reader, filename, comment string, size int) (*CliOutput, error) {
postTime := time.Now()
if filename == "" {
filename = fmt.Sprintf("%s.txt", postTime.Format("20060102_150405.999999"))
}
fups := slack.UploadFileV2Parameters{
Filename: filename,
FileSize: size,
Reader: fileReader,
InitialComment: comment,
Channel: postOpts.channel,
ThreadTimestamp: postOpts.threadTs,
}
if _, err := client.UploadFileV2(fups); err != nil {
return nil, errors.Wrap(err, "error postFile")
}
output := &CliOutput{
Channel: postOpts.channel,
// Timestamp: UploadFileはtimestampを取得できない
}
return output, nil
}