file

package
v2.2.6 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: MIT Imports: 8 Imported by: 0

README

goutils/v2/file

The file package is a collection of utility functions designed to simplify common file tasks.


Table of contents


Functions

CSVToLines(string)
CSVToLines(string) [][]string, error

CSVToLines reads a CSV file and returns it as a 2D string slice. Each element in the outer slice represents a row in the CSV, each element in the inner slice represents a value in that row. The first row of the CSV, assumed to contain column headers, is skipped.

Parameters:

path: String representing the path to the CSV file.

Returns:

[][]string: 2D slice of strings representing the rows and values of the CSV. error: An error if the file cannot be read or parsed.


Create(string, []byte, CreateType)
Create(string, []byte, CreateType) string, error

Create makes a directory, an empty file, a file with content, or a temporary file at the specified path, depending on the createType argument.

Parameters:

path: Path to the directory or file. For temporary files, this serves as a pattern. contents: Content to write to the file as a byte slice. createType: A CreateType value representing what kind of file creation action to execute.

Returns:

error: An error if the directory or file can't be created, if it already exists (except for temporary files), or if there's a problem writing to the file.


Delete(string)
Delete(string) error

Delete removes the specified file.

Parameters:

path: String representing the path to the file.

Returns:

error: An error if the file cannot be deleted.


Exists(string)
Exists(string) bool

Exists checks whether a file at the specified path exists.

Parameters:

fileLoc: String representing the path to the file.

Returns:

bool: Returns true if the file exists, otherwise false.


Find(string, []string)
Find(string, []string) []string, error

Find searches for a specified filename in a set of directories and returns all matches found as a slice of file paths. If no matches are found, it returns an error.

Parameters:

fileName: Name of the file to find. dirs: Slice of strings representing the directories to search in.

Returns:

[]string: Slice of file paths if the file is found. error: An error if the file cannot be found.


HasStr(string, string)
HasStr(string, string) bool, error

HasStr checks for the presence of a string in a specified file.

Parameters:

path: String representing the path to the file. searchStr: String to look for in the file.

Returns:

bool: Returns true if the string is found, otherwise false. error: An error if the file cannot be read.


ListR(string)
ListR(string) []string, error

ListR lists all files in a directory and its subdirectories.

Parameters:

dirPath: String representing the path to the directory.

Returns:

[]string: Slice of strings representing the paths of the files found. error: An error if the files cannot be listed.


RealFile.Append(string)
Append(string) error

Append adds a string to the end of a file. If the file doesn't exist, it's created with the default permissions.

Parameters:

text: String to append to the end of the file.

Returns:

error: An error if the file can't be opened or the string can't be written to the file.


RealFile.Open()
Open() io.ReadCloser, error

Open is a method for the RealFile type that opens the file and returns a io.ReadCloser and an error.

Returns:

io.ReadCloser: An object that allows reading from and closing the file. error: An error if any issue occurs while trying to open the file.


RealFile.Remove()
Remove() error

Remove is a method for the RealFile type that removes the specified file or directory. Note that it will not remove a directory unless it is empty.

Parameters:

name: A string representing the path to the file or directory to remove.

Returns:

error: An error if any issue occurs while trying to remove the file or directory.


RealFile.RemoveAll()
RemoveAll() error

RemoveAll is a method for the RealFile type that removes a file or directory at the specified path. If the path represents a directory, RemoveAll will remove the directory and all its content.

Parameters:

path: A string representing the path to the file or directory to remove.

Returns:

error: An error if any issue occurs while trying to remove the file or directory.


RealFile.Stat()
Stat() os.FileInfo, error

Stat is a method for the RealFile type that retrieves the FileInfo for the specified file or directory.

Parameters:

name: A string representing the path to the file or directory.

Returns:

os.FileInfo: FileInfo describing the named file. error: An error if any issue occurs while trying to get the FileInfo.


RealFile.Write([]byte, os.FileMode)
Write([]byte, os.FileMode) error

Write is a method for the RealFile type that writes a slice of bytes to the file with specified file permissions.

Parameters:

contents: A slice of bytes that should be written to the file. mode: File permissions to use when creating the file.

Returns:

error: An error if any issue occurs while trying to write to the file.


SeekAndDestroy(string, string)
SeekAndDestroy(string, string) error

