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

Code before:
	if p.result&resultDeletable == resultDeletable {
		ret = "(?d)" + ret
	}
	return ret
}

func (p Pattern) allowsSkippingIgnoredDirs() bool {
	if p.result.IsIgnored() {
		return true
	}
	if p.pattern[0] != '/' {
		return false
	}
	// Double asterisk everywhere in the path except at the end is bad
	tocheck := strings.TrimSuffix(p.pattern[1:], "**")
	if strings.Contains(tocheck, "**") {
		return false
	}
	// Any wildcards (*, [...]) anywhere except for the last path component are bad
	comps := strings.Split(tocheck, "/")
	for _, comp := range comps[:len(comps)-1] {
		if strings.Contains(comp, "*") {
			return false
		}
		// need to check for escapes
		for i := strings.Index(comp, "["); i != -1; i = strings.Index(comp[i+1:], "[") {
			if i == 0 || comp[i-1] != '\\' {
				return false
			}
		}
	}
	return true
}

type Result uint8

func (r Result) IsIgnored() bool {
	return r&resultInclude == resultInclude
}

func (r Result) IsDeletable() bool {
	return r.IsIgnored() && r&resultDeletable == resultDeletable
}

func (r Result) IsCaseFolded() bool {
	return r&resultFoldCase == resultFoldCase
}

// The ChangeDetector is responsible for determining if files have changed
// on disk. It gets told to Remember() files (name and modtime) and will
// then get asked if a file has been Seen() (i.e., Remember() has been

Review comment (security):
There are also `?` wildcards and `{bracketed,alternatives}`, should we check for those?

Also escapes are not processed on Windows, so `\[foo]` there is a rooted path with a wildcard expression in it...

Code after:
		ret = "(?i)" + ret
	}
	if p.result&resultDeletable == resultDeletable {
		ret = "(?d)" + ret
	}
	return ret
}

func (p Pattern) allowsSkippingIgnoredDirs() bool {
	if p.result.IsIgnored() {
		return true
	}
	if p.pattern[0] != '/' {
		return false
	}
	// Double asterisk everywhere in the path except at the end is bad
	if strings.Contains(strings.TrimSuffix(p.pattern, "**"), "**") {
		return false
	}
	// Any wildcards anywhere except for the last path component are bad
	lastSep := strings.LastIndex(p.pattern, "/")
	if lastSep == -1 {
		return true
	}
	return p.pattern[:lastSep] == glob.QuoteMeta(p.pattern[:lastSep])
}

type Result uint8

func (r Result) IsIgnored() bool {
	return r&resultInclude == resultInclude
}

func (r Result) IsDeletable() bool {
	return r.IsIgnored() && r&resultDeletable == resultDeletable
}

func (r Result) IsCaseFolded() bool {
	return r&resultFoldCase == resultFoldCase
}

// The ChangeDetector is responsible for determining if files have changed
// on disk. It gets told to Remember() files (name and modtime) and will
// then get asked if a file has been Seen() (i.e., Remember() has been
// called on it) and if any of the files have Changed(). To forget all
// files, call Reset().
type ChangeDetector interface {
	Remember(fs fs.Filesystem, name string, modtime time.Time)
	Seen(fs fs.Filesystem, name string) bool
	Changed() bool
	Reset()
Repository: syncthing/syncthing
File: lib/ignore/ignore.go (Go)

Code before:
	ret := p.pattern
	if p.result&resultInclude != resultInclude {
		ret = "!" + ret
	}
	if p.result&resultFoldCase == resultFoldCase {
		ret = "(?i)" + ret
	}
	if p.result&resultDeletable == resultDeletable {
		ret = "(?d)" + ret
	}
	return ret
}

