task.go

43 lines
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
package models

import (
	"fmt"
	"time"

	"congo.gg/pkg/database"
)

// Task represents a background operation (build, deploy, clone, etc.).
type Task struct {
	database.Model
	Type      string // "build", "deploy", "create_project", "clone", "pull"
	Name      string // "Building myapp", "Deploying api"
	RepoID    string // optional
	ServiceID string // optional
	Status    string // "running", "completed", "failed"
	Output    string // last lines of stdout/stderr
	StartedAt time.Time
	EndedAt   time.Time
}

// Ago returns a human-readable relative time string.
func (t *Task) Ago() string {
	ref := t.EndedAt
	if ref.IsZero() {
		ref = t.StartedAt
	}
	if ref.IsZero() {
		ref = t.CreatedAt
	}
	d := time.Since(ref)
	switch {
	case d < 5*time.Second:
		return "now"
	case d < time.Minute:
		return fmt.Sprintf("%ds", int(d.Seconds()))
	case d < time.Hour:
		return fmt.Sprintf("%dm ago", int(d.Minutes()))
	default:
		return fmt.Sprintf("%dh ago", int(d.Hours()))
	}
}