I propose adding ReadFile and WriteFile methods to *os.Root:

package os

// ReadFile reads the named file in the root and returns the contents.
// See [ReadFile] for more details.
func (r *Root) ReadFile(name string) ([]byte, error)

// WriteFile writes data to the named file in the root, creating it if necessary.
// See [WriteFile] for more details.
func (r *Root) WriteFile(name string, data []byte, perm FileMode) error

These are purely convenience functions (as are os.ReadFile and os.WriteFile). I propose adding them because:

  1. os.ReadFile and os.WriteFile are very convenient convenience functions, and it's a shame not to have an equivalent that works with os.Root.
  2. The io/fs package not only includes a ReadFile convenience function, it includes a ReadFileFS variant of FS containing a ReadFile method. I think that points at this being something we consider core filesystem functionality.

Comment From: gabyhelp

Related Issues

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

Comment From: irsl

Could we have an os level shortcut methods as well (similar to os.OpenInRoot)? By having that, one wouldn't need to bother with closing the root for one-time operations.

Without that, the following oneliner:

data, err:= os.ReadFile(filepath.Join(dir, file))

Would be around 6:

r, err:= os.OpenRoot(dir)
if err != nil {
   log.Fatalf(...)
}
defer r.Close()
data, err:= r.ReadFile(file)

Comment From: neild

I don't think we want to have top-level functions for every Root operation. That'd be a lot of new functions.

Filed #73168 with a proposal for a single top-level InRoot function that would allow using any Root method as a one-liner.

Comment From: aclements

Based on the discussion above, this proposal seems like a likely accept. — aclements for the proposal review group

The proposal is given in https://github.com/golang/go/issues/73126#issue-2964067605.

Comment From: gopherbot

Change https://go.dev/cl/674315 mentions this issue: os: add Root.ReadFile and Root.WriteFile

Comment From: aclements

No change in consensus, so accepted. 🎉 This issue now tracks the work of implementing the proposal. — aclements for the proposal review group

The proposal is given in https://github.com/golang/go/issues/73126#issue-2964067605.

Comment From: aclements

@neild , should this issue be closed now?

Comment From: neild

Implemented, closing.