ronantakizawa/codereview-bench huggingface dataset:
Repository: syncthing/syncthing
File: lib/scanner/walk.go (Go)

Code before:
					return
				}
			}
		}()

	loop:
		for _, file := range filesToHash {
			l.Debugln("real to hash:", file.Name)
			select {
			case realToHashChan <- file:
			case <-ctx.Done():
				break loop
			}
		}
		close(realToHashChan)
	}()

	return finishedChan
}

func (w *walker) walkAndHashFiles(ctx context.Context, fchan, dchan chan protocol.FileInfo) fs.WalkFunc {
	var skip error // nil
	now := time.Now()
	ignoredParent := ""

	handleItem := func(path string) error {
		info, err := w.Filesystem.Lstat(path)
		// An error here would be weird as we've already gotten to this point, but act on it nonetheless
		if err != nil {
			return skip
		}

		path, shouldSkip := w.normalizePath(path, info)
		if shouldSkip {
			return skip
		}

		switch {
		case info.IsSymlink():
			if err := w.walkSymlink(ctx, path, dchan); err != nil {
				return err
			}
			if info.IsDir() {
				// under no circumstances shall we descend into a symlink
				return fs.SkipDir
			}
			return nil

		case info.IsDir():
			err = w.walkDir(ctx, path, info, dchan)


Review comment (suggestion):
Can this be a method instead of a closure? I see it uses skip, but this could be handled by the caller or be a parameter. It would reduce the mental stack depth to understand what's going on here

Code after:
					return
				}
			}
		}()

	loop:
		for _, file := range filesToHash {
			l.Debugln("real to hash:", file.Name)
			select {
			case realToHashChan <- file:
			case <-ctx.Done():
				break loop
			}
		}
		close(realToHashChan)
	}()

	return finishedChan
}

