cli/pkg/cmd/pr/shared/preserve.go
Kynan Ware 5de7a10080 Add godoc comments to exported symbols in pkg/cmd/pr
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-04 15:53:47 -07:00

69 lines
1.6 KiB
Go

package shared
import (
"encoding/json"
"fmt"
"os"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
)
// PreserveInput returns a cleanup function that saves issue or PR metadata state to a temporary file when a creation error occurs, enabling recovery with --recover.
func PreserveInput(io *iostreams.IOStreams, state *IssueMetadataState, createErr *error) func() {
return func() {
if !state.IsDirty() {
return
}
if *createErr == nil {
return
}
if cmdutil.IsUserCancellation(*createErr) {
// these errors are user-initiated cancellations
return
}
out := io.ErrOut
// this extra newline guards against appending to the end of a survey line
fmt.Fprintln(out)
data, err := json.Marshal(state)
if err != nil {
fmt.Fprintf(out, "failed to save input to file: %s\n", err)
fmt.Fprintln(out, "would have saved:")
fmt.Fprintf(out, "%v\n", state)
return
}
tmpfile, err := io.TempFile(os.TempDir(), "gh*.json")
if err != nil {
fmt.Fprintf(out, "failed to save input to file: %s\n", err)
fmt.Fprintln(out, "would have saved:")
fmt.Fprintf(out, "%v\n", state)
return
}
_, err = tmpfile.Write(data)
if err != nil {
fmt.Fprintf(out, "failed to save input to file: %s\n", err)
fmt.Fprintln(out, "would have saved:")
fmt.Fprintln(out, string(data))
return
}
cs := io.ColorScheme()
issueType := "pr"
if state.Type == IssueMetadata {
issueType = "issue"
}
fmt.Fprintf(out, "%s operation failed. To restore: gh %s create --recover %s\n", cs.FailureIcon(), issueType, tmpfile.Name())
// some whitespace before the actual error
fmt.Fprintln(out)
}
}