SeekAndDestroy walks through a directory and deletes all files that match the pattern

Parameters:

path: String representing the path to the directory. pattern: String representing the pattern to match.

Returns:

error: An error if the files cannot be deleted.


ToSlice(string)
ToSlice(string) []string, error

ToSlice reads a file and returns its content as a slice of strings, each element represents a line in the file. Blank lines are omitted.

Parameters:

path: String representing the path to the file.

Returns:

[]string: Slice of strings where each element represents a line in the file. error: An error if the file cannot be read.


WriteTempFile(string, *bytes.Buffer)
WriteTempFile(string, *bytes.Buffer) string, error

WriteTempFile creates a temporary file in the system default temp directory, writes the contents from the provided buffer, and returns the file path.

Parameters:

workloadName: A string representing the base name of the temporary file. jobFile: A *bytes.Buffer containing the data to write to the temporary file.

Returns:

string: The name of the temporary file created. error: An error if any issue occurs during file creation or writing.


Installation

To use the goutils/v2/file package, you first need to install it. Follow the steps below to install via go get.

go get github.com/l50/goutils/v2/file

Usage

After installation, you can import the package in your Go project using the following import statement:

import "github.com/l50/goutils/v2/file"

Tests

To ensure the package is working correctly, run the following command to execute the tests for goutils/v2/file:

go test -v

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.


License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CSVToLines

func CSVToLines(path string) ([][]string, error)

CSVToLines reads a CSV file and returns it as a 2D string slice. Each element in the outer slice represents a row in the CSV, each element in the inner slice represents a value in that row. The first row of the CSV, assumed to contain column headers, is skipped.

**Parameters:**

path: String representing the path to the CSV file.

**Returns:**

[][]string: 2D slice of strings representing the rows and values of the CSV. error: An error if the file cannot be read or parsed.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example.csv")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	if _, err := tmpfile.WriteString("header1,header2\nvalue1,value2\nvalue3,value4"); err != nil {
		log.Printf("failed to write to temp file: %v", err)
		return
	}
	tmpfile.Close()

	records, err := fileutils.CSVToLines(tmpfile.Name())
	if err != nil {
		log.Printf("failed to read CSV file: %v", err)
		return
	}

	for _, row := range records {
		log.Println(row)
	}
}
Output:

func Create

func Create(path string, contents []byte, createType CreateType) (string, error)

Create makes a directory, an empty file, a file with content, or a temporary file at the specified path, depending on the createType argument.

**Parameters:**

path: Path to the directory or file. For temporary files, this serves as a pattern. contents: Content to write to the file as a byte slice. createType: A CreateType value representing what kind of file creation action to execute.

**Returns:**

error: An error if the directory or file can't be created, if it already exists (except for temporary files), or if there's a problem writing to the file.

func Delete

func Delete(path string) error

Delete removes the specified file.

**Parameters:**

path: String representing the path to the file.

**Returns:**

error: An error if the file cannot be deleted.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}

	if err := fileutils.Delete(tmpfile.Name()); err != nil {
		log.Printf("failed to delete file: %v", err)
		return
	}
}
Output:

func Exists

func Exists(fileLoc string) bool

Exists checks whether a file at the specified path exists.

**Parameters:**

fileLoc: String representing the path to the file.

**Returns:**

bool: Returns true if the file exists, otherwise false.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	exists := fileutils.Exists(tmpfile.Name())
	if !exists {
		log.Printf("file does not exist")
		return
	}
}
Output:

func Find

func Find(fileName string, dirs []string) ([]string, error)

Find searches for a specified filename in a set of directories and returns all matches found as a slice of file paths. If no matches are found, it returns an error.

**Parameters:**

fileName: Name of the file to find. dirs: Slice of strings representing the directories to search in.

**Returns:**

[]string: Slice of file paths if the file is found. error: An error if the file cannot be found.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpdir, err := os.MkdirTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp directory: %v", err)
	}
	defer os.RemoveAll(tmpdir)

	tmpfile, err := os.CreateTemp(tmpdir, "file_to_find.txt")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}

	dirs := []string{tmpdir}

	filePaths, err := fileutils.Find(tmpfile.Name(), dirs)
	if err != nil {
		log.Printf("failed to find file: %v", err)
		return
	}

	for _, filePath := range filePaths {
		log.Printf("file found at: %s\n", filePath)
	}
}
Output:

