flerr

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 17, 2025 License: MIT Imports: 2 Imported by: 2

README

Flush errors

Helper library that can be used to capture errors from deferred functions and allows something close to a block level defer.

Example usage:

func createScriptDir(sourceDir embed.FS, scriptDir string) (outErr error) {
	err := os.MkdirAll(scriptDir, 0o700)
	if err != nil {
		return fmt.Errorf("create script directory: %w", err)
	}

	scripts, err := sourceDir.ReadDir(".")
	if err != nil {
		return fmt.Errorf("list files in source directory: %w", err)
	}

	var clean flerr.Cleaner

	// Clean up all files when the function returns, joining in any errors
	// that might result from the cleanup.
	defer clean.FlushTo(&outErr)

	for _, f := range scripts {
		if f.IsDir() || !strings.HasSuffix(f.Name(), ".py") {
			continue
		}

		src, err := pysrc.Scripts.Open(f.Name())
		if err != nil {
			return fmt.Errorf("open %q for reading: %w", f.Name(), err)
		}

		clean.Addf(src.Close, "close %q", f.Name())

		dst, err := os.Create(filepath.Join(scriptDir, f.Name()))
		if err != nil {
			return fmt.Errorf("create destination file for %q: %w", f.Name(), err)
		}

		clean.Addf(src.Close, "close %q destination", f.Name())

		_, err = io.Copy(dst, src)
		if err != nil {
			return fmt.Errorf("copy %q: %w", f.Name(), err)
		}

		// Clean up all files at the end of the loop.
		err = clean.Flush()
		if err != nil {
			return err
		}
	}

	return nil
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cleaner

type Cleaner struct {
	// contains filtered or unexported fields
}

Cleaner helps with handling errors from deferred functions and doing defers in loop blocks.

func (*Cleaner) Add

func (c *Cleaner) Add(fn func() error)

Add adds a cleanup function.

func (*Cleaner) Addf

func (c *Cleaner) Addf(fn func() error, format string, a ...any)

Adds a cleanup function together with a message format that will be used to construct an error that wraps any error returned by the cleanup function.

func (*Cleaner) Flush

func (c *Cleaner) Flush() error

Flush runs all cleanup functions and returns the join of all errors.

func (*Cleaner) FlushTo

func (c *Cleaner) FlushTo(outErr *error)

FlushTo runs all cleanup functions and joins outErr with any errors that occurred.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL