github.com/anacrolix/torrent@v1.61.0/storage/file-io-common.go (about)

     1  package storage
     2  
     3  import (
     4  	"errors"
     5  	"io/fs"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/anacrolix/missinggo/v2/panicif"
    10  )
    11  
    12  // Opens file for write, creating dirs and fixing permissions as necessary.
    13  func openFileExtra(p string, osRdwr int) (f *os.File, err error) {
    14  	panicif.NotZero(osRdwr & ^(os.O_RDONLY | os.O_RDWR | os.O_WRONLY))
    15  	flag := osRdwr | os.O_CREATE
    16  	f, err = os.OpenFile(p, flag, filePerm)
    17  	if err == nil {
    18  		return
    19  	}
    20  	if errors.Is(err, fs.ErrNotExist) {
    21  		err = os.MkdirAll(filepath.Dir(p), dirPerm)
    22  		if err != nil {
    23  			return
    24  		}
    25  	} else if errors.Is(err, fs.ErrPermission) {
    26  		err = os.Chmod(p, filePerm)
    27  		if err != nil {
    28  			return
    29  		}
    30  	} else {
    31  		return
    32  	}
    33  	f, err = os.OpenFile(p, flag, filePerm)
    34  	return
    35  }