Help us shape the future of Go! Take the 2026 Go Developer Survey

dotfiles

package
v1.65.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package dotfiles provides cobra commands for managing user dotfiles via a bare git repository.

Index

Constants

This section is empty.

Variables

View Source
var CheckoutCmd = &cobra.Command{
	Use:   "checkout",
	Short: "checkout files in your local bare repository",
	Long:  `This command checks out files from the dotfiles repository, optionally discarding local changes with the force flag.`,
	Run: func(cmd *cobra.Command, args []string) {
		log.Start("Checking out dotfiles")

		isVerbose := cmdutil.IsVerbose(cmd)
		all, _ := cmd.Flags().GetBool("all")
		force, _ := cmd.Flags().GetBool("force")

		repoPath, worktreePath, err := getDotfilesConfig()
		if err != nil || repoPath == "" {
			log.Error("Dotfiles repository path is not set in configuration")
			return
		}
		log.Verbose(isVerbose, "Repository path: %s", repoPath)
		log.Verbose(isVerbose, "Worktree path:   %s", worktreePath)

		operation := "Checking out"
		if force {
			operation += " (force)"
		}
		if all {
			operation += " all files"
		} else {
			operation += " files"
		}
		log.Info(operation)

		err = checkoutRepo(cmd.Context(), repoPath, worktreePath, force, all)
		if err != nil {
			log.Error("Failed to checkout dotfiles: %s", err)
			return
		}

		log.Success("Dotfiles checked out successfully")
	},
}

CheckoutCmd defines the cobra command for checking out files in the dotfiles repository. It can checkout all files or specific files, optionally with force to discard local changes.

View Source
var CopyChangesCmd = &cobra.Command{
	Use:   "copy-changes",
	Short: "copy modified dotfiles to local git repo",
	Long: `This command copies modified dotfiles from the worktree to the local git repository for committing.

The destination resolves as: --repo flag, explicit config
('eng config dotfiles-target-repo-path'), then dev-folder heuristics.
When nothing resolves to a git repository, it offers to locate one
interactively and persists the choice.`,
	Example: `  eng dotfiles copy-changes
  eng dotfiles copy-changes --repo ~/Development/dotfiles`,
	Run: func(cmd *cobra.Command, args []string) {
		log.Start("Copying modified dotfiles")

		isVerbose := cmdutil.IsVerbose(cmd)

		repoPath, worktreePath, err := getDotfilesConfig()
		if err != nil || repoPath == "" {
			log.Error("Dotfiles repository path is not set in configuration")
			return
		}
		log.Verbose(isVerbose, "Repository path: %s", repoPath)
		log.Verbose(isVerbose, "Worktree path:   %s", worktreePath)

		repoFlag, _ := cmd.Flags().GetString("repo")
		targetRepoPath, err := resolveCopyTarget(repoFlag)
		if err != nil {
			log.Error("%s", err)
			return
		}
		log.Verbose(isVerbose, "Target repository path: %s", targetRepoPath)

		modifiedFiles, err := getModifiedFilesFunc(repoPath, worktreePath)
		if err != nil {
			log.Error("Failed to get modified files: %s", err)
			return
		}

		if len(modifiedFiles) == 0 {
			log.Info("No modified files found")
			return
		}

		log.Info("Found %d modified files", len(modifiedFiles))

		for _, file := range modifiedFiles {
			src := filepath.Join(worktreePath, file)
			dest := filepath.Join(targetRepoPath, file)

			destDir := filepath.Dir(dest)
			if err := os.MkdirAll(destDir, 0o755); err != nil {
				log.Error("Failed to create directory %s: %s", destDir, err)
				continue
			}

			if err := copyFile(src, dest, isVerbose); err != nil {
				log.Error("Failed to copy %s to %s: %s", src, dest, err)
				continue
			}

			log.Info("Copied %s to %s", file, dest)
		}

		log.Success("Copied modified dotfiles successfully")

		// Ask to reset
		var resetConfirm bool
		resetConfirm, err = ui.Confirm("Do you want to reset the local copies in the worktree?", true)
		if err != nil {
			log.Error("Failed to get user confirmation: %s", err)
			return
		}

		if resetConfirm {
			log.Start("Resetting local copies")
			for _, file := range modifiedFiles {
				if err := resetFile(repoPath, worktreePath, file); err != nil {
					log.Error("Failed to reset %s: %s", file, err)
					continue
				}
				log.Verbose(isVerbose, "Reset %s", file)
			}
			log.Success("Reset local copies successfully")
		}
	},
}

