* perf(git): locate the repository in-process instead of running git rev-parse Every bd invocation resolved the process-wide git context (beads directory discovery reads it) with `git rev-parse --git-dir --git-common-dir --show-toplevel`: one git subprocess per bd call before any work. Tools that call bd hundreds of times (gascity's doctor issues ~250 bd calls per run) paid it on every call. On Linux, initGitContext now first runs discoverGitInProcess, which mirrors Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir check, filesystem-boundary stop) and produces byte-for-byte what rev-parse prints for ordinary repositories (top and subdirectories), linked worktrees (absolute or relative gitfile, symlinked targets), submodules (core.worktree pointing back at the gitfile's directory), nested repositories and no repository. Both answers feed one shared normalization (gitContextFromRevParse), so downstream values are unchanged. It declines, and git runs exactly as before, whenever it cannot prove the answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES / GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS / GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile or git directory, a cwd inside a git directory; repository config with core.worktree (other than the submodule shape), core.bare, extensions, include directives, a format version above 1 or unmodeled syntax; any path not owned by the effective uid (safe.directory is git's to evaluate), or root under sudo. darwin and windows keep the subprocess (case folding and ownership semantics). Tests compare discoverGitFrom with real `git rev-parse` output across those layouts, pin every decline case, and check the resulting cached context equals the subprocess-derived one. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(cli): resolve the git user.name actor fallback only when needed PersistentPreRunE assigned `actor = getActorWithGit()` for every command, which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs `git config user.name`: the second git subprocess of every bd call, paid by read-only commands that never consult the actor. The pre-run now calls deferActorGitFallback, which marks an empty actor as pending; currentActor (and getActorWithGit, getActor) resolve it on first use with the unchanged priority order and store it in the global and the CommandContext copy, as the eager assignment did. Command code reads the actor through currentActor() instead of the raw global (a mechanical rewrite of every read site the compiler reported; writes, the flag binding and the pre-run config binding keep the raw variable). setActor cancels a pending fallback. The telemetry span's bd.actor attribute is still set, but only for a recording span, so a noop span does not force the lookup. With the in-process repository discovery from the previous commit, a read-only `bd list` / `bd show` now starts no git process at startup, in the main checkout and in a linked worktree; a write asks git for user.name once (bd create previously asked once, now still once) and records the same value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs (embedded and proxied-server workspaces, main checkout and worktree). TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim; TestDeferredActorGitFallback pins the deferral semantics. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(git): decline in-process discovery on any config line git might read differently Review follow-ups to the in-process repository discovery. - The repository config scanner was looser than git: a config starting with a UTF-8 BOM followed by `[core] worktree = /other` made git report /other while discovery returned the cwd repository, and `[ core ]` or `!!! = x` (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now skips a leading BOM exactly as git does and accepts only a narrow grammar: blank/comment lines, `[section]` / `[section "sub"]` headers at column 0, and `key` / `key = value` lines inside a section, with values free of backslashes and unbalanced quotes. Any other line declines to git. - Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd, which trusts $PWD when it names the same inode (bind-mount aliases). - Resolve relative gitfile and commondir targets without filepath.Join's lexical Clean, so "link/.." resolves physically like git's realpath. - A mount-boundary stop reports its own reason in the not-a-repository error. - Tests: every decline case (BOM + core.worktree, malformed headers and keys, keys before a section, escapes, continuations, bare repositories, a commondir inside .git, ...) now also checks that what startup derives equals git's answer; BOM and CRLF/comment configs are equivalence cases; the no-repository case must be answered in-process instead of skipping; a $PWD alias test pins the getcwd walk. - The exec-count test drops every GIT_* variable except the config-file selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make it fail spuriously. - Comment the two places that touch the raw actor before the deferral. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(backup): decide embedded auto-backup's git-remote probe without git In an embedded workspace whose backup.enabled is unset, maybeAutoBackup asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads included. That built a RepoContext (`git -C .beads rev-parse --git-common-dir`) and ran `git remote`: two git processes per read even after the startup calls were gone. The throttle cannot short-circuit it: without a remote no backup ever runs, so there is no backup state to throttle on. Both probes are now answered in-process when provable, and the subprocess remains the fallback, so the decision and every warning/notice downstream of it are unchanged: - internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the discovery walk from the given directory, git's spelling). - primeHasGitRemote uses git.HasRemoteInProcess in the same directory primeGitCmd would run git in (primeGitDir, factored out). It answers only when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own -- is absent or within scanGitConfig's grammar and include-free, no GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and no legacy .git/remotes or .git/branches entries exist. A remote seen only in a system-config candidate declines. Remote names outside [A-Za-z0-9._-] decline. Tests compare HasRemoteInProcess with `git remote` (no remote, local, worktree, submodule, remote.pushDefault only, global remote, no repo) and pin the declines (global include, malformed global, command-line config); CommonDirInProcess is compared with `git -C dir rev-parse --git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with backup.enabled at its default, with and without a git remote, and still expects zero git processes for list/show. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
774 lines
24 KiB
Go
774 lines
24 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/notion"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/tracker"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
type notionConfig struct {
|
|
DataSourceID string
|
|
ViewURL string
|
|
}
|
|
|
|
type notionConfigSetter interface {
|
|
SetConfig(ctx context.Context, key, value string) error
|
|
}
|
|
|
|
type notionConfigDeleter interface {
|
|
DeleteConfig(ctx context.Context, key string) error
|
|
}
|
|
|
|
type notionUnsupportedPushStats struct {
|
|
counts map[types.IssueType]int
|
|
}
|
|
|
|
func newNotionUnsupportedPushStats() *notionUnsupportedPushStats {
|
|
return ¬ionUnsupportedPushStats{counts: make(map[types.IssueType]int)}
|
|
}
|
|
|
|
func (s *notionUnsupportedPushStats) record(issueType types.IssueType) {
|
|
if s == nil || strings.TrimSpace(string(issueType)) == "" {
|
|
return
|
|
}
|
|
s.counts[issueType]++
|
|
}
|
|
|
|
func (s *notionUnsupportedPushStats) warningText() string {
|
|
if s == nil || len(s.counts) == 0 {
|
|
return ""
|
|
}
|
|
parts := make([]string, 0, len(s.counts))
|
|
for issueType, count := range s.counts {
|
|
parts = append(parts, fmt.Sprintf("%s=%d", issueType, count))
|
|
}
|
|
sort.Strings(parts)
|
|
return fmt.Sprintf(
|
|
"Skipped unsupported Notion issue types: %s (supported: bug, feature, task, epic, chore)",
|
|
strings.Join(parts, ", "),
|
|
)
|
|
}
|
|
|
|
type notionSetupResult struct {
|
|
Action string `json:"action"`
|
|
DatabaseID string `json:"database_id,omitempty"`
|
|
DataSourceID string `json:"data_source_id,omitempty"`
|
|
ViewURL string `json:"view_url,omitempty"`
|
|
Message string `json:"message,omitempty"`
|
|
}
|
|
|
|
var (
|
|
notionInitParent string
|
|
notionInitTitle string
|
|
notionConnectURL string
|
|
|
|
notionSyncPull bool
|
|
notionSyncPush bool
|
|
notionSyncDryRun bool
|
|
notionPreferLocal bool
|
|
notionPreferNotion bool
|
|
notionCreateOnly bool
|
|
notionSyncState string
|
|
)
|
|
|
|
var newNotionStatusClient = notion.NewClient
|
|
var newNotionSetupClient = notion.NewClient
|
|
|
|
var notionCmd = &cobra.Command{
|
|
Use: "notion",
|
|
Short: "Notion integration commands",
|
|
Long: "Commands for syncing issues between beads and Notion.",
|
|
}
|
|
|
|
var notionStatusCmd = &cobra.Command{
|
|
Use: "status",
|
|
Short: "Show Notion sync status",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runNotionStatus,
|
|
}
|
|
|
|
var notionInitCmd = &cobra.Command{
|
|
Use: "init",
|
|
Short: "Create a dedicated Beads database in Notion",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runNotionInit,
|
|
}
|
|
|
|
var notionConnectCmd = &cobra.Command{
|
|
Use: "connect",
|
|
Short: "Connect bd to an existing Notion database or data source",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runNotionConnect,
|
|
}
|
|
|
|
var notionSyncCmd = &cobra.Command{
|
|
Use: "sync",
|
|
Short: "Sync issues with Notion",
|
|
Long: "Synchronize issues between beads and Notion.\n\n" +
|
|
"By default this performs bidirectional sync. Use --pull or --push to limit direction.",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runNotionSync,
|
|
}
|
|
|
|
func init() {
|
|
notionInitCmd.Flags().StringVar(¬ionInitParent, "parent", "", "Parent page ID")
|
|
notionInitCmd.Flags().StringVar(¬ionInitTitle, "title", notion.DefaultDatabaseTitle, "Database title")
|
|
_ = notionInitCmd.MarkFlagRequired("parent")
|
|
|
|
notionConnectCmd.Flags().StringVar(¬ionConnectURL, "url", "", "Existing Notion database or data source URL")
|
|
_ = notionConnectCmd.MarkFlagRequired("url")
|
|
|
|
notionSyncCmd.Flags().BoolVar(¬ionSyncPull, "pull", false, "Only pull issues from Notion")
|
|
notionSyncCmd.Flags().BoolVar(¬ionSyncPush, "push", false, "Only push issues to Notion")
|
|
notionSyncCmd.Flags().BoolVar(¬ionSyncDryRun, "dry-run", false, "Preview changes without making mutations")
|
|
notionSyncCmd.Flags().BoolVar(¬ionPreferLocal, "prefer-local", false, "On conflict, keep the local beads version")
|
|
notionSyncCmd.Flags().BoolVar(¬ionPreferNotion, "prefer-notion", false, "On conflict, use the Notion version")
|
|
notionSyncCmd.Flags().BoolVar(¬ionCreateOnly, "create-only", false, "Only create missing remote pages, do not update existing ones")
|
|
notionSyncCmd.Flags().StringVar(¬ionSyncState, "state", "all", "Issue state to sync: open, closed, or all")
|
|
registerSelectiveSyncFlags(notionSyncCmd)
|
|
|
|
notionCmd.AddCommand(
|
|
notionInitCmd,
|
|
notionConnectCmd,
|
|
notionStatusCmd,
|
|
notionSyncCmd,
|
|
)
|
|
rootCmd.AddCommand(notionCmd)
|
|
}
|
|
|
|
func getNotionConfig() notionConfig {
|
|
ctx := context.Background()
|
|
if store != nil {
|
|
return getNotionConfigWithReader(ctx, store)
|
|
}
|
|
if dbPath != "" {
|
|
tempStore, err := openReadOnlyStoreForDBPath(ctx, dbPath)
|
|
if err == nil {
|
|
defer func() { _ = tempStore.Close() }()
|
|
return getNotionConfigWithReader(ctx, tempStore)
|
|
}
|
|
}
|
|
return getNotionConfigWithReader(ctx, nil)
|
|
}
|
|
|
|
func getNotionConfigWithReader(ctx context.Context, reader notion.ConfigReader) notionConfig {
|
|
return notionConfig{
|
|
DataSourceID: getNotionConfigValue(ctx, reader, "notion.data_source_id", "NOTION_DATA_SOURCE_ID"),
|
|
ViewURL: getNotionConfigValue(ctx, reader, "notion.view_url", "NOTION_VIEW_URL"),
|
|
}
|
|
}
|
|
|
|
func getNotionConfigValue(ctx context.Context, reader notion.ConfigReader, key, envVar string) string {
|
|
if reader != nil {
|
|
value, _ := reader.GetConfig(ctx, key)
|
|
if strings.TrimSpace(value) != "" {
|
|
return strings.TrimSpace(value)
|
|
}
|
|
}
|
|
if envVar != "" {
|
|
return strings.TrimSpace(os.Getenv(envVar))
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func resolveNotionAuth(ctx context.Context) (*notion.ResolvedAuth, error) {
|
|
if store != nil {
|
|
return notion.ResolveAuth(ctx, store)
|
|
}
|
|
if dbPath != "" {
|
|
tempStore, err := openReadOnlyStoreForDBPath(ctx, dbPath)
|
|
if err == nil {
|
|
defer func() { _ = tempStore.Close() }()
|
|
return notion.ResolveAuth(ctx, tempStore)
|
|
}
|
|
}
|
|
return notion.ResolveAuth(ctx, nil)
|
|
}
|
|
|
|
func validateNotionConfig(cfg notionConfig, auth *notion.ResolvedAuth) error {
|
|
if auth == nil || strings.TrimSpace(auth.Token) == "" {
|
|
// NOTION_TOKEN leads deliberately: `bd config set notion.token` is
|
|
// refused when .beads/config.yaml is git-tracked, which is the default
|
|
// after `bd init` in a repo — so the first suggestion used to be the
|
|
// one that does not work. Matches the quickstart's ordering.
|
|
return fmt.Errorf("Notion authentication is not configured. Run 'export NOTION_TOKEN=<token>', or 'bd config set notion.token <token>' if .beads/config.yaml is not tracked by git")
|
|
}
|
|
if cfg.DataSourceID == "" {
|
|
return fmt.Errorf("notion.data_source_id is not configured. Run 'bd notion init --parent <page-id>' or 'bd notion connect --url <notion-url>', or set it directly via bd config set notion.data_source_id <id> or NOTION_DATA_SOURCE_ID")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateNotionToken(auth *notion.ResolvedAuth) error {
|
|
if auth == nil || strings.TrimSpace(auth.Token) == "" {
|
|
// NOTION_TOKEN leads deliberately: `bd config set notion.token` is
|
|
// refused when .beads/config.yaml is git-tracked, which is the default
|
|
// after `bd init` in a repo — so the first suggestion used to be the
|
|
// one that does not work. Matches the quickstart's ordering.
|
|
return fmt.Errorf("Notion authentication is not configured. Run 'export NOTION_TOKEN=<token>', or 'bd config set notion.token <token>' if .beads/config.yaml is not tracked by git")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func maskNotionAuth(auth *notion.ResolvedAuth) string {
|
|
if auth == nil || strings.TrimSpace(auth.Token) == "" {
|
|
return "(not set)"
|
|
}
|
|
token := auth.Token
|
|
if len(token) <= 4 {
|
|
return "****"
|
|
}
|
|
return token[:4] + "****"
|
|
}
|
|
|
|
func runNotionStatus(cmd *cobra.Command, _ []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("notion status is not supported in proxied-server mode")
|
|
}
|
|
evt := metrics.NewCommandEvent("notion-status")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
cfg := getNotionConfig()
|
|
auth, err := resolveNotionAuth(cmd.Context())
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result := notion.StatusResponse{
|
|
Configured: auth != nil && strings.TrimSpace(auth.Token) != "" && cfg.DataSourceID != "",
|
|
DataSourceID: cfg.DataSourceID,
|
|
ViewURL: cfg.ViewURL,
|
|
}
|
|
if auth != nil && strings.TrimSpace(auth.Token) != "" {
|
|
result.Auth = ¬ion.StatusAuth{OK: true, Source: string(auth.Source)}
|
|
} else {
|
|
result.Auth = ¬ion.StatusAuth{OK: false}
|
|
}
|
|
if !result.Configured {
|
|
if err := validateNotionConfig(cfg, auth); err != nil {
|
|
result.Error = err.Error()
|
|
}
|
|
if jsonOutput {
|
|
return writeNotionJSON(cmd, result)
|
|
}
|
|
renderNotionStatus(cmd, auth, cfg, &result)
|
|
return nil
|
|
}
|
|
|
|
client := newNotionStatusClient(auth.Token)
|
|
ctx := cmd.Context()
|
|
user, err := client.GetCurrentUser(ctx)
|
|
if err != nil {
|
|
result.Error = err.Error()
|
|
result.Auth = ¬ion.StatusAuth{OK: false, Source: string(auth.Source)}
|
|
} else {
|
|
result.Auth = ¬ion.StatusAuth{
|
|
OK: true,
|
|
Source: string(auth.Source),
|
|
User: statusUserFromNotionUser(user),
|
|
}
|
|
}
|
|
|
|
dataSource, dsErr := client.RetrieveDataSource(ctx, cfg.DataSourceID)
|
|
if dsErr != nil {
|
|
if result.Error == "" {
|
|
result.Error = dsErr.Error()
|
|
}
|
|
} else {
|
|
result.Database = ¬ion.StatusDatabase{
|
|
ID: dataSource.ID,
|
|
Title: notion.DataSourceTitle(dataSource.Title),
|
|
URL: dataSource.URL,
|
|
}
|
|
result.Schema = notion.ValidateDataSourceSchema(dataSource)
|
|
result.Ready = result.Auth != nil && result.Auth.OK && len(result.Schema.Missing) == 0
|
|
}
|
|
|
|
if jsonOutput {
|
|
return writeNotionJSON(cmd, result)
|
|
}
|
|
renderNotionStatus(cmd, auth, cfg, &result)
|
|
return nil
|
|
}
|
|
|
|
func runNotionInit(cmd *cobra.Command, _ []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("notion init is not supported in proxied-server mode")
|
|
}
|
|
CheckReadonly("notion init")
|
|
|
|
evt := metrics.NewCommandEvent("notion-init")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleError("database not available: %v", err)
|
|
}
|
|
auth, err := resolveNotionAuth(cmd.Context())
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if err := validateNotionToken(auth); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
result, err := runNotionInitAfterValidation(cmd.Context(), newNotionSetupClient(auth.Token), notionInitParent, notionInitTitle, store, notionConfigDeleteTarget())
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if jsonOutput {
|
|
return writeNotionJSON(cmd, result)
|
|
}
|
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "✓ Created Notion database %s\n", firstNonEmpty(result.DatabaseID, "(unknown)"))
|
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Saved data source: %s\n", result.DataSourceID)
|
|
if result.ViewURL != "" {
|
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Launch URL: %s\n", result.ViewURL)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func runNotionConnect(cmd *cobra.Command, _ []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("notion connect is not supported in proxied-server mode")
|
|
}
|
|
CheckReadonly("notion connect")
|
|
|
|
evt := metrics.NewCommandEvent("notion-connect")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleError("database not available: %v", err)
|
|
}
|
|
auth, err := resolveNotionAuth(cmd.Context())
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if err := validateNotionToken(auth); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
result, err := runNotionConnectAfterValidation(cmd.Context(), newNotionSetupClient(auth.Token), notionConnectURL, store, notionConfigDeleteTarget())
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if jsonOutput {
|
|
return writeNotionJSON(cmd, result)
|
|
}
|
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "✓ Connected Notion data source %s\n", result.DataSourceID)
|
|
if result.ViewURL != "" {
|
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Launch URL: %s\n", result.ViewURL)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func renderNotionStatus(cmd *cobra.Command, auth *notion.ResolvedAuth, cfg notionConfig, result *notion.StatusResponse) {
|
|
out := cmd.OutOrStdout()
|
|
_, _ = fmt.Fprintln(out, "Notion Configuration")
|
|
_, _ = fmt.Fprintln(out, "====================")
|
|
_, _ = fmt.Fprintf(out, "Auth: %s\n", maskNotionAuth(auth))
|
|
if auth != nil && auth.Source != "" {
|
|
_, _ = fmt.Fprintf(out, "Auth source: %s\n", auth.Source)
|
|
}
|
|
// The one place a workspace learns it is the population GH#6676 tells to
|
|
// rotate. Without it the CHANGELOG's advice has no addressee: the token
|
|
// keeps working, so nothing else ever mentions where it is stored.
|
|
if auth != nil && auth.Source == notion.AuthSourceDatabaseLegacy {
|
|
_, _ = fmt.Fprintln(out, "⚠ This token is stored in the beads database, which 'bd dolt push' replicates to every remote.")
|
|
_, _ = fmt.Fprintln(out, " Rotate it, then run 'bd config unset notion.token' to delete the stored row.")
|
|
}
|
|
_, _ = fmt.Fprintf(out, "Data source: %s\n", cfg.DataSourceID)
|
|
if cfg.ViewURL != "" {
|
|
_, _ = fmt.Fprintf(out, "View URL: %s\n", cfg.ViewURL)
|
|
}
|
|
if result.Database != nil {
|
|
_, _ = fmt.Fprintf(out, "Database: %s\n", result.Database.Title)
|
|
}
|
|
|
|
statusLine := "○ Not configured"
|
|
switch {
|
|
case result.Ready:
|
|
statusLine = "✓ Ready"
|
|
case result.Configured:
|
|
statusLine = "◐ Not ready"
|
|
}
|
|
_, _ = fmt.Fprintf(out, "\nStatus: %s\n", statusLine)
|
|
if result.Error != "" {
|
|
_, _ = fmt.Fprintf(out, "Error: %s\n", result.Error)
|
|
}
|
|
if result.Schema != nil {
|
|
if len(result.Schema.Missing) == 0 {
|
|
_, _ = fmt.Fprintln(out, "Schema: ✓ Required properties present")
|
|
} else {
|
|
_, _ = fmt.Fprintf(out, "Schema: missing %s\n", strings.Join(result.Schema.Missing, ", "))
|
|
}
|
|
}
|
|
}
|
|
|
|
func runNotionSync(cmd *cobra.Command, _ []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("notion sync is not supported in proxied-server mode")
|
|
}
|
|
evt := metrics.NewCommandEvent("notion-sync")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
cfg := getNotionConfig()
|
|
auth, err := resolveNotionAuth(cmd.Context())
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if err := validateNotionConfig(cfg, auth); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if !notionSyncDryRun {
|
|
CheckReadonly("notion sync")
|
|
}
|
|
if notionPreferLocal && notionPreferNotion {
|
|
return HandleError("cannot use both --prefer-local and --prefer-notion")
|
|
}
|
|
if notionSyncPull && notionSyncPush {
|
|
return HandleError("cannot use both --pull and --push")
|
|
}
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleError("database not available: %v", err)
|
|
}
|
|
|
|
ctx := cmd.Context()
|
|
nt := ¬ion.Tracker{}
|
|
if err := nt.Init(ctx, store); err != nil {
|
|
return HandleError("initializing Notion tracker: %v", err)
|
|
}
|
|
|
|
engine := tracker.NewEngine(nt, store, currentActor())
|
|
engine.PullHooks = buildNotionPullHooks(ctx)
|
|
unsupportedStats := newNotionUnsupportedPushStats()
|
|
engine.PushHooks = buildNotionPushHooks(ctx, nt, unsupportedStats)
|
|
if jsonOutput {
|
|
engine.OnMessage = func(msg string) { _, _ = fmt.Fprintln(cmd.ErrOrStderr(), " "+msg) }
|
|
} else {
|
|
engine.OnMessage = func(msg string) { _, _ = fmt.Fprintln(cmd.OutOrStdout(), " "+msg) }
|
|
}
|
|
engine.OnWarning = func(msg string) { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Warning: %s\n", msg) }
|
|
|
|
pull := true
|
|
push := true
|
|
if notionSyncPull {
|
|
push = false
|
|
}
|
|
if notionSyncPush {
|
|
pull = false
|
|
}
|
|
|
|
conflictResolution := tracker.ConflictTimestamp
|
|
if notionPreferLocal {
|
|
conflictResolution = tracker.ConflictLocal
|
|
}
|
|
if notionPreferNotion {
|
|
conflictResolution = tracker.ConflictExternal
|
|
}
|
|
|
|
syncOpts := tracker.SyncOptions{
|
|
Pull: pull,
|
|
Push: push,
|
|
DryRun: notionSyncDryRun,
|
|
CreateOnly: notionCreateOnly,
|
|
State: notionSyncState,
|
|
ExcludeEphemeral: true,
|
|
ConflictResolution: conflictResolution,
|
|
}
|
|
|
|
if err := applySelectiveSyncFlags(cmd, &syncOpts, push); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
result, err := engine.Sync(ctx, syncOpts)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
if warning := unsupportedStats.warningText(); warning != "" {
|
|
result.Warnings = append(result.Warnings, warning)
|
|
}
|
|
|
|
if jsonOutput {
|
|
return writeNotionJSON(cmd, result)
|
|
}
|
|
renderNotionSyncResult(cmd, result)
|
|
return nil
|
|
}
|
|
|
|
func renderNotionSyncResult(cmd *cobra.Command, result *tracker.SyncResult) {
|
|
out := cmd.OutOrStdout()
|
|
if notionSyncDryRun {
|
|
_, _ = fmt.Fprintln(out, "Dry run mode")
|
|
}
|
|
if result.PullStats.Queried > 0 || result.PullStats.Candidates > 0 {
|
|
_, _ = fmt.Fprintf(out, "Queried %d pages from Notion (%d pull candidates)\n",
|
|
result.PullStats.Queried, result.PullStats.Candidates)
|
|
}
|
|
if result.PullStats.Created > 0 || result.PullStats.Updated > 0 {
|
|
_, _ = fmt.Fprintf(out, "✓ Pulled %d issues (%d created, %d updated)\n",
|
|
result.Stats.Pulled, result.PullStats.Created, result.PullStats.Updated)
|
|
}
|
|
if result.PushStats.Created > 0 || result.PushStats.Updated > 0 {
|
|
_, _ = fmt.Fprintf(out, "✓ Pushed %d issues (%d created, %d updated)\n",
|
|
result.Stats.Pushed, result.PushStats.Created, result.PushStats.Updated)
|
|
}
|
|
if result.Stats.Conflicts > 0 {
|
|
_, _ = fmt.Fprintf(out, "◐ Resolved %d conflicts\n", result.Stats.Conflicts)
|
|
}
|
|
for _, line := range summarizeNotionSyncWarnings(result.Warnings) {
|
|
_, _ = fmt.Fprintln(out, line)
|
|
}
|
|
if notionSyncDryRun {
|
|
_, _ = fmt.Fprintln(out, "Run without --dry-run to apply changes")
|
|
}
|
|
}
|
|
|
|
func summarizeNotionSyncWarnings(warnings []string) []string {
|
|
staleTargetCount := 0
|
|
for _, warning := range warnings {
|
|
warning = strings.TrimSpace(warning)
|
|
switch {
|
|
case warning == "":
|
|
continue
|
|
case strings.HasPrefix(warning, "Skipped unsupported Notion issue types:"):
|
|
continue
|
|
case strings.Contains(warning, "outside the current target"):
|
|
staleTargetCount++
|
|
}
|
|
}
|
|
if staleTargetCount == 0 {
|
|
return nil
|
|
}
|
|
return []string{
|
|
fmt.Sprintf("Skipped %d linked issues that still point at a different Notion target. Clear external_ref to recreate them in this data source.", staleTargetCount),
|
|
}
|
|
}
|
|
|
|
func buildNotionPullHooks(ctx context.Context) *tracker.PullHooks {
|
|
prefix := "bd"
|
|
if p := config.GetString("issue-prefix"); p != "" {
|
|
prefix = p
|
|
} else if store != nil {
|
|
if p, err := store.GetConfig(ctx, "issue_prefix"); err == nil && p != "" {
|
|
prefix = p
|
|
}
|
|
}
|
|
return &tracker.PullHooks{
|
|
GenerateID: func(_ context.Context, issue *types.Issue) error {
|
|
if issue.ID == "" {
|
|
issue.ID = generateIssueID(prefix)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
}
|
|
|
|
func buildNotionPushHooks(ctx context.Context, tr tracker.IssueTracker, stats *notionUnsupportedPushStats) *tracker.PushHooks {
|
|
return &tracker.PushHooks{
|
|
ShouldPush: func(issue *types.Issue) bool {
|
|
if issue == nil || tr == nil {
|
|
return false
|
|
}
|
|
if notion.SupportsIssueType(issue.IssueType, nil) {
|
|
pushPrefix, _ := store.GetConfig(ctx, "notion.push_prefix")
|
|
pushLabel, _ := store.GetConfig(ctx, "notion.push_label")
|
|
return shouldPushNotionIssue(issue, tr, pushPrefix, pushLabel)
|
|
}
|
|
stats.record(issue.IssueType)
|
|
return false
|
|
},
|
|
}
|
|
}
|
|
|
|
func shouldPushNotionIssue(issue *types.Issue, tr tracker.IssueTracker, pushPrefix, pushLabel string) bool {
|
|
if issue == nil || tr == nil {
|
|
return false
|
|
}
|
|
|
|
if issue.ExternalRef != nil && strings.TrimSpace(*issue.ExternalRef) != "" {
|
|
return tr.IsExternalRef(*issue.ExternalRef)
|
|
}
|
|
|
|
if strings.TrimSpace(pushLabel) != "" && !matchesNotionPushLabel(issue, pushLabel) {
|
|
return false
|
|
}
|
|
|
|
if strings.TrimSpace(pushPrefix) == "" {
|
|
return true
|
|
}
|
|
|
|
for _, prefix := range strings.Split(pushPrefix, ",") {
|
|
prefix = strings.TrimSpace(prefix)
|
|
prefix = strings.TrimSuffix(prefix, "-")
|
|
if prefix != "" && strings.HasPrefix(issue.ID, prefix+"-") {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func matchesNotionPushLabel(issue *types.Issue, pushLabel string) bool {
|
|
if issue == nil || strings.TrimSpace(pushLabel) == "" {
|
|
return false
|
|
}
|
|
|
|
configured := make(map[string]struct{})
|
|
for _, raw := range strings.Split(pushLabel, ",") {
|
|
label := strings.ToLower(strings.TrimSpace(raw))
|
|
if label != "" {
|
|
configured[label] = struct{}{}
|
|
}
|
|
}
|
|
if len(configured) == 0 {
|
|
return false
|
|
}
|
|
|
|
for _, raw := range issue.Labels {
|
|
label := strings.ToLower(strings.TrimSpace(raw))
|
|
if _, ok := configured[label]; ok {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func runNotionInitAfterValidation(ctx context.Context, client *notion.Client, parent, title string, setter notionConfigSetter, deleter notionConfigDeleter) (notionSetupResult, error) {
|
|
db, err := client.CreateDatabase(ctx, parent, title)
|
|
if err != nil {
|
|
return notionSetupResult{}, err
|
|
}
|
|
if len(db.DataSources) == 0 || strings.TrimSpace(db.DataSources[0].ID) == "" {
|
|
return notionSetupResult{}, fmt.Errorf("Notion create database response did not include a child data source")
|
|
}
|
|
result := notionSetupResult{
|
|
Action: "init",
|
|
DatabaseID: strings.TrimSpace(db.ID),
|
|
DataSourceID: strings.TrimSpace(db.DataSources[0].ID),
|
|
ViewURL: strings.TrimSpace(db.URL),
|
|
Message: "Notion target initialized",
|
|
}
|
|
if err := saveNotionTargetConfigWithWriter(ctx, setter, deleter, result.DataSourceID, result.ViewURL); err != nil {
|
|
return notionSetupResult{}, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func runNotionConnectAfterValidation(ctx context.Context, client *notion.Client, url string, setter notionConfigSetter, deleter notionConfigDeleter) (notionSetupResult, error) {
|
|
resolved, err := notion.ResolveDataSourceReference(ctx, client, url)
|
|
if err != nil {
|
|
return notionSetupResult{}, err
|
|
}
|
|
schema := notion.ValidateDataSourceSchema(resolved.DataSource)
|
|
if len(schema.Missing) > 0 {
|
|
return notionSetupResult{}, fmt.Errorf("target is missing required Notion properties: %s", strings.Join(schema.Missing, ", "))
|
|
}
|
|
result := notionSetupResult{
|
|
Action: "connect",
|
|
DataSourceID: resolved.DataSourceID,
|
|
ViewURL: strings.TrimSpace(url),
|
|
Message: "Notion target connected",
|
|
}
|
|
if resolved.Database != nil {
|
|
result.DatabaseID = strings.TrimSpace(resolved.Database.ID)
|
|
}
|
|
if err := saveNotionTargetConfigWithWriter(ctx, setter, deleter, result.DataSourceID, result.ViewURL); err != nil {
|
|
return notionSetupResult{}, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func notionConfigDeleteTarget() notionConfigDeleter {
|
|
if store == nil {
|
|
return nil
|
|
}
|
|
deleter, _ := storage.UnwrapStore(store).(notionConfigDeleter)
|
|
return deleter
|
|
}
|
|
|
|
func saveNotionTargetConfigWithWriter(ctx context.Context, setter notionConfigSetter, deleter notionConfigDeleter, dataSourceID, viewURL string) error {
|
|
if setter == nil {
|
|
return fmt.Errorf("database not available")
|
|
}
|
|
if err := setter.SetConfig(ctx, "notion.data_source_id", strings.TrimSpace(dataSourceID)); err != nil {
|
|
return fmt.Errorf("save notion.data_source_id: %w", err)
|
|
}
|
|
viewURL = strings.TrimSpace(viewURL)
|
|
if viewURL == "" {
|
|
if deleter == nil {
|
|
return fmt.Errorf("store does not support config deletion")
|
|
}
|
|
if err := deleter.DeleteConfig(ctx, "notion.view_url"); err != nil {
|
|
return fmt.Errorf("clear notion.view_url: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
if err := setter.SetConfig(ctx, "notion.view_url", viewURL); err != nil {
|
|
return fmt.Errorf("save notion.view_url: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func writeNotionJSON(cmd *cobra.Command, value interface{}) error {
|
|
encoder := json.NewEncoder(cmd.OutOrStdout())
|
|
encoder.SetIndent("", " ")
|
|
return encoder.Encode(value)
|
|
}
|
|
|
|
func firstNonEmpty(values ...string) string {
|
|
for _, value := range values {
|
|
if strings.TrimSpace(value) != "" {
|
|
return strings.TrimSpace(value)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func statusUserFromNotionUser(user *notion.User) *notion.StatusUser {
|
|
if user == nil {
|
|
return nil
|
|
}
|
|
return ¬ion.StatusUser{
|
|
ID: user.ID,
|
|
Name: user.Name,
|
|
Type: user.Type,
|
|
Email: userEmail(user),
|
|
}
|
|
}
|
|
|
|
func userEmail(user *notion.User) string {
|
|
if user == nil || user.Person == nil {
|
|
return ""
|
|
}
|
|
return user.Person.Email
|
|
}
|