func (p Pattern) allowsSkippingIgnoredDirs() bool {
	if p.result.IsIgnored() {
		return true
	}
	if p.pattern[0] != '/' {
		return false
	}
	// Double asterisk everywhere in the path except at the end is bad
	tocheck := strings.TrimSuffix(p.pattern[1:], "**")
	if strings.Contains(tocheck, "**") {
		return false
	}
	// Any wildcards (*, [...]) anywhere except for the last path component are bad
	lastSep := strings.LastIndex(tocheck, "/")
	if lastSep == -1 {
		return true
	}
	tocheck = tocheck[:lastSep]
	return tocheck == glob.QuoteMeta(tocheck)
}

type Result uint8

func (r Result) IsIgnored() bool {
	return r&resultInclude == resultInclude
}

func (r Result) IsDeletable() bool {
	return r.IsIgnored() && r&resultDeletable == resultDeletable
}

func (r Result) IsCaseFolded() bool {
	return r&resultFoldCase == resultFoldCase
}

// The ChangeDetector is responsible for determining if files have changed
// on disk. It gets told to Remember() files (name and modtime) and will
// then get asked if a file has been Seen() (i.e., Remember() has been

Review comment (suggestion):
I think `**` is also a valid wildcard in the library.

I think all you need to do is:
1. Get the string without the last component
2. Check that quoted string matches original string

Code after:
	ret := p.pattern
	if p.result&resultInclude != resultInclude {
		ret = "!" + ret
	}
	if p.result&resultFoldCase == resultFoldCase {
		ret = "(?i)" + ret
	}
	if p.result&resultDeletable == resultDeletable {
		ret = "(?d)" + ret
	}
	return ret
}

func (p Pattern) allowsSkippingIgnoredDirs() bool {
	if p.result.IsIgnored() {
		return true
	}
	if p.pattern[0] != '/' {
		return false
	}
	// Double asterisk everywhere in the path except at the end is bad
	if strings.Contains(strings.TrimSuffix(p.pattern, "**"), "**") {
		return false
	}
	// Any wildcards anywhere except for the last path component are bad
	lastSep := strings.LastIndex(p.pattern, "/")
	if lastSep == -1 {
		return true
	}
	return p.pattern[:lastSep] == glob.QuoteMeta(p.pattern[:lastSep])
}

type Result uint8

func (r Result) IsIgnored() bool {
	return r&resultInclude == resultInclude
}

func (r Result) IsDeletable() bool {
	return r.IsIgnored() && r&resultDeletable == resultDeletable
}

func (r Result) IsCaseFolded() bool {
	return r&resultFoldCase == resultFoldCase
}

// The ChangeDetector is responsible for determining if files have changed
// on disk. It gets told to Remember() files (name and modtime) and will
// then get asked if a file has been Seen() (i.e., Remember() has been
// called on it) and if any of the files have Changed(). To forget all
// files, call Reset().
Repository: syncthing/syncthing
File: lib/model/model.go (Go)

Code before:
	defer restartMut.Unlock()

	var infoMsg string
	var errMsg string
	switch {
	case to.Paused:
		infoMsg = "Paused"
		errMsg = "pausing"
	case from.Paused:
		infoMsg = "Unpaused"
		errMsg = "unpausing"
	default:
		infoMsg = "Restarted"
		errMsg = "restarting"
	}

	m.fmut.Lock()
	defer m.fmut.Unlock()

	m.tearDownFolderLocked(from, fmt.Errorf("%v folder %v", errMsg, to.Description()))
	if !to.Paused {
		// Creating the fileset can take a long time (metadata calculation)
		// so we do it outside of the lock.
		m.fmut.Unlock()
		fset := db.NewFileSet(to.ID, to.Filesystem(), m.db)
		m.fmut.Lock()
		m.addFolderLocked(to, fset)
		m.startFolderLocked(to)
	}
	l.Infof("%v folder %v (%v)", infoMsg, to.Description(), to.Type)
}

