~jzs/srhtdeploy

07a76c0b786a66bc44bdbaf7dae173ee0a672826 — Jens Zeilund a year ago master
Simple program to deploy sh.ht build manifests
2 files changed, 105 insertions(+), 0 deletions(-)

A go.mod
A main.go
A  => go.mod +3 -0
@@ 1,3 @@
module git.sr.ht/~jzs/srhtdeploy

go 1.17

A  => main.go +102 -0
@@ 1,102 @@
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

type Job struct {
	Manifest string   `json:"manifest"`
	Tags     []string `json:"tags"`
	Execute  bool     `json:"execute"`
	Secrets  bool     `json:"secrets"`
	Note     string   `json:"note"`
}

func main() {
	cfg := flag.String("manifest", "", "Path for build manifest for sr.ht")
	tags := flag.String("tags", "", "Optional comma separated tags for the build job (optional)")
	execute := flag.Bool("execute", true, "Execute the job right away (optional / default true)")
	secrets := flag.Bool("secrets", true, "Provide secrets during build (optional / default true)")
	flag.Parse()

	if len(flag.Args()) > 1 {
		Abort("Too many arguments, did you forget to quote your note message?")
		return
	}

	note := flag.Arg(0)

	srhtKey := os.Getenv("SRHT_KEY")
	if srhtKey == "" {
		Abort("environment variable SRHT_KEY not set. It must be set to your sr.ht personal access token")
		return
	}

	if cfg == nil || *cfg == "" {
		Abort("manifest not specified")
		return
	}

	data, err := os.Open(*cfg)
	if err != nil {
		Abort(fmt.Sprintf("Could not open manifest: %v", err))
		return
	}
	defer data.Close()

	manifest, err := ioutil.ReadAll(data)
	if err != nil {
		Abort("manifest could not be read")
		return
	}

	j := Job{
		Manifest: string(manifest),
		Execute:  *execute,
		Secrets:  *secrets,
		Note:     note,
		Tags:     []string{},
	}
	if *tags != "" {
		j.Tags = strings.Split(*tags, ",")
	}

	jData, _ := json.Marshal(j)
	buf := bytes.NewBuffer(jData)

	req, err := http.NewRequest("POST", "https://builds.sr.ht/api/jobs", buf)
	if err != nil {
		Abort(fmt.Sprintf("Failed making request: %v", err))
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", fmt.Sprintf("token %v", strings.TrimSpace(srhtKey)))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		Abort(fmt.Sprintf("Posting to builds.sr.ht failed: %v", err))
		return
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		Abort(fmt.Sprintf("Parsing response body from builds.sr.ht failed: %v", err))
		return
	}
	fmt.Printf("%v", string(respBody))
}

func Abort(msg string) {
	fmt.Fprintf(os.Stderr, "%v\n", msg)
	fmt.Fprintf(os.Stderr, "Usage:\n")
	flag.PrintDefaults()
	os.Exit(1)
}