func (w *walker) walkAndHashFiles(ctx context.Context, fchan, dchan chan protocol.FileInfo) fs.WalkFunc {
	now := time.Now()
	ignoredParent := ""

	return func(path string, info fs.FileInfo, err error) error {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}

		// Return value used when we are returning early and don't want to
		// process the item. For directories, this means do-not-descend.
		var skip error // nil
		// info nil when error is not nil
		if info != nil && info.IsDir() {
			skip = fs.SkipDir
		}

		if err != nil {
			l.Debugln("error:", path, info, err)
			return skip
		}

		if path == "." {
			return nil
		}

		if fs.IsTemporary(path) {
			l.Debugln("temporary:", path)
			if info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
Repository: syncthing/syncthing
File: lib/model/folder.go (Go)

Code before:
	"github.com/syncthing/syncthing/lib/watchaggregator"
)

var errWatchNotStarted error = errors.New("not started")

type folder struct {
	stateTracker
	config.FolderConfiguration

	model   *Model
	shortID protocol.ShortID
	ctx     context.Context
	cancel  context.CancelFunc

	scan                folderScanner
	initialScanFinished chan struct{}

	pullScheduled chan struct{}

	watchCancel      context.CancelFunc
	watchChan        chan []string
	restartWatchChan chan struct{}
	watchErr         error
	watchErrMut      sync.Mutex

	puller puller
}

type puller interface {
	pull() (success bool)
}

func newFolder(model *Model, cfg config.FolderConfiguration) folder {
	ctx, cancel := context.WithCancel(context.Background())

	return folder{
		stateTracker:        newStateTracker(cfg.ID),
		FolderConfiguration: cfg,

		model:   model,
		shortID: model.shortID,
		ctx:     ctx,
		cancel:  cancel,

		scan:                newFolderScanner(cfg),
		initialScanFinished: make(chan struct{}),

		pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.

		watchCancel: func() {},
		watchErr:    errWatchNotStarted,

Review comment (suggestion):
Still feels that sendRcv et all should embed folder, and then derived can just implement their own pull (and base folder panics).

Code after:
	"github.com/syncthing/syncthing/lib/watchaggregator"
)

var errWatchNotStarted error = errors.New("not started")

type folder struct {
	stateTracker
	config.FolderConfiguration

	model   *Model
	shortID protocol.ShortID
	ctx     context.Context
	cancel  context.CancelFunc

	scan                folderScanner
	initialScanFinished chan struct{}

	pullScheduled chan struct{}

	watchCancel      context.CancelFunc
	watchChan        chan []string
	restartWatchChan chan struct{}
	watchErr         error
	watchErrMut      sync.Mutex

	puller puller
}

type puller interface {
	pull() bool // true when successfull and should not be retried
}

func newFolder(model *Model, cfg config.FolderConfiguration) folder {
	ctx, cancel := context.WithCancel(context.Background())

	return folder{
		stateTracker:        newStateTracker(cfg.ID),
		FolderConfiguration: cfg,

		model:   model,
		shortID: model.shortID,
		ctx:     ctx,
		cancel:  cancel,

		scan:                newFolderScanner(cfg),
		initialScanFinished: make(chan struct{}),

		pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.

		watchCancel: func() {},
		watchErr:    errWatchNotStarted,
Repository: syncthing/syncthing
File: lib/db/set_test.go (Go)

Code before:
	s.WithPrefixedHaveTruncated(protocol.LocalDeviceID, "dir/", func(fi db.FileIntf) bool {
		i++
		return true
	})
	if i != 1 {
		t.Errorf(`Expected 1, got %v local items below "dir/"`, i)
	}

	i = 0
	s.WithPrefixedHaveTruncated(protocol.LocalDeviceID, "dir", func(fi db.FileIntf) bool {
		i++
		return true
	})
	if i != 2 {
		t.Errorf(`Expected 2, got %v global items below "dir"`, i)
	}

	i = 0
	s.WithPrefixedGlobalTruncated("dir/", func(fi db.FileIntf) bool {
		i++
		return true
	})
	if i != 1 {
		t.Errorf(`Expected 1, got %v global items below "dir/"`, i)
	}
}

func replace(fs *db.FileSet, device protocol.DeviceID, files []protocol.FileInfo) {
	fs.Drop(device)
	fs.Update(device, files)
}


Review comment (bug):
Just out of curiosity, was this failing previously on second time iterating? If yes, that would mean the iterators are somehow stateful? If not, I am confused why you do the same thing twice.

Code after:

	localHave := fileList{
		protocol.FileInfo{Name: "dir"},
		protocol.FileInfo{Name: "dir.file"},
		protocol.FileInfo{Name: "dir/file"},
	}

	replace(s, protocol.LocalDeviceID, localHave)

	for _, prefix := range []string{"dir", "dir/"} {
		pl := haveListPrefixed(s, protocol.LocalDeviceID, prefix)
		if l := len(pl); l != 2 {
			t.Errorf("Expected 2, got %v local items below %v", l, prefix)
		}
		pl = globalListPrefixed(s, prefix)
		if l := len(pl); l != 2 {
			t.Errorf("Expected 2, got %v global items below %v", l, prefix)
		}
	}
}

func replace(fs *db.FileSet, device protocol.DeviceID, files []protocol.FileInfo) {
	fs.Drop(device)
	fs.Update(device, files)
}
Repository: syncthing/syncthing
File: lib/db/leveldb_dbinstance.go (Go)

Code before:
		t.Delete(dbi.Key())
	}
}

func unmarshalTrunc(bs []byte, truncate bool) (FileIntf, error) {
	if truncate {
		var tf FileInfoTruncated
		err := tf.Unmarshal(bs)
		return tf, err
	}

	var tf protocol.FileInfo
	err := tf.Unmarshal(bs)
	return tf, err
}

func unmarshalVersionList(data []byte) (VersionList, bool) {
	var vl VersionList
	if err := vl.Unmarshal(data); err != nil {
		l.Debugln("unmarshal error:", err)
		return VersionList{}, false
	}
	if len(vl.Versions) == 0 {
		l.Debugln("empty version list")
		return VersionList{}, false
	}
	return vl, true
}

// A "better" version of leveldb's errors.IsCorrupted.
func leveldbIsCorrupted(err error) bool {
	switch {
	case err == nil:
		return false

	case errors.IsCorrupted(err):
		return true

	case strings.Contains(err.Error(), "corrupted"):
		return true
	}

	return false
}

