package gitvcs

import (
	
	
	
	
	
	
	
	
	
	

	
)

// Name is the backend identifier for Git.
const Name = "git"

const (
	defaultRev    = "HEAD"
	defaultRemote = "origin"
	headsPrefix   = "refs/heads/"
	tagsPrefix    = "refs/tags/"
)

// Config holds Git-specific options decoded from goship.json’s "vcs" object.
type Config struct {
	// Program overrides the git executable name or path passed to exec.LookPath
	// (default "git").
	Program string `json:"program,omitzero"`
	// Annotated creates annotated tags when true (default true) or lightweight
	// tags when false.
	Annotated *bool `json:"annotated,omitzero"`
	// Sign forces GPG/SSH signing when true, disables it when false, or
	// respects native git config (commit.gpgSign / tag.gpgSign) when nil.
	Sign *bool `json:"sign,omitzero"`
}

func ( Config) () bool {
	return .Annotated == nil || *.Annotated
}

// Opener returns a vcs.Opener for the Git backend using cfg.
func ( Config) vcs.Opener {
	return vcs.Opener{
		Name: Name,
		Open: func( context.Context,  string) (vcs.VCS, error) {
			return Open(, , )
		},
	}
}

// Repo implements vcs.VCS for a Git repository.
type Repo struct {
	root    string
	program string
	cfg     Config
}

// Open locates the Git repository containing dir.
func ( context.Context,  string,  Config) (vcs.VCS, error) {
	,  := exec.LookPath(cmp.Or(.Program, Name))
	if  != nil {
		return nil, fmt.Errorf("git binary not found: %w", )
	}
	,  := runGit(, , , "rev-parse", "--show-toplevel")
	if  != nil {
		return nil, fmt.Errorf("not a git repository: %w", )
	}
	return &Repo{
		root:    filepath.Clean(strings.TrimSpace()),
		program: ,
		cfg:     ,
	}, nil
}

// Name returns "git".
func ( *Repo) () string { return Name }

// Root returns the absolute path to the repository root.
func ( *Repo) () string { return .root }

// ResolveRev resolves rev ("" defaults to HEAD) to a commit SHA and optional branch.
func ( *Repo) ( context.Context,  string) (vcs.Revision, error) {
	 = cmp.Or(, defaultRev)
	,  := runGit(, .program, .root, "rev-parse", "--verify", +"^{commit}")
	if  != nil {
		return vcs.Revision{}, fmt.Errorf("resolve revision %q: %w", , )
	}
	 := vcs.Revision{ID: strings.TrimSpace()}

	switch  {
	case defaultRev:
		if ,  := runGit(, .program, .root, "symbolic-ref", "-q", defaultRev);  == nil {
			.Ref = strings.TrimSpace()
			.Label = strings.TrimPrefix(.Ref, headsPrefix)
		}
	default:
		 := 
		if !strings.HasPrefix(, headsPrefix) {
			 = headsPrefix + 
		}
		if ,  := runGit(, .program, .root, "show-ref", "--verify", "--quiet", );  == nil {
			.Ref = 
			.Label = strings.TrimPrefix(, headsPrefix)
		}
	}
	return , nil
}

// Tags returns all tags in the repository.
func ( *Repo) ( context.Context) ([]string, error) {
	,  := runGit(, .program, .root, "tag", "--list")
	if  != nil {
		return nil, fmt.Errorf("list git tags: %w", )
	}
	var  []string
	for  := range strings.Lines() {
		if  = strings.TrimSpace();  != "" {
			 = append(, )
		}
	}
	return , nil
}

// ChangedFiles returns repo-relative slash paths changed between baseRev and
// targetRev under dir.
func ( *Repo) ( context.Context, , ,  string) ([]string, error) {
	 := []string{"diff", "--name-only", "-z",  + ".." + }
	if  := vcs.CleanRelDir();  != "" {
		 = append(, "--", )
	}
	,  := runGitBytes(, .program, .root, nil, ...)
	if  != nil {
		return nil, fmt.Errorf("git diff %s..%s: %w", , , )
	}
	var  []string
	for  := range bytes.SplitSeq(, []byte{0}) {
		if len() > 0 {
			 = append(, string())
		}
	}
	return , nil
}

// ListFiles returns all tracked blob files at rev under dir.
func ( *Repo) ( context.Context, ,  string) ([]vcs.FileEntry, error) {
	return listFiles(, .program, .root, , )
}

