Closed as not planned
Description
I propose adding the function os.Copy(dst, src string)
that does the exact same thing as the cp
command.
This function would help simplify these codes in Go itself:
go/src/cmd/go/internal/modcmd/vendor.go
Line 293 in be9e244
Line 261 in 8d3631f
In the wild, there are 91k results for the search https://github.com/search?p=4&q=os.create+%22io.copy%22&type=Code , and one-tenth of them are copying files.
This implies that this function would help 10k codes out there.
Tentative implementation:
// Copy copies src to dst like the cp command.
func Copy(dst, src string) error {
if dst == src {
return ErrInvalid
}
srcF, err := Open(src)
if err != nil {
return err
}
defer srcF.Close()
info, err := srcF.Stat()
if err != nil {
return err
}
dstF, err := OpenFile(dst, O_RDWR|O_CREATE|O_TRUNC, info.Mode())
if err != nil {
return err
}
defer dstF.Close()
if _, err := io.Copy(dstF, srcF); err != nil {
return err
}
return nil
}
Unsettled questions:
- Should the name be
Copy
orCopyFile
? - How can the implementation handle errors from
File.Close()
in a clean manner withoutdefer
? - Should it return the number of bytes that were copied like io.Copy does?