0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-11-21 04:00:40 +00:00

feat: add GetUserHomeDir and WriteTmpFile (#78)

This commit is contained in:
Robert Kaussow 2024-05-06 14:27:56 +02:00 committed by GitHub
parent c48fbf9bd7
commit df36058fa9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 97 additions and 0 deletions

View File

@ -54,3 +54,21 @@ func ExpandFileList(fileList []string) ([]string, error) {
return result, nil
}
// WriteTmpFile creates a temporary file with the given name and content, and returns the path to the created file.
func WriteTmpFile(name, content string) (string, error) {
tmpfile, err := os.CreateTemp("", name)
if err != nil {
return "", err
}
if _, err := tmpfile.Write([]byte(content)); err != nil {
return "", err
}
if err := tmpfile.Close(); err != nil {
return "", err
}
return tmpfile.Name(), nil
}

64
file/file_test.go Normal file
View File

@ -0,0 +1,64 @@
package file
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
const helloWorld = "Hello, World!"
func TestWriteTmpFile(t *testing.T) {
tests := []struct {
name string
fileName string
content string
wantErr bool
}{
{
name: "write to temp file",
fileName: "test.txt",
content: helloWorld,
wantErr: false,
},
{
name: "empty file name",
fileName: "",
content: helloWorld,
wantErr: false,
},
{
name: "empty file content",
fileName: "test.txt",
content: "",
wantErr: false,
},
{
name: "create temp file error",
fileName: filepath.Join(os.TempDir(), "non-existent", "test.txt"),
content: helloWorld,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpFile, err := WriteTmpFile(tt.fileName, tt.content)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
defer os.Remove(tmpFile)
data, err := os.ReadFile(tmpFile)
assert.NoError(t, err)
assert.Equal(t, tt.content, string(data))
})
}
}

15
util/user.go Normal file
View File

@ -0,0 +1,15 @@
package util
import "os/user"
// GetUserHomeDir returns the home directory path for the current user.
// If the current user cannot be determined, it returns the default "/root" path.
func GetUserHomeDir() string {
home := "/root"
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
}
return home
}