Skip to content

Commit

Permalink
feat: add GetUserHomeDir and WriteTmpFile (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
xoxys authored May 6, 2024
1 parent c48fbf9 commit df36058
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
18 changes: 18 additions & 0 deletions file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 64 additions & 0 deletions file/file_test.go
Original file line number Diff line number Diff line change
@@ -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 changes: 15 additions & 0 deletions util/user.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit df36058

Please sign in to comment.