diff --git a/README.md b/README.md index 2167f52..32842ca 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,10 @@ go install github.com/wailsapp/wails/v2/cmd/wails@latest make install # builds and installs to ~/.local (binary, .desktop file, icon) ``` +### Updating + +dbro checks for a new release on startup (turn it off in Settings) and offers to update itself: it downloads the release for your platform, checks its SHA-256 and replaces itself, and the new version runs after a restart. `dbro update` does the same from a terminal. A copy installed by a package manager (under `/usr`) is left to that package manager. + ## Themes Seven built-in themes, light or dark from your system, live [Omarchy](https://omarchy.org) sync, and your own themes as TOML files. See [docs/themes.md](docs/themes.md) for the gallery and the theme format. diff --git a/app.go b/app.go index 748e28a..1833cc4 100644 --- a/app.go +++ b/app.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "os" + "os/exec" "path/filepath" "strings" "sync" @@ -23,6 +24,7 @@ import ( "github.com/ExeQue/dbro/internal/sqllog" "github.com/ExeQue/dbro/internal/sshtunnel" "github.com/ExeQue/dbro/internal/theme" + "github.com/ExeQue/dbro/internal/update" ) // App is bound to the frontend; every exported method is callable from TypeScript. @@ -849,3 +851,32 @@ func (a *App) TableInfo(name, database, schema, table string) ([]db.InfoItem, er } return c.TableInfo(a.ctx, database, schema, table) } + +// CheckUpdate looks up the latest release on GitHub. +func (a *App) CheckUpdate() (update.Release, error) { + return update.Latest(a.ctx, version) +} + +// InstallUpdate replaces dbro with the latest release; it runs from the next start. +func (a *App) InstallUpdate() (string, error) { + r, err := update.Latest(a.ctx, version) + if err != nil { + return "", err + } + if !r.Available { + return "", fmt.Errorf("dbro %s is the latest version", version) + } + return r.Version, update.Install(a.ctx, r) +} + +// Restart starts the installed version and closes this one. +func (a *App) Restart() error { + if a.headless != nil { + return errors.New("restart dbro serve to run the new version") + } + if err := exec.Command(update.Executable(), os.Args[1:]...).Start(); err != nil { + return err + } + runtime.Quit(a.ctx) + return nil +} diff --git a/frontend/src/actions.ts b/frontend/src/actions.ts index 0fd16f0..ad6c43f 100644 --- a/frontend/src/actions.ts +++ b/frontend/src/actions.ts @@ -5,7 +5,8 @@ import { modal, confirm, prompt, toast, showError, errorMessage, field, type Men import { state, emit, connInfo, dialect, quoteIdent, displayName, type Selection } from './state'; import { applyTheme, currentTheme, applyFont } from './theme'; import type { Tree } from './tree'; -import { config, db } from '../wailsjs/go/models'; +import { config, db, type update } from '../wailsjs/go/models'; +import { BrowserOpenURL } from '../wailsjs/runtime/runtime'; let tree: Tree; export function bindTree(t: Tree) { @@ -492,6 +493,7 @@ export async function settings() { const lerdConnect = h('input', { type: 'checkbox', checked: boot.settings.lerdAutoConnect }); const font = h('input', { class: 'input', value: boot.settings.font ?? '', placeholder: 'monospace (from fontconfig)' }); const timeout = h('input', { class: 'input', value: boot.settings.queryTimeout, inputmode: 'numeric' }); + const updates = h('input', { type: 'checkbox', checked: boot.settings.checkUpdates }); const exe = boot.executable || 'dbro'; const mcpCmd = `claude mcp add dbro -- ${exe} mcp`; const r = await modal('Settings', h('div', { class: 'form' }, @@ -507,12 +509,16 @@ export async function settings() { h('div', { class: 'form-row' }, field('Font', font), field('Agent query timeout (seconds)', timeout)), h('label', { class: 'check' }, lerd, ' Show lerd database services in the tree'), h('label', { class: 'check' }, lerdConnect, ' Connect to lerd on startup'), + h('div', { style: { display: 'flex', gap: '10px', alignItems: 'center' } }, + h('label', { class: 'check' }, updates, ' Check for updates on startup'), + h('span', { class: 'muted' }, `dbro ${boot.version}`), + h('button', { type: 'button', class: 'btn small', onclick: () => checkUpdate(true) }, 'Check now')), h('fieldset', {}, h('legend', {}, 'MCP server for agents'), h('p', { class: 'muted' }, 'Agents get read-only access to your saved connections. Writes need "Allow agents to change data" on the connection.'), h('div', { style: { display: 'flex', gap: '6px' } }, h('code', { style: { flex: '1', userSelect: 'all' } }, mcpCmd), h('button', { type: 'button', class: 'btn small', onclick: () => { Go.CopyText(mcpCmd); toast('Copied'); } }, 'Copy')), h('p', { class: 'muted' }, 'Over HTTP: ', h('code', {}, `${exe} mcp --http`), ' or the headless ', h('code', {}, `${exe} serve`), ' (also at /mcp).')), ), [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => { - const s = { ...boot.settings, lerd: lerd.checked, lerdAutoConnect: lerdConnect.checked, font: font.value.trim(), queryTimeout: Number(timeout.value) || 30 }; + const s = { ...boot.settings, lerd: lerd.checked, lerdAutoConnect: lerdConnect.checked, checkUpdates: updates.checked, font: font.value.trim(), queryTimeout: Number(timeout.value) || 30 }; await Go.SaveSettings(s as any); const t = await Go.SetTheme(chosen); applyTheme(t); @@ -559,3 +565,34 @@ export async function generateSQL(sel: Selection, kind: 'SELECT' | 'INSERT' | 'U showError(e); } } + +// ---- updates ---- + +/** checkUpdate looks for a newer release; quiet on startup, with feedback when asked for. */ +export async function checkUpdate(manual = false) { + try { + const r = await Go.CheckUpdate(); + if (r.available) emit('updateAvailable', r); + if (manual) { + if (r.available) await installUpdate(r); + else toast(`dbro ${state.boot.version} is the latest version`); + } + } catch (e) { + if (manual) showError(e, 'Could not check for updates'); + } +} + +export async function installUpdate(r: update.Release) { + const notes = h('a', { href: r.url, onclick: (e: Event) => { e.preventDefault(); BrowserOpenURL(r.url); } }, 'Release notes'); + if (!r.installable) { + await modal(`dbro ${r.version} is available`, h('div', {}, h('p', {}, `You have ${state.boot.version}. dbro cannot update itself here: ${r.reason}.`), h('p', {}, notes))); + return; + } + const ok = await modal(`dbro ${r.version} is available`, h('div', {}, h('p', {}, `You have ${state.boot.version}. dbro downloads the new version, checks it and replaces itself.`), h('p', {}, notes)), + [{ label: 'Later' }, { label: 'Update', primary: true, action: () => Go.InstallUpdate() }]); + if (ok !== 1) return; + emit('updateInstalled', r); + if (await confirm('Update installed', `dbro ${r.version} is installed. Restart now to use it?`, 'Restart')) { + await Go.Restart().catch((e) => showError(e, 'Could not restart')); + } +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 79cca71..11854d0 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -11,7 +11,7 @@ import { QueryTab } from './query'; import { dialogOpen, confirm, toast, showError } from './dialogs'; import * as actions from './actions'; import { logo } from './logo'; -import type { theme } from '../wailsjs/go/models'; +import type { theme, update } from '../wailsjs/go/models'; type TabId = 'data' | 'structure' | string; @@ -29,6 +29,8 @@ const content = h('div', { class: 'pane' }); const logBox = h('section', { class: 'log', 'aria-label': 'SQL log' }); const statusLeft = h('span'); const statusRight = h('span', { class: 'right' }); +const versionButton = h('button', { type: 'button', class: 'btn small', title: 'Check for updates', onclick: () => (pendingUpdate ? actions.installUpdate(pendingUpdate) : actions.checkUpdate(true)) }); +let pendingUpdate: update.Release | null = null; function layout() { const sidebar = h('div', { class: 'sidebar' }, tree.root); @@ -60,7 +62,7 @@ function layout() { toolbar, h('div', { class: 'body' }, sidebar, resizer, main), logBox, - h('footer', { class: 'statusbar' }, statusLeft, h('span', { class: 'right' }, statusRight, logToggle))); + h('footer', { class: 'statusbar' }, statusLeft, h('span', { class: 'right' }, statusRight, versionButton, logToggle))); } function renderTabs() { @@ -199,6 +201,16 @@ on('reloadData', () => data.load()); on('schemaChanged', () => { if (state.selection?.table) data.show(state.selection, true); }); +on('updateAvailable', (r: update.Release) => { + pendingUpdate = r; + versionButton.textContent = `Update to ${r.version}`; + versionButton.classList.add('primary'); +}); +on('updateInstalled', (r: update.Release) => { + pendingUpdate = null; + versionButton.textContent = `${r.version} on restart`; + versionButton.classList.remove('primary'); +}); on('themeChanged', (t: theme.Theme) => { state.boot.theme = t; updateStatus(); @@ -261,6 +273,7 @@ async function commandPalette() { { label: 'Refresh', icon: 'refresh', shortcut: 'F5', run: () => refresh() }, { label: 'Settings', icon: 'gear', shortcut: 'Ctrl+,', run: () => actions.settings() }, { label: 'Toggle SQL log', run: () => logBox.classList.toggle('collapsed') }, + { label: 'Check for updates', icon: 'refresh', run: () => actions.checkUpdate(true) }, ]; if (sel && (sel.kind === 'table' || sel.kind === 'view')) { const t = sel.table!; @@ -327,6 +340,8 @@ async function start() { showTab('data'); updateStatus(); if (state.boot.askOmarchy) actions.askOmarchy(); + versionButton.textContent = state.boot.version; + if (state.boot.settings.checkUpdates && state.boot.version !== 'dev') actions.checkUpdate(); } start(); diff --git a/frontend/wailsjs/go/main/App.d.ts b/frontend/wailsjs/go/main/App.d.ts index 923598f..8e1ed3c 100755 --- a/frontend/wailsjs/go/main/App.d.ts +++ b/frontend/wailsjs/go/main/App.d.ts @@ -3,6 +3,7 @@ import {theme} from '../models'; import {db} from '../models'; import {main} from '../models'; +import {update} from '../models'; import {config} from '../models'; import {history} from '../models'; @@ -16,6 +17,8 @@ export function Browse(arg1:string,arg2:string,arg3:string,arg4:string,arg5:stri export function CancelQuery(arg1:string):Promise; +export function CheckUpdate():Promise; + export function Clone(arg1:string,arg2:string,arg3:Array,arg4:string,arg5:string,arg6:string,arg7:db.CloneOptions):Promise; export function CloseQueryTab(arg1:string,arg2:string,arg3:string):Promise; @@ -62,6 +65,8 @@ export function ImportCSV(arg1:string,arg2:string,arg3:string,arg4:string,arg5:s export function ImportSQL(arg1:string,arg2:string,arg3:boolean):Promise; +export function InstallUpdate():Promise; + export function ListConnections():Promise; export function ListThemes():Promise>; @@ -86,6 +91,8 @@ export function ProvidePassword(arg1:string,arg2:string,arg3:string,arg4:boolean export function ResolveLaravel(arg1:string):Promise; +export function Restart():Promise; + export function RoutineSource(arg1:string,arg2:string,arg3:db.Routine):Promise; export function RunQuery(arg1:string,arg2:string,arg3:string,arg4:string,arg5:number,arg6:Record):Promise; diff --git a/frontend/wailsjs/go/main/App.js b/frontend/wailsjs/go/main/App.js index a88337c..0c6d02e 100755 --- a/frontend/wailsjs/go/main/App.js +++ b/frontend/wailsjs/go/main/App.js @@ -22,6 +22,10 @@ export function CancelQuery(arg1) { return window['go']['main']['App']['CancelQuery'](arg1); } +export function CheckUpdate() { + return window['go']['main']['App']['CheckUpdate'](); +} + export function Clone(arg1, arg2, arg3, arg4, arg5, arg6, arg7) { return window['go']['main']['App']['Clone'](arg1, arg2, arg3, arg4, arg5, arg6, arg7); } @@ -114,6 +118,10 @@ export function ImportSQL(arg1, arg2, arg3) { return window['go']['main']['App']['ImportSQL'](arg1, arg2, arg3); } +export function InstallUpdate() { + return window['go']['main']['App']['InstallUpdate'](); +} + export function ListConnections() { return window['go']['main']['App']['ListConnections'](); } @@ -162,6 +170,10 @@ export function ResolveLaravel(arg1) { return window['go']['main']['App']['ResolveLaravel'](arg1); } +export function Restart() { + return window['go']['main']['App']['Restart'](); +} + export function RoutineSource(arg1, arg2, arg3) { return window['go']['main']['App']['RoutineSource'](arg1, arg2, arg3); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9ceb952..3c46449 100755 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -93,6 +93,7 @@ export namespace config { lerdAutoConnect: boolean; firstRunDone: boolean; queryTimeout: number; + checkUpdates: boolean; static createFrom(source: any = {}) { return new Settings(source); @@ -107,6 +108,7 @@ export namespace config { this.lerdAutoConnect = source["lerdAutoConnect"]; this.firstRunDone = source["firstRunDone"]; this.queryTimeout = source["queryTimeout"]; + this.checkUpdates = source["checkUpdates"]; } } @@ -710,3 +712,28 @@ export namespace theme { } +export namespace update { + + export class Release { + version: string; + url: string; + available: boolean; + installable: boolean; + reason?: string; + + static createFrom(source: any = {}) { + return new Release(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.version = source["version"]; + this.url = source["url"]; + this.available = source["available"]; + this.installable = source["installable"]; + this.reason = source["reason"]; + } + } + +} + diff --git a/internal/config/config.go b/internal/config/config.go index b7150c0..5b52733 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -58,6 +58,7 @@ type Settings struct { LerdConnect bool `toml:"lerd_auto_connect" json:"lerdAutoConnect"` // connect to them on startup FirstRunDone bool `toml:"first_run_done,omitempty" json:"firstRunDone"` QueryTimeout int `toml:"query_timeout,omitempty" json:"queryTimeout"` // seconds + CheckUpdates bool `toml:"check_updates" json:"checkUpdates"` // look for a new release on startup } // Dir returns the config directory, honoring DBRO_CONFIG_DIR and XDG_CONFIG_HOME. @@ -121,7 +122,7 @@ func SaveConnections(conns []Connection) error { // LoadSettings reads config.toml with defaults for missing values. func LoadSettings() (Settings, error) { - s := Settings{Lerd: true, LerdConnect: true, QueryTimeout: 30} + s := Settings{Lerd: true, LerdConnect: true, QueryTimeout: 30, CheckUpdates: true} _, err := toml.DecodeFile(filepath.Join(Dir(), "config.toml"), &s) if err != nil && !errors.Is(err, os.ErrNotExist) { return s, fmt.Errorf("read config.toml: %w", err) diff --git a/internal/update/update.go b/internal/update/update.go new file mode 100644 index 0000000..18e10b5 --- /dev/null +++ b/internal/update/update.go @@ -0,0 +1,346 @@ +// Package update finds the latest dbro release on GitHub and installs it over the running binary. +package update + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +const api = "https://api.github.com/repos/ExeQue/dbro/releases/latest" + +// Release is the latest published version. +type Release struct { + Version string `json:"version"` + URL string `json:"url"` + Available bool `json:"available"` // newer than the running version + // Installable is false when dbro cannot replace itself (a package manager owns it, or the folder is read-only). + Installable bool `json:"installable"` + Reason string `json:"reason,omitempty"` + assets map[string]string +} + +var client = &http.Client{Timeout: 30 * time.Second} + +// Latest asks GitHub for the newest release and compares it with current. +func Latest(ctx context.Context, current string) (Release, error) { + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, api, nil) + req.Header.Set("Accept", "application/vnd.github+json") + resp, err := client.Do(req) + if err != nil { + return Release{}, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return Release{}, fmt.Errorf("GitHub answered %s", resp.Status) + } + var gh struct { + Tag string `json:"tag_name"` + URL string `json:"html_url"` + Assets []struct { + Name string `json:"name"` + URL string `json:"browser_download_url"` + } `json:"assets"` + } + if err := json.NewDecoder(resp.Body).Decode(&gh); err != nil { + return Release{}, err + } + r := Release{Version: gh.Tag, URL: gh.URL, Available: Newer(gh.Tag, current), assets: map[string]string{}} + for _, a := range gh.Assets { + r.assets[a.Name] = a.URL + } + r.Reason = installable(r) + r.Installable = r.Reason == "" + return r, nil +} + +// Newer reports whether release is a later version than current. A development build +// ("dev") never asks to update; "v0.1.4-3-gabc" counts as v0.1.4. +func Newer(release, current string) bool { + a, ok1 := parse(release) + b, ok2 := parse(current) + if !ok1 || !ok2 { + return false + } + for i := range a { + if a[i] != b[i] { + return a[i] > b[i] + } + } + return false +} + +func parse(v string) ([3]int, bool) { + var n [3]int + v, _, _ = strings.Cut(strings.TrimPrefix(v, "v"), "-") + parts := strings.Split(v, ".") + if len(parts) != 3 { + return n, false + } + for i, p := range parts { + x, err := strconv.Atoi(p) + if err != nil { + return n, false + } + n[i] = x + } + return n, true +} + +// target names the release archive for this platform. +func target() (string, error) { + switch runtime.GOOS + "/" + runtime.GOARCH { + case "linux/amd64", "linux/arm64": + return "linux-" + runtime.GOARCH + ".tar.gz", nil + case "darwin/amd64", "darwin/arm64": + return "macos-universal.zip", nil + case "windows/amd64": + return "windows-amd64.zip", nil + } + return "", fmt.Errorf("no release build for %s/%s", runtime.GOOS, runtime.GOARCH) +} + +// self is the running binary, read at start: once an update moves it aside, os.Executable points at the old file. +var self = func() string { + exe, err := os.Executable() + if err == nil { + exe, err = filepath.EvalSymlinks(exe) + } + if err != nil { + return "" + } + return exe +}() + +// Executable is the path dbro was started from, where an update puts the new version. +func Executable() string { return self } + +// dest is what an update replaces: the binary, or the whole dbro.app on macOS. +func dest() (string, error) { + exe := self + if exe == "" { + return "", errors.New("cannot find the dbro binary") + } + if runtime.GOOS == "darwin" { + if app := filepath.Dir(filepath.Dir(filepath.Dir(exe))); strings.HasSuffix(app, ".app") { + return app, nil + } + } + return exe, nil +} + +// installable explains why this copy cannot update itself, or returns "". +func installable(r Release) string { + t, err := target() + if err != nil { + return err.Error() + } + if _, ok := r.assets[archiveName(r.Version, t)]; !ok { + return "the release has no build for this platform" + } + d, err := dest() + if err != nil { + return err.Error() + } + if strings.HasPrefix(d, "/usr/") { + return "installed by a package manager; update it there" + } + f, err := os.CreateTemp(filepath.Dir(d), ".dbro-update-*") + if err != nil { + return filepath.Dir(d) + " is not writable" + } + f.Close() + os.Remove(f.Name()) + return "" +} + +func archiveName(version, target string) string { return "dbro-" + version + "-" + target } + +// Install downloads the release, checks its SHA-256 and swaps it in for the running copy. +// The new version runs from the next start. +func Install(ctx context.Context, r Release) error { + if !r.Installable { + return errors.New(r.Reason) + } + t, _ := target() + name := archiveName(r.Version, t) + archive, err := get(ctx, r.assets[name]) + if err != nil { + return err + } + sum, err := get(ctx, r.assets[name+".sha256"]) + if err != nil { + return fmt.Errorf("checksum: %w", err) + } + got := sha256.Sum256(archive) + if want, _, _ := strings.Cut(string(sum), " "); hex.EncodeToString(got[:]) != strings.TrimSpace(want) { + return errors.New("the download does not match its checksum") + } + d, err := dest() + if err != nil { + return err + } + if runtime.GOOS == "darwin" { + return installApp(archive, d) + } + bin, err := extractBinary(archive) + if err != nil { + return err + } + return swapFile(bin, d) +} + +func get(ctx context.Context, url string) ([]byte, error) { + if url == "" { + return nil, errors.New("missing download") + } + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + resp, err := (&http.Client{Timeout: 5 * time.Minute}).Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("download answered %s", resp.Status) + } + return io.ReadAll(resp.Body) +} + +// extractBinary pulls the dbro binary out of a Linux tar.gz or the Windows zip. +func extractBinary(archive []byte) ([]byte, error) { + want := "dbro" + if runtime.GOOS == "windows" { + want = "dbro.exe" + zr, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive))) + if err != nil { + return nil, err + } + for _, f := range zr.File { + if filepath.Base(f.Name) == want { + rc, err := f.Open() + if err != nil { + return nil, err + } + defer rc.Close() + return io.ReadAll(rc) + } + } + } else { + gz, err := gzip.NewReader(bytes.NewReader(archive)) + if err != nil { + return nil, err + } + tr := tar.NewReader(gz) + for { + h, err := tr.Next() + if err != nil { + break + } + if h.Typeflag == tar.TypeReg && filepath.Base(h.Name) == want { + return io.ReadAll(tr) + } + } + } + return nil, fmt.Errorf("%s not found in the download", want) +} + +// swapFile replaces path with data. A running binary can be renamed (also on Windows), +// so the old one moves aside and is removed now or, on Windows, on the next start. +func swapFile(data []byte, path string) error { + tmp := path + ".new" + if err := os.WriteFile(tmp, data, 0o755); err != nil { + return err + } + old := path + ".old" + os.Remove(old) + if err := os.Rename(path, old); err != nil { + os.Remove(tmp) + return err + } + if err := os.Rename(tmp, path); err != nil { + os.Rename(old, path) + return err + } + os.Remove(old) // fails on Windows while running; Cleanup takes it later + return nil +} + +// installApp unpacks dbro.app next to the current one and swaps the folders. +func installApp(archive []byte, app string) error { + zr, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive))) + if err != nil { + return err + } + stage, err := os.MkdirTemp(filepath.Dir(app), ".dbro-update-") + if err != nil { + return err + } + defer os.RemoveAll(stage) + for _, f := range zr.File { + p := filepath.Join(stage, f.Name) + if !strings.HasPrefix(p, stage+string(os.PathSeparator)) { + return fmt.Errorf("bad path in download: %s", f.Name) + } + if f.FileInfo().IsDir() { + if err := os.MkdirAll(p, 0o755); err != nil { + return err + } + continue + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + rc, err := f.Open() + if err != nil { + return err + } + data, err := io.ReadAll(rc) + rc.Close() + if err != nil { + return err + } + if f.Mode()&os.ModeSymlink != 0 { + err = os.Symlink(string(data), p) + } else { + err = os.WriteFile(p, data, f.Mode().Perm()) + } + if err != nil { + return err + } + } + fresh := filepath.Join(stage, "dbro.app") + if _, err := os.Stat(fresh); err != nil { + return errors.New("dbro.app not found in the download") + } + old := filepath.Join(stage, "old.app") + if err := os.Rename(app, old); err != nil { + return err + } + if err := os.Rename(fresh, app); err != nil { + os.Rename(old, app) + return err + } + return nil +} + +// Cleanup removes the binary an update on Windows had to leave behind. +func Cleanup() { + if d, err := dest(); err == nil { + os.Remove(d + ".old") + } +} diff --git a/internal/update/update_test.go b/internal/update/update_test.go new file mode 100644 index 0000000..44b5bb7 --- /dev/null +++ b/internal/update/update_test.go @@ -0,0 +1,65 @@ +package update + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestNewer(t *testing.T) { + for _, c := range []struct { + release, current string + want bool + }{ + {"v0.1.5", "v0.1.4", true}, + {"v0.2.0", "v0.1.9", true}, + {"v0.1.10", "v0.1.9", true}, + {"v0.1.4", "v0.1.4", false}, + {"v0.1.4", "v0.1.5", false}, + {"v0.1.4", "v0.1.4-3-gabc123", false}, + {"v0.1.5", "v0.1.4-3-gabc123", true}, + {"v0.1.5", "dev", false}, + {"nightly", "v0.1.4", false}, + } { + if got := Newer(c.release, c.current); got != c.want { + t.Errorf("Newer(%q, %q) = %v", c.release, c.current, got) + } + } +} + +func TestExtractAndSwap(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("tar.gz archives are the Linux release") + } + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for name, body := range map[string]string{"dbro-v1.0.0-linux-amd64/README.md": "readme", "dbro-v1.0.0-linux-amd64/dbro": "new binary"} { + tw.WriteHeader(&tar.Header{Name: name, Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write([]byte(body)) + } + tw.Close() + gz.Close() + + bin, err := extractBinary(buf.Bytes()) + if err != nil || string(bin) != "new binary" { + t.Fatalf("extractBinary = %q, %v", bin, err) + } + path := filepath.Join(t.TempDir(), "dbro") + os.WriteFile(path, []byte("old binary"), 0o755) + if err := swapFile(bin, path); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(path) + st, _ := os.Stat(path) + if string(got) != "new binary" || st.Mode().Perm()&0o100 == 0 { + t.Fatalf("after swap: %q %v", got, st.Mode()) + } + if _, err := os.Stat(path + ".old"); !os.IsNotExist(err) { + t.Fatal("old binary left behind") + } +} diff --git a/main.go b/main.go index 9068f4c..1bed4b1 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "github.com/wailsapp/wails/v2/pkg/options/linux" "github.com/ExeQue/dbro/internal/mcpserver" + "github.com/ExeQue/dbro/internal/update" ) //go:embed all:frontend/dist @@ -32,6 +33,7 @@ Usage: dbro serve [--addr 127.0.0.1:7810] headless: the app in a web browser, plus MCP at /mcp dbro version print the version + dbro update install the latest release Beyond loopback a token is required: set DBRO_TOKEN, or dbro prints a fresh one. @@ -62,6 +64,12 @@ func main() { case "version", "--version": fmt.Println(version) return + case "update": + if err := selfUpdate(); err != nil { + fmt.Fprintln(os.Stderr, "dbro update:", err) + os.Exit(1) + } + return case "help", "--help", "-h": fmt.Print(usage) return @@ -76,6 +84,7 @@ func main() { } } + update.Cleanup() app := NewApp() err := wails.Run(&options.App{ Title: "dbro", @@ -99,3 +108,22 @@ func main() { os.Exit(1) } } + +// selfUpdate is "dbro update": install the latest release over this binary. +func selfUpdate() error { + ctx := context.Background() + r, err := update.Latest(ctx, version) + if err != nil { + return err + } + if !r.Available { + fmt.Printf("dbro %s is the latest version.\n", version) + return nil + } + fmt.Printf("Installing dbro %s (running %s)...\n", r.Version, version) + if err := update.Install(ctx, r); err != nil { + return err + } + fmt.Println("Done. Restart dbro to use it.") + return nil +} diff --git a/serve.go b/serve.go index 67eba58..ceae77b 100644 --- a/serve.go +++ b/serve.go @@ -41,6 +41,7 @@ const headlessJS = `(() => { return () => (on[n] = on[n].filter((x) => x !== f)); }, EventsOff: (n) => delete on[n], + BrowserOpenURL: (u) => window.open(u, '_blank', 'noopener'), LogInfo: () => {}, LogError: () => {}, };