CopyChangesCmd defines the cobra command for copying modified dotfiles to the local git repository.

View Source
var DiffCmd = &cobra.Command{
	Use:   "diff [path...]",
	Short: "show local dotfiles changes",
	Long: `Show unstaged and staged changes in your local bare dotfiles repository.

This is the dotfiles equivalent of running:
  git --git-dir=<repo> --work-tree=<worktree> diff

By default it shows unstaged changes. Use --staged to show staged
changes, --stat for a summary, or --name-only for just file names.
Pass optional paths to limit the diff, e.g. 'eng cfg diff -- .zshrc'.`,
	Example: `  eng dotfiles diff
  eng cfg diff --staged
  eng cfg diff --stat
  eng cfg diff --name-only
  eng cfg diff -- .zshrc .config/nvim`,
	Run: func(cmd *cobra.Command, args []string) {
		headerStyle := lipgloss.NewStyle().
			Bold(true).
			Foreground(theme.Primary).
			MarginBottom(1)
		if !ui.DisableProgress {
			fmt.Fprintln(log.Out, headerStyle.Render("📝 Dotfiles Changes"))
		}

		isVerbose := cmdutil.IsVerbose(cmd)

		repoPath, worktreePath, err := getDotfilesConfig()
		if err != nil || repoPath == "" {
			log.Error("Dotfiles repository path is not set in configuration")
			return
		}

		log.Verbose(isVerbose, "Repository path: %s", repoPath)
		log.Verbose(isVerbose, "Worktree path:   %s", worktreePath)

		staged, _ := cmd.Flags().GetBool("staged")

		cached, _ := cmd.Flags().GetBool("cached")
		stat, _ := cmd.Flags().GetBool("stat")
		nameOnly, _ := cmd.Flags().GetBool("name-only")

		opts := diffOptions{
			Staged:   staged || cached,
			Stat:     stat,
			NameOnly: nameOnly,
			Paths:    args,
		}

		if err := runDiff(repoPath, worktreePath, opts); err != nil {
			log.Error("Failed to show diff: %s", err)
			return
		}

		theme.SuccessMessage("Dotfiles diff complete.")
	},
}

DiffCmd defines the cobra command for showing local dotfiles changes. It wraps `git --git-dir --work-tree diff` so bare-repo dotfiles diff like a normal checkout.

View Source
var DotfilesCmd = &cobra.Command{
	Use:     "dotfiles",
	Short:   "Manage dotfiles",
	Long:    `This command is used to facilitate the management of private hidden dot files.`,
	Aliases: []string{"cfg"},
	Run: func(cmd *cobra.Command, args []string) {
		showInfo, _ := cmd.Flags().GetBool("info")
		isVerbose := cmdutil.IsVerbose(cmd)

		if showInfo {
			log.Info("Current dotfiles configuration:")
			repoPath, worktreePath, _ := getDotfilesConfig()

			if repoPath == "" {
				log.Warn("  Repository Path: Not Set")
			} else {
				log.Info("  Repository Path: %s", repoPath)
			}
			if worktreePath == "" {
				log.Warn("  Worktree Path:   Not Set")
			} else {
				log.Info("  Worktree Path:   %s", worktreePath)
			}

			gitCfg := config.GetGitConfig()
			if gitCfg.DevPath != "" {
				targetPath := config.TargetRepoPath(gitCfg.DevPath)
				log.Info("  Target Path:     %s", targetPath)
			}
			return
		}

		if len(args) == 0 {
			log.Verbose(isVerbose, "No subcommand provided, showing help.")
			err := cmd.Help()
			cobra.CheckErr(err)
		} else {
			log.Verbose(isVerbose, "Subcommand '%s' provided.", args[0])
		}
	},
}

