diff --git a/mc_work/dorun.go b/mc_work/dorun.go index a6d4f7e687845f73c800c4e7b912431d0f6a76fa..b3d338dc13996db3239d52c3b7d67c57142898b4 100644 --- a/mc_work/dorun.go +++ b/mc_work/dorun.go @@ -11,6 +11,7 @@ import ( "math" "math/rand" "os" + "path/filepath" "sync" "example.com/ackley_mc/ackley" @@ -66,37 +67,45 @@ func isNotSane(mcPrm *McPrm) error { // fExists returns true if the file exists. // It is part of the exercise, working around file permissions on windows -func fExists (name string) bool { +func fExists(name string) bool { var err error - if _, err := os.Stat (name); err == nil { + if _, err = os.Stat(name); err == nil { return true } - if errors.Is (err, fs.ErrNotExist) { + if errors.Is(err, fs.ErrNotExist) { return false } return true } - // createFix is a wrapper around os.Create() which I seem to need for windows. // On windows, I cannot overwrite an existing file. To be very exact, the // O_CREATE fails if a file exists. O_TRUNC also fails. -func createFix (name string) (*os.File, error) { - var rErr = `Remove the file %s and try again. This only happens on windows: %w` +// Doing an open on the file gives the same, "The system cannot find the file specified" +// The calls fail, even if the file does not exist. It must be a problem +// with permissions on the directory, not the file. +func createFix(name string) (*os.File, error) { + longErr := `%s does not exist, but could not create it. +Tried setting pemissions on directory %s, but failed: +%w` var f *os.File var err error if f, err = os.Create(name); err == nil { return f, nil // Most common path (no problem) } - - if !fExists(name) { // does not exist, but we have a real error. - return nil, err // Return original error - } // Next step try to remove original file - if e := os.Remove (name); e != nil { - return nil, fmt.Errorf (rErr, name, e) - } - if f, err = os.Create(name); err == nil { // second attempt, after removing name - return f, nil + if !fExists(name) { // does not exist, but we have a problem. + var t string + if t, err = filepath.Abs(name); err != nil { + return nil, fmt.Errorf("cannot work out path %w", err) + } + d := filepath.Dir(t) + e := os.Chmod(d, 0200) + if e != nil { + return nil, fmt.Errorf(longErr, name, d, e) + } + + } else { // the file exists + fmt.Println("file exists, what to do ?") } return nil, err }