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

Code before:
	}
	if &compressed[0] != &buf[0] {
		panic("bug: lz4.Compress allocated, which it must not (should use buffer pool)")
	}

	binary.BigEndian.PutUint32(compressed, binary.LittleEndian.Uint32(compressed))
	return compressed, nil
}

func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
	size := binary.BigEndian.Uint32(src)
	binary.LittleEndian.PutUint32(src, size)
	var err error
	buf := BufferPool.Get(int(size))
	decoded, err := lz4.Decode(buf, src)
	if err != nil {
		BufferPool.Put(buf)
		return nil, err
	}
	if &decoded[0] != &buf[0] {
		panic("bug: lz4.Decode allocated, which it must not (should use buffer pool)")
	}
	return decoded, nil
}

type ProtocolError commonError

func newProtocolError(err error, msgContext string) *ProtocolError {
	return (*ProtocolError)(newCommonError(err, msgContext))
}

func (e *ProtocolError) Error() string {
	return fmt.Sprintf("protocol error on %v: %v", e.msgContext, e.err)
}

type HandleError commonError

func newHandleError(err error, msgContext string) *HandleError {
	return (*HandleError)(newCommonError(err, msgContext))
}

func (e *HandleError) Error() string {
	return fmt.Sprintf("handling %v: %v", e.msgContext, e.err)
}

type commonError struct {
	err        error
	msgContext string
}

func newCommonError(err error, msgContext string) *commonError {

Review comment (suggestion):
ProtocolError doesn't inherit Unwrap, should probably be a wrapping struct instead (same for HandleError), or just have the two fields and the unwrap explicitly

Code after:
	}
	if &compressed[0] != &buf[0] {
		panic("bug: lz4.Compress allocated, which it must not (should use buffer pool)")
	}

	binary.BigEndian.PutUint32(compressed, binary.LittleEndian.Uint32(compressed))
	return compressed, nil
}

func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
	size := binary.BigEndian.Uint32(src)
	binary.LittleEndian.PutUint32(src, size)
	var err error
	buf := BufferPool.Get(int(size))
	decoded, err := lz4.Decode(buf, src)
	if err != nil {
		BufferPool.Put(buf)
		return nil, err
	}
	if &decoded[0] != &buf[0] {
		panic("bug: lz4.Decode allocated, which it must not (should use buffer pool)")
	}
	return decoded, nil
}

func newProtocolError(err error, msgContext string) error {
	return fmt.Errorf("protocol error on %v: %w", msgContext, err)
}

func newHandleError(err error, msgContext string) error {
	return fmt.Errorf("handling %v: %w", msgContext, err)
}

func messageContext(msg message) (string, error) {
	switch msg := msg.(type) {
	case *ClusterConfig:
		return "cluster-config", nil
	case *Index:
		return fmt.Sprintf("index for %v", msg.Folder), nil
	case *IndexUpdate:
		return fmt.Sprintf("index-update for %v", msg.Folder), nil
	case *Request:
		return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
	case *Response:
		return "response", nil
	case *DownloadProgress:
		return fmt.Sprintf("download-progress for %v", msg.Folder), nil
	case *Ping:
		return "ping", nil
	case *Close:
		return "close", nil
Repository: syncthing/syncthing
File: lib/protocol/protocol.go (Go)

Code before:
	buf := BufferPool.Get(int(size))
	decoded, err := lz4.Decode(buf, src)
	if err != nil {
		BufferPool.Put(buf)
		return nil, err
	}
	if &decoded[0] != &buf[0] {
		panic("bug: lz4.Decode allocated, which it must not (should use buffer pool)")
	}
	return decoded, nil
}

type unwrapError interface {
	error
	Unwrap() error
}

type ProtocolError struct {
	unwrapError
}

func newProtocolError(err error, msgContext string) *ProtocolError {
	return &ProtocolError{
		unwrapError: fmt.Errorf("protocol error on %v: %w", msgContext, err).(unwrapError),
	}
}

type HandleError struct {
	unwrapError
}

func newHandleError(err error, msgContext string) *HandleError {
	return &HandleError{
		unwrapError: fmt.Errorf("handling %v: %w", msgContext, err).(unwrapError),
	}
}

func messageContext(msg message) (string, error) {
	switch msg := msg.(type) {
	case *ClusterConfig:
		return "cluster-config", nil
	case *Index:
		return fmt.Sprintf("index for %v", msg.Folder), nil
	case *IndexUpdate:
		return fmt.Sprintf("index-update for %v", msg.Folder), nil
	case *Request:
		return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
	case *Response:
		return "response", nil
	case *DownloadProgress:
		return fmt.Sprintf("download-progress for %v", msg.Folder), nil

Review comment (suggestion):
```suggestion
func protocolError(err error, msgContext string) error {
	return fmt.Errorf("protocol error on %v: %w", msgContext, err)
}
```

I mean, at this point we don't use the types for formatting or recognition, so we could skip having them :)

Code after:
	buf := BufferPool.Get(int(size))
	decoded, err := lz4.Decode(buf, src)
	if err != nil {
		BufferPool.Put(buf)
		return nil, err
	}
	if &decoded[0] != &buf[0] {
		panic("bug: lz4.Decode allocated, which it must not (should use buffer pool)")
	}
	return decoded, nil
}

func newProtocolError(err error, msgContext string) error {
	return fmt.Errorf("protocol error on %v: %w", msgContext, err)
}

func newHandleError(err error, msgContext string) error {
	return fmt.Errorf("handling %v: %w", msgContext, err)
}

func messageContext(msg message) (string, error) {
	switch msg := msg.(type) {
	case *ClusterConfig:
		return "cluster-config", nil
	case *Index:
		return fmt.Sprintf("index for %v", msg.Folder), nil
	case *IndexUpdate:
		return fmt.Sprintf("index-update for %v", msg.Folder), nil
	case *Request:
		return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
	case *Response:
		return "response", nil
	case *DownloadProgress:
		return fmt.Sprintf("download-progress for %v", msg.Folder), nil
	case *Ping:
		return "ping", nil
	case *Close:
		return "close", nil
	default:
		return "", errors.New("unknown or empty message")
	}
}
Repository: syncthing/syncthing
File: cmd/syncthing/cli/operations.go (Go)

Code before:
	Subcommands: []cli.Command{
		{
			Name:   "restart",
			Usage:  "Restart syncthing",
			Action: expects(0, emptyPost("system/restart")),
		},
		{
			Name:   "shutdown",
			Usage:  "Shutdown syncthing",
			Action: expects(0, emptyPost("system/shutdown")),
		},
		{
			Name:   "upgrade",
			Usage:  "Upgrade syncthing (if a newer version is available)",
			Action: expects(0, emptyPost("system/upgrade")),
		},
		{
			Name:      "folder-override",
			Usage:     "Override changes on folder (remote for sendonly, local for receiveonly). WARNING: Destructive - deletes/changes your data.",
			ArgsUsage: "[folder id]",
			Action:    expects(1, foldersOverride),
		},
		{
			Name:      "pause",
			Usage:     "Pause the folder/device",
			ArgsUsage: folderArgsUsage,
			Action:    expects(2, pause(true)),
		},
		{
			Name:      "resume",
			Usage:     "Resume the folder/device",
			ArgsUsage: folderArgsUsage,
			Action:    expects(2, pause(false)),
		},
	},
}

func foldersOverride(c *cli.Context) error {
	client := c.App.Metadata["client"].(*APIClient)
	cfg, err := getConfig(client)
	if err != nil {
		return err
	}
	rid := c.Args()[0]
	for _, folder := range cfg.Folders {
		if folder.ID == rid {
			response, err := client.Post("db/override", "")
			if err != nil {
				return err
			}
			if response.StatusCode != 200 {

Review comment (suggestion):
This accepts only a single device or folder ID.  Requiring `devices | folders` (plural) is confusing.

Code after:
		{
			Name:   "restart",
			Usage:  "Restart syncthing",
			Action: expects(0, emptyPost("system/restart")),
		},
		{
			Name:   "shutdown",
			Usage:  "Shutdown syncthing",
			Action: expects(0, emptyPost("system/shutdown")),
		},
		{
			Name:   "upgrade",
			Usage:  "Upgrade syncthing (if a newer version is available)",
			Action: expects(0, emptyPost("system/upgrade")),
		},
		{
			Name:      "folder-override",
			Usage:     "Override changes on folder (remote for sendonly, local for receiveonly). WARNING: Destructive - deletes/changes your data.",
			ArgsUsage: "[folder id]",
			Action:    expects(1, foldersOverride),
		},
	},
}

func foldersOverride(c *cli.Context) error {
	client := c.App.Metadata["client"].(*APIClient)
	cfg, err := getConfig(client)
	if err != nil {
		return err
	}
	rid := c.Args()[0]
	for _, folder := range cfg.Folders {
		if folder.ID == rid {
			response, err := client.Post("db/override", "")
			if err != nil {
				return err
			}
			if response.StatusCode != 200 {
				errStr := fmt.Sprint("Failed to override changes\nStatus code: ", response.StatusCode)
				bytes, err := responseToBArray(response)
				if err != nil {
					return err
				}
				body := string(bytes)
				if body != "" {
					errStr += "\nBody: " + body
				}
				return fmt.Errorf(errStr)
			}
			return nil
		}
Repository: syncthing/syncthing
File: cmd/syncthing/cli/debug.go (Go)

Code before:
// Copyright (C) 2021 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package cli

import (
	"fmt"

	"github.com/urfave/cli"
)

var debugCommand = cli.Command{
	Name:     "debug",
	HideHelp: true,
	Usage:    "Debug command group",
	Subcommands: []cli.Command{
		{
			Name:   "enable",
			Usage:  "Enable debugging",
			Action: expects(0, setDebug(true)),
		},
		{
			Name:   "disable",
			Usage:  "Disable debugging",
			Action: expects(0, setDebug(true)),
		},
		{
			Name:      "file",
			Usage:     "Show information about a file (or directory/symlink)",
			ArgsUsage: "FOLDER-ID PATH",
			Action:    expects(2, debugFile()),
		},
	},
}

func setDebug(enabled bool) func(c *cli.Context) error {
	return func(c *cli.Context) error {
		client := c.App.Metadata["client"].(*APIClient)
		_, err := client.Patch("config/gui", fmt.Sprintf(`{"debugging": %v}`, enabled))
		return err
	}
}


Review comment (bug):
Aren't these driver by the config, so you could do `config gui debug set true`? 

Code after:
// Copyright (C) 2021 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package cli

import (
	"fmt"

	"github.com/urfave/cli"
)

var debugCommand = cli.Command{
	Name:     "debug",
	HideHelp: true,
	Usage:    "Debug command group",
	Subcommands: []cli.Command{
		{
			Name:      "file",
			Usage:     "Show information about a file (or directory/symlink)",
			ArgsUsage: "FOLDER-ID PATH",
			Action:    expects(2, debugFile()),
		},
		indexCommand,
		{
			Name:      "profile",
			Usage:     "Save a profile to help figuring out what Syncthing does.",
			ArgsUsage: "cpu | heap",
			Action:    expects(1, profile()),
		},
	},
}

func debugFile() cli.ActionFunc {
	return func(c *cli.Context) error {
		return indexDumpOutput(fmt.Sprintf("debug/file?folder=%v&file=%v", c.Args()[0], normalizePath(c.Args()[1])))(c)
	}
}

func profile() cli.ActionFunc {
	return func(c *cli.Context) error {
		switch t := c.Args()[0]; t {
		case "cpu", "heap":
			return saveToFile(fmt.Sprintf("debug/%vprof", c.Args()[0]))(c)
Repository: syncthing/syncthing
File: cmd/syncthing/cli/index.go (Go)

Code before:
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package cli

import (
	"github.com/urfave/cli"
)

var indexCommand = cli.Command{
	Name:  "index",
	Usage: "Show information about the index (database)",
	Subcommands: []cli.Command{
		{
			Name:   "indexDump",
			Usage:  "Print the entire db",
			Action: expects(0, indexDump),
		},
		{
			Name:   "indexDumpsize",
			Usage:  "Print the db size of different categories of information",
			Action: expects(0, indexDumpSize),
		},
		{
			Name:   "check",
			Usage:  "Check the database for inconsistencies",
			Action: expects(0, indexCheck),
		},
		{
			Name:   "indexAccount",
			Usage:  "Print key and value size statistics per key type",
			Action: expects(0, indexAccount),
		},
	},
}


Review comment (suggestion):
this is already a index subcommand. why not just dump?
```syncthing cli index indexDump``` sounds silly, almost feels like replace snafu

Code after:
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package cli

import (
	"github.com/urfave/cli"
)

var indexCommand = cli.Command{
	Name:  "index",
	Usage: "Show information about the index (database)",
	Subcommands: []cli.Command{
		{
			Name:   "dump",
			Usage:  "Print the entire db",
			Action: expects(0, indexDump),
		},
		{
			Name:   "dump-size",
			Usage:  "Print the db size of different categories of information",
			Action: expects(0, indexDumpSize),
		},
		{
			Name:   "check",
			Usage:  "Check the database for inconsistencies",
			Action: expects(0, indexCheck),
		},
		{
			Name:   "account",
			Usage:  "Print key and value size statistics per key type",
			Action: expects(0, indexAccount),
		},
	},
}
Repository: syncthing/syncthing
File: cmd/syncthing/cli/config.go (Go)

Code before:
		Name:        "config",
		HideHelp:    true,
		Usage:       "Configuration modification command group",
		Subcommands: commands,
		After:       h.configAfter,
	}, nil
}

func (h *configHandler) configAfter(c *cli.Context) error {
	if h.err != nil {
		return h.err
	}
	if reflect.DeepEqual(h.cfg, h.original) {
		return nil
	}
	body, err := json.MarshalIndent(h.cfg, "", "  ")
	if err != nil {
		return err
	}
	resp, err := h.client.Post("system/config", string(body))
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		body, err := responseToBArray(resp)
		if err != nil {
			return err
		}
		return errors.New(string(body))
	}
	return nil
}


Review comment (suggestion):
If you moved this above the h.err check, --help should not modify the config, in which case we'd end up not returning the error.

Code after:
		Name:        "config",
		HideHelp:    true,
		Usage:       "Configuration modification command group",
		Subcommands: commands,
		Before:      h.configBefore,
		After:       h.configAfter,
	}, nil
}

func (h *configHandler) configBefore(c *cli.Context) error {
	for _, arg := range c.Args() {
		if arg == "--help" || arg == "-h" {
			return nil
		}
	}
	return h.err
}

func (h *configHandler) configAfter(c *cli.Context) error {
	if h.err != nil {
		// Error was already returned in configBefore
		return nil
	}
	if reflect.DeepEqual(h.cfg, h.original) {
		return nil
	}
	body, err := json.MarshalIndent(h.cfg, "", "  ")
	if err != nil {
		return err
	}
	resp, err := h.client.Post("system/config", string(body))
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		body, err := responseToBArray(resp)
		if err != nil {
			return err
		}
		return errors.New(string(body))
	}
	return nil
}
Repository: syncthing/syncthing
File: lib/connections/service.go (Go)

Code before:
		seen[addr] = struct{}{}
	}

	for addr, listener := range s.listeners {
		if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
			l.Debugln("Stopping listener", addr)
			s.listenerSupervisor.Remove(s.listenerTokens[addr])
			delete(s.listenerTokens, addr)
			delete(s.listeners, addr)
		}
	}
	s.listenersMut.Unlock()

	return true
}