// A smallIndex is an in memory bidirectional []byte to uint32 map. It gives
// fast lookups in both directions and persists to the database. Don't use for
// storing more items than fit comfortably in RAM.
type smallIndex struct {
	db     *Instance
	prefix []byte

Review comment (bug):
I can't see how these debug logs are useful, they would appear thousands and thousands of times in a db walk, amd include no indication which file they are talking about etc. I'd just remove them.

Code after:

	for dbi.Next() {
		t.Delete(dbi.Key())
	}
}

func unmarshalTrunc(bs []byte, truncate bool) (FileIntf, error) {
	if truncate {
		var tf FileInfoTruncated
		err := tf.Unmarshal(bs)
		return tf, err
	}

	var tf protocol.FileInfo
	err := tf.Unmarshal(bs)
	return tf, err
}

func unmarshalVersionList(data []byte) (VersionList, bool) {
	var vl VersionList
	if err := vl.Unmarshal(data); err != nil {
		l.Debugln("unmarshal error:", err)
		return VersionList{}, false
	}
	if len(vl.Versions) == 0 {
		l.Debugln("empty version list")
		return VersionList{}, false
	}
	return vl, true
}

// A "better" version of leveldb's errors.IsCorrupted.
func leveldbIsCorrupted(err error) bool {
	switch {
	case err == nil:
		return false

	case errors.IsCorrupted(err):
		return true

	case strings.Contains(err.Error(), "corrupted"):
		return true
	}

	return false
}

// A smallIndex is an in memory bidirectional []byte to uint32 map. It gives
// fast lookups in both directions and persists to the database. Don't use for
// storing more items than fit comfortably in RAM.
type smallIndex struct {
Repository: syncthing/syncthing
File: lib/db/leveldb_dbinstance.go (Go)

Code before:
}

func (db *Instance) withHave(folder, device, prefix []byte, truncate bool, fn Iterator) {
	if len(prefix) > 0 && !bytes.HasSuffix(prefix, []byte{'/'}) {
		f, ok := db.getFileTrunc(db.deviceKey(folder, device, prefix), true)
		if !ok {
			// nothing to be done if the root element doesn't exist
			return
		}
		if !fn(f) {
			return
		}
		prefix = append(prefix, '/')
	}

	t := db.newReadOnlyTransaction()
	defer t.close()

	dbi := t.NewIterator(util.BytesPrefix(db.deviceKey(folder, device, prefix)[:keyPrefixLen+keyFolderLen+keyDeviceLen+len(prefix)]), nil)
	defer dbi.Release()

	for dbi.Next() {
		name := db.deviceKeyName(dbi.Key())
		if len(prefix) > 0 && !bytes.HasPrefix(name, prefix) {
			return
		}

		// The iterator function may keep a reference to the unmarshalled
		// struct, which in turn references the buffer it was unmarshalled
		// from. dbi.Value() just returns an internal slice that it reuses, so
		// we need to copy it.
		f, err := unmarshalTrunc(append([]byte{}, dbi.Value()...), truncate)
		if err != nil {
			l.Debugln("unmarshal error:", err)
			continue
		}
		if !fn(f) {
			return
		}
	}
}

