From 2f9c2cf75e0792c987edde613deb7070b565b6f7 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Fri, 29 Sep 2023 17:47:35 +0100 Subject: [PATCH] vfs: add vfs.WriteFile as an analogue to os.WriteFile --- vfs/vfs.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/vfs/vfs.go b/vfs/vfs.go index 9f0fc1f14..b29983099 100644 --- a/vfs/vfs.go +++ b/vfs/vfs.go @@ -766,6 +766,21 @@ func (vfs *VFS) ReadFile(filename string) (b []byte, err error) { return io.ReadAll(f) } +// WriteFile writes data to the named file, creating it if necessary. +// If the file does not exist, WriteFile creates it with permissions perm (before umask); +// otherwise WriteFile truncates it before writing, without changing permissions. +// Since Writefile requires multiple system calls to complete, a failure mid-operation +// can leave the file in a partially written state. +func (vfs *VFS) WriteFile(name string, data []byte, perm os.FileMode) (err error) { + f, err := vfs.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) + if err != nil { + return err + } + defer fs.CheckClose(f, &err) + _, err = f.Write(data) + return err +} + // AddVirtual adds the object (file or dir) to the directory cache func (vfs *VFS) AddVirtual(remote string, size int64, isDir bool) (err error) { remote = strings.TrimRight(remote, "/")