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
//! Functions for interacting with GitHub via the `gh` CLI
use serde::{Deserialize, Serialize};
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use std::sync::OnceLock;
use std::{error::Error, process::Command};

pub mod gh_cli;
pub mod gh_cli_fake;
pub mod util;

/// Get the GitHub CLI and initialize it with a default repository
/// If `fake` is true, a fake GitHub CLI is returned.
/// The fake GitHub CLI is used for testing and does not interact with GitHub
///
/// # Arguments
///
/// * `repo` - The default repository to use
/// * `fake` - If true, a fake GitHub CLI is returned
///
/// # Returns
///
/// [`Box<dyn GitHub>`](GitHub) - The GitHub CLI interface
///
/// # Example
///
/// ```
/// # use gh_workflow_parser::gh::init_github_cli;
/// let github_cli = init_github_cli("https://example.com/repo".to_string(), false);
/// ```
pub fn init_github_cli(repo: String, fake: bool) -> Box<dyn GitHub> {
    if fake {
        Box::new(gh_cli_fake::GitHubCliFake::new(repo))
    } else {
        Box::new(gh_cli::GitHubCli::new(repo))
    }
}

/// Trait describing the methods that the GitHub CLI should implement
pub trait GitHub {
    /// Get the summary of a run in a GitHub repository, if `repo` is `None` the default repository is used
    /// Returns the summary as a [String]
    fn run_summary(&self, repo: Option<&str>, run_id: &str) -> Result<String, Box<dyn Error>>;

    /// Get the log of a failed job in a GitHub repository, if `repo` is `None` the default repository is used
    /// Returns the log as a [String]
    fn failed_job_log(&self, repo: Option<&str>, job_id: &str) -> Result<String, Box<dyn Error>>;

    /// Create an issue in a GitHub repository, if `repo` is `None` the default repository is used
    fn create_issue(
        &self,
        repo: Option<&str>,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> Result<(), Box<dyn Error>>;

    /// Get the bodies of open issues with a specific label in a GitHub repository, if `repo` is `None` the default repository is used
    /// Returns [`Vec<String>`](Vec) of issue bodies
    fn issue_bodies_open_with_label(
        &self,
        repo: Option<&str>,
        label: &str,
    ) -> Result<Vec<String>, Box<dyn Error>>;

    /// Get all labels in a GitHub repository, if `repo` is `None` the default repository is used
    /// Returns [`Vec<String>`](Vec) of GitHub labels
    fn all_labels(&self, repo: Option<&str>) -> Result<Vec<String>, Box<dyn Error>>;

    /// Create a label in a GitHub repository, if `repo` is `None` the default repository is used
    /// The color should be a 6 character hex code (e.g. "FF0000")
    /// if `force` is true and the label already exists, it will be overwritten
    fn create_label(
        &self,
        repo: Option<&str>,
        name: &str,
        color: &str,
        description: &str,
        force: bool,
    ) -> Result<(), Box<dyn Error>>;

    /// Get the default repository for the GitHub CLI
    fn default_repo(&self) -> &str;
}

include!(concat!(env!("OUT_DIR"), "/include_gh_cli.rs"));
pub static GITHUB_CLI: OnceLock<OsString> = OnceLock::new();
pub fn gh_cli() -> &'static OsStr {
    GITHUB_CLI.get_or_init(|| {
        let gh_cli_path = gh_cli_first_time_setup().unwrap();
        OsString::from(gh_cli_path)
    })
}

pub fn gh_cli_first_time_setup() -> Result<PathBuf, Box<dyn Error>> {
    let mut path = std::env::current_exe()?;
    path.pop();
    path.push("gh-workflow-parser-deps");

    if !path.exists() {
        std::fs::create_dir(&path)?;
    }

    let gh_cli_path = path.join("gh_cli");

    if !gh_cli_path.exists() {
        log::debug!("the gh_cli file at {gh_cli_path:?} doesn't exist. Creating it...");
        // first decompress the gh-cli binary blob
        let gh_cli_bytes = GH_CLI_BYTES;
        log::trace!("gh_cli_bytes size: {}", gh_cli_bytes.len());

        let decompressed_gh_cli = crate::util::bzip2_decompress(gh_cli_bytes)?;
        log::trace!("decompressed_gh_cli size: {}", decompressed_gh_cli.len());

        // Write the gh_cli file to the gh_cli_path
        std::fs::write(&gh_cli_path, decompressed_gh_cli)?;
        #[cfg(target_os = "linux")]
        crate::util::set_linux_file_permissions(&gh_cli_path, 0o755)?;
        log::debug!("gh_cli file written to {gh_cli_path:?}");
    } else {
        log::debug!(
            "the gh_cli file at {gh_cli_path:?} already exists. Skipping first time setup..."
        );
    }

    Ok(gh_cli_path)
}