func (db *Instance) withHaveSequence(folder []byte, startSeq int64, fn Iterator) {
	t := db.newReadOnlyTransaction()
	defer t.close()

	dbi := t.NewIterator(&util.Range{Start: db.sequenceKey(folder, startSeq), Limit: db.sequenceKey(folder, maxInt64)}, nil)
	defer dbi.Release()

	for dbi.Next() {
		f, ok := db.getFile(dbi.Value())

Review comment (suggestion):
So this no longer walks the directory itself? I think that's not how it should work, as I think walk returns the directory.

Code after:
}

func (db *Instance) withHave(folder, device, prefix []byte, truncate bool, fn Iterator) {
	if len(prefix) > 0 {
		unslashedPrefix := prefix
		if bytes.HasSuffix(prefix, []byte{'/'}) {
			unslashedPrefix = unslashedPrefix[:len(unslashedPrefix)-1]
		} else {
			prefix = append(prefix, '/')
		}

		if f, ok := db.getFileTrunc(db.deviceKey(folder, device, unslashedPrefix), true); ok && !fn(f) {
			return
		}
	}

	t := db.newReadOnlyTransaction()
	defer t.close()

	dbi := t.NewIterator(util.BytesPrefix(db.deviceKey(folder, device, prefix)[:keyPrefixLen+keyFolderLen+keyDeviceLen+len(prefix)]), nil)
	defer dbi.Release()

	for dbi.Next() {
		name := db.deviceKeyName(dbi.Key())
		if len(prefix) > 0 && !bytes.HasPrefix(name, prefix) {
			return
		}

		// The iterator function may keep a reference to the unmarshalled
		// struct, which in turn references the buffer it was unmarshalled
		// from. dbi.Value() just returns an internal slice that it reuses, so
		// we need to copy it.
		f, err := unmarshalTrunc(append([]byte{}, dbi.Value()...), truncate)
		if err != nil {
			l.Debugln("unmarshal error:", err)
			continue
		}
		if !fn(f) {
			return
		}
	}
}

func (db *Instance) withHaveSequence(folder []byte, startSeq int64, fn Iterator) {
	t := db.newReadOnlyTransaction()
	defer t.close()

	dbi := t.NewIterator(&util.Range{Start: db.sequenceKey(folder, startSeq), Limit: db.sequenceKey(folder, maxInt64)}, nil)
	defer dbi.Release()

	for dbi.Next() {
Repository: syncthing/syncthing
File: lib/events/events.go (Go)

Code before:
		return "ConfigSaved"
	case DownloadProgress:
		return "DownloadProgress"
	case RemoteDownloadProgress:
		return "RemoteDownloadProgress"
	case FolderSummary:
		return "FolderSummary"
	case FolderCompletion:
		return "FolderCompletion"
	case FolderErrors:
		return "FolderErrors"
	case DevicePaused:
		return "DevicePaused"
	case DeviceResumed:
		return "DeviceResumed"
	case FolderScanProgress:
		return "FolderScanProgress"
	case FolderPaused:
		return "FolderPaused"
	case FolderResumed:
		return "FolderResumed"
	case ListenAddressesChanged:
		return "ListenAddressesChanged"
	case LoginAttempt:
		return "LoginAttempt"
	case FolderWatcherStateChanged:
		return "FolderWatcherStateChanged"
	default:
		return "Unknown"
	}
}

func (t EventType) MarshalText() ([]byte, error) {
	return []byte(t.String()), nil
}

func (t *EventType) UnmarshalJSON(b []byte) error {
	var s string

	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}

	*t = UnmarshalEventType(s)

	return nil
}

func UnmarshalEventType(s string) EventType {
	switch s {
	case "Starting":

Review comment (suggestion):
Perhaps FolderWatcherErrorStateChanged?
As it's not generic state changing.

Code after:
		return "ConfigSaved"
	case DownloadProgress:
		return "DownloadProgress"
	case RemoteDownloadProgress:
		return "RemoteDownloadProgress"
	case FolderSummary:
		return "FolderSummary"
	case FolderCompletion:
		return "FolderCompletion"
	case FolderErrors:
		return "FolderErrors"
	case DevicePaused:
		return "DevicePaused"
	case DeviceResumed:
		return "DeviceResumed"
	case FolderScanProgress:
		return "FolderScanProgress"
	case FolderPaused:
		return "FolderPaused"
	case FolderResumed:
		return "FolderResumed"
	case ListenAddressesChanged:
		return "ListenAddressesChanged"
	case LoginAttempt:
		return "LoginAttempt"
	case FolderWatchStateChanged:
		return "FolderWatchStateChanged"
	default:
		return "Unknown"
	}
}

func (t EventType) MarshalText() ([]byte, error) {
	return []byte(t.String()), nil
}

func (t *EventType) UnmarshalJSON(b []byte) error {
	var s string

	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}

	*t = UnmarshalEventType(s)

	return nil
}