func (s *service) checkAndSignalConnectLoopOnUpdatedDevices(from, to config.Configuration) {
	oldDevices := make(map[protocol.DeviceID]config.DeviceConfiguration, len(to.Devices))
	for _, dev := range from.Devices {
		oldDevices[dev.DeviceID] = dev
	}

	for _, dev := range to.Devices {
		oldDev, ok := oldDevices[dev.DeviceID]
		if !ok || !util.EqualStrings(oldDev.Addresses, dev.Addresses) {
			s.deviceAddressesChanged <- struct{}{}
			break
		}
	}
}

func (s *service) AllAddresses() []string {
	s.listenersMut.RLock()
	var addrs []string
	for _, listener := range s.listeners {
		for _, lanAddr := range listener.LANAddresses() {
			addrs = append(addrs, lanAddr.String())
		}
		for _, wanAddr := range listener.WANAddresses() {
			addrs = append(addrs, wanAddr.String())
		}
	}
	s.listenersMut.RUnlock()
	return util.UniqueTrimmedStrings(addrs)
}

func (s *service) ExternalAddresses() []string {
	if s.cfg.Options().AnnounceLANAddresses {
		return s.AllAddresses()
	}
	s.listenersMut.RLock()

Review comment (suggestion):
This might block `CommitConfiguration` for however long a connection loop pass takes (which can be a fair amount of time). I suggest making the channel 1-buffered and using a non-blocking send here.

Code after:
		seen[addr] = struct{}{}
	}

	for addr, listener := range s.listeners {
		if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
			l.Debugln("Stopping listener", addr)
			s.listenerSupervisor.Remove(s.listenerTokens[addr])
			delete(s.listenerTokens, addr)
			delete(s.listeners, addr)
		}
	}
	s.listenersMut.Unlock()

	return true
}

