ci / test (push) Canceled after 0s
ci / cross-build (amd64, darwin) (push) Canceled after 0s
ci / cross-build (amd64, linux) (push) Canceled after 0s
ci / cross-build (amd64, windows) (push) Canceled after 0s
ci / cross-build (arm64, darwin) (push) Canceled after 0s
ci / cross-build (arm64, linux) (push) Canceled after 0s
ci / cross-build (arm64, windows) (push) Canceled after 0s
- archive: use Docker's own patternmatcher for .dockerignore/.gitignore/.gyignore + hard secret/VCS/build-output exclusions - crypto: AES-256-CTR encrypt the source archive before upload (key/IV to gateway via HTTPS) - deploy: --max-upload / GY_MAX_UPLOAD (default 500 MB) - Makefile + CI matrix: cross-compile linux/darwin/windows x amd64/arm64 - tests: crypto round-trip + ignore rules
621 lines
16 KiB
Go
621 lines
16 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/charmbracelet/bubbles/progress"
|
|
"github.com/charmbracelet/bubbles/spinner"
|
|
tea "github.com/charmbracelet/bubbletea"
|
|
"github.com/charmbracelet/lipgloss"
|
|
"github.com/spf13/cobra"
|
|
|
|
"gitlab.com/ghaymah/gy/internal/apiclient"
|
|
"gitlab.com/ghaymah/gy/internal/gyconfig"
|
|
"gitlab.com/ghaymah/gy/internal/source"
|
|
"gitlab.com/ghaymah/gy/internal/uit"
|
|
)
|
|
|
|
type deployOpts struct {
|
|
dir string
|
|
name string
|
|
strategy string
|
|
port int
|
|
detach bool
|
|
timeout time.Duration
|
|
maxUpload int64
|
|
}
|
|
|
|
func newDeployCmd() *cobra.Command {
|
|
var name, strategy string
|
|
var port int
|
|
var detach bool
|
|
var timeout time.Duration
|
|
var maxUploadMB int
|
|
|
|
cmd := &cobra.Command{
|
|
Use: "deploy",
|
|
Short: "Deploy the current directory",
|
|
Long: "Packs the project, uploads it, builds it in the cloud (kaniko/buildpacks), and gives you a live URL. No Docker required.",
|
|
Args: cobra.NoArgs,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
c, err := requireClient()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dir, err := os.Getwd()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
det := source.Detect(dir)
|
|
|
|
// Name: flag → existing link → folder name.
|
|
if name == "" {
|
|
if l, lerr := gyconfig.LoadLink(dir); lerr == nil && l.Name != "" {
|
|
name = l.Name
|
|
}
|
|
}
|
|
if name == "" {
|
|
name = det.Name
|
|
}
|
|
if strategy == "" {
|
|
strategy = det.Strategy
|
|
}
|
|
if port <= 0 {
|
|
port = det.Port
|
|
}
|
|
if timeout <= 0 {
|
|
timeout = 20 * time.Minute
|
|
}
|
|
|
|
// Upload size limit (MB): flag → GY_MAX_UPLOAD → 500 MB default.
|
|
maxUpload := int64(maxUploadMB) * 1024 * 1024
|
|
if maxUpload <= 0 {
|
|
if envMB := envInt64("GY_MAX_UPLOAD"); envMB > 0 {
|
|
maxUpload = envMB * 1024 * 1024
|
|
} else {
|
|
maxUpload = 500 * 1024 * 1024
|
|
}
|
|
}
|
|
|
|
opts := deployOpts{dir: dir, name: name, strategy: strategy, port: port, detach: detach, timeout: timeout, maxUpload: maxUpload}
|
|
|
|
if flagJSON {
|
|
return runDeployJSON(c, opts)
|
|
}
|
|
if useTUI() {
|
|
return runDeployTUI(c, opts)
|
|
}
|
|
return runDeployPlain(c, opts)
|
|
},
|
|
}
|
|
|
|
cmd.Flags().StringVar(&name, "name", "", "app name (defaults to the folder name)")
|
|
cmd.Flags().StringVar(&strategy, "strategy", "", "build strategy: auto, dockerfile, or buildpacks")
|
|
cmd.Flags().IntVar(&port, "port", 0, "HTTP port the app listens on")
|
|
cmd.Flags().BoolVar(&detach, "detach", false, "return after the build starts instead of waiting")
|
|
cmd.Flags().DurationVar(&timeout, "timeout", 20*time.Minute, "how long to wait for the build")
|
|
cmd.Flags().IntVar(&maxUploadMB, "max-upload", 0, "max source size in MB (default 500, or GY_MAX_UPLOAD)")
|
|
return cmd
|
|
}
|
|
|
|
// --- shared pipeline helpers ---
|
|
|
|
func uploadArchive(path, url string, total int64, onProgress func(int64)) error {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
pr := &progressReader{r: f, total: total, onProgress: onProgress}
|
|
req, err := http.NewRequest(http.MethodPut, url, pr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.ContentLength = total
|
|
req.Header.Set("Content-Type", "application/octet-stream")
|
|
|
|
resp, err := (&http.Client{}).Do(req) // no timeout: uploads can be large
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
return fmt.Errorf("upload failed: %s %s", resp.Status, strings.TrimSpace(string(b)))
|
|
}
|
|
if onProgress != nil {
|
|
onProgress(total)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type progressReader struct {
|
|
r io.Reader
|
|
total int64
|
|
done int64
|
|
last int64
|
|
onProgress func(int64)
|
|
}
|
|
|
|
func (p *progressReader) Read(b []byte) (int, error) {
|
|
n, err := p.r.Read(b)
|
|
p.done += int64(n)
|
|
if p.done-p.last >= 256*1024 || err != nil {
|
|
p.last = p.done
|
|
if p.onProgress != nil {
|
|
p.onProgress(p.done)
|
|
}
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
// saveLink records the project link so gy status/open/logs work afterwards.
|
|
func saveLink(dir, projectID, name string) {
|
|
if projectID == "" {
|
|
return
|
|
}
|
|
_ = gyconfig.SaveLink(dir, gyconfig.Link{ProjectID: projectID, Name: name})
|
|
}
|
|
|
|
func humanSize(n int64) string {
|
|
switch {
|
|
case n >= 1<<30:
|
|
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
|
|
case n >= 1<<20:
|
|
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
|
|
case n >= 1<<10:
|
|
return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
|
|
default:
|
|
return fmt.Sprintf("%d B", n)
|
|
}
|
|
}
|
|
|
|
// packSource archives the project, enforces the upload size limit, and encrypts
|
|
// the archive with AES-256-CTR. It returns the encrypted file path (the caller
|
|
// removes it), its size, and the key/IV as hex for the gateway to pass to the
|
|
// build container.
|
|
func packSource(dir string, maxBytes int64) (encPath string, size int64, keyHex, ivHex string, err error) {
|
|
plain, size, err := source.ArchiveToTemp(dir)
|
|
if err != nil {
|
|
return "", 0, "", "", err
|
|
}
|
|
defer os.Remove(plain)
|
|
|
|
if maxBytes > 0 && size > maxBytes {
|
|
return "", size, "", "", fmt.Errorf("source is %s — exceeds the %s upload limit (raise it with --max-upload)", humanSize(size), humanSize(maxBytes))
|
|
}
|
|
|
|
encPath = plain + ".enc"
|
|
keyHex, ivHex, err = source.EncryptFile(plain, encPath)
|
|
if err != nil {
|
|
return "", 0, "", "", err
|
|
}
|
|
return encPath, size, keyHex, ivHex, nil
|
|
}
|
|
|
|
// envInt64 reads a non-negative int64 env var (0 when unset/invalid).
|
|
func envInt64(key string) int64 {
|
|
v := os.Getenv(key)
|
|
if v == "" {
|
|
return 0
|
|
}
|
|
var n int64
|
|
fmt.Sscanf(v, "%d", &n)
|
|
return n
|
|
}
|
|
|
|
// --- plain (non-TTY / CI) mode ---
|
|
|
|
func runDeployPlain(c *apiclient.Client, opts deployOpts) error {
|
|
fmt.Printf("%s deploying %s (%s)\n", uit.Title.Render("ghaymah"), uit.AppName.Render(opts.name), filepath.Base(opts.dir))
|
|
|
|
archivePath, size, keyHex, ivHex, err := packSource(opts.dir, opts.maxUpload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(archivePath)
|
|
fmt.Printf(" packed + encrypted source · %s\n", humanSize(size))
|
|
|
|
dep, err := c.CreateDeployment(context.Background(), opts.name, opts.strategy, opts.port, keyHex, ivHex, size)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := uploadArchive(archivePath, dep.UploadURL, size, func(done int64) {
|
|
pct := 0
|
|
if size > 0 {
|
|
pct = int(done * 100 / size)
|
|
}
|
|
fmt.Fprintf(os.Stderr, "\r uploading %3d%% ", pct)
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
fmt.Fprintln(os.Stderr)
|
|
|
|
if opts.detach {
|
|
if _, err := c.CompleteDeployment(context.Background(), dep.BuildID); err != nil {
|
|
return err
|
|
}
|
|
saveLink(opts.dir, dep.ProjectID, opts.name)
|
|
fmt.Printf(" build started · run `gy status` or `gy logs` to follow\n")
|
|
return nil
|
|
}
|
|
|
|
if _, err := c.CompleteDeployment(context.Background(), dep.BuildID); err != nil {
|
|
return err
|
|
}
|
|
|
|
build, appURL, err := waitForBuild(c, dep.BuildID, opts.timeout, func(lines []string) {
|
|
for _, l := range lines {
|
|
fmt.Println(" " + l)
|
|
}
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if build.Status != "succeeded" {
|
|
return fmt.Errorf("build %s: %s", build.Status, stripANSI(build.Error))
|
|
}
|
|
saveLink(opts.dir, dep.ProjectID, opts.name)
|
|
fmt.Printf("\n%s Live: %s\n", uitCheck(), uit.URL.Render(appURL))
|
|
return nil
|
|
}
|
|
|
|
func runDeployJSON(c *apiclient.Client, opts deployOpts) error {
|
|
result := map[string]any{"name": opts.name, "status": "failed"}
|
|
|
|
archivePath, size, keyHex, ivHex, err := packSource(opts.dir, opts.maxUpload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(archivePath)
|
|
|
|
dep, err := c.CreateDeployment(context.Background(), opts.name, opts.strategy, opts.port, keyHex, ivHex, size)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result["project_id"] = dep.ProjectID
|
|
result["build_id"] = dep.BuildID
|
|
|
|
if err := uploadArchive(archivePath, dep.UploadURL, size, nil); err != nil {
|
|
return err
|
|
}
|
|
if _, err := c.CompleteDeployment(context.Background(), dep.BuildID); err != nil {
|
|
return err
|
|
}
|
|
|
|
if opts.detach {
|
|
saveLink(opts.dir, dep.ProjectID, opts.name)
|
|
result["status"] = "building"
|
|
return printJSON(result)
|
|
}
|
|
|
|
build, appURL, err := waitForBuild(c, dep.BuildID, opts.timeout, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if build.Status == "succeeded" {
|
|
saveLink(opts.dir, dep.ProjectID, opts.name)
|
|
}
|
|
result["status"] = build.Status
|
|
result["image"] = build.ImageRef
|
|
result["app_url"] = appURL
|
|
if build.Error != "" {
|
|
result["error"] = stripANSI(build.Error)
|
|
}
|
|
return printJSON(result)
|
|
}
|
|
|
|
// waitForBuild polls build status, streaming new log lines, until it finishes.
|
|
func waitForBuild(c *apiclient.Client, buildID string, timeout time.Duration, onLogs func([]string)) (*apiclient.Build, string, error) {
|
|
deadline := time.Now().Add(timeout)
|
|
seen := 0
|
|
grace := 0
|
|
var last *apiclient.Build
|
|
var lastURL string
|
|
|
|
for {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
build, appURL, err := c.GetDeployment(ctx, buildID)
|
|
if err == nil {
|
|
last = build
|
|
lastURL = appURL
|
|
}
|
|
if err == nil {
|
|
logs, _ := c.DeploymentLogs(ctx, buildID, 300)
|
|
if len(logs) > seen {
|
|
lines := make([]string, 0, len(logs)-seen)
|
|
for _, l := range logs[seen:] {
|
|
lines = append(lines, stripANSI(l.Message))
|
|
}
|
|
seen = len(logs)
|
|
if onLogs != nil {
|
|
onLogs(lines)
|
|
}
|
|
}
|
|
if build.Terminal() {
|
|
if build.Status == "succeeded" && appURL == "" && grace < 5 {
|
|
grace++
|
|
} else {
|
|
cancel()
|
|
return build, appURL, nil
|
|
}
|
|
}
|
|
}
|
|
cancel()
|
|
|
|
if time.Now().After(deadline) {
|
|
if last != nil && last.Terminal() {
|
|
return last, lastURL, nil
|
|
}
|
|
return nil, "", errors.New("timed out waiting for the build to finish")
|
|
}
|
|
time.Sleep(2 * time.Second)
|
|
}
|
|
}
|
|
|
|
// --- TUI mode ---
|
|
|
|
type deployPhaseMsg struct {
|
|
phase string
|
|
msg string
|
|
err error
|
|
}
|
|
type uploadProgressMsg struct{ done, total int64 }
|
|
type buildRefMsg struct{ projectID, buildID string }
|
|
type pollMsg struct {
|
|
build apiclient.Build
|
|
appURL string
|
|
logs []apiclient.LogEntry
|
|
}
|
|
|
|
type deployModel struct {
|
|
c *apiclient.Client
|
|
opts deployOpts
|
|
|
|
phase string
|
|
status string
|
|
err error
|
|
|
|
uploadDone int64
|
|
uploadTotal int64
|
|
progress progress.Model
|
|
spinner spinner.Model
|
|
|
|
projectID string
|
|
buildID string
|
|
appURL string
|
|
|
|
logs []string
|
|
seenLogs int
|
|
grace int
|
|
|
|
width int
|
|
height int
|
|
}
|
|
|
|
func newDeployModel(c *apiclient.Client, opts deployOpts) deployModel {
|
|
s := spinner.New(spinner.WithSpinner(spinner.Dot))
|
|
p := progress.New(progress.WithDefaultGradient())
|
|
return deployModel{c: c, opts: opts, phase: "starting", spinner: s, progress: p}
|
|
}
|
|
|
|
func runDeployTUI(c *apiclient.Client, opts deployOpts) error {
|
|
m := newDeployModel(c, opts)
|
|
p := tea.NewProgram(m, tea.WithAltScreen())
|
|
go runDeployPipeline(p, c, opts)
|
|
final, err := p.Run()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if dm, ok := final.(deployModel); ok && dm.err != nil {
|
|
return dm.err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func runDeployPipeline(p *tea.Program, c *apiclient.Client, opts deployOpts) {
|
|
send := p.Send
|
|
|
|
send(deployPhaseMsg{phase: "archiving", msg: "packing source"})
|
|
archivePath, size, keyHex, ivHex, err := packSource(opts.dir, opts.maxUpload)
|
|
if err != nil {
|
|
send(deployPhaseMsg{phase: "failed", err: err})
|
|
return
|
|
}
|
|
defer os.Remove(archivePath)
|
|
|
|
send(deployPhaseMsg{phase: "creating", msg: "creating deployment"})
|
|
dep, err := c.CreateDeployment(context.Background(), opts.name, opts.strategy, opts.port, keyHex, ivHex, size)
|
|
if err != nil {
|
|
send(deployPhaseMsg{phase: "failed", err: err})
|
|
return
|
|
}
|
|
|
|
send(buildRefMsg{projectID: dep.ProjectID, buildID: dep.BuildID})
|
|
send(uploadProgressMsg{done: 0, total: size})
|
|
send(deployPhaseMsg{phase: "uploading", msg: "uploading source"})
|
|
|
|
err = uploadArchive(archivePath, dep.UploadURL, size, func(done int64) {
|
|
send(uploadProgressMsg{done: done, total: size})
|
|
})
|
|
if err != nil {
|
|
send(deployPhaseMsg{phase: "failed", err: err})
|
|
return
|
|
}
|
|
|
|
send(deployPhaseMsg{phase: "starting", msg: "starting build"})
|
|
if _, err := c.CompleteDeployment(context.Background(), dep.BuildID); err != nil {
|
|
send(deployPhaseMsg{phase: "failed", err: err})
|
|
return
|
|
}
|
|
send(deployPhaseMsg{phase: "building", msg: "building in the cloud"})
|
|
}
|
|
|
|
func (m deployModel) Init() tea.Cmd {
|
|
return m.spinner.Tick
|
|
}
|
|
|
|
func (m deployModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
switch msg := msg.(type) {
|
|
case tea.WindowSizeMsg:
|
|
m.width = msg.Width
|
|
m.height = msg.Height
|
|
m.progress.Width = msg.Width - 12
|
|
if m.progress.Width < 20 {
|
|
m.progress.Width = 20
|
|
}
|
|
return m, nil
|
|
|
|
case tea.KeyMsg:
|
|
switch msg.String() {
|
|
case "ctrl+c", "q":
|
|
return m, tea.Quit
|
|
}
|
|
|
|
case spinner.TickMsg:
|
|
var cmd tea.Cmd
|
|
m.spinner, cmd = m.spinner.Update(msg)
|
|
return m, cmd
|
|
|
|
case deployPhaseMsg:
|
|
if msg.err != nil {
|
|
m.phase = "failed"
|
|
m.err = msg.err
|
|
return m, tea.Quit
|
|
}
|
|
m.phase = msg.phase
|
|
m.status = msg.msg
|
|
if msg.phase == "building" {
|
|
return m, deployPollCmd(m.c, m.buildID)
|
|
}
|
|
return m, nil
|
|
|
|
case buildRefMsg:
|
|
m.projectID = msg.projectID
|
|
m.buildID = msg.buildID
|
|
return m, nil
|
|
|
|
case uploadProgressMsg:
|
|
m.uploadDone = msg.done
|
|
m.uploadTotal = msg.total
|
|
if msg.total > 0 && msg.done >= msg.total {
|
|
m.uploadDone = msg.total
|
|
}
|
|
return m, nil
|
|
|
|
case pollMsg:
|
|
if len(msg.logs) > m.seenLogs {
|
|
for _, l := range msg.logs[m.seenLogs:] {
|
|
m.logs = append(m.logs, stripANSI(l.Message))
|
|
}
|
|
m.seenLogs = len(msg.logs)
|
|
}
|
|
if len(m.logs) > 200 {
|
|
m.logs = m.logs[len(m.logs)-200:]
|
|
}
|
|
if msg.build.Status != "" {
|
|
m.status = msg.build.Status
|
|
}
|
|
if msg.build.Terminal() {
|
|
if msg.build.Status == "succeeded" {
|
|
if msg.appURL == "" && m.grace < 5 {
|
|
m.grace++
|
|
return m, deployPollCmd(m.c, m.buildID)
|
|
}
|
|
m.appURL = msg.appURL
|
|
m.phase = "done"
|
|
saveLink(m.opts.dir, m.projectID, m.opts.name)
|
|
return m, nil
|
|
}
|
|
m.phase = "failed"
|
|
m.err = errors.New(orDefault(stripANSI(msg.build.Error), "build failed"))
|
|
return m, nil
|
|
}
|
|
return m, deployPollCmd(m.c, m.buildID)
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
func deployPollCmd(c *apiclient.Client, buildID string) tea.Cmd {
|
|
return func() tea.Msg {
|
|
time.Sleep(2 * time.Second)
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
build, appURL, err := c.GetDeployment(ctx, buildID)
|
|
if err != nil {
|
|
build = &apiclient.Build{Status: "error", Error: err.Error()}
|
|
}
|
|
logs, _ := c.DeploymentLogs(ctx, buildID, 300)
|
|
return pollMsg{build: *build, appURL: appURL, logs: logs}
|
|
}
|
|
}
|
|
|
|
func orDefault(s, def string) string {
|
|
if strings.TrimSpace(s) == "" {
|
|
return def
|
|
}
|
|
return s
|
|
}
|
|
|
|
func (m deployModel) View() string {
|
|
header := lipgloss.NewStyle().Bold(true).Foreground(uit.Accent).Render("ghaymah · " + m.opts.name)
|
|
body := ""
|
|
|
|
switch m.phase {
|
|
case "uploading":
|
|
pct := 0.0
|
|
if m.uploadTotal > 0 {
|
|
pct = float64(m.uploadDone) / float64(m.uploadTotal)
|
|
}
|
|
bar := m.progress.ViewAs(pct)
|
|
body = lipgloss.JoinVertical(lipgloss.Left,
|
|
"uploading source",
|
|
bar,
|
|
fmt.Sprintf("%s / %s", humanSize(m.uploadDone), humanSize(m.uploadTotal)),
|
|
)
|
|
case "building":
|
|
lines := []string{m.spinner.View() + " building · " + m.status}
|
|
if len(m.logs) > 0 {
|
|
tail := m.logs
|
|
if len(tail) > 12 {
|
|
tail = tail[len(tail)-12:]
|
|
}
|
|
for _, l := range tail {
|
|
lines = append(lines, uit.Dim.Render(strings.TrimSpace(l)))
|
|
}
|
|
}
|
|
body = lipgloss.JoinVertical(lipgloss.Left, lines...)
|
|
case "done":
|
|
body = lipgloss.JoinVertical(lipgloss.Left,
|
|
uit.Check()+" deployed "+m.opts.name,
|
|
"",
|
|
uit.URL.Render(m.appURL),
|
|
"",
|
|
uit.Dim.Render("gy open · gy logs · gy status"),
|
|
)
|
|
case "failed":
|
|
msg := "deploy failed"
|
|
if m.err != nil {
|
|
msg = m.err.Error()
|
|
}
|
|
body = uit.Err.Render(uitCross() + " " + msg)
|
|
default:
|
|
body = m.spinner.View() + " " + m.status
|
|
}
|
|
|
|
footer := uit.Dim.Render("q: quit")
|
|
return lipgloss.NewStyle().Padding(1, 2).Render(lipgloss.JoinVertical(lipgloss.Left, header, "", body, "", footer))
|
|
}
|