Skip to content

WriteFile occassionaly truncates files entirely #137

Open
@klauern

Description

@klauern

I am trying to write a simple sed -i script using this, but it seems that when I run it on the same path that I am reading it from, occasionally the file is completely truncated instead of written with the piped changes.

func Replace(path, from, to string) error {
	pipe := script.File(path)
	file, err := pipe.Replace(from, to).WriteFile(path)
	if err != nil {
		fmt.Println(path, err)
		return fmt.Errorf("error writing file %s: %w", path, err)
	}
    return nil
}

I can make this work by pulling the write operation out of the pipe:

func Replace(path, from, to string) error {
	pipe := script.File(path)
	file, err := pipe.Replace(from, to).String()
	if err != nil {
		fmt.Println(path, err)
		return fmt.Errorf("error writing file %s: %w", path, err)
	}
	return os.WriteFile(path, []byte(file), 0644)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions