|
| 1 | +open Base |
| 2 | +open Printf |
| 3 | +open Devkit |
| 4 | +open Common |
| 5 | + |
| 6 | +module Github : Api.Github = struct |
| 7 | + let log = Log.from "github" |
| 8 | + |
| 9 | + let commits_url ~(repo : Github_t.repository) ~sha = |
| 10 | + String.substr_replace_first ~pattern:"{/sha}" ~with_:sha repo.commits_url |
| 11 | + |
| 12 | + let contents_url ~(repo : Github_t.repository) ~path = |
| 13 | + String.substr_replace_first ~pattern:"{+path}" ~with_:path repo.contents_url |
| 14 | + |
| 15 | + let build_headers ?token () = |
| 16 | + let headers = [ "Accept: application/vnd.github.v3+json" ] in |
| 17 | + Option.value_map token ~default:headers ~f:(fun v -> sprintf "Authorization: token %s" v :: headers) |
| 18 | + |
| 19 | + let get_config ~(ctx : Context.t) ~repo = |
| 20 | + let url = contents_url ~repo ~path:ctx.data.cfg_filename in |
| 21 | + let headers = build_headers ?token:ctx.secrets.gh_token () in |
| 22 | + match%lwt http_get ~headers url with |
| 23 | + | Error e -> |
| 24 | + log#error "error while querying %s: %s" url e; |
| 25 | + Lwt.return @@ fmt_error "failed to get config from file %s" url |
| 26 | + | Ok res -> |
| 27 | + let response = Github_j.content_api_response_of_string res in |
| 28 | + ( match response.encoding with |
| 29 | + | "base64" -> |
| 30 | + begin |
| 31 | + try |
| 32 | + response.content |> String.split_lines |> String.concat |> decode_string_pad |> Config_j.config_of_string |
| 33 | + |> fun res -> Lwt.return @@ Ok res |
| 34 | + with Base64.Invalid_char as exn -> |
| 35 | + log#error ~exn "failed to decode base64 in Github response"; |
| 36 | + Lwt.return @@ fmt_error "failed to get config from file %s" url |
| 37 | + end |
| 38 | + | encoding -> |
| 39 | + log#error "unexpected encoding '%s' in Github response" encoding; |
| 40 | + Lwt.return @@ fmt_error "failed to get config from file %s" url |
| 41 | + ) |
| 42 | + |
| 43 | + let get_api_commit ~(ctx : Context.t) ~repo ~sha = |
| 44 | + let url = commits_url ~repo ~sha in |
| 45 | + let headers = build_headers ?token:ctx.secrets.gh_token () in |
| 46 | + match%lwt http_get ~headers url with |
| 47 | + | Ok res -> Lwt.return @@ Ok (Github_j.api_commit_of_string res) |
| 48 | + | Error e -> |
| 49 | + log#error "error while querying %s: %s" url e; |
| 50 | + Lwt.return @@ fmt_error "failed to get api commit %s" sha |
| 51 | +end |
| 52 | + |
| 53 | +module Slack : Api.Slack = struct |
| 54 | + let log = Log.from "slack" |
| 55 | + |
| 56 | + let send_notification ~chan ~msg ~url = |
| 57 | + let data = Slack_j.string_of_webhook_notification msg in |
| 58 | + log#info "sending to %s : %s" chan data; |
| 59 | + match%lwt http_post ~path:url ~data with |
| 60 | + | Ok _ -> Lwt.return @@ Ok () |
| 61 | + | Error e -> |
| 62 | + log#error "error while querying %s: %s" url e; |
| 63 | + Lwt.return @@ fmt_error "failed to send Slack notification" |
| 64 | +end |
0 commit comments