func (m *model) UsageReportingStats(version int, preview bool) map[string]interface{} {
	stats := make(map[string]interface{})
	if version >= 3 {
		// Block stats
		blockStatsMut.Lock()
		copyBlockStats := make(map[string]int)
		for k, v := range blockStats {
			copyBlockStats[k] = v
			if !preview {
				blockStats[k] = 0
			}
		}
		blockStatsMut.Unlock()
		stats["blockStats"] = copyBlockStats

		// Transport stats
		m.pmut.RLock()
		transportStats := make(map[string]int)
		for _, conn := range m.conn {

Review comment (suggestion):
Could we use newFolder here? Also logic wise, if both from and to are paused, we'd drop connections for no good reason inside of stopFolder.

Code after:
	// because those locks are released while we are waiting for the folder
	// to shut down (and must be so because the folder might need them as
	// part of its operations before shutting down).
	restartMut := m.folderRestartMuts.Get(to.ID)
	restartMut.Lock()
	defer restartMut.Unlock()

	var infoMsg string
	var errMsg string
	switch {
	case to.Paused:
		infoMsg = "Paused"
		errMsg = "pausing"
	case from.Paused:
		infoMsg = "Unpaused"
		errMsg = "unpausing"
	default:
		infoMsg = "Restarted"
		errMsg = "restarting"
	}

	var fset *db.FileSet
	if !to.Paused {
		// Creating the fileset can take a long time (metadata calculation)
		// so we do it outside of the lock.
		fset = db.NewFileSet(to.ID, to.Filesystem(), m.db)
	}

	m.stopFolder(from, fmt.Errorf("%v folder %v", errMsg, to.Description()))

	m.fmut.Lock()
	defer m.fmut.Unlock()

	m.removeFolderLocked(from)
	if !to.Paused {
		m.addFolderLocked(to, fset)
		m.startFolderLocked(to)
	}
	l.Infof("%v folder %v (%v)", infoMsg, to.Description(), to.Type)
}

func (m *model) newFolder(cfg config.FolderConfiguration) {
	// Creating the fileset can take a long time (metadata calculation) so
	// we do it outside of the lock.
	fset := db.NewFileSet(cfg.ID, cfg.Filesystem(), m.db)

	// Close connections to affected devices
	m.closeConns(cfg.DeviceIDs(), fmt.Errorf("started folder %v", cfg.Description()))

	m.fmut.Lock()
	defer m.fmut.Unlock()
Repository: syncthing/syncthing
File: lib/connections/service.go (Go)

Code before:
			status.Error = &errStr
		}

		status.LANAddresses = urlsToStrings(listener.LANAddresses())
		status.WANAddresses = urlsToStrings(listener.WANAddresses())

		result[addr] = status
	}
	s.listenersMut.RUnlock()
	return result
}

func (s *service) ConnectionStatus() map[string]ConnectionStatusEntry {
	result := make(map[string]ConnectionStatusEntry)
	s.connectionStatusMut.RLock()
	for k, v := range s.connectionStatus {
		result[k] = v
	}
	s.connectionStatusMut.RUnlock()
	return result
}

func (s *service) setConnectionStatus(address string, err error) {
	if err == context.Canceled {
		return
	}

	status := ConnectionStatusEntry{When: time.Now().UTC().Truncate(time.Second)}
	if err != nil {
		errStr := err.Error()
		status.Error = &errStr
	}

	s.connectionStatusMut.Lock()
	s.connectionStatus[address] = status
	s.connectionStatusMut.Unlock()
}

func (s *service) NATType() string {
	s.listenersMut.RLock()
	defer s.listenersMut.RUnlock()
	for _, listener := range s.listeners {
		natType := listener.NATType()
		if natType != "unknown" {
			return natType
		}
	}
	return "unknown"
}

func getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {

Review comment (suggestion):
Again, verify there is no fmt.Errorf.
I guess we should have a PR in general replacing errors.New and fmt.Errorf with errors.Wrap

Code after:
			status.Error = &errStr
		}

		status.LANAddresses = urlsToStrings(listener.LANAddresses())
		status.WANAddresses = urlsToStrings(listener.WANAddresses())

		result[addr] = status
	}
	s.listenersMut.RUnlock()
	return result
}