func UnmarshalEventType(s string) EventType {
	switch s {
	case "Starting":
Repository: syncthing/syncthing
File: lib/events/events.go (Go)

Code before:
	Starting EventType = 1 << iota
	StartupComplete
	DeviceDiscovered
	DeviceConnected
	DeviceDisconnected
	DeviceRejected
	DevicePaused
	DeviceResumed
	LocalChangeDetected
	RemoteChangeDetected
	LocalIndexUpdated
	RemoteIndexUpdated
	ItemStarted
	ItemFinished
	StateChanged
	FolderRejected
	ConfigSaved
	DownloadProgress
	RemoteDownloadProgress
	FolderSummary
	FolderCompletion
	FolderErrors
	FolderScanProgress
	FolderPaused
	FolderResumed
	FolderWatcherErrorStateChanged
	ListenAddressesChanged
	LoginAttempt

	AllEvents = (1 << iota) - 1
)

var runningTests = false

const eventLogTimeout = 15 * time.Millisecond

func (t EventType) String() string {
	switch t {
	case Starting:
		return "Starting"
	case StartupComplete:
		return "StartupComplete"
	case DeviceDiscovered:
		return "DeviceDiscovered"
	case DeviceConnected:
		return "DeviceConnected"
	case DeviceDisconnected:
		return "DeviceDisconnected"
	case DeviceRejected:
		return "DeviceRejected"
	case LocalChangeDetected:

Review comment (suggestion):
Can we call this FolderWatchStateChanged, just in case there are more than one stage in the future, and we could reuse the event.

Code after:
	Starting EventType = 1 << iota
	StartupComplete
	DeviceDiscovered
	DeviceConnected
	DeviceDisconnected
	DeviceRejected
	DevicePaused
	DeviceResumed
	LocalChangeDetected
	RemoteChangeDetected
	LocalIndexUpdated
	RemoteIndexUpdated
	ItemStarted
	ItemFinished
	StateChanged
	FolderRejected
	ConfigSaved
	DownloadProgress
	RemoteDownloadProgress
	FolderSummary
	FolderCompletion
	FolderErrors
	FolderScanProgress
	FolderPaused
	FolderResumed
	FolderWatchStateChanged
	ListenAddressesChanged
	LoginAttempt

	AllEvents = (1 << iota) - 1
)

var runningTests = false

const eventLogTimeout = 15 * time.Millisecond

func (t EventType) String() string {
	switch t {
	case Starting:
		return "Starting"
	case StartupComplete:
		return "StartupComplete"
	case DeviceDiscovered:
		return "DeviceDiscovered"
	case DeviceConnected:
		return "DeviceConnected"
	case DeviceDisconnected:
		return "DeviceDisconnected"
	case DeviceRejected:
		return "DeviceRejected"
	case LocalChangeDetected:
Repository: syncthing/syncthing
File: lib/scanner/walk.go (Go)

Code before:
		}
		if info.IsDir() {
			// under no circumstances shall we descend into a symlink
			return fs.SkipDir
		}
		return nil

	case info.IsDir():
		err = w.walkDir(ctx, path, info, dchan)

	case info.IsRegular():
		err = w.walkRegular(ctx, path, info, fchan)
	}

	return err
}

func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, fchan chan protocol.FileInfo) error {
	curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)

	newMode := uint32(info.Mode())
	if runtime.GOOS == "windows" {
		if osutil.IsWindowsExecutable(relPath) {
			newMode |= 0111
		}
		if hasCurFile {
			newMode |= (0111 & curFile.Permissions)
		}
	}

	blockSize := protocol.MinBlockSize

	if w.UseLargeBlocks {
		blockSize = protocol.BlockSize(info.Size())

		if hasCurFile {
			// Check if we should retain current block size.
			curBlockSize := curFile.BlockSize()
			if blockSize > curBlockSize && blockSize/curBlockSize <= 2 {
				// New block size is larger, but not more than twice larger.
				// Retain.
				blockSize = curBlockSize
			} else if curBlockSize > blockSize && curBlockSize/blockSize <= 2 {
				// Old block size is larger, but not more than twice larger.
				// Retain.
				blockSize = curBlockSize
			}
		}
	}

	f := protocol.FileInfo{

Review comment (suggestion):
else if
Also I'd add a comment about why to do this, not having the fixed issue in mind, this change looks pretty mysterious.

Code after:
		}
		if info.IsDir() {
			// under no circumstances shall we descend into a symlink
			return fs.SkipDir
		}
		return nil

	case info.IsDir():
		err = w.walkDir(ctx, path, info, dchan)

	case info.IsRegular():
		err = w.walkRegular(ctx, path, info, fchan)
	}

	return err
}