func (s *service) checkAndSignalConnectLoopOnUpdatedDevices(from, to config.Configuration) {
	oldDevices := make(map[protocol.DeviceID]config.DeviceConfiguration, len(from.Devices))
	for _, dev := range from.Devices {
		oldDevices[dev.DeviceID] = dev
	}

	for _, dev := range to.Devices {
		oldDev, ok := oldDevices[dev.DeviceID]
		if !ok || !util.EqualStrings(oldDev.Addresses, dev.Addresses) {
			select {
			case s.deviceAddressesChanged <- struct{}{}:
			default:
				// channel is blocked - a config update is already pending for the connection loop.
			}
			break
		}
	}
}

func (s *service) AllAddresses() []string {
	s.listenersMut.RLock()
	var addrs []string
	for _, listener := range s.listeners {
		for _, lanAddr := range listener.LANAddresses() {
			addrs = append(addrs, lanAddr.String())
		}
		for _, wanAddr := range listener.WANAddresses() {
			addrs = append(addrs, wanAddr.String())
		}
	}
	s.listenersMut.RUnlock()
	return util.UniqueTrimmedStrings(addrs)
}

func (s *service) ExternalAddresses() []string {
Repository: syncthing/syncthing
File: lib/connections/service.go (Go)

Code before:
			l.Debugf("Listener for %v: %v", uri, err)
			continue
		} else if err != nil {
			l.Infof("Listener for %v: %v", uri, err)
			continue
		}

		s.createListener(factory, uri)
		seen[addr] = struct{}{}
	}

	for addr, listener := range s.listeners {
		if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
			l.Debugln("Stopping listener", addr)
			s.listenerSupervisor.Remove(s.listenerTokens[addr])
			delete(s.listenerTokens, addr)
			delete(s.listeners, addr)
		}
	}
	s.listenersMut.Unlock()

	return true
}

