summaryrefslogtreecommitdiffstats
path: root/cmd/update.go
blob: a9df463b5c4c667a48119f0f254ffa3e6124b540 (plain)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package cmd

import (
	"fmt"
	"os"
	"os/exec"

	"runtime/debug"
	"strings"

	"git.db.org.ai/dborg/internal/utils"
	"github.com/spf13/cobra"
)

func getLatestVersion() (string, error) {
	cmd := exec.Command("git", "ls-remote", "--tags", "--refs", "--sort=-v:refname", utils.RepositoryURL)
	output, err := cmd.Output()
	if err != nil {
		return "", err
	}

	lines := strings.Split(strings.TrimSpace(string(output)), "\n")
	if len(lines) == 0 {
		return "", fmt.Errorf("no tags found")
	}

	parts := strings.Split(lines[0], "refs/tags/")
	if len(parts) < 2 {
		return "", fmt.Errorf("invalid tag format")
	}

	return strings.TrimSpace(parts[1]), nil
}

var updateCmd = &cobra.Command{
	Use:   "update",
	Short: "Update dborg to the latest version",
	Long:  `Update dborg by running go install git.db.org.ai/dborg@<version>`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Checking for updates...")

		latestVersion, err := getLatestVersion()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to get latest version: %v\n", err)
			os.Exit(1)
		}

		currentVersion := "dev"
		if info, ok := debug.ReadBuildInfo(); ok {
			if info.Main.Version != "" && info.Main.Version != "(devel)" {
				currentVersion = info.Main.Version
			}
		}

		if currentVersion != "dev" && currentVersion == latestVersion {
			fmt.Printf("You're already on the latest version: %s\n", latestVersion)
			return
		}

		fmt.Printf("Updating from %s to %s...\n", currentVersion, latestVersion)
		fmt.Printf("Installing dborg %s...\n", latestVersion)

		installTarget := fmt.Sprintf("git.db.org.ai/dborg@%s", latestVersion)
		installCmd := exec.Command("go", "install", installTarget)
		installCmd.Stdout = os.Stdout
		installCmd.Stderr = os.Stderr

		if err := installCmd.Run(); err != nil {
			fmt.Fprintf(os.Stderr, "Failed to update dborg: %v\n", err)
			os.Exit(1)
		}

		fmt.Printf("Updated to %s\n", latestVersion)
	},
}

func init() {
	rootCmd.AddCommand(updateCmd)
}