DotfilesCmd serves as the base command for all dotfiles related operations. It doesn't perform any action itself but groups subcommands like sync and fetch.

View Source
var FetchCmd = &cobra.Command{
	Use:   "fetch",
	Short: "fetch your local bare repository",
	Long:  `This command fetches remote changes to the local bare dot repository.`,
	Run: func(cmd *cobra.Command, args []string) {
		headerStyle := lipgloss.NewStyle().
			Bold(true).
			Foreground(theme.Primary).
			MarginBottom(1)
		if !ui.DisableProgress {
			fmt.Fprintln(log.Out, headerStyle.Render("🔍 Fetching Dotfiles Repository"))
		}

		repoPath, worktreePath, err := getDotfilesConfig()
		if err != nil || repoPath == "" {
			log.Error("Dotfiles repository path is not set in configuration")
			return
		}

		err = dotfiles.FetchRepo(cmd.Context(), repoPath, worktreePath)
		if err != nil {
			log.Error("Failed to fetch dotfiles: %s", err)
			return
		}

		theme.SuccessMessage("Dotfiles fetched successfully.")
	},
}

FetchCmd defines the cobra command for fetching the dotfiles repository.

View Source
var InstallCmd = &cobra.Command{
	Use:   "install",
	Short: "Install dotfiles from a bare git repository",
	Long: `Install dotfiles from a bare git repository. This command will:
	- Check and install prerequisites (Homebrew, Git, Bash)
	- Setup SSH keys for GitHub when required by the repository URL
  - Clone your dotfiles repository as a bare repository
  - Backup any conflicting files
  - Checkout dotfiles to your home directory
  - Initialize git submodules
  - Configure git to hide untracked files`,
	RunE: func(cmd *cobra.Command, args []string) error {
		repoURL, branch, bareRepoPath, worktreePath, err := config.VerifyDotfilesConfig()
		if err != nil {
			return fmt.Errorf("configuration verification failed: %w", err)
		}

		opts := dotfiles.InstallOptions{
			RepoURL:      repoURL,
			Branch:       branch,
			BareRepoPath: bareRepoPath,
			WorktreePath: worktreePath,
			Verbose:      cmdutil.IsVerbose(cmd),
		}

		if err := dotfiles.Install(cmd.Context(), opts); err != nil {
			return fmt.Errorf("dotfiles installation failed: %w", err)
		}
		return nil
	},
}
View Source
var SecretsBackupCmd = &cobra.Command{
	Use:   "backup",
	Short: "Backup managed dotfiles env values into Bitwarden Secrets Manager",
	RunE: func(cmd *cobra.Command, _args []string) error {
		return secrets.BackupDotfilesSecrets(dotfilesSecretsOptions(cmd))
	},
}

SecretsBackupCmd saves managed env keys from the dotfiles worktree into bws.

View Source
var SecretsCmd = &cobra.Command{
	Use:   "secrets",
	Short: "Backup and restore dotfiles env secrets via Bitwarden Secrets Manager",
	Long:  `Backup and restore managed dotfiles env files using a tracked manifest and Bitwarden Secrets Manager.`,
	RunE: func(cmd *cobra.Command, _args []string) error {
		return cmd.Help()
	},
}

SecretsCmd manages manifest-driven dotfiles env secrets with Bitwarden Secrets Manager.

View Source
var SecretsDoctorCmd = &cobra.Command{
	Use:   "doctor",
	Short: "Validate manifest templates and Bitwarden Secrets Manager values",
	RunE: func(cmd *cobra.Command, _args []string) error {
		return secrets.DoctorDotfilesSecrets(dotfilesSecretsOptions(cmd))
	},
}

SecretsDoctorCmd validates manifest mappings, templates, and bws secrets.

View Source
var SecretsRestoreCmd = &cobra.Command{
	Use:   "restore",
	Short: "Restore managed dotfiles env files from Bitwarden Secrets Manager",
	RunE: func(cmd *cobra.Command, _args []string) error {
		return secrets.RestoreDotfilesSecrets(dotfilesSecretsOptions(cmd))
	},
}

