github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/flock/flock_windows.go (about)

     1  // +build windows
     2  
     3  package flock
     4  
     5  import (
     6  	"syscall"
     7  )
     8  
     9  // FileLockGuard holds a lock of file on a directory.
    10  type FileLockGuard struct {
    11  	// file descriptor on directory.
    12  	fd syscall.Handle
    13  }
    14  
    15  // AcquireFileLock acquire the lock on the directory by syscall.Flock.
    16  // Return a FileLockGuard or an error, if any.
    17  func AcquireFileLock(path string, readOnly bool) (*FileLockGuard, error) {
    18  	ptr, err := syscall.UTF16PtrFromString(path)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	var access, mode uint32
    24  	if readOnly {
    25  		access = syscall.GENERIC_READ
    26  		mode = syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE
    27  	} else {
    28  		access = syscall.GENERIC_READ | syscall.GENERIC_WRITE
    29  	}
    30  
    31  	file, err := syscall.CreateFile(ptr, access, mode, nil,
    32  		syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
    33  	if err == syscall.ERROR_FILE_NOT_FOUND {
    34  		file, err = syscall.CreateFile(ptr, access, mode, nil,
    35  			syscall.OPEN_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0)
    36  	}
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	return &FileLockGuard{fd: file}, nil
    41  }
    42  
    43  // SyncDir do nothing in windows.
    44  func SyncDir(name string) error {
    45  	return nil
    46  }
    47  
    48  // Release release the file lock.
    49  func (fl *FileLockGuard) Release() error {
    50  	return syscall.Close(fl.fd)
    51  }