github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/pr/shared/preserve.go (about)

     1  package shared
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/ungtb10d/cli/v2/pkg/cmdutil"
     9  	"github.com/ungtb10d/cli/v2/pkg/iostreams"
    10  )
    11  
    12  func PreserveInput(io *iostreams.IOStreams, state *IssueMetadataState, createErr *error) func() {
    13  	return func() {
    14  		if !state.IsDirty() {
    15  			return
    16  		}
    17  
    18  		if *createErr == nil {
    19  			return
    20  		}
    21  
    22  		if cmdutil.IsUserCancellation(*createErr) {
    23  			// these errors are user-initiated cancellations
    24  			return
    25  		}
    26  
    27  		out := io.ErrOut
    28  
    29  		// this extra newline guards against appending to the end of a survey line
    30  		fmt.Fprintln(out)
    31  
    32  		data, err := json.Marshal(state)
    33  		if err != nil {
    34  			fmt.Fprintf(out, "failed to save input to file: %s\n", err)
    35  			fmt.Fprintln(out, "would have saved:")
    36  			fmt.Fprintf(out, "%v\n", state)
    37  			return
    38  		}
    39  
    40  		tmpfile, err := io.TempFile(os.TempDir(), "gh*.json")
    41  		if err != nil {
    42  			fmt.Fprintf(out, "failed to save input to file: %s\n", err)
    43  			fmt.Fprintln(out, "would have saved:")
    44  			fmt.Fprintf(out, "%v\n", state)
    45  			return
    46  		}
    47  
    48  		_, err = tmpfile.Write(data)
    49  		if err != nil {
    50  			fmt.Fprintf(out, "failed to save input to file: %s\n", err)
    51  			fmt.Fprintln(out, "would have saved:")
    52  			fmt.Fprintln(out, string(data))
    53  			return
    54  		}
    55  
    56  		cs := io.ColorScheme()
    57  
    58  		issueType := "pr"
    59  		if state.Type == IssueMetadata {
    60  			issueType = "issue"
    61  		}
    62  
    63  		fmt.Fprintf(out, "%s operation failed. To restore: gh %s create --recover %s\n", cs.FailureIcon(), issueType, tmpfile.Name())
    64  
    65  		// some whitespace before the actual error
    66  		fmt.Fprintln(out)
    67  	}
    68  }