Skip to content

proposal: os: add Copy  #56172

Closed as not planned
Closed as not planned
@fumin

Description

@fumin

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:

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 or CopyFile?
  • How can the implementation handle errors from File.Close() in a clean manner without defer?
  • Should it return the number of bytes that were copied like io.Copy does?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions