chore: style fixes from go fix (#10846)

Just `go fix ./...`

Signed-off-by: Jakob Borg <jakob@kastelo.net>
This commit is contained in:
Jakob Borg
2026-08-05 20:23:22 +02:00
committed by GitHub
parent 946e2b83a1
commit 8ea09c0094
144 changed files with 211 additions and 315 deletions
+4 -4
View File
@@ -17,10 +17,10 @@ import (
) )
type event struct { type event struct {
ID int `json:"id"` ID int `json:"id"`
Type string `json:"type"` Type string `json:"type"`
Time time.Time `json:"time"` Time time.Time `json:"time"`
Data map[string]interface{} `json:"data"` Data map[string]any `json:"data"`
} }
func main() { func main() {
-1
View File
@@ -60,7 +60,6 @@ func checkServers(deviceID protocol.DeviceID, servers ...string) {
t0 := time.Now() t0 := time.Now()
resc := make(chan checkResult) resc := make(chan checkResult)
for _, srv := range servers { for _, srv := range servers {
srv := srv
go func() { go func() {
res := checkServer(deviceID, srv) res := checkServer(deviceID, srv)
res.server = srv res.server = srv
+2 -5
View File
@@ -34,7 +34,7 @@ func generateFiles(dir string, files, maxexp int, srcname string) error {
return err return err
} }
for i := 0; i < files; i++ { for range files {
n := randomName() n := randomName()
if rand.Float64() < 0.05 { if rand.Float64() < 0.05 {
@@ -51,10 +51,7 @@ func generateFiles(dir string, files, maxexp int, srcname string) error {
p1 := filepath.Join(p0, n) p1 := filepath.Join(p0, n)
s := int64(1 << uint(rand.Intn(maxexp))) s := int64(1 << uint(rand.Intn(maxexp)))
a := int64(128 * 1024) a := min(int64(128*1024), s)
if a > s {
a = s
}
s += rand.Int63n(a) s += rand.Int63n(a)
if err := generateOneFile(fd, p1, s); err != nil { if err := generateOneFile(fd, p1, s); err != nil {
+2 -2
View File
@@ -138,7 +138,7 @@ func printProgress(prefix string, count *atomic.Int64) {
} }
} }
func saveCert(priv interface{}, derBytes []byte) { func saveCert(priv any, derBytes []byte) {
certOut, err := os.Create("cert.pem") certOut, err := os.Create("cert.pem")
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
@@ -179,7 +179,7 @@ func saveCert(priv interface{}, derBytes []byte) {
} }
} }
func pemBlockForKey(priv interface{}) (*pem.Block, error) { func pemBlockForKey(priv any) (*pem.Block, error) {
switch k := priv.(type) { switch k := priv.(type) {
case *rsa.PrivateKey: case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil
+1 -1
View File
@@ -203,7 +203,7 @@ func loadIgnorePatterns(path string) (*ignorePatterns, error) {
} }
var patterns []*regexp.Regexp var patterns []*regexp.Regexp
for _, line := range strings.Split(string(bs), "\n") { for line := range strings.SplitSeq(string(bs), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build noassets //go:build noassets
// +build noassets
package auto package auto
+1 -1
View File
@@ -587,7 +587,7 @@ func loadRelays(file string, geoip *geoip.Provider) []*relay {
} }
var relays []*relay var relays []*relay
for _, line := range strings.Split(string(content), "\n") { for line := range strings.SplitSeq(string(content), "\n") {
if line == "" { if line == "" {
continue continue
} }
+1 -1
View File
@@ -17,7 +17,7 @@ import (
) )
func init() { func init() {
for i := 0; i < 10; i++ { for i := range 10 {
u := fmt.Sprintf("permanent%d", i) u := fmt.Sprintf("permanent%d", i)
permanentRelays = append(permanentRelays, &relay{URL: u}) permanentRelays = append(permanentRelays, &relay{URL: u})
} }
+1 -1
View File
@@ -188,7 +188,7 @@ func (p *proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(resp.StatusCode) w.WriteHeader(resp.StatusCode)
if strings.HasPrefix(ct, "application/json") { if strings.HasPrefix(ct, "application/json") {
// Special JSON handling; clean it up a bit. // Special JSON handling; clean it up a bit.
var v interface{} var v any
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
+1 -4
View File
@@ -402,10 +402,7 @@ func (s *apiSrv) certificateBytes(req *http.Request) ([]byte, error) {
b.WriteByte('\n') b.WriteByte('\n')
for i := 0; i < len(cert); i += 64 { for i := 0; i < len(cert); i += 64 {
end := i + 64 end := min(i+64, len(cert))
if end > len(cert) {
end = len(cert)
}
b.WriteString(cert[i:end]) b.WriteString(cert[i:end])
b.WriteByte('\n') b.WriteByte('\n')
} }
+3 -8
View File
@@ -7,7 +7,6 @@
package main package main
import ( import (
"context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"io" "io"
@@ -120,7 +119,7 @@ func TestRetryAfterSHistogram(t *testing.T) {
numBuckets := (notFoundRetryUnknownMaxSeconds + bucketSize - 1) / bucketSize numBuckets := (notFoundRetryUnknownMaxSeconds + bucketSize - 1) / bucketSize
buckets := make([]int, numBuckets) buckets := make([]int, numBuckets)
for i := 0; i < n; i++ { for range n {
v := tracker.retryAfterS() v := tracker.retryAfterS()
if v < notFoundRetryUnknownMinSeconds || v > notFoundRetryUnknownMaxSeconds { if v < notFoundRetryUnknownMinSeconds || v > notFoundRetryUnknownMaxSeconds {
t.Fatalf("retryAfterS() = %d, out of range [%d, %d]", v, notFoundRetryUnknownMinSeconds, notFoundRetryUnknownMaxSeconds) t.Fatalf("retryAfterS() = %d, out of range [%d, %d]", v, notFoundRetryUnknownMinSeconds, notFoundRetryUnknownMaxSeconds)
@@ -142,10 +141,7 @@ func TestRetryAfterSHistogram(t *testing.T) {
barWidth := 60 barWidth := 60
for i, c := range buckets { for i, c := range buckets {
lo := i*bucketSize + 1 lo := i*bucketSize + 1
hi := (i + 1) * bucketSize hi := min((i+1)*bucketSize, notFoundRetryUnknownMaxSeconds)
if hi > notFoundRetryUnknownMaxSeconds {
hi = notFoundRetryUnknownMaxSeconds
}
bar := "" bar := ""
if maxCount > 0 { if maxCount > 0 {
bar = strings.Repeat("#", c*barWidth/maxCount) bar = strings.Repeat("#", c*barWidth/maxCount)
@@ -156,8 +152,7 @@ func TestRetryAfterSHistogram(t *testing.T) {
func BenchmarkAPIRequests(b *testing.B) { func BenchmarkAPIRequests(b *testing.B) {
db := newInMemoryStore(b.TempDir(), 0, nil) db := newInMemoryStore(b.TempDir(), 0, nil)
ctx, cancel := context.WithCancel(context.Background()) ctx := b.Context()
defer cancel()
go db.Serve(ctx) go db.Serve(ctx)
api := newAPISrv("127.0.0.1:0", tls.Certificate{}, db, nil, true, true, 1000, 1000) api := newAPISrv("127.0.0.1:0", tls.Certificate{}, db, nil, true, true, 1000, 1000)
srv := httptest.NewServer(http.HandlerFunc(api.handler)) srv := httptest.NewServer(http.HandlerFunc(api.handler))
+4 -4
View File
@@ -18,7 +18,7 @@ import (
var ( var (
outboxesMut = sync.RWMutex{} outboxesMut = sync.RWMutex{}
outboxes = make(map[syncthingprotocol.DeviceID]chan interface{}) outboxes = make(map[syncthingprotocol.DeviceID]chan any)
numConnections atomic.Int64 numConnections atomic.Int64
) )
@@ -97,9 +97,9 @@ func protocolConnectionHandler(tcpConn net.Conn, config *tls.Config, token strin
id := syncthingprotocol.NewDeviceID(certs[0].Raw) id := syncthingprotocol.NewDeviceID(certs[0].Raw)
messages := make(chan interface{}) messages := make(chan any)
errors := make(chan error, 1) errors := make(chan error, 1)
outbox := make(chan interface{}) outbox := make(chan any)
// Read messages from the connection and send them on the messages // Read messages from the connection and send them on the messages
// channel. When there is an error, send it on the error channel and // channel. When there is an error, send it on the error channel and
@@ -364,7 +364,7 @@ func sessionConnectionHandler(conn net.Conn) {
} }
} }
func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) { func messageReader(conn net.Conn, messages chan<- any, errors chan<- error) {
numConnections.Add(1) numConnections.Add(1)
defer numConnections.Add(-1) defer numConnections.Add(-1)
+1 -4
View File
@@ -330,10 +330,7 @@ func take(tokens int, ls ...*rate.Limiter) {
for tokens > 0 { for tokens > 0 {
// chunk is how many tokens we can consume at a time // chunk is how many tokens we can consume at a time
chunk := tokens chunk := min(tokens, minBurst)
if chunk > minBurst {
chunk = minBurst
}
// maxDelay is the longest delay mandated by any of the limiters for // maxDelay is the longest delay mandated by any of the limiters for
// the chosen chunk size. // the chosen chunk size.
+2 -2
View File
@@ -38,7 +38,7 @@ func statusService(addr string) {
func getStatus(w http.ResponseWriter, _ *http.Request) { func getStatus(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Origin", "*")
status := make(map[string]interface{}) status := make(map[string]any)
sessionMut.Lock() sessionMut.Lock()
// This can potentially be double the number of pending sessions, as each session has two keys, one for each side. // This can potentially be double the number of pending sessions, as each session has two keys, one for each side.
@@ -67,7 +67,7 @@ func getStatus(w http.ResponseWriter, _ *http.Request) {
rc.rate(30*60/10) * 8 / 1000, rc.rate(30*60/10) * 8 / 1000,
rc.rate(60*60/10) * 8 / 1000, rc.rate(60*60/10) * 8 / 1000,
} }
status["options"] = map[string]interface{}{ status["options"] = map[string]any{
"network-timeout": networkTimeout / time.Second, "network-timeout": networkTimeout / time.Second,
"ping-interval": pingInterval / time.Second, "ping-interval": pingInterval / time.Second,
"message-timeout": messageTimeout / time.Second, "message-timeout": messageTimeout / time.Second,
+3 -3
View File
@@ -27,7 +27,7 @@ import (
type APIClient interface { type APIClient interface {
Get(url string) (*http.Response, error) Get(url string) (*http.Response, error)
Post(url, body string) (*http.Response, error) Post(url, body string) (*http.Response, error)
PutJSON(url string, o interface{}) (*http.Response, error) PutJSON(url string, o any) (*http.Response, error)
} }
type apiClient struct { type apiClient struct {
@@ -134,7 +134,7 @@ func (c *apiClient) RequestString(url, method, data string) (*http.Response, err
return c.Request(url, method, bytes.NewBufferString(data)) return c.Request(url, method, bytes.NewBufferString(data))
} }
func (c *apiClient) RequestJSON(url, method string, o interface{}) (*http.Response, error) { func (c *apiClient) RequestJSON(url, method string, o any) (*http.Response, error) {
data, err := json.Marshal(o) data, err := json.Marshal(o)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -150,7 +150,7 @@ func (c *apiClient) Post(url, body string) (*http.Response, error) {
return c.RequestString(url, "POST", body) return c.RequestString(url, "POST", body)
} }
func (c *apiClient) PutJSON(url string, o interface{}) (*http.Response, error) { func (c *apiClient) PutJSON(url string, o any) (*http.Response, error) {
return c.RequestJSON(url, "PUT", o) return c.RequestJSON(url, "PUT", o)
} }
+1 -1
View File
@@ -81,7 +81,7 @@ func (c *configCommand) Run(ctx Context, outerCtx *kong.Context) error {
app.Name = "syncthing cli config" app.Name = "syncthing cli config"
app.HelpName = "syncthing cli config" app.HelpName = "syncthing cli config"
app.Description = outerCtx.Selected().Help app.Description = outerCtx.Selected().Help
app.Metadata = map[string]interface{}{ app.Metadata = map[string]any{
"clientFactory": ctx.clientFactory, "clientFactory": ctx.clientFactory,
} }
app.CustomAppHelpTemplate = customAppHelpTemplate app.CustomAppHelpTemplate = customAppHelpTemplate
+2 -2
View File
@@ -112,7 +112,7 @@ func getConfig(c APIClient) (config.Configuration, error) {
return cfg, nil return cfg, nil
} }
func prettyPrintJSON(data interface{}) error { func prettyPrintJSON(data any) error {
enc := json.NewEncoder(os.Stdout) enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ") enc.SetIndent("", " ")
return enc.Encode(data) return enc.Encode(data)
@@ -123,7 +123,7 @@ func prettyPrintResponse(response *http.Response) error {
if err != nil { if err != nil {
return err return err
} }
var data interface{} var data any
if err := json.Unmarshal(bytes, &data); err != nil { if err := json.Unmarshal(bytes, &data); err != nil {
return err return err
} }
+1 -1
View File
@@ -125,7 +125,7 @@ func uploadPanicLog(ctx context.Context, urlBase, file string) error {
func filterLogLines(data []byte) []byte { func filterLogLines(data []byte) []byte {
filtered := data[:0] filtered := data[:0]
matched := false matched := false
for _, line := range bytes.Split(data, []byte("\n")) { for line := range bytes.SplitSeq(data, []byte("\n")) {
switch { switch {
case !matched && bytes.HasPrefix(line, []byte("Panic ")): case !matched && bytes.HasPrefix(line, []byte("Panic ")):
// This begins the panic trace, set the matched flag and append. // This begins the panic trace, set the matched flag and append.
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows //go:build !windows
// +build !windows
package main package main
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows //go:build !windows
// +build !windows
package main package main
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build windows //go:build windows
// +build windows
package main package main
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !solaris && !windows //go:build !solaris && !windows
// +build !solaris,!windows
package main package main
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build solaris || windows //go:build solaris || windows
// +build solaris windows
package main package main
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build go1.7 //go:build go1.7
// +build go1.7
package main package main
+1 -1
View File
@@ -313,7 +313,7 @@ nextScript:
// files on lines containing only a semicolon and execute them // files on lines containing only a semicolon and execute them
// separately. We require it on a separate line because there are // separately. We require it on a separate line because there are
// also statement-internal semicolons in the triggers. // also statement-internal semicolons in the triggers.
for _, stmt := range strings.Split(string(bs), "\n;") { for stmt := range strings.SplitSeq(string(bs), "\n;") {
if _, err := tx.Exec(s.expandTemplateVars(stmt)); err != nil { if _, err := tx.Exec(s.expandTemplateVars(stmt)); err != nil {
if strings.Contains(stmt, "syncthing:ignore-failure") { if strings.Contains(stmt, "syncthing:ignore-failure") {
// We're ok with this failing. Just note it. // We're ok with this failing. Just note it.
+1 -4
View File
@@ -474,10 +474,7 @@ func (s *folderDB) recalcGlobalForFile(txp *txPreparedStmts, file string) error
// The global version is the first one in the list that is not invalid, // The global version is the first one in the list that is not invalid,
// or just the first one in the list if all are invalid. // or just the first one in the list if all are invalid.
var global fileRow var global fileRow
globIdx := slices.IndexFunc(es, func(e fileRow) bool { return !e.IsInvalid() }) globIdx := max(slices.IndexFunc(es, func(e fileRow) bool { return !e.IsInvalid() }), 0)
if globIdx < 0 {
globIdx = 0
}
global = es[globIdx] global = es[globIdx]
// We "have" the file if the position in the list of versions is at the // We "have" the file if the position in the list of versions is at the
+2 -2
View File
@@ -41,8 +41,8 @@ func SetDefaultLevel(level slog.Level) {
} }
func SetLevelOverrides(sttrace string) { func SetLevelOverrides(sttrace string) {
pkgs := strings.Split(sttrace, ",") pkgs := strings.SplitSeq(sttrace, ",")
for _, pkg := range pkgs { for pkg := range pkgs {
pkg = strings.TrimSpace(pkg) pkg = strings.TrimSpace(pkg)
if pkg == "" { if pkg == "" {
continue continue
+2 -2
View File
@@ -45,11 +45,11 @@ type adapter struct {
l *slog.Logger l *slog.Logger
} }
func (a adapter) Debugln(vals ...interface{}) { func (a adapter) Debugln(vals ...any) {
a.log(strings.TrimSpace(fmt.Sprintln(vals...)), slog.LevelDebug) a.log(strings.TrimSpace(fmt.Sprintln(vals...)), slog.LevelDebug)
} }
func (a adapter) Debugf(format string, vals ...interface{}) { func (a adapter) Debugf(format string, vals ...any) {
a.log(fmt.Sprintf(format, vals...), slog.LevelDebug) a.log(fmt.Sprintf(format, vals...), slog.LevelDebug)
} }
+15 -15
View File
@@ -202,7 +202,7 @@ func (s *service) getListener(guiCfg config.GUIConfiguration) (net.Listener, err
return listener, nil return listener, nil
} }
func sendJSON(w http.ResponseWriter, jsonObject interface{}) { func sendJSON(w http.ResponseWriter, jsonObject any) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
// Marshalling might fail, in which case we should return a 500 with the // Marshalling might fail, in which case we should return a 500 with the
// actual error. // actual error.
@@ -696,7 +696,7 @@ func (*service) getSystemPaths(w http.ResponseWriter, _ *http.Request) {
} }
func (s *service) getJSMetadata(w http.ResponseWriter, _ *http.Request) { func (s *service) getJSMetadata(w http.ResponseWriter, _ *http.Request) {
meta, _ := json.Marshal(map[string]interface{}{ meta, _ := json.Marshal(map[string]any{
"deviceID": s.id.String(), "deviceID": s.id.String(),
"deviceIDShort": s.id.Short().String(), "deviceIDShort": s.id.Short().String(),
"authenticated": true, "authenticated": true,
@@ -706,7 +706,7 @@ func (s *service) getJSMetadata(w http.ResponseWriter, _ *http.Request) {
} }
func (*service) getSystemVersion(w http.ResponseWriter, _ *http.Request) { func (*service) getSystemVersion(w http.ResponseWriter, _ *http.Request) {
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"version": build.Version, "version": build.Version,
"codename": build.Codename, "codename": build.Codename,
"longVersion": build.LongVersion, "longVersion": build.LongVersion,
@@ -838,7 +838,7 @@ func (s *service) getDBNeed(w http.ResponseWriter, r *http.Request) {
} }
// Convert the struct to a more loose structure, and inject the size. // Convert the struct to a more loose structure, and inject the size.
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"progress": toJsonFileInfoSlice(progress), "progress": toJsonFileInfoSlice(progress),
"queued": toJsonFileInfoSlice(queued), "queued": toJsonFileInfoSlice(queued),
"rest": toJsonFileInfoSlice(rest), "rest": toJsonFileInfoSlice(rest),
@@ -866,7 +866,7 @@ func (s *service) getDBRemoteNeed(w http.ResponseWriter, r *http.Request) {
return return
} }
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"files": toJsonFileInfoSlice(files), "files": toJsonFileInfoSlice(files),
"page": page, "page": page,
"perpage": perpage, "perpage": perpage,
@@ -886,7 +886,7 @@ func (s *service) getDBLocalChanged(w http.ResponseWriter, r *http.Request) {
return return
} }
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"files": toJsonFileInfoSlice(files), "files": toJsonFileInfoSlice(files),
"page": page, "page": page,
"perpage": perpage, "perpage": perpage,
@@ -951,7 +951,7 @@ func (s *service) getDBFile(w http.ResponseWriter, r *http.Request) {
return return
} }
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"global": jsonFileInfo(gf), "global": jsonFileInfo(gf),
"local": jsonFileInfo(lf), "local": jsonFileInfo(lf),
"availability": av, "availability": av,
@@ -967,7 +967,7 @@ func (s *service) getDebugFile(w http.ResponseWriter, r *http.Request) {
gf, _, _ := s.model.CurrentGlobalFile(folder, file) gf, _, _ := s.model.CurrentGlobalFile(folder, file)
av, _ := s.model.Availability(folder, protocol.FileInfo{Name: file}, protocol.BlockInfo{}) av, _ := s.model.Availability(folder, protocol.FileInfo{Name: file}, protocol.BlockInfo{})
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"global": jsonFileInfo(gf), "global": jsonFileInfo(gf),
"local": jsonFileInfo(lf), "local": jsonFileInfo(lf),
"availability": av, "availability": av,
@@ -1037,7 +1037,7 @@ func (s *service) getSystemStatus(w http.ResponseWriter, _ *http.Request) {
runtime.ReadMemStats(&m) runtime.ReadMemStats(&m)
tilde, _ := fs.ExpandTilde("~") tilde, _ := fs.ExpandTilde("~")
res := make(map[string]interface{}) res := make(map[string]any)
res["myID"] = s.id.String() res["myID"] = s.id.String()
res["goroutines"] = runtime.NumGoroutine() res["goroutines"] = runtime.NumGoroutine()
res["alloc"] = m.Alloc res["alloc"] = m.Alloc
@@ -1302,7 +1302,7 @@ func (s *service) getDBIgnores(w http.ResponseWriter, r *http.Request) {
folder := qs.Get("folder") folder := qs.Get("folder")
lines, patterns, err := s.model.LoadIgnores(folder) lines, patterns, err := s.model.LoadIgnores(folder)
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"ignore": lines, "ignore": lines,
"expanded": patterns, "expanded": patterns,
"error": errorString(err), "error": errorString(err),
@@ -1411,7 +1411,7 @@ func (s *service) getSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
httpError(w, err) httpError(w, err)
return return
} }
res := make(map[string]interface{}) res := make(map[string]any)
res["running"] = build.Version res["running"] = build.Version
res["latest"] = rel.Tag res["latest"] = rel.Tag
res["newer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.Newer res["newer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.Newer
@@ -1439,7 +1439,7 @@ func (*service) getDeviceID(w http.ResponseWriter, r *http.Request) {
func (*service) getLang(w http.ResponseWriter, r *http.Request) { func (*service) getLang(w http.ResponseWriter, r *http.Request) {
lang := r.Header.Get("Accept-Language") lang := r.Header.Get("Accept-Language")
weights := make(map[string]float64) weights := make(map[string]float64)
for _, l := range strings.Split(lang, ",") { for l := range strings.SplitSeq(lang, ",") {
parts := strings.SplitN(l, ";", 2) parts := strings.SplitN(l, ";", 2)
code := strings.ToLower(strings.TrimSpace(parts[0])) code := strings.ToLower(strings.TrimSpace(parts[0]))
weights[code] = 1.0 weights[code] = 1.0
@@ -1638,7 +1638,7 @@ func (s *service) getFolderErrors(w http.ResponseWriter, r *http.Request) {
} }
} }
sendJSON(w, map[string]interface{}{ sendJSON(w, map[string]any{
"folder": folder, "folder": folder,
"errors": errors, "errors": errors,
"page": page, "page": page,
@@ -1770,8 +1770,8 @@ func (f jsonFileInfo) MarshalJSON() ([]byte, error) {
return json.Marshal(m) return json.Marshal(m)
} }
func fileIntfJSONMap(f protocol.FileInfo) map[string]interface{} { func fileIntfJSONMap(f protocol.FileInfo) map[string]any {
out := map[string]interface{}{ out := map[string]any{
"name": f.FileName(), "name": f.FileName(),
"type": f.FileType().String(), "type": f.FileType().String(),
"size": f.Size, "size": f.Size,
+1 -4
View File
@@ -311,10 +311,7 @@ func authLDAP(username string, password string, cfg config.LDAPConfiguration) bo
func formatOptionalPercentS(template string, username string) string { func formatOptionalPercentS(template string, username string) string {
var replacements []any var replacements []any
nReps := strings.Count(template, "%s") - strings.Count(template, "%%s") nReps := max(strings.Count(template, "%s")-strings.Count(template, "%%s"), 0)
if nReps < 0 {
nReps = 0
}
for range nReps { for range nReps {
replacements = append(replacements, username) replacements = append(replacements, username)
} }
+1 -2
View File
@@ -433,7 +433,6 @@ func TestAPIServiceRequests(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
tc := tc
t.Run(tc.URL, func(t *testing.T) { t.Run(tc.URL, func(t *testing.T) {
t.Parallel() t.Parallel()
testHTTPRequest(t, baseURL, tc, testAPIKey) testHTTPRequest(t, baseURL, tc, testAPIKey)
@@ -1723,7 +1722,7 @@ func TestConfigChanges(t *testing.T) {
return resp return resp
} }
mod := func(method, path string, data interface{}) { mod := func(method, path string, data any) {
t.Helper() t.Helper()
bs, err := json.Marshal(data) bs, err := json.Marshal(data)
if err != nil { if err != nil {
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build noassets //go:build noassets
// +build noassets
package auto package auto
+1 -1
View File
@@ -441,7 +441,7 @@ func (c *configMuxBuilder) adjustLDAP(w http.ResponseWriter, r *http.Request, ld
} }
// Unmarshals the content of the given body and stores it in to (i.e. to must be a pointer). // Unmarshals the content of the given body and stores it in to (i.e. to must be a pointer).
func unmarshalTo(body io.ReadCloser, to interface{}) error { func unmarshalTo(body io.ReadCloser, to any) error {
bs, err := io.ReadAll(body) bs, err := io.ReadAll(body)
body.Close() body.Close()
if err != nil { if err != nil {
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build race //go:build race
// +build race
package build package build
+2 -2
View File
@@ -664,7 +664,7 @@ func (defaults *Defaults) prepare(myID protocol.DeviceID, existingDevices map[pr
defaults.Device.prepare(nil) defaults.Device.prepare(nil)
} }
func ensureZeroForNodefault(empty interface{}, target interface{}) { func ensureZeroForNodefault(empty any, target any) {
copyMatchingTag(empty, target, "nodefault", func(v string) bool { copyMatchingTag(empty, target, "nodefault", func(v string) bool {
if len(v) > 0 && v != "true" { if len(v) > 0 && v != "true" {
panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "true"`, v)) panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "true"`, v))
@@ -674,7 +674,7 @@ func ensureZeroForNodefault(empty interface{}, target interface{}) {
} }
// copyMatchingTag copies fields tagged tag:"value" from "from" struct onto "to" struct. // copyMatchingTag copies fields tagged tag:"value" from "from" struct onto "to" struct.
func copyMatchingTag(from interface{}, to interface{}, tag string, shouldCopy func(value string) bool) { func copyMatchingTag(from any, to any, tag string, shouldCopy func(value string) bool) {
fromStruct := reflect.ValueOf(from).Elem() fromStruct := reflect.ValueOf(from).Elem()
fromType := fromStruct.Type() fromType := fromStruct.Type()
+6 -6
View File
@@ -1158,8 +1158,8 @@ func TestInvalidDeviceIDRejected(t *testing.T) {
// Change the device ID of the first device to "invalid". Fast and loose // Change the device ID of the first device to "invalid". Fast and loose
// with the type assertions as we know what the JSON decoder returns. // with the type assertions as we know what the JSON decoder returns.
devs := cfg["devices"].([]interface{}) devs := cfg["devices"].([]any)
dev0 := devs[0].(map[string]interface{}) dev0 := devs[0].(map[string]any)
dev0["deviceID"] = tc.id dev0["deviceID"] = tc.id
devs[0] = dev0 devs[0] = dev0
@@ -1197,8 +1197,8 @@ func TestInvalidFolderIDRejected(t *testing.T) {
// Change the folder ID of the first folder to the empty string. // Change the folder ID of the first folder to the empty string.
// Fast and loose with the type assertions as we know what the JSON // Fast and loose with the type assertions as we know what the JSON
// decoder returns. // decoder returns.
devs := cfg["folders"].([]interface{}) devs := cfg["folders"].([]any)
dev0 := devs[0].(map[string]interface{}) dev0 := devs[0].(map[string]any)
dev0["id"] = tc.id dev0["id"] = tc.id
devs[0] = dev0 devs[0] = dev0
@@ -1324,7 +1324,7 @@ func adjustFolderConfiguration(cfg *FolderConfiguration, id, label string, fsTyp
// defaultConfigAsMap returns a valid default config as a JSON-decoded // defaultConfigAsMap returns a valid default config as a JSON-decoded
// map[string]interface{}. This is useful to override random elements and // map[string]interface{}. This is useful to override random elements and
// re-encode into JSON. // re-encode into JSON.
func defaultConfigAsMap() map[string]interface{} { func defaultConfigAsMap() map[string]any {
cfg := New(device1) cfg := New(device1)
dev := cfg.Defaults.Device.Copy() dev := cfg.Defaults.Device.Copy()
adjustDeviceConfiguration(&dev, device2, "name") adjustDeviceConfiguration(&dev, device2, "name")
@@ -1337,7 +1337,7 @@ func defaultConfigAsMap() map[string]interface{} {
// can't happen // can't happen
panic(err) panic(err)
} }
var tmp map[string]interface{} var tmp map[string]any
if err := json.Unmarshal(bs, &tmp); err != nil { if err := json.Unmarshal(bs, &tmp); err != nil {
// can't happen // can't happen
panic(err) panic(err)
+2 -3
View File
@@ -9,6 +9,7 @@ package config
import ( import (
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
"maps"
"slices" "slices"
"strings" "strings"
@@ -45,9 +46,7 @@ type internalParam struct {
func (c VersioningConfiguration) Copy() VersioningConfiguration { func (c VersioningConfiguration) Copy() VersioningConfiguration {
cp := c cp := c
cp.Params = make(map[string]string, len(c.Params)) cp.Params = make(map[string]string, len(c.Params))
for k, v := range c.Params { maps.Copy(cp.Params, c.Params)
cp.Params[k] = v
}
return cp return cp
} }
+2 -2
View File
@@ -401,7 +401,7 @@ func TestConnectionEstablishment(t *testing.T) {
} }
} }
func withConnectionPair(b interface{ Fatal(...interface{}) }, connUri string, h func(client, server internalConn)) { func withConnectionPair(b interface{ Fatal(...any) }, connUri string, h func(client, server internalConn)) {
// Root of the service tree. // Root of the service tree.
supervisor := suture.New("main", suture.Spec{ supervisor := suture.New("main", suture.Spec{
PassThroughPanics: true, PassThroughPanics: true,
@@ -494,7 +494,7 @@ func withConnectionPair(b interface{ Fatal(...interface{}) }, connUri string, h
_ = serverConn.Close() _ = serverConn.Close()
} }
func mustGetCert(b interface{ Fatal(...interface{}) }) tls.Certificate { func mustGetCert(b interface{ Fatal(...any) }) tls.Certificate {
cert, err := tlsutil.NewCertificateInMemory("bench", 10) cert, err := tlsutil.NewCertificateInMemory("bench", 10)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
+2 -2
View File
@@ -54,7 +54,7 @@ func TestDialQueueSort(t *testing.T) {
var seen1, seen2 int var seen1, seen2 int
for i := 0; i < 100; i++ { for range 100 {
queue.Sort() queue.Sort()
res := shortDevices(queue) res := shortDevices(queue)
if reflect.DeepEqual(res, expected1) { if reflect.DeepEqual(res, expected1) {
@@ -90,7 +90,7 @@ func TestDialQueueSort(t *testing.T) {
var seen1, seen2 int var seen1, seen2 int
for i := 0; i < 100; i++ { for range 100 {
queue.Sort() queue.Sort()
res := shortDevices(queue) res := shortDevices(queue)
if reflect.DeepEqual(res, expected1) { if reflect.DeepEqual(res, expected1) {
+5 -9
View File
@@ -256,18 +256,14 @@ func (w *limitedWriter) Write(buf []byte) (int, error) {
// try to be a bit adaptable. We range from the minimum write size of 1 // try to be a bit adaptable. We range from the minimum write size of 1
// KiB up to the limiter burst size, aiming for about a write every // KiB up to the limiter burst size, aiming for about a write every
// 10ms. // 10ms.
singleWriteSize := int(w.waiter.Limit() / 100) // 10ms worth of data singleWriteSize := int(w.waiter.Limit() / 100) // 10ms worth of data
singleWriteSize = ((singleWriteSize / 1024) + 1) * 1024 // round up to the next kibibyte singleWriteSize = min(
if singleWriteSize > limiterBurstSize { // round up to the next kibibyte
singleWriteSize = limiterBurstSize ((singleWriteSize/1024)+1)*1024, limiterBurstSize)
}
written := 0 written := 0
for written < len(buf) { for written < len(buf) {
toWrite := singleWriteSize toWrite := min(singleWriteSize, len(buf)-written)
if toWrite > len(buf)-written {
toWrite = len(buf) - written
}
w.take(toWrite) w.take(toWrite)
n, err := w.writer.Write(buf[written : written+toWrite]) n, err := w.writer.Write(buf[written : written+toWrite])
written += n written += n
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build go1.15 && !noquic //go:build go1.15 && !noquic
// +build go1.15,!noquic
package connections package connections
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build !noquic //go:build !noquic
// +build !noquic
package connections package connections
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build !noquic //go:build !noquic
// +build !noquic
package connections package connections
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build noquic //go:build noquic
// +build noquic
package connections package connections
+6 -6
View File
@@ -18,23 +18,23 @@ import (
type Registry struct { type Registry struct {
mut sync.Mutex mut sync.Mutex
available map[string][]interface{} available map[string][]any
} }
func New() *Registry { func New() *Registry {
return &Registry{ return &Registry{
available: make(map[string][]interface{}), available: make(map[string][]any),
} }
} }
func (r *Registry) Register(scheme string, item interface{}) { func (r *Registry) Register(scheme string, item any) {
r.mut.Lock() r.mut.Lock()
defer r.mut.Unlock() defer r.mut.Unlock()
r.available[scheme] = append(r.available[scheme], item) r.available[scheme] = append(r.available[scheme], item)
} }
func (r *Registry) Unregister(scheme string, item interface{}) { func (r *Registry) Unregister(scheme string, item any) {
r.mut.Lock() r.mut.Lock()
defer r.mut.Unlock() defer r.mut.Unlock()
@@ -49,12 +49,12 @@ func (r *Registry) Unregister(scheme string, item interface{}) {
// Get returns an item for a schema compatible with the given scheme. // Get returns an item for a schema compatible with the given scheme.
// If any item satisfies preferred, that has precedence over other items. // If any item satisfies preferred, that has precedence over other items.
func (r *Registry) Get(scheme string, preferred func(interface{}) bool) interface{} { func (r *Registry) Get(scheme string, preferred func(any) bool) any {
r.mut.Lock() r.mut.Lock()
defer r.mut.Unlock() defer r.mut.Unlock()
var ( var (
best interface{} best any
bestPref bool bestPref bool
bestScheme string bestScheme string
) )
+4 -4
View File
@@ -14,8 +14,8 @@ import (
func TestRegistry(t *testing.T) { func TestRegistry(t *testing.T) {
r := New() r := New()
want := func(i int) func(interface{}) bool { want := func(i int) func(any) bool {
return func(x interface{}) bool { return x.(int) == i } return func(x any) bool { return x.(int) == i }
} }
if res := r.Get("int", want(1)); res != nil { if res := r.Get("int", want(1)); res != nil {
@@ -73,7 +73,7 @@ func TestShortSchemeFirst(t *testing.T) {
r.Register("foobar", 1) r.Register("foobar", 1)
// If we don't care about the value, we should get the one with "foo". // If we don't care about the value, we should get the one with "foo".
res := r.Get("foo", func(interface{}) bool { return false }) res := r.Get("foo", func(any) bool { return false })
if res != 0 { if res != 0 {
t.Error("unexpected", res) t.Error("unexpected", res)
} }
@@ -89,7 +89,7 @@ func BenchmarkGet(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
r.Get("tcp", func(x interface{}) bool { r.Get("tcp", func(x any) bool {
return x.(*net.TCPAddr).IP.IsUnspecified() return x.(*net.TCPAddr).IP.IsUnspecified()
}) })
} }
+3 -4
View File
@@ -19,6 +19,7 @@ import (
"fmt" "fmt"
"io" "io"
"log/slog" "log/slog"
"maps"
"math" "math"
"net" "net"
"net/url" "net/url"
@@ -817,7 +818,7 @@ func (s *service) createListener(factory listenerFactory, uri *url.URL) bool {
} }
func (s *service) logListenAddressesChangedEvent(l ListenerAddresses) { func (s *service) logListenAddressesChangedEvent(l ListenerAddresses) {
s.evLogger.Log(events.ListenAddressesChanged, map[string]interface{}{ s.evLogger.Log(events.ListenAddressesChanged, map[string]any{
"address": l.URI, "address": l.URI,
"lan": l.LANAddresses, "lan": l.LANAddresses,
"wan": l.WANAddresses, "wan": l.WANAddresses,
@@ -995,9 +996,7 @@ func newConnectionStatusHandler() connectionStatusHandler {
func (s *connectionStatusHandler) ConnectionStatus() map[string]ConnectionStatusEntry { func (s *connectionStatusHandler) ConnectionStatus() map[string]ConnectionStatusEntry {
result := make(map[string]ConnectionStatusEntry) result := make(map[string]ConnectionStatusEntry)
s.connectionStatusMut.RLock() s.connectionStatusMut.RLock()
for k, v := range s.connectionStatus { maps.Copy(result, s.connectionStatus)
result[k] = v
}
s.connectionStatusMut.RUnlock() s.connectionStatusMut.RUnlock()
return result return result
} }
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !solaris && !windows //go:build !solaris && !windows
// +build !solaris,!windows
package dialer package dialer
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build solaris //go:build solaris
// +build solaris
package dialer package dialer
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build windows //go:build windows
// +build windows
package dialer package dialer
+1 -1
View File
@@ -111,7 +111,7 @@ func DialContextReusePortFunc(registry *registry.Registry) func(ctx context.Cont
return DialContext(ctx, network, addr) return DialContext(ctx, network, addr)
} }
localAddrInterface := registry.Get(network, func(addr interface{}) bool { localAddrInterface := registry.Get(network, func(addr any) bool {
return addr.(*net.TCPAddr).IP.IsUnspecified() return addr.(*net.TCPAddr).IP.IsUnspecified()
}) })
if localAddrInterface == nil { if localAddrInterface == nil {
+2 -3
View File
@@ -7,6 +7,7 @@
package discover package discover
import ( import (
"maps"
"sync" "sync"
"time" "time"
@@ -60,9 +61,7 @@ func (c *cache) Get(id protocol.DeviceID) (CacheEntry, bool) {
func (c *cache) Cache() map[protocol.DeviceID]CacheEntry { func (c *cache) Cache() map[protocol.DeviceID]CacheEntry {
c.mut.Lock() c.mut.Lock()
m := make(map[protocol.DeviceID]CacheEntry, len(c.entries)) m := make(map[protocol.DeviceID]CacheEntry, len(c.entries))
for k, v := range c.entries { maps.Copy(m, c.entries)
m[k] = v
}
c.mut.Unlock() c.mut.Unlock()
return m return m
} }
+1 -1
View File
@@ -294,7 +294,7 @@ func (c *localClient) registerDevice(src net.Addr, device *discoproto.Announce)
}) })
if isNewDevice { if isNewDevice {
c.evLogger.Log(events.DeviceDiscovered, map[string]interface{}{ c.evLogger.Log(events.DeviceDiscovered, map[string]any{
"device": id.String(), "device": id.String(),
"addrs": validAddresses, "addrs": validAddresses,
}) })
+7 -7
View File
@@ -235,7 +235,7 @@ const BufferSize = 64
type Logger interface { type Logger interface {
suture.Service suture.Service
Log(t EventType, data interface{}) Log(t EventType, data any)
Subscribe(mask EventType) Subscription Subscribe(mask EventType) Subscription
} }
@@ -253,10 +253,10 @@ type Event struct {
// Per-subscription sequential event ID. Named "id" for backwards compatibility with the REST API // Per-subscription sequential event ID. Named "id" for backwards compatibility with the REST API
SubscriptionID int `json:"id"` SubscriptionID int `json:"id"`
// Global ID of the event across all subscriptions // Global ID of the event across all subscriptions
GlobalID int `json:"globalID"` GlobalID int `json:"globalID"`
Time time.Time `json:"time"` Time time.Time `json:"time"`
Type EventType `json:"type"` Type EventType `json:"type"`
Data interface{} `json:"data"` Data any `json:"data"`
} }
type Subscription interface { type Subscription interface {
@@ -325,7 +325,7 @@ loop:
return nil return nil
} }
func (l *logger) Log(t EventType, data interface{}) { func (l *logger) Log(t EventType, data any) {
l.events <- Event{ l.events <- Event{
Time: time.Now(), // intentionally high precision Time: time.Now(), // intentionally high precision
Type: t, Type: t,
@@ -559,7 +559,7 @@ var NoopLogger Logger = &noopLogger{}
func (*noopLogger) Serve(_ context.Context) error { return nil } func (*noopLogger) Serve(_ context.Context) error { return nil }
func (*noopLogger) Log(_ EventType, _ interface{}) {} func (*noopLogger) Log(_ EventType, _ any) {}
func (*noopLogger) Subscribe(_ EventType) Subscription { func (*noopLogger) Subscribe(_ EventType) Subscription {
return &noopSubscription{} return &noopSubscription{}
+4 -4
View File
@@ -127,7 +127,7 @@ func TestBufferOverflow(t *testing.T) {
t0 := time.Now() t0 := time.Now()
const nEvents = BufferSize * 2 const nEvents = BufferSize * 2
for i := 0; i < nEvents; i++ { for range nEvents {
l.Log(DeviceConnected, "foo") l.Log(DeviceConnected, "foo")
} }
if d := time.Since(t0); d > 15*time.Second { if d := time.Since(t0); d > 15*time.Second {
@@ -237,7 +237,7 @@ func TestBufferedSub(t *testing.T) {
bs := NewBufferedSubscription(s, 10*BufferSize) bs := NewBufferedSubscription(s, 10*BufferSize)
go func() { go func() {
for i := 0; i < 10*BufferSize; i++ { for i := range 10 * BufferSize {
l.Log(DeviceConnected, fmt.Sprintf("event-%d", i)) l.Log(DeviceConnected, fmt.Sprintf("event-%d", i))
if i%30 == 0 { if i%30 == 0 {
// Give the buffer routine time to pick up the events // Give the buffer routine time to pick up the events
@@ -378,7 +378,7 @@ func TestUnsubscribeContention(t *testing.T) {
stopListeners := make(chan struct{}) stopListeners := make(chan struct{})
var listenerWg sync.WaitGroup var listenerWg sync.WaitGroup
for i := 0; i < listeners; i++ { for range listeners {
listenerWg.Go(func() { listenerWg.Go(func() {
s := l.Subscribe(AllEvents) s := l.Subscribe(AllEvents)
defer s.Unsubscribe() defer s.Unsubscribe()
@@ -400,7 +400,7 @@ func TestUnsubscribeContention(t *testing.T) {
stopSenders := make(chan struct{}) stopSenders := make(chan struct{})
defer close(stopSenders) defer close(stopSenders)
var senderWg sync.WaitGroup var senderWg sync.WaitGroup
for i := 0; i < senders; i++ { for range senders {
senderWg.Go(func() { senderWg.Go(func() {
t := time.NewTicker(time.Millisecond) t := time.NewTicker(time.Millisecond)
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build linux //go:build linux
// +build linux
package fs package fs
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build windows //go:build windows
// +build windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build linux //go:build linux
// +build linux
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build linux || solaris //go:build linux || solaris
// +build linux solaris
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows //go:build !windows
// +build !windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build linux || android //go:build linux || android
// +build linux android
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !linux && !android && !windows //go:build !linux && !android && !windows
// +build !linux,!android,!windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build windows //go:build windows
// +build windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows //go:build !windows
// +build !windows
package fs package fs
+1 -1
View File
@@ -580,7 +580,7 @@ func TestXattr(t *testing.T) {
// Create a set of random attributes that we will set and read back // Create a set of random attributes that we will set and read back
var attrs []protocol.Xattr var attrs []protocol.Xattr
for i := 0; i < 10; i++ { for i := range 10 {
key := fmt.Sprintf("user.test-%d", i) key := fmt.Sprintf("user.test-%d", i)
value := make([]byte, xattrSize()) value := make([]byte, xattrSize())
rand.Read(value) rand.Read(value)
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows //go:build !windows
// +build !windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build linux //go:build linux
// +build linux
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build !linux //go:build !linux
// +build !linux
package fs package fs
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build darwin && !kqueue && cgo && !ios //go:build darwin && !kqueue && cgo && !ios
// +build darwin,!kqueue,cgo,!ios
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build solaris && cgo //go:build solaris && cgo
// +build solaris,cgo
package fs package fs
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build linux //go:build linux
// +build linux
package fs package fs
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build dragonfly || freebsd || netbsd || openbsd || ios || kqueue //go:build dragonfly || freebsd || netbsd || openbsd || ios || kqueue
// +build dragonfly freebsd netbsd openbsd ios kqueue
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build !linux && !windows && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !darwin && !cgo && !ios //go:build !linux && !windows && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !darwin && !cgo && !ios
// +build !linux,!windows,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!darwin,!cgo,!ios
// Catch all platforms that are not specifically handled to use the generic // Catch all platforms that are not specifically handled to use the generic
// event types. // event types.
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build windows //go:build windows
// +build windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build !dragonfly && !freebsd && !netbsd && !openbsd && !kqueue && !ios //go:build !dragonfly && !freebsd && !netbsd && !openbsd && !kqueue && !ios
// +build !dragonfly,!freebsd,!netbsd,!openbsd,!kqueue,!ios
package fs package fs
+2 -4
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build (!solaris && !darwin) || (solaris && cgo) || (darwin && cgo) //go:build (!solaris && !darwin) || (solaris && cgo) || (darwin && cgo)
// +build !solaris,!darwin solaris,cgo darwin,cgo
package fs package fs
@@ -364,8 +363,7 @@ func TestWatchSymlinkedRoot(t *testing.T) {
linkedFs := NewFilesystem(FilesystemTypeBasic, filepath.Join(testFs.URI(), link)) linkedFs := NewFilesystem(FilesystemTypeBasic, filepath.Join(testFs.URI(), link))
ctx, cancel := context.WithCancel(context.Background()) ctx := t.Context()
defer cancel()
if _, _, err := linkedFs.Watch(".", fakeMatcher{}, ctx, false); err != nil { if _, _, err := linkedFs.Watch(".", fakeMatcher{}, ctx, false); err != nil {
panic(err) panic(err)
} }
@@ -635,6 +633,6 @@ func (fakeEventInfo) Event() notify.Event {
return notify.Write return notify.Write
} }
func (fakeEventInfo) Sys() interface{} { func (fakeEventInfo) Sys() any {
return nil return nil
} }
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at http://mozilla.org/MPL/2.0/. // You can obtain one at http://mozilla.org/MPL/2.0/.
//go:build (solaris && !cgo) || (darwin && !cgo) || (darwin && kqueue) //go:build (solaris && !cgo) || (darwin && !cgo) || (darwin && kqueue)
// +build solaris,!cgo darwin,!cgo darwin,kqueue
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build windows //go:build windows
// +build windows
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build freebsd || netbsd //go:build freebsd || netbsd
// +build freebsd netbsd
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build linux || darwin //go:build linux || darwin
// +build linux darwin
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows && !dragonfly && !illumos && !solaris && !openbsd //go:build !windows && !dragonfly && !illumos && !solaris && !openbsd
// +build !windows,!dragonfly,!illumos,!solaris,!openbsd
package fs package fs
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build windows || dragonfly || illumos || solaris || openbsd //go:build windows || dragonfly || illumos || solaris || openbsd
// +build windows dragonfly illumos solaris openbsd
package fs package fs
+1 -1
View File
@@ -1017,6 +1017,6 @@ func (f *fakeFileInfo) Group() int {
return f.gid return f.gid
} }
func (*fakeFileInfo) Sys() interface{} { func (*fakeFileInfo) Sys() any {
return nil return nil
} }
+1 -1
View File
@@ -95,7 +95,7 @@ type FileInfo interface {
Size() int64 Size() int64
ModTime() time.Time ModTime() time.Time
IsDir() bool IsDir() bool
Sys() interface{} Sys() any
// Extensions // Extensions
IsRegular() bool IsRegular() bool
IsSymlink() bool IsSymlink() bool
+1 -4
View File
@@ -192,10 +192,7 @@ func CommonPrefix(first, second string) string {
isAbs := filepath.IsAbs(first) && filepath.IsAbs(second) isAbs := filepath.IsAbs(first) && filepath.IsAbs(second)
count := len(firstParts) count := min(len(secondParts), len(firstParts))
if len(secondParts) < len(firstParts) {
count = len(secondParts)
}
common := make([]string, 0, count) common := make([]string, 0, count)
for i := range count { for i := range count {
+1 -1
View File
@@ -106,7 +106,7 @@ func TestSanitizePath(t *testing.T) {
func TestSanitizePathFuzz(t *testing.T) { func TestSanitizePathFuzz(t *testing.T) {
buf := make([]byte, 128) buf := make([]byte, 128)
for i := 0; i < 100; i++ { for range 100 {
rand.Read(buf) rand.Read(buf)
path := SanitizePath(string(buf)) path := SanitizePath(string(buf))
if !utf8.ValidString(path) { if !utf8.ValidString(path) {
+2 -3
View File
@@ -11,6 +11,7 @@ import (
"compress/gzip" "compress/gzip"
"context" "context"
"fmt" "fmt"
"maps"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -43,9 +44,7 @@ type recordedResponse struct {
} }
func (resp *recordedResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (resp *recordedResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for k, v := range resp.header { maps.Copy(w.Header(), resp.header)
w.Header()[k] = v
}
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(resp.keep.Seconds()))) w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(resp.keep.Seconds())))
+1 -1
View File
@@ -925,7 +925,7 @@ func TestIssue4901(t *testing.T) {
} }
// Cache does not suddenly make the load succeed. // Cache does not suddenly make the load succeed.
for i := 0; i < 2; i++ { for range 2 {
err := pats.Load(".stignore") err := pats.Load(".stignore")
if err == nil { if err == nil {
t.Fatal("expected an error") t.Fatal("expected an error")
+2 -5
View File
@@ -47,7 +47,7 @@ func (randomOrderBlockPullReorderer) Reorder(blocks []protocol.BlockInfo) []prot
type standardBlockPullReorderer struct { type standardBlockPullReorderer struct {
myIndex int myIndex int
count int count int
shuffle func(interface{}) // Used for test shuffle func(any) // Used for test
} }
func newStandardBlockPullReorderer(id protocol.DeviceID, otherDevices []protocol.DeviceID) *standardBlockPullReorderer { func newStandardBlockPullReorderer(id protocol.DeviceID, otherDevices []protocol.DeviceID) *standardBlockPullReorderer {
@@ -116,10 +116,7 @@ func chunk(blocks []protocol.BlockInfo, partCount int) [][]protocol.BlockInfo {
chunkSize := (count + partCount - 1) / partCount chunkSize := (count + partCount - 1) / partCount
parts := make([][]protocol.BlockInfo, 0, partCount) parts := make([][]protocol.BlockInfo, 0, partCount)
for i := 0; i < count; i += chunkSize { for i := 0; i < count; i += chunkSize {
end := i + chunkSize end := min(i+chunkSize, count)
if end > count {
end = count
}
parts = append(parts, blocks[i:end]) parts = append(parts, blocks[i:end])
} }
return parts return parts
+1 -1
View File
@@ -92,7 +92,7 @@ func Test_standardBlockPullReorderer_Reorder(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
p := newStandardBlockPullReorderer(tt.myId, tt.devices) p := newStandardBlockPullReorderer(tt.myId, tt.devices)
p.shuffle = func(i interface{}) {} // Noop shuffle p.shuffle = func(i any) {} // Noop shuffle
if got := p.Reorder(tt.blocks); !reflect.DeepEqual(got, tt.want) { if got := p.Reorder(tt.blocks); !reflect.DeepEqual(got, tt.want) {
t.Errorf("reorderBlocksForDevices() = %v, want %v (my idx: %d, count %d)", got, tt.want, p.myIndex, p.count) t.Errorf("reorderBlocksForDevices() = %v, want %v (my idx: %d, count %d)", got, tt.want, p.myIndex, p.count)
} }
+2 -2
View File
@@ -1164,7 +1164,7 @@ func (f *folder) setWatchError(err error, nextTryIn time.Duration) {
f.watchErr = err f.watchErr = err
f.watchMut.Unlock() f.watchMut.Unlock()
if err != prevErr { //nolint:errorlint if err != prevErr { //nolint:errorlint
data := map[string]interface{}{ data := map[string]any{
"folder": f.ID, "folder": f.ID,
} }
if prevErr != nil { if prevErr != nil {
@@ -1338,7 +1338,7 @@ func (f *folder) updateLocals(fs []protocol.FileInfo) error {
if err != nil { if err != nil {
return err return err
} }
f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{ f.evLogger.Log(events.LocalIndexUpdated, map[string]any{
"folder": f.ID, "folder": f.ID,
"items": len(fs), "items": len(fs),
"filenames": filenames, "filenames": filenames,
+9 -9
View File
@@ -229,7 +229,7 @@ func (f *sendReceiveFolder) pull(ctx context.Context) (bool, error) {
f.errorsMut.Unlock() f.errorsMut.Unlock()
if pullErrNum > 0 { if pullErrNum > 0 {
f.evLogger.Log(events.FolderErrors, map[string]interface{}{ f.evLogger.Log(events.FolderErrors, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"errors": f.Errors(), "errors": f.Errors(),
}) })
@@ -564,7 +564,7 @@ func (f *sendReceiveFolder) handleDir(file protocol.FileInfo, dbUpdateChan chan<
defer func() { defer func() {
slog.Info("Created or updated directory", f.LogAttr(), file.LogAttr()) slog.Info("Created or updated directory", f.LogAttr(), file.LogAttr())
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": file.Name, "item": file.Name,
"error": events.Error(err), "error": events.Error(err),
@@ -737,7 +737,7 @@ func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo, dbUpdateChan c
} else { } else {
slog.Info("Created or updated symlink", f.LogAttr(), file.LogAttr()) slog.Info("Created or updated symlink", f.LogAttr(), file.LogAttr())
} }
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": file.Name, "item": file.Name,
"error": events.Error(err), "error": events.Error(err),
@@ -832,7 +832,7 @@ func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, dbUpdateChan chan<
} else { } else {
slog.Info("Deleted directory", f.LogAttr(), file.LogAttr()) slog.Info("Deleted directory", f.LogAttr(), file.LogAttr())
} }
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": file.Name, "item": file.Name,
"error": events.Error(err), "error": events.Error(err),
@@ -896,7 +896,7 @@ func (f *sendReceiveFolder) deleteFileWithCurrent(file, cur protocol.FileInfo, h
} else { } else {
slog.Info("Deleted "+kind, f.LogAttr(), file.LogAttr()) slog.Info("Deleted "+kind, f.LogAttr(), file.LogAttr())
} }
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": file.Name, "item": file.Name,
"error": events.Error(err), "error": events.Error(err),
@@ -981,14 +981,14 @@ func (f *sendReceiveFolder) renameFile(cur, source, target protocol.FileInfo, db
} else { } else {
slog.Info("Renamed file", f.LogAttr(), target.LogAttr(), slog.String("from", source.Name)) slog.Info("Renamed file", f.LogAttr(), target.LogAttr(), slog.String("from", source.Name))
} }
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": source.Name, "item": source.Name,
"error": events.Error(err), "error": events.Error(err),
"type": "file", "type": "file",
"action": "delete", "action": "delete",
}) })
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": target.Name, "item": target.Name,
"error": events.Error(err), "error": events.Error(err),
@@ -1275,7 +1275,7 @@ func (f *sendReceiveFolder) shortcutFile(file protocol.FileInfo, dbUpdateChan ch
} else { } else {
slog.Info("Updated file metadata", f.LogAttr(), file.LogAttr()) slog.Info("Updated file metadata", f.LogAttr(), file.LogAttr())
} }
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": file.Name, "item": file.Name,
"error": events.Error(err), "error": events.Error(err),
@@ -1748,7 +1748,7 @@ func (f *sendReceiveFolder) finisherRoutine(ctx context.Context, in <-chan *shar
f.model.progressEmitter.Deregister(state) f.model.progressEmitter.Deregister(state)
} }
f.evLogger.Log(events.ItemFinished, map[string]interface{}{ f.evLogger.Log(events.ItemFinished, map[string]any{
"folder": f.folderID, "folder": f.folderID,
"item": state.file.Name, "item": state.file.Name,
"error": events.Error(err), "error": events.Error(err),
+4 -4
View File
@@ -251,7 +251,7 @@ func TestCopierFinder(t *testing.T) {
timeout := time.After(10 * time.Second) timeout := time.After(10 * time.Second)
pulls := make([]pullBlockState, 4) pulls := make([]pullBlockState, 4)
for i := 0; i < 4; i++ { for i := range 4 {
select { select {
case pulls[i] = <-pullChan: case pulls[i] = <-pullChan:
case <-timeout: case <-timeout:
@@ -408,7 +408,7 @@ func TestDeregisterOnFailInCopy(t *testing.T) {
t0 := time.Now() t0 := time.Now()
if ev, err := s.Poll(time.Minute); err != nil { if ev, err := s.Poll(time.Minute); err != nil {
t.Fatal("Got error waiting for ItemFinished event:", err) t.Fatal("Got error waiting for ItemFinished event:", err)
} else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name { } else if n := ev.Data.(map[string]any)["item"]; n != state.file.Name {
t.Fatal("Got ItemFinished event for wrong file:", n) t.Fatal("Got ItemFinished event for wrong file:", n)
} }
t.Log("event took", time.Since(t0)) t.Log("event took", time.Since(t0))
@@ -513,7 +513,7 @@ func TestDeregisterOnFailInPull(t *testing.T) {
t0 := time.Now() t0 := time.Now()
if ev, err := s.Poll(time.Minute); err != nil { if ev, err := s.Poll(time.Minute); err != nil {
t.Fatal("Got error waiting for ItemFinished event:", err) t.Fatal("Got error waiting for ItemFinished event:", err)
} else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name { } else if n := ev.Data.(map[string]any)["item"]; n != state.file.Name {
t.Fatal("Got ItemFinished event for wrong file:", n) t.Fatal("Got ItemFinished event for wrong file:", n)
} }
t.Log("event took", time.Since(t0)) t.Log("event took", time.Since(t0))
@@ -899,7 +899,7 @@ func TestPullCtxCancel(t *testing.T) {
done := make(chan struct{}) done := make(chan struct{})
defer close(done) defer close(done)
for i := 0; i < 2; i++ { for i := range 2 {
go func() { go func() {
select { select {
case pullChan <- emptyState(): case pullChan <- emptyState():
-1
View File
@@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/. // You can obtain one at https://mozilla.org/MPL/2.0/.
//go:build !windows //go:build !windows
// +build !windows
package model package model
+2 -2
View File
@@ -265,7 +265,7 @@ func (c *folderSummaryService) processUpdate(ev events.Event) {
return return
case events.StateChanged: case events.StateChanged:
data := ev.Data.(map[string]interface{}) data := ev.Data.(map[string]any)
if data["to"].(string) != "idle" { if data["to"].(string) != "idle" {
return return
} }
@@ -296,7 +296,7 @@ func (c *folderSummaryService) processUpdate(ev events.Event) {
// This folder needs to be refreshed whenever we do the next // This folder needs to be refreshed whenever we do the next
// refresh. // refresh.
folder = ev.Data.(map[string]interface{})["folder"].(string) folder = ev.Data.(map[string]any)["folder"].(string)
} }
c.foldersMut.Lock() c.foldersMut.Lock()
+2 -2
View File
@@ -119,7 +119,7 @@ func (s *stateTracker) setState(newState folderState) {
metricFolderState.WithLabelValues(s.folderID).Set(float64(s.current)) metricFolderState.WithLabelValues(s.folderID).Set(float64(s.current))
}() }()
eventData := map[string]interface{}{ eventData := map[string]any{
"folder": s.folderID, "folder": s.folderID,
"to": newState.String(), "to": newState.String(),
"from": s.current.String(), "from": s.current.String(),
@@ -156,7 +156,7 @@ func (s *stateTracker) setError(err error) {
metricFolderState.WithLabelValues(s.folderID).Set(float64(s.current)) metricFolderState.WithLabelValues(s.folderID).Set(float64(s.current))
}() }()
eventData := map[string]interface{}{ eventData := map[string]any{
"folder": s.folderID, "folder": s.folderID,
"from": s.current.String(), "from": s.current.String(),
} }
+1 -1
View File
@@ -453,7 +453,7 @@ func (s *indexHandler) receive(fs []protocol.FileInfo, update bool, op string, p
}) })
} }
s.evLogger.Log(events.RemoteIndexUpdated, map[string]interface{}{ s.evLogger.Log(events.RemoteIndexUpdated, map[string]any{
"device": deviceID.String(), "device": deviceID.String(),
"folder": s.folder, "folder": s.folder,
"items": len(fs), "items": len(fs),
+4 -6
View File
@@ -7,7 +7,6 @@
package model_test package model_test
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@@ -23,8 +22,7 @@ import (
func TestIndexhandlerConcurrency(t *testing.T) { func TestIndexhandlerConcurrency(t *testing.T) {
// Verify that sending a lot of index update messages using the // Verify that sending a lot of index update messages using the
// FileInfoBatch works and doesn't trigger the race detector. // FileInfoBatch works and doesn't trigger the race detector.
ctx, cancel := context.WithCancel(context.Background()) ctx := t.Context()
defer cancel()
ar, aw := io.Pipe() ar, aw := io.Pipe()
br, bw := io.Pipe() br, bw := io.Pipe()
@@ -52,7 +50,7 @@ func TestIndexhandlerConcurrency(t *testing.T) {
recvdBatches := 0 recvdBatches := 0
var wg sync.WaitGroup var wg sync.WaitGroup
m2.IndexUpdateCalls(func(_ protocol.Connection, idxUp *protocol.IndexUpdate) error { m2.IndexUpdateCalls(func(_ protocol.Connection, idxUp *protocol.IndexUpdate) error {
for j := 0; j < files; j++ { for j := range int(files) {
if n := idxUp.Files[j].Name; n != fmt.Sprintf("f%d-%d", recvdBatches, j) { if n := idxUp.Files[j].Name; n != fmt.Sprintf("f%d-%d", recvdBatches, j) {
t.Error("wrong filename", n) t.Error("wrong filename", n)
} }
@@ -67,8 +65,8 @@ func TestIndexhandlerConcurrency(t *testing.T) {
return c1.IndexUpdate(ctx, &protocol.IndexUpdate{Folder: "foo", Files: fs}) return c1.IndexUpdate(ctx, &protocol.IndexUpdate{Folder: "foo", Files: fs})
}) })
sentEntries := 0 sentEntries := 0
for i := 0; i < msgs; i++ { for i := range int(msgs) {
for j := 0; j < files; j++ { for j := range int(files) {
b1.Append(protocol.FileInfo{ b1.Append(protocol.FileInfo{
Name: fmt.Sprintf("f%d-%d", i, j), Name: fmt.Sprintf("f%d-%d", i, j),
Blocks: []protocol.BlockInfo{{Hash: make([]byte, 32)}}, Blocks: []protocol.BlockInfo{{Hash: make([]byte, 32)}},
+15 -15
View File
@@ -116,7 +116,7 @@ type Model interface {
Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) ([]Availability, error) Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) ([]Availability, error)
Completion(device protocol.DeviceID, folder string) (FolderCompletion, error) Completion(device protocol.DeviceID, folder string) (FolderCompletion, error)
ConnectionStats() map[string]interface{} ConnectionStats() map[string]any
DeviceStatistics() (map[protocol.DeviceID]stats.DeviceStatistics, error) DeviceStatistics() (map[protocol.DeviceID]stats.DeviceStatistics, error)
FolderStatistics() (map[string]stats.FolderStatistics, error) FolderStatistics() (map[string]stats.FolderStatistics, error)
UsageReportingStats(report *contract.Report, version int, preview bool) UsageReportingStats(report *contract.Report, version int, preview bool)
@@ -684,7 +684,7 @@ type ConnectionStats struct {
IsLocal bool `json:"isLocal"` // mirror values from Primary, for compatibility with <1.24.0 IsLocal bool `json:"isLocal"` // mirror values from Primary, for compatibility with <1.24.0
Crypto string `json:"crypto"` // mirror values from Primary, for compatibility with <1.24.0 Crypto string `json:"crypto"` // mirror values from Primary, for compatibility with <1.24.0
Primary ConnectionInfo `json:"primary,omitempty"` Primary ConnectionInfo `json:"primary"`
Secondary []ConnectionInfo `json:"secondary,omitempty"` Secondary []ConnectionInfo `json:"secondary,omitempty"`
} }
@@ -698,11 +698,11 @@ type ConnectionInfo struct {
} }
// ConnectionStats returns a map with connection statistics for each device. // ConnectionStats returns a map with connection statistics for each device.
func (m *model) ConnectionStats() map[string]interface{} { func (m *model) ConnectionStats() map[string]any {
m.mut.RLock() m.mut.RLock()
defer m.mut.RUnlock() defer m.mut.RUnlock()
res := make(map[string]interface{}) res := make(map[string]any)
devs := m.cfg.Devices() devs := m.cfg.Devices()
conns := make(map[string]ConnectionStats, len(devs)) conns := make(map[string]ConnectionStats, len(devs))
for device, deviceCfg := range devs { for device, deviceCfg := range devs {
@@ -762,7 +762,7 @@ func (m *model) ConnectionStats() map[string]interface{} {
res["connections"] = conns res["connections"] = conns
in, out := protocol.TotalInOut() in, out := protocol.TotalInOut()
res["total"] = map[string]interface{}{ res["total"] = map[string]any{
"at": time.Now().Truncate(time.Second), "at": time.Now().Truncate(time.Second),
"inBytesTotal": in, "inBytesTotal": in,
"outBytesTotal": out, "outBytesTotal": out,
@@ -862,8 +862,8 @@ func (comp *FolderCompletion) setCompletionPct() {
} }
// Map returns the members as a map, e.g. used in api to serialize as JSON. // Map returns the members as a map, e.g. used in api to serialize as JSON.
func (comp *FolderCompletion) Map() map[string]interface{} { func (comp *FolderCompletion) Map() map[string]any {
return map[string]interface{}{ return map[string]any{
"completion": comp.CompletionPct, "completion": comp.CompletionPct,
"globalBytes": comp.GlobalBytes, "globalBytes": comp.GlobalBytes,
"needBytes": comp.NeedBytes, "needBytes": comp.NeedBytes,
@@ -1516,7 +1516,7 @@ func (m *model) ccHandleFolders(folders []protocol.Folder, deviceCfg config.Devi
}) })
} }
if len(updatedPending) > 0 || len(expiredPendingList) > 0 { if len(updatedPending) > 0 || len(expiredPendingList) > 0 {
m.evLogger.Log(events.PendingFoldersChanged, map[string]interface{}{ m.evLogger.Log(events.PendingFoldersChanged, map[string]any{
"added": updatedPending, "added": updatedPending,
"removed": expiredPendingList, "removed": expiredPendingList,
}) })
@@ -2266,7 +2266,7 @@ func (m *model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protoco
if err := m.observed.AddOrUpdatePendingDevice(remoteID, hello.DeviceName, addr.String()); err != nil { if err := m.observed.AddOrUpdatePendingDevice(remoteID, hello.DeviceName, addr.String()); err != nil {
slog.Warn("Failed to persist pending device entry to database", slogutil.Error(err)) slog.Warn("Failed to persist pending device entry to database", slogutil.Error(err))
} }
m.evLogger.Log(events.PendingDevicesChanged, map[string][]interface{}{ m.evLogger.Log(events.PendingDevicesChanged, map[string][]any{
"added": {map[string]string{ "added": {map[string]string{
"deviceID": remoteID.String(), "deviceID": remoteID.String(),
"name": hello.DeviceName, "name": hello.DeviceName,
@@ -2426,7 +2426,7 @@ func (m *model) DownloadProgress(conn protocol.Connection, p *protocol.DownloadP
downloads.Update(p.Folder, p.Updates) downloads.Update(p.Folder, p.Updates)
state := downloads.GetBlockCounts(p.Folder) state := downloads.GetBlockCounts(p.Folder)
m.evLogger.Log(events.RemoteDownloadProgress, map[string]interface{}{ m.evLogger.Log(events.RemoteDownloadProgress, map[string]any{
"device": deviceID.String(), "device": deviceID.String(),
"folder": p.Folder, "folder": p.Folder,
"state": state, "state": state,
@@ -2772,7 +2772,7 @@ func (m *model) GlobalDirectoryTree(folder, prefix string, levels int, dirsOnly
parent := root parent := root
if dir != "." { if dir != "." {
for _, path := range strings.Split(dir, sep) { for path := range strings.SplitSeq(dir, sep) {
child := findByName(parent.Children, path) child := findByName(parent.Children, path)
if child == nil { if child == nil {
return nil, fmt.Errorf("could not find child '%s' for path '%s' in parent '%s'", path, f.Name, parent.Name) return nil, fmt.Errorf("could not find child '%s' for path '%s' in parent '%s'", path, f.Name, parent.Name)
@@ -3183,7 +3183,7 @@ func (m *model) cleanPending(existingDevices map[protocol.DeviceID]config.Device
} }
} }
if len(removedPendingFolders) > 0 { if len(removedPendingFolders) > 0 {
m.evLogger.Log(events.PendingFoldersChanged, map[string]interface{}{ m.evLogger.Log(events.PendingFoldersChanged, map[string]any{
"removed": removedPendingFolders, "removed": removedPendingFolders,
}) })
} }
@@ -3218,7 +3218,7 @@ func (m *model) cleanPending(existingDevices map[protocol.DeviceID]config.Device
}) })
} }
if len(removedPendingDevices) > 0 { if len(removedPendingDevices) > 0 {
m.evLogger.Log(events.PendingDevicesChanged, map[string]interface{}{ m.evLogger.Log(events.PendingDevicesChanged, map[string]any{
"removed": removedPendingDevices, "removed": removedPendingDevices,
}) })
} }
@@ -3264,7 +3264,7 @@ func (m *model) DismissPendingDevice(device protocol.DeviceID) error {
removedPendingDevices := []map[string]string{ removedPendingDevices := []map[string]string{
{"deviceID": device.String()}, {"deviceID": device.String()},
} }
m.evLogger.Log(events.PendingDevicesChanged, map[string]interface{}{ m.evLogger.Log(events.PendingDevicesChanged, map[string]any{
"removed": removedPendingDevices, "removed": removedPendingDevices,
}) })
return nil return nil
@@ -3298,7 +3298,7 @@ func (m *model) DismissPendingFolder(device protocol.DeviceID, folder string) er
} }
} }
if len(removedPendingFolders) > 0 { if len(removedPendingFolders) > 0 {
m.evLogger.Log(events.PendingFoldersChanged, map[string]interface{}{ m.evLogger.Log(events.PendingFoldersChanged, map[string]any{
"removed": removedPendingFolders, "removed": removedPendingFolders,
}) })
} }
+8 -8
View File
@@ -151,7 +151,7 @@ func TestRequest(t *testing.T) {
func genFiles(n int) []protocol.FileInfo { func genFiles(n int) []protocol.FileInfo {
files := make([]protocol.FileInfo, n) files := make([]protocol.FileInfo, n)
t := time.Now().Unix() t := time.Now().Unix()
for i := 0; i < n; i++ { for i := range n {
files[i] = protocol.FileInfo{ files[i] = protocol.FileInfo{
Name: fmt.Sprintf("file%d", i), Name: fmt.Sprintf("file%d", i),
ModifiedS: t, ModifiedS: t,
@@ -1007,7 +1007,7 @@ func TestIssue5063(t *testing.T) {
reps := 10 reps := 10
ids := make([]string, reps) ids := make([]string, reps)
for i := 0; i < reps; i++ { for i := range reps {
ids[i] = srand.String(8) ids[i] = srand.String(8)
wg.Go(func() { addAndVerify(ids[i]) }) wg.Go(func() { addAndVerify(ids[i]) })
} }
@@ -1668,7 +1668,7 @@ func waitForState(t *testing.T, sub events.Subscription, folder, expected string
for { for {
select { select {
case ev := <-sub.C(): case ev := <-sub.C():
data := ev.Data.(map[string]interface{}) data := ev.Data.(map[string]any)
if data["folder"].(string) == folder { if data["folder"].(string) == folder {
if data["error"] == nil { if data["error"] == nil {
err = "" err = ""
@@ -1880,7 +1880,7 @@ func TestGlobalDirectoryTree(t *testing.T) {
f("zzrootfile"), f("zzrootfile"),
} }
mm := func(data interface{}) string { mm := func(data any) string {
bytes, err := json.MarshalIndent(data, "", " ") bytes, err := json.MarshalIndent(data, "", " ")
if err != nil { if err != nil {
panic(err) panic(err)
@@ -2952,7 +2952,7 @@ func TestFolderRestartZombies(t *testing.T) {
// Run a few parallel configuration changers for one second. Each waits // Run a few parallel configuration changers for one second. Each waits
// for the commit to complete, but there are many of them. // for the commit to complete, but there are many of them.
var wg sync.WaitGroup var wg sync.WaitGroup
for i := 0; i < 25; i++ { for range 25 {
wg.Go(func() { wg.Go(func() {
t0 := time.Now() t0 := time.Now()
for time.Since(t0) < time.Second { for time.Since(t0) < time.Second {
@@ -3258,7 +3258,7 @@ func TestRenameSequenceOrder(t *testing.T) {
numFiles := 20 numFiles := 20
ffs := fcfg.Filesystem() ffs := fcfg.Filesystem()
for i := 0; i < numFiles; i++ { for i := range numFiles {
v := fmt.Sprintf("%d", i) v := fmt.Sprintf("%d", i)
writeFile(t, ffs, v, []byte(v)) writeFile(t, ffs, v, []byte(v))
} }
@@ -3272,7 +3272,7 @@ func TestRenameSequenceOrder(t *testing.T) {
// Modify all the files other than the rename sources, whose content we // Modify all the files other than the rename sources, whose content we
// keep intact so the renamed copies still match by block hash. // keep intact so the renamed copies still match by block hash.
for i := 0; i < numFiles; i++ { for i := range numFiles {
if i == 3 || i == 16 { if i == 3 || i == 16 {
continue continue
} }
@@ -3388,7 +3388,7 @@ func TestRenameBatchFlush(t *testing.T) {
writeFile(t, ffs, "dst-a", content) writeFile(t, ffs, "dst-a", content)
writeFile(t, ffs, "dst-b", content) writeFile(t, ffs, "dst-b", content)
for i := range MaxBatchSizeFiles * 2 { for i := range MaxBatchSizeFiles * 2 {
writeFile(t, ffs, fmt.Sprintf("filler-%04d", i), []byte(fmt.Sprintf("filler-%04d", i))) writeFile(t, ffs, fmt.Sprintf("filler-%04d", i), fmt.Appendf(nil, "filler-%04d", i))
} }
m.ScanFolders() m.ScanFolders()

Some files were not shown because too many files have changed in this diff Show More