pub fn run_summary(repo: &str, run_id: &str) -> Result<String, Box<dyn Error>> {
    let output = Command::new(gh_cli())
        .arg("run")
        .arg(format!("--repo={repo}"))
        .arg("view")
        .arg(run_id)
        .output()?;

    assert!(
        output.status.success(),
        "Failed to get logs for repo={repo} run_id={run_id}. Failure: {stderr}",
        stderr = String::from_utf8_lossy(&output.stderr)
    );

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

pub fn failed_job_log(repo: &str, job_id: &str) -> Result<String, Box<dyn Error>> {
    let output = Command::new(gh_cli())
        .arg("run")
        .arg("view")
        .arg("--repo")
        .arg(repo)
        .arg("--job")
        .arg(job_id)
        .arg("--log-failed")
        .output()?;

    assert!(
        output.status.success(),
        "Failed to get logs for job ID: {job_id}. Failure: {stderr}",
        stderr = String::from_utf8_lossy(&output.stderr)
    );

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Create an issue in the GitHub repository
pub fn create_issue(
    repo: &str,
    title: &str,
    body: &str,
    labels: &[String],
) -> Result<(), Box<dyn Error>> {
    // First check if the labels exist on the repository
    let existing_labels = all_labels(repo)?;
    for label in labels {
        if !existing_labels.contains(label) {
            log::info!("Label {label} does not exist in the repository. Creating it...");
            create_label(repo, label, "FF0000", "", false)?;
        } else {
            log::debug!(
                "Label {label} already exists in the repository, continuing without creating it."
            )
        }
    }
    // format the labels into a single string separated by commas
    let labels = labels.join(",");
    let mut command = Command::new(gh_cli());
    command
        .arg("issue")
        .arg("create")
        .arg("--repo")
        .arg(repo)
        .arg("--title")
        .arg(title)
        .arg("--body")
        .arg(body)
        .arg("--label")
        .arg(labels);

    log::debug!("Debug view of command struct: {command:?}");
    // Run the command
    let output = command.output()?;

    assert!(
        output.status.success(),
        "Failed to create issue. Failure: {stderr}",
        stderr = String::from_utf8_lossy(&output.stderr)
    );

    Ok(())
}

/// Get the bodies of open issues with a specific label
pub fn issue_bodies_open_with_label(
    repo: &str,
    label: &str,
) -> Result<Vec<String>, Box<dyn Error>> {
    let output = Command::new(gh_cli())
        .arg("issue")
        .arg("list")
        .arg("--repo")
        .arg(repo)
        .arg("--label")
        .arg(label)
        .arg("--json")
        .arg("body")
        .output()
        .expect("Failed to list issues");

    assert!(
        output.status.success(),
        "Failed to list issues. Failure: {stderr}",
        stderr = String::from_utf8_lossy(&output.stderr)
    );

    let output = String::from_utf8_lossy(&output.stdout);

    /// Helper struct to deserialize a JSON array of github issue bodies
    #[derive(Serialize, Deserialize)]
    struct GhIssueBody {
        pub body: String,
    }

    let parsed: Vec<GhIssueBody> = serde_json::from_str(&output)?;
    Ok(parsed.into_iter().map(|item| item.body).collect())
}

/// Get all labels in a GitHub repository
pub fn all_labels(repo: &str) -> Result<Vec<String>, Box<dyn Error>> {
    let output = Command::new(gh_cli())
        .arg("--repo")
        .arg(repo)
        .arg("label")
        .arg("list")
        .arg("--json")
        .arg("name")
        .output()?;

    assert!(
        output.status.success(),
        "Failed to list labels. Failure: {stderr}",
        stderr = String::from_utf8_lossy(&output.stderr)
    );

    // Parse the received JSON vector of objects with a `name` field
    let output = String::from_utf8_lossy(&output.stdout);
    #[derive(Serialize, Deserialize)]
    struct Label {
        name: String,
    }
    let parsed: Vec<Label> = serde_json::from_str(&output)?;
    Ok(parsed.into_iter().map(|label| label.name).collect())
}

/// Create a label in the GitHub repository
/// The color should be a 6 character hex code
/// if `force` is true and the label already exists, it will be overwritten
pub fn create_label(
    repo: &str,
    name: &str,
    color: &str,
    description: &str,
    force: bool,
) -> Result<(), Box<dyn Error>> {
    let mut cmd = Command::new(gh_cli());
    cmd.arg("label")
        .arg("create")
        .arg(name)
        .arg("--repo")
        .arg(repo)
        .arg("--color")
        .arg(color)
        .arg("--description")
        .arg(description);

    if force {
        cmd.arg("--force");
    }

    let output = cmd.output()?;
    assert!(
        output.status.success(),
        "Failed to create label. Failure: {stderr}",
        stderr = String::from_utf8_lossy(&output.stderr)
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    #[ignore = "This test requires a GitHub repository"]
    fn test_issue_body_display() {
        let issue_bodies = issue_bodies_open_with_label(
            "https://github.com/luftkode/distro-template",
            "CI scheduled build",
        )
        .unwrap();
        for body in issue_bodies {
            println!("{body}");
        }
    }

    #[test]
    fn test_parse_json_body() {
        /// Helper struct to deserialize a JSON array of github issue bodies
        #[derive(Serialize, Deserialize)]
        struct GhIssueBody {
            pub body: String,
        }

        let data = r#"
    [
      {
        "body": "**Run ID**: 7858139663 [LINK TO RUN](github.com/luftkode/distro-template/actions/runs/7858139663)\\n\\n**1 job failed:**\\n- **`Test template xilinx`**\\n\\n### `Test template xilinx` (ID 21442749267)\\n**Step failed:** `📦 Build yocto image`\\n\\\\n**Log:** github.com/luftkode/distro-template/actions/runs/7858139663/job/21442749267\\n\\\\n*Best effort error summary*:\\n``\\nERROR: sqlite3-native-3_3.43.2-r0 do_fetch: Bitbake Fetcher Error: MalformedUrl('${SOURCE_MIRROR_URL}')\\nERROR: Logfile of failure stored in: /app/yocto/build/tmp/work/x86_64-linux/sqlite3-native/3.43.2/temp/log.do_fetch.21616\\nERROR: Task (virtual:native:/app/yocto/build/../poky/meta/recipes-support/sqlite/sqlite3_3.43.2.bb:do_fetch) failed with exit code '1'\\n\\n2024-02-11 00:09:04 - ERROR    - Command \"/app/yocto/poky/bitbake/bin/bitbake -c build test-template-ci-xilinx-image package-index\" failed with error 1\\n```"
      },
      {
        "body": "Build failed on xilinx. Check the logs at https://github.com/luftkode/distro-template/actions/runs/7858139663 for more details."
      },
      {
        "body": "Build failed on xilinx. Check the logs at https://github.com/luftkode/distro-template/actions/runs/7850874958 for more details."
      }
    ]
    "#;

        // Parse the JSON string to Vec<Item>
        let parsed: Vec<GhIssueBody> = serde_json::from_str(data).unwrap();

        // Extract the bodies into a Vec<String>
        let bodies: Vec<String> = parsed.into_iter().map(|item| item.body).collect();

        // Assert that the bodies are as expected
        assert_eq!(bodies.len(), 3);
        assert!(bodies[0].contains("**Run ID**: 7858139663 [LINK TO RUN]("));
        assert_eq!(
            bodies[1],
            "Build failed on xilinx. Check the logs at https://github.com/luftkode/distro-template/actions/runs/7858139663 for more details.");
        assert_eq!(
            bodies[2],
            "Build failed on xilinx. Check the logs at https://github.com/luftkode/distro-template/actions/runs/7850874958 for more details.");
    }
}