file

package
v2.1.21 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Open opens a file for reading
	Open = ioeither.Eitherize1(os.Open)
	// Create opens a file for writing
	Create = ioeither.Eitherize1(os.Create)
	// ReadFile reads the context of a file
	ReadFile = ioeither.Eitherize1(os.ReadFile)
	// Stat returns [FileInfo] object
	Stat = ioeither.Eitherize1(os.Stat)

	// UserCacheDir returns an [IOEither] that resolves to the default root directory
	// to use for user-specific cached data. Users should create their own application-specific
	// subdirectory within this one and use that.
	//
	// On Unix systems, it returns $XDG_CACHE_HOME as specified by
	// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
	// non-empty, else $HOME/.cache.
	// On Darwin, it returns $HOME/Library/Caches.
	// On Windows, it returns %LocalAppData%.
	// On Plan 9, it returns $home/lib/cache.
	//
	// If the location cannot be determined (for example, $HOME is not defined),
	// then it will return an error wrapped in [E.Left].
	UserCacheDir = ioeither.Eitherize0(os.UserCacheDir)()

	// UserConfigDir returns an [IOEither] that resolves to the default root directory
	// to use for user-specific configuration data. Users should create their own
	// application-specific subdirectory within this one and use that.
	//
	// On Unix systems, it returns $XDG_CONFIG_HOME as specified by
	// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
	// non-empty, else $HOME/.config.
	// On Darwin, it returns $HOME/Library/Application Support.
	// On Windows, it returns %AppData%.
	// On Plan 9, it returns $home/lib.
	//
	// If the location cannot be determined (for example, $HOME is not defined),
	// then it will return an error wrapped in [E.Left].
	UserConfigDir = ioeither.Eitherize0(os.UserConfigDir)()

	// UserHomeDir returns an [IOEither] that resolves to the current user's home directory.
	//
	// On Unix, including macOS, it returns the $HOME environment variable.
	// On Windows, it returns %USERPROFILE%.
	// On Plan 9, it returns the $home environment variable.
	//
	// If the location cannot be determined (for example, $HOME is not defined),
	// then it will return an error wrapped in [E.Left].
	UserHomeDir = ioeither.Eitherize0(os.UserHomeDir)()
)
View Source
var (
	// CreateTemp created a temp file with proper parametrization
	CreateTemp = ioeither.Eitherize2(os.CreateTemp)
)

Functions

func CopyFile added in v2.1.0

func CopyFile(src string) func(dst string) IOEither[error, string]

CopyFile copies a file from source to destination path with proper resource management.

This is a curried function that follows the "data-last" pattern, where the source path is provided first, returning a function that accepts the destination path. This design enables partial application and better composition with other functional operations.

The function uses ioeither.WithResource to ensure both source and destination files are properly closed, even if an error occurs during the copy operation. The copy is performed using io.Copy which efficiently transfers data between the files.

Parameters:

  • src: The path to the source file to copy from

Returns:

  • A function that accepts the destination path and returns an IOEither that:
  • On success: Contains the destination path (Right)
  • On failure: Contains the error (Left) from opening, copying, or closing files

Example:

// Create a copy operation for a specific source file
copyFromSource := CopyFile("/path/to/source.txt")

// Execute the copy to a destination
result := copyFromSource("/path/to/destination.txt")()

// Or use it in a pipeline
result := F.Pipe1(
    CopyFile("/path/to/source.txt"),
    ioeither.Map(func(dst string) string {
        return "Copied to: " + dst
    }),
)("/path/to/destination.txt")()

Types

type Either added in v2.1.0

type Either[E, T any] = either.Either[E, T]

type IOEither

type IOEither[E, T any] = ioeither.IOEither[E, T]

func Close

func Close[C io.Closer](c C) IOEither[error, struct{}]

Close closes an object

func Mkdir

func Mkdir(path string, perm os.FileMode) IOEither[error, string]

Mkdir creates a single directory with the specified permissions. Unlike MkdirAll, it returns an error if the parent directory does not exist or if the directory already exists.

The perm parameter specifies the Unix permission bits for the created directory. Common values include 0755 (rwxr-xr-x) for directories.

Returns an IOEither that, when executed, creates the directory and returns the path on success or an error on failure.

See os.Mkdir for more details.

Example:

mkdirOp := Mkdir("/tmp/mydir", 0755)
result := mkdirOp() // Either[error, string]

func MkdirAll

func MkdirAll(path string, perm os.FileMode) IOEither[error, string]

