-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
common.go
85 lines (81 loc) · 2.27 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"bufio"
"bytes"
"os"
"strings"
"github.com/rs/zerolog"
"github.com/spf13/pflag"
)
// Reads input from a side file or from standard input, but not both.
//
// Parameters:
//
// * from: Path to a file whose contents will be appended to the prompt. If path is -, read standard input.
// * logger: A zerolog logger to use for logging errors.
//
// Returns:
//
// Returns the pointer to the input string.
func ReadFromFileOrStdin(readFrom string, logger *zerolog.Logger) *string {
var fileContents string
const READ_FROM_STDIN string = "-"
if readFrom != READ_FROM_STDIN {
// Read input from a side file
fileContentsAsBytes, err := os.ReadFile(readFrom)
if err != nil {
logger.Fatal().Msgf("failed to load file %s: %s", readFrom, err)
}
fileContents = string(fileContentsAsBytes)
} else {
// Read input from stdin
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fileContents += scanner.Text()
}
}
}
return &fileContents
}
// Builds the full prompt from the provided arguments, with the positional arguments being the first part of the prompt, followed by the named arguments -f. For example, the command
//
// askg -f "FILE1" -f - -f "FILE2,FILE3" "PROMPT_PART_1" "PROMPT_PART_2"
//
// will result in the following prompt:
//
// <PROMPT_PART_1> <PROMPT_PART_2>
// <FILE1 contents>
// <stdin contents>
// <FILE2 contents>
// <FILE3 contents>
//
// Parameters:
//
// * flags: a *pflag.FlagSet pointer
//
// Returns:
//
// Returns the pointer to the buffer containing the full prompt.
func BuildPrompt(flags *pflag.FlagSet) *bytes.Buffer {
fullPromptAsBuffer := bytes.Buffer{}
firstPartOfPrompt := strings.Join(flags.Args(), " ")
fullPromptAsBuffer.WriteString(firstPartOfPrompt)
alsoReadFrom, _ := flags.GetStringSlice("file")
if len(alsoReadFrom) == 0 {
return &fullPromptAsBuffer
}
fileSeparator, _ := flags.GetString("file-separator")
for _, pathOrStdin := range alsoReadFrom {
pNextPartOfPrompt := ReadFromFileOrStdin(pathOrStdin, &logger)
if *pNextPartOfPrompt == "" {
continue
}
if fullPromptAsBuffer.Len() > 0 {
fullPromptAsBuffer.WriteString(fileSeparator)
}
fullPromptAsBuffer.WriteString(*pNextPartOfPrompt)
}
return &fullPromptAsBuffer
}