func (s *service) ConnectionStatus() map[string]ConnectionStatusEntry {
	result := make(map[string]ConnectionStatusEntry)
	s.connectionStatusMut.RLock()
	for k, v := range s.connectionStatus {
		result[k] = v
	}
	s.connectionStatusMut.RUnlock()
	return result
}

func (s *service) setConnectionStatus(address string, err error) {
	if errors.Cause(err) != context.Canceled {
		return
	}

	status := ConnectionStatusEntry{When: time.Now().UTC().Truncate(time.Second)}
	if err != nil {
		errStr := err.Error()
		status.Error = &errStr
	}

	s.connectionStatusMut.Lock()
	s.connectionStatus[address] = status
	s.connectionStatusMut.Unlock()
}

func (s *service) NATType() string {
	s.listenersMut.RLock()
	defer s.listenersMut.RUnlock()
	for _, listener := range s.listeners {
		natType := listener.NATType()
		if natType != "unknown" {
			return natType
		}
	}
	return "unknown"
}

func getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
Repository: syncthing/syncthing
File: lib/dialer/public.go (Go)

Code before:

func SetTrafficClass(conn net.Conn, class int) error {
	switch conn := conn.(type) {
	case *net.TCPConn:
		e1 := ipv4.NewConn(conn).SetTOS(class)
		e2 := ipv6.NewConn(conn).SetTrafficClass(class)

		if e1 != nil {
			return e1
		}
		return e2
	default:
		return fmt.Errorf("unknown connection type %T", conn)
	}
}

func dialContextWithFallback(ctx context.Context, fallback proxy.ContextDialer, network, addr string) (net.Conn, error) {
	dialer, ok := proxy.FromEnvironment().(proxy.ContextDialer)
	if !ok {
		return nil, errUnexpectedInterfaceType
	}
	if dialer != proxy.Direct {
		// Capture the existing timeout by checking the deadline
		var timeout time.Duration
		if deadline, ok := ctx.Deadline(); ok {
			timeout = deadline.Sub(deadline)
		}
		if conn, err := dialer.DialContext(ctx, network, addr); noFallback || err == nil {
			return conn, err
		}
		// If the deadline was set, reset it again for the next dial attempt.
		if timeout != 0 {
			var cancel context.CancelFunc
			ctx, cancel = context.WithTimeout(ctx, timeout)
			defer cancel()
		}
	}
	return fallback.DialContext(ctx, network, addr)
}

// DialContext tries dialing via proxy if a proxy is configured, and falls back to
// a direct connection if no proxy is defined, or connecting via proxy fails.
// If the context has a timeout, the timeout might be applied twice.
func DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
	return dialContextWithFallback(ctx, proxy.Direct, network, addr)
}


Review comment (bug):
This is probably my own code, but this definately looks wrong. I think it should be time.Until(deadline) or something like that.

Code after:

func SetTrafficClass(conn net.Conn, class int) error {
	switch conn := conn.(type) {
	case *net.TCPConn:
		e1 := ipv4.NewConn(conn).SetTOS(class)
		e2 := ipv6.NewConn(conn).SetTrafficClass(class)

		if e1 != nil {
			return e1
		}
		return e2
	default:
		return fmt.Errorf("unknown connection type %T", conn)
	}
}