func HasStr

func HasStr(path string, searchStr string) (bool, error)

HasStr checks for the presence of a string in a specified file.

**Parameters:**

path: String representing the path to the file. searchStr: String to look for in the file.

**Returns:**

bool: Returns true if the string is found, otherwise false. error: An error if the file cannot be read.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	// Create a new temporary file
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name()) // clean up

	// Write some content to the file
	if _, err := tmpfile.WriteString("Hello, World!"); err != nil {
		log.Printf("failed to write to temp file: %v", err)
		return
	}
	tmpfile.Close()

	found, err := fileutils.HasStr(tmpfile.Name(), "World")
	if err != nil {
		log.Printf("failed to read from file: %v", err)
		return
	}

	if !found {
		log.Printf("failed to find string in file")
		return
	}
}
Output:

func ListR

func ListR(dirPath string) ([]string, error)

ListR lists all files in a directory and its subdirectories.

**Parameters:**

dirPath: String representing the path to the directory.

**Returns:**

[]string: Slice of strings representing the paths of the files found. error: An error if the files cannot be listed.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpdir, err := os.MkdirTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp directory: %v", err)
		return
	}
	defer os.RemoveAll(tmpdir)

	if _, err := os.CreateTemp(tmpdir, "file1.txt"); err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}

	files, err := fileutils.ListR(tmpdir)
	if err != nil {
		log.Printf("failed to list files: %v", err)
		return
	}

	for _, file := range files {
		log.Println(file)
	}
}
Output:

func SeekAndDestroy

func SeekAndDestroy(path string, pattern string) error

SeekAndDestroy walks through a directory and deletes all files that match the pattern

**Parameters:**

path: String representing the path to the directory. pattern: String representing the pattern to match.

**Returns:**

error: An error if the files cannot be deleted.

Example
package main

import (
	"fmt"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	dir := "/tmp"      // choose a directory that should exist on the testing machine
	pattern := "*.txt" // choose a pattern that should match files in the directory

	err := fileutils.SeekAndDestroy(dir, pattern)

	if err != nil {
		fmt.Printf("failed to delete files matching pattern %s in directory %s: %v\n", pattern, dir, err)
	} else {
		fmt.Println("Files matching pattern deleted successfully!")
	}

}
Output:

Files matching pattern deleted successfully!

func ToSlice

func ToSlice(path string) ([]string, error)

ToSlice reads a file and returns its content as a slice of strings, each element represents a line in the file. Blank lines are omitted.

**Parameters:**

path: String representing the path to the file.

**Returns:**

[]string: Slice of strings where each element represents a line in the file. error: An error if the file cannot be read.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	if _, err := tmpfile.WriteString("Hello\nWorld"); err != nil {
		log.Printf("failed to write to temp file: %v", err)
		return
	}
	tmpfile.Close()

	lines, err := fileutils.ToSlice(tmpfile.Name())

	if err != nil {
		log.Printf("failed to read file: %v", err)
		return
	}

	for _, line := range lines {
		log.Println(line)
	}
}
Output:

func WriteTempFile added in v2.2.5

func WriteTempFile(workloadName string, jobFile *bytes.Buffer) (string, error)

WriteTempFile creates a temporary file in the system default temp directory, writes the contents from the provided buffer, and returns the file path.

**Parameters:**

workloadName: A string representing the base name of the temporary file. jobFile: A *bytes.Buffer containing the data to write to the temporary file.

**Returns:**

string: The name of the temporary file created. error: An error if any issue occurs during file creation or writing.

Types

type CreateType

type CreateType int

CreateType represents the type of file creation action to execute.

const (
	// CreateDirectory represents a directory creation action.
	CreateDirectory CreateType = iota
	// CreateEmptyFile represents an empty file creation action.
	CreateEmptyFile
	// CreateFile represents a file creation action.
	CreateFile
	// CreateTempFile represents a temporary file creation action.
	CreateTempFile
)

type File

type File interface {
	Open() (io.ReadCloser, error)
	Write(contents []byte, perm os.FileMode) error
	RemoveAll() error
	Stat() (os.FileInfo, error)
	Remove() error
}

File is an interface representing a system file.