// ReadFile returns the contents of slashPath at rev.
func ( *Repo) ( context.Context, ,  string) ([]byte, error) {
	 :=  + ":" + vcs.CleanRelPath()
	,  := runGitBytes(, .program, .root, nil, "cat-file", "blob", )
	if  != nil {
		return nil, fmt.Errorf("read %s: %w", , )
	}
	return , nil
}

// Export extracts the tracked tree at rev into destDir using a single
// "git archive" invocation.
func ( *Repo) ( context.Context, ,  string) error {
	 := exec.CommandContext(, .program, "-c", "core.autocrlf=false", "archive", "--format=tar", )
	.Dir = .root
	,  := .StdoutPipe()
	if  != nil {
		return fmt.Errorf("git archive %s pipe: %w", , )
	}
	var  bytes.Buffer
	.Stderr = &
	if  := .Start();  != nil {
		return fmt.Errorf("start git archive %s: %w", , )
	}
	 := vcs.ExtractTar(, , "")
	 := .Wait()
	if  != nil {
		return fmt.Errorf("git archive %s: %w", , )
	}
	if  != nil {
		return fmt.Errorf("git archive %s: %w: %s", , , strings.TrimSpace(.String()))
	}
	return nil
}

// Begin starts an isolated release session using a temporary detached git worktree.
func ( *Repo) ( context.Context,  vcs.Revision) (vcs.Session, error) {
	,  := os.MkdirTemp("", "goship-git-worktree-*")
	if  != nil {
		return nil, fmt.Errorf("create temp worktree dir: %w", )
	}
	if ,  := runGit(, .program, .root, "worktree", "add", "--detach", , .ID);  != nil {
		_ = os.RemoveAll()
		return nil, fmt.Errorf("create git worktree at %s: %w", .ID, )
	}
	return &session{
		repo:    ,
		dir:     ,
		rev:     ,
		head:    .ID,
		signing: .defaultTagSign(),
	}, nil
}

// Push pushes the branch (if non-empty) and tags to remote in a single command.
func ( *Repo) ( context.Context, ,  string,  []string) error {
	 = cmp.Or(, defaultRemote)
	 := []string{"push", }
	if  != "" {
		 = append(, )
	}
	for ,  := range  {
		 = append(, tagsPrefix+)
	}
	if len() == 2 {
		return nil
	}
	if ,  := runGit(, .program, .root, ...);  != nil {
		return fmt.Errorf("git push to %s: %w", , )
	}
	return nil
}

// PushHint formats a git push command for res.
func ( *Repo) ( string,  vcs.PublishResult) string {
	 = cmp.Or(, defaultRemote)
	var  []string
	if .Label != "" {
		 = append(, .Label)
	}
	 = append(, .Tags...)
	if len() == 0 {
		return ""
	}
	return fmt.Sprintf("git push %s %s", , strings.Join(, " "))
}

func ( *Repo) ( context.Context) bool {
	,  := runGit(, .program, .root, "config", "--type=bool", "tag.gpgSign")
	return  == nil && strings.TrimSpace() == "true"
}

func ( context.Context, , , ,  string) ([]vcs.FileEntry, error) {
	 := []string{"ls-tree", "-r", "-z", "--full-tree", }
	if  := vcs.CleanRelDir();  != "" {
		 = append(, "--", )
	}
	,  := runGitBytes(, , , nil, ...)
	if  != nil {
		return nil, fmt.Errorf("git ls-tree %s: %w", , )
	}
	var  []vcs.FileEntry
	for  := range bytes.SplitSeq(, []byte{0}) {
		if len() == 0 {
			continue
		}
		, ,  := bytes.Cut(, []byte{'\t'})
		if ! {
			continue
		}
		 := strings.Fields(string())
		if len() < 3 || [1] != "blob" {
			continue
		}
		,  := strconv.ParseUint([0], 8, 32)
		if  != nil {
			continue
		}
		 := fs.FileMode(0o644)
		if &0o111 != 0 {
			 = 0o755
		}
		 = append(, vcs.FileEntry{
			Path: string(),
			Mode: ,
		})
	}
	return , nil
}

func ( context.Context, ,  string,  ...string) (string, error) {
	,  := runGitBytes(, , , nil, ...)
	return string(), 
}

func ( context.Context, ,  string,  []byte,  ...string) ([]byte, error) {
	return vcs.RunCmd(, , , nil, , ...)
}