func (s *service) checkAndSignalConnectLoopOnUpdatedDevices(from, to config.Configuration) {
	oldDevices := make(map[protocol.DeviceID]config.DeviceConfiguration, len(to.Devices))
	for _, dev := range from.Devices {
		oldDevices[dev.DeviceID] = dev
	}

	for _, dev := range to.Devices {
		oldDev, ok := oldDevices[dev.DeviceID]
		if !ok || !util.EqualStrings(oldDev.Addresses, dev.Addresses) {
			select {
			case s.deviceAddressesChanged <- struct{}{}:
			default:
				// channel is blocked - a config update is already pending for the connection loop.
			}
			break
		}
	}
}

func (s *service) AllAddresses() []string {
	s.listenersMut.RLock()
	var addrs []string
	for _, listener := range s.listeners {
		for _, lanAddr := range listener.LANAddresses() {
			addrs = append(addrs, lanAddr.String())
		}
		for _, wanAddr := range listener.WANAddresses() {

Review comment (suggestion):
```suggestion
	oldDevices := make(map[protocol.DeviceID]config.DeviceConfiguration, len(from.Devices))
```

Code after:
			l.Debugf("Listener for %v: %v", uri, err)
			continue
		} else if err != nil {
			l.Infof("Listener for %v: %v", uri, err)
			continue
		}

		s.createListener(factory, uri)
		seen[addr] = struct{}{}
	}

	for addr, listener := range s.listeners {
		if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
			l.Debugln("Stopping listener", addr)
			s.listenerSupervisor.Remove(s.listenerTokens[addr])
			delete(s.listenerTokens, addr)
			delete(s.listeners, addr)
		}
	}
	s.listenersMut.Unlock()

	return true
}

