Skip to content

Commit 840ac97

Browse files
Allow embedding gptscripts in python files
1 parent fa5634f commit 840ac97

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

pkg/parser/parser.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111
)
1212

1313
func normalize(key string) string {
14-
return strings.ToLower(strings.ReplaceAll(key, " ", ""))
14+
return strings.TrimSpace(strings.ToLower(strings.ReplaceAll(key, " ", "")))
1515
}
1616

1717
func toBool(line string) (bool, error) {
@@ -156,6 +156,17 @@ func (c *context) finish(tools *[]types.Tool) {
156156
*c = context{}
157157
}
158158

159+
func commentEmbedded(line string) (string, bool) {
160+
for _, i := range []string{"#", "# ", "//", "// "} {
161+
prefix := i + "gptscript:"
162+
cut, ok := strings.CutPrefix(line, prefix)
163+
if ok {
164+
return cut, ok
165+
}
166+
}
167+
return line, false
168+
}
169+
159170
func Parse(input io.Reader) ([]types.Tool, error) {
160171
scan := bufio.NewScanner(input)
161172

@@ -179,6 +190,16 @@ func Parse(input io.Reader) ([]types.Tool, error) {
179190
}
180191

181192
if !context.inBody {
193+
// Strip special comments to allow embedding the preamble in python or other interpreted languages
194+
if newLine, ok := commentEmbedded(line); ok {
195+
line = newLine
196+
}
197+
198+
// If the very first line is #! just skip because this is a unix interpreter declaration
199+
if strings.HasPrefix(line, "#!") && lineNo == 1 {
200+
continue
201+
}
202+
182203
// This is a comment
183204
if strings.HasPrefix(line, "#") && !strings.HasPrefix(line, "#!") {
184205
continue

0 commit comments

Comments
 (0)