simple_slack_gen 0.2.0

Rust API Client
Documentation
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use clap::{CommandFactory, Parser};
use std::str::FromStr;
#[tokio::main]
async fn main() {
    let cli = SidekoCli::parse();
    if let Err(e) = handle_cli(cli).await {
        display_error(e);
        std::process::exit(1);
    }
}
async fn handle_cli(cli: SidekoCli) -> simple_slack_gen::SdkResult<()> {
    init_logger(cli.verbose);
    load_dotsideko();
    let base_url_env_var = "SIMPLE_SLACK_GEN_BASE_URL";
    match cli.command {
        SidekoCommand::SidekoConfigSubcommand(
            SidekoConfigSubcommand::Docs { output },
        ) => {
            let markdown = clap_markdown::help_markdown::<SidekoCli>();
            std::fs::write(&output, markdown)?;
            log::info!("CLI documentation saved to {output}")
        }
        SidekoCommand::SidekoConfigSubcommand(
            SidekoConfigSubcommand::Completions { shell },
        ) => {
            let mut cmd = SidekoCli::command();
            let cmd_name = cmd.get_name().to_string();
            clap_complete::generate(shell, &mut cmd, cmd_name, &mut std::io::stdout());
        }
        SidekoCommand::SidekoConfigSubcommand(
            SidekoConfigSubcommand::BaseUrl { unset, url },
        ) => {
            if unset {
                write_dotsideko(base_url_env_var, "", true);
            } else if let Some(url) = url {
                write_dotsideko(base_url_env_var, &url, false);
            } else {
                log::error!("No base url provided");
                std::process::exit(1);
            }
            log::info!("Base URL updated")
        }
        SidekoCommand::ConversationsSubcommand(ConversationsSubcommand::List(req)) => {
            let mut client = simple_slack_gen::Client::default();
            if let Ok(base_url) = std::env::var(base_url_env_var) {
                client = client.with_base_url(&base_url);
                log::debug!("Using custom base url: {base_url}");
            }
            if let Ok(val) = std::env::var("SIMPLE_SLACK_GEN_AUTH") {
                log::debug!("Adding oauth auth 'auth' (key=\"****\")");
                client = client.with_auth(&val);
            }
            let res = client.conversations().list(req).await?;
            println!(
                "{}", serde_json::to_string_pretty(& res).unwrap_or_else(| _ |
                serde_json::json!(& res) .to_string())
            );
        }
        SidekoCommand::ChatSubcommand(ChatSubcommand::PostMessage(req)) => {
            let mut client = simple_slack_gen::Client::default();
            if let Ok(base_url) = std::env::var(base_url_env_var) {
                client = client.with_base_url(&base_url);
                log::debug!("Using custom base url: {base_url}");
            }
            if let Ok(val) = std::env::var("SIMPLE_SLACK_GEN_AUTH") {
                log::debug!("Adding oauth auth 'auth' (key=\"****\")");
                client = client.with_auth(&val);
            }
            let res = client.chat().post_message(req).await?;
            println!(
                "{}", serde_json::to_string_pretty(& res).unwrap_or_else(| _ |
                serde_json::json!(& res) .to_string())
            );
        }
        SidekoCommand::SidekoConfigSubcommand(
            SidekoConfigSubcommand::SidekoAuthSubcommand(
                SidekoAuthSubcommand::Auth { token },
            ),
        ) => {
            write_dotsideko("SIMPLE_SLACK_GEN_AUTH", &token, false);
            log::info!("Authentication added to CLI");
        }
    }
    Ok(())
}
fn display_error(e: simple_slack_gen::Error) {
    match &e {
        simple_slack_gen::Error::Io(error) => log::debug!("IO Error: {:?}", error),
        simple_slack_gen::Error::Request(error) => {
            log::debug!("Request Error: {:?}", error)
        }
        simple_slack_gen::Error::Api(api_error)
        | simple_slack_gen::Error::ContentType(api_error) => {
            log::debug!("Response headers: {:?}", & api_error.headers);
            if let Ok(val) = api_error.json::<serde_json::Value>() {
                log::debug!(
                    "Body: {}", serde_json::to_string_pretty(& val).unwrap_or_else(| _ |
                    val.to_string())
                );
            } else if let Ok(text) = std::str::from_utf8(&api_error.content) {
                log::debug!("Body: {text}",);
            } else {
                log::debug!("Unable to process body ({} bytes)", api_error.content.len())
            }
        }
        simple_slack_gen::Error::DeserializeJson(error, _json_str) => {
            log::debug!("JSON Error: {error}")
        }
    }
    log::error!("{e}");
}
#[allow(unused)]
fn save_binary_response(
    res: simple_slack_gen::BinaryResponse,
) -> Result<(), std::io::Error> {
    log::debug!("Binary response headers: {:?}", & res.headers);
    let content_type = res
        .headers
        .get("content-type")
        .map(|val| val.to_str().unwrap_or_default());
    let mut extension = "out".to_string();
    if let Some(ct) = content_type {
        if let Some(Some(suffix)) = mime_guess::get_mime_extensions_str(ct)
            .map(|s| s.first())
        {
            extension = suffix.to_string()
        } else {
            log::warn!("Unsable to determine file extension from content type '{ct}'")
        }
    } else {
        log::warn!(
            "Unable to determine file extension from empty content type header in response"
        )
    }
    let outpath = camino::Utf8PathBuf::from(format!("./output.{extension}"));
    std::fs::write(&outpath, &res.content)?;
    log::info!("Wrote {} bytes to {outpath}", res.content.len());
    Ok(())
}
fn get_dotsideko_path() -> camino::Utf8PathBuf {
    if let Ok(custom_dotsideko) = std::env::var("SIDEKO_CLI_CONFIG") {
        camino::Utf8PathBuf::from_str(&custom_dotsideko)
            .unwrap_or_else(|_| {
                log::debug!("$SIDEKO_CLI_CONFIG set to: '{custom_dotsideko}'");
                log::error!(
                    "$SIDEKO_CLI_CONFIG environment variable must be a valid path if set"
                );
                std::process::exit(1)
            })
    } else {
        let home = std::env::var("HOME")
            .unwrap_or_else(|_| {
                log::error!(
                    "$HOME environment variable must be set for the CLI to function"
                );
                std::process::exit(1)
            });
        let buf = camino::Utf8PathBuf::from_str(&home)
            .unwrap_or_else(|_| {
                log::debug!("$HOME set to: '{home}'");
                log::error!("$HOME environment variable must be a valid path");
                std::process::exit(1)
            });
        buf.join(".sideko-cli")
    }
}
fn load_dotsideko() {
    let path = get_dotsideko_path();
    if path.exists() {
        log::debug!("Loading CLI config from {path}");
        if let Err(e) = dotenv::from_path(path.clone()) {
            log::debug!("Dotenv error: {:?}", e);
            log::error!("Failed loading config from '{path}'");
            std::process::exit(1);
        }
        log::debug!("Loaded config from {path}")
    }
}
fn write_dotsideko(var: &str, val: &str, unset: bool) {
    let sh_safe_val = shlex::try_quote(val)
        .map(String::from)
        .unwrap_or_else(|_| val.to_string());
    let dotenv_entry = format!("{var}={sh_safe_val}");
    let path = get_dotsideko_path();
    let current_dotenv: Vec<String> = if path.exists() {
        let dotenv_string = std::fs::read_to_string(path.clone())
            .unwrap_or_else(|e| {
                log::debug!("FS error: {:?}", e);
                log::error!("Failed loading config from '{path}'");
                std::process::exit(1);
            });
        dotenv_string.split("\n").map(String::from).collect()
    } else {
        vec![]
    };
    let mut new_dotenv: Vec<String> = vec![];
    let mut replaced = false;
    for line in current_dotenv {
        if line.starts_with(&format!("{var}=")) {
            if !unset {
                new_dotenv.push(dotenv_entry.clone());
                replaced = true;
            }
        } else {
            new_dotenv.push(line);
        }
    }
    if !unset && !replaced {
        new_dotenv.push(dotenv_entry)
    }
    std::fs::write(&path, new_dotenv.join("\n"))
        .unwrap_or_else(|e| {
            log::debug!("FS error: {:?}", e);
            log::error!("Failed updating config at '{path}'");
            std::process::exit(1);
        });
    if unset {
        log::debug!("{var} unset in {path}")
    } else {
        log::debug!("{var} updated in {path}")
    }
}
fn init_logger(verbosity: u8) {
    let self_module = std::env::var("CARGO_PKG_NAME").unwrap_or_default();
    let mut builder = env_logger::builder();
    if verbosity == 0 {
        builder
            .filter_module(&self_module, log::LevelFilter::Info)
            .format_target(false)
            .format_timestamp(None)
    } else if verbosity == 1 {
        builder.filter_module(&self_module, log::LevelFilter::Debug).format_target(false)
    } else {
        builder.filter_level(log::LevelFilter::Trace)
    };
    let _ = builder.try_init();
}
fn get_styles() -> clap::builder::Styles {
    clap::builder::Styles::styled()
        .usage(
            anstyle::Style::new()
                .bold()
                .underline()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Blue))),
        )
        .header(
            anstyle::Style::new()
                .bold()
                .underline()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Blue))),
        )
        .literal(
            anstyle::Style::new()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Green))),
        )
        .invalid(
            anstyle::Style::new()
                .bold()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Red))),
        )
        .error(
            anstyle::Style::new()
                .bold()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Red))),
        )
        .valid(
            anstyle::Style::new()
                .bold()
                .underline()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Green))),
        )
        .placeholder(
            anstyle::Style::new()
                .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::White))),
        )
}
#[derive(clap::Subcommand)]
enum SidekoConfigSubcommand {
    /// Generate markdown documentation for this CLI
    #[command(name = "docs")]
    Docs {
        /// Sets custom output path
        #[arg(long, default_value = "./CLI.md")]
        output: camino::Utf8PathBuf,
    },
    /// Output shell-autocompletion for this CLI
    /// (output to be piped into relevant rc file for sourcing)
    #[command(name = "completions")]
    Completions { #[arg(long)] shell: clap_complete::Shell },
    /// Configure a custom base url for the CLI to use
    #[command(name = "base-url")]
    BaseUrl {
        /// Base URL to use in future API requests
        #[arg(long)]
        url: Option<String>,
        /// Clear previously set custom base url in favour of default
        #[arg(long)]
        unset: bool,
    },
    /// Add authentication credentials to the CLI
    #[command(subcommand, name = "auth")]
    SidekoAuthSubcommand(SidekoAuthSubcommand),
}
#[derive(clap::Subcommand)]
enum SidekoAuthSubcommand {
    /// Add oAuth bearer token to the CLI for the 'auth' authentication method
    #[command(name = "auth")]
    Auth { #[arg(long)] token: String },
}
#[derive(clap::Parser)]
#[command(version, propagate_version = true, name = "simple-slack-gen")]
struct SidekoCli {
    #[command(subcommand)]
    command: SidekoCommand,
    #[arg(
        long,
        short = 'v',
        action = clap::ArgAction::Count,
        global = true,
        help = "Increase logging verbosity"
    )]
    verbose: u8,
}
#[derive(clap::Parser)]
#[command(styles = get_styles())]
#[allow(clippy::enum_variant_names)]
enum SidekoCommand {
    /// command group: authentication/documenention/configurations/etc.
    #[command(subcommand, name = "config")]
    SidekoConfigSubcommand(SidekoConfigSubcommand),
    /// command group (1 commands, 0 sub groups)
    #[command(subcommand, name = "conversations")]
    ConversationsSubcommand(ConversationsSubcommand),
    /// command group (1 commands, 0 sub groups)
    #[command(subcommand, name = "chat")]
    ChatSubcommand(ChatSubcommand),
}
#[derive(clap::Subcommand)]
#[allow(clippy::enum_variant_names)]
enum ConversationsSubcommand {
    /// Lists channels in the workspace.
    ///
    /// GET /conversations.list
    ///
    /// **Required Auth:** auth
    ///
    /// **Example:** `simple-slack-gen conversations list --cursor 'dXNlcjpVMDYxTkZUVDI=' --exclude-archived true --limit 10 --team-id T1234567890 --types 'public_channel,private_channel'`
    #[command(name = "list")]
    List(simple_slack_gen::resources::conversations::ListRequest),
}
#[derive(clap::Subcommand)]
#[allow(clippy::enum_variant_names)]
enum ChatSubcommand {
    /// Sends a message to a channel.
    ///
    /// POST /chat.postMessage
    ///
    /// **Required Auth:** auth
    ///
    /// **Example:** `simple-slack-gen chat post-message --as-user string --attachments string --blocks string --channel channel_id --icon-emoji string --icon-url string --link-names true --mrkdwn true --parse string --reply-broadcast true --text 'Hello World!' --thread-ts string --unfurl-links true --unfurl-media true --username string`
    #[command(name = "post-message")]
    PostMessage(simple_slack_gen::resources::chat::PostMessageRequest),
}
#[cfg(test)]
mod cli_tests {
    use clap::Parser;
    #[serial_test::serial]
    #[tokio::test]
    async fn test_cli_conversations_list_200_generated_success() {
        let cli = super::SidekoCli::try_parse_from(
                shlex::Shlex::new(
                    &["simple-slack-gen", "config", "auth", "auth"].join(" "),
                ),
            )
            .expect("failed parsing auth cli input");
        super::handle_cli(cli).await.expect("failed running auth command");
        let cli = super::SidekoCli::try_parse_from(
                shlex::Shlex::new(
                    &[
                        "simple-slack-gen",
                        "conversations",
                        "list",
                        "--cursor",
                        "'dXNlcjpVMDYxTkZUVDI='",
                        "--exclude-archived",
                        "true",
                        "--limit",
                        "10",
                        "--team-id",
                        "T1234567890",
                        "--types",
                        "'public_channel,private_channel'",
                    ]
                        .join(" "),
                ),
            )
            .expect("failed parsing cli input");
        let result = super::handle_cli(cli).await;
        println!("{:?}", & result);
        assert!(result.is_ok())
    }
    #[serial_test::serial]
    #[tokio::test]
    async fn test_cli_chat_post_message_200_success_default() {
        let cli = super::SidekoCli::try_parse_from(
                shlex::Shlex::new(
                    &["simple-slack-gen", "config", "auth", "auth"].join(" "),
                ),
            )
            .expect("failed parsing auth cli input");
        super::handle_cli(cli).await.expect("failed running auth command");
        let cli = super::SidekoCli::try_parse_from(
                shlex::Shlex::new(
                    &[
                        "simple-slack-gen",
                        "chat",
                        "post-message",
                        "--as-user",
                        "string",
                        "--attachments",
                        "string",
                        "--blocks",
                        "string",
                        "--channel",
                        "channel_id",
                        "--icon-emoji",
                        "string",
                        "--icon-url",
                        "string",
                        "--link-names",
                        "true",
                        "--mrkdwn",
                        "true",
                        "--parse",
                        "string",
                        "--reply-broadcast",
                        "true",
                        "--text",
                        "'Hello World!'",
                        "--thread-ts",
                        "string",
                        "--unfurl-links",
                        "true",
                        "--unfurl-media",
                        "true",
                        "--username",
                        "string",
                    ]
                        .join(" "),
                ),
            )
            .expect("failed parsing cli input");
        let result = super::handle_cli(cli).await;
        println!("{:?}", & result);
        assert!(result.is_ok())
    }
}