func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, fchan chan protocol.FileInfo) error {
	curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)

	newMode := uint32(info.Mode())
	if runtime.GOOS == "windows" {
		if osutil.IsWindowsExecutable(relPath) {
			// Set executable bits on files with executable extenions (.exe,
			// .bat, etc).
			newMode |= 0111
		} else if hasCurFile {
			// If we have an existing index entry, copy the executable bits
			// from there.
			newMode |= (curFile.Permissions & 0111)
		}
	}

	blockSize := protocol.MinBlockSize

	if w.UseLargeBlocks {
		blockSize = protocol.BlockSize(info.Size())

		if hasCurFile {
			// Check if we should retain current block size.
			curBlockSize := curFile.BlockSize()
			if blockSize > curBlockSize && blockSize/curBlockSize <= 2 {
				// New block size is larger, but not more than twice larger.
				// Retain.
				blockSize = curBlockSize
			} else if curBlockSize > blockSize && curBlockSize/blockSize <= 2 {
				// Old block size is larger, but not more than twice larger.
				// Retain.
				blockSize = curBlockSize
			}
		}
Repository: syncthing/syncthing
File: lib/fs/basicfs_windows.go (Go)

Code before:

	hr, _, _ := getLogicalDriveStringsHandle.Call(uintptr(unsafe.Pointer(&bufferSize)), uintptr(unsafe.Pointer(&buffer)))
	if hr == 0 {
		return nil, fmt.Errorf("Syscall failed")
	}

	var drives []string
	parts := bytes.Split(buffer[:], []byte{0})
	for _, part := range parts {
		if len(part) == 0 {
			break
		}
		drives = append(drives, string(part))
	}

	return drives, nil
}

func (f *BasicFilesystem) resolveWin83(absPath string) string {
	if !strings.Contains(absPath, "~") {
		return absPath
	}
	if in, err := syscall.UTF16FromString(absPath); err != nil {
		out := make([]uint16, 2*len(absPath))
		n := uint32(len(out))
		for {
			n, err = syscall.GetLongPathName(&in[0], &out[0], n)
			if err != nil {
				break
			}
			if n <= uint32(len(out)) {
				return syscall.UTF16ToString(out[:n])
			}
			out = make([]uint16, n)
		}
	}
	// Failed getting the long path. Return the part of the path which is
	// already a long path.
	for absPath = filepath.Dir(absPath); strings.HasPrefix(absPath, f.rootSymlinkEvaluated); absPath = filepath.Dir(absPath) {
		if !strings.Contains(absPath, "~") {
			return absPath
		}
	}
	return f.rootSymlinkEvaluated
}


Review comment (suggestion):
Not sure I agree with the use of a loop - you should only need to call `GetLongPathName` twice, at max. That can be handled by an `if` statement. 

Code after:

	hr, _, _ := getLogicalDriveStringsHandle.Call(uintptr(unsafe.Pointer(&bufferSize)), uintptr(unsafe.Pointer(&buffer)))
	if hr == 0 {
		return nil, fmt.Errorf("Syscall failed")
	}

	var drives []string
	parts := bytes.Split(buffer[:], []byte{0})
	for _, part := range parts {
		if len(part) == 0 {
			break
		}
		drives = append(drives, string(part))
	}

	return drives, nil
}

func (f *BasicFilesystem) resolveWin83(absPath string) string {
	if !isMaybeWin83(absPath) {
		return absPath
	}
	if in, err := syscall.UTF16FromString(absPath); err == nil {
		out := make([]uint16, 4*len(absPath)) // *2 for UTF16 and *2 to double path length
		if n, err := syscall.GetLongPathName(&in[0], &out[0], uint32(len(out))); err == nil {
			if n <= uint32(len(out)) {
				return syscall.UTF16ToString(out[:n])
			}
			out = make([]uint16, n)
			if _, err = syscall.GetLongPathName(&in[0], &out[0], n); err == nil {
				return syscall.UTF16ToString(out)
			}
		}
	}
	// Failed getting the long path. Return the part of the path which is
	// already a long path.
	for absPath = filepath.Dir(absPath); strings.HasPrefix(absPath, f.rootSymlinkEvaluated); absPath = filepath.Dir(absPath) {
		if !isMaybeWin83(absPath) {
			return absPath
		}
	}
	return f.rootSymlinkEvaluated
}

func isMaybeWin83(absPath string) bool {
	if !strings.Contains(absPath, "~") {
		return false
	}
	if strings.Contains(filepath.Dir(absPath), "~") {
		return true
	}