SecretsRestoreCmd restores managed env files from tracked templates and bws values.

View Source
var StatusCmd = &cobra.Command{
	Use:   "status",
	Short: "check the status of your dotfiles repository",
	Long: `This command checks the status of your local bare dotfiles repository to see if there are any local changes.

When changes exist it prints a diff --stat summary with a hint to run
'eng cfg diff' for the full patch. Use --diff to pretty-print the full
diff inline.

When run interactively without --diff and changes are detected, it
offers to show the full diff inline (same rendering as 'eng cfg diff').`,
	Example: `  eng dotfiles status
  eng cfg status --diff
  eng cfg status --diff --staged
  eng cfg status --yes`,
	Run: func(cmd *cobra.Command, args []string) {
		headerStyle := lipgloss.NewStyle().
			Bold(true).
			Foreground(theme.Primary).
			MarginBottom(1)
		if !ui.DisableProgress {
			fmt.Fprintln(log.Out, headerStyle.Render("📊 Dotfiles Repository Status"))
		}

		isVerbose := cmdutil.IsVerbose(cmd)

		repoPath, worktreePath, err := getDotfilesConfig()
		if err != nil || repoPath == "" {
			log.Error("Dotfiles repository path is not set in configuration")
			return
		}
		log.Verbose(isVerbose, "Repository path: %s", repoPath)
		log.Verbose(isVerbose, "Worktree path:   %s", worktreePath)

		err = checkStatus(repoPath, worktreePath)
		if err != nil {
			log.Error("Failed to check status: %s", err)
			return
		}

		showDiff, _ := cmd.Flags().GetBool("diff")
		showStaged, _ := cmd.Flags().GetBool("staged")
		autoYes, _ := cmd.Flags().GetBool("yes")
		if showDiff || autoYes {
			opts := diffOptions{Staged: showStaged, Paths: args}
			if err := runDiff(repoPath, worktreePath, opts); err != nil {
				log.Error("Failed to show diff: %s", err)
				return
			}
		} else {

			if stat, statErr := diffStatSummary(repoPath, worktreePath); statErr != nil {
				log.Verbose(isVerbose, "Skipping diff summary: %s", statErr)
			} else if stat != "" {
				fmt.Fprintln(log.Out, "")
				fmt.Fprintln(log.Out, "Changes:")
				fmt.Fprintln(log.Out, ui.RenderDiffStat(stat))
				log.Info("Run `eng cfg diff` for the full patch, or `eng cfg status --diff`.")
				offerDiffPrompt(isVerbose, repoPath, worktreePath, showStaged, args)
			}
		}

		theme.SuccessMessage("Dotfiles status check complete.")
	},
}

StatusCmd defines the cobra command for checking the status of the dotfiles repository. It shows any local changes, untracked files, or uncommitted modifications.

View Source
var SyncCmd = &cobra.Command{
	Use:   "sync",
	Short: "sync your local bare repository",
	Long:  `This command fetches and pulls in remote changes to the local bare dot repository.`,
	Run: func(cmd *cobra.Command, args []string) {
		headerStyle := lipgloss.NewStyle().
			Bold(true).
			Foreground(theme.Primary).
			MarginBottom(1)
		if !ui.DisableProgress {
			fmt.Fprintln(log.Out, headerStyle.Render("🔄 Syncing Dotfiles Repository"))
		}

		isVerbose := cmdutil.IsVerbose(cmd)

		repoPath, worktreePath, err := getDotfilesConfig()
		if err != nil || repoPath == "" {
			log.Error("Dotfiles repository path is not set in configuration")
			return
		}
		log.Verbose(isVerbose, "Repository path: %s", repoPath)
		log.Verbose(isVerbose, "Worktree path:   %s", worktreePath)

		ctx := cmd.Context()
		if ctx == nil {
			ctx = context.Background()
		}
		if err = dotfiles.SyncRepo(ctx, repoPath, worktreePath, isVerbose); err != nil {
			log.Error("Sync failed: %v", err)
			return
		}

		theme.SuccessMessage("Dotfiles synced successfully.")
	},
}

SyncCmd defines the cobra command for syncing the dotfiles repository.

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL