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
use super::capture::{CaptureOpts, OutputCapture};
use super::config_load::FoundConfig;
use super::models::prelude::{ReportUploadLocationDestination, ScopeModel};
use super::prelude::OutputDestination;
use anyhow::{anyhow, Result};
use minijinja::{context, Environment};
use reqwest::header::{ACCEPT, AUTHORIZATION, USER_AGENT};
use std::fs::File;
use std::io::Write;
use tracing::{debug, info, warn};

pub struct ReportBuilder<'a> {
    message: String,
    command_results: String,
    config: &'a FoundConfig,
}

impl<'a> ReportBuilder<'a> {
    pub async fn new(capture: &OutputCapture, config: &'a FoundConfig) -> Result<Self> {
        let message = Self::make_default_message(&capture.command, config)?;

        let mut this = Self {
            message,
            command_results: String::new(),
            config,
        };

        this.add_capture(capture)?;

        for command in config.get_report_definition().additional_data.values() {
            let args: Vec<String> = command.split(' ').map(|x| x.to_string()).collect();
            let capture = OutputCapture::capture_output(CaptureOpts {
                working_dir: &config.working_dir,
                args: &args,
                output_dest: OutputDestination::Null,
                path: &config.bin_path,
                env_vars: Default::default(),
            })
            .await?;
            this.add_capture(&capture)?;
        }

        Ok(this)
    }

    fn add_capture(&mut self, capture: &OutputCapture) -> Result<()> {
        self.command_results.push('\n');
        self.command_results
            .push_str(&capture.create_report_text()?);

        Ok(())
    }

    pub fn write_local_report(&self) -> Result<()> {
        let report = self.make_report_test();

        let base_report_loc = write_to_report_file("base", &report)?;
        info!(target: "always", "The basic report was created at {}", base_report_loc);

        Ok(())
    }

    fn make_default_message(command: &str, config: &FoundConfig) -> Result<String> {
        let mut env = Environment::new();
        let report_def = config.get_report_definition();
        env.add_template("tmpl", &report_def.template)?;
        let template = env.get_template("tmpl")?;
        let template = template.render(context! { command => command })?;

        Ok(template)
    }

    fn make_report_test(&self) -> String {
        format!(
            "{}\n\n## Captured Data\n\n{}",
            self.message, self.command_results
        )
    }

    pub async fn distribute_report(&self) -> Result<()> {
        let report = self.make_report_test();

        for dest in self.config.report_upload.values() {
            if let Err(e) = &dest.spec.destination.upload(&report).await {
                warn!(target: "user", "Unable to upload to {}: {}", dest.name(), e);
            }
        }

        Ok(())
    }
}

impl ReportUploadLocationDestination {
    async fn upload(&self, report: &str) -> Result<()> {
        match self {
            ReportUploadLocationDestination::RustyPaste { url } => {
                ReportUploadLocationDestination::upload_to_rusty_paste(url, report).await
            }
            ReportUploadLocationDestination::GithubIssue { owner, repo, tags } => {
                ReportUploadLocationDestination::upload_to_github_issue(
                    owner,
                    repo,
                    tags.clone(),
                    report,
                )
                .await
            }
        }
    }

    async fn upload_to_github_issue(
        owner: &str,
        repo: &str,
        tags: Vec<String>,
        report: &str,
    ) -> Result<()> {
        let gh_auth = match std::env::var("GH_TOKEN") {
            Ok(v) => v,
            Err(_) => {
                return Err(anyhow!(
                    "GH_TOKEN env var was not set with token to access GitHub"
                ))
            }
        };

        let title = match report.find('\n') {
            Some(value) => report[0..value].to_string(),
            None => "Scope bug report".to_string(),
        };

        let body = json::object! {
            title: title,
            body: report,
            labels: tags
        };

        let client = reqwest::Client::new();
        let res = client
            .post(format!(
                "https://api.github.com/repos/{}/{}/issues",
                owner, repo
            ))
            .header(ACCEPT, "application/vnd.github+json")
            .header(AUTHORIZATION, format!("Bearer {}", gh_auth))
            .header(USER_AGENT, "scope")
            .header("X-GitHub-Api-Version", "2022-11-28")
            .body(body.dump())
            .send()
            .await;

        match res {
            Ok(res) => {
                debug!("API Response was {:?}", res);
                let status = res.status();
                match res.text().await {
                    Err(e) => {
                        warn!(target: "user", "Unable to read Github response: {:?}", e)
                    }
                    Ok(body) => {
                        let body = body.trim();
                        if status.is_success() {
                            match json::parse(body) {
                                Ok(json_body) => {
                                    info!(target: "always", "Report was uploaded to {}.", json_body["html_url"])
                                }
                                Err(e) => {
                                    warn!(server = "github", "GitHub response {}", body);
                                    warn!(server = "github", "GitHub parse error {:?}", e);
                                    warn!(target: "always", server="github", "GitHub responded with weird response, please check the logs.");
                                }
                            }
                        } else {
                            info!(target: "always", server="github", "Report upload failed for {}.", body)
                        }
                    }
                }
            }
            Err(e) => {
                warn!(target: "always", "Unable to upload report to server because {}", e)
            }
        }

        Ok(())
    }

    async fn upload_to_rusty_paste(url: &str, report: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let some_file = reqwest::multipart::Part::stream(report.to_string())
            .file_name("file")
            .mime_str("text/plain")?;

        let form = reqwest::multipart::Form::new().part("file", some_file);

        let res = client.post(url).multipart(form).send().await;

        match res {
            Ok(res) => {
                debug!(server = "RustyPaste", "API Response was {:?}", res);
                let status = res.status();
                match res.text().await {
                    Err(e) => {
                        warn!(target: "user",server="RustyPaste",  "Unable to fetch body from Server: {:?}", e)
                    }
                    Ok(body) => {
                        let body = body.trim();
                        if !status.is_success() {
                            info!(target: "always", server="RustyPaste", "Report was uploaded to {}.", body)
                        } else {
                            info!(target: "always", server="RustyPaste", "Report upload failed for {}.", body)
                        }
                    }
                }
            }
            Err(e) => {
                warn!(target: "always", server="RustyPaste", "Unable to upload report to server because {}", e)
            }
        }
        Ok(())
    }
}

pub fn write_to_report_file(prefix: &str, text: &str) -> Result<String> {
    let id = nanoid::nanoid!(10, &nanoid::alphabet::SAFE);

    let file_path = format!("/tmp/scope/scope-{}-{}.md", prefix, id);
    let mut file = File::create(&file_path)?;
    file.write_all(text.as_bytes())?;

    Ok(file_path)
}