eclipse/cmd/eclipse-pick/main.go

103 lines
2.1 KiB
Go

// Copyright (C) 2023-2024 Umorpha Systems
// SPDX-License-Identifier: AGPL-3.0-or-later
package main
import (
"context"
"encoding/json"
"net/url"
"fmt"
"math/big"
"io"
"crypto/rand"
"net/http"
"os"
"github.com/datawire/ocibuild/pkg/cliutil"
"github.com/spf13/cobra"
"git.mothstuff.lol/lukeshu/eclipse/lib/eclipse"
)
func main() {
argparser := &cobra.Command{
Use: os.Args[0] + " [flags] JOBS_URL",
Short: "Choose a job from the central cordinator server",
Args: cliutil.WrapPositionalArgs(cobra.ExactArgs(1)),
SilenceErrors: true, // we'll handle this ourselves after .ExecuteContext()
SilenceUsage: true, // FlagErrorFunc will handle this
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
},
}
argparser.SetFlagErrorFunc(cliutil.FlagErrorFunc)
argparser.SetHelpTemplate(cliutil.HelpTemplate)
argparser.RunE = func(cmd *cobra.Command, args []string) error {
return Pick(args[0])
}
ctx := context.Background()
if err := argparser.ExecuteContext(ctx); err != nil {
fmt.Fprintf(os.Stderr, "%v: error: %v\n", argparser.CommandPath(), err)
os.Exit(1)
}
}
func randInt(max int) (int, error) {
bigN, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
return 0, err
}
return int(bigN.Int64()), nil
}
func Pick(serverURL string) error {
u, err := url.Parse(serverURL)
if err != nil {
return err
}
u.Path = "/jobs/"
u.RawQuery = url.Values{
"status": []string{"new"},
"wait": []string{"true"},
}.Encode()
resp, err := http.Get(u.String())
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
err := fmt.Errorf("HTTP %s", resp.Status)
body, _ := io.ReadAll(resp.Body)
if len(body) > 0 {
err = fmt.Errorf("%w\n%s", err, body)
}
return err
}
bodyBytes , err := io.ReadAll(resp.Body)
if err != nil {
return err
}
var options []eclipse.Job
if err := json.Unmarshal(bodyBytes, &options); err != nil {
return err
}
n, err := randInt(len(options))
if err != nil {
return err
}
u.Path = fmt.Sprintf("/jobs/%d/", options[n].ID)
u.RawQuery = ""
fmt.Println(u)
return nil
}