/{cmd,internal}: wip, implementing init with proxied-server
This commit is contained in:
parent
c79177073a
commit
4fcbd58825
23 changed files with 2313 additions and 203 deletions
30
cmd/bd/fs_adapters.go
Normal file
30
cmd/bd/fs_adapters.go
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/cmd/bd/setup"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/templates/agents"
|
||||
)
|
||||
|
||||
func newFileSystemAdapters() domain.BeadsDirFSAdapters {
|
||||
return domain.BeadsDirFSAdapters{
|
||||
ResolveBeadsDir: func() domain.BeadsDirResolution {
|
||||
beadsDir, hasExplicit := resolveBeadsDirForInit()
|
||||
return domain.BeadsDirResolution{BeadsDir: beadsDir, HasExplicit: hasExplicit}
|
||||
},
|
||||
ApplyNoCOW: applyNoCOW,
|
||||
WriteLocalVersion: writeLocalVersion,
|
||||
SetupForkExclude: setupForkExclude,
|
||||
SetupStealthMode: setupStealthMode,
|
||||
InstallGitHooks: func(p domain.HooksInstallParams) error {
|
||||
return installHooksWithOptions(p.HookNames, p.Force, p.Shared, p.Chain, p.BeadsHooks)
|
||||
},
|
||||
InstallJJHooks: installJJHooks,
|
||||
AddAgentsInstructions: func(p domain.AgentsFileParams) {
|
||||
addAgentsInstructions(p.File, p.Verbose, p.TemplatePath, agents.Profile(p.Profile), agents.RenderOpts{HasRemote: p.HasRemote})
|
||||
},
|
||||
InstallClaudeProject: setup.InstallClaudeProject,
|
||||
SetYAMLConfig: config.SetYamlConfig,
|
||||
}
|
||||
}
|
||||
|
|
@ -219,6 +219,30 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
cmdCtx.ProxiedServerMode = initProxiedServer
|
||||
}
|
||||
|
||||
if initProxiedServer {
|
||||
runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{
|
||||
prefix: prefix,
|
||||
database: database,
|
||||
roleFlag: roleFlag,
|
||||
initRemote: initRemote,
|
||||
initRemoteChanged: initRemoteChanged,
|
||||
destroyToken: destroyToken,
|
||||
serverConfigPath: serverConfigPath,
|
||||
serverLogPath: serverLogPath,
|
||||
serverRootPath: serverRootPath,
|
||||
quiet: quiet,
|
||||
stealth: stealth,
|
||||
skipHooks: skipHooks,
|
||||
skipAgents: skipAgents,
|
||||
reinitLocal: reinitLocal,
|
||||
contributor: contributor,
|
||||
team: team,
|
||||
fromJSONL: fromJSONL,
|
||||
nonInteractive: nonInteractive,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Propagate --shared-server flag to env so that IsSharedServerMode(),
|
||||
// ResolveDoltDir(), and DefaultConfig() all see shared mode immediately
|
||||
// (before config.yaml exists). Safe: init runs once and exits.
|
||||
|
|
|
|||
476
cmd/bd/init_proxied_server.go
Normal file
476
cmd/bd/init_proxied_server.go
Normal file
|
|
@ -0,0 +1,476 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/storage/fs"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
type initProxiedServerInput struct {
|
||||
prefix string
|
||||
database string
|
||||
roleFlag string
|
||||
initRemote string
|
||||
initRemoteChanged bool
|
||||
destroyToken string
|
||||
serverConfigPath string
|
||||
serverLogPath string
|
||||
serverRootPath string
|
||||
quiet bool
|
||||
stealth bool
|
||||
skipHooks bool
|
||||
skipAgents bool
|
||||
reinitLocal bool
|
||||
contributor bool
|
||||
team bool
|
||||
fromJSONL bool
|
||||
nonInteractive bool
|
||||
}
|
||||
|
||||
func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput) {
|
||||
if in.fromJSONL {
|
||||
FatalError("--from-jsonl is not supported with --proxied-server")
|
||||
}
|
||||
if in.contributor {
|
||||
FatalError("--contributor is not supported with --proxied-server")
|
||||
}
|
||||
if in.team {
|
||||
FatalError("--team is not supported with --proxied-server")
|
||||
}
|
||||
|
||||
if err := config.Initialize(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to initialize config: %v\n", err)
|
||||
}
|
||||
|
||||
if err := checkExistingBeadsData(in.prefix); err != nil {
|
||||
FatalError("%v", err)
|
||||
}
|
||||
|
||||
fsProvider := fs.NewFileSystemProvider(newFileSystemAdapters())
|
||||
fsUseCase := fsProvider.BeadsDirFSUseCase()
|
||||
|
||||
if in.stealth {
|
||||
if err := fsUseCase.SetupStealthMode(ctx, !in.quiet); err != nil {
|
||||
FatalError("setting up stealth mode: %v", err)
|
||||
}
|
||||
in.skipHooks = true
|
||||
}
|
||||
|
||||
prefix := resolveInitPrefix(in.prefix)
|
||||
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
FatalError("failed to get current directory: %v", err)
|
||||
}
|
||||
|
||||
beadsDirResolution := fsUseCase.ResolveBeadsDir(ctx)
|
||||
beadsDir, hasExplicitBeadsDir := beadsDirResolution.BeadsDir, beadsDirResolution.HasExplicit
|
||||
if strings.Contains(filepath.Clean(cwd), string(filepath.Separator)+".beads"+string(filepath.Separator)) ||
|
||||
strings.HasSuffix(filepath.Clean(cwd), string(filepath.Separator)+".beads") {
|
||||
fmt.Fprintf(os.Stderr, "Error: cannot initialize bd inside a .beads directory\n")
|
||||
fmt.Fprintf(os.Stderr, "Current directory: %s\n", cwd)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
beadsDirAbs, err := filepath.Abs(beadsDir)
|
||||
if err != nil {
|
||||
beadsDirAbs = filepath.Clean(beadsDir)
|
||||
}
|
||||
|
||||
cwdAbs, _ := filepath.Abs(cwd)
|
||||
beadsDirIsLocal := strings.HasPrefix(beadsDirAbs, filepath.Clean(cwdAbs)+string(filepath.Separator)) ||
|
||||
filepath.Clean(beadsDirAbs) == filepath.Clean(cwdAbs)
|
||||
useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal
|
||||
|
||||
if !isGitRepo() && !hasExplicitBeadsDir {
|
||||
gitInitCmd := exec.Command("git", "init")
|
||||
if output, err := gitInitCmd.CombinedOutput(); err != nil {
|
||||
FatalError("failed to initialize git repository: %v\n%s", err, output)
|
||||
}
|
||||
git.ResetCaches()
|
||||
if !in.quiet {
|
||||
fmt.Printf(" %s Initialized git repository\n", ui.RenderPass("✓"))
|
||||
}
|
||||
}
|
||||
|
||||
dbName := resolveProxiedDatabaseName(beadsDir, prefix, in.database)
|
||||
projectID := resolveProjectID(beadsDir)
|
||||
|
||||
metadataBody, err := composeProxiedServerMetadataJSON(proxiedMetadataInputs{
|
||||
dbName: dbName,
|
||||
projectID: projectID,
|
||||
serverConfigPath: in.serverConfigPath,
|
||||
serverLogPath: in.serverLogPath,
|
||||
serverRootPath: in.serverRootPath,
|
||||
})
|
||||
if err != nil {
|
||||
FatalError("composing metadata.json: %v", err)
|
||||
}
|
||||
configYAMLBody := renderInitConfigYAML("", false)
|
||||
|
||||
fsParams := domain.InitializeBeadsDirParams{
|
||||
BeadsDir: beadsDir,
|
||||
MetadataJSONBody: metadataBody,
|
||||
ConfigYAMLBody: configYAMLBody,
|
||||
SetNoCOW: true,
|
||||
}
|
||||
if useLocalBeads && beadsDirIsLocal {
|
||||
fsParams.RepoRoot = cwd
|
||||
}
|
||||
if useLocalBeads {
|
||||
fsParams.LocalVersion = Version
|
||||
}
|
||||
|
||||
fsResult, err := fsUseCase.InitializeBeadsDir(ctx, fsParams)
|
||||
if err != nil {
|
||||
FatalError("initializing .beads directory: %v", err)
|
||||
}
|
||||
if fsResult.NoCOWErr != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to set FS_NOCOW_FL on %s: %v\n", beadsDir, fsResult.NoCOWErr)
|
||||
}
|
||||
if fsResult.LocalVersionErr != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to initialize version tracking: %v\n", fsResult.LocalVersionErr)
|
||||
}
|
||||
|
||||
uowProvider, err := newProxiedServerUOWProvider(ctx, beadsDir)
|
||||
if err != nil {
|
||||
FatalError("failed to open uow provider: %v", err)
|
||||
}
|
||||
|
||||
uw, err := uowProvider.NewUOW(ctx)
|
||||
if err != nil {
|
||||
FatalError("failed to open unit of work: %v", err)
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
bootstrapParams := domain.BootstrapProjectParams{
|
||||
Prefix: prefix,
|
||||
ProjectID: projectID,
|
||||
BdVersion: Version,
|
||||
LastImportTime: time.Now(),
|
||||
}
|
||||
|
||||
if repoID, err := beads.ComputeRepoID(); err == nil {
|
||||
bootstrapParams.RepoID = repoID
|
||||
} else if !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not compute repository ID: %v\n", err)
|
||||
}
|
||||
if cloneID, err := beads.GetCloneID(); err == nil {
|
||||
bootstrapParams.CloneID = cloneID
|
||||
} else if !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err)
|
||||
}
|
||||
if remoteURL := resolveProxiedInitRemoteURL(in); remoteURL != "" {
|
||||
bootstrapParams.RemoteName = "origin"
|
||||
bootstrapParams.RemoteURL = remoteURL
|
||||
}
|
||||
|
||||
if _, err := uw.BootstrapUseCase().BootstrapProject(ctx, bootstrapParams); err != nil {
|
||||
FatalError("bootstrap project: %v", err)
|
||||
}
|
||||
|
||||
if err := uw.Commit(ctx, "bd init"); err != nil {
|
||||
FatalError("commit init: %v", err)
|
||||
}
|
||||
|
||||
runInitProxiedServerTail(cmd, ctx, in, runInitTailContext{
|
||||
beadsDir: beadsDir,
|
||||
prefix: prefix,
|
||||
dbName: dbName,
|
||||
useLocalBeads: useLocalBeads,
|
||||
remoteURL: bootstrapParams.RemoteURL,
|
||||
fsUseCase: fsUseCase,
|
||||
})
|
||||
}
|
||||
|
||||
func resolveInitPrefix(flagPrefix string) string {
|
||||
prefix := flagPrefix
|
||||
if prefix == "" {
|
||||
prefix = config.GetString("issue-prefix")
|
||||
}
|
||||
if prefix == "" {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
FatalError("failed to get current directory: %v", err)
|
||||
}
|
||||
prefix = filepath.Base(cwd)
|
||||
}
|
||||
prefix = strings.TrimLeft(prefix, ".")
|
||||
prefix = strings.TrimRight(prefix, "-")
|
||||
prefix = strings.ReplaceAll(prefix, ".", "_")
|
||||
if len(prefix) > 0 && !((prefix[0] >= 'a' && prefix[0] <= 'z') || (prefix[0] >= 'A' && prefix[0] <= 'Z') || prefix[0] == '_') {
|
||||
prefix = "bd_" + prefix
|
||||
}
|
||||
return prefix
|
||||
}
|
||||
|
||||
func resolveBeadsDirForInit() (beadsDir string, hasExplicit bool) {
|
||||
if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" {
|
||||
return utils.CanonicalizePath(envBeadsDir), true
|
||||
}
|
||||
beadsDir = beads.GetWorktreeFallbackBeadsDir()
|
||||
if beadsDir == "" {
|
||||
beadsDir = beads.FollowRedirect(filepath.Join(".", ".beads"))
|
||||
}
|
||||
return beadsDir, false
|
||||
}
|
||||
|
||||
func resolveProxiedDatabaseName(beadsDir, prefix, dbFlag string) string {
|
||||
if dbFlag != "" {
|
||||
return dbFlag
|
||||
}
|
||||
if cfg, _ := configfile.Load(beadsDir); cfg != nil && cfg.DoltDatabase != "" {
|
||||
return cfg.DoltDatabase
|
||||
}
|
||||
if prefix != "" {
|
||||
return strings.ReplaceAll(prefix, "-", "_")
|
||||
}
|
||||
return configfile.DefaultDoltDatabase
|
||||
}
|
||||
|
||||
func resolveProjectID(beadsDir string) string {
|
||||
if cfg, _ := configfile.Load(beadsDir); cfg != nil && cfg.ProjectID != "" {
|
||||
return cfg.ProjectID
|
||||
}
|
||||
return configfile.GenerateProjectID()
|
||||
}
|
||||
|
||||
func resolveProxiedInitRemoteURL(in initProxiedServerInput) string {
|
||||
url, source := resolveInitConfiguredSyncRemote(in.initRemote, in.initRemoteChanged, resolveSyncRemote)
|
||||
if url != "" {
|
||||
return url
|
||||
}
|
||||
if source != initSyncRemoteNone {
|
||||
return ""
|
||||
}
|
||||
if !in.stealth && isGitRepo() && !isBareGitRepo() {
|
||||
if originURL, err := gitOriginGetURL(); err == nil && originURL != "" {
|
||||
return normalizeRemoteURL(originURL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type proxiedMetadataInputs struct {
|
||||
dbName string
|
||||
projectID string
|
||||
serverConfigPath string
|
||||
serverLogPath string
|
||||
serverRootPath string
|
||||
}
|
||||
|
||||
func composeProxiedServerMetadataJSON(in proxiedMetadataInputs) ([]byte, error) {
|
||||
cfg := configfile.DefaultConfig()
|
||||
cfg.Backend = configfile.BackendDolt
|
||||
cfg.Database = "dolt"
|
||||
cfg.DoltDatabase = in.dbName
|
||||
cfg.DoltMode = configfile.DoltModeProxiedServer
|
||||
cfg.ProjectID = in.projectID
|
||||
|
||||
cfg.DoltProxiedServerConfig = in.serverConfigPath
|
||||
cfg.DoltProxiedServerLog = in.serverLogPath
|
||||
cfg.DoltProxiedServerRootPath = in.serverRootPath
|
||||
|
||||
if filepath.IsAbs(cfg.DoltDataDir) {
|
||||
cfg.DoltDataDir = ""
|
||||
}
|
||||
if filepath.IsAbs(cfg.DoltProxiedServerConfig) {
|
||||
cfg.DoltProxiedServerConfig = ""
|
||||
}
|
||||
if filepath.IsAbs(cfg.DoltProxiedServerLog) {
|
||||
cfg.DoltProxiedServerLog = ""
|
||||
}
|
||||
if filepath.IsAbs(cfg.DoltProxiedServerRootPath) {
|
||||
cfg.DoltProxiedServerRootPath = ""
|
||||
}
|
||||
|
||||
return json.MarshalIndent(cfg, "", " ")
|
||||
}
|
||||
|
||||
type runInitTailContext struct {
|
||||
beadsDir string
|
||||
prefix string
|
||||
dbName string
|
||||
useLocalBeads bool
|
||||
remoteURL string
|
||||
fsUseCase domain.BeadsDirFSUseCase
|
||||
}
|
||||
|
||||
func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) {
|
||||
if isGitRepo() {
|
||||
role := in.roleFlag
|
||||
if role == "" {
|
||||
role = "maintainer"
|
||||
}
|
||||
if _, hasRole := getBeadsRole(); !hasRole {
|
||||
if err := setBeadsRole(role); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err)
|
||||
}
|
||||
} else if in.roleFlag != "" {
|
||||
if err := setBeadsRole(role); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setupExclude, _ := cmd.Flags().GetBool("setup-exclude")
|
||||
if setupExclude {
|
||||
if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
} else if !in.stealth && isGitRepo() {
|
||||
if isFork, upstreamURL := detectForkSetup(); isFork {
|
||||
if in.nonInteractive {
|
||||
if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
} else {
|
||||
shouldExclude, err := promptForkExclude(upstreamURL, in.quiet)
|
||||
if err != nil && isCanceled(err) {
|
||||
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
||||
exitCanceled()
|
||||
}
|
||||
if shouldExclude {
|
||||
if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !in.skipHooks && (!hooksInstalled() || hooksNeedUpdate()) {
|
||||
if hooksInstalled() && !in.quiet {
|
||||
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
||||
}
|
||||
isJJ := git.IsJujutsuRepo()
|
||||
isColocated := git.IsColocatedJJGit()
|
||||
switch {
|
||||
case isJJ && !isColocated:
|
||||
if !in.quiet {
|
||||
printJJAliasInstructions()
|
||||
}
|
||||
case isColocated:
|
||||
if err := t.fsUseCase.InstallJJHooks(ctx); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
||||
}
|
||||
default:
|
||||
if isGitRepo() {
|
||||
hooksParams := domain.HooksInstallParams{
|
||||
HookNames: managedHookNames,
|
||||
BeadsHooks: true,
|
||||
}
|
||||
if err := t.fsUseCase.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !in.stealth && !in.skipAgents {
|
||||
agentsTemplate, _ := cmd.Flags().GetString("agents-template")
|
||||
agentsProfileStr, _ := cmd.Flags().GetString("agents-profile")
|
||||
agentsFile, _ := cmd.Flags().GetString("agents-file")
|
||||
if agentsFile != "" {
|
||||
if err := config.ValidateAgentsFile(agentsFile); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid --agents-file: %v\n", err)
|
||||
return
|
||||
}
|
||||
if err := t.fsUseCase.SetYAMLConfig(ctx, "agents.file", agentsFile); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to persist agents.file to config: %v\n", err)
|
||||
}
|
||||
}
|
||||
resolvedAgentsFile := agentsFile
|
||||
if resolvedAgentsFile == "" {
|
||||
resolvedAgentsFile = config.SafeAgentsFile()
|
||||
}
|
||||
if isBareGitRepo() {
|
||||
if !in.quiet {
|
||||
fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile)
|
||||
}
|
||||
} else {
|
||||
_ = t.fsUseCase.AddAgentsInstructions(ctx, domain.AgentsFileParams{
|
||||
File: resolvedAgentsFile,
|
||||
Verbose: !in.quiet,
|
||||
TemplatePath: agentsTemplate,
|
||||
Profile: agentsProfileStr,
|
||||
HasRemote: t.remoteURL != "",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if !in.stealth && !in.skipAgents && !isBareGitRepo() {
|
||||
if err := t.fsUseCase.InstallClaudeProject(ctx, in.stealth); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
if !in.stealth && isGitRepo() && t.useLocalBeads {
|
||||
gitAddCmd := exec.Command("git", "add", ".beads/")
|
||||
if _, addErr := gitAddCmd.CombinedOutput(); addErr == nil {
|
||||
agentsFileToStage := config.SafeAgentsFile()
|
||||
if _, statErr := os.Stat(agentsFileToStage); statErr == nil {
|
||||
_ = exec.Command("git", "add", agentsFileToStage).Run()
|
||||
}
|
||||
if _, statErr := os.Stat(filepath.Join(".claude", "settings.json")); statErr == nil {
|
||||
_ = exec.Command("git", "add", filepath.Join(".claude", "settings.json")).Run()
|
||||
}
|
||||
if _, statErr := os.Stat("CLAUDE.md"); statErr == nil {
|
||||
_ = exec.Command("git", "add", "CLAUDE.md").Run()
|
||||
}
|
||||
if _, statErr := os.Stat(".gitignore"); statErr == nil {
|
||||
_ = exec.Command("git", "add", ".gitignore").Run()
|
||||
}
|
||||
commitCmd := exec.Command("git", "commit", "--no-verify", "-m", "bd init: initialize beads issue tracking")
|
||||
if commitOut, commitErr := commitCmd.CombinedOutput(); commitErr != nil {
|
||||
if !in.quiet && !strings.Contains(string(commitOut), "nothing to commit") {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", commitErr)
|
||||
}
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if isGitRepo() && !in.quiet {
|
||||
if gitHasAnyRemotes() && !gitHasUpstream() {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠"))
|
||||
fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n")
|
||||
fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("git remote add upstream <repo-url>"))
|
||||
}
|
||||
if !in.stealth && !in.initRemoteChanged && t.remoteURL == "" {
|
||||
printInitNoDoltRemoteWarning()
|
||||
}
|
||||
}
|
||||
|
||||
if in.quiet {
|
||||
return
|
||||
}
|
||||
fmt.Printf("\n%s bd initialized successfully!\n\n", ui.RenderPass("✓"))
|
||||
fmt.Printf(" Backend: %s\n", ui.RenderAccent(configfile.BackendDolt))
|
||||
fmt.Printf(" Mode: %s\n", ui.RenderAccent("proxied-server"))
|
||||
fmt.Printf(" Database: %s\n", ui.RenderAccent(t.dbName))
|
||||
fmt.Printf(" Issue prefix: %s\n", ui.RenderAccent(t.prefix))
|
||||
fmt.Printf(" Issues will be named: %s\n\n", ui.RenderAccent(t.prefix+"-<hash> (e.g., "+t.prefix+"-a3f2dd)"))
|
||||
fmt.Printf("Run %s to get started.\n\n", ui.RenderAccent("bd quickstart"))
|
||||
}
|
||||
|
|
@ -16,18 +16,29 @@ func createConfigYaml(beadsDir string, noDbMode bool, prefix string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
body := renderInitConfigYAML(prefix, noDbMode)
|
||||
if err := os.WriteFile(configYamlPath, body, 0600); err != nil {
|
||||
return fmt.Errorf("failed to write config.yaml: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// renderInitConfigYAML returns the canonical config.yaml body produced by
|
||||
// bd init. When noDbMode is true, the prefix is baked into the file (since
|
||||
// there's no database to store it).
|
||||
func renderInitConfigYAML(prefix string, noDbMode bool) []byte {
|
||||
noDbLine := "# no-db: false"
|
||||
if noDbMode {
|
||||
noDbLine = "no-db: true # JSONL-only mode, no database"
|
||||
}
|
||||
|
||||
// In no-db mode, we need to persist the prefix in config.yaml
|
||||
prefixLine := "# issue-prefix: \"\""
|
||||
if noDbMode && prefix != "" {
|
||||
prefixLine = fmt.Sprintf("issue-prefix: %q", prefix)
|
||||
}
|
||||
|
||||
configYamlTemplate := fmt.Sprintf(`# Beads Configuration File
|
||||
body := fmt.Sprintf(`# Beads Configuration File
|
||||
# This file configures default behavior for all bd commands in this repository
|
||||
# All settings can also be set via environment variables (BD_* prefix)
|
||||
# or overridden with command-line flags
|
||||
|
|
@ -83,12 +94,7 @@ func createConfigYaml(beadsDir string, noDbMode bool, prefix string) error {
|
|||
# - linear.api_key → use LINEAR_API_KEY env var instead
|
||||
# - github.token → use GITHUB_TOKEN env var instead
|
||||
`, prefixLine, noDbLine)
|
||||
|
||||
if err := os.WriteFile(configYamlPath, []byte(configYamlTemplate), 0600); err != nil {
|
||||
return fmt.Errorf("failed to write config.yaml: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return []byte(body)
|
||||
}
|
||||
|
||||
// createReadme creates the README.md file in the .beads directory
|
||||
|
|
|
|||
132
cmd/bd/main.go
132
cmd/bd/main.go
|
|
@ -28,6 +28,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/molecules"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/dolt"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/telemetry"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
|
|
@ -35,11 +36,12 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
changeDir string
|
||||
dbPath string
|
||||
actor string
|
||||
store storage.DoltStorage
|
||||
jsonOutput bool
|
||||
changeDir string
|
||||
dbPath string
|
||||
actor string
|
||||
store storage.DoltStorage
|
||||
uowProvider uow.UnitOfWorkProvider
|
||||
jsonOutput bool
|
||||
|
||||
// Signal-aware context for graceful cancellation
|
||||
rootCtx context.Context
|
||||
|
|
@ -67,9 +69,9 @@ var changeDirEnvSnapshot map[string]envSnapshotValue
|
|||
|
||||
var (
|
||||
sandboxMode bool
|
||||
globalFlag bool // Use the global shared-server database (beads_global)
|
||||
serverMode bool // True when using external dolt sql-server (dolt_mode=server)
|
||||
proxiedServerMode bool // True when using per-workspace proxied dolt sql-server (dolt_mode=proxied-server)
|
||||
globalFlag bool // Use the global shared-server database (beads_global)
|
||||
serverMode bool // True when using external dolt sql-server (dolt_mode=server)
|
||||
proxiedServerMode bool
|
||||
readonlyMode bool // Read-only mode: block write operations (for worker sandboxes)
|
||||
storeIsReadOnly bool // Track if store was opened read-only (for staleness checks)
|
||||
lockTimeout = 30 * time.Second // Dolt open timeout (fixed default)
|
||||
|
|
@ -988,6 +990,17 @@ var rootCmd = &cobra.Command{
|
|||
// other helper paths stay in lockstep with the main command path.
|
||||
dolt.ApplyCLIAutoStart(beadsDir, doltCfg)
|
||||
|
||||
if proxiedServerMode {
|
||||
p, err := newProxiedServerUOWProvider(rootCtx, beadsDir)
|
||||
if err != nil {
|
||||
FatalError("failed to open uow provider: %v", err)
|
||||
}
|
||||
uowProvider = p
|
||||
|
||||
syncCommandContext()
|
||||
return
|
||||
}
|
||||
|
||||
// Default auto-commit based on mode when the user hasn't set a value:
|
||||
// - Server mode: OFF — the server handles commits via its own transaction
|
||||
// lifecycle; firing DOLT_COMMIT after every write under concurrent load
|
||||
|
|
@ -1087,65 +1100,72 @@ var rootCmd = &cobra.Command{
|
|||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
defer restoreChangeDirSelection()
|
||||
|
||||
// Dolt auto-commit: after a successful write command (and after final flush),
|
||||
// create a Dolt commit so changes don't remain only in the working set.
|
||||
if commandDidWrite.Load() && !commandDidExplicitDoltCommit {
|
||||
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil {
|
||||
FatalError("dolt auto-commit failed: %v", err)
|
||||
if proxiedServerMode {
|
||||
if uowProvider != nil {
|
||||
_ = uowProvider.Close(rootCtx)
|
||||
uowProvider = nil
|
||||
}
|
||||
} else {
|
||||
// Dolt auto-commit: after a successful write command (and after final flush),
|
||||
// create a Dolt commit so changes don't remain only in the working set.
|
||||
if commandDidWrite.Load() && !commandDidExplicitDoltCommit {
|
||||
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil {
|
||||
FatalError("dolt auto-commit failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the
|
||||
// tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands.
|
||||
if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 {
|
||||
// Only applies when dolt auto-commit is enabled and backend is versioned (Dolt).
|
||||
if mode, err := getDoltAutoCommitMode(); err != nil {
|
||||
FatalError("dolt tip auto-commit failed: %v", err)
|
||||
} else if mode == doltAutoCommitOn {
|
||||
// Apply tip metadata writes now (deferred in recordTipShown for Dolt).
|
||||
for tipID := range commandTipIDsShown {
|
||||
key := fmt.Sprintf("tip_%s_last_shown", tipID)
|
||||
value := time.Now().Format(time.RFC3339)
|
||||
if err := store.SetLocalMetadata(rootCtx, key, value); err != nil {
|
||||
// Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the
|
||||
// tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands.
|
||||
if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 {
|
||||
// Only applies when dolt auto-commit is enabled and backend is versioned (Dolt).
|
||||
if mode, err := getDoltAutoCommitMode(); err != nil {
|
||||
FatalError("dolt tip auto-commit failed: %v", err)
|
||||
} else if mode == doltAutoCommitOn {
|
||||
// Apply tip metadata writes now (deferred in recordTipShown for Dolt).
|
||||
for tipID := range commandTipIDsShown {
|
||||
key := fmt.Sprintf("tip_%s_last_shown", tipID)
|
||||
value := time.Now().Format(time.RFC3339)
|
||||
if err := store.SetLocalMetadata(rootCtx, key, value); err != nil {
|
||||
FatalError("dolt tip auto-commit failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(commandTipIDsShown))
|
||||
for tipID := range commandTipIDsShown {
|
||||
ids = append(ids, tipID)
|
||||
}
|
||||
msg := formatDoltAutoCommitMessage("tip", getActor(), ids)
|
||||
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil {
|
||||
FatalError("dolt tip auto-commit failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(commandTipIDsShown))
|
||||
for tipID := range commandTipIDsShown {
|
||||
ids = append(ids, tipID)
|
||||
}
|
||||
msg := formatDoltAutoCommitMessage("tip", getActor(), ids)
|
||||
if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil {
|
||||
FatalError("dolt tip auto-commit failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-backup: export JSONL to .beads/backup/ if enabled and due
|
||||
maybeAutoBackup(rootCtx)
|
||||
// Auto-backup: export JSONL to .beads/backup/ if enabled and due
|
||||
maybeAutoBackup(rootCtx)
|
||||
|
||||
// Auto-export: write git-tracked JSONL for portability if enabled and due.
|
||||
// Read-only commands must not perform post-run maintenance writes or emit
|
||||
// sync guidance after machine-readable output.
|
||||
if shouldRunPostCommandAutoExport(cmd) {
|
||||
maybeAutoExport(rootCtx)
|
||||
}
|
||||
// Auto-export: write git-tracked JSONL for portability if enabled and due.
|
||||
// Read-only commands must not perform post-run maintenance writes or emit
|
||||
// sync guidance after machine-readable output.
|
||||
if shouldRunPostCommandAutoExport(cmd) {
|
||||
maybeAutoExport(rootCtx)
|
||||
}
|
||||
|
||||
// Auto-push: push to Dolt remote if enabled and due.
|
||||
// Skip for read-only commands to avoid unnecessary network operations
|
||||
// and metadata writes on commands like bd list/show/ready (GH#2191).
|
||||
if !isReadOnlyCommand(cmd.Name()) {
|
||||
maybeAutoPush(rootCtx)
|
||||
}
|
||||
// Auto-push: push to Dolt remote if enabled and due.
|
||||
// Skip for read-only commands to avoid unnecessary network operations
|
||||
// and metadata writes on commands like bd list/show/ready (GH#2191).
|
||||
if !isReadOnlyCommand(cmd.Name()) {
|
||||
maybeAutoPush(rootCtx)
|
||||
}
|
||||
|
||||
// Signal that store is closing (prevents background flush from accessing closed store)
|
||||
storeMutex.Lock()
|
||||
storeActive = false
|
||||
storeMutex.Unlock()
|
||||
// Signal that store is closing (prevents background flush from accessing closed store)
|
||||
storeMutex.Lock()
|
||||
storeActive = false
|
||||
storeMutex.Unlock()
|
||||
|
||||
if store != nil {
|
||||
_ = store.Close() // Best effort cleanup
|
||||
if store != nil {
|
||||
_ = store.Close() // Best effort cleanup
|
||||
}
|
||||
}
|
||||
|
||||
// End the command span and flush OTel data before process exit.
|
||||
|
|
|
|||
57
cmd/bd/uow_factory.go
Normal file
57
cmd/bd/uow_factory.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/storage/dbproxy/proxy"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
)
|
||||
|
||||
func newProxiedServerUOWProvider(ctx context.Context, beadsDir string) (uow.UnitOfWorkProvider, error) {
|
||||
if beadsDir == "" {
|
||||
return nil, fmt.Errorf("newProxiedServerUOWProvider: beadsDir must be set")
|
||||
}
|
||||
|
||||
doltBin, err := exec.LookPath("dolt")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("newProxiedServerUOWProvider: dolt is not installed (not found in PATH); install from https://docs.dolthub.com/introduction/installation: %w", err)
|
||||
}
|
||||
|
||||
persisted, _ := configfile.Load(beadsDir)
|
||||
database := configfile.DefaultDoltDatabase
|
||||
if persisted != nil {
|
||||
database = persisted.GetDoltDatabase()
|
||||
}
|
||||
|
||||
rootPath := resolveProxiedServerRootPath(beadsDir, persisted)
|
||||
if err := validateProxiedServerRootPath(rootPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
configPath, err := ensureProxiedServerConfig(beadsDir, persisted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logPath, isCustomLog := resolveProxiedServerLogPath(beadsDir, persisted)
|
||||
if isCustomLog {
|
||||
if err := validateProxiedServerLogPath(logPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return uow.NewDoltServerUOWProvider(
|
||||
ctx,
|
||||
rootPath,
|
||||
database,
|
||||
logPath,
|
||||
configPath,
|
||||
proxy.BackendLocalServer,
|
||||
"root",
|
||||
"", // proxy is loopback-only, no auth
|
||||
doltBin,
|
||||
)
|
||||
}
|
||||
207
internal/storage/domain/beads.go
Normal file
207
internal/storage/domain/beads.go
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type BeadsDirFSRepository interface {
|
||||
CreateBeadsDir(ctx context.Context, beadsDir string) error
|
||||
BeadsDirExists(ctx context.Context, beadsDir string) (bool, error)
|
||||
WriteBeadsGitignore(ctx context.Context, beadsDir string) error
|
||||
BeadsGitignoreExists(ctx context.Context, beadsDir string) (bool, error)
|
||||
WriteProjectGitignore(ctx context.Context, repoRoot string) error
|
||||
ProjectGitignoreExists(ctx context.Context, repoRoot string) (bool, error)
|
||||
WriteInteractionsLog(ctx context.Context, beadsDir string) error
|
||||
WriteReadme(ctx context.Context, beadsDir string) error
|
||||
WriteMetadataJSON(ctx context.Context, beadsDir string, content []byte) error
|
||||
ReadMetadataJSON(ctx context.Context, beadsDir string) ([]byte, error)
|
||||
WriteConfigYAML(ctx context.Context, beadsDir string, content []byte) error
|
||||
ReadConfigYAML(ctx context.Context, beadsDir string) ([]byte, error)
|
||||
}
|
||||
|
||||
type BeadsDirFSUseCase interface {
|
||||
ResolveBeadsDir(ctx context.Context) BeadsDirResolution
|
||||
InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error)
|
||||
SetupForkExclude(ctx context.Context, verbose bool) error
|
||||
SetupStealthMode(ctx context.Context, verbose bool) error
|
||||
InstallGitHooks(ctx context.Context, params HooksInstallParams) error
|
||||
InstallJJHooks(ctx context.Context) error
|
||||
AddAgentsInstructions(ctx context.Context, params AgentsFileParams) error
|
||||
InstallClaudeProject(ctx context.Context, stealth bool) error
|
||||
SetYAMLConfig(ctx context.Context, key, value string) error
|
||||
}
|
||||
|
||||
type BeadsDirResolution struct {
|
||||
BeadsDir string
|
||||
HasExplicit bool
|
||||
}
|
||||
|
||||
type InitializeBeadsDirParams struct {
|
||||
BeadsDir string
|
||||
RepoRoot string
|
||||
MetadataJSONBody []byte
|
||||
ConfigYAMLBody []byte
|
||||
|
||||
// SetNoCOW, when true, applies FS_NOCOW_FL to BeadsDir after creation.
|
||||
// Best-effort: failures surface in InitializeBeadsDirResult.NoCOWErr,
|
||||
// not the returned error.
|
||||
SetNoCOW bool
|
||||
|
||||
// LocalVersion, when non-empty, writes BeadsDir/.local_version with
|
||||
// the given value. Best-effort: failures surface in
|
||||
// InitializeBeadsDirResult.LocalVersionErr, not the returned error.
|
||||
LocalVersion string
|
||||
}
|
||||
|
||||
type InitializeBeadsDirResult struct {
|
||||
NoCOWErr error
|
||||
LocalVersionErr error
|
||||
}
|
||||
|
||||
type HooksInstallParams struct {
|
||||
HookNames []string
|
||||
Force bool
|
||||
Shared bool
|
||||
Chain bool
|
||||
BeadsHooks bool
|
||||
}
|
||||
|
||||
type AgentsFileParams struct {
|
||||
File string
|
||||
Verbose bool
|
||||
TemplatePath string
|
||||
Profile string
|
||||
HasRemote bool
|
||||
}
|
||||
|
||||
// BeadsDirFSAdapters wires the use case's non-trivial side effects to the
|
||||
// CLI-side helper implementations. Each adapter is optional at the type
|
||||
// level; methods that depend on a nil adapter return a configuration error.
|
||||
type BeadsDirFSAdapters struct {
|
||||
ResolveBeadsDir func() BeadsDirResolution
|
||||
ApplyNoCOW func(path string) error
|
||||
WriteLocalVersion func(path, version string) error
|
||||
SetupForkExclude func(verbose bool) error
|
||||
SetupStealthMode func(verbose bool) error
|
||||
InstallGitHooks func(params HooksInstallParams) error
|
||||
InstallJJHooks func() error
|
||||
AddAgentsInstructions func(params AgentsFileParams)
|
||||
InstallClaudeProject func(stealth bool) error
|
||||
SetYAMLConfig func(key, value string) error
|
||||
}
|
||||
|
||||
func NewBeadsDirFSUseCase(fsRepo BeadsDirFSRepository, adapters BeadsDirFSAdapters) BeadsDirFSUseCase {
|
||||
return &beadsDirFSUseCaseImpl{fsRepo: fsRepo, adapters: adapters}
|
||||
}
|
||||
|
||||
type beadsDirFSUseCaseImpl struct {
|
||||
fsRepo BeadsDirFSRepository
|
||||
adapters BeadsDirFSAdapters
|
||||
}
|
||||
|
||||
var _ BeadsDirFSUseCase = (*beadsDirFSUseCaseImpl)(nil)
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) ResolveBeadsDir(ctx context.Context) BeadsDirResolution {
|
||||
if u.adapters.ResolveBeadsDir == nil {
|
||||
return BeadsDirResolution{}
|
||||
}
|
||||
return u.adapters.ResolveBeadsDir()
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error) {
|
||||
if params.BeadsDir == "" {
|
||||
return InitializeBeadsDirResult{}, fmt.Errorf("InitializeBeadsDir: BeadsDir must not be empty")
|
||||
}
|
||||
|
||||
if err := u.fsRepo.CreateBeadsDir(ctx, params.BeadsDir); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if err := u.fsRepo.WriteBeadsGitignore(ctx, params.BeadsDir); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if len(params.MetadataJSONBody) > 0 {
|
||||
if err := u.fsRepo.WriteMetadataJSON(ctx, params.BeadsDir, params.MetadataJSONBody); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
}
|
||||
if len(params.ConfigYAMLBody) > 0 {
|
||||
if err := u.fsRepo.WriteConfigYAML(ctx, params.BeadsDir, params.ConfigYAMLBody); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
}
|
||||
if err := u.fsRepo.WriteInteractionsLog(ctx, params.BeadsDir); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if err := u.fsRepo.WriteReadme(ctx, params.BeadsDir); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if params.RepoRoot != "" {
|
||||
if err := u.fsRepo.WriteProjectGitignore(ctx, params.RepoRoot); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
}
|
||||
|
||||
var result InitializeBeadsDirResult
|
||||
if params.SetNoCOW && u.adapters.ApplyNoCOW != nil {
|
||||
result.NoCOWErr = u.adapters.ApplyNoCOW(params.BeadsDir)
|
||||
}
|
||||
if params.LocalVersion != "" && u.adapters.WriteLocalVersion != nil {
|
||||
result.LocalVersionErr = u.adapters.WriteLocalVersion(
|
||||
filepath.Join(params.BeadsDir, ".local_version"),
|
||||
params.LocalVersion,
|
||||
)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) SetupForkExclude(ctx context.Context, verbose bool) error {
|
||||
if u.adapters.SetupForkExclude == nil {
|
||||
return fmt.Errorf("SetupForkExclude: adapter not configured")
|
||||
}
|
||||
return u.adapters.SetupForkExclude(verbose)
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) SetupStealthMode(ctx context.Context, verbose bool) error {
|
||||
if u.adapters.SetupStealthMode == nil {
|
||||
return fmt.Errorf("SetupStealthMode: adapter not configured")
|
||||
}
|
||||
return u.adapters.SetupStealthMode(verbose)
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) InstallGitHooks(ctx context.Context, params HooksInstallParams) error {
|
||||
if u.adapters.InstallGitHooks == nil {
|
||||
return fmt.Errorf("InstallGitHooks: adapter not configured")
|
||||
}
|
||||
return u.adapters.InstallGitHooks(params)
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) InstallJJHooks(ctx context.Context) error {
|
||||
if u.adapters.InstallJJHooks == nil {
|
||||
return fmt.Errorf("InstallJJHooks: adapter not configured")
|
||||
}
|
||||
return u.adapters.InstallJJHooks()
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) AddAgentsInstructions(ctx context.Context, params AgentsFileParams) error {
|
||||
if u.adapters.AddAgentsInstructions == nil {
|
||||
return fmt.Errorf("AddAgentsInstructions: adapter not configured")
|
||||
}
|
||||
u.adapters.AddAgentsInstructions(params)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) InstallClaudeProject(ctx context.Context, stealth bool) error {
|
||||
if u.adapters.InstallClaudeProject == nil {
|
||||
return fmt.Errorf("InstallClaudeProject: adapter not configured")
|
||||
}
|
||||
return u.adapters.InstallClaudeProject(stealth)
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) SetYAMLConfig(ctx context.Context, key, value string) error {
|
||||
if u.adapters.SetYAMLConfig == nil {
|
||||
return fmt.Errorf("SetYAMLConfig: adapter not configured")
|
||||
}
|
||||
return u.adapters.SetYAMLConfig(key, value)
|
||||
}
|
||||
|
|
@ -1,11 +1,107 @@
|
|||
package domain
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BootstrapUseCase interface {
|
||||
BootstrapProject(ctx context.Context, params BootstrapProjectParams) (BootstrapProjectResult, error)
|
||||
}
|
||||
|
||||
type BootstrapProjectParams struct{}
|
||||
type BootstrapProjectParams struct {
|
||||
Prefix string
|
||||
ProjectID string
|
||||
BdVersion string
|
||||
LastImportTime time.Time
|
||||
|
||||
type BootstrapProjectResult struct{}
|
||||
RepoID string
|
||||
CloneID string
|
||||
|
||||
RemoteName string
|
||||
RemoteURL string
|
||||
}
|
||||
|
||||
type BootstrapProjectResult struct {
|
||||
RemoteConfigured bool
|
||||
}
|
||||
|
||||
func NewBootstrapUseCase(cfgRepo ConfigSQLRepository, remoteUseCase DoltRemoteUseCase) BootstrapUseCase {
|
||||
return &bootstrapUseCaseImpl{
|
||||
cfgRepo: cfgRepo,
|
||||
remoteUseCase: remoteUseCase,
|
||||
}
|
||||
}
|
||||
|
||||
type bootstrapUseCaseImpl struct {
|
||||
cfgRepo ConfigSQLRepository
|
||||
remoteUseCase DoltRemoteUseCase
|
||||
}
|
||||
|
||||
var _ BootstrapUseCase = (*bootstrapUseCaseImpl)(nil)
|
||||
|
||||
func (u *bootstrapUseCaseImpl) BootstrapProject(ctx context.Context, params BootstrapProjectParams) (BootstrapProjectResult, error) {
|
||||
if params.Prefix == "" {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: Prefix must not be empty")
|
||||
}
|
||||
if params.ProjectID == "" {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: ProjectID must not be empty")
|
||||
}
|
||||
if params.BdVersion == "" {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: BdVersion must not be empty")
|
||||
}
|
||||
if params.LastImportTime.IsZero() {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: LastImportTime must not be zero")
|
||||
}
|
||||
|
||||
if err := u.cfgRepo.SetConfig(ctx, "issue_prefix", params.Prefix); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set issue_prefix: %w", err)
|
||||
}
|
||||
if err := u.cfgRepo.SetMetadata(ctx, "_project_id", params.ProjectID); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set _project_id: %w", err)
|
||||
}
|
||||
if params.RepoID != "" {
|
||||
if err := u.cfgRepo.SetMetadata(ctx, "repo_id", params.RepoID); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set repo_id: %w", err)
|
||||
}
|
||||
}
|
||||
if params.CloneID != "" {
|
||||
if err := u.cfgRepo.SetMetadata(ctx, "clone_id", params.CloneID); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set clone_id: %w", err)
|
||||
}
|
||||
}
|
||||
if err := u.cfgRepo.SetMetadata(ctx, "last_import_time", params.LastImportTime.UTC().Format(time.RFC3339)); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set last_import_time: %w", err)
|
||||
}
|
||||
if err := u.cfgRepo.SetLocalMetadata(ctx, "bd_version", params.BdVersion); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set bd_version: %w", err)
|
||||
}
|
||||
|
||||
var result BootstrapProjectResult
|
||||
if params.RemoteURL != "" {
|
||||
name := params.RemoteName
|
||||
if name == "" {
|
||||
name = "origin"
|
||||
}
|
||||
remotes, err := u.remoteUseCase.ListRemotes(ctx)
|
||||
if err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: list remotes: %w", err)
|
||||
}
|
||||
exists := false
|
||||
for _, r := range remotes {
|
||||
if r.Name == name {
|
||||
exists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !exists {
|
||||
if err := u.remoteUseCase.CreateRemote(ctx, name, params.RemoteURL); err != nil {
|
||||
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: create remote %s: %w", name, err)
|
||||
}
|
||||
result.RemoteConfigured = true
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
package domain
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ConfigSQLRepository interface {
|
||||
GetMetadata(ctx context.Context, key string) (string, error)
|
||||
|
|
@ -12,8 +15,6 @@ type ConfigSQLRepository interface {
|
|||
}
|
||||
|
||||
type ConfigUseCase interface {
|
||||
ConfigureContributorMode(ctx context.Context, params ContributorModeParams) error
|
||||
ConfigureTeamMode(ctx context.Context, params TeamModeParams) error
|
||||
VerifyInit(ctx context.Context) (VerifyResult, error)
|
||||
}
|
||||
|
||||
|
|
@ -23,12 +24,47 @@ type BatchCreateOptions struct{}
|
|||
|
||||
type Statistics struct{}
|
||||
|
||||
type ContributorModeParams struct{}
|
||||
|
||||
type TeamModeParams struct{}
|
||||
|
||||
type GlobalDatabaseParams struct{}
|
||||
|
||||
type ImportResult struct{}
|
||||
|
||||
type VerifyResult struct{}
|
||||
type VerifyResult struct {
|
||||
ProjectID string
|
||||
IssuePrefix string
|
||||
Missing []string
|
||||
}
|
||||
|
||||
func NewConfigUseCase(cfgRepo ConfigSQLRepository) ConfigUseCase {
|
||||
return &configUseCaseImpl{cfgRepo: cfgRepo}
|
||||
}
|
||||
|
||||
type configUseCaseImpl struct {
|
||||
cfgRepo ConfigSQLRepository
|
||||
}
|
||||
|
||||
var _ ConfigUseCase = (*configUseCaseImpl)(nil)
|
||||
|
||||
func (u *configUseCaseImpl) VerifyInit(ctx context.Context) (VerifyResult, error) {
|
||||
projectID, err := u.cfgRepo.GetMetadata(ctx, "_project_id")
|
||||
if err != nil {
|
||||
return VerifyResult{}, fmt.Errorf("VerifyInit: read _project_id: %w", err)
|
||||
}
|
||||
issuePrefix, err := u.cfgRepo.GetConfig(ctx, "issue_prefix")
|
||||
if err != nil {
|
||||
return VerifyResult{}, fmt.Errorf("VerifyInit: read issue_prefix: %w", err)
|
||||
}
|
||||
|
||||
var missing []string
|
||||
if projectID == "" {
|
||||
missing = append(missing, "metadata._project_id")
|
||||
}
|
||||
if issuePrefix == "" {
|
||||
missing = append(missing, "config.issue_prefix")
|
||||
}
|
||||
|
||||
return VerifyResult{
|
||||
ProjectID: projectID,
|
||||
IssuePrefix: issuePrefix,
|
||||
Missing: missing,
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
73
internal/storage/domain/db/config.go
Normal file
73
internal/storage/domain/db/config.go
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
func NewConfigSQLRepository(runner Runner) domain.ConfigSQLRepository {
|
||||
return &configSQLRepositoryImpl{runner: runner}
|
||||
}
|
||||
|
||||
type configSQLRepositoryImpl struct {
|
||||
runner Runner
|
||||
}
|
||||
|
||||
var _ domain.ConfigSQLRepository = (*configSQLRepositoryImpl)(nil)
|
||||
|
||||
func (r *configSQLRepositoryImpl) GetMetadata(ctx context.Context, key string) (string, error) {
|
||||
var value string
|
||||
err := r.runner.QueryRowContext(ctx, "SELECT value FROM metadata WHERE `key` = ?", key).Scan(&value)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("db: GetMetadata %s: %w", key, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *configSQLRepositoryImpl) SetMetadata(ctx context.Context, key, value string) error {
|
||||
if _, err := r.runner.ExecContext(ctx, "REPLACE INTO metadata (`key`, value) VALUES (?, ?)", key, value); err != nil {
|
||||
return fmt.Errorf("db: SetMetadata %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *configSQLRepositoryImpl) SetLocalMetadata(ctx context.Context, key, value string) error {
|
||||
if _, err := r.runner.ExecContext(ctx, "REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", key, value); err != nil {
|
||||
return fmt.Errorf("db: SetLocalMetadata %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *configSQLRepositoryImpl) GetConfig(ctx context.Context, key string) (string, error) {
|
||||
var value string
|
||||
err := r.runner.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", key).Scan(&value)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("db: GetConfig %s: %w", key, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *configSQLRepositoryImpl) SetConfig(ctx context.Context, key, value string) error {
|
||||
if key == "issue_prefix" {
|
||||
value = strings.TrimSuffix(value, "-")
|
||||
}
|
||||
if _, err := r.runner.ExecContext(ctx, "REPLACE INTO config (`key`, value) VALUES (?, ?)", key, value); err != nil {
|
||||
return fmt.Errorf("db: SetConfig %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *configSQLRepositoryImpl) GetStatistics(ctx context.Context) (domain.Statistics, error) {
|
||||
return domain.Statistics{}, nil
|
||||
}
|
||||
105
internal/storage/domain/db/config_test.go
Normal file
105
internal/storage/domain/db/config_test.go
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
func (s *testSuite) TestConfigSQLRepository() {
|
||||
s.Run("GetMetadata", func() {
|
||||
s.Run("MissingKeyReturnsEmpty", s.configGetMetadataMissingKey)
|
||||
s.Run("RoundTrip", s.configGetMetadataRoundTrip)
|
||||
})
|
||||
s.Run("SetMetadata", func() {
|
||||
s.Run("Overwrite", s.configSetMetadataOverwrite)
|
||||
})
|
||||
s.Run("SetLocalMetadata", func() {
|
||||
s.Run("WritesToLocalMetadataTable", s.configSetLocalMetadataWrites)
|
||||
})
|
||||
s.Run("GetConfig", func() {
|
||||
s.Run("MissingKeyReturnsEmpty", s.configGetConfigMissingKey)
|
||||
s.Run("RoundTrip", s.configGetConfigRoundTrip)
|
||||
})
|
||||
s.Run("SetConfig", func() {
|
||||
s.Run("Overwrite", s.configSetConfigOverwrite)
|
||||
s.Run("IssuePrefixTrimsTrailingHyphen", s.configSetConfigIssuePrefixTrim)
|
||||
s.Run("IssuePrefixWithoutHyphenUnchanged", s.configSetConfigIssuePrefixUnchanged)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *testSuite) configRepo() domain.ConfigSQLRepository {
|
||||
return NewConfigSQLRepository(s.Runner())
|
||||
}
|
||||
|
||||
func (s *testSuite) configGetMetadataMissingKey() {
|
||||
v, err := s.configRepo().GetMetadata(s.Ctx(), "no_such_key")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configGetMetadataRoundTrip() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetMetadata(s.Ctx(), "_project_id", "abc-123"))
|
||||
v, err := r.GetMetadata(s.Ctx(), "_project_id")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("abc-123", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configSetMetadataOverwrite() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetMetadata(s.Ctx(), "k", "v1"))
|
||||
s.Require().NoError(r.SetMetadata(s.Ctx(), "k", "v2"))
|
||||
v, err := r.GetMetadata(s.Ctx(), "k")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("v2", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configSetLocalMetadataWrites() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.2.3"))
|
||||
|
||||
var v string
|
||||
err := s.Runner().
|
||||
QueryRowContext(s.Ctx(), "SELECT value FROM local_metadata WHERE `key` = ?", "bd_version").
|
||||
Scan(&v)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("1.2.3", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configGetConfigMissingKey() {
|
||||
v, err := s.configRepo().GetConfig(s.Ctx(), "no_such_key")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configGetConfigRoundTrip() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetConfig(s.Ctx(), "team.sync_branch", "main"))
|
||||
v, err := r.GetConfig(s.Ctx(), "team.sync_branch")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("main", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configSetConfigOverwrite() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetConfig(s.Ctx(), "k", "v1"))
|
||||
s.Require().NoError(r.SetConfig(s.Ctx(), "k", "v2"))
|
||||
v, err := r.GetConfig(s.Ctx(), "k")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("v2", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configSetConfigIssuePrefixTrim() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetConfig(s.Ctx(), "issue_prefix", "bd-"))
|
||||
v, err := r.GetConfig(s.Ctx(), "issue_prefix")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("bd", v)
|
||||
}
|
||||
|
||||
func (s *testSuite) configSetConfigIssuePrefixUnchanged() {
|
||||
r := s.configRepo()
|
||||
s.Require().NoError(r.SetConfig(s.Ctx(), "issue_prefix", "bd"))
|
||||
v, err := r.GetConfig(s.Ctx(), "issue_prefix")
|
||||
s.Require().NoError(err)
|
||||
s.Equal("bd", v)
|
||||
}
|
||||
57
internal/storage/domain/db/remote.go
Normal file
57
internal/storage/domain/db/remote.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
func NewRemoteSQLRepository(runner Runner) domain.RemoteSQLRepository {
|
||||
return &remoteSQLRepositoryImpl{
|
||||
runner: runner,
|
||||
vc: NewDoltVersionControlSQLRepository(runner),
|
||||
}
|
||||
}
|
||||
|
||||
type remoteSQLRepositoryImpl struct {
|
||||
runner Runner
|
||||
vc DoltVersionControlSQLRepository
|
||||
}
|
||||
|
||||
var _ domain.RemoteSQLRepository = (*remoteSQLRepositoryImpl)(nil)
|
||||
|
||||
func (r *remoteSQLRepositoryImpl) AddRemote(ctx context.Context, name, url string) error {
|
||||
if err := r.vc.Remote(ctx, "add", name, url); err != nil {
|
||||
return fmt.Errorf("db: AddRemote %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *remoteSQLRepositoryImpl) RemoveRemote(ctx context.Context, name string) error {
|
||||
if err := r.vc.Remote(ctx, "remove", name); err != nil {
|
||||
return fmt.Errorf("db: RemoveRemote %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *remoteSQLRepositoryImpl) ListRemotes(ctx context.Context) ([]domain.Remote, error) {
|
||||
rows, err := r.runner.QueryContext(ctx, "SELECT name, url FROM dolt_remotes")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db: ListRemotes: query: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var remotes []domain.Remote
|
||||
for rows.Next() {
|
||||
var rem domain.Remote
|
||||
if err := rows.Scan(&rem.Name, &rem.URL); err != nil {
|
||||
return nil, fmt.Errorf("db: ListRemotes: scan: %w", err)
|
||||
}
|
||||
remotes = append(remotes, rem)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("db: ListRemotes: rows: %w", err)
|
||||
}
|
||||
return remotes, nil
|
||||
}
|
||||
106
internal/storage/domain/db/suite_test.go
Normal file
106
internal/storage/domain/db/suite_test.go
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"math/rand"
|
||||
"testing"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/doltutil"
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
"github.com/steveyegge/beads/internal/testutil"
|
||||
)
|
||||
|
||||
type testSuite struct {
|
||||
suite.Suite
|
||||
db *sql.DB
|
||||
dbName string
|
||||
baselineCommit string
|
||||
}
|
||||
|
||||
func (s *testSuite) SetupSuite() {
|
||||
testutil.RequireDoltContainer(s.T())
|
||||
|
||||
port := testutil.DoltContainerPortInt()
|
||||
s.Require().NotZero(port, "test container port must be set")
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
rootDSN := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String()
|
||||
root, err := sql.Open("mysql", rootDSN)
|
||||
s.Require().NoError(err)
|
||||
defer root.Close()
|
||||
|
||||
s.dbName = "beads_domain_db_test_" + randomSuffix(8)
|
||||
_, err = root.ExecContext(ctx, "CREATE DATABASE `"+s.dbName+"`")
|
||||
s.Require().NoError(err)
|
||||
|
||||
dsn := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root", Database: s.dbName}.String()
|
||||
db, err := sql.Open("mysql", dsn)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NoError(db.PingContext(ctx))
|
||||
s.db = db
|
||||
|
||||
_, err = schema.MigrateUp(ctx, db)
|
||||
s.Require().NoError(err, "applying beads schema")
|
||||
|
||||
_, err = db.ExecContext(ctx, "CALL DOLT_ADD('-A')")
|
||||
s.Require().NoError(err, "dolt add baseline")
|
||||
_, err = db.ExecContext(ctx, "CALL DOLT_COMMIT('-m', ?, '--allow-empty')", "beads domain/db test baseline")
|
||||
s.Require().NoError(err, "dolt commit baseline")
|
||||
s.Require().NoError(
|
||||
db.QueryRowContext(ctx, "SELECT HASHOF('HEAD')").Scan(&s.baselineCommit),
|
||||
"capture baseline commit hash",
|
||||
)
|
||||
}
|
||||
|
||||
func (s *testSuite) TearDownSuite() {
|
||||
if s.db != nil {
|
||||
_ = s.db.Close()
|
||||
s.db = nil
|
||||
}
|
||||
if s.dbName == "" {
|
||||
return
|
||||
}
|
||||
port := testutil.DoltContainerPortInt()
|
||||
if port == 0 {
|
||||
return
|
||||
}
|
||||
rootDSN := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String()
|
||||
root, err := sql.Open("mysql", rootDSN)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
_, _ = root.ExecContext(context.Background(), "DROP DATABASE IF EXISTS `"+s.dbName+"`")
|
||||
}
|
||||
|
||||
func (s *testSuite) SetupTest() {
|
||||
_, err := s.db.ExecContext(context.Background(), "CALL DOLT_RESET('--hard', ?)", s.baselineCommit)
|
||||
s.Require().NoError(err, "reset to baseline %s", s.baselineCommit)
|
||||
}
|
||||
|
||||
func (s *testSuite) Runner() Runner {
|
||||
return s.db
|
||||
}
|
||||
|
||||
func (s *testSuite) Ctx() context.Context {
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
var suffixLetters = []rune("abcdefghijklmnopqrstuvwxyz")
|
||||
|
||||
func randomSuffix(n int) string {
|
||||
b := make([]rune, n)
|
||||
for i := range b {
|
||||
b[i] = suffixLetters[rand.Intn(len(suffixLetters))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestDomainDB(t *testing.T) {
|
||||
suite.Run(t, &testSuite{})
|
||||
}
|
||||
288
internal/storage/domain/fs/beads.go
Normal file
288
internal/storage/domain/fs/beads.go
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
const beadsGitignoreTemplate = `# Dolt database (managed by Dolt, not git)
|
||||
dolt/
|
||||
embeddeddolt/
|
||||
proxieddb/
|
||||
|
||||
# Runtime files
|
||||
bd.sock
|
||||
bd.sock.startlock
|
||||
sync-state.json
|
||||
last-touched
|
||||
.exclusive-lock
|
||||
|
||||
# Daemon runtime (lock, log, pid)
|
||||
daemon.*
|
||||
|
||||
# Push state (runtime, per-machine)
|
||||
push-state.json
|
||||
|
||||
# Lock files (various runtime locks)
|
||||
*.lock
|
||||
|
||||
# Credential key (encryption key for federation peer auth — never commit)
|
||||
.beads-credential-key
|
||||
|
||||
# Local version tracking (prevents upgrade notification spam after git ops)
|
||||
.local_version
|
||||
|
||||
# Worktree redirect file (contains relative path to main repo's .beads/)
|
||||
# Must not be committed as paths would be wrong in other clones
|
||||
redirect
|
||||
|
||||
# Sync state (local-only, per-machine)
|
||||
# These files are machine-specific and should not be shared across clones
|
||||
.sync.lock
|
||||
export-state/
|
||||
export-state.json
|
||||
|
||||
# Ephemeral store (SQLite - wisps/molecules, intentionally not versioned)
|
||||
ephemeral.sqlite3
|
||||
ephemeral.sqlite3-journal
|
||||
ephemeral.sqlite3-wal
|
||||
ephemeral.sqlite3-shm
|
||||
|
||||
# Dolt server management (auto-started by bd)
|
||||
dolt-server.pid
|
||||
dolt-server.log
|
||||
dolt-server.lock
|
||||
dolt-server.port
|
||||
dolt-server.activity
|
||||
|
||||
# Corrupt backup directories (created by bd doctor --fix recovery)
|
||||
*.corrupt.backup/
|
||||
|
||||
# Backup data (auto-exported JSONL, local-only)
|
||||
backup/
|
||||
|
||||
# Per-project environment file (Dolt connection config, GH#2520)
|
||||
.env
|
||||
|
||||
# Legacy files (from pre-Dolt versions)
|
||||
*.db
|
||||
*.db?*
|
||||
*.db-journal
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
db.sqlite
|
||||
bd.db
|
||||
# NOTE: Do NOT add negation patterns here.
|
||||
# They would override fork protection in .git/info/exclude.
|
||||
# Config files (metadata.json, config.yaml) are tracked by git by default
|
||||
# since no pattern above ignores them.
|
||||
`
|
||||
|
||||
var projectGitignorePatterns = []string{
|
||||
".dolt/",
|
||||
"*.db",
|
||||
".beads-credential-key",
|
||||
".beads/proxieddb/",
|
||||
}
|
||||
|
||||
const projectGitignoreHeader = "# Beads / Dolt files (added by bd init)"
|
||||
|
||||
const beadsReadmeTemplate = `# Beads
|
||||
|
||||
This directory is managed by [beads](https://github.com/steveyegge/beads).
|
||||
Run ` + "`bd help`" + ` for available commands.
|
||||
`
|
||||
|
||||
func NewBeadsDirFSRepository() domain.BeadsDirFSRepository {
|
||||
return &beadsDirFSRepositoryImpl{}
|
||||
}
|
||||
|
||||
type beadsDirFSRepositoryImpl struct{}
|
||||
|
||||
var _ domain.BeadsDirFSRepository = (*beadsDirFSRepositoryImpl)(nil)
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) CreateBeadsDir(ctx context.Context, beadsDir string) error {
|
||||
if beadsDir == "" {
|
||||
return fmt.Errorf("fs: CreateBeadsDir: beadsDir must not be empty")
|
||||
}
|
||||
if err := os.MkdirAll(beadsDir, config.BeadsDirPerm); err != nil {
|
||||
return fmt.Errorf("fs: CreateBeadsDir: mkdir %s: %w", beadsDir, err)
|
||||
}
|
||||
if _, err := config.FixBeadsDirPermissions(beadsDir); err != nil {
|
||||
return fmt.Errorf("fs: CreateBeadsDir: fix perms %s: %w", beadsDir, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) BeadsDirExists(ctx context.Context, beadsDir string) (bool, error) {
|
||||
info, err := os.Stat(beadsDir)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("fs: BeadsDirExists: stat %s: %w", beadsDir, err)
|
||||
}
|
||||
return info.IsDir(), nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteBeadsGitignore(ctx context.Context, beadsDir string) error {
|
||||
path := filepath.Join(beadsDir, ".gitignore")
|
||||
// #nosec G304 -- path joined under caller-supplied beadsDir
|
||||
if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, []byte(beadsGitignoreTemplate)) {
|
||||
return nil
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(beadsGitignoreTemplate), 0600); err != nil {
|
||||
return fmt.Errorf("fs: WriteBeadsGitignore: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) BeadsGitignoreExists(ctx context.Context, beadsDir string) (bool, error) {
|
||||
return fileExists(filepath.Join(beadsDir, ".gitignore"), "fs: BeadsGitignoreExists")
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context, repoRoot string) error {
|
||||
if repoRoot == "" {
|
||||
return fmt.Errorf("fs: WriteProjectGitignore: repoRoot must not be empty")
|
||||
}
|
||||
path := filepath.Join(repoRoot, ".gitignore")
|
||||
// #nosec G304 -- path joined under caller-supplied repoRoot
|
||||
existing, err := os.ReadFile(path)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("fs: WriteProjectGitignore: read: %w", err)
|
||||
}
|
||||
|
||||
var toAdd []string
|
||||
for _, pattern := range projectGitignorePatterns {
|
||||
if !containsLine(existing, pattern) {
|
||||
toAdd = append(toAdd, pattern)
|
||||
}
|
||||
}
|
||||
if len(toAdd) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
buf.Write(existing)
|
||||
if len(existing) > 0 && !bytes.HasSuffix(existing, []byte("\n")) {
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
if !containsLine(existing, projectGitignoreHeader) {
|
||||
if len(existing) > 0 {
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
buf.WriteString(projectGitignoreHeader + "\n")
|
||||
}
|
||||
for _, pattern := range toAdd {
|
||||
buf.WriteString(pattern + "\n")
|
||||
}
|
||||
|
||||
// #nosec G306 -- .gitignore must be world-readable so users can read/edit it
|
||||
if err := os.WriteFile(path, buf.Bytes(), 0644); err != nil {
|
||||
return fmt.Errorf("fs: WriteProjectGitignore: write: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) ProjectGitignoreExists(ctx context.Context, repoRoot string) (bool, error) {
|
||||
return fileExists(filepath.Join(repoRoot, ".gitignore"), "fs: ProjectGitignoreExists")
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteInteractionsLog(ctx context.Context, beadsDir string) error {
|
||||
path := filepath.Join(beadsDir, "interactions.jsonl")
|
||||
switch _, err := os.Stat(path); {
|
||||
case err == nil:
|
||||
return nil
|
||||
case !errors.Is(err, os.ErrNotExist):
|
||||
return fmt.Errorf("fs: WriteInteractionsLog: stat: %w", err)
|
||||
}
|
||||
// #nosec G306 -- interactions log is consumed by user tooling
|
||||
if err := os.WriteFile(path, []byte{}, 0644); err != nil {
|
||||
return fmt.Errorf("fs: WriteInteractionsLog: write: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteReadme(ctx context.Context, beadsDir string) error {
|
||||
path := filepath.Join(beadsDir, "README.md")
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return nil // preserve any user edits
|
||||
}
|
||||
// #nosec G306 -- README should be world-readable
|
||||
if err := os.WriteFile(path, []byte(beadsReadmeTemplate), 0644); err != nil {
|
||||
return fmt.Errorf("fs: WriteReadme: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteMetadataJSON(ctx context.Context, beadsDir string, content []byte) error {
|
||||
path := filepath.Join(beadsDir, "metadata.json")
|
||||
if err := os.WriteFile(path, content, 0600); err != nil {
|
||||
return fmt.Errorf("fs: WriteMetadataJSON: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) ReadMetadataJSON(ctx context.Context, beadsDir string) ([]byte, error) {
|
||||
path := filepath.Join(beadsDir, "metadata.json")
|
||||
// #nosec G304 -- path joined under caller-supplied beadsDir
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fs: ReadMetadataJSON: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteConfigYAML(ctx context.Context, beadsDir string, content []byte) error {
|
||||
path := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(path, content, 0600); err != nil {
|
||||
return fmt.Errorf("fs: WriteConfigYAML: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) ReadConfigYAML(ctx context.Context, beadsDir string) ([]byte, error) {
|
||||
path := filepath.Join(beadsDir, "config.yaml")
|
||||
// #nosec G304 -- path joined under caller-supplied beadsDir
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fs: ReadConfigYAML: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func fileExists(path, opLabel string) (bool, error) {
|
||||
info, err := os.Stat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s: stat %s: %w", opLabel, path, err)
|
||||
}
|
||||
return !info.IsDir(), nil
|
||||
}
|
||||
|
||||
func containsLine(content []byte, line string) bool {
|
||||
s := bufio.NewScanner(bytes.NewReader(content))
|
||||
for s.Scan() {
|
||||
if strings.TrimSpace(s.Text()) == line {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
379
internal/storage/domain/fs/beads_test.go
Normal file
379
internal/storage/domain/fs/beads_test.go
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
)
|
||||
|
||||
func (s *testSuite) TestBeadsDirFSRepository() {
|
||||
s.Run("CreateBeadsDir", func() {
|
||||
s.Run("EmptyPathErrors", s.createBeadsDirEmptyPath)
|
||||
s.Run("CreatesDirectoryWithPerms", s.createBeadsDirCreates)
|
||||
s.Run("IdempotentOnExisting", s.createBeadsDirIdempotent)
|
||||
})
|
||||
s.Run("BeadsDirExists", func() {
|
||||
s.Run("MissingReturnsFalse", s.beadsDirExistsMissing)
|
||||
s.Run("PresentReturnsTrue", s.beadsDirExistsPresent)
|
||||
s.Run("FileNotDirReturnsFalse", s.beadsDirExistsIsFile)
|
||||
})
|
||||
s.Run("WriteBeadsGitignore", func() {
|
||||
s.Run("WritesTemplate", s.writeBeadsGitignoreWrites)
|
||||
s.Run("IdempotentOnMatchingContent", s.writeBeadsGitignoreIdempotent)
|
||||
s.Run("OverwritesDifferingContent", s.writeBeadsGitignoreOverwrites)
|
||||
})
|
||||
s.Run("BeadsGitignoreExists", func() {
|
||||
s.Run("MissingReturnsFalse", s.beadsGitignoreExistsMissing)
|
||||
s.Run("PresentReturnsTrue", s.beadsGitignoreExistsPresent)
|
||||
})
|
||||
s.Run("WriteProjectGitignore", func() {
|
||||
s.Run("EmptyRepoRootErrors", s.writeProjectGitignoreEmptyRoot)
|
||||
s.Run("CreatesWithHeaderAndPatterns", s.writeProjectGitignoreCreates)
|
||||
s.Run("AppendsToExisting", s.writeProjectGitignoreAppends)
|
||||
s.Run("SkipsAlreadyPresentPatterns", s.writeProjectGitignoreNoDuplicates)
|
||||
s.Run("NoChangeWhenAllPresent", s.writeProjectGitignoreNoOpWhenComplete)
|
||||
s.Run("AddsLeadingNewlineWhenMissing", s.writeProjectGitignoreFixesTrailingNewline)
|
||||
})
|
||||
s.Run("ProjectGitignoreExists", func() {
|
||||
s.Run("MissingReturnsFalse", s.projectGitignoreExistsMissing)
|
||||
s.Run("PresentReturnsTrue", s.projectGitignoreExistsPresent)
|
||||
})
|
||||
s.Run("WriteInteractionsLog", func() {
|
||||
s.Run("CreatesEmptyFile", s.writeInteractionsLogCreates)
|
||||
s.Run("PreservesExisting", s.writeInteractionsLogPreserves)
|
||||
})
|
||||
s.Run("WriteReadme", func() {
|
||||
s.Run("CreatesFromTemplate", s.writeReadmeCreates)
|
||||
s.Run("PreservesExisting", s.writeReadmePreserves)
|
||||
})
|
||||
s.Run("MetadataJSON", func() {
|
||||
s.Run("ReadMissingReturnsNil", s.readMetadataJSONMissing)
|
||||
s.Run("WriteThenReadRoundTrip", s.metadataJSONRoundTrip)
|
||||
s.Run("WriteOverwrites", s.metadataJSONOverwrite)
|
||||
})
|
||||
s.Run("ConfigYAML", func() {
|
||||
s.Run("ReadMissingReturnsNil", s.readConfigYAMLMissing)
|
||||
s.Run("WriteThenReadRoundTrip", s.configYAMLRoundTrip)
|
||||
s.Run("WriteOverwrites", s.configYAMLOverwrite)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *testSuite) createBeadsDirEmptyPath() {
|
||||
err := s.repo.CreateBeadsDir(s.Ctx(), "")
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *testSuite) createBeadsDirCreates() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir))
|
||||
|
||||
info, err := os.Stat(dir)
|
||||
s.Require().NoError(err)
|
||||
s.True(info.IsDir())
|
||||
|
||||
if runtime.GOOS != "windows" {
|
||||
s.Equal(config.BeadsDirPerm, info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) createBeadsDirIdempotent() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir))
|
||||
s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir))
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirExistsMissing() {
|
||||
_, dir := s.beadsDir()
|
||||
exists, err := s.repo.BeadsDirExists(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirExistsPresent() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
exists, err := s.repo.BeadsDirExists(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.True(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirExistsIsFile() {
|
||||
_, path := s.beadsDir()
|
||||
s.Require().NoError(os.WriteFile(path, []byte("not a dir"), 0600))
|
||||
exists, err := s.repo.BeadsDirExists(s.Ctx(), path)
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeBeadsGitignoreWrites() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(dir, ".gitignore"))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(beadsGitignoreTemplate, string(data))
|
||||
}
|
||||
|
||||
func (s *testSuite) writeBeadsGitignoreIdempotent() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
path := filepath.Join(dir, ".gitignore")
|
||||
s.Require().NoError(os.WriteFile(path, []byte(beadsGitignoreTemplate), 0600))
|
||||
|
||||
before, err := os.Stat(path)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir))
|
||||
|
||||
after, err := os.Stat(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(before.ModTime(), after.ModTime(), "file should not be rewritten when content already matches")
|
||||
}
|
||||
|
||||
func (s *testSuite) writeBeadsGitignoreOverwrites() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
path := filepath.Join(dir, ".gitignore")
|
||||
s.Require().NoError(os.WriteFile(path, []byte("stale\n"), 0600))
|
||||
|
||||
s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(beadsGitignoreTemplate, string(data))
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsGitignoreExistsMissing() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
exists, err := s.repo.BeadsGitignoreExists(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsGitignoreExistsPresent() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
s.Require().NoError(os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("x"), 0600))
|
||||
exists, err := s.repo.BeadsGitignoreExists(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.True(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreEmptyRoot() {
|
||||
err := s.repo.WriteProjectGitignore(s.Ctx(), "")
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreCreates() {
|
||||
root := s.tmpRoot()
|
||||
s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(root, ".gitignore"))
|
||||
s.Require().NoError(err)
|
||||
body := string(data)
|
||||
|
||||
s.Contains(body, projectGitignoreHeader)
|
||||
for _, pattern := range projectGitignorePatterns {
|
||||
s.Contains(body, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreAppends() {
|
||||
root := s.tmpRoot()
|
||||
path := filepath.Join(root, ".gitignore")
|
||||
preexisting := "node_modules/\n*.log\n"
|
||||
s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644))
|
||||
|
||||
s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
body := string(data)
|
||||
|
||||
s.True(strings.HasPrefix(body, preexisting), "preexisting content must be preserved at the top")
|
||||
s.Contains(body, projectGitignoreHeader)
|
||||
for _, pattern := range projectGitignorePatterns {
|
||||
s.Contains(body, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreNoDuplicates() {
|
||||
root := s.tmpRoot()
|
||||
path := filepath.Join(root, ".gitignore")
|
||||
preexisting := ".dolt/\nnode_modules/\n"
|
||||
s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644))
|
||||
|
||||
s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal(1, strings.Count(string(data), ".dolt/\n"), "must not duplicate existing patterns")
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreNoOpWhenComplete() {
|
||||
root := s.tmpRoot()
|
||||
path := filepath.Join(root, ".gitignore")
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("existing\n")
|
||||
buf.WriteString(projectGitignoreHeader + "\n")
|
||||
for _, pattern := range projectGitignorePatterns {
|
||||
buf.WriteString(pattern + "\n")
|
||||
}
|
||||
s.Require().NoError(os.WriteFile(path, buf.Bytes(), 0644))
|
||||
|
||||
before, err := os.Stat(path)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root))
|
||||
|
||||
after, err := os.Stat(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(before.ModTime(), after.ModTime(), "must not rewrite when all patterns already present")
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreFixesTrailingNewline() {
|
||||
root := s.tmpRoot()
|
||||
path := filepath.Join(root, ".gitignore")
|
||||
s.Require().NoError(os.WriteFile(path, []byte("no-trailing-newline"), 0644))
|
||||
|
||||
s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
body := string(data)
|
||||
|
||||
s.True(strings.HasPrefix(body, "no-trailing-newline\n"), "trailing newline must be inserted before appended content")
|
||||
s.Contains(body, projectGitignoreHeader)
|
||||
}
|
||||
|
||||
func (s *testSuite) projectGitignoreExistsMissing() {
|
||||
root := s.tmpRoot()
|
||||
exists, err := s.repo.ProjectGitignoreExists(s.Ctx(), root)
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) projectGitignoreExistsPresent() {
|
||||
root := s.tmpRoot()
|
||||
s.Require().NoError(os.WriteFile(filepath.Join(root, ".gitignore"), []byte("x"), 0644))
|
||||
exists, err := s.repo.ProjectGitignoreExists(s.Ctx(), root)
|
||||
s.Require().NoError(err)
|
||||
s.True(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeInteractionsLogCreates() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
s.Require().NoError(s.repo.WriteInteractionsLog(s.Ctx(), dir))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(dir, "interactions.jsonl"))
|
||||
s.Require().NoError(err)
|
||||
s.Empty(data)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeInteractionsLogPreserves() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
path := filepath.Join(dir, "interactions.jsonl")
|
||||
existing := []byte(`{"event":"x"}` + "\n")
|
||||
s.Require().NoError(os.WriteFile(path, existing, 0644))
|
||||
|
||||
s.Require().NoError(s.repo.WriteInteractionsLog(s.Ctx(), dir))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(existing, data)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeReadmeCreates() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
s.Require().NoError(s.repo.WriteReadme(s.Ctx(), dir))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(dir, "README.md"))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(beadsReadmeTemplate, string(data))
|
||||
}
|
||||
|
||||
func (s *testSuite) writeReadmePreserves() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
path := filepath.Join(dir, "README.md")
|
||||
custom := []byte("# My custom readme\n")
|
||||
s.Require().NoError(os.WriteFile(path, custom, 0644))
|
||||
|
||||
s.Require().NoError(s.repo.WriteReadme(s.Ctx(), dir))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(custom, data)
|
||||
}
|
||||
|
||||
func (s *testSuite) readMetadataJSONMissing() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
data, err := s.repo.ReadMetadataJSON(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.Nil(data)
|
||||
}
|
||||
|
||||
func (s *testSuite) metadataJSONRoundTrip() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
body := []byte(`{"_project_id":"abc-123"}`)
|
||||
|
||||
s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, body))
|
||||
|
||||
got, err := s.repo.ReadMetadataJSON(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(body, got)
|
||||
}
|
||||
|
||||
func (s *testSuite) metadataJSONOverwrite() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, []byte(`{"v":1}`)))
|
||||
s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, []byte(`{"v":2}`)))
|
||||
|
||||
got, err := s.repo.ReadMetadataJSON(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]byte(`{"v":2}`), got)
|
||||
}
|
||||
|
||||
func (s *testSuite) readConfigYAMLMissing() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
data, err := s.repo.ReadConfigYAML(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.Nil(data)
|
||||
}
|
||||
|
||||
func (s *testSuite) configYAMLRoundTrip() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
body := []byte("issue_prefix: bd\n")
|
||||
|
||||
s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, body))
|
||||
|
||||
got, err := s.repo.ReadConfigYAML(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(body, got)
|
||||
}
|
||||
|
||||
func (s *testSuite) configYAMLOverwrite() {
|
||||
_, dir := s.beadsDir()
|
||||
s.Require().NoError(os.MkdirAll(dir, 0700))
|
||||
s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, []byte("v: 1\n")))
|
||||
s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, []byte("v: 2\n")))
|
||||
|
||||
got, err := s.repo.ReadConfigYAML(s.Ctx(), dir)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]byte("v: 2\n"), got)
|
||||
}
|
||||
37
internal/storage/domain/fs/suite_test.go
Normal file
37
internal/storage/domain/fs/suite_test.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
type testSuite struct {
|
||||
suite.Suite
|
||||
repo domain.BeadsDirFSRepository
|
||||
}
|
||||
|
||||
func (s *testSuite) SetupTest() {
|
||||
s.repo = NewBeadsDirFSRepository()
|
||||
}
|
||||
|
||||
func (s *testSuite) Ctx() context.Context {
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func (s *testSuite) tmpRoot() string {
|
||||
return s.T().TempDir()
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDir() (string, string) {
|
||||
root := s.tmpRoot()
|
||||
return root, filepath.Join(root, ".beads")
|
||||
}
|
||||
|
||||
func TestDomainFS(t *testing.T) {
|
||||
suite.Run(t, &testSuite{})
|
||||
}
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
package domain
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type DoltRemoteUseCase interface {
|
||||
CreateRemote(ctx context.Context, name, url string) error
|
||||
|
|
@ -9,4 +12,70 @@ type DoltRemoteUseCase interface {
|
|||
ListRemotes(ctx context.Context) ([]Remote, error)
|
||||
}
|
||||
|
||||
type Remote struct{}
|
||||
type Remote struct {
|
||||
Name string
|
||||
URL string
|
||||
}
|
||||
|
||||
type RemoteSQLRepository interface {
|
||||
AddRemote(ctx context.Context, name, url string) error
|
||||
RemoveRemote(ctx context.Context, name string) error
|
||||
ListRemotes(ctx context.Context) ([]Remote, error)
|
||||
}
|
||||
|
||||
func NewDoltRemoteUseCase(remoteRepo RemoteSQLRepository) DoltRemoteUseCase {
|
||||
return &doltRemoteUseCaseImpl{remoteRepo: remoteRepo}
|
||||
}
|
||||
|
||||
type doltRemoteUseCaseImpl struct {
|
||||
remoteRepo RemoteSQLRepository
|
||||
}
|
||||
|
||||
var _ DoltRemoteUseCase = (*doltRemoteUseCaseImpl)(nil)
|
||||
|
||||
func (u *doltRemoteUseCaseImpl) CreateRemote(ctx context.Context, name, url string) error {
|
||||
if name == "" {
|
||||
return fmt.Errorf("CreateRemote: name must not be empty")
|
||||
}
|
||||
if url == "" {
|
||||
return fmt.Errorf("CreateRemote: url must not be empty")
|
||||
}
|
||||
if err := u.remoteRepo.AddRemote(ctx, name, url); err != nil {
|
||||
return fmt.Errorf("CreateRemote %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *doltRemoteUseCaseImpl) UpdateRemote(ctx context.Context, name, url string) error {
|
||||
if name == "" {
|
||||
return fmt.Errorf("UpdateRemote: name must not be empty")
|
||||
}
|
||||
if url == "" {
|
||||
return fmt.Errorf("UpdateRemote: url must not be empty")
|
||||
}
|
||||
if err := u.remoteRepo.RemoveRemote(ctx, name); err != nil {
|
||||
return fmt.Errorf("UpdateRemote %s: remove: %w", name, err)
|
||||
}
|
||||
if err := u.remoteRepo.AddRemote(ctx, name, url); err != nil {
|
||||
return fmt.Errorf("UpdateRemote %s: add: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *doltRemoteUseCaseImpl) DeleteRemote(ctx context.Context, name string) error {
|
||||
if name == "" {
|
||||
return fmt.Errorf("DeleteRemote: name must not be empty")
|
||||
}
|
||||
if err := u.remoteRepo.RemoveRemote(ctx, name); err != nil {
|
||||
return fmt.Errorf("DeleteRemote %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *doltRemoteUseCaseImpl) ListRemotes(ctx context.Context) ([]Remote, error) {
|
||||
remotes, err := u.remoteRepo.ListRemotes(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ListRemotes: %w", err)
|
||||
}
|
||||
return remotes, nil
|
||||
}
|
||||
|
|
|
|||
31
internal/storage/fs/provider.go
Normal file
31
internal/storage/fs/provider.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
domainfs "github.com/steveyegge/beads/internal/storage/domain/fs"
|
||||
)
|
||||
|
||||
type FileSystemProvider interface {
|
||||
BeadsDirFSUseCase() domain.BeadsDirFSUseCase
|
||||
}
|
||||
|
||||
func NewFileSystemProvider(adapters domain.BeadsDirFSAdapters) FileSystemProvider {
|
||||
return &fileSystemProviderImpl{adapters: adapters}
|
||||
}
|
||||
|
||||
type fileSystemProviderImpl struct {
|
||||
adapters domain.BeadsDirFSAdapters
|
||||
beadsDirFSUseCase domain.BeadsDirFSUseCase
|
||||
}
|
||||
|
||||
var _ FileSystemProvider = (*fileSystemProviderImpl)(nil)
|
||||
|
||||
func (p *fileSystemProviderImpl) BeadsDirFSUseCase() domain.BeadsDirFSUseCase {
|
||||
if p.beadsDirFSUseCase == nil {
|
||||
p.beadsDirFSUseCase = domain.NewBeadsDirFSUseCase(
|
||||
domainfs.NewBeadsDirFSRepository(),
|
||||
p.adapters,
|
||||
)
|
||||
}
|
||||
return p.beadsDirFSUseCase
|
||||
}
|
||||
|
|
@ -107,15 +107,28 @@ func (p *doltServerProvider) NewUOW(ctx context.Context) (UnitOfWork, error) {
|
|||
return NewUOW(ctx, p)
|
||||
}
|
||||
|
||||
func (p *doltServerProvider) NewTx(ctx context.Context) (Tx, error) {
|
||||
func (p *doltServerProvider) Close(ctx context.Context) error {
|
||||
if p.db == nil {
|
||||
return nil
|
||||
}
|
||||
db := p.db
|
||||
p.db = nil
|
||||
return db.Close()
|
||||
}
|
||||
|
||||
func (p *doltServerProvider) BeginTx(ctx context.Context) (Tx, error) {
|
||||
conn, err := p.db.Conn(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("uow: pin connection: %w", err)
|
||||
}
|
||||
|
||||
_, err = conn.ExecContext(ctx, "START TRANSACTION;")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("uow: failed to start transaction: %w", err)
|
||||
}
|
||||
|
||||
return &doltServerTx{
|
||||
conn: conn,
|
||||
vc: db.NewDoltVersionControlSQLRepository(conn),
|
||||
targetBranch: p.defaultBranch,
|
||||
conn: conn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,10 +20,6 @@ import (
|
|||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// shutdownOnInterrupt installs a SIGINT/SIGTERM handler that runs
|
||||
// proxy.Shutdown(rootDir) and exits, so the proxy and child dolt sql-server
|
||||
// don't survive an early test abort (e.g. Ctrl+C). The handler is removed via
|
||||
// t.Cleanup on normal test completion.
|
||||
func shutdownOnInterrupt(t *testing.T, rootDir string) {
|
||||
t.Helper()
|
||||
ch := make(chan os.Signal, 1)
|
||||
|
|
@ -111,8 +107,74 @@ func TestNewDoltServerUOWProvider_HappyPath(t *testing.T) {
|
|||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, provider)
|
||||
impl := provider.(*doltServerProvider)
|
||||
t.Cleanup(func() { _ = impl.db.Close() })
|
||||
t.Cleanup(func() { _ = provider.Close(context.Background()) })
|
||||
}
|
||||
|
||||
func TestNewDoltServerUOWProvider_ConcurrentInstantiation(t *testing.T) {
|
||||
testutil.RequireDoltBinary(t)
|
||||
bin, err := exec.LookPath("dolt")
|
||||
require.NoError(t, err)
|
||||
|
||||
bdBin := buildBDBinary(t)
|
||||
prev := proxy.ResolveExecutable
|
||||
proxy.ResolveExecutable = func() (string, error) { return bdBin, nil }
|
||||
t.Cleanup(func() { proxy.ResolveExecutable = prev })
|
||||
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
|
||||
port, err := proxy.PickFreePort()
|
||||
require.NoError(t, err)
|
||||
storeRootDir := t.TempDir()
|
||||
shutdownOnInterrupt(t, storeRootDir)
|
||||
t.Cleanup(func() {
|
||||
if err := proxy.Shutdown(storeRootDir); err != nil {
|
||||
t.Logf("proxy.Shutdown(%s): %v", storeRootDir, err)
|
||||
}
|
||||
})
|
||||
cfgPath := writeServerConfig(t, port)
|
||||
logPath := filepath.Join(t.TempDir(), "server.log")
|
||||
|
||||
const concurrency = 10
|
||||
type result struct {
|
||||
provider UnitOfWorkProvider
|
||||
err error
|
||||
}
|
||||
results := make([]result, concurrency)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(concurrency)
|
||||
for i := 0; i < concurrency; i++ {
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
p, err := NewDoltServerUOWProvider(
|
||||
context.Background(),
|
||||
storeRootDir,
|
||||
"beads",
|
||||
logPath,
|
||||
cfgPath,
|
||||
proxy.BackendLocalServer,
|
||||
"root",
|
||||
"",
|
||||
bin,
|
||||
)
|
||||
results[i] = result{provider: p, err: err}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
t.Cleanup(func() {
|
||||
for _, r := range results {
|
||||
if r.provider != nil {
|
||||
_ = r.provider.Close(context.Background())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for i, r := range results {
|
||||
assert.NoErrorf(t, r.err, "provider %d", i)
|
||||
assert.NotNilf(t, r.provider, "provider %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
|
|
|
|||
|
|
@ -2,102 +2,31 @@ package uow
|
|||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
db "github.com/steveyegge/beads/internal/storage/domain/db"
|
||||
"github.com/steveyegge/beads/internal/storage/domain/db"
|
||||
)
|
||||
|
||||
type doltServerTx struct {
|
||||
conn *sql.Conn
|
||||
vc db.DoltVersionControlSQLRepository
|
||||
tx *sql.Tx
|
||||
branch string
|
||||
targetBranch string
|
||||
done bool
|
||||
conn *sql.Conn
|
||||
done bool
|
||||
}
|
||||
|
||||
var _ Tx = (*doltServerTx)(nil)
|
||||
|
||||
func (t *doltServerTx) Begin(ctx context.Context) (*sql.Tx, error) {
|
||||
if t.tx != nil {
|
||||
return nil, errors.New("uow: Begin: already begun")
|
||||
}
|
||||
|
||||
success := false
|
||||
defer func() {
|
||||
if !success {
|
||||
t.releaseConn()
|
||||
}
|
||||
}()
|
||||
|
||||
branch, err := genRandomBranchName()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := t.vc.Branch(ctx, branch, t.targetBranch); err != nil {
|
||||
return nil, fmt.Errorf("uow: create work branch %q from %q: %w", branch, t.targetBranch, err)
|
||||
}
|
||||
|
||||
if err := t.vc.Checkout(ctx, branch); err != nil {
|
||||
_ = t.vc.Branch(ctx, "-d", branch)
|
||||
return nil, fmt.Errorf("uow: checkout work branch %q: %w", branch, err)
|
||||
}
|
||||
|
||||
sqlTx, err := t.conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.cleanupBranchBestEffort(ctx)
|
||||
return nil, fmt.Errorf("uow: begin sql tx: %w", err)
|
||||
}
|
||||
|
||||
t.branch = branch
|
||||
t.tx = sqlTx
|
||||
success = true
|
||||
|
||||
return sqlTx, nil
|
||||
func (t *doltServerTx) Runner() db.Runner {
|
||||
return t.conn
|
||||
}
|
||||
|
||||
func (t *doltServerTx) Commit(ctx context.Context, message string) error {
|
||||
if t.done {
|
||||
return errors.New("uow: commit: already done")
|
||||
}
|
||||
|
||||
t.done = true
|
||||
defer func() {
|
||||
t.cleanupBranchBestEffort(ctx)
|
||||
t.releaseConn()
|
||||
}()
|
||||
|
||||
if err := t.tx.Commit(); err != nil {
|
||||
return fmt.Errorf("uow: commit sql tx: %w", err)
|
||||
}
|
||||
|
||||
if err := t.vc.Add(ctx, "-A"); err != nil {
|
||||
return fmt.Errorf("uow: dolt add: %w", err)
|
||||
}
|
||||
|
||||
if err := t.vc.Commit(ctx, "-m", message); err != nil && !isNothingToCommit(err) {
|
||||
return fmt.Errorf("uow: dolt commit: %w", err)
|
||||
}
|
||||
|
||||
if err := t.vc.Checkout(ctx, t.targetBranch); err != nil {
|
||||
return fmt.Errorf("uow: checkout %s: %w", t.targetBranch, err)
|
||||
}
|
||||
|
||||
if err := t.vc.Merge(ctx, t.branch); err != nil {
|
||||
return fmt.Errorf("uow: merge %s into %s: %w", t.branch, t.targetBranch, err)
|
||||
}
|
||||
|
||||
if err := t.vc.Branch(ctx, "-d", t.branch); err != nil {
|
||||
return fmt.Errorf("uow: delete work branch %s: %w", t.branch, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
defer t.releaseConn()
|
||||
_, err := t.conn.ExecContext(ctx, "CALL DOLT_COMMIT('-Am', ?);", message)
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *doltServerTx) Rollback(ctx context.Context) error {
|
||||
|
|
@ -106,18 +35,8 @@ func (t *doltServerTx) Rollback(ctx context.Context) error {
|
|||
}
|
||||
t.done = true
|
||||
defer t.releaseConn()
|
||||
|
||||
var errs []error
|
||||
if err := t.tx.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) {
|
||||
errs = append(errs, fmt.Errorf("uow: rollback sql tx: %w", err))
|
||||
}
|
||||
if err := t.vc.Checkout(ctx, t.targetBranch); err != nil {
|
||||
errs = append(errs, fmt.Errorf("uow: checkout %s on rollback: %w", t.targetBranch, err))
|
||||
}
|
||||
if err := t.vc.Branch(ctx, "-d", t.branch); err != nil {
|
||||
errs = append(errs, fmt.Errorf("uow: delete work branch %s on rollback: %w", t.branch, err))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
_, err := t.conn.ExecContext(ctx, "ROLLBACK;")
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *doltServerTx) RollbackUnlessCommitted(ctx context.Context) {
|
||||
|
|
@ -126,26 +45,9 @@ func (t *doltServerTx) RollbackUnlessCommitted(ctx context.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
func (t *doltServerTx) cleanupBranchBestEffort(ctx context.Context) {
|
||||
_ = t.vc.Checkout(ctx, t.targetBranch)
|
||||
_ = t.vc.Branch(ctx, "-d", t.branch)
|
||||
}
|
||||
|
||||
func (t *doltServerTx) releaseConn() {
|
||||
if t.conn != nil {
|
||||
_ = t.conn.Close()
|
||||
t.conn = nil
|
||||
}
|
||||
}
|
||||
|
||||
func isNothingToCommit(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "nothing to commit")
|
||||
}
|
||||
|
||||
func genRandomBranchName() (string, error) {
|
||||
var buf [8]byte
|
||||
if _, err := rand.Read(buf[:]); err != nil {
|
||||
return "", fmt.Errorf("uow: gen random branch name: %w", err)
|
||||
}
|
||||
return "bd-" + hex.EncodeToString(buf[:]), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,16 +2,17 @@ package uow
|
|||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain/db"
|
||||
)
|
||||
|
||||
type Tx interface {
|
||||
Begin(ctx context.Context) (*sql.Tx, error)
|
||||
Runner() db.Runner
|
||||
Commit(ctx context.Context, message string) error
|
||||
Rollback(ctx context.Context) error
|
||||
RollbackUnlessCommitted(ctx context.Context)
|
||||
}
|
||||
|
||||
type TxProvider interface {
|
||||
NewTx(ctx context.Context) (Tx, error)
|
||||
BeginTx(ctx context.Context) (Tx, error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,29 +1,40 @@
|
|||
package uow
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/storage/domain/db"
|
||||
)
|
||||
|
||||
type UnitOfWork interface {
|
||||
Close(ctx context.Context)
|
||||
Commit(ctx context.Context, message string) error
|
||||
|
||||
ConfigUseCase() domain.ConfigUseCase
|
||||
DoltRemoteUseCase() domain.DoltRemoteUseCase
|
||||
BootstrapUseCase() domain.BootstrapUseCase
|
||||
}
|
||||
|
||||
type UnitOfWorkProvider interface {
|
||||
NewUOW(ctx context.Context) (UnitOfWork, error)
|
||||
Close(ctx context.Context) error
|
||||
}
|
||||
|
||||
func NewUOW(ctx context.Context, p TxProvider) (UnitOfWork, error) {
|
||||
tx, err := p.NewTx(ctx)
|
||||
tx, err := p.BeginTx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.Begin(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &baseUOW{tx: tx}, nil
|
||||
}
|
||||
|
||||
type baseUOW struct {
|
||||
tx Tx
|
||||
|
||||
configUseCase domain.ConfigUseCase
|
||||
remoteUseCase domain.DoltRemoteUseCase
|
||||
bootstrapUseCase domain.BootstrapUseCase
|
||||
}
|
||||
|
||||
func (u *baseUOW) Commit(ctx context.Context, message string) error {
|
||||
|
|
@ -33,3 +44,27 @@ func (u *baseUOW) Commit(ctx context.Context, message string) error {
|
|||
func (u *baseUOW) Close(ctx context.Context) {
|
||||
u.tx.RollbackUnlessCommitted(ctx)
|
||||
}
|
||||
|
||||
func (u *baseUOW) ConfigUseCase() domain.ConfigUseCase {
|
||||
if u.configUseCase == nil {
|
||||
u.configUseCase = domain.NewConfigUseCase(db.NewConfigSQLRepository(u.tx.Runner()))
|
||||
}
|
||||
return u.configUseCase
|
||||
}
|
||||
|
||||
func (u *baseUOW) DoltRemoteUseCase() domain.DoltRemoteUseCase {
|
||||
if u.remoteUseCase == nil {
|
||||
u.remoteUseCase = domain.NewDoltRemoteUseCase(db.NewRemoteSQLRepository(u.tx.Runner()))
|
||||
}
|
||||
return u.remoteUseCase
|
||||
}
|
||||
|
||||
func (u *baseUOW) BootstrapUseCase() domain.BootstrapUseCase {
|
||||
if u.bootstrapUseCase == nil {
|
||||
u.bootstrapUseCase = domain.NewBootstrapUseCase(
|
||||
db.NewConfigSQLRepository(u.tx.Runner()),
|
||||
u.DoltRemoteUseCase(),
|
||||
)
|
||||
}
|
||||
return u.bootstrapUseCase
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue