|
| 1 | +// / ctx: https://ctx.ist |
| 2 | +// ,'`./ do you remember? |
| 3 | +// `.,'\ |
| 4 | +// \ Copyright 2026-present Context contributors. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 |
| 6 | + |
| 7 | +package hubsync |
| 8 | + |
| 9 | +import ( |
| 10 | + "context" |
| 11 | + "fmt" |
| 12 | + "os" |
| 13 | + "path/filepath" |
| 14 | + |
| 15 | + connectCfg "github.com/ActiveMemory/ctx/internal/cli/connect/core/config" |
| 16 | + "github.com/ActiveMemory/ctx/internal/cli/connect/core/render" |
| 17 | + "github.com/ActiveMemory/ctx/internal/hub" |
| 18 | + "github.com/ActiveMemory/ctx/internal/rc" |
| 19 | +) |
| 20 | + |
| 21 | +// connectFile is the encrypted connection config filename. |
| 22 | +const connectFile = ".connect.enc" |
| 23 | + |
| 24 | +// Connected reports whether a hub connection config exists. |
| 25 | +// |
| 26 | +// Returns: |
| 27 | +// - bool: true if .context/.connect.enc exists |
| 28 | +func Connected() bool { |
| 29 | + path := filepath.Join(rc.ContextDir(), connectFile) |
| 30 | + _, statErr := os.Stat(path) |
| 31 | + return statErr == nil |
| 32 | +} |
| 33 | + |
| 34 | +// Sync pulls new entries from the hub and writes them to |
| 35 | +// .context/shared/. Returns the count of synced entries |
| 36 | +// and a formatted status message, or empty string if no |
| 37 | +// new entries. |
| 38 | +// |
| 39 | +// Parameters: |
| 40 | +// - sessionID: current session ID (unused, for future) |
| 41 | +// |
| 42 | +// Returns: |
| 43 | +// - string: status message or empty if nothing synced |
| 44 | +func Sync(_ string) string { |
| 45 | + cfg, loadErr := connectCfg.Load() |
| 46 | + if loadErr != nil { |
| 47 | + return "" |
| 48 | + } |
| 49 | + |
| 50 | + client, dialErr := hub.NewClient( |
| 51 | + cfg.HubAddr, cfg.Token, |
| 52 | + ) |
| 53 | + if dialErr != nil { |
| 54 | + return "" |
| 55 | + } |
| 56 | + defer func() { _ = client.Close() }() |
| 57 | + |
| 58 | + entries, syncErr := client.Sync( |
| 59 | + context.Background(), cfg.Types, 0, |
| 60 | + ) |
| 61 | + if syncErr != nil || len(entries) == 0 { |
| 62 | + return "" |
| 63 | + } |
| 64 | + |
| 65 | + if writeErr := render.WriteEntries(entries); writeErr != nil { |
| 66 | + return "" |
| 67 | + } |
| 68 | + |
| 69 | + return fmt.Sprintf( |
| 70 | + "Hub sync: %d shared entries updated", |
| 71 | + len(entries), |
| 72 | + ) |
| 73 | +} |
0 commit comments