Documentation ¶
Index ¶
- func CSVToLines(path string) ([][]string, error)
- func Create(path string, contents []byte, createType CreateType) (string, error)
- func Delete(path string) error
- func Exists(fileLoc string) bool
- func Find(fileName string, dirs []string) ([]string, error)
- func HasStr(path string, searchStr string) (bool, error)
- func ListR(dirPath string) ([]string, error)
- func SeekAndDestroy(path string, pattern string) error
- func ToSlice(path string) ([]string, error)
- func WriteTempFile(workloadName string, jobFile *bytes.Buffer) (string, error)
- type CreateType
- type File
- type RealFile
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CSVToLines ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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: