Skip to content

Commit a2daea4

Browse files
committed
feat: add sys.append built-in
Add a new built-in tool called `sys.append` that appends content to a file instead of truncating it. Signed-off-by: Nick Hale <[email protected]>
1 parent 118ea59 commit a2daea4

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

pkg/builtin/builtin.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ var tools = map[string]types.Tool{
3737
},
3838
BuiltinFunc: SysWrite,
3939
},
40+
"sys.append": {
41+
Parameters: types.Parameters{
42+
Description: "Appends the contents to a file",
43+
Arguments: types.ObjectSchema(
44+
"filename", "The name of the file to append to",
45+
"content", "The content to append"),
46+
},
47+
BuiltinFunc: SysAppend,
48+
},
4049
"sys.http.get": {
4150
Parameters: types.Parameters{
4251
Description: "Download the contents of a http or https URL",
@@ -258,6 +267,33 @@ func SysWrite(ctx context.Context, env []string, input string) (string, error) {
258267
return "", os.WriteFile(params.Filename, data, 0644)
259268
}
260269

270+
func SysAppend(ctx context.Context, env []string, input string) (string, error) {
271+
var params struct {
272+
Filename string `json:"filename,omitempty"`
273+
Content string `json:"content,omitempty"`
274+
}
275+
if err := json.Unmarshal([]byte(input), &params); err != nil {
276+
return "", err
277+
}
278+
279+
f, err := os.OpenFile(params.Filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
280+
if err != nil {
281+
return "", err
282+
}
283+
284+
// Attempt to append to the file and close it immediately.
285+
// Write is guaranteed to return an error when n != len([]byte(params.Content))
286+
n, err := f.Write([]byte(params.Content))
287+
if err := errors.Join(err, f.Close()); err != nil {
288+
return "", err
289+
}
290+
291+
msg := fmt.Sprintf("Appended %d bytes to file %s", n, params.Filename)
292+
log.Debugf(msg)
293+
294+
return "", err
295+
}
296+
261297
func fixQueries(u string) (string, error) {
262298
url, err := url.Parse(u)
263299
if err != nil {

0 commit comments

Comments
 (0)