commit
8f5ec4611f
31 changed files with 3154 additions and 222 deletions
45
.github/workflows/ci.yml
vendored
45
.github/workflows/ci.yml
vendored
|
|
@ -209,6 +209,51 @@ jobs:
|
|||
report_type: test_results
|
||||
fail_ci_if_error: false
|
||||
|
||||
# Focused job for the hexagonal storage layer (internal/storage/domain/* and
|
||||
# internal/storage/uow). These packages back the proxied-server init path and
|
||||
# also live behind the existing ./... matrix, but TestDomainDB requires the
|
||||
# Dolt sql-server image cached locally (testcontainers checks `docker image
|
||||
# inspect` and skips otherwise). Pulling the image up front guarantees the
|
||||
# suite actually runs and surfaces failures here with a clear job name.
|
||||
test-domain-uow:
|
||||
name: Test (storage domain + uow)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install Dolt CLI
|
||||
run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash
|
||||
|
||||
- name: Verify dolt on PATH
|
||||
run: dolt version
|
||||
|
||||
- name: Configure Git and Dolt identity
|
||||
run: |
|
||||
git config --global user.name "CI Bot"
|
||||
git config --global user.email "ci@beads.test"
|
||||
dolt config --global --add user.name "CI Bot"
|
||||
dolt config --global --add user.email "ci@beads.test"
|
||||
|
||||
- name: Pull Dolt sql-server image
|
||||
# Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage.
|
||||
# Without this, RequireDoltContainer reports doltNoImage and TestDomainDB skips.
|
||||
run: docker pull dolthub/dolt-sql-server:1.88.1
|
||||
|
||||
- name: Pre-build bd binary for uow concurrent test
|
||||
# internal/storage/uow tests spin up the proxy which re-execs `bd`. The
|
||||
# BEADS_TEST_BD_BINARY env var lets the test skip the per-process build.
|
||||
run: go build -tags gms_pure_go -o /tmp/bd-uow-test ./cmd/bd
|
||||
|
||||
- name: Test domain + uow
|
||||
env:
|
||||
BEADS_TEST_BD_BINARY: /tmp/bd-uow-test
|
||||
run: go test -tags gms_pure_go -race -count=1 -v ./internal/storage/domain/... ./internal/storage/uow/...
|
||||
|
||||
# Embedded Dolt tests - test the in-process Dolt engine (no server required)
|
||||
#
|
||||
# Split into: build → storage tests + parallel cmd test shards.
|
||||
|
|
|
|||
|
|
@ -94,8 +94,8 @@ var ProjectGitignorePatterns = []string{
|
|||
".beads/proxieddb/",
|
||||
}
|
||||
|
||||
// projectGitignoreComment is the section header added to the project .gitignore
|
||||
const projectGitignoreComment = "# Beads / Dolt files (added by bd init)"
|
||||
// ProjectGitignoreHeader is the section header added to the project .gitignore
|
||||
const ProjectGitignoreHeader = "# Beads / Dolt files (added by bd init)"
|
||||
|
||||
// requiredPatterns are patterns that MUST be in .beads/.gitignore
|
||||
var requiredPatterns = []string{
|
||||
|
|
@ -712,7 +712,7 @@ func EnsureProjectGitignore(repoPath string) error {
|
|||
newContent += "\n"
|
||||
}
|
||||
|
||||
newContent += "\n" + projectGitignoreComment + "\n"
|
||||
newContent += "\n" + ProjectGitignoreHeader + "\n"
|
||||
for _, pattern := range toAdd {
|
||||
newContent += pattern + "\n"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1812,7 +1812,7 @@ func TestEnsureProjectGitignore_CreatesFile(t *testing.T) {
|
|||
if !strings.Contains(contentStr, "*.db") {
|
||||
t.Error("Expected *.db pattern in .gitignore")
|
||||
}
|
||||
if !strings.Contains(contentStr, projectGitignoreComment) {
|
||||
if !strings.Contains(contentStr, ProjectGitignoreHeader) {
|
||||
t.Error("Expected section comment in .gitignore")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
36
cmd/bd/fs_adapters.go
Normal file
36
cmd/bd/fs_adapters.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
"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 newBeadsDirTemplates() domain.BeadsDirTemplates {
|
||||
return domain.BeadsDirTemplates{
|
||||
BeadsGitignore: doctor.GitignoreTemplate,
|
||||
ProjectGitignoreHeader: doctor.ProjectGitignoreHeader,
|
||||
ProjectGitignorePatterns: doctor.ProjectGitignorePatterns,
|
||||
Readme: BeadsReadmeTemplate,
|
||||
}
|
||||
}
|
||||
|
||||
func newFileSystemAdapters() domain.BeadsDirFSAdapters {
|
||||
return domain.BeadsDirFSAdapters{
|
||||
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.
|
||||
|
|
|
|||
429
cmd/bd/init_proxied_server.go
Normal file
429
cmd/bd/init_proxied_server.go
Normal file
|
|
@ -0,0 +1,429 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"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/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/storage/fs"
|
||||
"github.com/steveyegge/beads/internal/storage/git"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
FatalError("failed to get current directory: %v", err)
|
||||
}
|
||||
|
||||
fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newFileSystemAdapters())
|
||||
fsUseCase := fsProvider.BeadsDirFSUseCase()
|
||||
gitUC := git.NewGitProvider(cwd).GitUseCase()
|
||||
|
||||
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)
|
||||
|
||||
proxiedInit, err := fsUseCase.ResolveProxiedInit(ctx, domain.ResolveProxiedInitParams{
|
||||
Prefix: prefix,
|
||||
DBFlag: in.database,
|
||||
})
|
||||
if err != nil {
|
||||
FatalError("resolving proxied init: %v", err)
|
||||
}
|
||||
beadsDir, hasExplicitBeadsDir := proxiedInit.BeadsDir, proxiedInit.HasExplicit
|
||||
dbName, projectID := proxiedInit.DBName, proxiedInit.ProjectID
|
||||
beadsDirIsLocal := proxiedInit.IsLocal
|
||||
useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
if !hasExplicitBeadsDir {
|
||||
res, err := gitUC.EnsureGitRepo(ctx)
|
||||
if err != nil {
|
||||
FatalError("failed to initialize git repository: %v", err)
|
||||
}
|
||||
if res.DidInit && !in.quiet {
|
||||
fmt.Printf(" %s Initialized git repository\n", ui.RenderPass("✓"))
|
||||
}
|
||||
}
|
||||
|
||||
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{
|
||||
MetadataJSONBody: metadataBody,
|
||||
ConfigYAMLBody: configYAMLBody,
|
||||
SetNoCOW: true,
|
||||
WriteProjectGitignore: useLocalBeads && beadsDirIsLocal,
|
||||
}
|
||||
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(ctx, gitUC, 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,
|
||||
gitUC: gitUC,
|
||||
})
|
||||
}
|
||||
|
||||
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 resolveProxiedInitRemoteURL(ctx context.Context, gitUC domain.GitUseCase, in initProxiedServerInput) string {
|
||||
url, source := resolveInitConfiguredSyncRemote(in.initRemote, in.initRemoteChanged, resolveSyncRemote)
|
||||
if url != "" {
|
||||
return url
|
||||
}
|
||||
if source != initSyncRemoteNone {
|
||||
return ""
|
||||
}
|
||||
if !in.stealth {
|
||||
if originURL, err := gitUC.OriginRemoteURL(ctx); 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
|
||||
gitUC domain.GitUseCase
|
||||
}
|
||||
|
||||
func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) {
|
||||
isRepo := t.gitUC.IsGitRepo(ctx)
|
||||
|
||||
if isRepo {
|
||||
role := in.roleFlag
|
||||
if role == "" {
|
||||
role = "maintainer"
|
||||
}
|
||||
_, hasRole, _ := t.gitUC.BeadsRole(ctx)
|
||||
if !hasRole || in.roleFlag != "" {
|
||||
if err := t.gitUC.SetBeadsRole(ctx, 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 && isRepo {
|
||||
if isFork, upstreamURL, _ := t.gitUC.DetectFork(ctx); 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 := t.gitUC.IsJujutsuRepo(ctx)
|
||||
isColocated := t.gitUC.IsColocatedJJGit(ctx)
|
||||
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 isRepo {
|
||||
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()
|
||||
}
|
||||
isBare := t.gitUC.IsBareGitRepo(ctx)
|
||||
if isBare {
|
||||
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 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 && isRepo && t.useLocalBeads {
|
||||
commitResult, err := t.gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{
|
||||
BeadsDir: ".beads/",
|
||||
OptionalPaths: []string{
|
||||
config.SafeAgentsFile(),
|
||||
filepath.Join(".claude", "settings.json"),
|
||||
"CLAUDE.md",
|
||||
".gitignore",
|
||||
},
|
||||
Message: "bd init: initialize beads issue tracking",
|
||||
NoVerify: true,
|
||||
})
|
||||
switch {
|
||||
case err != nil && !in.quiet:
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", err)
|
||||
case err == nil && commitResult.DidCommit && !in.quiet:
|
||||
fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓"))
|
||||
}
|
||||
}
|
||||
|
||||
if isRepo && !in.quiet {
|
||||
if t.gitUC.HasAnyRemotes(ctx) && !t.gitUC.HasUpstream(ctx) {
|
||||
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,26 @@ 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
|
||||
}
|
||||
|
||||
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,24 +91,10 @@ 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
|
||||
func createReadme(beadsDir string) error {
|
||||
readmePath := filepath.Join(beadsDir, "README.md")
|
||||
|
||||
// Skip if already exists
|
||||
if _, err := os.Stat(readmePath); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
readmeTemplate := `# Beads - AI-Native Issue Tracking
|
||||
const BeadsReadmeTemplate = `# Beads - AI-Native Issue Tracking
|
||||
|
||||
Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code.
|
||||
|
||||
|
|
@ -183,9 +177,17 @@ bd create "Try out Beads"
|
|||
*Beads: Issue tracking that moves at the speed of thought* ⚡
|
||||
`
|
||||
|
||||
func createReadme(beadsDir string) error {
|
||||
readmePath := filepath.Join(beadsDir, "README.md")
|
||||
|
||||
// Skip if already exists
|
||||
if _, err := os.Stat(readmePath); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write README.md (0644 is standard for markdown files)
|
||||
// #nosec G306 - README needs to be readable
|
||||
if err := os.WriteFile(readmePath, []byte(readmeTemplate), 0644); err != nil {
|
||||
if err := os.WriteFile(readmePath, []byte(BeadsReadmeTemplate), 0644); err != nil {
|
||||
return fmt.Errorf("failed to write README.md: %w", err)
|
||||
}
|
||||
|
||||
|
|
|
|||
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
|
||||
serverMode bool
|
||||
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,
|
||||
)
|
||||
}
|
||||
254
internal/storage/domain/beads.go
Normal file
254
internal/storage/domain/beads.go
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
)
|
||||
|
||||
type BeadsDirFSRepository interface {
|
||||
ResolveBeadsDirPath(ctx context.Context) BeadsDirResolution
|
||||
BeadsDirIsLocal(ctx context.Context) bool
|
||||
|
||||
CreateBeadsDir(ctx context.Context) error
|
||||
BeadsDirExists(ctx context.Context) (bool, error)
|
||||
WriteBeadsGitignore(ctx context.Context) error
|
||||
BeadsGitignoreExists(ctx context.Context) (bool, error)
|
||||
WriteProjectGitignore(ctx context.Context) error
|
||||
ProjectGitignoreExists(ctx context.Context) (bool, error)
|
||||
WriteInteractionsLog(ctx context.Context) error
|
||||
WriteReadme(ctx context.Context) error
|
||||
WriteMetadataJSON(ctx context.Context, content []byte) error
|
||||
ReadMetadataJSON(ctx context.Context) ([]byte, error)
|
||||
WriteConfigYAML(ctx context.Context, content []byte) error
|
||||
ReadConfigYAML(ctx context.Context) ([]byte, error)
|
||||
ReadBeadsConfig(ctx context.Context) (*configfile.Config, error)
|
||||
}
|
||||
|
||||
type BeadsDirFSUseCase interface {
|
||||
ResolveBeadsDir(ctx context.Context) BeadsDirResolution
|
||||
ResolveProxiedInit(ctx context.Context, params ResolveProxiedInitParams) (ResolveProxiedInitResult, error)
|
||||
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 ResolveProxiedInitParams struct {
|
||||
Prefix string
|
||||
DBFlag string
|
||||
}
|
||||
|
||||
type ResolveProxiedInitResult struct {
|
||||
BeadsDir string
|
||||
HasExplicit bool
|
||||
IsLocal bool
|
||||
DBName string
|
||||
ProjectID string
|
||||
}
|
||||
|
||||
type BeadsDirTemplates struct {
|
||||
BeadsGitignore string
|
||||
ProjectGitignoreHeader string
|
||||
ProjectGitignorePatterns []string
|
||||
Readme string
|
||||
}
|
||||
|
||||
type InitializeBeadsDirParams struct {
|
||||
MetadataJSONBody []byte
|
||||
ConfigYAMLBody []byte
|
||||
WriteProjectGitignore bool
|
||||
SetNoCOW bool
|
||||
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
|
||||
}
|
||||
|
||||
type BeadsDirFSAdapters struct {
|
||||
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 {
|
||||
return u.fsRepo.ResolveBeadsDirPath(ctx)
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) ResolveProxiedInit(ctx context.Context, params ResolveProxiedInitParams) (ResolveProxiedInitResult, error) {
|
||||
resolution := u.fsRepo.ResolveBeadsDirPath(ctx)
|
||||
result := ResolveProxiedInitResult{
|
||||
BeadsDir: resolution.BeadsDir,
|
||||
HasExplicit: resolution.HasExplicit,
|
||||
IsLocal: u.fsRepo.BeadsDirIsLocal(ctx),
|
||||
}
|
||||
|
||||
cfg, err := u.fsRepo.ReadBeadsConfig(ctx)
|
||||
if err != nil {
|
||||
return ResolveProxiedInitResult{}, fmt.Errorf("ResolveProxiedInit: read config: %w", err)
|
||||
}
|
||||
|
||||
result.DBName = resolveDoltDatabaseName(cfg, params.Prefix, params.DBFlag)
|
||||
result.ProjectID = resolveProjectID(cfg)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func resolveDoltDatabaseName(cfg *configfile.Config, prefix, dbFlag string) string {
|
||||
if dbFlag != "" {
|
||||
return dbFlag
|
||||
}
|
||||
if cfg != nil && cfg.DoltDatabase != "" {
|
||||
return cfg.DoltDatabase
|
||||
}
|
||||
if prefix != "" {
|
||||
return strings.ReplaceAll(prefix, "-", "_")
|
||||
}
|
||||
return configfile.DefaultDoltDatabase
|
||||
}
|
||||
|
||||
func resolveProjectID(cfg *configfile.Config) string {
|
||||
if cfg != nil && cfg.ProjectID != "" {
|
||||
return cfg.ProjectID
|
||||
}
|
||||
return configfile.GenerateProjectID()
|
||||
}
|
||||
|
||||
func (u *beadsDirFSUseCaseImpl) InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error) {
|
||||
if err := u.fsRepo.CreateBeadsDir(ctx); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if err := u.fsRepo.WriteBeadsGitignore(ctx); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if len(params.MetadataJSONBody) > 0 {
|
||||
if err := u.fsRepo.WriteMetadataJSON(ctx, params.MetadataJSONBody); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
}
|
||||
if len(params.ConfigYAMLBody) > 0 {
|
||||
if err := u.fsRepo.WriteConfigYAML(ctx, params.ConfigYAMLBody); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
}
|
||||
if err := u.fsRepo.WriteInteractionsLog(ctx); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if err := u.fsRepo.WriteReadme(ctx); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
if params.WriteProjectGitignore {
|
||||
if err := u.fsRepo.WriteProjectGitignore(ctx); err != nil {
|
||||
return InitializeBeadsDirResult{}, err
|
||||
}
|
||||
}
|
||||
|
||||
var result InitializeBeadsDirResult
|
||||
if params.SetNoCOW && u.adapters.ApplyNoCOW != nil {
|
||||
result.NoCOWErr = u.adapters.ApplyNoCOW(u.fsRepo.ResolveBeadsDirPath(ctx).BeadsDir)
|
||||
}
|
||||
if params.LocalVersion != "" && u.adapters.WriteLocalVersion != nil {
|
||||
beadsDir := u.fsRepo.ResolveBeadsDirPath(ctx).BeadsDir
|
||||
result.LocalVersionErr = u.adapters.WriteLocalVersion(
|
||||
filepath.Join(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)
|
||||
|
|
@ -8,12 +11,9 @@ type ConfigSQLRepository interface {
|
|||
SetLocalMetadata(ctx context.Context, key, value string) error
|
||||
GetConfig(ctx context.Context, key string) (string, error)
|
||||
SetConfig(ctx context.Context, key, value string) error
|
||||
GetStatistics(ctx context.Context) (Statistics, error)
|
||||
}
|
||||
|
||||
type ConfigUseCase interface {
|
||||
ConfigureContributorMode(ctx context.Context, params ContributorModeParams) error
|
||||
ConfigureTeamMode(ctx context.Context, params TeamModeParams) error
|
||||
VerifyInit(ctx context.Context) (VerifyResult, error)
|
||||
}
|
||||
|
||||
|
|
@ -21,14 +21,47 @@ type Issue struct{}
|
|||
|
||||
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
|
||||
}
|
||||
|
|
|
|||
69
internal/storage/domain/db/config.go
Normal file
69
internal/storage/domain/db/config.go
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
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
|
||||
}
|
||||
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{})
|
||||
}
|
||||
262
internal/storage/domain/fs/beads.go
Normal file
262
internal/storage/domain/fs/beads.go
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
func NewBeadsDirFSRepository(workDir string, templates domain.BeadsDirTemplates) domain.BeadsDirFSRepository {
|
||||
beadsDir, hasExplicit := resolveBeadsDir(workDir)
|
||||
return &beadsDirFSRepositoryImpl{
|
||||
workDir: workDir,
|
||||
beadsDir: beadsDir,
|
||||
hasExplicit: hasExplicit,
|
||||
templates: templates,
|
||||
}
|
||||
}
|
||||
|
||||
type beadsDirFSRepositoryImpl struct {
|
||||
workDir string
|
||||
beadsDir string
|
||||
hasExplicit bool
|
||||
templates domain.BeadsDirTemplates
|
||||
}
|
||||
|
||||
var _ domain.BeadsDirFSRepository = (*beadsDirFSRepositoryImpl)(nil)
|
||||
|
||||
func resolveBeadsDir(workDir string) (string, bool) {
|
||||
if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" {
|
||||
return utils.CanonicalizePath(envBeadsDir), true
|
||||
}
|
||||
if dir := beads.GetWorktreeFallbackBeadsDir(); dir != "" {
|
||||
return dir, false
|
||||
}
|
||||
return beads.FollowRedirect(filepath.Join(workDir, ".beads")), false
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) ResolveBeadsDirPath(ctx context.Context) domain.BeadsDirResolution {
|
||||
return domain.BeadsDirResolution{BeadsDir: r.beadsDir, HasExplicit: r.hasExplicit}
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) BeadsDirIsLocal(ctx context.Context) bool {
|
||||
workDirAbs, err := filepath.Abs(r.workDir)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
beadsDirAbs, err := filepath.Abs(r.beadsDir)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(beadsDirAbs, filepath.Clean(workDirAbs)+string(filepath.Separator)) ||
|
||||
filepath.Clean(beadsDirAbs) == filepath.Clean(workDirAbs)
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) CreateBeadsDir(ctx context.Context) error {
|
||||
if r.beadsDir == "" {
|
||||
return fmt.Errorf("fs: CreateBeadsDir: beadsDir not resolved")
|
||||
}
|
||||
if err := os.MkdirAll(r.beadsDir, config.BeadsDirPerm); err != nil {
|
||||
return fmt.Errorf("fs: CreateBeadsDir: mkdir %s: %w", r.beadsDir, err)
|
||||
}
|
||||
if _, err := config.FixBeadsDirPermissions(r.beadsDir); err != nil {
|
||||
return fmt.Errorf("fs: CreateBeadsDir: fix perms %s: %w", r.beadsDir, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) BeadsDirExists(ctx context.Context) (bool, error) {
|
||||
info, err := os.Stat(r.beadsDir)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("fs: BeadsDirExists: stat %s: %w", r.beadsDir, err)
|
||||
}
|
||||
return info.IsDir(), nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteBeadsGitignore(ctx context.Context) error {
|
||||
if r.templates.BeadsGitignore == "" {
|
||||
return fmt.Errorf("fs: WriteBeadsGitignore: template not configured")
|
||||
}
|
||||
path := filepath.Join(r.beadsDir, ".gitignore")
|
||||
body := []byte(r.templates.BeadsGitignore)
|
||||
// #nosec G304 -- path joined under bound beadsDir
|
||||
if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, body) {
|
||||
return nil
|
||||
}
|
||||
if err := os.WriteFile(path, body, 0600); err != nil {
|
||||
return fmt.Errorf("fs: WriteBeadsGitignore: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) BeadsGitignoreExists(ctx context.Context) (bool, error) {
|
||||
return fileExists(filepath.Join(r.beadsDir, ".gitignore"), "fs: BeadsGitignoreExists")
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context) error {
|
||||
if r.workDir == "" {
|
||||
return fmt.Errorf("fs: WriteProjectGitignore: workDir not set")
|
||||
}
|
||||
if len(r.templates.ProjectGitignorePatterns) == 0 {
|
||||
return fmt.Errorf("fs: WriteProjectGitignore: patterns not configured")
|
||||
}
|
||||
path := filepath.Join(r.workDir, ".gitignore")
|
||||
// #nosec G304 -- path joined under bound workDir
|
||||
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 r.templates.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 header := r.templates.ProjectGitignoreHeader; header != "" && !containsLine(existing, header) {
|
||||
if len(existing) > 0 {
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
buf.WriteString(header + "\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) (bool, error) {
|
||||
return fileExists(filepath.Join(r.workDir, ".gitignore"), "fs: ProjectGitignoreExists")
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteInteractionsLog(ctx context.Context) error {
|
||||
path := filepath.Join(r.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) error {
|
||||
if r.templates.Readme == "" {
|
||||
return fmt.Errorf("fs: WriteReadme: template not configured")
|
||||
}
|
||||
path := filepath.Join(r.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(r.templates.Readme), 0644); err != nil {
|
||||
return fmt.Errorf("fs: WriteReadme: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *beadsDirFSRepositoryImpl) WriteMetadataJSON(ctx context.Context, content []byte) error {
|
||||
path := filepath.Join(r.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) ([]byte, error) {
|
||||
path := filepath.Join(r.beadsDir, "metadata.json")
|
||||
// #nosec G304 -- path joined under bound 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, content []byte) error {
|
||||
path := filepath.Join(r.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) ([]byte, error) {
|
||||
path := filepath.Join(r.beadsDir, "config.yaml")
|
||||
// #nosec G304 -- path joined under bound 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 (r *beadsDirFSRepositoryImpl) ReadBeadsConfig(ctx context.Context) (*configfile.Config, error) {
|
||||
if r.beadsDir == "" {
|
||||
return nil, fmt.Errorf("fs: ReadBeadsConfig: beadsDir not resolved")
|
||||
}
|
||||
cfg, err := configfile.Load(r.beadsDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fs: ReadBeadsConfig: %w", err)
|
||||
}
|
||||
return cfg, 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
|
||||
}
|
||||
445
internal/storage/domain/fs/beads_test.go
Normal file
445
internal/storage/domain/fs/beads_test.go
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
func (s *testSuite) TestBeadsDirFSRepository() {
|
||||
s.Run("CreateBeadsDir", func() {
|
||||
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("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)
|
||||
})
|
||||
s.Run("ReadBeadsConfig", func() {
|
||||
s.Run("MissingFileReturnsNil", s.readBeadsConfigMissing)
|
||||
s.Run("ParsesMetadataJSON", s.readBeadsConfigParses)
|
||||
})
|
||||
s.Run("ResolveBeadsDirPath", func() {
|
||||
s.Run("HonorsBeadsDirEnv", s.resolveBeadsDirPathHonorsEnv)
|
||||
s.Run("FallsBackToLocalDotBeads", s.resolveBeadsDirPathLocalFallback)
|
||||
})
|
||||
s.Run("BeadsDirIsLocal", func() {
|
||||
s.Run("TrueForWorkDirChild", s.beadsDirIsLocalTrue)
|
||||
s.Run("FalseForExplicitEnv", s.beadsDirIsLocalFalseEnv)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *testSuite) createBeadsDirCreates() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(repo.CreateBeadsDir(s.Ctx()))
|
||||
|
||||
info, err := os.Stat(beadsDir)
|
||||
s.Require().NoError(err)
|
||||
s.True(info.IsDir())
|
||||
|
||||
if runtime.GOOS != "windows" {
|
||||
s.Equal(config.BeadsDirPerm, info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) createBeadsDirIdempotent() {
|
||||
_, _, repo := s.newRepo()
|
||||
s.Require().NoError(repo.CreateBeadsDir(s.Ctx()))
|
||||
s.Require().NoError(repo.CreateBeadsDir(s.Ctx()))
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirExistsMissing() {
|
||||
_, _, repo := s.newRepo()
|
||||
exists, err := repo.BeadsDirExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirExistsPresent() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
exists, err := repo.BeadsDirExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirExistsIsFile() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.WriteFile(beadsDir, []byte("not a dir"), 0600))
|
||||
exists, err := repo.BeadsDirExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeBeadsGitignoreWrites() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
s.Require().NoError(repo.WriteBeadsGitignore(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(beadsDir, ".gitignore"))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(testTemplates().BeadsGitignore, string(data))
|
||||
}
|
||||
|
||||
func (s *testSuite) writeBeadsGitignoreIdempotent() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
path := filepath.Join(beadsDir, ".gitignore")
|
||||
s.Require().NoError(os.WriteFile(path, []byte(testTemplates().BeadsGitignore), 0600))
|
||||
|
||||
before, err := os.Stat(path)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(repo.WriteBeadsGitignore(s.Ctx()))
|
||||
|
||||
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() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
path := filepath.Join(beadsDir, ".gitignore")
|
||||
s.Require().NoError(os.WriteFile(path, []byte("stale\n"), 0600))
|
||||
|
||||
s.Require().NoError(repo.WriteBeadsGitignore(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(testTemplates().BeadsGitignore, string(data))
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsGitignoreExistsMissing() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
exists, err := repo.BeadsGitignoreExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsGitignoreExistsPresent() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
s.Require().NoError(os.WriteFile(filepath.Join(beadsDir, ".gitignore"), []byte("x"), 0600))
|
||||
exists, err := repo.BeadsGitignoreExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreCreates() {
|
||||
workDir, _, repo := s.newRepo()
|
||||
s.Require().NoError(repo.WriteProjectGitignore(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(workDir, ".gitignore"))
|
||||
s.Require().NoError(err)
|
||||
body := string(data)
|
||||
|
||||
tpl := testTemplates()
|
||||
s.Contains(body, tpl.ProjectGitignoreHeader)
|
||||
for _, pattern := range tpl.ProjectGitignorePatterns {
|
||||
s.Contains(body, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreAppends() {
|
||||
workDir, _, repo := s.newRepo()
|
||||
path := filepath.Join(workDir, ".gitignore")
|
||||
preexisting := "node_modules/\n*.log\n"
|
||||
s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644))
|
||||
|
||||
s.Require().NoError(repo.WriteProjectGitignore(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
body := string(data)
|
||||
|
||||
tpl := testTemplates()
|
||||
s.True(strings.HasPrefix(body, preexisting), "preexisting content must be preserved at the top")
|
||||
s.Contains(body, tpl.ProjectGitignoreHeader)
|
||||
for _, pattern := range tpl.ProjectGitignorePatterns {
|
||||
s.Contains(body, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) writeProjectGitignoreNoDuplicates() {
|
||||
workDir, _, repo := s.newRepo()
|
||||
path := filepath.Join(workDir, ".gitignore")
|
||||
preexisting := ".dolt/\nnode_modules/\n"
|
||||
s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644))
|
||||
|
||||
s.Require().NoError(repo.WriteProjectGitignore(s.Ctx()))
|
||||
|
||||
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() {
|
||||
workDir, _, repo := s.newRepo()
|
||||
path := filepath.Join(workDir, ".gitignore")
|
||||
tpl := testTemplates()
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("existing\n")
|
||||
buf.WriteString(tpl.ProjectGitignoreHeader + "\n")
|
||||
for _, pattern := range tpl.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(repo.WriteProjectGitignore(s.Ctx()))
|
||||
|
||||
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() {
|
||||
workDir, _, repo := s.newRepo()
|
||||
path := filepath.Join(workDir, ".gitignore")
|
||||
s.Require().NoError(os.WriteFile(path, []byte("no-trailing-newline"), 0644))
|
||||
|
||||
s.Require().NoError(repo.WriteProjectGitignore(s.Ctx()))
|
||||
|
||||
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, testTemplates().ProjectGitignoreHeader)
|
||||
}
|
||||
|
||||
func (s *testSuite) projectGitignoreExistsMissing() {
|
||||
_, _, repo := s.newRepo()
|
||||
exists, err := repo.ProjectGitignoreExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) projectGitignoreExistsPresent() {
|
||||
workDir, _, repo := s.newRepo()
|
||||
s.Require().NoError(os.WriteFile(filepath.Join(workDir, ".gitignore"), []byte("x"), 0644))
|
||||
exists, err := repo.ProjectGitignoreExists(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(exists)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeInteractionsLogCreates() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
s.Require().NoError(repo.WriteInteractionsLog(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(beadsDir, "interactions.jsonl"))
|
||||
s.Require().NoError(err)
|
||||
s.Empty(data)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeInteractionsLogPreserves() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
path := filepath.Join(beadsDir, "interactions.jsonl")
|
||||
existing := []byte(`{"event":"x"}` + "\n")
|
||||
s.Require().NoError(os.WriteFile(path, existing, 0644))
|
||||
|
||||
s.Require().NoError(repo.WriteInteractionsLog(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(existing, data)
|
||||
}
|
||||
|
||||
func (s *testSuite) writeReadmeCreates() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
s.Require().NoError(repo.WriteReadme(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(beadsDir, "README.md"))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(testTemplates().Readme, string(data))
|
||||
}
|
||||
|
||||
func (s *testSuite) writeReadmePreserves() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
path := filepath.Join(beadsDir, "README.md")
|
||||
custom := []byte("# My custom readme\n")
|
||||
s.Require().NoError(os.WriteFile(path, custom, 0644))
|
||||
|
||||
s.Require().NoError(repo.WriteReadme(s.Ctx()))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(custom, data)
|
||||
}
|
||||
|
||||
func (s *testSuite) readMetadataJSONMissing() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
data, err := repo.ReadMetadataJSON(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Nil(data)
|
||||
}
|
||||
|
||||
func (s *testSuite) metadataJSONRoundTrip() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
body := []byte(`{"_project_id":"abc-123"}`)
|
||||
|
||||
s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), body))
|
||||
|
||||
got, err := repo.ReadMetadataJSON(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Equal(body, got)
|
||||
}
|
||||
|
||||
func (s *testSuite) metadataJSONOverwrite() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), []byte(`{"v":1}`)))
|
||||
s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), []byte(`{"v":2}`)))
|
||||
|
||||
got, err := repo.ReadMetadataJSON(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]byte(`{"v":2}`), got)
|
||||
}
|
||||
|
||||
func (s *testSuite) readConfigYAMLMissing() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
data, err := repo.ReadConfigYAML(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Nil(data)
|
||||
}
|
||||
|
||||
func (s *testSuite) configYAMLRoundTrip() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
body := []byte("issue_prefix: bd\n")
|
||||
|
||||
s.Require().NoError(repo.WriteConfigYAML(s.Ctx(), body))
|
||||
|
||||
got, err := repo.ReadConfigYAML(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Equal(body, got)
|
||||
}
|
||||
|
||||
func (s *testSuite) configYAMLOverwrite() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
s.Require().NoError(repo.WriteConfigYAML(s.Ctx(), []byte("v: 1\n")))
|
||||
s.Require().NoError(repo.WriteConfigYAML(s.Ctx(), []byte("v: 2\n")))
|
||||
|
||||
got, err := repo.ReadConfigYAML(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]byte("v: 2\n"), got)
|
||||
}
|
||||
|
||||
func (s *testSuite) readBeadsConfigMissing() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
cfg, err := repo.ReadBeadsConfig(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Nil(cfg)
|
||||
}
|
||||
|
||||
func (s *testSuite) readBeadsConfigParses() {
|
||||
_, beadsDir, repo := s.newRepo()
|
||||
s.Require().NoError(os.MkdirAll(beadsDir, 0700))
|
||||
body := []byte(`{"dolt_database":"my_db","project_id":"pid-123"}`)
|
||||
s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), body))
|
||||
|
||||
cfg, err := repo.ReadBeadsConfig(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotNil(cfg)
|
||||
s.Equal("my_db", cfg.DoltDatabase)
|
||||
s.Equal("pid-123", cfg.ProjectID)
|
||||
}
|
||||
|
||||
func (s *testSuite) resolveBeadsDirPathHonorsEnv() {
|
||||
envDir := s.T().TempDir()
|
||||
s.T().Setenv("BEADS_DIR", envDir)
|
||||
|
||||
workDir := s.T().TempDir()
|
||||
repo := NewBeadsDirFSRepository(workDir, testTemplates())
|
||||
|
||||
res := repo.ResolveBeadsDirPath(s.Ctx())
|
||||
s.True(res.HasExplicit)
|
||||
s.NotEmpty(res.BeadsDir)
|
||||
}
|
||||
|
||||
func (s *testSuite) resolveBeadsDirPathLocalFallback() {
|
||||
workDir, beadsDir, repo := s.newRepo()
|
||||
|
||||
res := repo.ResolveBeadsDirPath(s.Ctx())
|
||||
s.False(res.HasExplicit)
|
||||
// When BEADS_DIR is unset and we're outside a git worktree, the fallback is
|
||||
// workDir/.beads (FollowRedirect leaves the path unchanged when no redirect).
|
||||
s.Equal(beadsDir, res.BeadsDir)
|
||||
_ = workDir
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirIsLocalTrue() {
|
||||
_, _, repo := s.newRepo()
|
||||
s.True(repo.BeadsDirIsLocal(s.Ctx()))
|
||||
}
|
||||
|
||||
func (s *testSuite) beadsDirIsLocalFalseEnv() {
|
||||
envDir := s.T().TempDir()
|
||||
s.T().Setenv("BEADS_DIR", envDir)
|
||||
|
||||
workDir := s.T().TempDir()
|
||||
repo := NewBeadsDirFSRepository(workDir, testTemplates())
|
||||
|
||||
s.False(repo.BeadsDirIsLocal(s.Ctx()), "explicit BEADS_DIR outside workDir is not local")
|
||||
}
|
||||
|
||||
// statically assert the BeadsDirTemplates type is reachable for downstream callers.
|
||||
var _ = domain.BeadsDirTemplates{}
|
||||
41
internal/storage/domain/fs/suite_test.go
Normal file
41
internal/storage/domain/fs/suite_test.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
type testSuite struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
func (s *testSuite) Ctx() context.Context {
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func (s *testSuite) newRepo() (workDir, beadsDir string, repo domain.BeadsDirFSRepository) {
|
||||
s.T().Helper()
|
||||
s.T().Setenv("BEADS_DIR", "")
|
||||
workDir = s.T().TempDir()
|
||||
beadsDir = filepath.Join(workDir, ".beads")
|
||||
repo = NewBeadsDirFSRepository(workDir, testTemplates())
|
||||
return
|
||||
}
|
||||
|
||||
func testTemplates() domain.BeadsDirTemplates {
|
||||
return domain.BeadsDirTemplates{
|
||||
BeadsGitignore: "# test beads gitignore\ndolt/\n",
|
||||
ProjectGitignoreHeader: "# Beads test header",
|
||||
ProjectGitignorePatterns: []string{".dolt/", "*.db"},
|
||||
Readme: "# test readme\n",
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainFS(t *testing.T) {
|
||||
suite.Run(t, &testSuite{})
|
||||
}
|
||||
211
internal/storage/domain/git.go
Normal file
211
internal/storage/domain/git.go
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type GitRepository interface {
|
||||
IsGitRepo(ctx context.Context) (bool, error)
|
||||
IsBareGitRepo(ctx context.Context) (bool, error)
|
||||
IsJujutsuRepo(ctx context.Context) (bool, error)
|
||||
IsColocatedJJGit(ctx context.Context) (bool, error)
|
||||
|
||||
Init(ctx context.Context) error
|
||||
|
||||
GetConfig(ctx context.Context, key string) (value string, found bool, err error)
|
||||
SetConfig(ctx context.Context, key, value string) error
|
||||
|
||||
GetRemoteURL(ctx context.Context, name string) (url string, found bool, err error)
|
||||
ListRemoteNames(ctx context.Context) ([]string, error)
|
||||
|
||||
CurrentBranch(ctx context.Context) (string, error)
|
||||
BranchHasUpstream(ctx context.Context, branch string) (bool, error)
|
||||
|
||||
Add(ctx context.Context, paths ...string) error
|
||||
Commit(ctx context.Context, params GitCommitParams) (GitCommitResult, error)
|
||||
}
|
||||
|
||||
type GitCommitParams struct {
|
||||
Message string
|
||||
NoVerify bool
|
||||
}
|
||||
|
||||
type GitCommitResult struct {
|
||||
DidCommit bool
|
||||
Output []byte
|
||||
}
|
||||
|
||||
type GitUseCase interface {
|
||||
IsGitRepo(ctx context.Context) bool
|
||||
IsBareGitRepo(ctx context.Context) bool
|
||||
IsJujutsuRepo(ctx context.Context) bool
|
||||
IsColocatedJJGit(ctx context.Context) bool
|
||||
|
||||
EnsureGitRepo(ctx context.Context) (EnsureGitRepoResult, error)
|
||||
OriginRemoteURL(ctx context.Context) (string, error)
|
||||
DetectFork(ctx context.Context) (isFork bool, upstreamURL string, err error)
|
||||
|
||||
BeadsRole(ctx context.Context) (role string, hasRole bool, err error)
|
||||
SetBeadsRole(ctx context.Context, role string) error
|
||||
|
||||
HasAnyRemotes(ctx context.Context) bool
|
||||
HasUpstream(ctx context.Context) bool
|
||||
|
||||
CommitInitArtifacts(ctx context.Context, params CommitInitArtifactsParams) (CommitInitArtifactsResult, error)
|
||||
}
|
||||
|
||||
type EnsureGitRepoResult struct {
|
||||
DidInit bool
|
||||
AlreadyExists bool
|
||||
}
|
||||
|
||||
type CommitInitArtifactsParams struct {
|
||||
BeadsDir string
|
||||
OptionalPaths []string
|
||||
Message string
|
||||
NoVerify bool
|
||||
}
|
||||
|
||||
type CommitInitArtifactsResult struct {
|
||||
StagedPaths []string
|
||||
DidCommit bool
|
||||
}
|
||||
|
||||
const beadsRoleConfigKey = "beads.role"
|
||||
|
||||
func NewGitUseCase(workDir string, repo GitRepository) GitUseCase {
|
||||
return &gitUseCaseImpl{workDir: workDir, repo: repo}
|
||||
}
|
||||
|
||||
type gitUseCaseImpl struct {
|
||||
workDir string
|
||||
repo GitRepository
|
||||
}
|
||||
|
||||
var _ GitUseCase = (*gitUseCaseImpl)(nil)
|
||||
|
||||
func (u *gitUseCaseImpl) IsGitRepo(ctx context.Context) bool {
|
||||
ok, _ := u.repo.IsGitRepo(ctx)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) IsBareGitRepo(ctx context.Context) bool {
|
||||
ok, _ := u.repo.IsBareGitRepo(ctx)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) IsJujutsuRepo(ctx context.Context) bool {
|
||||
ok, _ := u.repo.IsJujutsuRepo(ctx)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) IsColocatedJJGit(ctx context.Context) bool {
|
||||
ok, _ := u.repo.IsColocatedJJGit(ctx)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) EnsureGitRepo(ctx context.Context) (EnsureGitRepoResult, error) {
|
||||
exists, err := u.repo.IsGitRepo(ctx)
|
||||
if err != nil {
|
||||
return EnsureGitRepoResult{}, fmt.Errorf("EnsureGitRepo: check: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return EnsureGitRepoResult{AlreadyExists: true}, nil
|
||||
}
|
||||
if err := u.repo.Init(ctx); err != nil {
|
||||
return EnsureGitRepoResult{}, fmt.Errorf("EnsureGitRepo: init: %w", err)
|
||||
}
|
||||
return EnsureGitRepoResult{DidInit: true}, nil
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) OriginRemoteURL(ctx context.Context) (string, error) {
|
||||
isRepo, err := u.repo.IsGitRepo(ctx)
|
||||
if err != nil || !isRepo {
|
||||
return "", err
|
||||
}
|
||||
bare, err := u.repo.IsBareGitRepo(ctx)
|
||||
if err != nil || bare {
|
||||
return "", err
|
||||
}
|
||||
url, _, err := u.repo.GetRemoteURL(ctx, "origin")
|
||||
return url, err
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) DetectFork(ctx context.Context) (bool, string, error) {
|
||||
isRepo, err := u.repo.IsGitRepo(ctx)
|
||||
if err != nil || !isRepo {
|
||||
return false, "", err
|
||||
}
|
||||
url, found, err := u.repo.GetRemoteURL(ctx, "upstream")
|
||||
if err != nil || !found {
|
||||
return false, "", err
|
||||
}
|
||||
return true, url, nil
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) BeadsRole(ctx context.Context) (string, bool, error) {
|
||||
return u.repo.GetConfig(ctx, beadsRoleConfigKey)
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) SetBeadsRole(ctx context.Context, role string) error {
|
||||
if role == "" {
|
||||
return fmt.Errorf("SetBeadsRole: role must not be empty")
|
||||
}
|
||||
return u.repo.SetConfig(ctx, beadsRoleConfigKey, role)
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) HasAnyRemotes(ctx context.Context) bool {
|
||||
names, err := u.repo.ListRemoteNames(ctx)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return len(names) > 0
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) HasUpstream(ctx context.Context) bool {
|
||||
branch, err := u.repo.CurrentBranch(ctx)
|
||||
if err != nil || branch == "" {
|
||||
return false
|
||||
}
|
||||
ok, err := u.repo.BranchHasUpstream(ctx, branch)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
func (u *gitUseCaseImpl) CommitInitArtifacts(ctx context.Context, params CommitInitArtifactsParams) (CommitInitArtifactsResult, error) {
|
||||
if params.BeadsDir == "" {
|
||||
return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: BeadsDir must not be empty")
|
||||
}
|
||||
if params.Message == "" {
|
||||
return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: Message must not be empty")
|
||||
}
|
||||
|
||||
paths := []string{params.BeadsDir}
|
||||
for _, p := range params.OptionalPaths {
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
statPath := p
|
||||
if !filepath.IsAbs(statPath) {
|
||||
statPath = filepath.Join(u.workDir, statPath)
|
||||
}
|
||||
if _, err := os.Stat(statPath); err == nil {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
}
|
||||
|
||||
if err := u.repo.Add(ctx, paths...); err != nil {
|
||||
return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: add: %w", err)
|
||||
}
|
||||
|
||||
commit, err := u.repo.Commit(ctx, GitCommitParams{Message: params.Message, NoVerify: params.NoVerify})
|
||||
if err != nil {
|
||||
return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: commit: %w", err)
|
||||
}
|
||||
return CommitInitArtifactsResult{StagedPaths: paths, DidCommit: commit.DidCommit}, nil
|
||||
}
|
||||
216
internal/storage/domain/git/git.go
Normal file
216
internal/storage/domain/git/git.go
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
package git
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
internalgit "github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
func NewGitRepository(workDir string) domain.GitRepository {
|
||||
return &gitRepositoryImpl{workDir: workDir}
|
||||
}
|
||||
|
||||
type gitRepositoryImpl struct {
|
||||
workDir string
|
||||
}
|
||||
|
||||
var _ domain.GitRepository = (*gitRepositoryImpl)(nil)
|
||||
|
||||
func (r *gitRepositoryImpl) gitCmd(ctx context.Context, args ...string) *exec.Cmd {
|
||||
cmd := exec.CommandContext(ctx, "git", args...)
|
||||
cmd.Dir = r.workDir
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) IsGitRepo(ctx context.Context) (bool, error) {
|
||||
if err := r.gitCmd(ctx, "rev-parse", "--git-dir").Run(); err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("git: IsGitRepo: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) IsBareGitRepo(ctx context.Context) (bool, error) {
|
||||
out, err := r.gitCmd(ctx, "rev-parse", "--is-bare-repository").Output()
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("git: IsBareGitRepo: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(out)) == "true", nil
|
||||
}
|
||||
|
||||
// IsJujutsuRepo walks upward from workDir looking for a .jj directory.
|
||||
// Mirrors the boundary rule in internal/git.GetJujutsuRoot: a .git directory
|
||||
// found before .jj terminates the walk so a nested git repo does not inherit
|
||||
// an ancestor JJ workspace.
|
||||
func (r *gitRepositoryImpl) IsJujutsuRepo(ctx context.Context) (bool, error) {
|
||||
dir, err := filepath.Abs(r.workDir)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("git: IsJujutsuRepo: abs %s: %w", r.workDir, err)
|
||||
}
|
||||
for {
|
||||
if info, err := os.Stat(filepath.Join(dir, ".jj")); err == nil && info.IsDir() {
|
||||
return true, nil
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil {
|
||||
return false, nil
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
return false, nil
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) IsColocatedJJGit(ctx context.Context) (bool, error) {
|
||||
isJJ, err := r.IsJujutsuRepo(ctx)
|
||||
if err != nil || !isJJ {
|
||||
return false, err
|
||||
}
|
||||
return r.IsGitRepo(ctx)
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) Init(ctx context.Context) error {
|
||||
out, err := r.gitCmd(ctx, "init").CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git: Init: %w: %s", err, bytes.TrimSpace(out))
|
||||
}
|
||||
internalgit.ResetCaches()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string, bool, error) {
|
||||
if key == "" {
|
||||
return "", false, fmt.Errorf("git: GetConfig: key must not be empty")
|
||||
}
|
||||
out, err := r.gitCmd(ctx, "config", "--get", key).Output()
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return "", false, nil
|
||||
}
|
||||
return "", false, fmt.Errorf("git: GetConfig %s: %w", key, err)
|
||||
}
|
||||
value := strings.TrimSpace(string(out))
|
||||
if value == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) error {
|
||||
if key == "" {
|
||||
return fmt.Errorf("git: SetConfig: key must not be empty")
|
||||
}
|
||||
out, err := r.gitCmd(ctx, "config", key, value).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git: SetConfig %s: %w: %s", key, err, bytes.TrimSpace(out))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) GetRemoteURL(ctx context.Context, name string) (string, bool, error) {
|
||||
if name == "" {
|
||||
return "", false, fmt.Errorf("git: GetRemoteURL: name must not be empty")
|
||||
}
|
||||
out, err := r.gitCmd(ctx, "remote", "get-url", name).Output()
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return "", false, nil
|
||||
}
|
||||
return "", false, fmt.Errorf("git: GetRemoteURL %s: %w", name, err)
|
||||
}
|
||||
url := strings.TrimSpace(string(out))
|
||||
if url == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
return url, true, nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) ListRemoteNames(ctx context.Context) ([]string, error) {
|
||||
out, err := r.gitCmd(ctx, "remote").Output()
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("git: ListRemoteNames: %w", err)
|
||||
}
|
||||
trimmed := strings.TrimSpace(string(out))
|
||||
if trimmed == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return strings.Split(trimmed, "\n"), nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) CurrentBranch(ctx context.Context) (string, error) {
|
||||
out, err := r.gitCmd(ctx, "symbolic-ref", "--short", "HEAD").Output()
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("git: CurrentBranch: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(out)), nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) BranchHasUpstream(ctx context.Context, branch string) (bool, error) {
|
||||
if branch == "" {
|
||||
return false, fmt.Errorf("git: BranchHasUpstream: branch must not be empty")
|
||||
}
|
||||
if err := r.gitCmd(ctx, "config", "--get", "branch."+branch+".remote").Run(); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
if err := r.gitCmd(ctx, "config", "--get", "branch."+branch+".merge").Run(); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) Add(ctx context.Context, paths ...string) error {
|
||||
if len(paths) == 0 {
|
||||
return fmt.Errorf("git: Add: at least one path required")
|
||||
}
|
||||
args := append([]string{"add", "--"}, paths...)
|
||||
out, err := r.gitCmd(ctx, args...).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git: Add: %w: %s", err, bytes.TrimSpace(out))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepositoryImpl) Commit(ctx context.Context, params domain.GitCommitParams) (domain.GitCommitResult, error) {
|
||||
if params.Message == "" {
|
||||
return domain.GitCommitResult{}, fmt.Errorf("git: Commit: Message must not be empty")
|
||||
}
|
||||
args := []string{"commit"}
|
||||
if params.NoVerify {
|
||||
args = append(args, "--no-verify")
|
||||
}
|
||||
args = append(args, "-m", params.Message)
|
||||
out, err := r.gitCmd(ctx, args...).CombinedOutput()
|
||||
if err != nil {
|
||||
if bytes.Contains(out, []byte("nothing to commit")) || bytes.Contains(out, []byte("no changes added to commit")) {
|
||||
return domain.GitCommitResult{DidCommit: false, Output: out}, nil
|
||||
}
|
||||
return domain.GitCommitResult{Output: out}, fmt.Errorf("git: Commit: %w: %s", err, bytes.TrimSpace(out))
|
||||
}
|
||||
return domain.GitCommitResult{DidCommit: true, Output: out}, nil
|
||||
}
|
||||
221
internal/storage/domain/git/git_test.go
Normal file
221
internal/storage/domain/git/git_test.go
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
package git
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
func (s *testSuite) TestIsGitRepo_FalseOutsideRepo() {
|
||||
ok, err := s.repo.IsGitRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsGitRepo_TrueInsideRepo() {
|
||||
s.gitInit()
|
||||
ok, err := s.repo.IsGitRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsBareGitRepo_FalseForRegularRepo() {
|
||||
s.gitInit()
|
||||
bare, err := s.repo.IsBareGitRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(bare)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsBareGitRepo_FalseOutsideRepo() {
|
||||
bare, err := s.repo.IsBareGitRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(bare)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestInit_CreatesRepo() {
|
||||
s.Require().NoError(s.repo.Init(s.Ctx()))
|
||||
ok, err := s.repo.IsGitRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestConfig_GetMissing() {
|
||||
s.gitInit()
|
||||
value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role")
|
||||
s.Require().NoError(err)
|
||||
s.False(found)
|
||||
s.Empty(value)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestConfig_RoundTrip() {
|
||||
s.gitInit()
|
||||
s.Require().NoError(s.repo.SetConfig(s.Ctx(), "beads.role", "maintainer"))
|
||||
|
||||
value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role")
|
||||
s.Require().NoError(err)
|
||||
s.True(found)
|
||||
s.Equal("maintainer", value)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestConfig_SetEmptyKeyErrors() {
|
||||
s.gitInit()
|
||||
err := s.repo.SetConfig(s.Ctx(), "", "x")
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestRemote_GetMissing() {
|
||||
s.gitInit()
|
||||
url, found, err := s.repo.GetRemoteURL(s.Ctx(), "origin")
|
||||
s.Require().NoError(err)
|
||||
s.False(found)
|
||||
s.Empty(url)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestRemote_AddedRemoteVisible() {
|
||||
s.gitInit()
|
||||
s.run("git", "remote", "add", "origin", "https://example.com/repo.git")
|
||||
|
||||
url, found, err := s.repo.GetRemoteURL(s.Ctx(), "origin")
|
||||
s.Require().NoError(err)
|
||||
s.True(found)
|
||||
s.Equal("https://example.com/repo.git", url)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestRemote_ListEmpty() {
|
||||
s.gitInit()
|
||||
names, err := s.repo.ListRemoteNames(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Empty(names)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestRemote_ListMultiple() {
|
||||
s.gitInit()
|
||||
s.run("git", "remote", "add", "origin", "https://example.com/a.git")
|
||||
s.run("git", "remote", "add", "upstream", "https://example.com/b.git")
|
||||
|
||||
names, err := s.repo.ListRemoteNames(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.ElementsMatch([]string{"origin", "upstream"}, names)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestCurrentBranch_NoErrorOnFreshRepo() {
|
||||
s.gitInit()
|
||||
_, err := s.repo.CurrentBranch(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestBranchHasUpstream_FalseWhenUnset() {
|
||||
s.gitInit()
|
||||
s.writeFile("a.txt", "x")
|
||||
s.run("git", "add", "a.txt")
|
||||
s.run("git", "commit", "-q", "-m", "init")
|
||||
|
||||
branch, err := s.repo.CurrentBranch(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(branch)
|
||||
|
||||
has, err := s.repo.BranchHasUpstream(s.Ctx(), branch)
|
||||
s.Require().NoError(err)
|
||||
s.False(has)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestBranchHasUpstream_TrueWhenSet() {
|
||||
s.gitInit()
|
||||
s.writeFile("a.txt", "x")
|
||||
s.run("git", "add", "a.txt")
|
||||
s.run("git", "commit", "-q", "-m", "init")
|
||||
|
||||
branch, err := s.repo.CurrentBranch(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.run("git", "config", "branch."+branch+".remote", "origin")
|
||||
s.run("git", "config", "branch."+branch+".merge", "refs/heads/"+branch)
|
||||
|
||||
has, err := s.repo.BranchHasUpstream(s.Ctx(), branch)
|
||||
s.Require().NoError(err)
|
||||
s.True(has)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestAdd_StageAndCommitFile() {
|
||||
s.gitInit()
|
||||
s.writeFile("a.txt", "x")
|
||||
|
||||
s.Require().NoError(s.repo.Add(s.Ctx(), "a.txt"))
|
||||
result, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "test"})
|
||||
s.Require().NoError(err)
|
||||
s.True(result.DidCommit)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestCommit_NoVerifyBypassesHook() {
|
||||
s.gitInit()
|
||||
hookPath := filepath.Join(s.tmpDir, ".git", "hooks", "pre-commit")
|
||||
s.Require().NoError(os.WriteFile(hookPath, []byte("#!/bin/sh\nexit 1\n"), 0755)) //nolint:gosec // test hook
|
||||
s.writeFile("a.txt", "x")
|
||||
s.Require().NoError(s.repo.Add(s.Ctx(), "a.txt"))
|
||||
|
||||
result, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "test", NoVerify: true})
|
||||
s.Require().NoError(err)
|
||||
s.True(result.DidCommit)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestCommit_NothingToCommitDidCommitFalse() {
|
||||
s.gitInit()
|
||||
s.writeFile("a.txt", "x")
|
||||
s.Require().NoError(s.repo.Add(s.Ctx(), "a.txt"))
|
||||
_, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "first"})
|
||||
s.Require().NoError(err)
|
||||
|
||||
result, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "second"})
|
||||
s.Require().NoError(err)
|
||||
s.False(result.DidCommit)
|
||||
s.True(strings.Contains(string(result.Output), "nothing to commit"))
|
||||
}
|
||||
|
||||
func (s *testSuite) TestAdd_EmptyPathsErrors() {
|
||||
s.gitInit()
|
||||
err := s.repo.Add(s.Ctx())
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsJujutsuRepo_FalseOnTempDir() {
|
||||
ok, err := s.repo.IsJujutsuRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsJujutsuRepo_TrueWhenJJDirPresent() {
|
||||
s.Require().NoError(os.MkdirAll(filepath.Join(s.tmpDir, ".jj"), 0700))
|
||||
ok, err := s.repo.IsJujutsuRepo(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsColocatedJJGit_FalseOnTempDir() {
|
||||
s.gitInit()
|
||||
ok, err := s.repo.IsColocatedJJGit(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.False(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestIsColocatedJJGit_TrueWhenBothPresent() {
|
||||
s.gitInit()
|
||||
s.Require().NoError(os.MkdirAll(filepath.Join(s.tmpDir, ".jj"), 0700))
|
||||
ok, err := s.repo.IsColocatedJJGit(s.Ctx())
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
}
|
||||
|
||||
func (s *testSuite) TestExec_HappensInWorkDir() {
|
||||
// Confirms cmd.Dir is honored: chdir away, then init via repo bound to tmpDir.
|
||||
wd, err := os.Getwd()
|
||||
s.Require().NoError(err)
|
||||
defer func() { _ = os.Chdir(wd) }()
|
||||
s.Require().NoError(os.Chdir(s.T().TempDir())) // unrelated working directory
|
||||
|
||||
s.Require().NoError(s.repo.Init(s.Ctx()))
|
||||
|
||||
info, err := os.Stat(filepath.Join(s.tmpDir, ".git"))
|
||||
s.Require().NoError(err)
|
||||
s.True(info.IsDir())
|
||||
}
|
||||
58
internal/storage/domain/git/suite_test.go
Normal file
58
internal/storage/domain/git/suite_test.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
)
|
||||
|
||||
type testSuite struct {
|
||||
suite.Suite
|
||||
repo domain.GitRepository
|
||||
tmpDir string
|
||||
}
|
||||
|
||||
func (s *testSuite) SetupSuite() {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
s.T().Skip("git binary not found")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSuite) SetupTest() {
|
||||
s.tmpDir = s.T().TempDir()
|
||||
s.repo = NewGitRepository(s.tmpDir)
|
||||
}
|
||||
|
||||
func (s *testSuite) Ctx() context.Context {
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func (s *testSuite) gitInit() {
|
||||
s.T().Helper()
|
||||
s.run("git", "init", "-q")
|
||||
s.run("git", "config", "user.email", "test@example.com")
|
||||
s.run("git", "config", "user.name", "test")
|
||||
s.run("git", "config", "commit.gpgsign", "false")
|
||||
}
|
||||
|
||||
func (s *testSuite) run(name string, args ...string) {
|
||||
s.T().Helper()
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd.Dir = s.tmpDir
|
||||
s.Require().NoError(cmd.Run())
|
||||
}
|
||||
|
||||
func (s *testSuite) writeFile(rel, body string) {
|
||||
s.T().Helper()
|
||||
s.Require().NoError(os.WriteFile(filepath.Join(s.tmpDir, rel), []byte(body), 0600))
|
||||
}
|
||||
|
||||
func TestDomainGit(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
|
||||
}
|
||||
|
|
|
|||
37
internal/storage/fs/provider.go
Normal file
37
internal/storage/fs/provider.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
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(workDir string, templates domain.BeadsDirTemplates, adapters domain.BeadsDirFSAdapters) FileSystemProvider {
|
||||
return &fileSystemProviderImpl{
|
||||
workDir: workDir,
|
||||
templates: templates,
|
||||
adapters: adapters,
|
||||
}
|
||||
}
|
||||
|
||||
type fileSystemProviderImpl struct {
|
||||
workDir string
|
||||
templates domain.BeadsDirTemplates
|
||||
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.workDir, p.templates),
|
||||
p.adapters,
|
||||
)
|
||||
}
|
||||
return p.beadsDirFSUseCase
|
||||
}
|
||||
28
internal/storage/git/provider.go
Normal file
28
internal/storage/git/provider.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package git
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
domaingit "github.com/steveyegge/beads/internal/storage/domain/git"
|
||||
)
|
||||
|
||||
type GitProvider interface {
|
||||
GitUseCase() domain.GitUseCase
|
||||
}
|
||||
|
||||
func NewGitProvider(workDir string) GitProvider {
|
||||
return &gitProviderImpl{workDir: workDir}
|
||||
}
|
||||
|
||||
type gitProviderImpl struct {
|
||||
workDir string
|
||||
gitUseCase domain.GitUseCase
|
||||
}
|
||||
|
||||
var _ GitProvider = (*gitProviderImpl)(nil)
|
||||
|
||||
func (p *gitProviderImpl) GitUseCase() domain.GitUseCase {
|
||||
if p.gitUseCase == nil {
|
||||
p.gitUseCase = domain.NewGitUseCase(p.workDir, domaingit.NewGitRepository(p.workDir))
|
||||
}
|
||||
return p.gitUseCase
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
@ -153,8 +166,6 @@ func openDB(ctx context.Context, dsn string) (*sql.DB, error) {
|
|||
func (p *doltServerProvider) initSchema(ctx context.Context, database string) error {
|
||||
bo := backoff.NewExponentialBackOff()
|
||||
bo.InitialInterval = 25 * time.Millisecond
|
||||
// Must exceed schema.MigrateUpWithLock's 5s GET_LOCK wait so a
|
||||
// contended schema migration can time out once and still retry.
|
||||
bo.MaxElapsedTime = 15 * time.Second
|
||||
return backoff.Retry(func() error {
|
||||
conn, err := p.db.Conn(ctx)
|
||||
|
|
|
|||
|
|
@ -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