0

I'm trying to mirror the functionality of other programs like the awscli and oh-my-zsh, where they're able to programmatically generate files in the current user's home directory, but I'm running into an issue with replicating this functionality.

My guess is that it's something to do with the permissions param (2nd param in os.MkdirAll), due to the syscall.Errno(30) I'm receiving back, but I'm not super sure what the correct permission to pass in is.

fullPath := /.testProject/config
// check if the file exists
if _, err = os.Stat(fullPath); err != nil {
    // if it doesn't exist, create it
    if err = os.MkdirAll(fullPath, 0700); err != nil {
        // currently errors out to `(*fs.PathError){Op:"mkdir", 
        //     Path:"/.testProject", Err:syscall.Errno(30)}
        return err
    }
}
// return nil if successful write to 
// $HOME/.testProject/config
return nil

Solution

s/o to @larsks for helping me remember how to fetch home directories. Final working code block:

dirname, err := os.UserHomeDir()
if err != nil {
    return err
}
fullPath := dirname + "/.testProject/config"
// check if the file exists
if _, err = os.Stat(fullPath); err != nil {
    // if it doesn't exist, create it
    if err = os.MkdirAll(fullPath, 0700); err != nil {
        return err
    }
}
// creates file at $HOME/.testProject/config
return nil
Rachel Sheikh
  • 81
  • 1
  • 3
  • 2
    You're not going to be able to create `/.testProject` unless you're `root`, and even then it's unlikely you want to create a directory in `/`. Most of the tools you've mentioned create files/directories in the user's **home** directory. – larsks Sep 20 '22 at 02:30
  • Updated the question, creating it in the home directory is definitely what I'm looking for – Rachel Sheikh Sep 20 '22 at 02:32
  • 1
    So the problem still remains; you're using the path `/.testProject/config`, which doesn't point into the user's home directory. Maybe you're look for [this question](https://stackoverflow.com/questions/7922270/obtain-users-home-directory)? – larsks Sep 20 '22 at 02:33
  • 1
    That did the trick @larsks, thank you! – Rachel Sheikh Sep 20 '22 at 02:35
  • 1
    Please use [`filepath.Join()`](https://pkg.go.dev/path/filepath#Join) to join $HOME to your directory. Also, you don't need to call `os.Stat()` before `os.MkDirAll()` to check if the directory exists because `os.MkDirAll()` will do nothing if the directory already exists. `If path is already a directory, MkdirAll does nothing and returns nil.` [doc](https://pkg.go.dev/os#MkdirAll) – Benny Jobigan Sep 20 '22 at 06:10

0 Answers0