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:
parent
c48fbf9bd7
commit
df36058fa9
18
file/file.go
18
file/file.go
@ -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
64
file/file_test.go
Normal 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
15
util/user.go
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user