func dialContextWithFallback(ctx context.Context, fallback proxy.ContextDialer, network, addr string) (net.Conn, error) {
	dialer, ok := proxy.FromEnvironment().(proxy.ContextDialer)
	if !ok {
		return nil, errUnexpectedInterfaceType
	}
	if dialer == proxy.Direct {
		return fallback.DialContext(ctx, network, addr)
	}
	if noFallback {
		return dialer.DialContext(ctx, network, addr)
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	var proxyConn, fallbackConn net.Conn
	var proxyErr, fallbackErr error
	proxyDone := make(chan struct{})
	fallbackDone := make(chan struct{})
	go func() {
		proxyConn, proxyErr = dialer.DialContext(ctx, network, addr)
		close(proxyDone)
	}()
	go func() {
		fallbackConn, fallbackErr = fallback.DialContext(ctx, network, addr)
		close(fallbackDone)
	}()
	<-proxyDone
	if proxyErr == nil {
		go func() {
			<-fallbackDone
			if fallbackErr == nil {
				fallbackConn.Close()
			}
		}()
		return proxyConn, nil
Repository: syncthing/syncthing
File: lib/model/model.go (Go)

Code before:
				directory, ok := last[path]
				if !ok {
					newdir := make(map[string]interface{})
					last[path] = newdir
					last = newdir
				} else {
					last = directory.(map[string]interface{})
				}
			}
		}

		if !dirsonly && base != "" {
			last[base] = []interface{}{
				f.ModTime(), f.FileSize(),
			}
		}

		return true
	})

	return output
}

func (m *model) GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error) {
	m.fmut.RLock()
	ver := m.folderVersioners[folder]
	m.fmut.RUnlock()
	if ver == nil {
		return nil, errNoVersioner
	}

	return ver.GetVersions()
}

func (m *model) RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error) {
	fcfg, ok := m.cfg.Folder(folder)
	if !ok {
		return nil, errFolderMissing
	}

	m.fmut.RLock()
	ver := m.folderVersioners[folder]
	m.fmut.RUnlock()
	if ver == nil {
		return nil, errNoVersioner
	}

	restoreErrors := make(map[string]string)

	for file, version := range versions {
		if err := ver.Restore(file, version); err != nil {

Review comment (suggestion):
I'd keep returning `errFolderMissing` if `!ok` (using `ver, ok := ...`) - it's a tiny bit more accurate.

Code after:
		if dir != "." {
			for _, path := range strings.Split(dir, sep) {
				directory, ok := last[path]
				if !ok {
					newdir := make(map[string]interface{})
					last[path] = newdir
					last = newdir
				} else {
					last = directory.(map[string]interface{})
				}
			}
		}

		if !dirsonly && base != "" {
			last[base] = []interface{}{
				f.ModTime(), f.FileSize(),
			}
		}

		return true
	})

	return output
}

func (m *model) GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error) {
	m.fmut.RLock()
	ver, ok := m.folderVersioners[folder]
	m.fmut.RUnlock()
	if !ok {
		return nil, errFolderMissing
	}
	if ver == nil {
		return nil, errNoVersioner
	}

	return ver.GetVersions()
}

func (m *model) RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error) {
	fcfg, ok := m.cfg.Folder(folder)
	if !ok {
		return nil, errFolderMissing
	}

	m.fmut.RLock()
	ver := m.folderVersioners[folder]
	m.fmut.RUnlock()
	if !ok {
		return nil, errFolderMissing
	}
Repository: syncthing/syncthing
File: lib/stats/folder.go (Go)

Code before:
}

func NewFolderStatisticsReference(ldb *db.Lowlevel, folder string) *FolderStatisticsReference {
	return &FolderStatisticsReference{
		ns:     db.NewFolderStatisticsNamespace(ldb, folder),
		folder: folder,
	}
}

func (s *FolderStatisticsReference) GetLastFile() (LastFile, error) {
	at, ok, err := s.ns.Time("lastFileAt")
	if err != nil {
		return LastFile{}, err
	} else if !ok {
		return LastFile{}, nil
	}
	file, ok, err := s.ns.String("lastFileName")
	if err != nil {
		return LastFile{}, err
	} else if !ok {
		return LastFile{}, nil
	}
	deleted, _, err := s.ns.Bool("lastFileDeleted")
	if err != nil {
		return LastFile{}, err
	} else if !ok {
		return LastFile{}, nil
	}
	return LastFile{
		At:       at,
		Filename: file,
		Deleted:  deleted,
	}, nil
}

func (s *FolderStatisticsReference) ReceivedFile(file string, deleted bool) error {
	l.Debugln("stats.FolderStatisticsReference.ReceivedFile:", s.folder, file)
	if err := s.ns.PutTime("lastFileAt", time.Now()); err != nil {
		return err
	}
	if err := s.ns.PutString("lastFileName", file); err != nil {
		return err
	}
	if err := s.ns.PutBool("lastFileDeleted", deleted); err != nil {
		return err
	}
	return nil
}

func (s *FolderStatisticsReference) ScanCompleted() error {
	return s.ns.PutTime("lastScan", time.Now())

Review comment (suggestion):
This check is redundant, unless the `ok` shouldn't be omitted in the last assignment above (also if it was purposely omitted, maybe add a comment - I don't understand why it might be).

Code after:
}

func NewFolderStatisticsReference(ldb *db.Lowlevel, folder string) *FolderStatisticsReference {
	return &FolderStatisticsReference{
		ns:     db.NewFolderStatisticsNamespace(ldb, folder),
		folder: folder,
	}
}

func (s *FolderStatisticsReference) GetLastFile() (LastFile, error) {
	at, ok, err := s.ns.Time("lastFileAt")
	if err != nil {
		return LastFile{}, err
	} else if !ok {
		return LastFile{}, nil
	}
	file, ok, err := s.ns.String("lastFileName")
	if err != nil {
		return LastFile{}, err
	} else if !ok {
		return LastFile{}, nil
	}
	deleted, _, err := s.ns.Bool("lastFileDeleted")
	if err != nil {
		return LastFile{}, err
	}
	return LastFile{
		At:       at,
		Filename: file,
		Deleted:  deleted,
	}, nil
}

func (s *FolderStatisticsReference) ReceivedFile(file string, deleted bool) error {
	l.Debugln("stats.FolderStatisticsReference.ReceivedFile:", s.folder, file)
	if err := s.ns.PutTime("lastFileAt", time.Now()); err != nil {
		return err
	}
	if err := s.ns.PutString("lastFileName", file); err != nil {
		return err
	}
	if err := s.ns.PutBool("lastFileDeleted", deleted); err != nil {
		return err
	}
	return nil
}

func (s *FolderStatisticsReference) ScanCompleted() error {
	return s.ns.PutTime("lastScan", time.Now())
}
Repository: syncthing/syncthing
File: lib/protocol/protocol.go (Go)

Code before:
		case c.inbox <- msg:
		case <-c.closed:
			return
		}

	}
}

