Skip to content

Commit

Permalink
break out just effectiveStartingDir
Browse files Browse the repository at this point in the history
This implements just the effectiveStartingDir() and a basic test from PR fyne-io#1108.
It does provide the ability to set a custom starting dir.
  • Loading branch information
charlesdaniels committed Jun 16, 2020
1 parent 8f5467d commit 76c6dde
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
29 changes: 29 additions & 0 deletions dialog/file.go
Expand Up @@ -262,6 +262,35 @@ func (f *fileDialog) setSelected(file *fileDialogItem) {
}
}

// effectiveStartingDir calculates the directory at which the file dialog
// should open, based on the values of CWD, home, and any error conditions
// which occur.
//
// Order of precedence is:
//
// * os.Getwd()
// * os.UserHomeDir()
// * "/" (should be filesystem root on all supported platforms)
func (f *FileDialog) effectiveStartingDir() string {

// Try to use CWD
var err error = nil
dir, err := os.Getwd()
if err == nil {
return dir
}
fyne.LogError("Could not load CWD", err)

// fail over to home dir
dir, err = os.UserHomeDir()
if err == nil {
return dir
}
fyne.LogError("Could not load user home dir", err)

return "/"
}

func showFile(file *FileDialog) *fileDialog {
d := &fileDialog{file: file}
ui := d.makeUI()
Expand Down
45 changes: 45 additions & 0 deletions dialog/file_test.go
Expand Up @@ -15,6 +15,51 @@ import (
"fyne.io/fyne/widget"
)

// comparePaths compares if two file paths point to the same thing, and calls
// t.Fatalf() if there is an error in performing the comparison.
//
// Returns true of both paths point to the same thing.
//
// You should use this if you need to compare file paths, since it explicitly
// normalizes the paths to a stable canonical form. It also nicely
// abstracts out the requisite error handling.
//
// You should only call this function on paths that you expect to be valid.
func comparePaths(t *testing.T, p1, p2 string) bool {
a1, err := filepath.Abs(p1)
if err != nil {
t.Fatalf("Failed to normalize path '%s'", p1)
}

a2, err := filepath.Abs(p2)
if err != nil {
t.Fatalf("Failed to normalize path '%s'", p2)
}

return a1 == a2
}

func TestEffectiveStartingDir(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Skipf("os.Getwd() failed, cannot run this test on this system (error getting ./), error was '%s'", err)
}

dialog := &FileDialog{}

// test that we get ./ when running with the default struct values
res := dialog.effectiveStartingDir()
expect := wd
if err != nil {
t.Skipf("os.Getwd() failed, cannot run this test on this system, error was '%s'", err)
}
if !comparePaths(t, res, expect) {
t.Errorf("Expected effectiveStartingDir() to be '%s', but it was '%s'",
expect, res)
}

}

func TestShowFileOpen(t *testing.T) {
var chosen fyne.URIReadCloser
var openErr error
Expand Down

0 comments on commit 76c6dde

Please sign in to comment.