**Methods:**

Open: Opens the file, returns a io.ReadCloser and an error. Write: Writes contents to the file, returns an error. RemoveAll: Removes a file or directory at the specified path, returns an error. Stat: Retrieves the FileInfo for the specified file or directory, returns an os.FileInfo and an error. Remove: Removes the specified file or directory, returns an error.

type RealFile

type RealFile string

RealFile is a concrete implementation of the File interface. It's used to operate with actual system files.

func (RealFile) Append

func (rf RealFile) Append(text string) error

Append adds a string to the end of a file. If the file doesn't exist, it's created with the default permissions.

**Parameters:**

text: String to append to the end of the file.

**Returns:**

error: An error if the file can't be opened or the string can't be written to the file.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	rf := fileutils.RealFile(tmpfile.Name())

	if err := rf.Append("Hello, World!"); err != nil {
		log.Printf("failed to append to file: %v", err)
		return
	}
}
Output:

func (RealFile) Open

func (rf RealFile) Open() (io.ReadCloser, error)

Open is a method for the RealFile type that opens the file and returns a io.ReadCloser and an error.

**Returns:**

io.ReadCloser: An object that allows reading from and closing the file. error: An error if any issue occurs while trying to open the file.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	rf := fileutils.RealFile(tmpfile.Name())

	reader, err := rf.Open()

	if err != nil {
		log.Printf("failed to open file: %v", err)
		return
	}

	_ = reader

	if err := reader.Close(); err != nil {
		log.Printf("failed to close file: %v", err)
		return
	}
}
Output:

func (RealFile) Remove

func (rf RealFile) Remove() error

Remove is a method for the RealFile type that removes the specified file or directory. Note that it will not remove a directory unless it is empty.

**Parameters:**

name: A string representing the path to the file or directory to remove.

**Returns:**

error: An error if any issue occurs while trying to remove the file or directory.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}

	rf := fileutils.RealFile(tmpfile.Name())

	if err := rf.Remove(); err != nil {
		log.Printf("failed to remove file: %v", err)
		return
	}
}
Output:

func (RealFile) RemoveAll

func (rf RealFile) RemoveAll() error

RemoveAll is a method for the RealFile type that removes a file or directory at the specified path. If the path represents a directory, RemoveAll will remove the directory and all its content.

**Parameters:**

path: A string representing the path to the file or directory to remove.

**Returns:**

error: An error if any issue occurs while trying to remove the file or directory.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpdir, err := os.MkdirTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp directory: %v", err)
		return
	}
	defer os.RemoveAll(tmpdir)

	rf := fileutils.RealFile(tmpdir)

	if err := rf.RemoveAll(); err != nil {
		log.Printf("failed to remove file or directory: %v", err)
		return
	}
}
Output:

func (RealFile) Stat

func (rf RealFile) Stat() (os.FileInfo, error)

Stat is a method for the RealFile type that retrieves the FileInfo for the specified file or directory.

**Parameters:**

name: A string representing the path to the file or directory.

**Returns:**

os.FileInfo: FileInfo describing the named file. error: An error if any issue occurs while trying to get the FileInfo.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	rf := fileutils.RealFile(tmpfile.Name())

	if _, err := rf.Stat(); err != nil {
		log.Printf("failed to get file stat: %v", err)
		return
	}
}
Output:

func (RealFile) Write

func (rf RealFile) Write(contents []byte, perm os.FileMode) error

Write is a method for the RealFile type that writes a slice of bytes to the file with specified file permissions.

**Parameters:**

contents: A slice of bytes that should be written to the file. mode: File permissions to use when creating the file.

**Returns:**

error: An error if any issue occurs while trying to write to the file.

Example
package main

import (
	"log"
	"os"

	fileutils "github.com/l50/goutils/v2/file/fileutils"
)

func main() {
	tmpfile, err := os.CreateTemp("", "example")
	if err != nil {
		log.Printf("failed to create temp file: %v", err)
		return
	}
	defer os.Remove(tmpfile.Name())

	rf := fileutils.RealFile(tmpfile.Name())

	err = rf.Write([]byte("Hello, World!"), 0644)

	if err != nil {
		log.Printf("failed to write to file: %v", err)
		return
	}
}
Output:

Jump to

Keyboard shortcuts

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