MkdirAll creates a directory and all necessary parent directories with the specified permissions. If the directory already exists, MkdirAll does nothing and returns success. This is equivalent to the Unix command `mkdir -p`.

The perm parameter specifies the Unix permission bits for the created directories. Common values include 0755 (rwxr-xr-x) for directories.

Returns an IOEither that, when executed, creates the directory structure and returns the path on success or an error on failure.

See os.MkdirAll for more details.

Example:

mkdirOp := MkdirAll("/tmp/my/nested/dir", 0755)
result := mkdirOp() // Either[error, string]

func ReadAll

func ReadAll[R io.ReadCloser](acquire IOEither[error, R]) IOEither[error, []byte]

ReadAll reads all data from a ReadCloser and ensures it is properly closed. It takes an IOEither that acquires the ReadCloser, reads all its content until EOF, and automatically closes the reader, even if an error occurs during reading.

This is the recommended way to read entire files with proper resource management.

Example:

readOp := ReadAll(Open("input.txt"))
result := readOp() // Either[error, []byte]

func Remove

func Remove(name string) IOEither[error, string]

Remove removes a file by name

func WithTempFile

func WithTempFile[A any](f Kleisli[error, *os.File, A]) IOEither[error, A]

WithTempFile creates a temporary file, then invokes a callback to create a resource based on the file, then close and remove the temp file

type Kleisli

type Kleisli[E, A, B any] = ioeither.Kleisli[E, A, B]

func Read

func Read[R any, RD io.ReadCloser](acquire IOEither[error, RD]) Kleisli[error, Kleisli[error, RD, R], R]

Read uses a generator function to create a stream, reads data from it using a provided reader function, and ensures the stream is properly closed after reading.

This function provides safe resource management for reading operations by:

  1. Acquiring a ReadCloser resource using the provided acquire function
  2. Applying a reader function to extract data from the resource
  3. Ensuring the resource is closed, even if an error occurs during reading

Type Parameters:

  • R: The type of data to be read from the stream
  • RD: The type of the ReadCloser resource (must implement io.ReadCloser)

Parameters:

  • acquire: An IOEither that produces the ReadCloser resource

Returns:

A Kleisli function that takes a reader function (which transforms RD to R)
and returns an IOEither that produces the read result R or an error.

Example:

import (
    "os"
    "io"
    F "github.com/IBM/fp-go/v2/function"
    "github.com/IBM/fp-go/v2/ioeither"
    "github.com/IBM/fp-go/v2/ioeither/file"
)

// Read first 10 bytes from a file
readFirst10 := func(f *os.File) ioeither.IOEither[error, []byte] {
    return ioeither.TryCatchError(func() ([]byte, error) {
        buf := make([]byte, 10)
        n, err := f.Read(buf)
        return buf[:n], err
    })
}

result := F.Pipe1(
    file.Open("data.txt"),
    file.Read[[]byte, *os.File],
)(readFirst10)

data, err := result()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Read: %s\n", data)

The Read function ensures that the file is closed even if the reading operation fails, providing safe and composable resource management in a functional style.

func Write

func Write[R any, W io.WriteCloser](acquire IOEither[error, W]) Kleisli[error, Kleisli[error, W, R], R]

Write creates a resource-safe writer that automatically manages the lifecycle of a WriteCloser. It takes an IOEither that acquires the WriteCloser and returns a Kleisli arrow that accepts a write operation. The WriteCloser is automatically closed after the operation completes, even if an error occurs.

This is useful for composing multiple write operations with proper resource management.

Example:

writeOp := Write[int](Open("output.txt"))
result := writeOp(func(f *os.File) IOEither[error, int] {
	return ioeither.TryCatchError(func() (int, error) {
		return f.Write([]byte("Hello"))
	})
})

func WriteFile

func WriteFile(dstName string, perm os.FileMode) Kleisli[error, []byte, []byte]

WriteFile writes a data blob to a file

type Operator

type Operator[E, A, B any] = ioeither.Operator[E, A, B]

func WriteAll

func WriteAll[W io.WriteCloser](data []byte) Operator[error, W, []byte]

WriteAll writes data to a WriteCloser and ensures it is properly closed. It takes the data to write and returns an Operator that accepts an IOEither that creates the WriteCloser. The WriteCloser is automatically closed after the write operation, even if an error occurs.

Example:

writeOp := F.Pipe2(
	Open("output.txt"),
	WriteAll([]byte("Hello, World!")),
)
result := writeOp() // Either[error, []byte]

Jump to

Keyboard shortcuts

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