func (s *service) checkAndSignalConnectLoopOnUpdatedDevices(from, to config.Configuration) {
	oldDevices := make(map[protocol.DeviceID]config.DeviceConfiguration, len(from.Devices))
	for _, dev := range from.Devices {
		oldDevices[dev.DeviceID] = dev
	}

	for _, dev := range to.Devices {
		oldDev, ok := oldDevices[dev.DeviceID]
		if !ok || !util.EqualStrings(oldDev.Addresses, dev.Addresses) {
			select {
			case s.deviceAddressesChanged <- struct{}{}:
			default:
				// channel is blocked - a config update is already pending for the connection loop.
			}
			break
		}
	}
}

func (s *service) AllAddresses() []string {
	s.listenersMut.RLock()
	var addrs []string
	for _, listener := range s.listeners {
		for _, lanAddr := range listener.LANAddresses() {
			addrs = append(addrs, lanAddr.String())
		}
		for _, wanAddr := range listener.WANAddresses() {
Repository: syncthing/syncthing
File: lib/fs/filesystem.go (Go)

Code before:
	// funkyness.
	file = filepath.Clean(file)

	// It is not acceptable to attempt to traverse upwards.
	if file == ".." {
		return "", errNotRelative
	}
	if strings.HasPrefix(file, ".."+pathSep) {
		return "", errNotRelative
	}

	if strings.HasPrefix(file, pathSep) {
		if file == pathSep {
			return ".", nil
		}
		return file[1:], nil
	}

	return file, nil
}

// wrapFilesystem should always be used when wrapping a Filesystem.
// It ensures proper wrapping order, which right now means:
// `logFilesystem` needs to be the outermost wrapper for caller lookup.
func wrapFilesystem(fs Filesystem, wrapFn func(Filesystem) Filesystem) Filesystem {
	logFs, ok := UnwrapFilesystem(fs, FilesystemWrapperTypeLog)
	if ok {
		fs = logFs.(*logFilesystem).Filesystem
	}
	fs = wrapFn(fs)
	if ok {
		fs = &logFilesystem{fs}
	}
	return fs
}

// UnwrapFilesystem removes "wrapping" filesystems to expose the filesystem of the requested wrapperType, if it exists.
func UnwrapFilesystem(fs Filesystem, wrapperType FilesystemWrapperType) (Filesystem, bool) {
	var ok bool
	for {
		if fs.wrapperType() == wrapperType {
			return fs, true
		}
		fs, ok = fs.underlying()
		if !ok {
			return nil, false
		}
	}
}


Review comment (suggestion):
I'd keep the direct type assertion: This functions is about the order of wrapping, while `UnwrapFilesystem` doesn't care about the order and just gets the wrapper from any "depth". And as the comment above explains, the logging wrapper needs to be the outermost at all times.

Code after:
	// funkyness.
	file = filepath.Clean(file)

	// It is not acceptable to attempt to traverse upwards.
	if file == ".." {
		return "", errNotRelative
	}
	if strings.HasPrefix(file, ".."+pathSep) {
		return "", errNotRelative
	}

	if strings.HasPrefix(file, pathSep) {
		if file == pathSep {
			return ".", nil
		}
		return file[1:], nil
	}

	return file, nil
}

// wrapFilesystem should always be used when wrapping a Filesystem.
// It ensures proper wrapping order, which right now means:
// `logFilesystem` needs to be the outermost wrapper for caller lookup.
func wrapFilesystem(fs Filesystem, wrapFn func(Filesystem) Filesystem) Filesystem {
	logFs, ok := fs.(*logFilesystem)
	if ok {
		fs = logFs.Filesystem
	}
	fs = wrapFn(fs)
	if ok {
		fs = &logFilesystem{fs}
	}
	return fs
}

// unwrapFilesystem removes "wrapping" filesystems to expose the filesystem of the requested wrapperType, if it exists.
func unwrapFilesystem(fs Filesystem, wrapperType filesystemWrapperType) (Filesystem, bool) {
	var ok bool
	for {
		if fs.wrapperType() == wrapperType {
			return fs, true
		}
		fs, ok = fs.underlying()
		if !ok {
			return nil, false
		}
	}
}