func (c *rawConnection) dispatcherLoop() (err error) {
	defer close(c.dispatcherLoopStopped)
	var msg message
	state := stateInitial
	for {
		select {
		case msg = <-c.inbox:
		case <-c.closed:
			return ErrClosed
		}
		switch msg := msg.(type) {
		case *ClusterConfig:
			l.Debugln("read ClusterConfig message")
			if state != stateInitial {
				return fmt.Errorf("protocol error: cluster config message in state %d", state)
			}
			if err := c.receiver.ClusterConfig(c.id, *msg); err != nil {
				return fmt.Errorf("receiver error: %v", err)
			}
			state = stateReady

		case *Index:
			l.Debugln("read Index message")
			if state != stateReady {
				return fmt.Errorf("protocol error: index message in state %d", state)
			}
			if err := checkIndexConsistency(msg.Files); err != nil {
				return errors.Wrap(err, "protocol error: index")
			}
			if err := c.handleIndex(*msg); err != nil {
				return fmt.Errorf("receiver error: %v", err)
			}
			state = stateReady

		case *IndexUpdate:
			l.Debugln("read IndexUpdate message")
			if state != stateReady {
				return fmt.Errorf("protocol error: index update message in state %d", state)
			}
			if err := checkIndexConsistency(msg.Files); err != nil {
				return errors.Wrap(err, "protocol error: index update")
			}
			if err := c.handleIndexUpdate(*msg); err != nil {

Review comment (suggestion):
Please use errors.Wrap (don't think it matters here, but still). Same below

Code after:
		case c.inbox <- msg:
		case <-c.closed:
			return
		}

	}
}

func (c *rawConnection) dispatcherLoop() (err error) {
	defer close(c.dispatcherLoopStopped)
	var msg message
	state := stateInitial
	for {
		select {
		case msg = <-c.inbox:
		case <-c.closed:
			return ErrClosed
		}
		switch msg := msg.(type) {
		case *ClusterConfig:
			l.Debugln("read ClusterConfig message")
			if state != stateInitial {
				return fmt.Errorf("protocol error: cluster config message in state %d", state)
			}
			if err := c.receiver.ClusterConfig(c.id, *msg); err != nil {
				return errors.Wrap(err, "receiver error")
			}
			state = stateReady

		case *Index:
			l.Debugln("read Index message")
			if state != stateReady {
				return fmt.Errorf("protocol error: index message in state %d", state)
			}
			if err := checkIndexConsistency(msg.Files); err != nil {
				return errors.Wrap(err, "protocol error: index")
			}
			if err := c.handleIndex(*msg); err != nil {
				return errors.Wrap(err, "receiver error")
			}
			state = stateReady

		case *IndexUpdate:
			l.Debugln("read IndexUpdate message")
			if state != stateReady {
				return fmt.Errorf("protocol error: index update message in state %d", state)
			}
			if err := checkIndexConsistency(msg.Files); err != nil {
				return errors.Wrap(err, "protocol error: index update")
			}
			if err := c.handleIndexUpdate(*msg); err != nil {
Repository: syncthing/syncthing
File: lib/syncthing/utils.go (Go)

Code before:
	// Copy the existing config to an archive copy
	archivePath := cfg.ConfigPath() + fmt.Sprintf(".v%d", cfg.RawCopy().OriginalVersion)
	l.Infoln("Archiving a copy of old config file format at:", archivePath)
	if err := copyFile(cfg.ConfigPath(), archivePath); err != nil {
		return err
	}

	// Do a regular atomic config sve
	return cfg.Save()
}

func copyFile(src, dst string) error {
	bs, err := ioutil.ReadFile(src)
	if err != nil {
		return err
	}

	if err := ioutil.WriteFile(dst, bs, 0600); err != nil {
		// Attempt to clean up
		os.Remove(dst)
		return err
	}

	return nil
}

func OpenGoleveldb(path string, tuning config.Tuning) (*db.Lowlevel, error) {
	ldb, err := backend.Open(path, backend.Tuning(tuning))
	if err != nil {
		return nil, err
	}
	return db.NewLowlevel(ldb), nil
}


Review comment (suggestion):
This function doesn't add much value. We could do the cast in main...

Code after:
	archivePath := cfg.ConfigPath() + fmt.Sprintf(".v%d", cfg.RawCopy().OriginalVersion)
	l.Infoln("Archiving a copy of old config file format at:", archivePath)
	if err := copyFile(cfg.ConfigPath(), archivePath); err != nil {
		return err
	}

	// Do a regular atomic config sve
	return cfg.Save()
}

func copyFile(src, dst string) error {
	bs, err := ioutil.ReadFile(src)
	if err != nil {
		return err
	}

	if err := ioutil.WriteFile(dst, bs, 0600); err != nil {
		// Attempt to clean up
		os.Remove(dst)
		return err
	}

	return nil
}

func OpenDBBackend(path string, tuning config.Tuning) (backend.Backend, error) {
	return backend.Open(path, backend.Tuning(tuning))
}