package hgvcs

import (
	
	
	
	
	
	
	

	
)

type preparedTag struct {
	name     string
	commitID string
}

type session struct {
	repo     *Repo
	dir      string
	rev      vcs.Revision
	head     string
	username string
	tags     []preparedTag
	closed   bool
}

func ( *session) () fs.FS {
	return os.DirFS(.dir)
}

func ( *session) ( string,  []byte) error {
	return vcs.WriteDirFile(.dir, , )
}

func ( *session) ( context.Context) (string, error) {
	,  := runHg(, .repo.program, .dir, "log", "-r", ".", "-T", "{node}")
	if  != nil {
		return "", 
	}
	.head = strings.TrimSpace()
	return .head, nil
}

func ( *session) ( context.Context,  string) ([]vcs.FileEntry, error) {
	return listFiles(, .repo.program, .dir, ".", )
}

func ( *session) ( context.Context,  []string,  vcs.CommitOptions) (string, error) {
	if len() == 0 {
		return .head, nil
	}
	// Ensure newly created files (such as go.sum) are tracked before committing.
	 := append([]string{"add", "--"}, ...)
	_, _ = runHg(, .repo.program, .dir, ...)

	 := []string{"commit", "-m", .Message}
	if .username != "" {
		 = append(, "-u", .username)
	}
	 = append(, "--")
	 = append(, ...)
	if ,  := runHg(, .repo.program, .dir, ...);  != nil {
		return "", fmt.Errorf("hg commit: %w", )
	}
	return .Head()
}

func ( *session) ( context.Context,  string,  vcs.TagOptions) error {
	,  := .Head()
	if  != nil {
		return 
	}
	.tags = append(.tags, preparedTag{name: , commitID: })
	return nil
}

func ( *session) ( context.Context) (vcs.PublishResult, error) {
	// Batch all tags into a single .hgtags commit pointing each tag at its
	// exact layer commit node.
	if len(.tags) > 0 {
		 := filepath.Join(.dir, ".hgtags")
		,  := os.ReadFile()
		var  bytes.Buffer
		.Write()
		if len() > 0 && [len()-1] != '\n' {
			.WriteByte('\n')
		}
		for ,  := range .tags {
			fmt.Fprintf(&, "%s %s\n", .commitID, .name)
		}
		if  := os.WriteFile(, .Bytes(), 0o644);  != nil {
			return vcs.PublishResult{}, fmt.Errorf("write .hgtags: %w", )
		}
		_, _ = runHg(, .repo.program, .dir, "add", ".hgtags")
		 := []string{"commit", "-m", .repo.cfg.tagCommitMessage()}
		if .username != "" {
			 = append(, "-u", .username)
		}
		 = append(, ".hgtags")
		if ,  := runHg(, .repo.program, .dir, ...);  != nil {
			return vcs.PublishResult{}, fmt.Errorf("commit .hgtags: %w", )
		}
	}

	,  := .Head()
	if  != nil {
		return vcs.PublishResult{}, 
	}

	if  != .rev.ID {
		if ,  := runHg(, .repo.program, .repo.root, "pull", .dir);  != nil {
			return vcs.PublishResult{}, fmt.Errorf("hg pull from release clone: %w", )
		}
		if .rev.Ref != "" {
			if ,  := runHg(, .repo.program, .repo.root, "bookmark", "-f", "-r", , .rev.Ref);  != nil {
				return vcs.PublishResult{}, fmt.Errorf("update hg bookmark %s: %w", .rev.Ref, )
			}
		}
		// Update main working copy if it is clean and currently at startID.
		if ,  := runHg(, .repo.program, .repo.root, "log", "-r", ".", "-T", "{node}");  == nil &&
			strings.TrimSpace() == .rev.ID {
			if ,  := runHg(, .repo.program, .repo.root, "status", "-mard");  == nil &&
				strings.TrimSpace() == "" {
				_, _ = runHg(, .repo.program, .repo.root, "update", "-r", )
			}
		}
	}

	 := make([]string, len(.tags))
	for ,  := range .tags {
		[] = .name
	}
	return vcs.PublishResult{
		StartID: .rev.ID,
		FinalID: ,
		Ref:     .rev.Ref,
		Label:   .rev.Label,
		Tags:    ,
	}, nil
}

func ( *session) () error {
	if .closed {
		return nil
	}
	.closed = true
	return os.RemoveAll(.dir)
}