arche / internal/cli/cmd_init.go

commit 154431fd
 1package cli
 2
 3import (
 4	"fmt"
 5	"os"
 6
 7	"arche/internal/gitcompat"
 8	"arche/internal/repo"
 9
10	"github.com/spf13/cobra"
11)
12
13var initGit bool
14
15var initCmd = &cobra.Command{
16	Use:   "init [directory]",
17	Short: "Initialise a new Arche repository",
18	Long: `Initialise a new Arche repository in the given directory (default: current
19directory). Creates a .arche/ directory with an SQLite store and an initial
20empty draft commit. HEAD is set to the change ID of that draft.
21
22With --git: also initialise (or reuse) a .git/ repository so the directory
23stays fully compatible with standard git tooling. Existing git history is
24imported as public-phase arche commits. Every subsequent "arche snap" will
25also create a git commit; "arche sync" will also run git push/pull.`,
26	Args: cobra.MaximumNArgs(1),
27	RunE: func(cmd *cobra.Command, args []string) error {
28		dir := "."
29		if len(args) == 1 {
30			dir = args[0]
31		}
32
33		hasGitHistory := initGit && gitcompat.IsGitRepo(dir)
34
35		if initGit && !hasGitHistory {
36			if err := gitcompat.GitInit(dir); err != nil {
37				return fmt.Errorf("git init: %w", err)
38			}
39		}
40
41		r, err := repo.Init(dir)
42		if err != nil {
43			return err
44		}
45		defer r.Close()
46
47		if initGit {
48			if err := gitcompat.EnsureGitIgnore(r.Root); err != nil {
49				return fmt.Errorf("update .gitignore: %w", err)
50			}
51
52			if hasGitHistory {
53				fmt.Println("Importing git history into arche store…")
54				if err := gitcompat.ImportFromGit(r.Root, r); err != nil {
55					return fmt.Errorf("import git history: %w", err)
56				}
57				fmt.Println("Import complete.")
58			}
59
60			r.Cfg.Git.Enabled = true
61			if r.Cfg.Git.Remote == "" {
62				r.Cfg.Git.Remote = "origin"
63			}
64			if err := r.SaveConfig(); err != nil {
65				return err
66			}
67		}
68
69		absDir, _ := os.Getwd()
70		if dir != "." {
71			absDir = dir
72		}
73		head, _ := r.Head()
74		fmt.Printf("Initialised empty Arche repository in %s/.arche/\n", absDir)
75		if initGit {
76			fmt.Printf("Git compatibility enabled — .arche/ added to .gitignore\n")
77		}
78		fmt.Printf("Working copy: %s (draft, empty)\n", head)
79		if !hasGitHistory {
80			fmt.Printf("No bookmark. Run 'arche snap' to record your first commit.\n")
81		}
82		return nil
83	},
84}
85
86func init() {
87	initCmd.Flags().BoolVar(&initGit, "git", false, "also initialise git compatibility (import existing history if present)")
88}