hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 6, "code_window": [ "func (f FileInfoTruncated) String() string {\n", "\treturn fmt.Sprintf(\"File{Name:%q, Flags:0%o, Modified:%d, Version:%d, Size:%d, NumBlocks:%d}\",\n", "\t\tf.Name, f.Flags, f.Modified, f.Version, f.Size(), f.NumBlocks)\n", "}\n", "\n", "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func BlocksToSize(num uint32) int64 {\n", "\tif num < 2 {\n", "\t\treturn BlockSize / 2\n", "\t}\n", "\treturn int64(num-1)*BlockSize + BlockSize/2\n", "}\n", "\n" ], "file_path": "internal/protocol/message.go", "type": "add", "edit_start_line_idx": 83 }
// Copyright (C) 2014 The Syncthing Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // // You should have received a copy of the GNU General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. package main import ( "crypto/tls" "encoding/json" "fmt" "io/ioutil" "mime" "net" "net/http" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "time" "code.google.com/p/go.crypto/bcrypt" "github.com/calmh/logger" "github.com/syncthing/syncthing/internal/auto" "github.com/syncthing/syncthing/internal/config" "github.com/syncthing/syncthing/internal/discover" "github.com/syncthing/syncthing/internal/events" "github.com/syncthing/syncthing/internal/model" "github.com/syncthing/syncthing/internal/osutil" "github.com/syncthing/syncthing/internal/protocol" "github.com/syncthing/syncthing/internal/upgrade" "github.com/vitrun/qart/qr" ) type guiError struct { Time time.Time Error string } var ( configInSync = true guiErrors = []guiError{} guiErrorsMut sync.Mutex modt = time.Now().UTC().Format(http.TimeFormat) eventSub *events.BufferedSubscription ) func init() { l.AddHandler(logger.LevelWarn, showGuiError) sub := events.Default.Subscribe(events.AllEvents) eventSub = events.NewBufferedSubscription(sub, 1000) } func startGUI(cfg config.GUIConfiguration, assetDir string, m *model.Model) error { var err error cert, err := loadCert(confDir, "https-") if err != nil { l.Infoln("Loading HTTPS certificate:", err) l.Infoln("Creating new HTTPS certificate") newCertificate(confDir, "https-") cert, err = loadCert(confDir, "https-") } if err != nil { return err } tlsCfg := &tls.Config{ Certificates: []tls.Certificate{cert}, ServerName: "syncthing", } rawListener, err := net.Listen("tcp", cfg.Address) if err != nil { return err } listener := &DowngradingListener{rawListener, tlsCfg} // The GET handlers getRestMux := http.NewServeMux() getRestMux.HandleFunc("/rest/ping", restPing) getRestMux.HandleFunc("/rest/completion", withModel(m, restGetCompletion)) getRestMux.HandleFunc("/rest/config", restGetConfig) getRestMux.HandleFunc("/rest/config/sync", restGetConfigInSync) getRestMux.HandleFunc("/rest/connections", withModel(m, restGetConnections)) getRestMux.HandleFunc("/rest/autocomplete/directory", restGetAutocompleteDirectory) getRestMux.HandleFunc("/rest/discovery", restGetDiscovery) getRestMux.HandleFunc("/rest/errors", restGetErrors) getRestMux.HandleFunc("/rest/events", restGetEvents) getRestMux.HandleFunc("/rest/ignores", withModel(m, restGetIgnores)) getRestMux.HandleFunc("/rest/lang", restGetLang) getRestMux.HandleFunc("/rest/model", withModel(m, restGetModel)) getRestMux.HandleFunc("/rest/need", withModel(m, restGetNeed)) getRestMux.HandleFunc("/rest/deviceid", restGetDeviceID) getRestMux.HandleFunc("/rest/report", withModel(m, restGetReport)) getRestMux.HandleFunc("/rest/system", restGetSystem) getRestMux.HandleFunc("/rest/upgrade", restGetUpgrade) getRestMux.HandleFunc("/rest/version", restGetVersion) getRestMux.HandleFunc("/rest/stats/device", withModel(m, restGetDeviceStats)) // Debug endpoints, not for general use getRestMux.HandleFunc("/rest/debug/peerCompletion", withModel(m, restGetPeerCompletion)) // The POST handlers postRestMux := http.NewServeMux() postRestMux.HandleFunc("/rest/ping", restPing) postRestMux.HandleFunc("/rest/config", withModel(m, restPostConfig)) postRestMux.HandleFunc("/rest/discovery/hint", restPostDiscoveryHint) postRestMux.HandleFunc("/rest/error", restPostError) postRestMux.HandleFunc("/rest/error/clear", restClearErrors) postRestMux.HandleFunc("/rest/ignores", withModel(m, restPostIgnores)) postRestMux.HandleFunc("/rest/model/override", withModel(m, restPostOverride)) postRestMux.HandleFunc("/rest/reset", restPostReset) postRestMux.HandleFunc("/rest/restart", restPostRestart) postRestMux.HandleFunc("/rest/shutdown", restPostShutdown) postRestMux.HandleFunc("/rest/upgrade", restPostUpgrade) postRestMux.HandleFunc("/rest/scan", withModel(m, restPostScan)) // A handler that splits requests between the two above and disables // caching restMux := noCacheMiddleware(getPostHandler(getRestMux, postRestMux)) // The main routing handler mux := http.NewServeMux() mux.Handle("/rest/", restMux) mux.HandleFunc("/qr/", getQR) // Serve compiled in assets unless an asset directory was set (for development) mux.Handle("/", embeddedStatic(assetDir)) // Wrap everything in CSRF protection. The /rest prefix should be // protected, other requests will grant cookies. handler := csrfMiddleware("/rest", cfg.APIKey, mux) // Add our version as a header to responses handler = withVersionMiddleware(handler) // Wrap everything in basic auth, if user/password is set. if len(cfg.User) > 0 && len(cfg.Password) > 0 { handler = basicAuthAndSessionMiddleware(cfg, handler) } // Redirect to HTTPS if we are supposed to if cfg.UseTLS { handler = redirectToHTTPSMiddleware(handler) } srv := http.Server{ Handler: handler, ReadTimeout: 2 * time.Second, } go func() { err := srv.Serve(listener) if err != nil { panic(err) } }() return nil } func getPostHandler(get, post http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": get.ServeHTTP(w, r) case "POST": post.ServeHTTP(w, r) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } }) } func redirectToHTTPSMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Add a generous access-control-allow-origin header since we may be // redirecting REST requests over protocols w.Header().Add("Access-Control-Allow-Origin", "*") if r.TLS == nil { // Redirect HTTP requests to HTTPS r.URL.Host = r.Host r.URL.Scheme = "https" http.Redirect(w, r, r.URL.String(), http.StatusFound) } else { h.ServeHTTP(w, r) } }) } func noCacheMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-cache") h.ServeHTTP(w, r) }) } func withVersionMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Syncthing-Version", Version) h.ServeHTTP(w, r) }) } func withModel(m *model.Model, h func(m *model.Model, w http.ResponseWriter, r *http.Request)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { h(m, w, r) } } func restPing(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(map[string]string{ "ping": "pong", }) } func restGetVersion(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(map[string]string{ "version": Version, "longVersion": LongVersion, "os": runtime.GOOS, "arch": runtime.GOARCH, }) } func restGetCompletion(m *model.Model, w http.ResponseWriter, r *http.Request) { var qs = r.URL.Query() var folder = qs.Get("folder") var deviceStr = qs.Get("device") device, err := protocol.DeviceIDFromString(deviceStr) if err != nil { http.Error(w, err.Error(), 500) return } res := map[string]float64{ "completion": m.Completion(device, folder), } w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(res) } func restGetModel(m *model.Model, w http.ResponseWriter, r *http.Request) { var qs = r.URL.Query() var folder = qs.Get("folder") var res = make(map[string]interface{}) res["invalid"] = cfg.Folders()[folder].Invalid globalFiles, globalDeleted, globalBytes := m.GlobalSize(folder) res["globalFiles"], res["globalDeleted"], res["globalBytes"] = globalFiles, globalDeleted, globalBytes localFiles, localDeleted, localBytes := m.LocalSize(folder) res["localFiles"], res["localDeleted"], res["localBytes"] = localFiles, localDeleted, localBytes needFiles, needBytes := m.NeedSize(folder) res["needFiles"], res["needBytes"] = needFiles, needBytes res["inSyncFiles"], res["inSyncBytes"] = globalFiles-needFiles, globalBytes-needBytes res["state"], res["stateChanged"] = m.State(folder) res["version"] = m.CurrentLocalVersion(folder) + m.RemoteLocalVersion(folder) w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(res) } func restPostOverride(m *model.Model, w http.ResponseWriter, r *http.Request) { var qs = r.URL.Query() var folder = qs.Get("folder") go m.Override(folder) } func restGetNeed(m *model.Model, w http.ResponseWriter, r *http.Request) { var qs = r.URL.Query() var folder = qs.Get("folder") files := m.NeedFolderFilesLimited(folder, 100, 2500) // max 100 files or 2500 blocks w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(files) } func restGetConnections(m *model.Model, w http.ResponseWriter, r *http.Request) { var res = m.ConnectionStats() w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(res) } func restGetDeviceStats(m *model.Model, w http.ResponseWriter, r *http.Request) { var res = m.DeviceStatistics() w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(res) } func restGetConfig(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(cfg.Raw()) } func restPostConfig(m *model.Model, w http.ResponseWriter, r *http.Request) { var newCfg config.Configuration err := json.NewDecoder(r.Body).Decode(&newCfg) if err != nil { l.Warnln("decoding posted config:", err) http.Error(w, err.Error(), 500) return } else { if newCfg.GUI.Password != cfg.GUI().Password { if newCfg.GUI.Password != "" { hash, err := bcrypt.GenerateFromPassword([]byte(newCfg.GUI.Password), 0) if err != nil { l.Warnln("bcrypting password:", err) http.Error(w, err.Error(), 500) return } else { newCfg.GUI.Password = string(hash) } } } // Start or stop usage reporting as appropriate if curAcc := cfg.Options().URAccepted; newCfg.Options.URAccepted > curAcc { // UR was enabled newCfg.Options.URAccepted = usageReportVersion err := sendUsageReport(m) if err != nil { l.Infoln("Usage report:", err) } go usageReportingLoop(m) } else if newCfg.Options.URAccepted < curAcc { // UR was disabled newCfg.Options.URAccepted = -1 stopUsageReporting() } // Activate and save configInSync = !config.ChangeRequiresRestart(cfg.Raw(), newCfg) cfg.Replace(newCfg) cfg.Save() } } func restGetConfigInSync(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(map[string]bool{"configInSync": configInSync}) } func restPostRestart(w http.ResponseWriter, r *http.Request) { flushResponse(`{"ok": "restarting"}`, w) go restart() } func restPostReset(w http.ResponseWriter, r *http.Request) { flushResponse(`{"ok": "resetting folders"}`, w) resetFolders() go restart() } func restPostShutdown(w http.ResponseWriter, r *http.Request) { flushResponse(`{"ok": "shutting down"}`, w) go shutdown() } func flushResponse(s string, w http.ResponseWriter) { w.Write([]byte(s + "\n")) f := w.(http.Flusher) f.Flush() } var cpuUsagePercent [10]float64 // The last ten seconds var cpuUsageLock sync.RWMutex func restGetSystem(w http.ResponseWriter, r *http.Request) { var m runtime.MemStats runtime.ReadMemStats(&m) tilde, _ := osutil.ExpandTilde("~") res := make(map[string]interface{}) res["myID"] = myID.String() res["goroutines"] = runtime.NumGoroutine() res["alloc"] = m.Alloc res["sys"] = m.Sys - m.HeapReleased res["tilde"] = tilde if cfg.Options().GlobalAnnEnabled && discoverer != nil { res["extAnnounceOK"] = discoverer.ExtAnnounceOK() } cpuUsageLock.RLock() var cpusum float64 for _, p := range cpuUsagePercent { cpusum += p } cpuUsageLock.RUnlock() res["cpuPercent"] = cpusum / 10 w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(res) } func restGetErrors(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") guiErrorsMut.Lock() json.NewEncoder(w).Encode(map[string][]guiError{"errors": guiErrors}) guiErrorsMut.Unlock() } func restPostError(w http.ResponseWriter, r *http.Request) { bs, _ := ioutil.ReadAll(r.Body) r.Body.Close() showGuiError(0, string(bs)) } func restClearErrors(w http.ResponseWriter, r *http.Request) { guiErrorsMut.Lock() guiErrors = []guiError{} guiErrorsMut.Unlock() } func showGuiError(l logger.LogLevel, err string) { guiErrorsMut.Lock() guiErrors = append(guiErrors, guiError{time.Now(), err}) if len(guiErrors) > 5 { guiErrors = guiErrors[len(guiErrors)-5:] } guiErrorsMut.Unlock() } func restPostDiscoveryHint(w http.ResponseWriter, r *http.Request) { var qs = r.URL.Query() var device = qs.Get("device") var addr = qs.Get("addr") if len(device) != 0 && len(addr) != 0 && discoverer != nil { discoverer.Hint(device, []string{addr}) } } func restGetDiscovery(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") devices := map[string][]discover.CacheEntry{} if discoverer != nil { // Device ids can't be marshalled as keys so we need to manually // rebuild this map using strings. Discoverer may be nil if discovery // has not started yet. for device, entries := range discoverer.All() { devices[device.String()] = entries } } json.NewEncoder(w).Encode(devices) } func restGetReport(m *model.Model, w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(reportData(m)) } func restGetIgnores(m *model.Model, w http.ResponseWriter, r *http.Request) { qs := r.URL.Query() w.Header().Set("Content-Type", "application/json; charset=utf-8") ignores, patterns, err := m.GetIgnores(qs.Get("folder")) if err != nil { http.Error(w, err.Error(), 500) return } json.NewEncoder(w).Encode(map[string][]string{ "ignore": ignores, "patterns": patterns, }) } func restPostIgnores(m *model.Model, w http.ResponseWriter, r *http.Request) { qs := r.URL.Query() var data map[string][]string err := json.NewDecoder(r.Body).Decode(&data) r.Body.Close() if err != nil { http.Error(w, err.Error(), 500) return } err = m.SetIgnores(qs.Get("folder"), data["ignore"]) if err != nil { http.Error(w, err.Error(), 500) return } restGetIgnores(m, w, r) } func restGetEvents(w http.ResponseWriter, r *http.Request) { qs := r.URL.Query() sinceStr := qs.Get("since") limitStr := qs.Get("limit") since, _ := strconv.Atoi(sinceStr) limit, _ := strconv.Atoi(limitStr) w.Header().Set("Content-Type", "application/json; charset=utf-8") // Flush before blocking, to indicate that we've received the request // and that it should not be retried. f := w.(http.Flusher) f.Flush() evs := eventSub.Since(since, nil) if 0 < limit && limit < len(evs) { evs = evs[len(evs)-limit:] } json.NewEncoder(w).Encode(evs) } func restGetUpgrade(w http.ResponseWriter, r *http.Request) { rel, err := upgrade.LatestRelease(strings.Contains(Version, "-beta")) if err != nil { http.Error(w, err.Error(), 500) return } res := make(map[string]interface{}) res["running"] = Version res["latest"] = rel.Tag res["newer"] = upgrade.CompareVersions(rel.Tag, Version) == 1 w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(res) } func restGetDeviceID(w http.ResponseWriter, r *http.Request) { qs := r.URL.Query() idStr := qs.Get("id") id, err := protocol.DeviceIDFromString(idStr) w.Header().Set("Content-Type", "application/json; charset=utf-8") if err == nil { json.NewEncoder(w).Encode(map[string]string{ "id": id.String(), }) } else { json.NewEncoder(w).Encode(map[string]string{ "error": err.Error(), }) } } func restGetLang(w http.ResponseWriter, r *http.Request) { lang := r.Header.Get("Accept-Language") var langs []string for _, l := range strings.Split(lang, ",") { parts := strings.SplitN(l, ";", 2) langs = append(langs, strings.ToLower(strings.TrimSpace(parts[0]))) } w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(langs) } func restPostUpgrade(w http.ResponseWriter, r *http.Request) { rel, err := upgrade.LatestRelease(strings.Contains(Version, "-beta")) if err != nil { l.Warnln("getting latest release:", err) http.Error(w, err.Error(), 500) return } if upgrade.CompareVersions(rel.Tag, Version) == 1 { err = upgrade.UpgradeTo(rel, GoArchExtra) if err != nil { l.Warnln("upgrading:", err) http.Error(w, err.Error(), 500) return } flushResponse(`{"ok": "restarting"}`, w) l.Infoln("Upgrading") stop <- exitUpgrading } } func restPostScan(m *model.Model, w http.ResponseWriter, r *http.Request) { qs := r.URL.Query() folder := qs.Get("folder") sub := qs.Get("sub") err := m.ScanFolderSub(folder, sub) if err != nil { http.Error(w, err.Error(), 500) } } func getQR(w http.ResponseWriter, r *http.Request) { var qs = r.URL.Query() var text = qs.Get("text") code, err := qr.Encode(text, qr.M) if err != nil { http.Error(w, "Invalid", 500) return } w.Header().Set("Content-Type", "image/png") w.Write(code.PNG()) } func restGetPeerCompletion(m *model.Model, w http.ResponseWriter, r *http.Request) { tot := map[string]float64{} count := map[string]float64{} for _, folder := range cfg.Folders() { for _, device := range folder.DeviceIDs() { deviceStr := device.String() if m.ConnectedTo(device) { tot[deviceStr] += m.Completion(device, folder.ID) } else { tot[deviceStr] = 0 } count[deviceStr]++ } } comp := map[string]int{} for device := range tot { comp[device] = int(tot[device] / count[device]) } w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(comp) } func restGetAutocompleteDirectory(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") qs := r.URL.Query() current := qs.Get("current") search, _ := osutil.ExpandTilde(current) pathSeparator := string(os.PathSeparator) if strings.HasSuffix(current, pathSeparator) && !strings.HasSuffix(search, pathSeparator) { search = search + pathSeparator } subdirectories, _ := filepath.Glob(search + "*") ret := make([]string, 0, 10) for _, subdirectory := range subdirectories { info, err := os.Stat(subdirectory) if err == nil && info.IsDir() { ret = append(ret, subdirectory + pathSeparator) if len(ret) > 9 { break } } } json.NewEncoder(w).Encode(ret) } func embeddedStatic(assetDir string) http.Handler { assets := auto.Assets() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { file := r.URL.Path if file[0] == '/' { file = file[1:] } if len(file) == 0 { file = "index.html" } if assetDir != "" { p := filepath.Join(assetDir, filepath.FromSlash(file)) _, err := os.Stat(p) if err == nil { http.ServeFile(w, r, p) return } } bs, ok := assets[file] if !ok { http.NotFound(w, r) return } mtype := mimeTypeForFile(file) if len(mtype) != 0 { w.Header().Set("Content-Type", mtype) } w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs))) w.Header().Set("Last-Modified", modt) w.Write(bs) }) } func mimeTypeForFile(file string) string { // We use a built in table of the common types since the system // TypeByExtension might be unreliable. But if we don't know, we delegate // to the system. ext := filepath.Ext(file) switch ext { case ".htm", ".html": return "text/html" case ".css": return "text/css" case ".js": return "application/javascript" case ".json": return "application/json" case ".png": return "image/png" case ".ttf": return "application/x-font-ttf" case ".woff": return "application/x-font-woff" default: return mime.TypeByExtension(ext) } }
cmd/syncthing/gui.go
1
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.033672939985990524, 0.0010464275255799294, 0.00016371349920518696, 0.0001718024432193488, 0.00400162348523736 ]
{ "id": 6, "code_window": [ "func (f FileInfoTruncated) String() string {\n", "\treturn fmt.Sprintf(\"File{Name:%q, Flags:0%o, Modified:%d, Version:%d, Size:%d, NumBlocks:%d}\",\n", "\t\tf.Name, f.Flags, f.Modified, f.Version, f.Size(), f.NumBlocks)\n", "}\n", "\n", "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func BlocksToSize(num uint32) int64 {\n", "\tif num < 2 {\n", "\t\treturn BlockSize / 2\n", "\t}\n", "\treturn int64(num-1)*BlockSize + BlockSize/2\n", "}\n", "\n" ], "file_path": "internal/protocol/message.go", "type": "add", "edit_start_line_idx": 83 }
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. package blowfish // The code is a port of Bruce Schneier's C implementation. // See http://www.schneier.com/blowfish.html. import "strconv" // The Blowfish block size in bytes. const BlockSize = 8 // A Cipher is an instance of Blowfish encryption using a particular key. type Cipher struct { p [18]uint32 s0, s1, s2, s3 [256]uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a Cipher. // The key argument should be the Blowfish key, from 1 to 56 bytes. func NewCipher(key []byte) (*Cipher, error) { var result Cipher if k := len(key); k < 1 || k > 56 { return nil, KeySizeError(k) } initCipher(&result) ExpandKey(key, &result) return &result, nil } // NewSaltedCipher creates a returns a Cipher that folds a salt into its key // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is // sufficient and desirable. For bcrypt compatiblity, the key can be over 56 // bytes. func NewSaltedCipher(key, salt []byte) (*Cipher, error) { if len(salt) == 0 { return NewCipher(key) } var result Cipher if k := len(key); k < 1 { return nil, KeySizeError(k) } initCipher(&result) expandKeyWithSalt(key, salt, &result) return &result, nil } // BlockSize returns the Blowfish block size, 8 bytes. // It is necessary to satisfy the Block interface in the // package "crypto/cipher". func (c *Cipher) BlockSize() int { return BlockSize } // Encrypt encrypts the 8-byte buffer src using the key k // and stores the result in dst. // Note that for amounts of data larger than a block, // it is not safe to just call Encrypt on successive blocks; // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). func (c *Cipher) Encrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = encryptBlock(l, r, c) dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) } // Decrypt decrypts the 8-byte buffer src using the key k // and stores the result in dst. func (c *Cipher) Decrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = decryptBlock(l, r, c) dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) } func initCipher(c *Cipher) { copy(c.p[0:], p[0:]) copy(c.s0[0:], s0[0:]) copy(c.s1[0:], s1[0:]) copy(c.s2[0:], s2[0:]) copy(c.s3[0:], s3[0:]) }
Godeps/_workspace/src/code.google.com/p/go.crypto/blowfish/cipher.go
0
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.0019772611558437347, 0.0005275063449516892, 0.00016560839139856398, 0.00017532431229483336, 0.0007034838781692088 ]
{ "id": 6, "code_window": [ "func (f FileInfoTruncated) String() string {\n", "\treturn fmt.Sprintf(\"File{Name:%q, Flags:0%o, Modified:%d, Version:%d, Size:%d, NumBlocks:%d}\",\n", "\t\tf.Name, f.Flags, f.Modified, f.Version, f.Size(), f.NumBlocks)\n", "}\n", "\n", "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func BlocksToSize(num uint32) int64 {\n", "\tif num < 2 {\n", "\t\treturn BlockSize / 2\n", "\t}\n", "\treturn int64(num-1)*BlockSize + BlockSize/2\n", "}\n", "\n" ], "file_path": "internal/protocol/message.go", "type": "add", "edit_start_line_idx": 83 }
// Copyright (c) 2012, Suryandaru Triandana <[email protected]> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package table import ( "encoding/binary" "errors" "fmt" "io" "github.com/syndtr/gosnappy/snappy" "github.com/syndtr/goleveldb/leveldb/comparer" "github.com/syndtr/goleveldb/leveldb/filter" "github.com/syndtr/goleveldb/leveldb/opt" "github.com/syndtr/goleveldb/leveldb/util" ) func sharedPrefixLen(a, b []byte) int { i, n := 0, len(a) if n > len(b) { n = len(b) } for i < n && a[i] == b[i] { i++ } return i } type blockWriter struct { restartInterval int buf util.Buffer nEntries int prevKey []byte restarts []uint32 scratch []byte } func (w *blockWriter) append(key, value []byte) { nShared := 0 if w.nEntries%w.restartInterval == 0 { w.restarts = append(w.restarts, uint32(w.buf.Len())) } else { nShared = sharedPrefixLen(w.prevKey, key) } n := binary.PutUvarint(w.scratch[0:], uint64(nShared)) n += binary.PutUvarint(w.scratch[n:], uint64(len(key)-nShared)) n += binary.PutUvarint(w.scratch[n:], uint64(len(value))) w.buf.Write(w.scratch[:n]) w.buf.Write(key[nShared:]) w.buf.Write(value) w.prevKey = append(w.prevKey[:0], key...) w.nEntries++ } func (w *blockWriter) finish() { // Write restarts entry. if w.nEntries == 0 { // Must have at least one restart entry. w.restarts = append(w.restarts, 0) } w.restarts = append(w.restarts, uint32(len(w.restarts))) for _, x := range w.restarts { buf4 := w.buf.Alloc(4) binary.LittleEndian.PutUint32(buf4, x) } } func (w *blockWriter) reset() { w.buf.Reset() w.nEntries = 0 w.restarts = w.restarts[:0] } func (w *blockWriter) bytesLen() int { restartsLen := len(w.restarts) if restartsLen == 0 { restartsLen = 1 } return w.buf.Len() + 4*restartsLen + 4 } type filterWriter struct { generator filter.FilterGenerator buf util.Buffer nKeys int offsets []uint32 } func (w *filterWriter) add(key []byte) { if w.generator == nil { return } w.generator.Add(key) w.nKeys++ } func (w *filterWriter) flush(offset uint64) { if w.generator == nil { return } for x := int(offset / filterBase); x > len(w.offsets); { w.generate() } } func (w *filterWriter) finish() { if w.generator == nil { return } // Generate last keys. if w.nKeys > 0 { w.generate() } w.offsets = append(w.offsets, uint32(w.buf.Len())) for _, x := range w.offsets { buf4 := w.buf.Alloc(4) binary.LittleEndian.PutUint32(buf4, x) } w.buf.WriteByte(filterBaseLg) } func (w *filterWriter) generate() { // Record offset. w.offsets = append(w.offsets, uint32(w.buf.Len())) // Generate filters. if w.nKeys > 0 { w.generator.Generate(&w.buf) w.nKeys = 0 } } // Writer is a table writer. type Writer struct { writer io.Writer err error // Options cmp comparer.Comparer filter filter.Filter compression opt.Compression blockSize int dataBlock blockWriter indexBlock blockWriter filterBlock filterWriter pendingBH blockHandle offset uint64 nEntries int // Scratch allocated enough for 5 uvarint. Block writer should not use // first 20-bytes since it will be used to encode block handle, which // then passed to the block writer itself. scratch [50]byte comparerScratch []byte compressionScratch []byte } func (w *Writer) writeBlock(buf *util.Buffer, compression opt.Compression) (bh blockHandle, err error) { // Compress the buffer if necessary. var b []byte if compression == opt.SnappyCompression { // Allocate scratch enough for compression and block trailer. if n := snappy.MaxEncodedLen(buf.Len()) + blockTrailerLen; len(w.compressionScratch) < n { w.compressionScratch = make([]byte, n) } var compressed []byte compressed, err = snappy.Encode(w.compressionScratch, buf.Bytes()) if err != nil { return } n := len(compressed) b = compressed[:n+blockTrailerLen] b[n] = blockTypeSnappyCompression } else { tmp := buf.Alloc(blockTrailerLen) tmp[0] = blockTypeNoCompression b = buf.Bytes() } // Calculate the checksum. n := len(b) - 4 checksum := util.NewCRC(b[:n]).Value() binary.LittleEndian.PutUint32(b[n:], checksum) // Write the buffer to the file. _, err = w.writer.Write(b) if err != nil { return } bh = blockHandle{w.offset, uint64(len(b) - blockTrailerLen)} w.offset += uint64(len(b)) return } func (w *Writer) flushPendingBH(key []byte) { if w.pendingBH.length == 0 { return } var separator []byte if len(key) == 0 { separator = w.cmp.Successor(w.comparerScratch[:0], w.dataBlock.prevKey) } else { separator = w.cmp.Separator(w.comparerScratch[:0], w.dataBlock.prevKey, key) } if separator == nil { separator = w.dataBlock.prevKey } else { w.comparerScratch = separator } n := encodeBlockHandle(w.scratch[:20], w.pendingBH) // Append the block handle to the index block. w.indexBlock.append(separator, w.scratch[:n]) // Reset prev key of the data block. w.dataBlock.prevKey = w.dataBlock.prevKey[:0] // Clear pending block handle. w.pendingBH = blockHandle{} } func (w *Writer) finishBlock() error { w.dataBlock.finish() bh, err := w.writeBlock(&w.dataBlock.buf, w.compression) if err != nil { return err } w.pendingBH = bh // Reset the data block. w.dataBlock.reset() // Flush the filter block. w.filterBlock.flush(w.offset) return nil } // Append appends key/value pair to the table. The keys passed must // be in increasing order. // // It is safe to modify the contents of the arguments after Append returns. func (w *Writer) Append(key, value []byte) error { if w.err != nil { return w.err } if w.nEntries > 0 && w.cmp.Compare(w.dataBlock.prevKey, key) >= 0 { w.err = fmt.Errorf("leveldb/table: Writer: keys are not in increasing order: %q, %q", w.dataBlock.prevKey, key) return w.err } w.flushPendingBH(key) // Append key/value pair to the data block. w.dataBlock.append(key, value) // Add key to the filter block. w.filterBlock.add(key) // Finish the data block if block size target reached. if w.dataBlock.bytesLen() >= w.blockSize { if err := w.finishBlock(); err != nil { w.err = err return w.err } } w.nEntries++ return nil } // BlocksLen returns number of blocks written so far. func (w *Writer) BlocksLen() int { n := w.indexBlock.nEntries if w.pendingBH.length > 0 { // Includes the pending block. n++ } return n } // EntriesLen returns number of entries added so far. func (w *Writer) EntriesLen() int { return w.nEntries } // BytesLen returns number of bytes written so far. func (w *Writer) BytesLen() int { return int(w.offset) } // Close will finalize the table. Calling Append is not possible // after Close, but calling BlocksLen, EntriesLen and BytesLen // is still possible. func (w *Writer) Close() error { if w.err != nil { return w.err } // Write the last data block. Or empty data block if there // aren't any data blocks at all. if w.dataBlock.nEntries > 0 || w.nEntries == 0 { if err := w.finishBlock(); err != nil { w.err = err return w.err } } w.flushPendingBH(nil) // Write the filter block. var filterBH blockHandle w.filterBlock.finish() if buf := &w.filterBlock.buf; buf.Len() > 0 { filterBH, w.err = w.writeBlock(buf, opt.NoCompression) if w.err != nil { return w.err } } // Write the metaindex block. if filterBH.length > 0 { key := []byte("filter." + w.filter.Name()) n := encodeBlockHandle(w.scratch[:20], filterBH) w.dataBlock.append(key, w.scratch[:n]) } w.dataBlock.finish() metaindexBH, err := w.writeBlock(&w.dataBlock.buf, w.compression) if err != nil { w.err = err return w.err } // Write the index block. w.indexBlock.finish() indexBH, err := w.writeBlock(&w.indexBlock.buf, w.compression) if err != nil { w.err = err return w.err } // Write the table footer. footer := w.scratch[:footerLen] for i := range footer { footer[i] = 0 } n := encodeBlockHandle(footer, metaindexBH) encodeBlockHandle(footer[n:], indexBH) copy(footer[footerLen-len(magic):], magic) if _, err := w.writer.Write(footer); err != nil { w.err = err return w.err } w.offset += footerLen w.err = errors.New("leveldb/table: writer is closed") return nil } // NewWriter creates a new initialized table writer for the file. // // Table writer is not goroutine-safe. func NewWriter(f io.Writer, o *opt.Options) *Writer { w := &Writer{ writer: f, cmp: o.GetComparer(), filter: o.GetFilter(), compression: o.GetCompression(), blockSize: o.GetBlockSize(), comparerScratch: make([]byte, 0), } // data block w.dataBlock.restartInterval = o.GetBlockRestartInterval() // The first 20-bytes are used for encoding block handle. w.dataBlock.scratch = w.scratch[20:] // index block w.indexBlock.restartInterval = 1 w.indexBlock.scratch = w.scratch[20:] // filter block if w.filter != nil { w.filterBlock.generator = w.filter.NewGenerator() w.filterBlock.flush(0) } return w }
Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go
0
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.00542819919064641, 0.00042104063322767615, 0.0001632347994018346, 0.0001710229553282261, 0.0009119738242588937 ]
{ "id": 6, "code_window": [ "func (f FileInfoTruncated) String() string {\n", "\treturn fmt.Sprintf(\"File{Name:%q, Flags:0%o, Modified:%d, Version:%d, Size:%d, NumBlocks:%d}\",\n", "\t\tf.Name, f.Flags, f.Modified, f.Version, f.Size(), f.NumBlocks)\n", "}\n", "\n", "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func BlocksToSize(num uint32) int64 {\n", "\tif num < 2 {\n", "\t\treturn BlockSize / 2\n", "\t}\n", "\treturn int64(num-1)*BlockSize + BlockSize/2\n", "}\n", "\n" ], "file_path": "internal/protocol/message.go", "type": "add", "edit_start_line_idx": 83 }
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" > <svg xmlns="http://www.w3.org/2000/svg"> <metadata></metadata> <defs> <font id="glyphicons_halflingsregular" horiz-adv-x="1200" > <font-face units-per-em="1200" ascent="960" descent="-240" /> <missing-glyph horiz-adv-x="500" /> <glyph /> <glyph /> <glyph unicode="&#xd;" /> <glyph unicode=" " /> <glyph unicode="*" d="M100 500v200h259l-183 183l141 141l183 -183v259h200v-259l183 183l141 -141l-183 -183h259v-200h-259l183 -183l-141 -141l-183 183v-259h-200v259l-183 -183l-141 141l183 183h-259z" /> <glyph unicode="+" d="M0 400v300h400v400h300v-400h400v-300h-400v-400h-300v400h-400z" /> <glyph unicode="&#xa0;" /> <glyph unicode="&#x2000;" horiz-adv-x="652" /> <glyph unicode="&#x2001;" horiz-adv-x="1304" /> <glyph unicode="&#x2002;" horiz-adv-x="652" /> <glyph unicode="&#x2003;" horiz-adv-x="1304" /> <glyph unicode="&#x2004;" horiz-adv-x="434" /> <glyph unicode="&#x2005;" horiz-adv-x="326" /> <glyph unicode="&#x2006;" horiz-adv-x="217" /> <glyph unicode="&#x2007;" horiz-adv-x="217" /> <glyph unicode="&#x2008;" horiz-adv-x="163" /> <glyph unicode="&#x2009;" horiz-adv-x="260" /> <glyph unicode="&#x200a;" horiz-adv-x="72" /> <glyph unicode="&#x202f;" horiz-adv-x="260" /> <glyph unicode="&#x205f;" horiz-adv-x="326" /> <glyph unicode="&#x20ac;" d="M100 500l100 100h113q0 47 5 100h-218l100 100h135q37 167 112 257q117 141 297 141q242 0 354 -189q60 -103 66 -209h-181q0 55 -25.5 99t-63.5 68t-75 36.5t-67 12.5q-24 0 -52.5 -10t-62.5 -32t-65.5 -67t-50.5 -107h379l-100 -100h-300q-6 -46 -6 -100h406l-100 -100 h-300q9 -74 33 -132t52.5 -91t62 -54.5t59 -29t46.5 -7.5q29 0 66 13t75 37t63.5 67.5t25.5 96.5h174q-31 -172 -128 -278q-107 -117 -274 -117q-205 0 -324 158q-36 46 -69 131.5t-45 205.5h-217z" /> <glyph unicode="&#x2212;" d="M200 400h900v300h-900v-300z" /> <glyph unicode="&#x2601;" d="M-14 494q0 -80 56.5 -137t135.5 -57h750q120 0 205 86t85 208q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5z" /> <glyph unicode="&#x2709;" d="M0 100l400 400l200 -200l200 200l400 -400h-1200zM0 300v600l300 -300zM0 1100l600 -603l600 603h-1200zM900 600l300 300v-600z" /> <glyph unicode="&#x270f;" d="M-13 -13l333 112l-223 223zM187 403l214 -214l614 614l-214 214zM887 1103l214 -214l99 92q13 13 13 32.5t-13 33.5l-153 153q-15 13 -33 13t-33 -13z" /> <glyph unicode="&#xe000;" horiz-adv-x="500" d="M0 0z" /> <glyph unicode="&#xe001;" d="M0 1200h1200l-500 -550v-550h300v-100h-800v100h300v550z" /> <glyph unicode="&#xe002;" d="M14 84q18 -55 86 -75.5t147 5.5q65 21 109 69t44 90v606l600 155v-521q-64 16 -138 -7q-79 -26 -122.5 -83t-25.5 -111q17 -55 85.5 -75.5t147.5 4.5q70 23 111.5 63.5t41.5 95.5v881q0 10 -7 15.5t-17 2.5l-752 -193q-10 -3 -17 -12.5t-7 -19.5v-689q-64 17 -138 -7 q-79 -25 -122.5 -82t-25.5 -112z" /> <glyph unicode="&#xe003;" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233z" /> <glyph unicode="&#xe005;" d="M100 784q0 64 28 123t73 100.5t104.5 64t119 20.5t120 -38.5t104.5 -104.5q48 69 109.5 105t121.5 38t118.5 -20.5t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-149.5 152.5t-126.5 127.5 t-94 124.5t-33.5 117.5z" /> <glyph unicode="&#xe006;" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1z" /> <glyph unicode="&#xe007;" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1zM237 700l196 -142l-73 -226l192 140l195 -141l-74 229l193 140h-235l-77 211l-78 -211h-239z" /> <glyph unicode="&#xe008;" d="M0 0v143l400 257v100q-37 0 -68.5 74.5t-31.5 125.5v200q0 124 88 212t212 88t212 -88t88 -212v-200q0 -51 -31.5 -125.5t-68.5 -74.5v-100l400 -257v-143h-1200z" /> <glyph unicode="&#xe009;" d="M0 0v1100h1200v-1100h-1200zM100 100h100v100h-100v-100zM100 300h100v100h-100v-100zM100 500h100v100h-100v-100zM100 700h100v100h-100v-100zM100 900h100v100h-100v-100zM300 100h600v400h-600v-400zM300 600h600v400h-600v-400zM1000 100h100v100h-100v-100z M1000 300h100v100h-100v-100zM1000 500h100v100h-100v-100zM1000 700h100v100h-100v-100zM1000 900h100v100h-100v-100z" /> <glyph unicode="&#xe010;" d="M0 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM0 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5zM600 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM600 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400 q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5z" /> <glyph unicode="&#xe011;" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200 q-21 0 -35.5 14.5t-14.5 35.5zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 450v200q0 21 14.5 35.5t35.5 14.5h200 q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5z" /> <glyph unicode="&#xe012;" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v200q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5 t-14.5 -35.5v-200zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5z" /> <glyph unicode="&#xe013;" d="M29 454l419 -420l818 820l-212 212l-607 -607l-206 207z" /> <glyph unicode="&#xe014;" d="M106 318l282 282l-282 282l212 212l282 -282l282 282l212 -212l-282 -282l282 -282l-212 -212l-282 282l-282 -282z" /> <glyph unicode="&#xe015;" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233zM300 600v200h100v100h200v-100h100v-200h-100v-100h-200v100h-100z" /> <glyph unicode="&#xe016;" d="M23 694q0 200 142 342t342 142t342 -142t142 -342q0 -141 -78 -262l300 -299q7 -7 7 -18t-7 -18l-109 -109q-8 -8 -18 -8t-18 8l-300 299q-120 -77 -261 -77q-200 0 -342 142t-142 342zM176 694q0 -136 97 -233t234 -97t233.5 97t96.5 233t-96.5 233t-233.5 97t-234 -97 t-97 -233zM300 601h400v200h-400v-200z" /> <glyph unicode="&#xe017;" d="M23 600q0 183 105 331t272 210v-166q-103 -55 -165 -155t-62 -220q0 -177 125 -302t302 -125t302 125t125 302q0 120 -62 220t-165 155v166q167 -62 272 -210t105 -331q0 -118 -45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5 zM500 750q0 -21 14.5 -35.5t35.5 -14.5h100q21 0 35.5 14.5t14.5 35.5v400q0 21 -14.5 35.5t-35.5 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-400z" /> <glyph unicode="&#xe018;" d="M100 1h200v300h-200v-300zM400 1v500h200v-500h-200zM700 1v800h200v-800h-200zM1000 1v1200h200v-1200h-200z" /> <glyph unicode="&#xe019;" d="M26 601q0 -33 6 -74l151 -38l2 -6q14 -49 38 -93l3 -5l-80 -134q45 -59 105 -105l133 81l5 -3q45 -26 94 -39l5 -2l38 -151q40 -5 74 -5q27 0 74 5l38 151l6 2q46 13 93 39l5 3l134 -81q56 44 104 105l-80 134l3 5q24 44 39 93l1 6l152 38q5 40 5 74q0 28 -5 73l-152 38 l-1 6q-16 51 -39 93l-3 5l80 134q-44 58 -104 105l-134 -81l-5 3q-45 25 -93 39l-6 1l-38 152q-40 5 -74 5q-27 0 -74 -5l-38 -152l-5 -1q-50 -14 -94 -39l-5 -3l-133 81q-59 -47 -105 -105l80 -134l-3 -5q-25 -47 -38 -93l-2 -6l-151 -38q-6 -48 -6 -73zM385 601 q0 88 63 151t152 63t152 -63t63 -151q0 -89 -63 -152t-152 -63t-152 63t-63 152z" /> <glyph unicode="&#xe020;" d="M100 1025v50q0 10 7.5 17.5t17.5 7.5h275v100q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5v-100h275q10 0 17.5 -7.5t7.5 -17.5v-50q0 -11 -7 -18t-18 -7h-1050q-11 0 -18 7t-7 18zM200 100v800h900v-800q0 -41 -29.5 -71t-70.5 -30h-700q-41 0 -70.5 30 t-29.5 71zM300 100h100v700h-100v-700zM500 100h100v700h-100v-700zM500 1100h300v100h-300v-100zM700 100h100v700h-100v-700zM900 100h100v700h-100v-700z" /> <glyph unicode="&#xe021;" d="M1 601l656 644l644 -644h-200v-600h-300v400h-300v-400h-300v600h-200z" /> <glyph unicode="&#xe022;" d="M100 25v1150q0 11 7 18t18 7h475v-500h400v-675q0 -11 -7 -18t-18 -7h-850q-11 0 -18 7t-7 18zM700 800v300l300 -300h-300z" /> <glyph unicode="&#xe023;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 500v400h100 v-300h200v-100h-300z" /> <glyph unicode="&#xe024;" d="M-100 0l431 1200h209l-21 -300h162l-20 300h208l431 -1200h-538l-41 400h-242l-40 -400h-539zM488 500h224l-27 300h-170z" /> <glyph unicode="&#xe025;" d="M0 0v400h490l-290 300h200v500h300v-500h200l-290 -300h490v-400h-1100zM813 200h175v100h-175v-100z" /> <glyph unicode="&#xe026;" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM188 600q0 -170 121 -291t291 -121t291 121t121 291t-121 291t-291 121 t-291 -121t-121 -291zM350 600h150v300h200v-300h150l-250 -300z" /> <glyph unicode="&#xe027;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM350 600l250 300 l250 -300h-150v-300h-200v300h-150z" /> <glyph unicode="&#xe028;" d="M0 25v475l200 700h800q199 -700 200 -700v-475q0 -11 -7 -18t-18 -7h-1150q-11 0 -18 7t-7 18zM200 500h200l50 -200h300l50 200h200l-97 500h-606z" /> <glyph unicode="&#xe029;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 397v401 l297 -200z" /> <glyph unicode="&#xe030;" d="M23 600q0 -118 45.5 -224.5t123 -184t184 -123t224.5 -45.5t224.5 45.5t184 123t123 184t45.5 224.5h-150q0 -177 -125 -302t-302 -125t-302 125t-125 302t125 302t302 125q136 0 246 -81l-146 -146h400v400l-145 -145q-157 122 -355 122q-118 0 -224.5 -45.5t-184 -123 t-123 -184t-45.5 -224.5z" /> <glyph unicode="&#xe031;" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5q198 0 355 -122l145 145v-400h-400l147 147q-112 80 -247 80q-177 0 -302 -125t-125 -302h-150zM100 0v400h400l-147 -147q112 -80 247 -80q177 0 302 125t125 302h150q0 -118 -45.5 -224.5t-123 -184t-184 -123 t-224.5 -45.5q-198 0 -355 122z" /> <glyph unicode="&#xe032;" d="M100 0h1100v1200h-1100v-1200zM200 100v900h900v-900h-900zM300 200v100h100v-100h-100zM300 400v100h100v-100h-100zM300 600v100h100v-100h-100zM300 800v100h100v-100h-100zM500 200h500v100h-500v-100zM500 400v100h500v-100h-500zM500 600v100h500v-100h-500z M500 800v100h500v-100h-500z" /> <glyph unicode="&#xe033;" d="M0 100v600q0 41 29.5 70.5t70.5 29.5h100v200q0 82 59 141t141 59h300q82 0 141 -59t59 -141v-200h100q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-900q-41 0 -70.5 29.5t-29.5 70.5zM400 800h300v150q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-150z" /> <glyph unicode="&#xe034;" d="M100 0v1100h100v-1100h-100zM300 400q60 60 127.5 84t127.5 17.5t122 -23t119 -30t110 -11t103 42t91 120.5v500q-40 -81 -101.5 -115.5t-127.5 -29.5t-138 25t-139.5 40t-125.5 25t-103 -29.5t-65 -115.5v-500z" /> <glyph unicode="&#xe035;" d="M0 275q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 127 70.5 231.5t184.5 161.5t245 57t245 -57t184.5 -161.5t70.5 -231.5v-300q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 116 -49.5 227t-131 192.5t-192.5 131t-227 49.5t-227 -49.5t-192.5 -131t-131 -192.5 t-49.5 -227v-300zM200 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14zM800 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14z" /> <glyph unicode="&#xe036;" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM688 459l141 141l-141 141l71 71l141 -141l141 141l71 -71l-141 -141l141 -141l-71 -71l-141 141l-141 -141z" /> <glyph unicode="&#xe037;" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM700 857l69 53q111 -135 111 -310q0 -169 -106 -302l-67 54q86 110 86 248q0 146 -93 257z" /> <glyph unicode="&#xe038;" d="M0 401v400h300l300 200v-800l-300 200h-300zM702 858l69 53q111 -135 111 -310q0 -170 -106 -303l-67 55q86 110 86 248q0 145 -93 257zM889 951l7 -8q123 -151 123 -344q0 -189 -119 -339l-7 -8l81 -66l6 8q142 178 142 405q0 230 -144 408l-6 8z" /> <glyph unicode="&#xe039;" d="M0 0h500v500h-200v100h-100v-100h-200v-500zM0 600h100v100h400v100h100v100h-100v300h-500v-600zM100 100v300h300v-300h-300zM100 800v300h300v-300h-300zM200 200v100h100v-100h-100zM200 900h100v100h-100v-100zM500 500v100h300v-300h200v-100h-100v-100h-200v100 h-100v100h100v200h-200zM600 0v100h100v-100h-100zM600 1000h100v-300h200v-300h300v200h-200v100h200v500h-600v-200zM800 800v300h300v-300h-300zM900 0v100h300v-100h-300zM900 900v100h100v-100h-100zM1100 200v100h100v-100h-100z" /> <glyph unicode="&#xe040;" d="M0 200h100v1000h-100v-1000zM100 0v100h300v-100h-300zM200 200v1000h100v-1000h-100zM500 0v91h100v-91h-100zM500 200v1000h200v-1000h-200zM700 0v91h100v-91h-100zM800 200v1000h100v-1000h-100zM900 0v91h200v-91h-200zM1000 200v1000h200v-1000h-200z" /> <glyph unicode="&#xe041;" d="M1 700v475q0 10 7.5 17.5t17.5 7.5h474l700 -700l-500 -500zM148 953q0 -42 29 -71q30 -30 71.5 -30t71.5 30q29 29 29 71t-29 71q-30 30 -71.5 30t-71.5 -30q-29 -29 -29 -71z" /> <glyph unicode="&#xe042;" d="M2 700v475q0 11 7 18t18 7h474l700 -700l-500 -500zM148 953q0 -42 30 -71q29 -30 71 -30t71 30q30 29 30 71t-30 71q-29 30 -71 30t-71 -30q-30 -29 -30 -71zM701 1200h100l700 -700l-500 -500l-50 50l450 450z" /> <glyph unicode="&#xe043;" d="M100 0v1025l175 175h925v-1000l-100 -100v1000h-750l-100 -100h750v-1000h-900z" /> <glyph unicode="&#xe044;" d="M200 0l450 444l450 -443v1150q0 20 -14.5 35t-35.5 15h-800q-21 0 -35.5 -15t-14.5 -35v-1151z" /> <glyph unicode="&#xe045;" d="M0 100v700h200l100 -200h600l100 200h200v-700h-200v200h-800v-200h-200zM253 829l40 -124h592l62 124l-94 346q-2 11 -10 18t-18 7h-450q-10 0 -18 -7t-10 -18zM281 24l38 152q2 10 11.5 17t19.5 7h500q10 0 19.5 -7t11.5 -17l38 -152q2 -10 -3.5 -17t-15.5 -7h-600 q-10 0 -15.5 7t-3.5 17z" /> <glyph unicode="&#xe046;" d="M0 200q0 -41 29.5 -70.5t70.5 -29.5h1000q41 0 70.5 29.5t29.5 70.5v600q0 41 -29.5 70.5t-70.5 29.5h-150q-4 8 -11.5 21.5t-33 48t-53 61t-69 48t-83.5 21.5h-200q-41 0 -82 -20.5t-70 -50t-52 -59t-34 -50.5l-12 -20h-150q-41 0 -70.5 -29.5t-29.5 -70.5v-600z M356 500q0 100 72 172t172 72t172 -72t72 -172t-72 -172t-172 -72t-172 72t-72 172zM494 500q0 -44 31 -75t75 -31t75 31t31 75t-31 75t-75 31t-75 -31t-31 -75zM900 700v100h100v-100h-100z" /> <glyph unicode="&#xe047;" d="M53 0h365v66q-41 0 -72 11t-49 38t1 71l92 234h391l82 -222q16 -45 -5.5 -88.5t-74.5 -43.5v-66h417v66q-34 1 -74 43q-18 19 -33 42t-21 37l-6 13l-385 998h-93l-399 -1006q-24 -48 -52 -75q-12 -12 -33 -25t-36 -20l-15 -7v-66zM416 521l178 457l46 -140l116 -317h-340 z" /> <glyph unicode="&#xe048;" d="M100 0v89q41 7 70.5 32.5t29.5 65.5v827q0 28 -1 39.5t-5.5 26t-15.5 21t-29 14t-49 14.5v70h471q120 0 213 -88t93 -228q0 -55 -11.5 -101.5t-28 -74t-33.5 -47.5t-28 -28l-12 -7q8 -3 21.5 -9t48 -31.5t60.5 -58t47.5 -91.5t21.5 -129q0 -84 -59 -156.5t-142 -111 t-162 -38.5h-500zM400 200h161q89 0 153 48.5t64 132.5q0 90 -62.5 154.5t-156.5 64.5h-159v-400zM400 700h139q76 0 130 61.5t54 138.5q0 82 -84 130.5t-239 48.5v-379z" /> <glyph unicode="&#xe049;" d="M200 0v57q77 7 134.5 40.5t65.5 80.5l173 849q10 56 -10 74t-91 37q-6 1 -10.5 2.5t-9.5 2.5v57h425l2 -57q-33 -8 -62 -25.5t-46 -37t-29.5 -38t-17.5 -30.5l-5 -12l-128 -825q-10 -52 14 -82t95 -36v-57h-500z" /> <glyph unicode="&#xe050;" d="M-75 200h75v800h-75l125 167l125 -167h-75v-800h75l-125 -167zM300 900v300h150h700h150v-300h-50q0 29 -8 48.5t-18.5 30t-33.5 15t-39.5 5.5t-50.5 1h-200v-850l100 -50v-100h-400v100l100 50v850h-200q-34 0 -50.5 -1t-40 -5.5t-33.5 -15t-18.5 -30t-8.5 -48.5h-49z " /> <glyph unicode="&#xe051;" d="M33 51l167 125v-75h800v75l167 -125l-167 -125v75h-800v-75zM100 901v300h150h700h150v-300h-50q0 29 -8 48.5t-18 30t-33.5 15t-40 5.5t-50.5 1h-200v-650l100 -50v-100h-400v100l100 50v650h-200q-34 0 -50.5 -1t-39.5 -5.5t-33.5 -15t-18.5 -30t-8 -48.5h-50z" /> <glyph unicode="&#xe052;" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 350q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM0 650q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1000q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 950q0 -20 14.5 -35t35.5 -15h600q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-600q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" /> <glyph unicode="&#xe053;" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 650q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM200 350q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM200 950q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" /> <glyph unicode="&#xe054;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM100 650v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1000q-21 0 -35.5 15 t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM500 950v100q0 21 14.5 35.5t35.5 14.5h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-600 q-21 0 -35.5 15t-14.5 35z" /> <glyph unicode="&#xe055;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100 q-21 0 -35.5 15t-14.5 35z" /> <glyph unicode="&#xe056;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM300 50v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800 q-21 0 -35.5 15t-14.5 35zM300 650v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 950v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15 h-800q-21 0 -35.5 15t-14.5 35z" /> <glyph unicode="&#xe057;" d="M-101 500v100h201v75l166 -125l-166 -125v75h-201zM300 0h100v1100h-100v-1100zM500 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35 v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 650q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100 q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100z" /> <glyph unicode="&#xe058;" d="M1 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 650 q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM801 0v1100h100v-1100 h-100zM934 550l167 -125v75h200v100h-200v75z" /> <glyph unicode="&#xe059;" d="M0 275v650q0 31 22 53t53 22h750q31 0 53 -22t22 -53v-650q0 -31 -22 -53t-53 -22h-750q-31 0 -53 22t-22 53zM900 600l300 300v-600z" /> <glyph unicode="&#xe060;" d="M0 44v1012q0 18 13 31t31 13h1112q19 0 31.5 -13t12.5 -31v-1012q0 -18 -12.5 -31t-31.5 -13h-1112q-18 0 -31 13t-13 31zM100 263l247 182l298 -131l-74 156l293 318l236 -288v500h-1000v-737zM208 750q0 56 39 95t95 39t95 -39t39 -95t-39 -95t-95 -39t-95 39t-39 95z " /> <glyph unicode="&#xe062;" d="M148 745q0 124 60.5 231.5t165 172t226.5 64.5q123 0 227 -63t164.5 -169.5t60.5 -229.5t-73 -272q-73 -114 -166.5 -237t-150.5 -189l-57 -66q-10 9 -27 26t-66.5 70.5t-96 109t-104 135.5t-100.5 155q-63 139 -63 262zM342 772q0 -107 75.5 -182.5t181.5 -75.5 q107 0 182.5 75.5t75.5 182.5t-75.5 182t-182.5 75t-182 -75.5t-75 -181.5z" /> <glyph unicode="&#xe063;" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM173 600q0 -177 125.5 -302t301.5 -125v854q-176 0 -301.5 -125 t-125.5 -302z" /> <glyph unicode="&#xe064;" d="M117 406q0 94 34 186t88.5 172.5t112 159t115 177t87.5 194.5q21 -71 57.5 -142.5t76 -130.5t83 -118.5t82 -117t70 -116t50 -125.5t18.5 -136q0 -89 -39 -165.5t-102 -126.5t-140 -79.5t-156 -33.5q-114 6 -211.5 53t-161.5 138.5t-64 210.5zM243 414q14 -82 59.5 -136 t136.5 -80l16 98q-7 6 -18 17t-34 48t-33 77q-15 73 -14 143.5t10 122.5l9 51q-92 -110 -119.5 -185t-12.5 -156z" /> <glyph unicode="&#xe065;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5q366 -6 397 -14l-186 -186h-311q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v125l200 200v-225q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM436 341l161 50l412 412l-114 113l-405 -405zM995 1015l113 -113l113 113l-21 85l-92 28z" /> <glyph unicode="&#xe066;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h261l2 -80q-133 -32 -218 -120h-145q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5l200 153v-53q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5 zM423 524q30 38 81.5 64t103 35.5t99 14t77.5 3.5l29 -1v-209l360 324l-359 318v-216q-7 0 -19 -1t-48 -8t-69.5 -18.5t-76.5 -37t-76.5 -59t-62 -88t-39.5 -121.5z" /> <glyph unicode="&#xe067;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q60 0 127 -23l-178 -177h-349q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v69l200 200v-169q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM342 632l283 -284l566 567l-136 137l-430 -431l-147 147z" /> <glyph unicode="&#xe068;" d="M0 603l300 296v-198h200v200h-200l300 300l295 -300h-195v-200h200v198l300 -296l-300 -300v198h-200v-200h195l-295 -300l-300 300h200v200h-200v-198z" /> <glyph unicode="&#xe069;" d="M200 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-1100l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" /> <glyph unicode="&#xe070;" d="M0 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-487l500 487v-1100l-500 488v-488l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" /> <glyph unicode="&#xe071;" d="M136 550l564 550v-487l500 487v-1100l-500 488v-488z" /> <glyph unicode="&#xe072;" d="M200 0l900 550l-900 550v-1100z" /> <glyph unicode="&#xe073;" d="M200 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-800zM600 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" /> <glyph unicode="&#xe074;" d="M200 150q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v800q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" /> <glyph unicode="&#xe075;" d="M0 0v1100l500 -487v487l564 -550l-564 -550v488z" /> <glyph unicode="&#xe076;" d="M0 0v1100l500 -487v487l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-500 -488v488z" /> <glyph unicode="&#xe077;" d="M300 0v1100l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438z" /> <glyph unicode="&#xe078;" d="M100 250v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5zM100 500h1100l-550 564z" /> <glyph unicode="&#xe079;" d="M185 599l592 -592l240 240l-353 353l353 353l-240 240z" /> <glyph unicode="&#xe080;" d="M272 194l353 353l-353 353l241 240l572 -571l21 -22l-1 -1v-1l-592 -591z" /> <glyph unicode="&#xe081;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -300t-217.5 -218t-299.5 -80t-299.5 80t-217.5 218t-80 300zM300 500h200v-200h200v200h200v200h-200v200h-200v-200h-200v-200z" /> <glyph unicode="&#xe082;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -300t-217.5 -218t-299.5 -80t-299.5 80t-217.5 218t-80 300zM300 500h600v200h-600v-200z" /> <glyph unicode="&#xe083;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -300t-217.5 -218t-299.5 -80t-299.5 80t-217.5 218t-80 300zM246 459l213 -213l141 142l141 -142l213 213l-142 141l142 141l-213 212l-141 -141l-141 142l-212 -213l141 -141z" /> <glyph unicode="&#xe084;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM270 551l276 -277l411 411l-175 174l-236 -236l-102 102z" /> <glyph unicode="&#xe085;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -300t-217.5 -218t-299.5 -80t-299.5 80t-217.5 218t-80 300zM363 700h144q4 0 11.5 -1t11 -1t6.5 3t3 9t1 11t3.5 8.5t3.5 6t5.5 4t6.5 2.5t9 1.5t9 0.5h11.5h12.5q19 0 30 -10t11 -26 q0 -22 -4 -28t-27 -22q-5 -1 -12.5 -3t-27 -13.5t-34 -27t-26.5 -46t-11 -68.5h200q5 3 14 8t31.5 25.5t39.5 45.5t31 69t14 94q0 51 -17.5 89t-42 58t-58.5 32t-58.5 15t-51.5 3q-105 0 -172 -56t-67 -183zM500 300h200v100h-200v-100z" /> <glyph unicode="&#xe086;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -300t-217.5 -218t-299.5 -80t-299.5 80t-217.5 218t-80 300zM400 300h400v100h-100v300h-300v-100h100v-200h-100v-100zM500 800h200v100h-200v-100z" /> <glyph unicode="&#xe087;" d="M0 500v200h194q15 60 36 104.5t55.5 86t88 69t126.5 40.5v200h200v-200q54 -20 113 -60t112.5 -105.5t71.5 -134.5h203v-200h-203q-25 -102 -116.5 -186t-180.5 -117v-197h-200v197q-140 27 -208 102.5t-98 200.5h-194zM290 500q24 -73 79.5 -127.5t130.5 -78.5v206h200 v-206q149 48 201 206h-201v200h200q-25 74 -76 127.5t-124 76.5v-204h-200v203q-75 -24 -130 -77.5t-79 -125.5h209v-200h-210z" /> <glyph unicode="&#xe088;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM356 465l135 135 l-135 135l109 109l135 -135l135 135l109 -109l-135 -135l135 -135l-109 -109l-135 135l-135 -135z" /> <glyph unicode="&#xe089;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM322 537l141 141 l87 -87l204 205l142 -142l-346 -345z" /> <glyph unicode="&#xe090;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -115 62 -215l568 567q-100 62 -216 62q-171 0 -292.5 -121.5t-121.5 -292.5zM391 245q97 -59 209 -59q171 0 292.5 121.5t121.5 292.5 q0 112 -59 209z" /> <glyph unicode="&#xe091;" d="M0 547l600 453v-300h600v-300h-600v-301z" /> <glyph unicode="&#xe092;" d="M0 400v300h600v300l600 -453l-600 -448v301h-600z" /> <glyph unicode="&#xe093;" d="M204 600l450 600l444 -600h-298v-600h-300v600h-296z" /> <glyph unicode="&#xe094;" d="M104 600h296v600h300v-600h298l-449 -600z" /> <glyph unicode="&#xe095;" d="M0 200q6 132 41 238.5t103.5 193t184 138t271.5 59.5v271l600 -453l-600 -448v301q-95 -2 -183 -20t-170 -52t-147 -92.5t-100 -135.5z" /> <glyph unicode="&#xe096;" d="M0 0v400l129 -129l294 294l142 -142l-294 -294l129 -129h-400zM635 777l142 -142l294 294l129 -129v400h-400l129 -129z" /> <glyph unicode="&#xe097;" d="M34 176l295 295l-129 129h400v-400l-129 130l-295 -295zM600 600v400l129 -129l295 295l142 -141l-295 -295l129 -130h-400z" /> <glyph unicode="&#xe101;" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5t224.5 -45.5t184 -123t123 -184t45.5 -224.5t-45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5zM456 851l58 -302q4 -20 21.5 -34.5t37.5 -14.5h54q20 0 37.5 14.5 t21.5 34.5l58 302q4 20 -8 34.5t-33 14.5h-207q-20 0 -32 -14.5t-8 -34.5zM500 300h200v100h-200v-100z" /> <glyph unicode="&#xe102;" d="M0 800h100v-200h400v300h200v-300h400v200h100v100h-111v6t-1 15t-3 18l-34 172q-11 39 -41.5 63t-69.5 24q-32 0 -61 -17l-239 -144q-22 -13 -40 -35q-19 24 -40 36l-238 144q-33 18 -62 18q-39 0 -69.5 -23t-40.5 -61l-35 -177q-2 -8 -3 -18t-1 -15v-6h-111v-100z M100 0h400v400h-400v-400zM200 900q-3 0 14 48t35 96l18 47l214 -191h-281zM700 0v400h400v-400h-400zM731 900l202 197q5 -12 12 -32.5t23 -64t25 -72t7 -28.5h-269z" /> <glyph unicode="&#xe103;" d="M0 -22v143l216 193q-9 53 -13 83t-5.5 94t9 113t38.5 114t74 124q47 60 99.5 102.5t103 68t127.5 48t145.5 37.5t184.5 43.5t220 58.5q0 -189 -22 -343t-59 -258t-89 -181.5t-108.5 -120t-122 -68t-125.5 -30t-121.5 -1.5t-107.5 12.5t-87.5 17t-56.5 7.5l-99 -55z M238.5 300.5q19.5 -6.5 86.5 76.5q55 66 367 234q70 38 118.5 69.5t102 79t99 111.5t86.5 148q22 50 24 60t-6 19q-7 5 -17 5t-26.5 -14.5t-33.5 -39.5q-35 -51 -113.5 -108.5t-139.5 -89.5l-61 -32q-369 -197 -458 -401q-48 -111 -28.5 -117.5z" /> <glyph unicode="&#xe104;" d="M111 408q0 -33 5 -63q9 -56 44 -119.5t105 -108.5q31 -21 64 -16t62 23.5t57 49.5t48 61.5t35 60.5q32 66 39 184.5t-13 157.5q79 -80 122 -164t26 -184q-5 -33 -20.5 -69.5t-37.5 -80.5q-10 -19 -14.5 -29t-12 -26t-9 -23.5t-3 -19t2.5 -15.5t11 -9.5t19.5 -5t30.5 2.5 t42 8q57 20 91 34t87.5 44.5t87 64t65.5 88.5t47 122q38 172 -44.5 341.5t-246.5 278.5q22 -44 43 -129q39 -159 -32 -154q-15 2 -33 9q-79 33 -120.5 100t-44 175.5t48.5 257.5q-13 -8 -34 -23.5t-72.5 -66.5t-88.5 -105.5t-60 -138t-8 -166.5q2 -12 8 -41.5t8 -43t6 -39.5 t3.5 -39.5t-1 -33.5t-6 -31.5t-13.5 -24t-21 -20.5t-31 -12q-38 -10 -67 13t-40.5 61.5t-15 81.5t10.5 75q-52 -46 -83.5 -101t-39 -107t-7.5 -85z" /> <glyph unicode="&#xe105;" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5t145.5 -23.5t132.5 -59t116.5 -83.5t97 -90t74.5 -85.5t49 -63.5t20 -30l26 -40l-26 -40q-6 -10 -20 -30t-49 -63.5t-74.5 -85.5t-97 -90t-116.5 -83.5t-132.5 -59t-145.5 -23.5 t-145.5 23.5t-132.5 59t-116.5 83.5t-97 90t-74.5 85.5t-49 63.5t-20 30zM120 600q7 -10 40.5 -58t56 -78.5t68 -77.5t87.5 -75t103 -49.5t125 -21.5t123.5 20t100.5 45.5t85.5 71.5t66.5 75.5t58 81.5t47 66q-1 1 -28.5 37.5t-42 55t-43.5 53t-57.5 63.5t-58.5 54 q49 -74 49 -163q0 -124 -88 -212t-212 -88t-212 88t-88 212q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l105 105q-37 24 -75 72t-57 84l-20 36z" /> <glyph unicode="&#xe106;" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5q61 0 121 -17l37 142h148l-314 -1200h-148l37 143q-82 21 -165 71.5t-140 102t-109.5 112t-72 88.5t-29.5 43zM120 600q210 -282 393 -336l37 141q-107 18 -178.5 101.5t-71.5 193.5 q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l47 47l23 87q-30 28 -59 69t-44 68l-14 26zM780 161l38 145q22 15 44.5 34t46 44t40.5 44t41 50.5t33.5 43.5t33 44t24.5 34q-97 127 -140 175l39 146q67 -54 131.5 -125.5t87.5 -103.5t36 -52l26 -40l-26 -40 q-7 -12 -25.5 -38t-63.5 -79.5t-95.5 -102.5t-124 -100t-146.5 -79z" /> <glyph unicode="&#xe107;" d="M-97.5 34q13.5 -34 50.5 -34h1294q37 0 50.5 35.5t-7.5 67.5l-642 1056q-20 33 -48 36t-48 -29l-642 -1066q-21 -32 -7.5 -66zM155 200l445 723l445 -723h-345v100h-200v-100h-345zM500 600l100 -300l100 300v100h-200v-100z" /> <glyph unicode="&#xe108;" d="M100 262v41q0 20 11 44.5t26 38.5l363 325v339q0 62 44 106t106 44t106 -44t44 -106v-339l363 -325q15 -14 26 -38.5t11 -44.5v-41q0 -20 -12 -26.5t-29 5.5l-359 249v-263q100 -91 100 -113v-64q0 -21 -13 -29t-32 1l-94 78h-222l-94 -78q-19 -9 -32 -1t-13 29v64 q0 22 100 113v263l-359 -249q-17 -12 -29 -5.5t-12 26.5z" /> <glyph unicode="&#xe109;" d="M0 50q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v750h-1100v-750zM0 900h1100v150q0 21 -14.5 35.5t-35.5 14.5h-150v100h-100v-100h-500v100h-100v-100h-150q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 100v100h100v-100h-100zM100 300v100h100v-100h-100z M100 500v100h100v-100h-100zM300 100v100h100v-100h-100zM300 300v100h100v-100h-100zM300 500v100h100v-100h-100zM500 100v100h100v-100h-100zM500 300v100h100v-100h-100zM500 500v100h100v-100h-100zM700 100v100h100v-100h-100zM700 300v100h100v-100h-100zM700 500 v100h100v-100h-100zM900 100v100h100v-100h-100zM900 300v100h100v-100h-100zM900 500v100h100v-100h-100z" /> <glyph unicode="&#xe110;" d="M0 200v200h259l600 600h241v198l300 -295l-300 -300v197h-159l-600 -600h-341zM0 800h259l122 -122l141 142l-181 180h-341v-200zM678 381l141 142l122 -123h159v198l300 -295l-300 -300v197h-241z" /> <glyph unicode="&#xe111;" d="M0 400v600q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-596l-304 -300v300h-100q-41 0 -70.5 29.5t-29.5 70.5z" /> <glyph unicode="&#xe112;" d="M100 600v200h300v-250q0 -113 6 -145q17 -92 102 -117q39 -11 92 -11q37 0 66.5 5.5t50 15.5t36 24t24 31.5t14 37.5t7 42t2.5 45t0 47v25v250h300v-200q0 -42 -3 -83t-15 -104t-31.5 -116t-58 -109.5t-89 -96.5t-129 -65.5t-174.5 -25.5t-174.5 25.5t-129 65.5t-89 96.5 t-58 109.5t-31.5 116t-15 104t-3 83zM100 900v300h300v-300h-300zM800 900v300h300v-300h-300z" /> <glyph unicode="&#xe113;" d="M-30 411l227 -227l352 353l353 -353l226 227l-578 579z" /> <glyph unicode="&#xe114;" d="M70 797l580 -579l578 579l-226 227l-353 -353l-352 353z" /> <glyph unicode="&#xe115;" d="M-198 700l299 283l300 -283h-203v-400h385l215 -200h-800v600h-196zM402 1000l215 -200h381v-400h-198l299 -283l299 283h-200v600h-796z" /> <glyph unicode="&#xe116;" d="M18 939q-5 24 10 42q14 19 39 19h896l38 162q5 17 18.5 27.5t30.5 10.5h94q20 0 35 -14.5t15 -35.5t-15 -35.5t-35 -14.5h-54l-201 -961q-2 -4 -6 -10.5t-19 -17.5t-33 -11h-31v-50q0 -20 -14.5 -35t-35.5 -15t-35.5 15t-14.5 35v50h-300v-50q0 -20 -14.5 -35t-35.5 -15 t-35.5 15t-14.5 35v50h-50q-21 0 -35.5 15t-14.5 35q0 21 14.5 35.5t35.5 14.5h535l48 200h-633q-32 0 -54.5 21t-27.5 43z" /> <glyph unicode="&#xe117;" d="M0 0v800h1200v-800h-1200zM0 900v100h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-100h-1200z" /> <glyph unicode="&#xe118;" d="M1 0l300 700h1200l-300 -700h-1200zM1 400v600h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-200h-1000z" /> <glyph unicode="&#xe119;" d="M302 300h198v600h-198l298 300l298 -300h-198v-600h198l-298 -300z" /> <glyph unicode="&#xe120;" d="M0 600l300 298v-198h600v198l300 -298l-300 -297v197h-600v-197z" /> <glyph unicode="&#xe121;" d="M0 100v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM31 400l172 739q5 22 23 41.5t38 19.5h672q19 0 37.5 -22.5t23.5 -45.5l172 -732h-1138zM800 100h100v100h-100v-100z M1000 100h100v100h-100v-100z" /> <glyph unicode="&#xe122;" d="M-101 600v50q0 24 25 49t50 38l25 13v-250l-11 5.5t-24 14t-30 21.5t-24 27.5t-11 31.5zM99 500v250v5q0 13 0.5 18.5t2.5 13t8 10.5t15 3h200l675 250v-850l-675 200h-38l47 -276q2 -12 -3 -17.5t-11 -6t-21 -0.5h-8h-83q-20 0 -34.5 14t-18.5 35q-56 337 -56 351z M1100 200v850q0 21 14.5 35.5t35.5 14.5q20 0 35 -14.5t15 -35.5v-850q0 -20 -15 -35t-35 -15q-21 0 -35.5 15t-14.5 35z" /> <glyph unicode="&#xe123;" d="M74 350q0 21 13.5 35.5t33.5 14.5h17l118 173l63 327q15 77 76 140t144 83l-18 32q-6 19 3 32t29 13h94q20 0 29 -10.5t3 -29.5l-18 -37q83 -19 144 -82.5t76 -140.5l63 -327l118 -173h17q20 0 33.5 -14.5t13.5 -35.5q0 -20 -13 -40t-31 -27q-22 -9 -63 -23t-167.5 -37 t-251.5 -23t-245.5 20.5t-178.5 41.5l-58 20q-18 7 -31 27.5t-13 40.5zM497 110q12 -49 40 -79.5t63 -30.5t63 30.5t39 79.5q-48 -6 -102 -6t-103 6z" /> <glyph unicode="&#xe124;" d="M21 445l233 -45l-78 -224l224 78l45 -233l155 179l155 -179l45 233l224 -78l-78 224l234 45l-180 155l180 156l-234 44l78 225l-224 -78l-45 233l-155 -180l-155 180l-45 -233l-224 78l78 -225l-233 -44l179 -156z" /> <glyph unicode="&#xe125;" d="M0 200h200v600h-200v-600zM300 275q0 -75 100 -75h61q123 -100 139 -100h250q46 0 83 57l238 344q29 31 29 74v100q0 44 -30.5 84.5t-69.5 40.5h-328q28 118 28 125v150q0 44 -30.5 84.5t-69.5 40.5h-50q-27 0 -51 -20t-38 -48l-96 -198l-145 -196q-20 -26 -20 -63v-400z M400 300v375l150 212l100 213h50v-175l-50 -225h450v-125l-250 -375h-214l-136 100h-100z" /> <glyph unicode="&#xe126;" d="M0 400v600h200v-600h-200zM300 525v400q0 75 100 75h61q123 100 139 100h250q46 0 83 -57l238 -344q29 -31 29 -74v-100q0 -44 -30.5 -84.5t-69.5 -40.5h-328q28 -118 28 -125v-150q0 -44 -30.5 -84.5t-69.5 -40.5h-50q-27 0 -51 20t-38 48l-96 198l-145 196 q-20 26 -20 63zM400 525l150 -212l100 -213h50v175l-50 225h450v125l-250 375h-214l-136 -100h-100v-375z" /> <glyph unicode="&#xe127;" d="M8 200v600h200v-600h-200zM308 275v525q0 17 14 35.5t28 28.5l14 9l362 230q14 6 25 6q17 0 29 -12l109 -112q14 -14 14 -34q0 -18 -11 -32l-85 -121h302q85 0 138.5 -38t53.5 -110t-54.5 -111t-138.5 -39h-107l-130 -339q-7 -22 -20.5 -41.5t-28.5 -19.5h-341 q-7 0 -90 81t-83 94zM408 289l100 -89h293l131 339q6 21 19.5 41t28.5 20h203q16 0 25 15t9 36q0 20 -9 34.5t-25 14.5h-457h-6.5h-7.5t-6.5 0.5t-6 1t-5 1.5t-5.5 2.5t-4 4t-4 5.5q-5 12 -5 20q0 14 10 27l147 183l-86 83l-339 -236v-503z" /> <glyph unicode="&#xe128;" d="M-101 651q0 72 54 110t139 37h302l-85 121q-11 16 -11 32q0 21 14 34l109 113q13 12 29 12q11 0 25 -6l365 -230q7 -4 16.5 -10.5t26 -26t16.5 -36.5v-526q0 -13 -85.5 -93.5t-93.5 -80.5h-342q-15 0 -28.5 20t-19.5 41l-131 339h-106q-84 0 -139 39t-55 111zM-1 601h222 q15 0 28.5 -20.5t19.5 -40.5l131 -339h293l106 89v502l-342 237l-87 -83l145 -184q10 -11 10 -26q0 -11 -5 -20q-1 -3 -3.5 -5.5l-4 -4t-5 -2.5t-5.5 -1.5t-6.5 -1t-6.5 -0.5h-7.5h-6.5h-476v-100zM999 201v600h200v-600h-200z" /> <glyph unicode="&#xe129;" d="M97 719l230 -363q4 -6 10.5 -15.5t26 -25t36.5 -15.5h525q13 0 94 83t81 90v342q0 15 -20 28.5t-41 19.5l-339 131v106q0 84 -39 139t-111 55t-110 -53.5t-38 -138.5v-302l-121 84q-15 12 -33.5 11.5t-32.5 -13.5l-112 -110q-22 -22 -6 -53zM172 739l83 86l183 -146 q22 -18 47 -5q3 1 5.5 3.5l4 4t2.5 5t1.5 5.5t1 6.5t0.5 6v7.5v7v456q0 22 25 31t50 -0.5t25 -30.5v-202q0 -16 20 -29.5t41 -19.5l339 -130v-294l-89 -100h-503zM400 0v200h600v-200h-600z" /> <glyph unicode="&#xe130;" d="M1 585q-15 -31 7 -53l112 -110q13 -13 32 -13.5t34 10.5l121 85l-1 -302q0 -84 38.5 -138t110.5 -54t111 55t39 139v106l339 131q20 6 40.5 19.5t20.5 28.5v342q0 7 -81 90t-94 83h-525q-17 0 -35.5 -14t-28.5 -28l-10 -15zM76 565l237 339h503l89 -100v-294l-340 -130 q-20 -6 -40 -20t-20 -29v-202q0 -22 -25 -31t-50 0t-25 31v456v14.5t-1.5 11.5t-5 12t-9.5 7q-24 13 -46 -5l-184 -146zM305 1104v200h600v-200h-600z" /> <glyph unicode="&#xe131;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 500h300l-2 -194l402 294l-402 298v-197h-298v-201z" /> <glyph unicode="&#xe132;" d="M0 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t231.5 47.5q122 0 232.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-218 -217.5t-300 -80t-299.5 80t-217.5 217.5t-80 299.5zM200 600l400 -294v194h302v201h-300v197z" /> <glyph unicode="&#xe133;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600h200v-300h200v300h200l-300 400z" /> <glyph unicode="&#xe134;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600l300 -400l300 400h-200v300h-200v-300h-200z" /> <glyph unicode="&#xe135;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM254 780q-8 -34 5.5 -93t7.5 -87q0 -9 17 -44t16 -60q12 0 23 -5.5 t23 -15t20 -13.5q20 -10 108 -42q22 -8 53 -31.5t59.5 -38.5t57.5 -11q8 -18 -15 -55.5t-20 -57.5q12 -21 22.5 -34.5t28 -27t36.5 -17.5q0 -6 -3 -15.5t-3.5 -14.5t4.5 -17q101 -2 221 111q31 30 47 48t34 49t21 62q-14 9 -37.5 9.5t-35.5 7.5q-14 7 -49 15t-52 19 q-9 0 -39.5 -0.5t-46.5 -1.5t-39 -6.5t-39 -16.5q-50 -35 -66 -12q-4 2 -3.5 25.5t0.5 25.5q-6 13 -26.5 17t-24.5 7q2 22 -2 41t-16.5 28t-38.5 -20q-23 -25 -42 4q-19 28 -8 58q8 16 22 22q6 -1 26 -1.5t33.5 -4.5t19.5 -13q12 -19 32 -37.5t34 -27.5l14 -8q0 3 9.5 39.5 t5.5 57.5q-4 23 14.5 44.5t22.5 31.5q5 14 10 35t8.5 31t15.5 22.5t34 21.5q-6 18 10 37q8 0 23.5 -1.5t24.5 -1.5t20.5 4.5t20.5 15.5q-10 23 -30.5 42.5t-38 30t-49 26.5t-43.5 23q11 41 1 44q31 -13 58.5 -14.5t39.5 3.5l11 4q6 36 -17 53.5t-64 28.5t-56 23 q-19 -3 -37 0q-15 -12 -36.5 -21t-34.5 -12t-44 -8t-39 -6q-15 -3 -46 0t-45 -3q-20 -6 -51.5 -25.5t-34.5 -34.5q-3 -11 6.5 -22.5t8.5 -18.5q-3 -34 -27.5 -91t-29.5 -79zM518 915q3 12 16 30.5t16 25.5q10 -10 18.5 -10t14 6t14.5 14.5t16 12.5q0 -18 8 -42.5t16.5 -44 t9.5 -23.5q-6 1 -39 5t-53.5 10t-36.5 16z" /> <glyph unicode="&#xe136;" d="M0 164.5q0 21.5 15 37.5l600 599q-33 101 6 201.5t135 154.5q164 92 306 -9l-259 -138l145 -232l251 126q13 -175 -151 -267q-123 -70 -253 -23l-596 -596q-15 -16 -36.5 -16t-36.5 16l-111 110q-15 15 -15 36.5z" /> <glyph unicode="&#xe137;" horiz-adv-x="1220" d="M0 196v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 596v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5zM0 996v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM600 596h500v100h-500v-100zM800 196h300v100h-300v-100zM900 996h200v100h-200v-100z" /> <glyph unicode="&#xe138;" d="M100 1100v100h1000v-100h-1000zM150 1000h900l-350 -500v-300l-200 -200v500z" /> <glyph unicode="&#xe139;" d="M0 200v200h1200v-200q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 500v400q0 41 29.5 70.5t70.5 29.5h300v100q0 41 29.5 70.5t70.5 29.5h200q41 0 70.5 -29.5t29.5 -70.5v-100h300q41 0 70.5 -29.5t29.5 -70.5v-400h-500v100h-200v-100h-500z M500 1000h200v100h-200v-100z" /> <glyph unicode="&#xe140;" d="M0 0v400l129 -129l200 200l142 -142l-200 -200l129 -129h-400zM0 800l129 129l200 -200l142 142l-200 200l129 129h-400v-400zM729 329l142 142l200 -200l129 129v-400h-400l129 129zM729 871l200 200l-129 129h400v-400l-129 129l-200 -200z" /> <glyph unicode="&#xe141;" d="M0 596q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 596q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM291 655 q0 23 15.5 38.5t38.5 15.5t39 -16t16 -38q0 -23 -16 -39t-39 -16q-22 0 -38 16t-16 39zM400 850q0 22 16 38.5t39 16.5q22 0 38 -16t16 -39t-16 -39t-38 -16q-23 0 -39 16.5t-16 38.5zM513 609q0 32 21 56.5t52 29.5l122 126l1 1q-9 14 -9 28q0 22 16 38.5t39 16.5 q22 0 38 -16t16 -39t-16 -39t-38 -16q-16 0 -29 10l-55 -145q17 -22 17 -51q0 -36 -25.5 -61.5t-61.5 -25.5q-37 0 -62.5 25.5t-25.5 61.5zM800 655q0 22 16 38t39 16t38.5 -15.5t15.5 -38.5t-16 -39t-38 -16q-23 0 -39 16t-16 39z" /> <glyph unicode="&#xe142;" d="M-40 375q-13 -95 35 -173q35 -57 94 -89t129 -32q63 0 119 28q33 16 65 40.5t52.5 45.5t59.5 64q40 44 57 61l394 394q35 35 47 84t-3 96q-27 87 -117 104q-20 2 -29 2q-46 0 -79.5 -17t-67.5 -51l-388 -396l-7 -7l69 -67l377 373q20 22 39 38q23 23 50 23q38 0 53 -36 q16 -39 -20 -75l-547 -547q-52 -52 -125 -52q-55 0 -100 33t-54 96q-5 35 2.5 66t31.5 63t42 50t56 54q24 21 44 41l348 348q52 52 82.5 79.5t84 54t107.5 26.5q25 0 48 -4q95 -17 154 -94.5t51 -175.5q-7 -101 -98 -192l-252 -249l-253 -256l7 -7l69 -60l517 511 q67 67 95 157t11 183q-16 87 -67 154t-130 103q-69 33 -152 33q-107 0 -197 -55q-40 -24 -111 -95l-512 -512q-68 -68 -81 -163z" /> <glyph unicode="&#xe143;" d="M79 784q0 131 99 229.5t230 98.5q144 0 242 -129q103 129 245 129q130 0 227 -98.5t97 -229.5q0 -46 -17.5 -91t-61 -99t-77 -89.5t-104.5 -105.5q-197 -191 -293 -322l-17 -23l-16 23q-43 58 -100 122.5t-92 99.5t-101 100l-84.5 84.5t-68 74t-60 78t-33.5 70.5t-15 78z M250 784q0 -27 30.5 -70t61.5 -75.5t95 -94.5l22 -22q93 -90 190 -201q82 92 195 203l12 12q64 62 97.5 97t64.5 79t31 72q0 71 -48 119.5t-106 48.5q-73 0 -131 -83l-118 -171l-114 174q-51 80 -124 80q-59 0 -108.5 -49.5t-49.5 -118.5z" /> <glyph unicode="&#xe144;" d="M57 353q0 -94 66 -160l141 -141q66 -66 159 -66q95 0 159 66l283 283q66 66 66 159t-66 159l-141 141q-12 12 -19 17l-105 -105l212 -212l-389 -389l-247 248l95 95l-18 18q-46 45 -75 101l-55 -55q-66 -66 -66 -159zM269 706q0 -93 66 -159l141 -141l19 -17l105 105 l-212 212l389 389l247 -247l-95 -96l18 -18q46 -46 77 -99l29 29q35 35 62.5 88t27.5 96q0 93 -66 159l-141 141q-66 66 -159 66q-95 0 -159 -66l-283 -283q-66 -64 -66 -159z" /> <glyph unicode="&#xe145;" d="M200 100v953q0 21 30 46t81 48t129 38t163 15t162 -15t127 -38t79 -48t29 -46v-953q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-41 0 -70.5 29.5t-29.5 70.5zM300 300h600v700h-600v-700zM496 150q0 -43 30.5 -73.5t73.5 -30.5t73.5 30.5t30.5 73.5t-30.5 73.5t-73.5 30.5 t-73.5 -30.5t-30.5 -73.5z" /> <glyph unicode="&#xe146;" d="M0 0l303 380l207 208l-210 212h300l267 279l-35 36q-15 14 -15 35t15 35q14 15 35 15t35 -15l283 -282q15 -15 15 -36t-15 -35q-14 -15 -35 -15t-35 15l-36 35l-279 -267v-300l-212 210l-208 -207z" /> <glyph unicode="&#xe148;" d="M295 433h139q5 -77 48.5 -126.5t117.5 -64.5v335l-27 7q-46 14 -79 26.5t-72 36t-62.5 52t-40 72.5t-16.5 99q0 92 44 159.5t109 101t144 40.5v78h100v-79q38 -4 72.5 -13.5t75.5 -31.5t71 -53.5t51.5 -84t24.5 -118.5h-159q-8 72 -35 109.5t-101 50.5v-307l64 -14 q34 -7 64 -16.5t70 -31.5t67.5 -52t47.5 -80.5t20 -112.5q0 -139 -89 -224t-244 -96v-77h-100v78q-152 17 -237 104q-40 40 -52.5 93.5t-15.5 139.5zM466 889q0 -29 8 -51t16.5 -34t29.5 -22.5t31 -13.5t38 -10q7 -2 11 -3v274q-61 -8 -97.5 -37.5t-36.5 -102.5zM700 237 q170 18 170 151q0 64 -44 99.5t-126 60.5v-311z" /> <glyph unicode="&#xe149;" d="M100 600v100h166q-24 49 -44 104q-10 26 -14.5 55.5t-3 72.5t25 90t68.5 87q97 88 263 88q129 0 230 -89t101 -208h-153q0 52 -34 89.5t-74 51.5t-76 14q-37 0 -79 -14.5t-62 -35.5q-41 -44 -41 -101q0 -11 2.5 -24.5t5.5 -24t9.5 -26.5t10.5 -25t14 -27.5t14 -25.5 t15.5 -27t13.5 -24h242v-100h-197q8 -50 -2.5 -115t-31.5 -94q-41 -59 -99 -113q35 11 84 18t70 7q32 1 102 -16t104 -17q76 0 136 30l50 -147q-41 -25 -80.5 -36.5t-59 -13t-61.5 -1.5q-23 0 -128 33t-155 29q-39 -4 -82 -17t-66 -25l-24 -11l-55 145l16.5 11t15.5 10 t13.5 9.5t14.5 12t14.5 14t17.5 18.5q48 55 54 126.5t-30 142.5h-221z" /> <glyph unicode="&#xe150;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM602 900l298 300l298 -300h-198v-900h-200v900h-198z" /> <glyph unicode="&#xe151;" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v200h100v-100h200v-100h-300zM700 400v100h300v-200h-99v-100h-100v100h99v100h-200zM700 700v500h300v-500h-100v100h-100v-100h-100zM801 900h100v200h-100v-200z" /> <glyph unicode="&#xe152;" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v500h300v-500h-100v100h-100v-100h-100zM700 700v200h100v-100h200v-100h-300zM700 1100v100h300v-200h-99v-100h-100v100h99v100h-200zM801 200h100v200h-100v-200z" /> <glyph unicode="&#xe153;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 100v400h300v-500h-100v100h-200zM800 1100v100h200v-500h-100v400h-100zM901 200h100v200h-100v-200z" /> <glyph unicode="&#xe154;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 400v100h200v-500h-100v400h-100zM800 800v400h300v-500h-100v100h-200zM901 900h100v200h-100v-200z" /> <glyph unicode="&#xe155;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h500v-200h-500zM700 400v200h400v-200h-400zM700 700v200h300v-200h-300zM700 1000v200h200v-200h-200z" /> <glyph unicode="&#xe156;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h200v-200h-200zM700 400v200h300v-200h-300zM700 700v200h400v-200h-400zM700 1000v200h500v-200h-500z" /> <glyph unicode="&#xe157;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q162 0 281 -118.5t119 -281.5v-300q0 -165 -118.5 -282.5t-281.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500z" /> <glyph unicode="&#xe158;" d="M0 400v300q0 163 119 281.5t281 118.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-163 0 -281.5 117.5t-118.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM400 300l333 250l-333 250v-500z" /> <glyph unicode="&#xe159;" d="M0 400v300q0 163 117.5 281.5t282.5 118.5h300q163 0 281.5 -119t118.5 -281v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 700l250 -333l250 333h-500z" /> <glyph unicode="&#xe160;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -162 -118.5 -281t-281.5 -119h-300q-165 0 -282.5 118.5t-117.5 281.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 400h500l-250 333z" /> <glyph unicode="&#xe161;" d="M0 400v300h300v200l400 -350l-400 -350v200h-300zM500 0v200h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-500v200h400q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-400z" /> <glyph unicode="&#xe162;" d="M216 519q10 -19 32 -19h302q-155 -438 -160 -458q-5 -21 4 -32l9 -8l9 -1q13 0 26 16l538 630q15 19 6 36q-8 18 -32 16h-300q1 4 78 219.5t79 227.5q2 17 -6 27l-8 8h-9q-16 0 -25 -15q-4 -5 -98.5 -111.5t-228 -257t-209.5 -238.5q-17 -19 -7 -40z" /> <glyph unicode="&#xe163;" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q47 0 100 15v185h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h500v185q-14 4 -114 7.5t-193 5.5l-93 2q-165 0 -282.5 -117.5t-117.5 -282.5v-300zM600 400v300h300v200l400 -350l-400 -350v200h-300z " /> <glyph unicode="&#xe164;" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q163 0 281.5 117.5t118.5 282.5v98l-78 73l-122 -123v-148q0 -41 -29.5 -70.5t-70.5 -29.5h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h156l118 122l-74 78h-100q-165 0 -282.5 -117.5t-117.5 -282.5 v-300zM496 709l353 342l-149 149h500v-500l-149 149l-342 -353z" /> <glyph unicode="&#xe165;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM406 600 q0 80 57 137t137 57t137 -57t57 -137t-57 -137t-137 -57t-137 57t-57 137z" /> <glyph unicode="&#xe166;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 800l445 -500l450 500h-295v400h-300v-400h-300zM900 150h100v50h-100v-50z" /> <glyph unicode="&#xe167;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 700h300v-300h300v300h295l-445 500zM900 150h100v50h-100v-50z" /> <glyph unicode="&#xe168;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 705l305 -305l596 596l-154 155l-442 -442l-150 151zM900 150h100v50h-100v-50z" /> <glyph unicode="&#xe169;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 988l97 -98l212 213l-97 97zM200 401h700v699l-250 -239l-149 149l-212 -212l149 -149zM900 150h100v50h-100v-50z" /> <glyph unicode="&#xe170;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM200 612l212 -212l98 97l-213 212zM300 1200l239 -250l-149 -149l212 -212l149 148l248 -237v700h-699zM900 150h100v50h-100v-50z" /> <glyph unicode="&#xe171;" d="M23 415l1177 784v-1079l-475 272l-310 -393v416h-392zM494 210l672 938l-672 -712v-226z" /> <glyph unicode="&#xe172;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-850q0 -21 -15 -35.5t-35 -14.5h-150v400h-700v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200z" /> <glyph unicode="&#xe173;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-218l-276 -275l-120 120l-126 -127h-378v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM581 306l123 123l120 -120l353 352l123 -123l-475 -476zM600 1000h100v200h-100v-200z" /> <glyph unicode="&#xe174;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-269l-103 -103l-170 170l-298 -298h-329v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200zM700 133l170 170l-170 170l127 127l170 -170l170 170l127 -128l-170 -169l170 -170 l-127 -127l-170 170l-170 -170z" /> <glyph unicode="&#xe175;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-300h-400v-200h-500v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300l300 -300l300 300h-200v300h-200v-300h-200zM600 1000v200h100v-200h-100z" /> <glyph unicode="&#xe176;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-402l-200 200l-298 -298h-402v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300h200v-300h200v300h200l-300 300zM600 1000v200h100v-200h-100z" /> <glyph unicode="&#xe177;" d="M0 250q0 -21 14.5 -35.5t35.5 -14.5h1100q21 0 35.5 14.5t14.5 35.5v550h-1200v-550zM0 900h1200v150q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 300v200h400v-200h-400z" /> <glyph unicode="&#xe178;" d="M0 400l300 298v-198h400v-200h-400v-198zM100 800v200h100v-200h-100zM300 800v200h100v-200h-100zM500 800v200h400v198l300 -298l-300 -298v198h-400zM800 300v200h100v-200h-100zM1000 300h100v200h-100v-200z" /> <glyph unicode="&#xe179;" d="M100 700v400l50 100l50 -100v-300h100v300l50 100l50 -100v-300h100v300l50 100l50 -100v-400l-100 -203v-447q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v447zM800 597q0 -29 10.5 -55.5t25 -43t29 -28.5t25.5 -18l10 -5v-397q0 -21 14.5 -35.5 t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v1106q0 31 -18 40.5t-44 -7.5l-276 -117q-25 -16 -43.5 -50.5t-18.5 -65.5v-359z" /> <glyph unicode="&#xe180;" d="M100 0h400v56q-75 0 -87.5 6t-12.5 44v394h500v-394q0 -38 -12.5 -44t-87.5 -6v-56h400v56q-4 0 -11 0.5t-24 3t-30 7t-24 15t-11 24.5v888q0 22 25 34.5t50 13.5l25 2v56h-400v-56q75 0 87.5 -6t12.5 -44v-394h-500v394q0 38 12.5 44t87.5 6v56h-400v-56q4 0 11 -0.5 t24 -3t30 -7t24 -15t11 -24.5v-888q0 -22 -25 -34.5t-50 -13.5l-25 -2v-56z" /> <glyph unicode="&#xe181;" d="M0 300q0 -41 29.5 -70.5t70.5 -29.5h300q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-300q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM100 100h400l200 200h105l295 98v-298h-425l-100 -100h-375zM100 300v200h300v-200h-300zM100 600v200h300v-200h-300z M100 1000h400l200 -200v-98l295 98h105v200h-425l-100 100h-375zM700 402v163l400 133v-163z" /> <glyph unicode="&#xe182;" d="M16.5 974.5q0.5 -21.5 16 -90t46.5 -140t104 -177.5t175 -208q103 -103 207.5 -176t180 -103.5t137 -47t92.5 -16.5l31 1l163 162q16 17 13 40.5t-22 37.5l-192 136q-19 14 -45 12t-42 -19l-119 -118q-143 103 -267 227q-126 126 -227 268l118 118q17 17 20 41.5 t-11 44.5l-139 194q-14 19 -36.5 22t-40.5 -14l-162 -162q-1 -11 -0.5 -32.5z" /> <glyph unicode="&#xe183;" d="M0 50v212q0 20 10.5 45.5t24.5 39.5l365 303v50q0 4 1 10.5t12 22.5t30 28.5t60 23t97 10.5t97 -10t60 -23.5t30 -27.5t12 -24l1 -10v-50l365 -303q14 -14 24.5 -39.5t10.5 -45.5v-212q0 -21 -15 -35.5t-35 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5zM0 712 q0 -21 14.5 -33.5t34.5 -8.5l202 33q20 4 34.5 21t14.5 38v146q141 24 300 24t300 -24v-146q0 -21 14.5 -38t34.5 -21l202 -33q20 -4 34.5 8.5t14.5 33.5v200q-6 8 -19 20.5t-63 45t-112 57t-171 45t-235 20.5q-92 0 -175 -10.5t-141.5 -27t-108.5 -36.5t-81.5 -40 t-53.5 -36.5t-31 -27.5l-9 -10v-200z" /> <glyph unicode="&#xe184;" d="M100 0v100h1100v-100h-1100zM175 200h950l-125 150v250l100 100v400h-100v-200h-100v200h-200v-200h-100v200h-200v-200h-100v200h-100v-400l100 -100v-250z" /> <glyph unicode="&#xe185;" d="M100 0h300v400q0 41 -29.5 70.5t-70.5 29.5h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-400zM500 0v1000q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-1000h-300zM900 0v700q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-700h-300z" /> <glyph unicode="&#xe186;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" /> <glyph unicode="&#xe187;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h100v200h100v-200h100v500h-100v-200h-100v200h-100v-500zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" /> <glyph unicode="&#xe188;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v100h-200v300h200v100h-300v-500zM600 300h300v100h-200v300h200v100h-300v-500z" /> <glyph unicode="&#xe189;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 550l300 -150v300zM600 400l300 150l-300 150v-300z" /> <glyph unicode="&#xe190;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300v500h700v-500h-700zM300 400h130q41 0 68 42t27 107t-28.5 108t-66.5 43h-130v-300zM575 549 q0 -65 27 -107t68 -42h130v300h-130q-38 0 -66.5 -43t-28.5 -108z" /> <glyph unicode="&#xe191;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" /> <glyph unicode="&#xe192;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v400h-200v100h-100v-500zM301 400v200h100v-200h-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" /> <glyph unicode="&#xe193;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 700v100h300v-300h-99v-100h-100v100h99v200h-200zM201 300v100h100v-100h-100zM601 300v100h100v-100h-100z M700 700v100h200v-500h-100v400h-100z" /> <glyph unicode="&#xe194;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 500v200 l100 100h300v-100h-300v-200h300v-100h-300z" /> <glyph unicode="&#xe195;" d="M0 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 400v400h300 l100 -100v-100h-100v100h-200v-100h200v-100h-200v-100h-100zM700 400v100h100v-100h-100z" /> <glyph unicode="&#xe197;" d="M-14 494q0 -80 56.5 -137t135.5 -57h222v300h400v-300h128q120 0 205 86t85 208q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200h200v300h200v-300 h200l-300 -300z" /> <glyph unicode="&#xe198;" d="M-14 494q0 -80 56.5 -137t135.5 -57h8l414 414l403 -403q94 26 154.5 104t60.5 178q0 121 -85 207.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200l300 300 l300 -300h-200v-300h-200v300h-200z" /> <glyph unicode="&#xe199;" d="M100 200h400v-155l-75 -45h350l-75 45v155h400l-270 300h170l-270 300h170l-300 333l-300 -333h170l-270 -300h170z" /> <glyph unicode="&#xe200;" d="M121 700q0 -53 28.5 -97t75.5 -65q-4 -16 -4 -38q0 -74 52.5 -126.5t126.5 -52.5q56 0 100 30v-306l-75 -45h350l-75 45v306q46 -30 100 -30q74 0 126.5 52.5t52.5 126.5q0 24 -9 55q50 32 79.5 83t29.5 112q0 90 -61.5 155.5t-150.5 71.5q-26 89 -99.5 145.5 t-167.5 56.5q-116 0 -197.5 -81.5t-81.5 -197.5q0 -4 1 -12t1 -11q-14 2 -23 2q-74 0 -126.5 -52.5t-52.5 -126.5z" /> </font> </defs></svg>
gui/bootstrap/fonts/glyphicons-halflings-regular.svg
0
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.0014653262915089726, 0.00046757553354837, 0.0001663263828959316, 0.0002628443471621722, 0.0003845311875920743 ]
{ "id": 7, "code_window": [ "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n", "\t\treturn 128\n", "\t}\n", "\tif f.NumBlocks < 2 {\n", "\t\treturn BlockSize / 2\n", "\t} else {\n", "\t\treturn int64(f.NumBlocks-1)*BlockSize + BlockSize/2\n", "\t}\n", "}\n", "\n", "func (f FileInfoTruncated) IsDeleted() bool {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn BlocksToSize(f.NumBlocks)\n" ], "file_path": "internal/protocol/message.go", "type": "replace", "edit_start_line_idx": 88 }
// Copyright (C) 2014 The Syncthing Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // // You should have received a copy of the GNU General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. package model import ( "bufio" "crypto/tls" "errors" "fmt" "io" "io/ioutil" "net" "os" "path/filepath" "strconv" "strings" "sync" "time" "github.com/syncthing/syncthing/internal/config" "github.com/syncthing/syncthing/internal/events" "github.com/syncthing/syncthing/internal/files" "github.com/syncthing/syncthing/internal/ignore" "github.com/syncthing/syncthing/internal/lamport" "github.com/syncthing/syncthing/internal/osutil" "github.com/syncthing/syncthing/internal/protocol" "github.com/syncthing/syncthing/internal/scanner" "github.com/syncthing/syncthing/internal/stats" "github.com/syncthing/syncthing/internal/symlinks" "github.com/syncthing/syncthing/internal/versioner" "github.com/syndtr/goleveldb/leveldb" ) type folderState int const ( FolderIdle folderState = iota FolderScanning FolderSyncing FolderCleaning ) func (s folderState) String() string { switch s { case FolderIdle: return "idle" case FolderScanning: return "scanning" case FolderCleaning: return "cleaning" case FolderSyncing: return "syncing" default: return "unknown" } } // How many files to send in each Index/IndexUpdate message. const ( indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed) indexPerFileSize = 250 // Each FileInfo is approximately this big, in bytes, excluding BlockInfos IndexPerBlockSize = 40 // Each BlockInfo is approximately this big indexBatchSize = 1000 // Either way, don't include more files than this ) type service interface { Serve() Stop() } type Model struct { cfg *config.ConfigWrapper db *leveldb.DB finder *files.BlockFinder deviceName string clientName string clientVersion string folderCfgs map[string]config.FolderConfiguration // folder -> cfg folderFiles map[string]*files.Set // folder -> files folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs deviceFolders map[protocol.DeviceID][]string // deviceID -> folders deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef folderIgnores map[string]*ignore.Matcher // folder -> matcher object folderRunners map[string]service // folder -> puller or scanner fmut sync.RWMutex // protects the above folderState map[string]folderState // folder -> state folderStateChanged map[string]time.Time // folder -> time when state changed smut sync.RWMutex protoConn map[protocol.DeviceID]protocol.Connection rawConn map[protocol.DeviceID]io.Closer deviceVer map[protocol.DeviceID]string pmut sync.RWMutex // protects protoConn and rawConn addedFolder bool started bool } var ( ErrNoSuchFile = errors.New("no such file") ErrInvalid = errors.New("file is invalid") SymlinkWarning = sync.Once{} ) // NewModel creates and starts a new model. The model starts in read-only mode, // where it sends index information to connected peers and responds to requests // for file data without altering the local folder in any way. func NewModel(cfg *config.ConfigWrapper, deviceName, clientName, clientVersion string, db *leveldb.DB) *Model { m := &Model{ cfg: cfg, db: db, deviceName: deviceName, clientName: clientName, clientVersion: clientVersion, folderCfgs: make(map[string]config.FolderConfiguration), folderFiles: make(map[string]*files.Set), folderDevices: make(map[string][]protocol.DeviceID), deviceFolders: make(map[protocol.DeviceID][]string), deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference), folderIgnores: make(map[string]*ignore.Matcher), folderRunners: make(map[string]service), folderState: make(map[string]folderState), folderStateChanged: make(map[string]time.Time), protoConn: make(map[protocol.DeviceID]protocol.Connection), rawConn: make(map[protocol.DeviceID]io.Closer), deviceVer: make(map[protocol.DeviceID]string), finder: files.NewBlockFinder(db, cfg), } var timeout = 20 * 60 // seconds if t := os.Getenv("STDEADLOCKTIMEOUT"); len(t) > 0 { it, err := strconv.Atoi(t) if err == nil { timeout = it } } deadlockDetect(&m.fmut, time.Duration(timeout)*time.Second) deadlockDetect(&m.smut, time.Duration(timeout)*time.Second) deadlockDetect(&m.pmut, time.Duration(timeout)*time.Second) return m } // StartRW starts read/write processing on the current model. When in // read/write mode the model will attempt to keep in sync with the cluster by // pulling needed files from peer devices. func (m *Model) StartFolderRW(folder string) { m.fmut.Lock() cfg, ok := m.folderCfgs[folder] if !ok { panic("cannot start nonexistent folder " + folder) } _, ok = m.folderRunners[folder] if ok { panic("cannot start already running folder " + folder) } p := &Puller{ folder: folder, dir: cfg.Path, scanIntv: time.Duration(cfg.RescanIntervalS) * time.Second, model: m, ignorePerms: cfg.IgnorePerms, lenientMtimes: cfg.LenientMtimes, } m.folderRunners[folder] = p m.fmut.Unlock() if len(cfg.Versioning.Type) > 0 { factory, ok := versioner.Factories[cfg.Versioning.Type] if !ok { l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type) } p.versioner = factory(folder, cfg.Path, cfg.Versioning.Params) } if cfg.LenientMtimes { l.Infof("Folder %q is running with LenientMtimes workaround. Syncing may not work properly.", folder) } go p.Serve() } // StartRO starts read only processing on the current model. When in // read only mode the model will announce files to the cluster but not // pull in any external changes. func (m *Model) StartFolderRO(folder string) { m.fmut.Lock() cfg, ok := m.folderCfgs[folder] if !ok { panic("cannot start nonexistent folder " + folder) } _, ok = m.folderRunners[folder] if ok { panic("cannot start already running folder " + folder) } s := &Scanner{ folder: folder, intv: time.Duration(cfg.RescanIntervalS) * time.Second, model: m, } m.folderRunners[folder] = s m.fmut.Unlock() go s.Serve() } type ConnectionInfo struct { protocol.Statistics Address string ClientVersion string } // ConnectionStats returns a map with connection statistics for each connected device. func (m *Model) ConnectionStats() map[string]ConnectionInfo { type remoteAddrer interface { RemoteAddr() net.Addr } m.pmut.RLock() m.fmut.RLock() var res = make(map[string]ConnectionInfo) for device, conn := range m.protoConn { ci := ConnectionInfo{ Statistics: conn.Statistics(), ClientVersion: m.deviceVer[device], } if nc, ok := m.rawConn[device].(remoteAddrer); ok { ci.Address = nc.RemoteAddr().String() } res[device.String()] = ci } m.fmut.RUnlock() m.pmut.RUnlock() in, out := protocol.TotalInOut() res["total"] = ConnectionInfo{ Statistics: protocol.Statistics{ At: time.Now(), InBytesTotal: in, OutBytesTotal: out, }, } return res } // Returns statistics about each device func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics { var res = make(map[string]stats.DeviceStatistics) for id := range m.cfg.Devices() { res[id.String()] = m.deviceStatRef(id).GetStatistics() } return res } // Returns the completion status, in percent, for the given device and folder. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 { defer m.leveldbPanicWorkaround() var tot int64 m.fmut.RLock() rf, ok := m.folderFiles[folder] m.fmut.RUnlock() if !ok { return 0 // Folder doesn't exist, so we hardly have any of it } rf.WithGlobalTruncated(func(f protocol.FileIntf) bool { if !f.IsDeleted() { tot += f.Size() } return true }) if tot == 0 { return 100 // Folder is empty, so we have all of it } var need int64 rf.WithNeedTruncated(device, func(f protocol.FileIntf) bool { if !f.IsDeleted() { need += f.Size() } return true }) res := 100 * (1 - float64(need)/float64(tot)) if debug { l.Debugf("%v Completion(%s, %q): %f (%d / %d)", m, device, folder, res, need, tot) } return res } func sizeOf(fs []protocol.FileInfo) (files, deleted int, bytes int64) { for _, f := range fs { fs, de, by := sizeOfFile(f) files += fs deleted += de bytes += by } return } func sizeOfFile(f protocol.FileIntf) (files, deleted int, bytes int64) { if !f.IsDeleted() { files++ } else { deleted++ } bytes += f.Size() return } // GlobalSize returns the number of files, deleted files and total bytes for all // files in the global model. func (m *Model) GlobalSize(folder string) (files, deleted int, bytes int64) { defer m.leveldbPanicWorkaround() m.fmut.RLock() defer m.fmut.RUnlock() if rf, ok := m.folderFiles[folder]; ok { rf.WithGlobalTruncated(func(f protocol.FileIntf) bool { fs, de, by := sizeOfFile(f) files += fs deleted += de bytes += by return true }) } return } // LocalSize returns the number of files, deleted files and total bytes for all // files in the local folder. func (m *Model) LocalSize(folder string) (files, deleted int, bytes int64) { defer m.leveldbPanicWorkaround() m.fmut.RLock() defer m.fmut.RUnlock() if rf, ok := m.folderFiles[folder]; ok { rf.WithHaveTruncated(protocol.LocalDeviceID, func(f protocol.FileIntf) bool { if f.IsInvalid() { return true } fs, de, by := sizeOfFile(f) files += fs deleted += de bytes += by return true }) } return } // NeedSize returns the number and total size of currently needed files. func (m *Model) NeedSize(folder string) (files int, bytes int64) { defer m.leveldbPanicWorkaround() m.fmut.RLock() defer m.fmut.RUnlock() if rf, ok := m.folderFiles[folder]; ok { rf.WithNeedTruncated(protocol.LocalDeviceID, func(f protocol.FileIntf) bool { fs, de, by := sizeOfFile(f) files += fs + de bytes += by return true }) } if debug { l.Debugf("%v NeedSize(%q): %d %d", m, folder, files, bytes) } return } // NeedFiles returns the list of currently needed files, stopping at maxFiles // files or maxBlocks blocks. Limits <= 0 are ignored. func (m *Model) NeedFolderFilesLimited(folder string, maxFiles, maxBlocks int) []protocol.FileInfo { defer m.leveldbPanicWorkaround() m.fmut.RLock() defer m.fmut.RUnlock() nblocks := 0 if rf, ok := m.folderFiles[folder]; ok { fs := make([]protocol.FileInfo, 0, maxFiles) rf.WithNeed(protocol.LocalDeviceID, func(f protocol.FileIntf) bool { fi := f.(protocol.FileInfo) fs = append(fs, fi) nblocks += len(fi.Blocks) return (maxFiles <= 0 || len(fs) < maxFiles) && (maxBlocks <= 0 || nblocks < maxBlocks) }) return fs } return nil } // Index is called when a new device is connected and we receive their full index. // Implements the protocol.Model interface. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) { if debug { l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs)) } if !m.folderSharedWith(folder, deviceID) { events.Default.Log(events.FolderRejected, map[string]string{ "folder": folder, "device": deviceID.String(), }) l.Warnf("Unexpected folder ID %q sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", folder, deviceID) return } m.fmut.RLock() files, ok := m.folderFiles[folder] ignores, _ := m.folderIgnores[folder] m.fmut.RUnlock() if !ok { l.Fatalf("Index for nonexistant folder %q", folder) } for i := 0; i < len(fs); { lamport.Default.Tick(fs[i].Version) if (ignores != nil && ignores.Match(fs[i].Name)) || symlinkInvalid(fs[i].IsSymlink()) { if debug { l.Debugln("dropping update for ignored/unsupported symlink", fs[i]) } fs[i] = fs[len(fs)-1] fs = fs[:len(fs)-1] } else { i++ } } files.Replace(deviceID, fs) events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{ "device": deviceID.String(), "folder": folder, "items": len(fs), "version": files.LocalVersion(deviceID), }) } // IndexUpdate is called for incremental updates to connected devices' indexes. // Implements the protocol.Model interface. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) { if debug { l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs)) } if !m.folderSharedWith(folder, deviceID) { l.Infof("Update for unexpected folder ID %q sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", folder, deviceID) return } m.fmut.RLock() files, ok := m.folderFiles[folder] ignores, _ := m.folderIgnores[folder] m.fmut.RUnlock() if !ok { l.Fatalf("IndexUpdate for nonexistant folder %q", folder) } for i := 0; i < len(fs); { lamport.Default.Tick(fs[i].Version) if (ignores != nil && ignores.Match(fs[i].Name)) || symlinkInvalid(fs[i].IsSymlink()) { if debug { l.Debugln("dropping update for ignored/unsupported symlink", fs[i]) } fs[i] = fs[len(fs)-1] fs = fs[:len(fs)-1] } else { i++ } } files.Update(deviceID, fs) events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{ "device": deviceID.String(), "folder": folder, "items": len(fs), "version": files.LocalVersion(deviceID), }) } func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool { m.fmut.RLock() defer m.fmut.RUnlock() for _, nfolder := range m.deviceFolders[deviceID] { if nfolder == folder { return true } } return false } func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) { m.pmut.Lock() if cm.ClientName == "syncthing" { m.deviceVer[deviceID] = cm.ClientVersion } else { m.deviceVer[deviceID] = cm.ClientName + " " + cm.ClientVersion } m.pmut.Unlock() l.Infof(`Device %s client is "%s %s"`, deviceID, cm.ClientName, cm.ClientVersion) var changed bool if name := cm.GetOption("name"); name != "" { l.Infof("Device %s name is %q", deviceID, name) device, ok := m.cfg.Devices()[deviceID] if ok && device.Name == "" { device.Name = name m.cfg.SetDevice(device) changed = true } } if m.cfg.Devices()[deviceID].Introducer { // This device is an introducer. Go through the announced lists of folders // and devices and add what we are missing. for _, folder := range cm.Folders { // If we don't have this folder yet, skip it. Ideally, we'd // offer up something in the GUI to create the folder, but for the // moment we only handle folders that we already have. if _, ok := m.folderDevices[folder.ID]; !ok { continue } nextDevice: for _, device := range folder.Devices { var id protocol.DeviceID copy(id[:], device.ID) if _, ok := m.cfg.Devices()[id]; !ok { // The device is currently unknown. Add it to the config. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID) newDeviceCfg := config.DeviceConfiguration{ DeviceID: id, Compression: true, Addresses: []string{"dynamic"}, } // The introducers' introducers are also our introducers. if device.Flags&protocol.FlagIntroducer != 0 { l.Infof("Device %v is now also an introducer", id) newDeviceCfg.Introducer = true } m.cfg.SetDevice(newDeviceCfg) changed = true } for _, er := range m.deviceFolders[id] { if er == folder.ID { // We already share the folder with this device, so // nothing to do. continue nextDevice } } // We don't yet share this folder with this device. Add the device // to sharing list of the folder. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID) m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID) m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id) folderCfg := m.cfg.Folders()[folder.ID] folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{ DeviceID: id, }) m.cfg.SetFolder(folderCfg) changed = true } } } if changed { m.cfg.Save() } } // Close removes the peer from the model and closes the underlying connection if possible. // Implements the protocol.Model interface. func (m *Model) Close(device protocol.DeviceID, err error) { l.Infof("Connection to %s closed: %v", device, err) events.Default.Log(events.DeviceDisconnected, map[string]string{ "id": device.String(), "error": err.Error(), }) m.pmut.Lock() m.fmut.RLock() for _, folder := range m.deviceFolders[device] { m.folderFiles[folder].Replace(device, nil) } m.fmut.RUnlock() conn, ok := m.rawConn[device] if ok { if conn, ok := conn.(*tls.Conn); ok { // If the underlying connection is a *tls.Conn, Close() does more // than it says on the tin. Specifically, it sends a TLS alert // message, which might block forever if the connection is dead // and we don't have a deadline site. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond)) } conn.Close() } delete(m.protoConn, device) delete(m.rawConn, device) delete(m.deviceVer, device) m.pmut.Unlock() } // Request returns the specified data segment by reading it from local disk. // Implements the protocol.Model interface. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, size int) ([]byte, error) { // Verify that the requested file exists in the local model. m.fmut.RLock() r, ok := m.folderFiles[folder] m.fmut.RUnlock() if !ok { l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder) return nil, ErrNoSuchFile } lf := r.Get(protocol.LocalDeviceID, name) if lf.IsInvalid() || lf.IsDeleted() { if debug { l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, size, lf) } return nil, ErrInvalid } if offset > lf.Size() { if debug { l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, size) } return nil, ErrNoSuchFile } if debug && deviceID != protocol.LocalDeviceID { l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size) } m.fmut.RLock() fn := filepath.Join(m.folderCfgs[folder].Path, name) m.fmut.RUnlock() var reader io.ReaderAt var err error if lf.IsSymlink() { target, _, err := symlinks.Read(fn) if err != nil { return nil, err } reader = strings.NewReader(target) } else { reader, err = os.Open(fn) // XXX: Inefficient, should cache fd? if err != nil { return nil, err } defer reader.(*os.File).Close() } buf := make([]byte, size) _, err = reader.ReadAt(buf, offset) if err != nil { return nil, err } return buf, nil } // ReplaceLocal replaces the local folder index with the given list of files. func (m *Model) ReplaceLocal(folder string, fs []protocol.FileInfo) { m.fmut.RLock() m.folderFiles[folder].ReplaceWithDelete(protocol.LocalDeviceID, fs) m.fmut.RUnlock() } func (m *Model) CurrentFolderFile(folder string, file string) protocol.FileInfo { m.fmut.RLock() f := m.folderFiles[folder].Get(protocol.LocalDeviceID, file) m.fmut.RUnlock() return f } func (m *Model) CurrentGlobalFile(folder string, file string) protocol.FileInfo { m.fmut.RLock() f := m.folderFiles[folder].GetGlobal(file) m.fmut.RUnlock() return f } type cFiler struct { m *Model r string } // Implements scanner.CurrentFiler func (cf cFiler) CurrentFile(file string) protocol.FileInfo { return cf.m.CurrentFolderFile(cf.r, file) } // ConnectedTo returns true if we are connected to the named device. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool { m.pmut.RLock() _, ok := m.protoConn[deviceID] m.pmut.RUnlock() if ok { m.deviceWasSeen(deviceID) } return ok } func (m *Model) GetIgnores(folder string) ([]string, []string, error) { var lines []string m.fmut.RLock() cfg, ok := m.folderCfgs[folder] m.fmut.RUnlock() if !ok { return lines, nil, fmt.Errorf("Folder %s does not exist", folder) } fd, err := os.Open(filepath.Join(cfg.Path, ".stignore")) if err != nil { if os.IsNotExist(err) { return lines, nil, nil } l.Warnln("Loading .stignore:", err) return lines, nil, err } defer fd.Close() scanner := bufio.NewScanner(fd) for scanner.Scan() { lines = append(lines, strings.TrimSpace(scanner.Text())) } var patterns []string if matcher := m.folderIgnores[folder]; matcher != nil { patterns = matcher.Patterns() } return lines, patterns, nil } func (m *Model) SetIgnores(folder string, content []string) error { cfg, ok := m.folderCfgs[folder] if !ok { return fmt.Errorf("Folder %s does not exist", folder) } fd, err := ioutil.TempFile(cfg.Path, ".syncthing.stignore-"+folder) if err != nil { l.Warnln("Saving .stignore:", err) return err } defer os.Remove(fd.Name()) for _, line := range content { _, err = fmt.Fprintln(fd, line) if err != nil { l.Warnln("Saving .stignore:", err) return err } } err = fd.Close() if err != nil { l.Warnln("Saving .stignore:", err) return err } file := filepath.Join(cfg.Path, ".stignore") err = osutil.Rename(fd.Name(), file) if err != nil { l.Warnln("Saving .stignore:", err) return err } return m.ScanFolder(folder) } // AddConnection adds a new peer connection to the model. An initial index will // be sent to the connected peer, thereafter index updates whenever the local // folder changes. func (m *Model) AddConnection(rawConn io.Closer, protoConn protocol.Connection) { deviceID := protoConn.ID() m.pmut.Lock() if _, ok := m.protoConn[deviceID]; ok { panic("add existing device") } m.protoConn[deviceID] = protoConn if _, ok := m.rawConn[deviceID]; ok { panic("add existing device") } m.rawConn[deviceID] = rawConn cm := m.clusterConfig(deviceID) protoConn.ClusterConfig(cm) m.fmut.RLock() for _, folder := range m.deviceFolders[deviceID] { fs := m.folderFiles[folder] go sendIndexes(protoConn, folder, fs, m.folderIgnores[folder]) } m.fmut.RUnlock() m.pmut.Unlock() m.deviceWasSeen(deviceID) } func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference { m.fmut.Lock() defer m.fmut.Unlock() if sr, ok := m.deviceStatRefs[deviceID]; ok { return sr } else { sr = stats.NewDeviceStatisticsReference(m.db, deviceID) m.deviceStatRefs[deviceID] = sr return sr } } func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) { m.deviceStatRef(deviceID).WasSeen() } func sendIndexes(conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) { deviceID := conn.ID() name := conn.Name() var err error if debug { l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder) } minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores) for err == nil { time.Sleep(5 * time.Second) if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer { continue } minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores) } if debug { l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err) } } func sendIndexTo(initial bool, minLocalVer uint64, conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) (uint64, error) { deviceID := conn.ID() name := conn.Name() batch := make([]protocol.FileInfo, 0, indexBatchSize) currentBatchSize := 0 maxLocalVer := uint64(0) var err error fs.WithHave(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool { f := fi.(protocol.FileInfo) if f.LocalVersion <= minLocalVer { return true } if f.LocalVersion > maxLocalVer { maxLocalVer = f.LocalVersion } if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) { if debug { l.Debugln("not sending update for ignored/unsupported symlink", f) } return true } if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize { if initial { if err = conn.Index(folder, batch); err != nil { return false } if debug { l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize) } initial = false } else { if err = conn.IndexUpdate(folder, batch); err != nil { return false } if debug { l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize) } } batch = make([]protocol.FileInfo, 0, indexBatchSize) currentBatchSize = 0 } batch = append(batch, f) currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize return true }) if initial && err == nil { err = conn.Index(folder, batch) if debug && err == nil { l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch)) } } else if len(batch) > 0 && err == nil { err = conn.IndexUpdate(folder, batch) if debug && err == nil { l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch)) } } return maxLocalVer, err } func (m *Model) updateLocal(folder string, f protocol.FileInfo) { f.LocalVersion = 0 m.fmut.RLock() m.folderFiles[folder].Update(protocol.LocalDeviceID, []protocol.FileInfo{f}) m.fmut.RUnlock() events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{ "folder": folder, "name": f.Name, "modified": time.Unix(f.Modified, 0), "flags": fmt.Sprintf("0%o", f.Flags), "size": f.Size(), }) } func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte) ([]byte, error) { m.pmut.RLock() nc, ok := m.protoConn[deviceID] m.pmut.RUnlock() if !ok { return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID) } if debug { l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x", m, deviceID, folder, name, offset, size, hash) } return nc.Request(folder, name, offset, size) } func (m *Model) AddFolder(cfg config.FolderConfiguration) { if m.started { panic("cannot add folder to started model") } if len(cfg.ID) == 0 { panic("cannot add empty folder id") } m.fmut.Lock() m.folderCfgs[cfg.ID] = cfg m.folderFiles[cfg.ID] = files.NewSet(cfg.ID, m.db) m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices)) for i, device := range cfg.Devices { m.folderDevices[cfg.ID][i] = device.DeviceID m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID) } m.addedFolder = true m.fmut.Unlock() } func (m *Model) ScanFolders() { m.fmut.RLock() var folders = make([]string, 0, len(m.folderCfgs)) for folder := range m.folderCfgs { folders = append(folders, folder) } m.fmut.RUnlock() var wg sync.WaitGroup wg.Add(len(folders)) for _, folder := range folders { folder := folder go func() { err := m.ScanFolder(folder) if err != nil { m.cfg.InvalidateFolder(folder, err.Error()) } wg.Done() }() } wg.Wait() } func (m *Model) ScanFolder(folder string) error { return m.ScanFolderSub(folder, "") } func (m *Model) ScanFolderSub(folder, sub string) error { if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) { return errors.New("invalid subpath") } m.fmut.RLock() fs, ok := m.folderFiles[folder] dir := m.folderCfgs[folder].Path ignores, _ := ignore.Load(filepath.Join(dir, ".stignore"), m.cfg.Options().CacheIgnoredFiles) m.folderIgnores[folder] = ignores w := &scanner.Walker{ Dir: dir, Sub: sub, Matcher: ignores, BlockSize: protocol.BlockSize, TempNamer: defTempNamer, CurrentFiler: cFiler{m, folder}, IgnorePerms: m.folderCfgs[folder].IgnorePerms, } m.fmut.RUnlock() if !ok { return errors.New("no such folder") } m.setState(folder, FolderScanning) fchan, err := w.Walk() if err != nil { return err } batchSize := 100 batch := make([]protocol.FileInfo, 0, batchSize) for f := range fchan { events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{ "folder": folder, "name": f.Name, "modified": time.Unix(f.Modified, 0), "flags": fmt.Sprintf("0%o", f.Flags), "size": f.Size(), }) if len(batch) == batchSize { fs.Update(protocol.LocalDeviceID, batch) batch = batch[:0] } batch = append(batch, f) } if len(batch) > 0 { fs.Update(protocol.LocalDeviceID, batch) } batch = batch[:0] // TODO: We should limit the Have scanning to start at sub seenPrefix := false fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool { f := fi.(protocol.FileInfoTruncated) if !strings.HasPrefix(f.Name, sub) { // Return true so that we keep iterating, until we get to the part // of the tree we are interested in. Then return false so we stop // iterating when we've passed the end of the subtree. return !seenPrefix } seenPrefix = true if !f.IsDeleted() { if f.IsInvalid() { return true } if len(batch) == batchSize { fs.Update(protocol.LocalDeviceID, batch) batch = batch[:0] } if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) { // File has been ignored or an unsupported symlink. Set invalid bit. l.Debugln("setting invalid bit on ignored", f) nf := protocol.FileInfo{ Name: f.Name, Flags: f.Flags | protocol.FlagInvalid, Modified: f.Modified, Version: f.Version, // The file is still the same, so don't bump version } events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{ "folder": folder, "name": f.Name, "modified": time.Unix(f.Modified, 0), "flags": fmt.Sprintf("0%o", f.Flags), "size": f.Size(), }) batch = append(batch, nf) } else if _, err := os.Lstat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) { // File has been deleted nf := protocol.FileInfo{ Name: f.Name, Flags: f.Flags | protocol.FlagDeleted, Modified: f.Modified, Version: lamport.Default.Tick(f.Version), } events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{ "folder": folder, "name": f.Name, "modified": time.Unix(f.Modified, 0), "flags": fmt.Sprintf("0%o", f.Flags), "size": f.Size(), }) batch = append(batch, nf) } } return true }) if len(batch) > 0 { fs.Update(protocol.LocalDeviceID, batch) } m.setState(folder, FolderIdle) return nil } // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage { cm := protocol.ClusterConfigMessage{ ClientName: m.clientName, ClientVersion: m.clientVersion, Options: []protocol.Option{ { Key: "name", Value: m.deviceName, }, }, } m.fmut.RLock() for _, folder := range m.deviceFolders[device] { cr := protocol.Folder{ ID: folder, } for _, device := range m.folderDevices[folder] { // DeviceID is a value type, but with an underlying array. Copy it // so we don't grab aliases to the same array later on in device[:] device := device // TODO: Set read only bit when relevant cn := protocol.Device{ ID: device[:], Flags: protocol.FlagShareTrusted, } if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer { cn.Flags |= protocol.FlagIntroducer } cr.Devices = append(cr.Devices, cn) } cm.Folders = append(cm.Folders, cr) } m.fmut.RUnlock() return cm } func (m *Model) setState(folder string, state folderState) { m.smut.Lock() oldState := m.folderState[folder] changed, ok := m.folderStateChanged[folder] if state != oldState { m.folderState[folder] = state m.folderStateChanged[folder] = time.Now() eventData := map[string]interface{}{ "folder": folder, "to": state.String(), } if ok { eventData["duration"] = time.Since(changed).Seconds() eventData["from"] = oldState.String() } events.Default.Log(events.StateChanged, eventData) } m.smut.Unlock() } func (m *Model) State(folder string) (string, time.Time) { m.smut.RLock() state := m.folderState[folder] changed := m.folderStateChanged[folder] m.smut.RUnlock() return state.String(), changed } func (m *Model) Override(folder string) { m.fmut.RLock() fs := m.folderFiles[folder] m.fmut.RUnlock() m.setState(folder, FolderScanning) batch := make([]protocol.FileInfo, 0, indexBatchSize) fs.WithNeed(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool { need := fi.(protocol.FileInfo) if len(batch) == indexBatchSize { fs.Update(protocol.LocalDeviceID, batch) batch = batch[:0] } have := fs.Get(protocol.LocalDeviceID, need.Name) if have.Name != need.Name { // We are missing the file need.Flags |= protocol.FlagDeleted need.Blocks = nil } else { // We have the file, replace with our version need = have } need.Version = lamport.Default.Tick(need.Version) need.LocalVersion = 0 batch = append(batch, need) return true }) if len(batch) > 0 { fs.Update(protocol.LocalDeviceID, batch) } m.setState(folder, FolderIdle) } // CurrentLocalVersion returns the change version for the given folder. // This is guaranteed to increment if the contents of the local folder has // changed. func (m *Model) CurrentLocalVersion(folder string) uint64 { m.fmut.RLock() fs, ok := m.folderFiles[folder] m.fmut.RUnlock() if !ok { // The folder might not exist, since this can be called with a user // specified folder name from the REST interface. return 0 } return fs.LocalVersion(protocol.LocalDeviceID) } // RemoteLocalVersion returns the change version for the given folder, as // sent by remote peers. This is guaranteed to increment if the contents of // the remote or global folder has changed. func (m *Model) RemoteLocalVersion(folder string) uint64 { m.fmut.RLock() defer m.fmut.RUnlock() fs, ok := m.folderFiles[folder] if !ok { // The folder might not exist, since this can be called with a user // specified folder name from the REST interface. return 0 } var ver uint64 for _, n := range m.folderDevices[folder] { ver += fs.LocalVersion(n) } return ver } func (m *Model) availability(folder string, file string) []protocol.DeviceID { // Acquire this lock first, as the value returned from foldersFiles can // gen heavily modified on Close() m.pmut.RLock() defer m.pmut.RUnlock() m.fmut.RLock() fs, ok := m.folderFiles[folder] m.fmut.RUnlock() if !ok { return nil } availableDevices := []protocol.DeviceID{} for _, device := range fs.Availability(file) { _, ok := m.protoConn[device] if ok { availableDevices = append(availableDevices, device) } } return availableDevices } func (m *Model) String() string { return fmt.Sprintf("model@%p", m) } func (m *Model) leveldbPanicWorkaround() { // When an inconsistency is detected in leveldb we panic(). This is // appropriate because it should never happen, but currently it does for // some reason. However it only seems to trigger in the asynchronous full- // database scans that happen due to REST and usage-reporting calls. In // those places we defer to this workaround to catch the panic instead of // taking down syncthing. // This is just a band-aid and should be removed as soon as we have found // a real root cause. if pnc := recover(); pnc != nil { if err, ok := pnc.(error); ok && strings.Contains(err.Error(), "leveldb") { l.Infoln("recovered:", err) } else { // Any non-leveldb error is genuine and should continue panicing. panic(err) } } } func symlinkInvalid(isLink bool) bool { if !symlinks.Supported && isLink { SymlinkWarning.Do(func() { l.Warnln("Symlinks are unsupported as they require Administrator priviledges. This might cause your folder to appear out of sync.") }) return true } return false }
internal/model/model.go
1
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.9974283576011658, 0.060945551842451096, 0.00016107359260786325, 0.00017348042456433177, 0.23230163753032684 ]
{ "id": 7, "code_window": [ "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n", "\t\treturn 128\n", "\t}\n", "\tif f.NumBlocks < 2 {\n", "\t\treturn BlockSize / 2\n", "\t} else {\n", "\t\treturn int64(f.NumBlocks-1)*BlockSize + BlockSize/2\n", "\t}\n", "}\n", "\n", "func (f FileInfoTruncated) IsDeleted() bool {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn BlocksToSize(f.NumBlocks)\n" ], "file_path": "internal/protocol/message.go", "type": "replace", "edit_start_line_idx": 88 }
// Copyright (c) 2014, Suryandaru Triandana <[email protected]> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package errors provides common error types used throughout leveldb. package errors import ( "errors" "fmt" "github.com/syndtr/goleveldb/leveldb/storage" "github.com/syndtr/goleveldb/leveldb/util" ) var ( ErrNotFound = New("leveldb: not found") ErrReleased = util.ErrReleased ErrHasReleaser = util.ErrHasReleaser ) // New returns an error that formats as the given text. func New(text string) error { return errors.New(text) } // ErrCorrupted is the type that wraps errors that indicate corruption in // the database. type ErrCorrupted struct { File *storage.FileInfo Err error } func (e *ErrCorrupted) Error() string { if e.File != nil { return fmt.Sprintf("%v [file=%v]", e.Err, e.File) } else { return e.Err.Error() } } // NewErrCorrupted creates new ErrCorrupted error. func NewErrCorrupted(f storage.File, err error) error { return &ErrCorrupted{storage.NewFileInfo(f), err} } // IsCorrupted returns a boolean indicating whether the error is indicating // a corruption. func IsCorrupted(err error) bool { switch err.(type) { case *ErrCorrupted: return true } return false } // ErrMissingFiles is the type that indicating a corruption due to missing // files. type ErrMissingFiles struct { Files []*storage.FileInfo } func (e *ErrMissingFiles) Error() string { return "file missing" } // SetFile sets 'file info' of the given error with the given file. // Currently only ErrCorrupted is supported, otherwise will do nothing. func SetFile(err error, f storage.File) error { switch x := err.(type) { case *ErrCorrupted: x.File = storage.NewFileInfo(f) return x } return err }
Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go
0
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.003906749188899994, 0.0009723786497488618, 0.00016371335368603468, 0.0002790357102639973, 0.0013099545612931252 ]
{ "id": 7, "code_window": [ "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n", "\t\treturn 128\n", "\t}\n", "\tif f.NumBlocks < 2 {\n", "\t\treturn BlockSize / 2\n", "\t} else {\n", "\t\treturn int64(f.NumBlocks-1)*BlockSize + BlockSize/2\n", "\t}\n", "}\n", "\n", "func (f FileInfoTruncated) IsDeleted() bool {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn BlocksToSize(f.NumBlocks)\n" ], "file_path": "internal/protocol/message.go", "type": "replace", "edit_start_line_idx": 88 }
// ************************************************************ // This file is automatically generated by genxdr. Do not edit. // ************************************************************ package files import ( "bytes" "io" "github.com/calmh/xdr" ) /* fileVersion Structure: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + version (64 bits) + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Length of device | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / \ device (variable length) \ / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ struct fileVersion { unsigned hyper version; opaque device<>; } */ func (o fileVersion) EncodeXDR(w io.Writer) (int, error) { var xw = xdr.NewWriter(w) return o.encodeXDR(xw) } func (o fileVersion) MarshalXDR() ([]byte, error) { return o.AppendXDR(make([]byte, 0, 128)) } func (o fileVersion) MustMarshalXDR() []byte { bs, err := o.MarshalXDR() if err != nil { panic(err) } return bs } func (o fileVersion) AppendXDR(bs []byte) ([]byte, error) { var aw = xdr.AppendWriter(bs) var xw = xdr.NewWriter(&aw) _, err := o.encodeXDR(xw) return []byte(aw), err } func (o fileVersion) encodeXDR(xw *xdr.Writer) (int, error) { xw.WriteUint64(o.version) xw.WriteBytes(o.device) return xw.Tot(), xw.Error() } func (o *fileVersion) DecodeXDR(r io.Reader) error { xr := xdr.NewReader(r) return o.decodeXDR(xr) } func (o *fileVersion) UnmarshalXDR(bs []byte) error { var br = bytes.NewReader(bs) var xr = xdr.NewReader(br) return o.decodeXDR(xr) } func (o *fileVersion) decodeXDR(xr *xdr.Reader) error { o.version = xr.ReadUint64() o.device = xr.ReadBytes() return xr.Error() } /* versionList Structure: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Number of versions | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / \ Zero or more fileVersion Structures \ / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ struct versionList { fileVersion versions<>; } */ func (o versionList) EncodeXDR(w io.Writer) (int, error) { var xw = xdr.NewWriter(w) return o.encodeXDR(xw) } func (o versionList) MarshalXDR() ([]byte, error) { return o.AppendXDR(make([]byte, 0, 128)) } func (o versionList) MustMarshalXDR() []byte { bs, err := o.MarshalXDR() if err != nil { panic(err) } return bs } func (o versionList) AppendXDR(bs []byte) ([]byte, error) { var aw = xdr.AppendWriter(bs) var xw = xdr.NewWriter(&aw) _, err := o.encodeXDR(xw) return []byte(aw), err } func (o versionList) encodeXDR(xw *xdr.Writer) (int, error) { xw.WriteUint32(uint32(len(o.versions))) for i := range o.versions { _, err := o.versions[i].encodeXDR(xw) if err != nil { return xw.Tot(), err } } return xw.Tot(), xw.Error() } func (o *versionList) DecodeXDR(r io.Reader) error { xr := xdr.NewReader(r) return o.decodeXDR(xr) } func (o *versionList) UnmarshalXDR(bs []byte) error { var br = bytes.NewReader(bs) var xr = xdr.NewReader(br) return o.decodeXDR(xr) } func (o *versionList) decodeXDR(xr *xdr.Reader) error { _versionsSize := int(xr.ReadUint32()) o.versions = make([]fileVersion, _versionsSize) for i := range o.versions { (&o.versions[i]).decodeXDR(xr) } return xr.Error() }
internal/files/leveldb_xdr.go
0
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.00030726901604793966, 0.00020622862211894244, 0.00016603308904450387, 0.00019372509268578142, 0.00003654815009213053 ]
{ "id": 7, "code_window": [ "// Returns a statistical guess on the size, not the exact figure\n", "func (f FileInfoTruncated) Size() int64 {\n", "\tif f.IsDeleted() || f.IsDirectory() {\n", "\t\treturn 128\n", "\t}\n", "\tif f.NumBlocks < 2 {\n", "\t\treturn BlockSize / 2\n", "\t} else {\n", "\t\treturn int64(f.NumBlocks-1)*BlockSize + BlockSize/2\n", "\t}\n", "}\n", "\n", "func (f FileInfoTruncated) IsDeleted() bool {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn BlocksToSize(f.NumBlocks)\n" ], "file_path": "internal/protocol/message.go", "type": "replace", "edit_start_line_idx": 88 }
<configuration version="2"> <folder id="default" directory="s2" ro="false" ignorePerms="false"> <device id="I6KAH76-66SLLLB-5PFXSOA-UFJCDZC-YAOMLEK-CP2GB32-BV5RQST-3PSROAU"></device> <device id="JMFJCXB-GZDE4BN-OCJE3VF-65GYZNU-AIVJRET-3J6HMRQ-AUQIGJO-FKNHMQU"></device> <versioning type="simple"> <param key="keep" val="5"></param> </versioning> </folder> <device id="I6KAH76-66SLLLB-5PFXSOA-UFJCDZC-YAOMLEK-CP2GB32-BV5RQST-3PSROAU" name="f1"> <address>127.0.0.1:22001</address> </device> <device id="JMFJCXB-GZDE4BN-OCJE3VF-65GYZNU-AIVJRET-3J6HMRQ-AUQIGJO-FKNHMQU" name="f2"> <address>127.0.0.1:22002</address> </device> <gui enabled="true" tls="false"> <address>127.0.0.1:8082</address> <apikey>abc123</apikey> </gui> <options> <listenAddress>127.0.0.1:22002</listenAddress> <globalAnnounceServer>announce.syncthing.net:22026</globalAnnounceServer> <globalAnnounceEnabled>false</globalAnnounceEnabled> <localAnnounceEnabled>true</localAnnounceEnabled> <localAnnouncePort>21025</localAnnouncePort> <parallelRequests>16</parallelRequests> <maxSendKbps>0</maxSendKbps> <rescanIntervalS>15</rescanIntervalS> <reconnectionIntervalS>5</reconnectionIntervalS> <maxChangeKbps>10000</maxChangeKbps> <startBrowser>false</startBrowser> <upnpEnabled>false</upnpEnabled> <urAccepted>-1</urAccepted> </options> </configuration>
test/f2/config.xml
0
https://github.com/syncthing/syncthing/commit/59a85c1d751c85e585ec93398c3ba5c50bdef91f
[ 0.00018313803593628109, 0.0001716504048090428, 0.0001643080759095028, 0.00016957774641923606, 0.000007069681942084571 ]
{ "id": 0, "code_window": [ "func Inventory() ManagerInventory {\n", "\treturn ManagerInventory{\n", "\t\tCheckMethod: {\n", "\t\t\tnewDenialsManager(),\n", "\t\t\tnewListsManager(),\n", "\t\t\tnewQuotasManager(), // TODO: Remove once proxy uses the Quota method\n", "\t\t},\n", "\n", "\t\tReportMethod: {\n", "\t\t\tnewApplicationLogsManager(),\n", "\t\t\tnewAccessLogsManager(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/inventory.go", "type": "replace", "edit_start_line_idx": 25 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "fmt" "strconv" "sync/atomic" ptypes "github.com/gogo/protobuf/types" "github.com/golang/glog" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/mixer/pkg/adapter" aconfig "istio.io/mixer/pkg/aspect/config" "istio.io/mixer/pkg/attribute" "istio.io/mixer/pkg/config" "istio.io/mixer/pkg/config/descriptor" cpb "istio.io/mixer/pkg/config/proto" "istio.io/mixer/pkg/expr" "istio.io/mixer/pkg/status" ) type ( quotasManager struct { dedupCounter int64 } quotaInfo struct { definition *adapter.QuotaDefinition labels map[string]string } quotasWrapper struct { manager *quotasManager aspect adapter.QuotasAspect metadata map[string]*quotaInfo adapter string } ) // newQuotasManager returns a manager for the quotas aspect. func newQuotasManager() Manager { return &quotasManager{} } // NewAspect creates a quota aspect. func (m *quotasManager) NewAspect(c *cpb.Combined, a adapter.Builder, env adapter.Env) (Wrapper, error) { params := c.Aspect.Params.(*aconfig.QuotasParams) // TODO: get this from config if len(params.Quotas) == 0 { params = &aconfig.QuotasParams{ Quotas: []*aconfig.QuotasParams_Quota{ {DescriptorName: "RequestCount"}, }, } } // TODO: get this from config desc := []dpb.QuotaDescriptor{ { Name: "RequestCount", MaxAmount: 5, Expiration: &ptypes.Duration{Seconds: 1}, }, } metadata := make(map[string]*quotaInfo, len(desc)) defs := make(map[string]*adapter.QuotaDefinition, len(desc)) for _, d := range desc { quota := findQuota(params.Quotas, d.Name) if quota == nil { env.Logger().Warningf("No quota found for descriptor %s, skipping it", d.Name) continue } // TODO: once we plumb descriptors into the validation, remove this err: no descriptor should make it through validation // if it cannot be converted into a QuotaDefinition, so we should never have to handle the error case. def, err := quotaDefinitionFromProto(&d) if err != nil { _ = env.Logger().Errorf("Failed to convert quota descriptor '%s' to definition with err: %s; skipping it.", d.Name, err) continue } defs[d.Name] = def metadata[d.Name] = &quotaInfo{ labels: quota.Labels, definition: def, } } asp, err := a.(adapter.QuotasBuilder).NewQuotasAspect(env, c.Builder.Params.(adapter.Config), defs) if err != nil { return nil, err } return &quotasWrapper{ manager: m, metadata: metadata, aspect: asp, adapter: a.Name(), }, nil } func (*quotasManager) Kind() Kind { return QuotasKind } func (*quotasManager) DefaultConfig() config.AspectParams { return &aconfig.QuotasParams{} } func (*quotasManager) ValidateConfig(config.AspectParams, expr.Validator, descriptor.Finder) (ce *adapter.ConfigErrors) { return } func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output { qma, ok := ma.(*QuotaMethodArgs) // TODO: this conditional is only necessary because we currently perform quota // checking via the Check API, which doesn't generate a QuotaMethodArgs if !ok { qma = &QuotaMethodArgs{ Quota: "RequestCount", Amount: 1, DeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16), BestEffort: false, } } info, ok := w.metadata[qma.Quota] if !ok { msg := fmt.Sprintf("Unknown quota '%s' requested", qma.Quota) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } labels, err := evalAll(info.labels, attrs, mapper) if err != nil { msg := fmt.Sprintf("Unable to evaluate labels for quota '%s' with err: %s", qma.Quota, err) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } qa := adapter.QuotaArgs{ Definition: info.definition, Labels: labels, QuotaAmount: qma.Amount, DeduplicationID: qma.DeduplicationID, } var qr adapter.QuotaResult if glog.V(2) { glog.Info("Invoking adapter %s for quota %s with amount %d", w.adapter, qa.Definition.Name, qa.QuotaAmount) } if qma.BestEffort { qr, err = w.aspect.AllocBestEffort(qa) } else { qr, err = w.aspect.Alloc(qa) } if err != nil { glog.Errorf("Quota allocation failed: %v", err) return Output{Status: status.WithError(err)} } if qr.Amount == 0 { msg := fmt.Sprintf("Unable to allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) glog.Warning(msg) return Output{Status: status.WithResourceExhausted(msg)} } if glog.V(2) { glog.Infof("Allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) } return Output{ Status: status.OK, Response: &QuotaMethodResp{ Amount: qr.Amount, Expiration: qr.Expiration, }} } func (w *quotasWrapper) Close() error { return w.aspect.Close() } func findQuota(quotas []*aconfig.QuotasParams_Quota, name string) *aconfig.QuotasParams_Quota { for _, q := range quotas { if q.DescriptorName == name { return q } } return nil } func quotaDefinitionFromProto(desc *dpb.QuotaDescriptor) (*adapter.QuotaDefinition, error) { labels := make(map[string]adapter.LabelType, len(desc.Labels)) for _, label := range desc.Labels { l, err := valueTypeToLabelType(label.ValueType) if err != nil { return nil, fmt.Errorf("descriptor '%s' label '%s' failed to convert label type value '%v' from proto with err: %s", desc.Name, label.Name, label.ValueType, err) } labels[label.Name] = l } dur, _ := ptypes.DurationFromProto(desc.Expiration) return &adapter.QuotaDefinition{ MaxAmount: desc.MaxAmount, Expiration: dur, Description: desc.Description, DisplayName: desc.DisplayName, Name: desc.Name, Labels: labels, }, nil }
mixer/pkg/aspect/quotasManager.go
1
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.004080708604305983, 0.0008276095031760633, 0.0001736619888106361, 0.00022440458997152746, 0.0010324568720534444 ]
{ "id": 0, "code_window": [ "func Inventory() ManagerInventory {\n", "\treturn ManagerInventory{\n", "\t\tCheckMethod: {\n", "\t\t\tnewDenialsManager(),\n", "\t\t\tnewListsManager(),\n", "\t\t\tnewQuotasManager(), // TODO: Remove once proxy uses the Quota method\n", "\t\t},\n", "\n", "\t\tReportMethod: {\n", "\t\t\tnewApplicationLogsManager(),\n", "\t\t\tnewAccessLogsManager(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/inventory.go", "type": "replace", "edit_start_line_idx": 25 }
#!/bin/bash set -x # This file should be replaced by bazel # # This file works around the issue that go jsonpb does not support # ptype.Struct parsing yet # https://github.com/istio/mixer/issues/134 # It does so by replacing Struct with interface{}. # From this point on the protos will only have a valid external representation as json. WD=$(dirname $0) WD=$(cd $WD; pwd) PKG=$(dirname $WD) BUILD_DIR=$(dirname $(dirname $(readlink ${WD}/../../../bazel-mixer))) ISTIO_API=${BUILD_DIR}/external/com_github_istio_api cd ${ISTIO_API} CKSUM=$(cksum mixer/v1/config/cfg.proto) # protoc keeps the directory structure leading up to the proto file, so it creates # the dir ${WD}/mixer/v1/config/. We don't want that, so we'll move the pb.go file # out and remove the dir. protoc mixer/v1/config/cfg.proto --go_out=${WD} mv ${WD}/mixer/v1/config/cfg.pb.go ${WD}/cfg.pb.go rm -rd ${WD}/mixer cd ${WD} TMPF="_cfg.pb.go" PB="cfg.pb.go" echo "// POST PROCESSED USING by build_cfg.sh" > ${TMPF} echo "// ${CKSUM}" >> ${TMPF} cat ${PB} >> ${TMPF} mv ${TMPF} ${PB} sed -i 's/*google_protobuf.Struct/interface{}/g' ${PB} sed -i 's/mixer\/v1\/config\/descriptor/istio.io\/api\/mixer\/v1\/config\/descriptor/g' ${PB} goimports -w ${PB}
mixer/pkg/config/proto/build_cfg.sh
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.0001767299690982327, 0.00017380912322551012, 0.00017115470836870372, 0.00017367590044159442, 0.0000021497244233614765 ]
{ "id": 0, "code_window": [ "func Inventory() ManagerInventory {\n", "\treturn ManagerInventory{\n", "\t\tCheckMethod: {\n", "\t\t\tnewDenialsManager(),\n", "\t\t\tnewListsManager(),\n", "\t\t\tnewQuotasManager(), // TODO: Remove once proxy uses the Quota method\n", "\t\t},\n", "\n", "\t\tReportMethod: {\n", "\t\t\tnewApplicationLogsManager(),\n", "\t\t\tnewAccessLogsManager(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/inventory.go", "type": "replace", "edit_start_line_idx": 25 }
// Copyright 2017 the Istio Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prometheus import ( "fmt" "net/http" "testing" "istio.io/mixer/pkg/adapter/test" ) func TestServer(t *testing.T) { testAddr := "127.0.0.1:9992" s := newServer(testAddr) if err := s.Start(test.NewEnv(t)); err != nil { t.Fatalf("Start() failed unexpectedly: %v", err) } testURL := fmt.Sprintf("http://%s%s", testAddr, metricsPath) // verify a response is returned from "/metrics" resp, err := http.Get(testURL) if err != nil { t.Fatalf("Failed to retrieve '%s' path: %v", metricsPath, err) } if resp.StatusCode != http.StatusOK { t.Errorf("http.GET => %v, wanted '%v'", resp.StatusCode, http.StatusOK) } _ = resp.Body.Close() s2 := newServer(testAddr) if err := s2.Start(test.NewEnv(t)); err == nil { t.Fatal("Start() succeeded, expecting a failure") } if err := s.Close(); err != nil { t.Errorf("Failed to close server properly: %v", err) } }
mixer/adapter/prometheus/server_test.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.00017955226940102875, 0.0001761530729709193, 0.00017324239888694137, 0.0001761142339091748, 0.000002401884557912126 ]
{ "id": 0, "code_window": [ "func Inventory() ManagerInventory {\n", "\treturn ManagerInventory{\n", "\t\tCheckMethod: {\n", "\t\t\tnewDenialsManager(),\n", "\t\t\tnewListsManager(),\n", "\t\t\tnewQuotasManager(), // TODO: Remove once proxy uses the Quota method\n", "\t\t},\n", "\n", "\t\tReportMethod: {\n", "\t\t\tnewApplicationLogsManager(),\n", "\t\t\tnewAccessLogsManager(),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/inventory.go", "type": "replace", "edit_start_line_idx": 25 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file contains an implementation of an opentracing carrier built on top of the mixer's attribute bag. This allows // clients to inject their span metadata into the set of attributes its reporting to the mixer, and lets the mixer extract // span information propagated as attributes in a standard call to the mixer. package tracing import ( "context" "strings" "istio.io/mixer/pkg/attribute" ) const ( // TODO: elevate this to a global registry, especially since non-go clients (the proxy) will need to use the same prefix prefix = ":istio-ot-" prefixLength = len(prefix) ) // AttributeCarrier implements opentracing's TextMapWriter and TextMapReader interfaces using Istio's attribute system. type AttributeCarrier struct { mb *attribute.MutableBag } // NewCarrier initializes a carrier that can be used to modify the attributes in the current request context. func NewCarrier(bag *attribute.MutableBag) *AttributeCarrier { return &AttributeCarrier{mb: bag.Child()} } type carrierKey struct{} // NewContext annotates the provided context with the provided carrier and returns the updated context. func NewContext(ctx context.Context, carrier *AttributeCarrier) context.Context { return context.WithValue(ctx, carrierKey{}, carrier) } // FromContext extracts the AttributeCarrier from the provided context, or returns nil if one is not found. func FromContext(ctx context.Context) *AttributeCarrier { mc := ctx.Value(carrierKey{}) if c, ok := mc.(*AttributeCarrier); ok { return c } return nil } // ForeachKey iterates over the keys that correspond to string attributes, filtering keys for the prefix used by the // AttributeCarrier to denote opentracing attributes. The AttributeCarrier specific prefix is stripped from the key // before its passed to handler. func (c *AttributeCarrier) ForeachKey(handler func(key, val string) error) error { keys := c.mb.Names() for _, key := range keys { if strings.HasPrefix(key, prefix) { if val, found := c.mb.Get(key); found { s, ok := val.(string) if ok { if err := handler(key[prefixLength:], s); err != nil { return err } } } } } return nil } // Set adds (key, val) to the set of string attributes in the request scope. It prefixes the key with an istio-private // string to avoid collisions with other attributes when arbitrary tracer implementations are used. func (c *AttributeCarrier) Set(key, val string) { c.mb.Set(prefix+key, val) }
mixer/pkg/tracing/attributes.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.00028370856307446957, 0.00018244911916553974, 0.0001638418616494164, 0.00016871128173079342, 0.000036079927667742595 ]
{ "id": 1, "code_window": [ "package aspect\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"strconv\"\n", "\t\"sync/atomic\"\n", "\n", "\tptypes \"github.com/gogo/protobuf/types\"\n", "\t\"github.com/golang/glog\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 18 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "fmt" "strconv" "sync/atomic" ptypes "github.com/gogo/protobuf/types" "github.com/golang/glog" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/mixer/pkg/adapter" aconfig "istio.io/mixer/pkg/aspect/config" "istio.io/mixer/pkg/attribute" "istio.io/mixer/pkg/config" "istio.io/mixer/pkg/config/descriptor" cpb "istio.io/mixer/pkg/config/proto" "istio.io/mixer/pkg/expr" "istio.io/mixer/pkg/status" ) type ( quotasManager struct { dedupCounter int64 } quotaInfo struct { definition *adapter.QuotaDefinition labels map[string]string } quotasWrapper struct { manager *quotasManager aspect adapter.QuotasAspect metadata map[string]*quotaInfo adapter string } ) // newQuotasManager returns a manager for the quotas aspect. func newQuotasManager() Manager { return &quotasManager{} } // NewAspect creates a quota aspect. func (m *quotasManager) NewAspect(c *cpb.Combined, a adapter.Builder, env adapter.Env) (Wrapper, error) { params := c.Aspect.Params.(*aconfig.QuotasParams) // TODO: get this from config if len(params.Quotas) == 0 { params = &aconfig.QuotasParams{ Quotas: []*aconfig.QuotasParams_Quota{ {DescriptorName: "RequestCount"}, }, } } // TODO: get this from config desc := []dpb.QuotaDescriptor{ { Name: "RequestCount", MaxAmount: 5, Expiration: &ptypes.Duration{Seconds: 1}, }, } metadata := make(map[string]*quotaInfo, len(desc)) defs := make(map[string]*adapter.QuotaDefinition, len(desc)) for _, d := range desc { quota := findQuota(params.Quotas, d.Name) if quota == nil { env.Logger().Warningf("No quota found for descriptor %s, skipping it", d.Name) continue } // TODO: once we plumb descriptors into the validation, remove this err: no descriptor should make it through validation // if it cannot be converted into a QuotaDefinition, so we should never have to handle the error case. def, err := quotaDefinitionFromProto(&d) if err != nil { _ = env.Logger().Errorf("Failed to convert quota descriptor '%s' to definition with err: %s; skipping it.", d.Name, err) continue } defs[d.Name] = def metadata[d.Name] = &quotaInfo{ labels: quota.Labels, definition: def, } } asp, err := a.(adapter.QuotasBuilder).NewQuotasAspect(env, c.Builder.Params.(adapter.Config), defs) if err != nil { return nil, err } return &quotasWrapper{ manager: m, metadata: metadata, aspect: asp, adapter: a.Name(), }, nil } func (*quotasManager) Kind() Kind { return QuotasKind } func (*quotasManager) DefaultConfig() config.AspectParams { return &aconfig.QuotasParams{} } func (*quotasManager) ValidateConfig(config.AspectParams, expr.Validator, descriptor.Finder) (ce *adapter.ConfigErrors) { return } func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output { qma, ok := ma.(*QuotaMethodArgs) // TODO: this conditional is only necessary because we currently perform quota // checking via the Check API, which doesn't generate a QuotaMethodArgs if !ok { qma = &QuotaMethodArgs{ Quota: "RequestCount", Amount: 1, DeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16), BestEffort: false, } } info, ok := w.metadata[qma.Quota] if !ok { msg := fmt.Sprintf("Unknown quota '%s' requested", qma.Quota) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } labels, err := evalAll(info.labels, attrs, mapper) if err != nil { msg := fmt.Sprintf("Unable to evaluate labels for quota '%s' with err: %s", qma.Quota, err) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } qa := adapter.QuotaArgs{ Definition: info.definition, Labels: labels, QuotaAmount: qma.Amount, DeduplicationID: qma.DeduplicationID, } var qr adapter.QuotaResult if glog.V(2) { glog.Info("Invoking adapter %s for quota %s with amount %d", w.adapter, qa.Definition.Name, qa.QuotaAmount) } if qma.BestEffort { qr, err = w.aspect.AllocBestEffort(qa) } else { qr, err = w.aspect.Alloc(qa) } if err != nil { glog.Errorf("Quota allocation failed: %v", err) return Output{Status: status.WithError(err)} } if qr.Amount == 0 { msg := fmt.Sprintf("Unable to allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) glog.Warning(msg) return Output{Status: status.WithResourceExhausted(msg)} } if glog.V(2) { glog.Infof("Allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) } return Output{ Status: status.OK, Response: &QuotaMethodResp{ Amount: qr.Amount, Expiration: qr.Expiration, }} } func (w *quotasWrapper) Close() error { return w.aspect.Close() } func findQuota(quotas []*aconfig.QuotasParams_Quota, name string) *aconfig.QuotasParams_Quota { for _, q := range quotas { if q.DescriptorName == name { return q } } return nil } func quotaDefinitionFromProto(desc *dpb.QuotaDescriptor) (*adapter.QuotaDefinition, error) { labels := make(map[string]adapter.LabelType, len(desc.Labels)) for _, label := range desc.Labels { l, err := valueTypeToLabelType(label.ValueType) if err != nil { return nil, fmt.Errorf("descriptor '%s' label '%s' failed to convert label type value '%v' from proto with err: %s", desc.Name, label.Name, label.ValueType, err) } labels[label.Name] = l } dur, _ := ptypes.DurationFromProto(desc.Expiration) return &adapter.QuotaDefinition{ MaxAmount: desc.MaxAmount, Expiration: dur, Description: desc.Description, DisplayName: desc.DisplayName, Name: desc.Name, Labels: labels, }, nil }
mixer/pkg/aspect/quotasManager.go
1
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.016085665673017502, 0.0012050910154357553, 0.00016438736929558218, 0.00019251840421929955, 0.003301767399534583 ]
{ "id": 1, "code_window": [ "package aspect\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"strconv\"\n", "\t\"sync/atomic\"\n", "\n", "\tptypes \"github.com/gogo/protobuf/types\"\n", "\t\"github.com/golang/glog\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 18 }
// Copyright 2017 The Istio Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "testing" ) func TestKinds(t *testing.T) { i := 0 for k := range kindToString { str := k.String() kind, ok := ParseKind(str) if !ok { t.Error("Got !ok, expecting true") } if kind != k { t.Errorf("%d: Got %v, expected %v", i, kind, k) } i++ } }
mixer/pkg/aspect/kind_test.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.0002061567356577143, 0.00018079948495142162, 0.0001673575898166746, 0.00017484178533777595, 0.000014958144674892537 ]
{ "id": 1, "code_window": [ "package aspect\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"strconv\"\n", "\t\"sync/atomic\"\n", "\n", "\tptypes \"github.com/gogo/protobuf/types\"\n", "\t\"github.com/golang/glog\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 18 }
# Istio ServiceGraph *WARNING WARNING WARNING WARNING* These services are examples ONLY. This code may change at will, or be removed entirely without warning. Taking any dependency on this code is done at your own peril. ## Services ### Servicegraph service Defined in `servicegraph/cmd/server`, this provides a basic HTTP API for generating servicegraphs. It exposes the following endpoints: - `/graph` which provides a JSON serialization of the servicegraph - `/dotgraph` which provides a dot serialization of the servicegraph - `/dotviz` which provides a visual representation of the servicegraph All endpoints take an optional argument of `time_horizon`, which controls the timespan to consider for graph generation. ### Demosvc service Defined in `servicegraph/cmd/demosvc`, this provides a simple HTTP endpoint that generates prometheus metrics. This can be used to test the servicegraph service.
mixer/example/servicegraph/README.md
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.00016874202992767096, 0.0001679602573858574, 0.00016690132906660438, 0.00016823739861138165, 7.765961527184118e-7 ]
{ "id": 1, "code_window": [ "package aspect\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"strconv\"\n", "\t\"sync/atomic\"\n", "\n", "\tptypes \"github.com/gogo/protobuf/types\"\n", "\t\"github.com/golang/glog\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 18 }
// Copyright 2016 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "fmt" "os" "istio.io/mixer/cmd/client/cmd" ) func main() { rootCmd := cmd.GetRootCmd(os.Args[1:], func(format string, a ...interface{}) { fmt.Printf(format, a...) }, func(format string, a ...interface{}) { fmt.Fprintf(os.Stderr, format+"\n", a...) os.Exit(-1) }) if err := rootCmd.Execute(); err != nil { os.Exit(-1) } }
mixer/cmd/client/main.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.00017350410053040832, 0.00016888976097106934, 0.00016524370585102588, 0.00016840558964759111, 0.0000034497413707867963 ]
{ "id": 2, "code_window": [ ")\n", "\n", "type (\n", "\tquotasManager struct {\n", "\t\tdedupCounter int64\n", "\t}\n", "\n", "\tquotaInfo struct {\n", "\t\tdefinition *adapter.QuotaDefinition\n", "\t\tlabels map[string]string\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tquotasManager struct{}\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 36 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "fmt" "strconv" "sync/atomic" ptypes "github.com/gogo/protobuf/types" "github.com/golang/glog" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/mixer/pkg/adapter" aconfig "istio.io/mixer/pkg/aspect/config" "istio.io/mixer/pkg/attribute" "istio.io/mixer/pkg/config" "istio.io/mixer/pkg/config/descriptor" cpb "istio.io/mixer/pkg/config/proto" "istio.io/mixer/pkg/expr" "istio.io/mixer/pkg/status" ) type ( quotasManager struct { dedupCounter int64 } quotaInfo struct { definition *adapter.QuotaDefinition labels map[string]string } quotasWrapper struct { manager *quotasManager aspect adapter.QuotasAspect metadata map[string]*quotaInfo adapter string } ) // newQuotasManager returns a manager for the quotas aspect. func newQuotasManager() Manager { return &quotasManager{} } // NewAspect creates a quota aspect. func (m *quotasManager) NewAspect(c *cpb.Combined, a adapter.Builder, env adapter.Env) (Wrapper, error) { params := c.Aspect.Params.(*aconfig.QuotasParams) // TODO: get this from config if len(params.Quotas) == 0 { params = &aconfig.QuotasParams{ Quotas: []*aconfig.QuotasParams_Quota{ {DescriptorName: "RequestCount"}, }, } } // TODO: get this from config desc := []dpb.QuotaDescriptor{ { Name: "RequestCount", MaxAmount: 5, Expiration: &ptypes.Duration{Seconds: 1}, }, } metadata := make(map[string]*quotaInfo, len(desc)) defs := make(map[string]*adapter.QuotaDefinition, len(desc)) for _, d := range desc { quota := findQuota(params.Quotas, d.Name) if quota == nil { env.Logger().Warningf("No quota found for descriptor %s, skipping it", d.Name) continue } // TODO: once we plumb descriptors into the validation, remove this err: no descriptor should make it through validation // if it cannot be converted into a QuotaDefinition, so we should never have to handle the error case. def, err := quotaDefinitionFromProto(&d) if err != nil { _ = env.Logger().Errorf("Failed to convert quota descriptor '%s' to definition with err: %s; skipping it.", d.Name, err) continue } defs[d.Name] = def metadata[d.Name] = &quotaInfo{ labels: quota.Labels, definition: def, } } asp, err := a.(adapter.QuotasBuilder).NewQuotasAspect(env, c.Builder.Params.(adapter.Config), defs) if err != nil { return nil, err } return &quotasWrapper{ manager: m, metadata: metadata, aspect: asp, adapter: a.Name(), }, nil } func (*quotasManager) Kind() Kind { return QuotasKind } func (*quotasManager) DefaultConfig() config.AspectParams { return &aconfig.QuotasParams{} } func (*quotasManager) ValidateConfig(config.AspectParams, expr.Validator, descriptor.Finder) (ce *adapter.ConfigErrors) { return } func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output { qma, ok := ma.(*QuotaMethodArgs) // TODO: this conditional is only necessary because we currently perform quota // checking via the Check API, which doesn't generate a QuotaMethodArgs if !ok { qma = &QuotaMethodArgs{ Quota: "RequestCount", Amount: 1, DeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16), BestEffort: false, } } info, ok := w.metadata[qma.Quota] if !ok { msg := fmt.Sprintf("Unknown quota '%s' requested", qma.Quota) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } labels, err := evalAll(info.labels, attrs, mapper) if err != nil { msg := fmt.Sprintf("Unable to evaluate labels for quota '%s' with err: %s", qma.Quota, err) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } qa := adapter.QuotaArgs{ Definition: info.definition, Labels: labels, QuotaAmount: qma.Amount, DeduplicationID: qma.DeduplicationID, } var qr adapter.QuotaResult if glog.V(2) { glog.Info("Invoking adapter %s for quota %s with amount %d", w.adapter, qa.Definition.Name, qa.QuotaAmount) } if qma.BestEffort { qr, err = w.aspect.AllocBestEffort(qa) } else { qr, err = w.aspect.Alloc(qa) } if err != nil { glog.Errorf("Quota allocation failed: %v", err) return Output{Status: status.WithError(err)} } if qr.Amount == 0 { msg := fmt.Sprintf("Unable to allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) glog.Warning(msg) return Output{Status: status.WithResourceExhausted(msg)} } if glog.V(2) { glog.Infof("Allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) } return Output{ Status: status.OK, Response: &QuotaMethodResp{ Amount: qr.Amount, Expiration: qr.Expiration, }} } func (w *quotasWrapper) Close() error { return w.aspect.Close() } func findQuota(quotas []*aconfig.QuotasParams_Quota, name string) *aconfig.QuotasParams_Quota { for _, q := range quotas { if q.DescriptorName == name { return q } } return nil } func quotaDefinitionFromProto(desc *dpb.QuotaDescriptor) (*adapter.QuotaDefinition, error) { labels := make(map[string]adapter.LabelType, len(desc.Labels)) for _, label := range desc.Labels { l, err := valueTypeToLabelType(label.ValueType) if err != nil { return nil, fmt.Errorf("descriptor '%s' label '%s' failed to convert label type value '%v' from proto with err: %s", desc.Name, label.Name, label.ValueType, err) } labels[label.Name] = l } dur, _ := ptypes.DurationFromProto(desc.Expiration) return &adapter.QuotaDefinition{ MaxAmount: desc.MaxAmount, Expiration: dur, Description: desc.Description, DisplayName: desc.DisplayName, Name: desc.Name, Labels: labels, }, nil }
mixer/pkg/aspect/quotasManager.go
1
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.9985514283180237, 0.1476263552904129, 0.00017021076928358525, 0.002886249916628003, 0.3313327431678772 ]
{ "id": 2, "code_window": [ ")\n", "\n", "type (\n", "\tquotasManager struct {\n", "\t\tdedupCounter int64\n", "\t}\n", "\n", "\tquotaInfo struct {\n", "\t\tdefinition *adapter.QuotaDefinition\n", "\t\tlabels map[string]string\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tquotasManager struct{}\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 36 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "fmt" "strconv" "strings" "testing" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/mixer/pkg/adapter" listcheckerpb "istio.io/mixer/pkg/aspect/config" "istio.io/mixer/pkg/attribute" "istio.io/mixer/pkg/config/descriptor" "istio.io/mixer/pkg/expr" ) type fakeVFinder struct { ada map[string]adapter.ConfigValidator asp map[string]AspectValidator kinds []string } func (f *fakeVFinder) FindAdapterValidator(name string) (adapter.ConfigValidator, bool) { v, found := f.ada[name] return v, found } func (f *fakeVFinder) FindAspectValidator(name string) (AspectValidator, bool) { v, found := f.asp[name] return v, found } func (f *fakeVFinder) AdapterToAspectMapperFunc(impl string) []string { return f.kinds } type lc struct { ce *adapter.ConfigErrors } func (m *lc) DefaultConfig() (c adapter.Config) { return &listcheckerpb.ListsParams{} } // ValidateConfig determines whether the given configuration meets all correctness requirements. func (m *lc) ValidateConfig(c adapter.Config) *adapter.ConfigErrors { return m.ce } type ac struct { ce *adapter.ConfigErrors } func (*ac) DefaultConfig() AspectParams { return &listcheckerpb.ListsParams{} } // ValidateConfig determines whether the given configuration meets all correctness requirements. func (a *ac) ValidateConfig(AspectParams, expr.Validator, descriptor.Finder) *adapter.ConfigErrors { return a.ce } type configTable struct { cerr *adapter.ConfigErrors ada map[string]adapter.ConfigValidator asp map[string]AspectValidator nerrors int selector string strict bool cfg string } func newVfinder(ada map[string]adapter.ConfigValidator, asp map[string]AspectValidator) *fakeVFinder { kinds := []string{} for k := range ada { kinds = append(kinds, k) } return &fakeVFinder{ada: ada, asp: asp, kinds: kinds} } func TestConfigValidatorError(t *testing.T) { var ct *adapter.ConfigErrors evaluator := newFakeExpr() cerr := ct.Appendf("Url", "Must have a valid URL") tests := []*configTable{ {nil, map[string]adapter.ConfigValidator{ "denyChecker": &lc{}, "metrics2": &lc{}, }, nil, 0, "service.name == “*”", false, sGlobalConfig}, {nil, map[string]adapter.ConfigValidator{ "metrics": &lc{}, "metrics2": &lc{}, }, nil, 1, "service.name == “*”", false, sGlobalConfig}, {nil, nil, map[string]AspectValidator{ "metrics": &ac{}, "metrics2": &ac{}, }, 0, "service.name == “*”", false, sSvcConfig}, {nil, nil, map[string]AspectValidator{ "metrics": &ac{}, "metrics2": &ac{}, }, 1, "service.name == “*”", true, sSvcConfig}, {cerr, nil, map[string]AspectValidator{ "metrics2": &ac{ce: cerr}, }, 2, "service.name == “*”", false, sSvcConfig}, {ct.Append("/:metrics", UnknownValidator("metrics")), nil, nil, 2, "\"\"", false, sSvcConfig}, } for idx, tt := range tests { t.Run(strconv.Itoa(idx), func(t *testing.T) { var ce *adapter.ConfigErrors mgr := newVfinder(tt.ada, tt.asp) p := NewValidator(mgr.FindAspectValidator, mgr.FindAdapterValidator, mgr.AdapterToAspectMapperFunc, tt.strict, evaluator) if tt.cfg == sSvcConfig { ce = p.validateServiceConfig(fmt.Sprintf(tt.cfg, tt.selector), false) } else { ce = p.validateGlobalConfig(tt.cfg) } cok := ce == nil ok := tt.nerrors == 0 if ok != cok { t.Fatalf("Expected %t Got %t", ok, cok) } if ce == nil { return } if len(ce.Multi.Errors) != tt.nerrors { t.Fatalf("Expected: '%v' Got: %v", tt.cerr.Error(), ce.Error()) } }) } } func TestFullConfigValidator(tt *testing.T) { fe := newFakeExpr() ctable := []struct { cerr *adapter.ConfigError ada map[string]adapter.ConfigValidator asp map[string]AspectValidator selector string strict bool cfg string exprErr error }{ {nil, map[string]adapter.ConfigValidator{ "denyChecker": &lc{}, "metrics": &lc{}, "listchecker": &lc{}, }, map[string]AspectValidator{ "denyChecker": &ac{}, "metrics": &ac{}, "listchecker": &ac{}, }, "service.name == “*”", false, sSvcConfig2, nil}, {nil, map[string]adapter.ConfigValidator{ "denyChecker": &lc{}, "metrics": &lc{}, "listchecker": &lc{}, }, map[string]AspectValidator{ "denyChecker": &ac{}, "metrics": &ac{}, "listchecker": &ac{}, }, "", false, sSvcConfig2, nil}, {&adapter.ConfigError{Field: "NamedAdapter", Underlying: fmt.Errorf("listchecker//denychecker.2 not available")}, map[string]adapter.ConfigValidator{ "denyChecker": &lc{}, "metrics": &lc{}, "listchecker": &lc{}, }, map[string]AspectValidator{ "denyChecker": &ac{}, "metrics": &ac{}, "listchecker": &ac{}, }, "", false, sSvcConfig3, nil}, {&adapter.ConfigError{Field: ":Selector service.name == “*”", Underlying: fmt.Errorf("invalid expression")}, map[string]adapter.ConfigValidator{ "denyChecker": &lc{}, "metrics": &lc{}, "listchecker": &lc{}, }, map[string]AspectValidator{ "denyChecker": &ac{}, "metrics": &ac{}, "listchecker": &ac{}, }, "service.name == “*”", false, sSvcConfig1, fmt.Errorf("invalid expression")}, } for idx, ctx := range ctable { tt.Run(fmt.Sprintf("[%d]", idx), func(t *testing.T) { mgr := newVfinder(ctx.ada, ctx.asp) fe.err = ctx.exprErr p := NewValidator(mgr.FindAspectValidator, mgr.FindAdapterValidator, mgr.AdapterToAspectMapperFunc, ctx.strict, fe) // sGlobalConfig only defines 1 adapter: denyChecker _, ce := p.Validate(ctx.cfg, sGlobalConfig) cok := ce == nil ok := ctx.cerr == nil if ok != cok { t.Fatalf("%d Expected %t Got %t", idx, ok, cok) } if ce == nil { return } if len(ce.Multi.Errors) < 2 { t.Fatal("expected at least 2 errors reported") } if !strings.Contains(ce.Multi.Errors[1].Error(), ctx.cerr.Error()) { t.Fatalf("%d got: %#v\nwant: %#v\n", idx, ce.Multi.Errors[1].Error(), ctx.cerr.Error()) } }) } } func TestConfigParseError(t *testing.T) { mgr := &fakeVFinder{} evaluator := newFakeExpr() p := NewValidator(mgr.FindAspectValidator, mgr.FindAdapterValidator, mgr.AdapterToAspectMapperFunc, false, evaluator) ce := p.validateServiceConfig("<config> </config>", false) if ce == nil || !strings.Contains(ce.Error(), "error unmarshaling") { t.Error("Expected unmarshal Error", ce) } ce = p.validateGlobalConfig("<config> </config>") if ce == nil || !strings.Contains(ce.Error(), "error unmarshaling") { t.Error("Expected unmarshal Error", ce) } _, ce = p.Validate("<config> </config>", "<config> </config>") if ce == nil || !strings.Contains(ce.Error(), "error unmarshaling") { t.Error("Expected unmarshal Error", ce) } } func TestDecoderError(t *testing.T) { err := Decode(make(chan int), nil, true) if err == nil { t.Error("Expected json encode error") } } const sGlobalConfigValid = ` subject: "namespace:ns" revision: "2022" adapters: - name: default kind: denials impl: denyChecker params: check_attribute: src.ip blacklist: true ` const sGlobalConfig = sGlobalConfigValid + ` unknown_field: true ` const sSvcConfig1 = ` subject: "namespace:ns" revision: "2022" rules: - selector: service.name == “*” aspects: - kind: metrics params: metrics: - name: response_time_by_consumer value: metric_response_time metric_kind: DELTA labels: - key: target_consumer_id ` const sSvcConfig2 = ` subject: namespace:ns revision: "2022" rules: - selector: service.name == “*” aspects: - kind: listchecker inputs: {} params: ` const sSvcConfig3 = ` subject: namespace:ns revision: "2022" rules: - selector: service.name == “*” aspects: - kind: listchecker inputs: {} params: adapter: denychecker.2 ` const sSvcConfig = ` subject: namespace:ns revision: "2022" rules: - selector: %s aspects: - kind: metrics adapter: "" inputs: {} params: check_attribute: src.ip blacklist: true unknown_field: true rules: - selector: src.name == "abc" aspects: - kind: metrics2 adapter: "" inputs: {} params: check_attribute: src.ip blacklist: true ` type fakeExpr struct { err error } // newFakeExpr returns the basic func newFakeExpr() *fakeExpr { return &fakeExpr{} } func UnboundVariable(vname string) error { return fmt.Errorf("unbound variable %s", vname) } // Eval evaluates given expression using the attribute bag func (e *fakeExpr) Eval(mapExpression string, attrs attribute.Bag) (interface{}, error) { if v, found := attrs.Get(mapExpression); found { return v, nil } return nil, UnboundVariable(mapExpression) } // EvalString evaluates given expression using the attribute bag to a string func (e *fakeExpr) EvalString(mapExpression string, attrs attribute.Bag) (string, error) { v, found := attrs.Get(mapExpression) if found { return v.(string), nil } return "", UnboundVariable(mapExpression) } // EvalPredicate evaluates given predicate using the attribute bag func (e *fakeExpr) EvalPredicate(mapExpression string, attrs attribute.Bag) (bool, error) { v, found := attrs.Get(mapExpression) if found { return v.(bool), nil } return false, UnboundVariable(mapExpression) } func (e *fakeExpr) Validate(expression string) error { return e.err } func (e *fakeExpr) TypeCheck(string, expr.AttributeDescriptorFinder) (dpb.ValueType, error) { return dpb.VALUE_TYPE_UNSPECIFIED, e.err }
mixer/pkg/config/validator_test.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.0020181310828775167, 0.0002802378439810127, 0.00016339831927325577, 0.00017413984460290521, 0.0003565910446923226 ]
{ "id": 2, "code_window": [ ")\n", "\n", "type (\n", "\tquotasManager struct {\n", "\t\tdedupCounter int64\n", "\t}\n", "\n", "\tquotaInfo struct {\n", "\t\tdefinition *adapter.QuotaDefinition\n", "\t\tlabels map[string]string\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tquotasManager struct{}\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 36 }
// Copyright 2016 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package attribute import ( "bytes" "fmt" "sync" "sync/atomic" "github.com/golang/glog" me "github.com/hashicorp/go-multierror" mixerpb "istio.io/api/mixer/v1" "istio.io/mixer/pkg/pool" ) // MutableBag is a generic mechanism to read and write a set of attributes. // // Bags can be chained together in a parent/child relationship. A child bag // represents a delta over a parent. By default a child looks identical to // the parent. But as mutations occur to the child, the two start to diverge. // Resetting a child makes it look identical to its parent again. type MutableBag struct { parent Bag values map[string]interface{} id int64 // strictly for use in diagnostic messages } var id int64 var mutableBags = sync.Pool{ New: func() interface{} { return &MutableBag{ values: make(map[string]interface{}), id: atomic.AddInt64(&id, 1), } }, } // GetMutableBag returns an initialized bag. // // Bags can be chained in a parent/child relationship. You can pass nil if the // bag has no parent. // // When you are done using the mutable bag, call the Done method to recycle it. func GetMutableBag(parent Bag) *MutableBag { mb := mutableBags.Get().(*MutableBag) mb.parent = parent if parent == nil { mb.parent = empty } return mb } // CopyBag makes a deep copy of MutableBag. func CopyBag(b Bag) *MutableBag { mb := GetMutableBag(nil) for _, k := range b.Names() { v, _ := b.Get(k) mb.Set(k, copyValue(v)) } return mb } // Given an attribute value, create a deep copy of it func copyValue(v interface{}) interface{} { switch t := v.(type) { case []byte: c := make([]byte, len(t)) copy(c, t) return c case map[string]string: c := make(map[string]string, len(t)) for k2, v2 := range t { c[k2] = v2 } return c } return v } // Done indicates the bag can be reclaimed. func (mb *MutableBag) Done() { mb.Reset() mb.parent = nil mutableBags.Put(mb) } // Get returns an attribute value. func (mb *MutableBag) Get(name string) (interface{}, bool) { var r interface{} var b bool if r, b = mb.values[name]; !b { r, b = mb.parent.Get(name) } return r, b } // Names return the names of all the attributes known to this bag. func (mb *MutableBag) Names() []string { i := 0 keys := make([]string, len(mb.values)) for k := range mb.values { keys[i] = k i++ } return append(keys, mb.parent.Names()...) } // Set creates an override for a named attribute. func (mb *MutableBag) Set(name string, value interface{}) { mb.values[name] = value } // Reset removes all local state. func (mb *MutableBag) Reset() { // my kingdom for a clear method on maps! for k := range mb.values { delete(mb.values, k) } } // Merge combines an array of bags into the current bag. // // The individual bags may not contain any conflicting attribute // values. If that happens, then the merge fails and no mutation // will have occurred to the current bag. func (mb *MutableBag) Merge(bags []*MutableBag) error { // first step is to make sure there are no redundant definitions of the same attribute keys := make(map[string]bool) for _, bag := range bags { for k := range bag.values { if keys[k] { return fmt.Errorf("conflicting value for attribute %s", k) } keys[k] = true } } // now that we know there are no conflicting definitions, do the actual merging... for _, bag := range bags { for k, v := range bag.values { mb.values[k] = copyValue(v) } } return nil } // Child allocates a derived mutable bag. // // Mutating a child doesn't affect the parent's state, all mutations are deltas. func (mb *MutableBag) Child() *MutableBag { return GetMutableBag(mb) } // Ensure that all dictionary indices are valid and that all values // are in range. // // Note that since we don't have the attribute schema, this doesn't validate // that a given attribute is being treated as the right type. That is, an // attribute called 'source.ip' which is of type IP_ADDRESS could be listed as // a string or an int, and we wouldn't catch it here. func checkPreconditions(dictionary dictionary, attrs *mixerpb.Attributes) error { var e *me.Error for k := range attrs.StringAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k := range attrs.Int64Attributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k := range attrs.DoubleAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k := range attrs.BoolAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k := range attrs.TimestampAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k := range attrs.DurationAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k := range attrs.BytesAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } } for k, v := range attrs.StringMapAttributes { if _, present := dictionary[k]; !present { e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k)) } for k2 := range v.Map { if _, present := dictionary[k2]; !present { e = me.Append(e, fmt.Errorf("string map index %d is not defined in the current dictionary", k2)) } } } // TODO: we should catch the case where the same attribute is being repeated in different types // (that is, an attribute called FOO which is both an int and a string for example) return e.ErrorOrNil() } // Update the state of the bag based on the content of an Attributes struct func (mb *MutableBag) update(dictionary dictionary, attrs *mixerpb.Attributes) error { // check preconditions up front and bail if there are any // errors without mutating the bag. if err := checkPreconditions(dictionary, attrs); err != nil { return err } var log *bytes.Buffer if glog.V(2) { log = pool.GetBuffer() } if attrs.ResetContext { if log != nil { log.WriteString(" resetting bag to empty state\n") } mb.Reset() } // delete requested attributes for _, d := range attrs.DeletedAttributes { if name, present := dictionary[d]; present { if log != nil { log.WriteString(fmt.Sprintf(" attempting to delete attribute %s\n", name)) } delete(mb.values, name) } } // apply all attributes for k, v := range attrs.StringAttributes { if log != nil { log.WriteString(fmt.Sprintf(" updating string attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.Int64Attributes { if log != nil { log.WriteString(fmt.Sprintf(" updating int64 attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.DoubleAttributes { if log != nil { log.WriteString(fmt.Sprintf(" updating double attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.BoolAttributes { if log != nil { log.WriteString(fmt.Sprintf(" updating bool attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.TimestampAttributes { if log != nil { log.WriteString(fmt.Sprintf(" updating time attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.DurationAttributes { if log != nil { log.WriteString(fmt.Sprintf(" updating duration attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.BytesAttributes { if log != nil { log.WriteString(fmt.Sprintf(" updating bytes attribute %s from '%v' to '%v'\n", dictionary[k], mb.values[dictionary[k]], v)) } mb.values[dictionary[k]] = v } for k, v := range attrs.StringMapAttributes { m, ok := mb.values[dictionary[k]].(map[string]string) if !ok { m = make(map[string]string) mb.values[dictionary[k]] = m } if log != nil { log.WriteString(fmt.Sprintf(" updating stringmap attribute %s from\n", dictionary[k])) if len(m) > 0 { for k2, v2 := range m { log.WriteString(fmt.Sprintf(" %s:%s\n", k2, v2)) } } else { log.WriteString(" <empty>\n") } log.WriteString(" to\n") } for k2, v2 := range v.Map { m[dictionary[k2]] = v2 } if log != nil { if len(m) > 0 { for k2, v2 := range m { log.WriteString(fmt.Sprintf(" %s:%s\n", k2, v2)) } } else { log.WriteString(" <empty>\n") } } } if log != nil { if log.Len() > 0 { glog.Infof("Updating attribute bag %d:\n%s", mb.id, log.String()) } } return nil }
mixer/pkg/attribute/mutableBag.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.945287823677063, 0.02583920769393444, 0.00016463491192553192, 0.0001714779791655019, 0.15324237942695618 ]
{ "id": 2, "code_window": [ ")\n", "\n", "type (\n", "\tquotasManager struct {\n", "\t\tdedupCounter int64\n", "\t}\n", "\n", "\tquotaInfo struct {\n", "\t\tdefinition *adapter.QuotaDefinition\n", "\t\tlabels map[string]string\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tquotasManager struct{}\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 36 }
package(default_visibility = ["//visibility:public"]) load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", testonly = 1, srcs = [ "adapters.go", "env.go", ], deps = [ "//pkg/adapter:go_default_library", ], )
mixer/pkg/adapter/test/BUILD
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.0001720981381367892, 0.0001699876447673887, 0.00016787716594990343, 0.0001699876447673887, 0.000002110486093442887 ]
{ "id": 3, "code_window": [ "}\n", "\n", "func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output {\n", "\tqma, ok := ma.(*QuotaMethodArgs)\n", "\n", "\t// TODO: this conditional is only necessary because we currently perform quota\n", "\t// checking via the Check API, which doesn't generate a QuotaMethodArgs\n", "\tif !ok {\n", "\t\tqma = &QuotaMethodArgs{\n", "\t\t\tQuota: \"RequestCount\",\n", "\t\t\tAmount: 1,\n", "\t\t\tDeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16),\n", "\t\t\tBestEffort: false,\n", "\t\t}\n", "\t}\n", "\n", "\tinfo, ok := w.metadata[qma.Quota]\n", "\tif !ok {\n", "\t\tmsg := fmt.Sprintf(\"Unknown quota '%s' requested\", qma.Quota)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tqma := ma.(*QuotaMethodArgs)\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 124 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "fmt" "strconv" "sync/atomic" ptypes "github.com/gogo/protobuf/types" "github.com/golang/glog" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/mixer/pkg/adapter" aconfig "istio.io/mixer/pkg/aspect/config" "istio.io/mixer/pkg/attribute" "istio.io/mixer/pkg/config" "istio.io/mixer/pkg/config/descriptor" cpb "istio.io/mixer/pkg/config/proto" "istio.io/mixer/pkg/expr" "istio.io/mixer/pkg/status" ) type ( quotasManager struct { dedupCounter int64 } quotaInfo struct { definition *adapter.QuotaDefinition labels map[string]string } quotasWrapper struct { manager *quotasManager aspect adapter.QuotasAspect metadata map[string]*quotaInfo adapter string } ) // newQuotasManager returns a manager for the quotas aspect. func newQuotasManager() Manager { return &quotasManager{} } // NewAspect creates a quota aspect. func (m *quotasManager) NewAspect(c *cpb.Combined, a adapter.Builder, env adapter.Env) (Wrapper, error) { params := c.Aspect.Params.(*aconfig.QuotasParams) // TODO: get this from config if len(params.Quotas) == 0 { params = &aconfig.QuotasParams{ Quotas: []*aconfig.QuotasParams_Quota{ {DescriptorName: "RequestCount"}, }, } } // TODO: get this from config desc := []dpb.QuotaDescriptor{ { Name: "RequestCount", MaxAmount: 5, Expiration: &ptypes.Duration{Seconds: 1}, }, } metadata := make(map[string]*quotaInfo, len(desc)) defs := make(map[string]*adapter.QuotaDefinition, len(desc)) for _, d := range desc { quota := findQuota(params.Quotas, d.Name) if quota == nil { env.Logger().Warningf("No quota found for descriptor %s, skipping it", d.Name) continue } // TODO: once we plumb descriptors into the validation, remove this err: no descriptor should make it through validation // if it cannot be converted into a QuotaDefinition, so we should never have to handle the error case. def, err := quotaDefinitionFromProto(&d) if err != nil { _ = env.Logger().Errorf("Failed to convert quota descriptor '%s' to definition with err: %s; skipping it.", d.Name, err) continue } defs[d.Name] = def metadata[d.Name] = &quotaInfo{ labels: quota.Labels, definition: def, } } asp, err := a.(adapter.QuotasBuilder).NewQuotasAspect(env, c.Builder.Params.(adapter.Config), defs) if err != nil { return nil, err } return &quotasWrapper{ manager: m, metadata: metadata, aspect: asp, adapter: a.Name(), }, nil } func (*quotasManager) Kind() Kind { return QuotasKind } func (*quotasManager) DefaultConfig() config.AspectParams { return &aconfig.QuotasParams{} } func (*quotasManager) ValidateConfig(config.AspectParams, expr.Validator, descriptor.Finder) (ce *adapter.ConfigErrors) { return } func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output { qma, ok := ma.(*QuotaMethodArgs) // TODO: this conditional is only necessary because we currently perform quota // checking via the Check API, which doesn't generate a QuotaMethodArgs if !ok { qma = &QuotaMethodArgs{ Quota: "RequestCount", Amount: 1, DeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16), BestEffort: false, } } info, ok := w.metadata[qma.Quota] if !ok { msg := fmt.Sprintf("Unknown quota '%s' requested", qma.Quota) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } labels, err := evalAll(info.labels, attrs, mapper) if err != nil { msg := fmt.Sprintf("Unable to evaluate labels for quota '%s' with err: %s", qma.Quota, err) glog.Error(msg) return Output{Status: status.WithInvalidArgument(msg)} } qa := adapter.QuotaArgs{ Definition: info.definition, Labels: labels, QuotaAmount: qma.Amount, DeduplicationID: qma.DeduplicationID, } var qr adapter.QuotaResult if glog.V(2) { glog.Info("Invoking adapter %s for quota %s with amount %d", w.adapter, qa.Definition.Name, qa.QuotaAmount) } if qma.BestEffort { qr, err = w.aspect.AllocBestEffort(qa) } else { qr, err = w.aspect.Alloc(qa) } if err != nil { glog.Errorf("Quota allocation failed: %v", err) return Output{Status: status.WithError(err)} } if qr.Amount == 0 { msg := fmt.Sprintf("Unable to allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) glog.Warning(msg) return Output{Status: status.WithResourceExhausted(msg)} } if glog.V(2) { glog.Infof("Allocate %v units from quota %s", qa.QuotaAmount, qa.Definition.Name) } return Output{ Status: status.OK, Response: &QuotaMethodResp{ Amount: qr.Amount, Expiration: qr.Expiration, }} } func (w *quotasWrapper) Close() error { return w.aspect.Close() } func findQuota(quotas []*aconfig.QuotasParams_Quota, name string) *aconfig.QuotasParams_Quota { for _, q := range quotas { if q.DescriptorName == name { return q } } return nil } func quotaDefinitionFromProto(desc *dpb.QuotaDescriptor) (*adapter.QuotaDefinition, error) { labels := make(map[string]adapter.LabelType, len(desc.Labels)) for _, label := range desc.Labels { l, err := valueTypeToLabelType(label.ValueType) if err != nil { return nil, fmt.Errorf("descriptor '%s' label '%s' failed to convert label type value '%v' from proto with err: %s", desc.Name, label.Name, label.ValueType, err) } labels[label.Name] = l } dur, _ := ptypes.DurationFromProto(desc.Expiration) return &adapter.QuotaDefinition{ MaxAmount: desc.MaxAmount, Expiration: dur, Description: desc.Description, DisplayName: desc.DisplayName, Name: desc.Name, Labels: labels, }, nil }
mixer/pkg/aspect/quotasManager.go
1
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.9978542923927307, 0.0907524898648262, 0.00017119549738708884, 0.0018002591095864773, 0.27998292446136475 ]
{ "id": 3, "code_window": [ "}\n", "\n", "func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output {\n", "\tqma, ok := ma.(*QuotaMethodArgs)\n", "\n", "\t// TODO: this conditional is only necessary because we currently perform quota\n", "\t// checking via the Check API, which doesn't generate a QuotaMethodArgs\n", "\tif !ok {\n", "\t\tqma = &QuotaMethodArgs{\n", "\t\t\tQuota: \"RequestCount\",\n", "\t\t\tAmount: 1,\n", "\t\t\tDeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16),\n", "\t\t\tBestEffort: false,\n", "\t\t}\n", "\t}\n", "\n", "\tinfo, ok := w.metadata[qma.Quota]\n", "\tif !ok {\n", "\t\tmsg := fmt.Sprintf(\"Unknown quota '%s' requested\", qma.Quota)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tqma := ma.(*QuotaMethodArgs)\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 124 }
# The Istio Mixer # ![Mixer](doc/logo.png) [![GoDoc](https://godoc.org/github.com/istio/mixer?status.svg)](http://godoc.org/github.com/istio/mixer) [![Build Status](https://testing.istio.io/buildStatus/icon?job=mixer/postsubmit)](https://testing.istio.io/job/mixer/) [![Go Report Card](https://goreportcard.com/badge/github.com/istio/mixer)](https://goreportcard.com/report/github.com/istio/mixer) [![codecov.io](https://codecov.io/github/istio/mixer/coverage.svg?branch=master)](https://codecov.io/github/istio/mixer?branch=master) The Istio mixer provides the foundation of the Istio service mesh design. It is responsible for insulating the Istio proxy and Istio-based services from details of the current execution environment, as well as to implement the control policies that Istio supports. The Istio mixer provides three distinct features: - **Precondition Checking**. Enables callers to verify a number of preconditions before responding to an incoming request from a service consumer. Preconditions can include whether the service consumer is properly authenticated, is on the service's whitelist, passes ACL checks, and more. - **Telemetry Reporting**. Enables services to produce logging, monitoring, tracing and billing streams intended for the service producer itself as well as for its consumers. - **Quota Management**. Enables services to allocate and free quota on a number of dimensions, Quotas are used as a relatively simple resource management tool to provide some fairness between service consumers when contending for limited resources. Please see the main Istio [README](https://github.com/istio/istio/blob/master/README.md) file to learn about the overall Istio project and how to get in touch with us. To learn how you can contribute to any of the Istio components, including the mixer, please see the Istio [contribution guidelines](https://github.com/istio/istio/blob/master/CONTRIBUTING.md). The Istio mixer's [developer's guide](doc/dev/development.md) presents everything you need to know to create, build, and test code for the mixer.
mixer/README.md
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.00017588907212484628, 0.00017149110499303788, 0.00016593131294939667, 0.0001720720320008695, 0.0000036071760405320674 ]
{ "id": 3, "code_window": [ "}\n", "\n", "func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output {\n", "\tqma, ok := ma.(*QuotaMethodArgs)\n", "\n", "\t// TODO: this conditional is only necessary because we currently perform quota\n", "\t// checking via the Check API, which doesn't generate a QuotaMethodArgs\n", "\tif !ok {\n", "\t\tqma = &QuotaMethodArgs{\n", "\t\t\tQuota: \"RequestCount\",\n", "\t\t\tAmount: 1,\n", "\t\t\tDeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16),\n", "\t\t\tBestEffort: false,\n", "\t\t}\n", "\t}\n", "\n", "\tinfo, ok := w.metadata[qma.Quota]\n", "\tif !ok {\n", "\t\tmsg := fmt.Sprintf(\"Unknown quota '%s' requested\", qma.Quota)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tqma := ma.(*QuotaMethodArgs)\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 124 }
// Copyright 2017 the Istio Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "fmt" "time" "github.com/golang/glog" "github.com/hashicorp/go-multierror" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/mixer/pkg/adapter" aconfig "istio.io/mixer/pkg/aspect/config" "istio.io/mixer/pkg/attribute" "istio.io/mixer/pkg/config" "istio.io/mixer/pkg/config/descriptor" cpb "istio.io/mixer/pkg/config/proto" "istio.io/mixer/pkg/expr" "istio.io/mixer/pkg/status" ) type ( metricsManager struct { } metricInfo struct { definition *adapter.MetricDefinition value string labels map[string]string } metricsWrapper struct { name string aspect adapter.MetricsAspect metadata map[string]*metricInfo // metric name -> info } ) // newMetricsManager returns a manager for the metric aspect. func newMetricsManager() Manager { return &metricsManager{} } // NewAspect creates a metric aspect. func (m *metricsManager) NewAspect(c *cpb.Combined, a adapter.Builder, env adapter.Env) (Wrapper, error) { params := c.Aspect.Params.(*aconfig.MetricsParams) // TODO: get descriptors from config // TODO: sync these schemas with the new standardized metric schemas. desc := []*dpb.MetricDescriptor{ { Name: "request_count", Kind: dpb.COUNTER, Value: dpb.INT64, Description: "request count by source, target, service, and code", Labels: []*dpb.LabelDescriptor{ {Name: "source", ValueType: dpb.STRING}, {Name: "target", ValueType: dpb.STRING}, {Name: "service", ValueType: dpb.STRING}, {Name: "method", ValueType: dpb.STRING}, {Name: "response_code", ValueType: dpb.INT64}, }, }, { Name: "request_latency", Kind: dpb.COUNTER, // TODO: nail this down; as is we'll have to do post-processing Value: dpb.DURATION, Description: "request latency by source, target, and service", Labels: []*dpb.LabelDescriptor{ {Name: "source", ValueType: dpb.STRING}, {Name: "target", ValueType: dpb.STRING}, {Name: "service", ValueType: dpb.STRING}, {Name: "method", ValueType: dpb.STRING}, {Name: "response_code", ValueType: dpb.INT64}, }, }, } metadata := make(map[string]*metricInfo) defs := make(map[string]*adapter.MetricDefinition, len(desc)) for _, d := range desc { metric, found := findMetric(params.Metrics, d.Name) if !found { env.Logger().Warningf("No metric found for descriptor %s, skipping it", d.Name) continue } // TODO: once we plumb descriptors into the validation, remove this err: no descriptor should make it through validation // if it cannot be converted into a MetricDefinition, so we should never have to handle the error case. def, err := metricDefinitionFromProto(d) if err != nil { _ = env.Logger().Errorf("Failed to convert metric descriptor '%s' to definition with err: %s; skipping it.", d.Name, err) continue } defs[def.Name] = def metadata[def.Name] = &metricInfo{ definition: def, value: metric.Value, labels: metric.Labels, } } b := a.(adapter.MetricsBuilder) asp, err := b.NewMetricsAspect(env, c.Builder.Params.(adapter.Config), defs) if err != nil { return nil, fmt.Errorf("failed to construct metrics aspect with config '%v' and err: %s", c, err) } return &metricsWrapper{b.Name(), asp, metadata}, nil } func (*metricsManager) Kind() Kind { return MetricsKind } func (*metricsManager) DefaultConfig() config.AspectParams { return &aconfig.MetricsParams{} } func (*metricsManager) ValidateConfig(config.AspectParams, expr.Validator, descriptor.Finder) (ce *adapter.ConfigErrors) { // TODO: we need to be provided the metric descriptors in addition to the metrics themselves here, so we can do type assertions. // We also need some way to assert the type of the result of evaluating an expression, but we don't have any attributes or an // evaluator on hand. // TODO: verify all descriptors can be marshalled into istio structs (DefinitionFromProto) return } func (w *metricsWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output { result := &multierror.Error{} var values []adapter.Value for name, md := range w.metadata { metricValue, err := mapper.Eval(md.value, attrs) if err != nil { result = multierror.Append(result, fmt.Errorf("failed to eval metric value for metric '%s' with err: %s", name, err)) continue } labels, err := evalAll(md.labels, attrs, mapper) if err != nil { result = multierror.Append(result, fmt.Errorf("failed to eval labels for metric '%s' with err: %s", name, err)) continue } // TODO: investigate either pooling these, or keeping a set around that has only its field's values updated. // we could keep a map[metric name]value, iterate over the it updating only the fields in each value values = append(values, adapter.Value{ Definition: md.definition, Labels: labels, // TODO: extract standard timestamp attributes for start/end once we det'm what they are StartTime: time.Now(), EndTime: time.Now(), MetricValue: metricValue, }) } if err := w.aspect.Record(values); err != nil { result = multierror.Append(result, fmt.Errorf("failed to record all values with err: %s", err)) } if glog.V(4) { glog.V(4).Infof("completed execution of metric adapter '%s' for %d values", w.name, len(values)) } err := result.ErrorOrNil() if err != nil { return Output{Status: status.WithError(err)} } return Output{Status: status.OK} } func (w *metricsWrapper) Close() error { return w.aspect.Close() } func evalAll(expressions map[string]string, attrs attribute.Bag, eval expr.Evaluator) (map[string]interface{}, error) { result := &multierror.Error{} labels := make(map[string]interface{}, len(expressions)) for label, texpr := range expressions { val, err := eval.Eval(texpr, attrs) if err != nil { result = multierror.Append(result, fmt.Errorf("failed to construct value for label '%s' with err: %s", label, err)) continue } labels[label] = val } return labels, result.ErrorOrNil() } func metricDefinitionFromProto(desc *dpb.MetricDescriptor) (*adapter.MetricDefinition, error) { labels := make(map[string]adapter.LabelType, len(desc.Labels)) for _, label := range desc.Labels { l, err := valueTypeToLabelType(label.ValueType) if err != nil { return nil, fmt.Errorf("descriptor '%s' label '%s' failed to convert label type value '%v' from proto with err: %s", desc.Name, label.Name, label.ValueType, err) } labels[label.Name] = l } kind, err := metricKindFromProto(desc.Kind) if err != nil { return nil, fmt.Errorf("descriptor '%s' failed to convert metric kind value '%v' from proto with err: %s", desc.Name, desc.Kind, err) } return &adapter.MetricDefinition{ Name: desc.Name, DisplayName: desc.DisplayName, Description: desc.Description, Kind: kind, Labels: labels, }, nil } func findMetric(defs []*aconfig.MetricsParams_Metric, name string) (*aconfig.MetricsParams_Metric, bool) { for _, def := range defs { if def.DescriptorName == name { return def, true } } return nil, false }
mixer/pkg/aspect/metricsManager.go
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.04401320964097977, 0.002146691782400012, 0.0001631619961699471, 0.0001719200809020549, 0.008741036057472229 ]
{ "id": 3, "code_window": [ "}\n", "\n", "func (w *quotasWrapper) Execute(attrs attribute.Bag, mapper expr.Evaluator, ma APIMethodArgs) Output {\n", "\tqma, ok := ma.(*QuotaMethodArgs)\n", "\n", "\t// TODO: this conditional is only necessary because we currently perform quota\n", "\t// checking via the Check API, which doesn't generate a QuotaMethodArgs\n", "\tif !ok {\n", "\t\tqma = &QuotaMethodArgs{\n", "\t\t\tQuota: \"RequestCount\",\n", "\t\t\tAmount: 1,\n", "\t\t\tDeduplicationID: strconv.FormatInt(atomic.AddInt64(&w.manager.dedupCounter, 1), 16),\n", "\t\t\tBestEffort: false,\n", "\t\t}\n", "\t}\n", "\n", "\tinfo, ok := w.metadata[qma.Quota]\n", "\tif !ok {\n", "\t\tmsg := fmt.Sprintf(\"Unknown quota '%s' requested\", qma.Quota)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tqma := ma.(*QuotaMethodArgs)\n" ], "file_path": "mixer/pkg/aspect/quotasManager.go", "type": "replace", "edit_start_line_idx": 124 }
global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: - job_name: 'mixer' scrape_interval: 5s kubernetes_sd_configs: - role: service relabel_configs: # only select k8s services named "mixer" with a port named "prometheus" - source_labels: [__meta_kubernetes_service_name, __meta_kubernetes_service_port_name] action: keep regex: mixer;prometheus
mixer/deploy/kube/conf/prometheus.yaml
0
https://github.com/istio/istio/commit/7ba39fa30087ea23c2c02c9e31648198bf801ccc
[ 0.0001764605549396947, 0.000175930792465806, 0.00017540104454383254, 0.000175930792465806, 5.297551979310811e-7 ]
{ "id": 0, "code_window": [ "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/gocui\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/style\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", ")\n", "\n", "type MenuContext struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 6 }
package gui import ( "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" ) func (gui *Gui) getMenuOptions() map[string]string { keybindingConfig := gui.c.UserConfig.Keybinding return map[string]string{ gui.getKeyDisplay(keybindingConfig.Universal.Return): gui.c.Tr.LcClose, fmt.Sprintf("%s %s", gui.getKeyDisplay(keybindingConfig.Universal.PrevItem), gui.getKeyDisplay(keybindingConfig.Universal.NextItem)): gui.c.Tr.LcNavigate, gui.getKeyDisplay(keybindingConfig.Universal.Select): gui.c.Tr.LcExecute, } } // note: items option is mutated by this function func (gui *Gui) createMenu(opts types.CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.c.Tr.LcCancel}, OnPress: func() error { return nil }, }) } for _, item := range opts.Items { if item.OpensMenu && item.LabelColumns != nil { return errors.New("Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user") } } gui.State.Contexts.Menu.SetMenuItems(opts.Items) gui.State.Contexts.Menu.SetSelectedLineIdx(0) gui.Views.Menu.Title = opts.Title gui.Views.Menu.FgColor = theme.GocuiDefaultTextColor gui.Views.Menu.SetOnSelectItem(gui.onSelectItemWrapper(func(selectedLine int) error { return nil })) gui.Views.Tooltip.Wrap = true gui.Views.Tooltip.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Visible = true // resetting keybindings so that the menu-specific keybindings are registered if err := gui.resetKeybindings(); err != nil { return err } _ = gui.c.PostRefreshUpdate(gui.State.Contexts.Menu) // TODO: ensure that if we're opened a menu from within a menu that it renders correctly return gui.c.PushContext(gui.State.Contexts.Menu) }
pkg/gui/menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.004427390173077583, 0.0009562671766616404, 0.00016594206681475043, 0.0004746110353153199, 0.0014304745709523559 ]
{ "id": 0, "code_window": [ "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/gocui\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/style\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", ")\n", "\n", "type MenuContext struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 6 }
package commands import ( "fmt" "os" "sync" "testing" "time" "github.com/go-errors/errors" gogit "github.com/jesseduffield/go-git/v5" "github.com/jesseduffield/lazygit/pkg/commands/git_config" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/stretchr/testify/assert" ) type fileInfoMock struct { name string size int64 fileMode os.FileMode fileModTime time.Time isDir bool sys interface{} } // Name is a function. func (f fileInfoMock) Name() string { return f.name } // Size is a function. func (f fileInfoMock) Size() int64 { return f.size } // Mode is a function. func (f fileInfoMock) Mode() os.FileMode { return f.fileMode } // ModTime is a function. func (f fileInfoMock) ModTime() time.Time { return f.fileModTime } // IsDir is a function. func (f fileInfoMock) IsDir() bool { return f.isDir } // Sys is a function. func (f fileInfoMock) Sys() interface{} { return f.sys } // TestNavigateToRepoRootDirectory is a function. func TestNavigateToRepoRootDirectory(t *testing.T) { type scenario struct { testName string stat func(string) (os.FileInfo, error) chdir func(string) error test func(error) } scenarios := []scenario{ { "Navigate to git repository", func(string) (os.FileInfo, error) { return fileInfoMock{isDir: true}, nil }, func(string) error { return nil }, func(err error) { assert.NoError(t, err) }, }, { "An error occurred when getting path information", func(string) (os.FileInfo, error) { return nil, fmt.Errorf("An error occurred") }, func(string) error { return nil }, func(err error) { assert.Error(t, err) assert.EqualError(t, err, "An error occurred") }, }, { "An error occurred when trying to move one path backward", func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }, func(string) error { return fmt.Errorf("An error occurred") }, func(err error) { assert.Error(t, err) assert.EqualError(t, err, "An error occurred") }, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { s.test(navigateToRepoRootDirectory(s.stat, s.chdir)) }) } } // TestSetupRepository is a function. func TestSetupRepository(t *testing.T) { type scenario struct { testName string openGitRepository func(string, *gogit.PlainOpenOptions) (*gogit.Repository, error) errorStr string options gogit.PlainOpenOptions test func(*gogit.Repository, error) } scenarios := []scenario{ { "A gitconfig parsing error occurred", func(string, *gogit.PlainOpenOptions) (*gogit.Repository, error) { return nil, fmt.Errorf(`unquoted '\' must be followed by new line`) }, "error translated", gogit.PlainOpenOptions{}, func(r *gogit.Repository, err error) { assert.Error(t, err) assert.EqualError(t, err, "error translated") }, }, { "A gogit error occurred", func(string, *gogit.PlainOpenOptions) (*gogit.Repository, error) { return nil, fmt.Errorf("Error from inside gogit") }, "", gogit.PlainOpenOptions{}, func(r *gogit.Repository, err error) { assert.Error(t, err) assert.EqualError(t, err, "Error from inside gogit") }, }, { "Setup done properly", func(string, *gogit.PlainOpenOptions) (*gogit.Repository, error) { assert.NoError(t, os.RemoveAll("/tmp/lazygit-test")) r, err := gogit.PlainInit("/tmp/lazygit-test", false) assert.NoError(t, err) return r, nil }, "", gogit.PlainOpenOptions{}, func(r *gogit.Repository, err error) { assert.NoError(t, err) assert.NotNil(t, r) }, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { s.test(setupRepository(s.openGitRepository, s.options, s.errorStr)) }) } } // TestNewGitCommand is a function. func TestNewGitCommand(t *testing.T) { actual, err := os.Getwd() assert.NoError(t, err) defer func() { assert.NoError(t, os.Chdir(actual)) }() type scenario struct { testName string setup func() test func(*GitCommand, error) } scenarios := []scenario{ { "An error occurred, folder doesn't contains a git repository", func() { assert.NoError(t, os.Chdir("/tmp")) }, func(gitCmd *GitCommand, err error) { assert.Error(t, err) assert.Regexp(t, `Must open lazygit in a git repository`, err.Error()) }, }, { "New GitCommand object created", func() { assert.NoError(t, os.RemoveAll("/tmp/lazygit-test")) _, err := gogit.PlainInit("/tmp/lazygit-test", false) assert.NoError(t, err) assert.NoError(t, os.Chdir("/tmp/lazygit-test")) }, func(gitCmd *GitCommand, err error) { assert.NoError(t, err) }, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { s.setup() s.test( NewGitCommand(utils.NewDummyCommon(), oscommands.NewDummyOSCommand(), git_config.NewFakeGitConfig(nil), &sync.Mutex{}, )) }) } } func TestFindDotGitDir(t *testing.T) { type scenario struct { testName string stat func(string) (os.FileInfo, error) readFile func(filename string) ([]byte, error) test func(string, error) } scenarios := []scenario{ { ".git is a directory", func(dotGit string) (os.FileInfo, error) { assert.Equal(t, ".git", dotGit) return os.Stat("testdata/a_dir") }, func(dotGit string) ([]byte, error) { assert.Fail(t, "readFile should not be called if .git is a directory") return nil, nil }, func(gitDir string, err error) { assert.NoError(t, err) assert.Equal(t, ".git", gitDir) }, }, { ".git is a file", func(dotGit string) (os.FileInfo, error) { assert.Equal(t, ".git", dotGit) return os.Stat("testdata/a_file") }, func(dotGit string) ([]byte, error) { assert.Equal(t, ".git", dotGit) return []byte("gitdir: blah\n"), nil }, func(gitDir string, err error) { assert.NoError(t, err) assert.Equal(t, "blah", gitDir) }, }, { "os.Stat returns an error", func(dotGit string) (os.FileInfo, error) { assert.Equal(t, ".git", dotGit) return nil, errors.New("error") }, func(dotGit string) ([]byte, error) { assert.Fail(t, "readFile should not be called os.Stat returns an error") return nil, nil }, func(gitDir string, err error) { assert.Error(t, err) }, }, { "readFile returns an error", func(dotGit string) (os.FileInfo, error) { assert.Equal(t, ".git", dotGit) return os.Stat("testdata/a_file") }, func(dotGit string) ([]byte, error) { return nil, errors.New("error") }, func(gitDir string, err error) { assert.Error(t, err) }, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { s.test(findDotGitDir(s.stat, s.readFile)) }) } }
pkg/commands/git_test.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.004872473422437906, 0.000322535663144663, 0.0001609529135748744, 0.00016837155271787196, 0.0008308599935844541 ]
{ "id": 0, "code_window": [ "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/gocui\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/style\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", ")\n", "\n", "type MenuContext struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 6 }
<<<<<<< HEAD test3 ======= test2 >>>>>>> develop
test/integration/mergeConflictUndo/expected/repo/directory/file2
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017029796435963362, 0.00017029796435963362, 0.00017029796435963362, 0.00017029796435963362, 0 ]
{ "id": 0, "code_window": [ "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/gocui\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/style\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", ")\n", "\n", "type MenuContext struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 6 }
del
test/integration/discardFileChanges/expected/repo/deleted.txt
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016749199130572379, 0.00016749199130572379, 0.00016749199130572379, 0.00016749199130572379, 0 ]
{ "id": 1, "code_window": [ "\t})\n", "\n", "\treturn slices.Map(self.menuItems, func(item *types.MenuItem) []string {\n", "\t\tdisplayStrings := getItemDisplayStrings(item)\n", "\t\tif showKeys {\n", "\t\t\tdisplayStrings = slices.Prepend(displayStrings, style.FgCyan.Sprint(keybindings.GetKeyDisplay(item.Key)))\n", "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdisplayStrings := item.LabelColumns\n" ], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 89 }
package gui import ( "log" "github.com/jesseduffield/generics/slices" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) func (gui *Gui) getBindings(context types.Context) []*types.Binding { var bindingsGlobal, bindingsPanel, bindingsNavigation []*types.Binding bindings, _ := gui.GetInitialKeybindings() customBindings, err := gui.CustomCommandsClient.GetCustomCommandKeybindings() if err != nil { log.Fatal(err) } bindings = append(customBindings, bindings...) for _, binding := range bindings { if keybindings.GetKeyDisplay(binding.Key) != "" && binding.Description != "" { if len(binding.Contexts) == 0 && binding.ViewName == "" { bindingsGlobal = append(bindingsGlobal, binding) } else if binding.Tag == "navigation" { bindingsNavigation = append(bindingsNavigation, binding) } else if lo.Contains(binding.Contexts, string(context.GetKey())) { bindingsPanel = append(bindingsPanel, binding) } } } resultBindings := []*types.Binding{} resultBindings = append(resultBindings, uniqueBindings(bindingsPanel)...) // adding a separator between the panel-specific bindings and the other bindings resultBindings = append(resultBindings, &types.Binding{}) resultBindings = append(resultBindings, uniqueBindings(bindingsGlobal)...) resultBindings = append(resultBindings, uniqueBindings(bindingsNavigation)...) return resultBindings } // We shouldn't really need to do this. We should define alternative keys for the same // handler in the keybinding struct. func uniqueBindings(bindings []*types.Binding) []*types.Binding { return lo.UniqBy(bindings, func(binding *types.Binding) string { return binding.Description }) } func (gui *Gui) displayDescription(binding *types.Binding) string { if binding.OpensMenu { return presentation.OpensMenuStyle(binding.Description) } return binding.Description } func (gui *Gui) handleCreateOptionsMenu() error { context := gui.currentContext() bindings := gui.getBindings(context) menuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem { return &types.MenuItem{ Label: gui.displayDescription(binding), OnPress: func() error { if binding.Key == nil { return nil } return binding.Handler() }, Key: binding.Key, Tooltip: binding.Tooltip, } }) return gui.c.Menu(types.CreateMenuOptions{ Title: gui.c.Tr.MenuTitle, Items: menuItems, HideCancel: true, }) }
pkg/gui/options_menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.005448812153190374, 0.0015278594801202416, 0.00016637411317788064, 0.00027577849687077105, 0.0018006309401243925 ]
{ "id": 1, "code_window": [ "\t})\n", "\n", "\treturn slices.Map(self.menuItems, func(item *types.MenuItem) []string {\n", "\t\tdisplayStrings := getItemDisplayStrings(item)\n", "\t\tif showKeys {\n", "\t\t\tdisplayStrings = slices.Prepend(displayStrings, style.FgCyan.Sprint(keybindings.GetKeyDisplay(item.Key)))\n", "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdisplayStrings := item.LabelColumns\n" ], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 89 }
#!/bin/sh set -e cd $1 git init git config user.email "[email protected]" git config user.name "CI" echo test0 > file0 git add . git commit -am file0 echo test1 > file1 git add . git commit -am file1
test/integration/tags4/setup.sh
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017542412388138473, 0.00017434234905522317, 0.0001732605742290616, 0.00017434234905522317, 0.0000010817748261615634 ]
{ "id": 1, "code_window": [ "\t})\n", "\n", "\treturn slices.Map(self.menuItems, func(item *types.MenuItem) []string {\n", "\t\tdisplayStrings := getItemDisplayStrings(item)\n", "\t\tif showKeys {\n", "\t\t\tdisplayStrings = slices.Prepend(displayStrings, style.FgCyan.Sprint(keybindings.GetKeyDisplay(item.Key)))\n", "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdisplayStrings := item.LabelColumns\n" ], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 89 }
{"KeyEvents":[{"Timestamp":1428,"Mod":0,"Key":256,"Ch":112},{"Timestamp":2571,"Mod":0,"Key":13,"Ch":13},{"Timestamp":3459,"Mod":0,"Key":13,"Ch":13},{"Timestamp":3852,"Mod":0,"Key":258,"Ch":0},{"Timestamp":4419,"Mod":0,"Key":256,"Ch":32},{"Timestamp":5267,"Mod":0,"Key":13,"Ch":13},{"Timestamp":6266,"Mod":0,"Key":256,"Ch":113}],"ResizeEvents":[{"Timestamp":0,"Width":272,"Height":74}]}
test/integration/pullMergeConflict/recording.json
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0001697697298368439, 0.0001697697298368439, 0.0001697697298368439, 0.0001697697298368439, 0 ]
{ "id": 1, "code_window": [ "\t})\n", "\n", "\treturn slices.Map(self.menuItems, func(item *types.MenuItem) []string {\n", "\t\tdisplayStrings := getItemDisplayStrings(item)\n", "\t\tif showKeys {\n", "\t\t\tdisplayStrings = slices.Prepend(displayStrings, style.FgCyan.Sprint(keybindings.GetKeyDisplay(item.Key)))\n", "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdisplayStrings := item.LabelColumns\n" ], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 89 }
Unnamed repository; edit this file 'description' to name the repository.
test/integration/fetchRemoteBranchWithNonmatchingName/expected/origin/description
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017331181152258068, 0.00017331181152258068, 0.00017331181152258068, 0.00017331181152258068, 0 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n", "}\n", "\n", "func getItemDisplayStrings(item *types.MenuItem) []string {\n", "\tif item.LabelColumns != nil {\n", "\t\treturn item.LabelColumns\n", "\t}\n", "\n", "\tstyledStr := item.Label\n", "\tif item.OpensMenu {\n", "\t\tstyledStr = presentation.OpensMenuStyle(styledStr)\n", "\t}\n", "\treturn []string{styledStr}\n", "}\n", "\n", "func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {\n", "\tbasicBindings := self.ListContextTrait.GetKeybindings(opts)\n", "\tmenuItemsWithKeys := slices.Filter(self.menuItems, func(item *types.MenuItem) bool {\n", "\t\treturn item.Key != nil\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 97 }
package gui import ( "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" ) func (gui *Gui) getMenuOptions() map[string]string { keybindingConfig := gui.c.UserConfig.Keybinding return map[string]string{ gui.getKeyDisplay(keybindingConfig.Universal.Return): gui.c.Tr.LcClose, fmt.Sprintf("%s %s", gui.getKeyDisplay(keybindingConfig.Universal.PrevItem), gui.getKeyDisplay(keybindingConfig.Universal.NextItem)): gui.c.Tr.LcNavigate, gui.getKeyDisplay(keybindingConfig.Universal.Select): gui.c.Tr.LcExecute, } } // note: items option is mutated by this function func (gui *Gui) createMenu(opts types.CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.c.Tr.LcCancel}, OnPress: func() error { return nil }, }) } for _, item := range opts.Items { if item.OpensMenu && item.LabelColumns != nil { return errors.New("Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user") } } gui.State.Contexts.Menu.SetMenuItems(opts.Items) gui.State.Contexts.Menu.SetSelectedLineIdx(0) gui.Views.Menu.Title = opts.Title gui.Views.Menu.FgColor = theme.GocuiDefaultTextColor gui.Views.Menu.SetOnSelectItem(gui.onSelectItemWrapper(func(selectedLine int) error { return nil })) gui.Views.Tooltip.Wrap = true gui.Views.Tooltip.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Visible = true // resetting keybindings so that the menu-specific keybindings are registered if err := gui.resetKeybindings(); err != nil { return err } _ = gui.c.PostRefreshUpdate(gui.State.Contexts.Menu) // TODO: ensure that if we're opened a menu from within a menu that it renders correctly return gui.c.PushContext(gui.State.Contexts.Menu) }
pkg/gui/menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0047106207348406315, 0.001402356312610209, 0.00016579088696744293, 0.00039025681326165795, 0.0017272155964747071 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n", "}\n", "\n", "func getItemDisplayStrings(item *types.MenuItem) []string {\n", "\tif item.LabelColumns != nil {\n", "\t\treturn item.LabelColumns\n", "\t}\n", "\n", "\tstyledStr := item.Label\n", "\tif item.OpensMenu {\n", "\t\tstyledStr = presentation.OpensMenuStyle(styledStr)\n", "\t}\n", "\treturn []string{styledStr}\n", "}\n", "\n", "func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {\n", "\tbasicBindings := self.ListContextTrait.GetKeybindings(opts)\n", "\tmenuItemsWithKeys := slices.Filter(self.menuItems, func(item *types.MenuItem) bool {\n", "\t\treturn item.Key != nil\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 97 }
test
test/integration/pullRebaseInteractive/expected/repo/myfile6
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016637730004731566, 0.00016637730004731566, 0.00016637730004731566, 0.00016637730004731566, 0 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n", "}\n", "\n", "func getItemDisplayStrings(item *types.MenuItem) []string {\n", "\tif item.LabelColumns != nil {\n", "\t\treturn item.LabelColumns\n", "\t}\n", "\n", "\tstyledStr := item.Label\n", "\tif item.OpensMenu {\n", "\t\tstyledStr = presentation.OpensMenuStyle(styledStr)\n", "\t}\n", "\treturn []string{styledStr}\n", "}\n", "\n", "func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {\n", "\tbasicBindings := self.ListContextTrait.GetKeybindings(opts)\n", "\tmenuItemsWithKeys := slices.Filter(self.menuItems, func(item *types.MenuItem) bool {\n", "\t\treturn item.Key != nil\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 97 }
#!/bin/sh set -e cd $1 git init git config user.email "[email protected]" git config user.name "CI" echo test0 > file0 git add . git commit -am file0 git checkout -b new-branch git checkout -b new-branch-2 git checkout -b new-branch-3 git checkout -b old-branch git checkout -b old-branch-2 git checkout -b old-branch-3
test/integration/branchSuggestions/setup.sh
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0001696566177997738, 0.00016781514568720013, 0.00016507833788637072, 0.00016871049592737108, 0.0000019733886347239604 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\treturn displayStrings\n", "\t})\n", "}\n", "\n", "func getItemDisplayStrings(item *types.MenuItem) []string {\n", "\tif item.LabelColumns != nil {\n", "\t\treturn item.LabelColumns\n", "\t}\n", "\n", "\tstyledStr := item.Label\n", "\tif item.OpensMenu {\n", "\t\tstyledStr = presentation.OpensMenuStyle(styledStr)\n", "\t}\n", "\treturn []string{styledStr}\n", "}\n", "\n", "func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {\n", "\tbasicBindings := self.ListContextTrait.GetKeybindings(opts)\n", "\tmenuItemsWithKeys := slices.Filter(self.menuItems, func(item *types.MenuItem) bool {\n", "\t\treturn item.Key != nil\n", "\t})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/context/menu_context.go", "type": "replace", "edit_start_line_idx": 97 }
Copyright (c) 2015 Conrad Irwin <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vendor/github.com/go-errors/errors/LICENSE.MIT
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0001764834305504337, 0.0001764834305504337, 0.0001764834305504337, 0.0001764834305504337, 0 ]
{ "id": 3, "code_window": [ "package gui\n", "\n", "import (\n", "\t\"errors\"\n", "\t\"fmt\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 3 }
package gui import ( "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" ) func (gui *Gui) getMenuOptions() map[string]string { keybindingConfig := gui.c.UserConfig.Keybinding return map[string]string{ gui.getKeyDisplay(keybindingConfig.Universal.Return): gui.c.Tr.LcClose, fmt.Sprintf("%s %s", gui.getKeyDisplay(keybindingConfig.Universal.PrevItem), gui.getKeyDisplay(keybindingConfig.Universal.NextItem)): gui.c.Tr.LcNavigate, gui.getKeyDisplay(keybindingConfig.Universal.Select): gui.c.Tr.LcExecute, } } // note: items option is mutated by this function func (gui *Gui) createMenu(opts types.CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.c.Tr.LcCancel}, OnPress: func() error { return nil }, }) } for _, item := range opts.Items { if item.OpensMenu && item.LabelColumns != nil { return errors.New("Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user") } } gui.State.Contexts.Menu.SetMenuItems(opts.Items) gui.State.Contexts.Menu.SetSelectedLineIdx(0) gui.Views.Menu.Title = opts.Title gui.Views.Menu.FgColor = theme.GocuiDefaultTextColor gui.Views.Menu.SetOnSelectItem(gui.onSelectItemWrapper(func(selectedLine int) error { return nil })) gui.Views.Tooltip.Wrap = true gui.Views.Tooltip.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Visible = true // resetting keybindings so that the menu-specific keybindings are registered if err := gui.resetKeybindings(); err != nil { return err } _ = gui.c.PostRefreshUpdate(gui.State.Contexts.Menu) // TODO: ensure that if we're opened a menu from within a menu that it renders correctly return gui.c.PushContext(gui.State.Contexts.Menu) }
pkg/gui/menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.9882979989051819, 0.38984745740890503, 0.00018113375699613243, 0.023571571335196495, 0.44419312477111816 ]
{ "id": 3, "code_window": [ "package gui\n", "\n", "import (\n", "\t\"errors\"\n", "\t\"fmt\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 3 }
// Package git implements the git transport protocol. package git import ( "fmt" "io" "net" "github.com/jesseduffield/go-git/v5/plumbing/format/pktline" "github.com/jesseduffield/go-git/v5/plumbing/transport" "github.com/jesseduffield/go-git/v5/plumbing/transport/internal/common" "github.com/jesseduffield/go-git/v5/utils/ioutil" ) // DefaultClient is the default git client. var DefaultClient = common.NewClient(&runner{}) const DefaultPort = 9418 type runner struct{} // Command returns a new Command for the given cmd in the given Endpoint func (r *runner) Command(cmd string, ep *transport.Endpoint, auth transport.AuthMethod) (common.Command, error) { // auth not allowed since git protocol doesn't support authentication if auth != nil { return nil, transport.ErrInvalidAuthMethod } c := &command{command: cmd, endpoint: ep} if err := c.connect(); err != nil { return nil, err } return c, nil } type command struct { conn net.Conn connected bool command string endpoint *transport.Endpoint } // Start executes the command sending the required message to the TCP connection func (c *command) Start() error { cmd := endpointToCommand(c.command, c.endpoint) e := pktline.NewEncoder(c.conn) return e.Encode([]byte(cmd)) } func (c *command) connect() error { if c.connected { return transport.ErrAlreadyConnected } var err error c.conn, err = net.Dial("tcp", c.getHostWithPort()) if err != nil { return err } c.connected = true return nil } func (c *command) getHostWithPort() string { host := c.endpoint.Host port := c.endpoint.Port if port <= 0 { port = DefaultPort } return fmt.Sprintf("%s:%d", host, port) } // StderrPipe git protocol doesn't have any dedicated error channel func (c *command) StderrPipe() (io.Reader, error) { return nil, nil } // StdinPipe return the underlying connection as WriteCloser, wrapped to prevent // call to the Close function from the connection, a command execution in git // protocol can't be closed or killed func (c *command) StdinPipe() (io.WriteCloser, error) { return ioutil.WriteNopCloser(c.conn), nil } // StdoutPipe return the underlying connection as Reader func (c *command) StdoutPipe() (io.Reader, error) { return c.conn, nil } func endpointToCommand(cmd string, ep *transport.Endpoint) string { host := ep.Host if ep.Port != DefaultPort { host = fmt.Sprintf("%s:%d", ep.Host, ep.Port) } return fmt.Sprintf("%s %s%chost=%s%c", cmd, ep.Path, 0, host, 0) } // Close closes the TCP connection and connection. func (c *command) Close() error { if !c.connected { return nil } c.connected = false return c.conn.Close() }
vendor/github.com/jesseduffield/go-git/v5/plumbing/transport/git/common.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00022920688206795603, 0.00018841767450794578, 0.00016675323422532529, 0.0001798367011360824, 0.000022147314666653983 ]
{ "id": 3, "code_window": [ "package gui\n", "\n", "import (\n", "\t\"errors\"\n", "\t\"fmt\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 3 }
// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package yaml // Set the writer error and return false. func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { emitter.error = yaml_WRITER_ERROR emitter.problem = problem return false } // Flush the output buffer. func yaml_emitter_flush(emitter *yaml_emitter_t) bool { if emitter.write_handler == nil { panic("write handler not set") } // Check if the buffer is empty. if emitter.buffer_pos == 0 { return true } if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) } emitter.buffer_pos = 0 return true }
vendor/gopkg.in/yaml.v3/writerc.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00020515041251201183, 0.00018053353414870799, 0.0001666875759838149, 0.0001734472025418654, 0.000013579261576524004 ]
{ "id": 3, "code_window": [ "package gui\n", "\n", "import (\n", "\t\"errors\"\n", "\t\"fmt\"\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 3 }
original1\noriginal2\noriginal3
test/integration/cherryPicking/expected/repo/file
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017772616411093622, 0.00017772616411093622, 0.00017772616411093622, 0.00017772616411093622, 0 ]
{ "id": 4, "code_window": [ "\t\"fmt\"\n", "\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 6 }
package gui import ( "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" ) func (gui *Gui) getMenuOptions() map[string]string { keybindingConfig := gui.c.UserConfig.Keybinding return map[string]string{ gui.getKeyDisplay(keybindingConfig.Universal.Return): gui.c.Tr.LcClose, fmt.Sprintf("%s %s", gui.getKeyDisplay(keybindingConfig.Universal.PrevItem), gui.getKeyDisplay(keybindingConfig.Universal.NextItem)): gui.c.Tr.LcNavigate, gui.getKeyDisplay(keybindingConfig.Universal.Select): gui.c.Tr.LcExecute, } } // note: items option is mutated by this function func (gui *Gui) createMenu(opts types.CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.c.Tr.LcCancel}, OnPress: func() error { return nil }, }) } for _, item := range opts.Items { if item.OpensMenu && item.LabelColumns != nil { return errors.New("Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user") } } gui.State.Contexts.Menu.SetMenuItems(opts.Items) gui.State.Contexts.Menu.SetSelectedLineIdx(0) gui.Views.Menu.Title = opts.Title gui.Views.Menu.FgColor = theme.GocuiDefaultTextColor gui.Views.Menu.SetOnSelectItem(gui.onSelectItemWrapper(func(selectedLine int) error { return nil })) gui.Views.Tooltip.Wrap = true gui.Views.Tooltip.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Visible = true // resetting keybindings so that the menu-specific keybindings are registered if err := gui.resetKeybindings(); err != nil { return err } _ = gui.c.PostRefreshUpdate(gui.State.Contexts.Menu) // TODO: ensure that if we're opened a menu from within a menu that it renders correctly return gui.c.PushContext(gui.State.Contexts.Menu) }
pkg/gui/menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.11126267910003662, 0.016057191416621208, 0.0001668488112045452, 0.00020089821191504598, 0.03886748477816582 ]
{ "id": 4, "code_window": [ "\t\"fmt\"\n", "\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 6 }
go-errors/errors ================ [![Build Status](https://travis-ci.org/go-errors/errors.svg?branch=master)](https://travis-ci.org/go-errors/errors) Package errors adds stacktrace support to errors in go. This is particularly useful when you want to understand the state of execution when an error was returned unexpectedly. It provides the type \*Error which implements the standard golang error interface, so you can use this library interchangably with code that is expecting a normal error return. Usage ----- Full documentation is available on [godoc](https://godoc.org/github.com/go-errors/errors), but here's a simple example: ```go package crashy import "github.com/go-errors/errors" var Crashed = errors.Errorf("oh dear") func Crash() error { return errors.New(Crashed) } ``` This can be called as follows: ```go package main import ( "crashy" "fmt" "github.com/go-errors/errors" ) func main() { err := crashy.Crash() if err != nil { if errors.Is(err, crashy.Crashed) { fmt.Println(err.(*errors.Error).ErrorStack()) } else { panic(err) } } } ``` Meta-fu ------- This package was original written to allow reporting to [Bugsnag](https://bugsnag.com/) from [bugsnag-go](https://github.com/bugsnag/bugsnag-go), but after I found similar packages by Facebook and Dropbox, it was moved to one canonical location so everyone can benefit. This package is licensed under the MIT license, see LICENSE.MIT for details. ## Changelog * v1.1.0 updated to use go1.13's standard-library errors.Is method instead of == in errors.Is * v1.2.0 added `errors.As` from the standard library. * v1.3.0 *BREAKING* updated error methods to return `error` instead of `*Error`. > Code that needs access to the underlying `*Error` can use the new errors.AsError(e) > ``` > // before > errors.New(err).ErrorStack() > // after >. errors.AsError(errors.Wrap(err)).ErrorStack() > ``` * v1.4.0 *BREAKING* v1.4.0 reverted all changes from v1.3.0 and is identical to v1.2.0 * v1.4.1 no code change, but now without an unnecessary cover.out file. * v1.4.2 performance improvement to ErrorStack() to avoid unnecessary work https://github.com/go-errors/errors/pull/40
vendor/github.com/go-errors/errors/README.md
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0005560846766456962, 0.00021449675841722637, 0.00016516793402843177, 0.0001694495149422437, 0.0001209313195431605 ]
{ "id": 4, "code_window": [ "\t\"fmt\"\n", "\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 6 }
commit 20
test/integration/bisectFromOtherBranch/expected/repo/.git_keep/COMMIT_EDITMSG
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017085715080611408, 0.00017085715080611408, 0.00017085715080611408, 0.00017085715080611408, 0 ]
{ "id": 4, "code_window": [ "\t\"fmt\"\n", "\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 6 }
0000000000000000000000000000000000000000 22f24c5fcc97c1ff826ecb66b60bdc01937f6052 CI <[email protected]> 1652009263 +0200 commit (initial): file0 22f24c5fcc97c1ff826ecb66b60bdc01937f6052 9e7ff93a5c67a0ef098e9e436961746f333edf98 CI <[email protected]> 1652009263 +0200 commit: file1 9e7ff93a5c67a0ef098e9e436961746f333edf98 02f629e46dbaa03b58196cced3df07b02c0daf22 CI <[email protected]> 1652009263 +0200 commit: file2
test/integration/discardStagedFiles/expected/repo/.git_keep/logs/refs/heads/master
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016629054152872413, 0.00016629054152872413, 0.00016629054152872413, 0.00016629054152872413, 0 ]
{ "id": 5, "code_window": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n", ")\n", "\n", "func (gui *Gui) getMenuOptions() map[string]string {\n", "\tkeybindingConfig := gui.c.UserConfig.Keybinding\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/utils\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 8 }
package gui import ( "log" "github.com/jesseduffield/generics/slices" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) func (gui *Gui) getBindings(context types.Context) []*types.Binding { var bindingsGlobal, bindingsPanel, bindingsNavigation []*types.Binding bindings, _ := gui.GetInitialKeybindings() customBindings, err := gui.CustomCommandsClient.GetCustomCommandKeybindings() if err != nil { log.Fatal(err) } bindings = append(customBindings, bindings...) for _, binding := range bindings { if keybindings.GetKeyDisplay(binding.Key) != "" && binding.Description != "" { if len(binding.Contexts) == 0 && binding.ViewName == "" { bindingsGlobal = append(bindingsGlobal, binding) } else if binding.Tag == "navigation" { bindingsNavigation = append(bindingsNavigation, binding) } else if lo.Contains(binding.Contexts, string(context.GetKey())) { bindingsPanel = append(bindingsPanel, binding) } } } resultBindings := []*types.Binding{} resultBindings = append(resultBindings, uniqueBindings(bindingsPanel)...) // adding a separator between the panel-specific bindings and the other bindings resultBindings = append(resultBindings, &types.Binding{}) resultBindings = append(resultBindings, uniqueBindings(bindingsGlobal)...) resultBindings = append(resultBindings, uniqueBindings(bindingsNavigation)...) return resultBindings } // We shouldn't really need to do this. We should define alternative keys for the same // handler in the keybinding struct. func uniqueBindings(bindings []*types.Binding) []*types.Binding { return lo.UniqBy(bindings, func(binding *types.Binding) string { return binding.Description }) } func (gui *Gui) displayDescription(binding *types.Binding) string { if binding.OpensMenu { return presentation.OpensMenuStyle(binding.Description) } return binding.Description } func (gui *Gui) handleCreateOptionsMenu() error { context := gui.currentContext() bindings := gui.getBindings(context) menuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem { return &types.MenuItem{ Label: gui.displayDescription(binding), OnPress: func() error { if binding.Key == nil { return nil } return binding.Handler() }, Key: binding.Key, Tooltip: binding.Tooltip, } }) return gui.c.Menu(types.CreateMenuOptions{ Title: gui.c.Tr.MenuTitle, Items: menuItems, HideCancel: true, }) }
pkg/gui/options_menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.058525606989860535, 0.008902362547814846, 0.00016645646246615797, 0.001561963465064764, 0.01770574226975441 ]
{ "id": 5, "code_window": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n", ")\n", "\n", "func (gui *Gui) getMenuOptions() map[string]string {\n", "\tkeybindingConfig := gui.c.UserConfig.Keybinding\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/utils\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 8 }
0000000000000000000000000000000000000000 a50a5125768001a3ea263ffb7cafbc421a508153 CI <[email protected]> 1534792759 +0100 commit (initial): myfile1 a50a5125768001a3ea263ffb7cafbc421a508153 42530e986dbb65877ed8d61ca0c816e425e5c62e CI <[email protected]> 1534792759 +0100 commit: myfile2 42530e986dbb65877ed8d61ca0c816e425e5c62e 9d10a5a0a21eb2cfdb6206f474ed57fd5cd51440 CI <[email protected]> 1534792759 +0100 commit: add submodule 9d10a5a0a21eb2cfdb6206f474ed57fd5cd51440 611cac756ef1944ab56d12f4ea3ae4623724c8cf CI <[email protected]> 1648348134 +1100 commit: remove submodule
test/integration/submoduleRemove/expected/repo/.git_keep/logs/refs/heads/master
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016329708159901202, 0.00016329708159901202, 0.00016329708159901202, 0.00016329708159901202, 0 ]
{ "id": 5, "code_window": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n", ")\n", "\n", "func (gui *Gui) getMenuOptions() map[string]string {\n", "\tkeybindingConfig := gui.c.UserConfig.Keybinding\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/utils\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 8 }
package git_commands import ( "testing" "github.com/go-errors/errors" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/stretchr/testify/assert" ) func TestBranchGetCommitDifferences(t *testing.T) { type scenario struct { testName string runner *oscommands.FakeCmdObjRunner expectedPushables string expectedPullables string } scenarios := []scenario{ { "Can't retrieve pushable count", oscommands.NewFakeRunner(t). Expect("git rev-list @{u}..HEAD --count", "", errors.New("error")), "?", "?", }, { "Can't retrieve pullable count", oscommands.NewFakeRunner(t). Expect("git rev-list @{u}..HEAD --count", "1\n", nil). Expect("git rev-list HEAD..@{u} --count", "", errors.New("error")), "?", "?", }, { "Retrieve pullable and pushable count", oscommands.NewFakeRunner(t). Expect("git rev-list @{u}..HEAD --count", "1\n", nil). Expect("git rev-list HEAD..@{u} --count", "2\n", nil), "1", "2", }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { instance := buildBranchCommands(commonDeps{runner: s.runner}) pushables, pullables := instance.GetCommitDifferences("HEAD", "@{u}") assert.EqualValues(t, s.expectedPushables, pushables) assert.EqualValues(t, s.expectedPullables, pullables) s.runner.CheckForMissingCalls() }) } } func TestBranchNewBranch(t *testing.T) { runner := oscommands.NewFakeRunner(t). Expect(`git checkout -b "test" "master"`, "", nil) instance := buildBranchCommands(commonDeps{runner: runner}) assert.NoError(t, instance.New("test", "master")) runner.CheckForMissingCalls() } func TestBranchDeleteBranch(t *testing.T) { type scenario struct { testName string force bool runner *oscommands.FakeCmdObjRunner test func(error) } scenarios := []scenario{ { "Delete a branch", false, oscommands.NewFakeRunner(t).Expect(`git branch -d "test"`, "", nil), func(err error) { assert.NoError(t, err) }, }, { "Force delete a branch", true, oscommands.NewFakeRunner(t).Expect(`git branch -D "test"`, "", nil), func(err error) { assert.NoError(t, err) }, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { instance := buildBranchCommands(commonDeps{runner: s.runner}) s.test(instance.Delete("test", s.force)) s.runner.CheckForMissingCalls() }) } } func TestBranchMerge(t *testing.T) { runner := oscommands.NewFakeRunner(t). Expect(`git merge --no-edit "test"`, "", nil) instance := buildBranchCommands(commonDeps{runner: runner}) assert.NoError(t, instance.Merge("test", MergeOpts{})) runner.CheckForMissingCalls() } func TestBranchCheckout(t *testing.T) { type scenario struct { testName string runner *oscommands.FakeCmdObjRunner test func(error) force bool } scenarios := []scenario{ { "Checkout", oscommands.NewFakeRunner(t).Expect(`git checkout "test"`, "", nil), func(err error) { assert.NoError(t, err) }, false, }, { "Checkout forced", oscommands.NewFakeRunner(t).Expect(`git checkout --force "test"`, "", nil), func(err error) { assert.NoError(t, err) }, true, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { instance := buildBranchCommands(commonDeps{runner: s.runner}) s.test(instance.Checkout("test", CheckoutOptions{Force: s.force})) s.runner.CheckForMissingCalls() }) } } func TestBranchGetBranchGraph(t *testing.T) { runner := oscommands.NewFakeRunner(t).ExpectGitArgs([]string{ "log", "--graph", "--color=always", "--abbrev-commit", "--decorate", "--date=relative", "--pretty=medium", "test", "--", }, "", nil) instance := buildBranchCommands(commonDeps{runner: runner}) _, err := instance.GetGraph("test") assert.NoError(t, err) } func TestBranchGetAllBranchGraph(t *testing.T) { runner := oscommands.NewFakeRunner(t).ExpectGitArgs([]string{ "log", "--graph", "--all", "--color=always", "--abbrev-commit", "--decorate", "--date=relative", "--pretty=medium", }, "", nil) instance := buildBranchCommands(commonDeps{runner: runner}) err := instance.AllBranchesLogCmdObj().Run() assert.NoError(t, err) } func TestBranchCurrentBranchName(t *testing.T) { type scenario struct { testName string runner *oscommands.FakeCmdObjRunner test func(string, string, error) } scenarios := []scenario{ { "says we are on the master branch if we are", oscommands.NewFakeRunner(t).Expect(`git symbolic-ref --short HEAD`, "master", nil), func(name string, displayname string, err error) { assert.NoError(t, err) assert.EqualValues(t, "master", name) assert.EqualValues(t, "master", displayname) }, }, { "falls back to git `git branch --contains` if symbolic-ref fails", oscommands.NewFakeRunner(t). Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")). Expect(`git branch --contains`, "* master", nil), func(name string, displayname string, err error) { assert.NoError(t, err) assert.EqualValues(t, "master", name) assert.EqualValues(t, "master", displayname) }, }, { "handles a detached head", oscommands.NewFakeRunner(t). Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")). Expect(`git branch --contains`, "* (HEAD detached at 123abcd)", nil), func(name string, displayname string, err error) { assert.NoError(t, err) assert.EqualValues(t, "123abcd", name) assert.EqualValues(t, "(HEAD detached at 123abcd)", displayname) }, }, { "bubbles up error if there is one", oscommands.NewFakeRunner(t). Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")). Expect(`git branch --contains`, "", errors.New("error")), func(name string, displayname string, err error) { assert.Error(t, err) assert.EqualValues(t, "", name) assert.EqualValues(t, "", displayname) }, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { instance := buildBranchCommands(commonDeps{runner: s.runner}) s.test(instance.CurrentBranchName()) s.runner.CheckForMissingCalls() }) } }
pkg/commands/git_commands/branch_test.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0003639319911599159, 0.00018331878527533263, 0.00016433940618298948, 0.00016759904974605888, 0.000046938974264776334 ]
{ "id": 5, "code_window": [ "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/theme\"\n", ")\n", "\n", "func (gui *Gui) getMenuOptions() map[string]string {\n", "\tkeybindingConfig := gui.c.UserConfig.Keybinding\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/jesseduffield/lazygit/pkg/utils\"\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 8 }
be485112173592dea7b39c7efc3a6f52f43b71b9
test/integration/stash/expected/repo/.git_keep/refs/stash
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0001647123135626316, 0.0001647123135626316, 0.0001647123135626316, 0.0001647123135626316, 0 ]
{ "id": 6, "code_window": [ "\t\t})\n", "\t}\n", "\n", "\tfor _, item := range opts.Items {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\tmaxColumnSize := 1\n", "\n", "\tfor _, item := range opts.Items {\n", "\t\tif item.LabelColumns == nil {\n", "\t\t\titem.LabelColumns = []string{item.Label}\n", "\t\t}\n", "\n", "\t\tif item.OpensMenu {\n", "\t\t\titem.LabelColumns[0] = presentation.OpensMenuStyle(item.LabelColumns[0])\n", "\t\t}\n", "\n", "\t\tmaxColumnSize = utils.Max(maxColumnSize, len(item.LabelColumns))\n", "\t}\n", "\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 32 }
package context import ( "github.com/jesseduffield/generics/slices" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type MenuContext struct { *MenuViewModel *ListContextTrait } var _ types.IListContext = (*MenuContext)(nil) func NewMenuContext( view *gocui.View, c *types.HelperCommon, getOptionsMap func() map[string]string, renderToDescriptionView func(string), ) *MenuContext { viewModel := NewMenuViewModel() onFocus := func(...types.OnFocusOpts) error { selectedMenuItem := viewModel.GetSelected() renderToDescriptionView(selectedMenuItem.Tooltip) return nil } return &MenuContext{ MenuViewModel: viewModel, ListContextTrait: &ListContextTrait{ Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{ ViewName: "menu", Key: "menu", Kind: types.PERSISTENT_POPUP, OnGetOptionsMap: getOptionsMap, Focusable: true, }), ContextCallbackOpts{ OnFocus: onFocus, }), getDisplayStrings: viewModel.GetDisplayStrings, list: viewModel, viewTrait: NewViewTrait(view), c: c, }, } } // TODO: remove this thing. func (self *MenuContext) GetSelectedItemId() string { item := self.GetSelected() if item == nil { return "" } return item.Label } type MenuViewModel struct { menuItems []*types.MenuItem *BasicViewModel[*types.MenuItem] } func NewMenuViewModel() *MenuViewModel { self := &MenuViewModel{ menuItems: nil, } self.BasicViewModel = NewBasicViewModel(func() []*types.MenuItem { return self.menuItems }) return self } func (self *MenuViewModel) SetMenuItems(items []*types.MenuItem) { self.menuItems = items } // TODO: move into presentation package func (self *MenuViewModel) GetDisplayStrings(_startIdx int, _length int) [][]string { showKeys := slices.Some(self.menuItems, func(item *types.MenuItem) bool { return item.Key != nil }) return slices.Map(self.menuItems, func(item *types.MenuItem) []string { displayStrings := getItemDisplayStrings(item) if showKeys { displayStrings = slices.Prepend(displayStrings, style.FgCyan.Sprint(keybindings.GetKeyDisplay(item.Key))) } return displayStrings }) } func getItemDisplayStrings(item *types.MenuItem) []string { if item.LabelColumns != nil { return item.LabelColumns } styledStr := item.Label if item.OpensMenu { styledStr = presentation.OpensMenuStyle(styledStr) } return []string{styledStr} } func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { basicBindings := self.ListContextTrait.GetKeybindings(opts) menuItemsWithKeys := slices.Filter(self.menuItems, func(item *types.MenuItem) bool { return item.Key != nil }) menuItemBindings := slices.Map(menuItemsWithKeys, func(item *types.MenuItem) *types.Binding { return &types.Binding{ Key: item.Key, Handler: func() error { return self.OnMenuPress(item) }, } }) // appending because that means the menu item bindings have lower precedence. // So if a basic binding is to escape from the menu, we want that to still be // what happens when you press escape. This matters when we're showing the menu // for all keybindings of say the files context. return append(basicBindings, menuItemBindings...) } func (self *MenuContext) OnMenuPress(selectedItem *types.MenuItem) error { if err := self.c.PopContext(); err != nil { return err } if err := selectedItem.OnPress(); err != nil { return err } return nil }
pkg/gui/context/menu_context.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.9979070425033569, 0.3911040127277374, 0.00016625264834146947, 0.004727478139102459, 0.4769449830055237 ]
{ "id": 6, "code_window": [ "\t\t})\n", "\t}\n", "\n", "\tfor _, item := range opts.Items {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\tmaxColumnSize := 1\n", "\n", "\tfor _, item := range opts.Items {\n", "\t\tif item.LabelColumns == nil {\n", "\t\t\titem.LabelColumns = []string{item.Label}\n", "\t\t}\n", "\n", "\t\tif item.OpensMenu {\n", "\t\t\titem.LabelColumns[0] = presentation.OpensMenuStyle(item.LabelColumns[0])\n", "\t\t}\n", "\n", "\t\tmaxColumnSize = utils.Max(maxColumnSize, len(item.LabelColumns))\n", "\t}\n", "\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 32 }
package git import ( "bytes" "errors" "io" "os" "path" "path/filepath" "strings" "github.com/go-git/go-billy/v5/util" "github.com/jesseduffield/go-git/v5/plumbing" "github.com/jesseduffield/go-git/v5/plumbing/filemode" "github.com/jesseduffield/go-git/v5/plumbing/format/gitignore" "github.com/jesseduffield/go-git/v5/plumbing/format/index" "github.com/jesseduffield/go-git/v5/plumbing/object" "github.com/jesseduffield/go-git/v5/utils/ioutil" "github.com/jesseduffield/go-git/v5/utils/merkletrie" "github.com/jesseduffield/go-git/v5/utils/merkletrie/filesystem" mindex "github.com/jesseduffield/go-git/v5/utils/merkletrie/index" "github.com/jesseduffield/go-git/v5/utils/merkletrie/noder" ) var ( // ErrDestinationExists in an Move operation means that the target exists on // the worktree. ErrDestinationExists = errors.New("destination exists") // ErrGlobNoMatches in an AddGlob if the glob pattern does not match any // files in the worktree. ErrGlobNoMatches = errors.New("glob pattern did not match any files") ) // Status returns the working tree status. func (w *Worktree) Status() (Status, error) { var hash plumbing.Hash ref, err := w.r.Head() if err != nil && err != plumbing.ErrReferenceNotFound { return nil, err } if err == nil { hash = ref.Hash() } return w.status(hash) } func (w *Worktree) status(commit plumbing.Hash) (Status, error) { s := make(Status) left, err := w.diffCommitWithStaging(commit, false) if err != nil { return nil, err } for _, ch := range left { a, err := ch.Action() if err != nil { return nil, err } fs := s.File(nameFromAction(&ch)) fs.Worktree = Unmodified switch a { case merkletrie.Delete: s.File(ch.From.String()).Staging = Deleted case merkletrie.Insert: s.File(ch.To.String()).Staging = Added case merkletrie.Modify: s.File(ch.To.String()).Staging = Modified } } right, err := w.diffStagingWithWorktree(false) if err != nil { return nil, err } for _, ch := range right { a, err := ch.Action() if err != nil { return nil, err } fs := s.File(nameFromAction(&ch)) if fs.Staging == Untracked { fs.Staging = Unmodified } switch a { case merkletrie.Delete: fs.Worktree = Deleted case merkletrie.Insert: fs.Worktree = Untracked fs.Staging = Untracked case merkletrie.Modify: fs.Worktree = Modified } } return s, nil } func nameFromAction(ch *merkletrie.Change) string { name := ch.To.String() if name == "" { return ch.From.String() } return name } func (w *Worktree) diffStagingWithWorktree(reverse bool) (merkletrie.Changes, error) { idx, err := w.r.Storer.Index() if err != nil { return nil, err } from := mindex.NewRootNode(idx) submodules, err := w.getSubmodulesStatus() if err != nil { return nil, err } to := filesystem.NewRootNode(w.Filesystem, submodules) var c merkletrie.Changes if reverse { c, err = merkletrie.DiffTree(to, from, diffTreeIsEquals) } else { c, err = merkletrie.DiffTree(from, to, diffTreeIsEquals) } if err != nil { return nil, err } return w.excludeIgnoredChanges(c), nil } func (w *Worktree) excludeIgnoredChanges(changes merkletrie.Changes) merkletrie.Changes { patterns, err := gitignore.ReadPatterns(w.Filesystem, nil) if err != nil { return changes } patterns = append(patterns, w.Excludes...) if len(patterns) == 0 { return changes } m := gitignore.NewMatcher(patterns) var res merkletrie.Changes for _, ch := range changes { var path []string for _, n := range ch.To { path = append(path, n.Name()) } if len(path) == 0 { for _, n := range ch.From { path = append(path, n.Name()) } } if len(path) != 0 { isDir := (len(ch.To) > 0 && ch.To.IsDir()) || (len(ch.From) > 0 && ch.From.IsDir()) if m.Match(path, isDir) { continue } } res = append(res, ch) } return res } func (w *Worktree) getSubmodulesStatus() (map[string]plumbing.Hash, error) { o := map[string]plumbing.Hash{} sub, err := w.Submodules() if err != nil { return nil, err } status, err := sub.Status() if err != nil { return nil, err } for _, s := range status { if s.Current.IsZero() { o[s.Path] = s.Expected continue } o[s.Path] = s.Current } return o, nil } func (w *Worktree) diffCommitWithStaging(commit plumbing.Hash, reverse bool) (merkletrie.Changes, error) { var t *object.Tree if !commit.IsZero() { c, err := w.r.CommitObject(commit) if err != nil { return nil, err } t, err = c.Tree() if err != nil { return nil, err } } return w.diffTreeWithStaging(t, reverse) } func (w *Worktree) diffTreeWithStaging(t *object.Tree, reverse bool) (merkletrie.Changes, error) { var from noder.Noder if t != nil { from = object.NewTreeRootNode(t) } idx, err := w.r.Storer.Index() if err != nil { return nil, err } to := mindex.NewRootNode(idx) if reverse { return merkletrie.DiffTree(to, from, diffTreeIsEquals) } return merkletrie.DiffTree(from, to, diffTreeIsEquals) } var emptyNoderHash = make([]byte, 24) // diffTreeIsEquals is a implementation of noder.Equals, used to compare // noder.Noder, it compare the content and the length of the hashes. // // Since some of the noder.Noder implementations doesn't compute a hash for // some directories, if any of the hashes is a 24-byte slice of zero values // the comparison is not done and the hashes are take as different. func diffTreeIsEquals(a, b noder.Hasher) bool { hashA := a.Hash() hashB := b.Hash() if bytes.Equal(hashA, emptyNoderHash) || bytes.Equal(hashB, emptyNoderHash) { return false } return bytes.Equal(hashA, hashB) } // Add adds the file contents of a file in the worktree to the index. if the // file is already staged in the index no error is returned. If a file deleted // from the Workspace is given, the file is removed from the index. If a // directory given, adds the files and all his sub-directories recursively in // the worktree to the index. If any of the files is already staged in the index // no error is returned. When path is a file, the blob.Hash is returned. func (w *Worktree) Add(path string) (plumbing.Hash, error) { // TODO(mcuadros): deprecate in favor of AddWithOption in v6. return w.doAdd(path, make([]gitignore.Pattern, 0)) } func (w *Worktree) doAddDirectory(idx *index.Index, s Status, directory string, ignorePattern []gitignore.Pattern) (added bool, err error) { files, err := w.Filesystem.ReadDir(directory) if err != nil { return false, err } if len(ignorePattern) > 0 { m := gitignore.NewMatcher(ignorePattern) matchPath := strings.Split(directory, string(os.PathSeparator)) if m.Match(matchPath, true) { // ignore return false, nil } } for _, file := range files { name := path.Join(directory, file.Name()) var a bool if file.IsDir() { if file.Name() == GitDirName { // ignore special git directory continue } a, err = w.doAddDirectory(idx, s, name, ignorePattern) } else { a, _, err = w.doAddFile(idx, s, name, ignorePattern) } if err != nil { return } if !added && a { added = true } } return } // AddWithOptions file contents to the index, updates the index using the // current content found in the working tree, to prepare the content staged for // the next commit. // // It typically adds the current content of existing paths as a whole, but with // some options it can also be used to add content with only part of the changes // made to the working tree files applied, or remove paths that do not exist in // the working tree anymore. func (w *Worktree) AddWithOptions(opts *AddOptions) error { if err := opts.Validate(w.r); err != nil { return err } if opts.All { _, err := w.doAdd(".", w.Excludes) return err } if opts.Glob != "" { return w.AddGlob(opts.Glob) } _, err := w.Add(opts.Path) return err } func (w *Worktree) doAdd(path string, ignorePattern []gitignore.Pattern) (plumbing.Hash, error) { s, err := w.Status() if err != nil { return plumbing.ZeroHash, err } idx, err := w.r.Storer.Index() if err != nil { return plumbing.ZeroHash, err } var h plumbing.Hash var added bool fi, err := w.Filesystem.Lstat(path) if err != nil || !fi.IsDir() { added, h, err = w.doAddFile(idx, s, path, ignorePattern) } else { added, err = w.doAddDirectory(idx, s, path, ignorePattern) } if err != nil { return h, err } if !added { return h, nil } return h, w.r.Storer.SetIndex(idx) } // AddGlob adds all paths, matching pattern, to the index. If pattern matches a // directory path, all directory contents are added to the index recursively. No // error is returned if all matching paths are already staged in index. func (w *Worktree) AddGlob(pattern string) error { // TODO(mcuadros): deprecate in favor of AddWithOption in v6. files, err := util.Glob(w.Filesystem, pattern) if err != nil { return err } if len(files) == 0 { return ErrGlobNoMatches } s, err := w.Status() if err != nil { return err } idx, err := w.r.Storer.Index() if err != nil { return err } var saveIndex bool for _, file := range files { fi, err := w.Filesystem.Lstat(file) if err != nil { return err } var added bool if fi.IsDir() { added, err = w.doAddDirectory(idx, s, file, make([]gitignore.Pattern, 0)) } else { added, _, err = w.doAddFile(idx, s, file, make([]gitignore.Pattern, 0)) } if err != nil { return err } if !saveIndex && added { saveIndex = true } } if saveIndex { return w.r.Storer.SetIndex(idx) } return nil } // doAddFile create a new blob from path and update the index, added is true if // the file added is different from the index. func (w *Worktree) doAddFile(idx *index.Index, s Status, path string, ignorePattern []gitignore.Pattern) (added bool, h plumbing.Hash, err error) { if s.File(path).Worktree == Unmodified { return false, h, nil } if len(ignorePattern) > 0 { m := gitignore.NewMatcher(ignorePattern) matchPath := strings.Split(path, string(os.PathSeparator)) if m.Match(matchPath, true) { // ignore return false, h, nil } } h, err = w.copyFileToStorage(path) if err != nil { if os.IsNotExist(err) { added = true h, err = w.deleteFromIndex(idx, path) } return } if err := w.addOrUpdateFileToIndex(idx, path, h); err != nil { return false, h, err } return true, h, err } func (w *Worktree) copyFileToStorage(path string) (hash plumbing.Hash, err error) { fi, err := w.Filesystem.Lstat(path) if err != nil { return plumbing.ZeroHash, err } obj := w.r.Storer.NewEncodedObject() obj.SetType(plumbing.BlobObject) obj.SetSize(fi.Size()) writer, err := obj.Writer() if err != nil { return plumbing.ZeroHash, err } defer ioutil.CheckClose(writer, &err) if fi.Mode()&os.ModeSymlink != 0 { err = w.fillEncodedObjectFromSymlink(writer, path, fi) } else { err = w.fillEncodedObjectFromFile(writer, path, fi) } if err != nil { return plumbing.ZeroHash, err } return w.r.Storer.SetEncodedObject(obj) } func (w *Worktree) fillEncodedObjectFromFile(dst io.Writer, path string, fi os.FileInfo) (err error) { src, err := w.Filesystem.Open(path) if err != nil { return err } defer ioutil.CheckClose(src, &err) if _, err := io.Copy(dst, src); err != nil { return err } return err } func (w *Worktree) fillEncodedObjectFromSymlink(dst io.Writer, path string, fi os.FileInfo) error { target, err := w.Filesystem.Readlink(path) if err != nil { return err } _, err = dst.Write([]byte(target)) return err } func (w *Worktree) addOrUpdateFileToIndex(idx *index.Index, filename string, h plumbing.Hash) error { e, err := idx.Entry(filename) if err != nil && err != index.ErrEntryNotFound { return err } if err == index.ErrEntryNotFound { return w.doAddFileToIndex(idx, filename, h) } return w.doUpdateFileToIndex(e, filename, h) } func (w *Worktree) doAddFileToIndex(idx *index.Index, filename string, h plumbing.Hash) error { return w.doUpdateFileToIndex(idx.Add(filename), filename, h) } func (w *Worktree) doUpdateFileToIndex(e *index.Entry, filename string, h plumbing.Hash) error { info, err := w.Filesystem.Lstat(filename) if err != nil { return err } e.Hash = h e.ModifiedAt = info.ModTime() e.Mode, err = filemode.NewFromOSFileMode(info.Mode()) if err != nil { return err } if e.Mode.IsRegular() { e.Size = uint32(info.Size()) } fillSystemInfo(e, info.Sys()) return nil } // Remove removes files from the working tree and from the index. func (w *Worktree) Remove(path string) (plumbing.Hash, error) { // TODO(mcuadros): remove plumbing.Hash from signature at v5. idx, err := w.r.Storer.Index() if err != nil { return plumbing.ZeroHash, err } var h plumbing.Hash fi, err := w.Filesystem.Lstat(path) if err != nil || !fi.IsDir() { h, err = w.doRemoveFile(idx, path) } else { _, err = w.doRemoveDirectory(idx, path) } if err != nil { return h, err } return h, w.r.Storer.SetIndex(idx) } func (w *Worktree) doRemoveDirectory(idx *index.Index, directory string) (removed bool, err error) { files, err := w.Filesystem.ReadDir(directory) if err != nil { return false, err } for _, file := range files { name := path.Join(directory, file.Name()) var r bool if file.IsDir() { r, err = w.doRemoveDirectory(idx, name) } else { _, err = w.doRemoveFile(idx, name) if err == index.ErrEntryNotFound { err = nil } } if err != nil { return } if !removed && r { removed = true } } err = w.removeEmptyDirectory(directory) return } func (w *Worktree) removeEmptyDirectory(path string) error { files, err := w.Filesystem.ReadDir(path) if err != nil { return err } if len(files) != 0 { return nil } return w.Filesystem.Remove(path) } func (w *Worktree) doRemoveFile(idx *index.Index, path string) (plumbing.Hash, error) { hash, err := w.deleteFromIndex(idx, path) if err != nil { return plumbing.ZeroHash, err } return hash, w.deleteFromFilesystem(path) } func (w *Worktree) deleteFromIndex(idx *index.Index, path string) (plumbing.Hash, error) { e, err := idx.Remove(path) if err != nil { return plumbing.ZeroHash, err } return e.Hash, nil } func (w *Worktree) deleteFromFilesystem(path string) error { err := w.Filesystem.Remove(path) if os.IsNotExist(err) { return nil } return err } // RemoveGlob removes all paths, matching pattern, from the index. If pattern // matches a directory path, all directory contents are removed from the index // recursively. func (w *Worktree) RemoveGlob(pattern string) error { idx, err := w.r.Storer.Index() if err != nil { return err } entries, err := idx.Glob(pattern) if err != nil { return err } for _, e := range entries { file := filepath.FromSlash(e.Name) if _, err := w.Filesystem.Lstat(file); err != nil && !os.IsNotExist(err) { return err } if _, err := w.doRemoveFile(idx, file); err != nil { return err } dir, _ := filepath.Split(file) if err := w.removeEmptyDirectory(dir); err != nil { return err } } return w.r.Storer.SetIndex(idx) } // Move moves or rename a file in the worktree and the index, directories are // not supported. func (w *Worktree) Move(from, to string) (plumbing.Hash, error) { // TODO(mcuadros): support directories and/or implement support for glob if _, err := w.Filesystem.Lstat(from); err != nil { return plumbing.ZeroHash, err } if _, err := w.Filesystem.Lstat(to); err == nil { return plumbing.ZeroHash, ErrDestinationExists } idx, err := w.r.Storer.Index() if err != nil { return plumbing.ZeroHash, err } hash, err := w.deleteFromIndex(idx, from) if err != nil { return plumbing.ZeroHash, err } if err := w.Filesystem.Rename(from, to); err != nil { return hash, err } if err := w.addOrUpdateFileToIndex(idx, to, hash); err != nil { return hash, err } return hash, w.r.Storer.SetIndex(idx) }
vendor/github.com/jesseduffield/go-git/v5/worktree_status.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.9832940101623535, 0.07312922179698944, 0.00016411454998888075, 0.0001726174814393744, 0.22336742281913757 ]
{ "id": 6, "code_window": [ "\t\t})\n", "\t}\n", "\n", "\tfor _, item := range opts.Items {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\tmaxColumnSize := 1\n", "\n", "\tfor _, item := range opts.Items {\n", "\t\tif item.LabelColumns == nil {\n", "\t\t\titem.LabelColumns = []string{item.Label}\n", "\t\t}\n", "\n", "\t\tif item.OpensMenu {\n", "\t\t\titem.LabelColumns[0] = presentation.OpensMenuStyle(item.LabelColumns[0])\n", "\t\t}\n", "\n", "\t\tmaxColumnSize = utils.Max(maxColumnSize, len(item.LabelColumns))\n", "\t}\n", "\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 32 }
f2b972db67c4667ac1896df3556a2cb2422bef8a
test/integration/pullRebase/expected/repo/.git_keep/refs/remotes/origin/master
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0002560467110015452, 0.0002560467110015452, 0.0002560467110015452, 0.0002560467110015452, 0 ]
{ "id": 6, "code_window": [ "\t\t})\n", "\t}\n", "\n", "\tfor _, item := range opts.Items {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\tmaxColumnSize := 1\n", "\n", "\tfor _, item := range opts.Items {\n", "\t\tif item.LabelColumns == nil {\n", "\t\t\titem.LabelColumns = []string{item.Label}\n", "\t\t}\n", "\n", "\t\tif item.OpensMenu {\n", "\t\t\titem.LabelColumns[0] = presentation.OpensMenuStyle(item.LabelColumns[0])\n", "\t\t}\n", "\n", "\t\tmaxColumnSize = utils.Max(maxColumnSize, len(item.LabelColumns))\n", "\t}\n", "\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "add", "edit_start_line_idx": 32 }
d108cb97213835c25d44e14d167e7c5b48f94ce2
test/integration/pushWithCredentials/expected/repo/.git_keep/refs/heads/master
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017027910507749766, 0.00017027910507749766, 0.00017027910507749766, 0.00017027910507749766, 0 ]
{ "id": 7, "code_window": [ "\tfor _, item := range opts.Items {\n", "\t\tif item.OpensMenu && item.LabelColumns != nil {\n", "\t\t\treturn errors.New(\"Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user\")\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(item.LabelColumns) < maxColumnSize {\n", "\t\t\t// we require that each item has the same number of columns so we're padding out with blank strings\n", "\t\t\t// if this item has too few\n", "\t\t\titem.LabelColumns = append(item.LabelColumns, make([]string, maxColumnSize-len(item.LabelColumns))...)\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 33 }
package gui import ( "log" "github.com/jesseduffield/generics/slices" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) func (gui *Gui) getBindings(context types.Context) []*types.Binding { var bindingsGlobal, bindingsPanel, bindingsNavigation []*types.Binding bindings, _ := gui.GetInitialKeybindings() customBindings, err := gui.CustomCommandsClient.GetCustomCommandKeybindings() if err != nil { log.Fatal(err) } bindings = append(customBindings, bindings...) for _, binding := range bindings { if keybindings.GetKeyDisplay(binding.Key) != "" && binding.Description != "" { if len(binding.Contexts) == 0 && binding.ViewName == "" { bindingsGlobal = append(bindingsGlobal, binding) } else if binding.Tag == "navigation" { bindingsNavigation = append(bindingsNavigation, binding) } else if lo.Contains(binding.Contexts, string(context.GetKey())) { bindingsPanel = append(bindingsPanel, binding) } } } resultBindings := []*types.Binding{} resultBindings = append(resultBindings, uniqueBindings(bindingsPanel)...) // adding a separator between the panel-specific bindings and the other bindings resultBindings = append(resultBindings, &types.Binding{}) resultBindings = append(resultBindings, uniqueBindings(bindingsGlobal)...) resultBindings = append(resultBindings, uniqueBindings(bindingsNavigation)...) return resultBindings } // We shouldn't really need to do this. We should define alternative keys for the same // handler in the keybinding struct. func uniqueBindings(bindings []*types.Binding) []*types.Binding { return lo.UniqBy(bindings, func(binding *types.Binding) string { return binding.Description }) } func (gui *Gui) displayDescription(binding *types.Binding) string { if binding.OpensMenu { return presentation.OpensMenuStyle(binding.Description) } return binding.Description } func (gui *Gui) handleCreateOptionsMenu() error { context := gui.currentContext() bindings := gui.getBindings(context) menuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem { return &types.MenuItem{ Label: gui.displayDescription(binding), OnPress: func() error { if binding.Key == nil { return nil } return binding.Handler() }, Key: binding.Key, Tooltip: binding.Tooltip, } }) return gui.c.Menu(types.CreateMenuOptions{ Title: gui.c.Tr.MenuTitle, Items: menuItems, HideCancel: true, }) }
pkg/gui/options_menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.003761979518458247, 0.000609203998465091, 0.00016385795606765896, 0.0001731844386085868, 0.0011165353935211897 ]
{ "id": 7, "code_window": [ "\tfor _, item := range opts.Items {\n", "\t\tif item.OpensMenu && item.LabelColumns != nil {\n", "\t\t\treturn errors.New(\"Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user\")\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(item.LabelColumns) < maxColumnSize {\n", "\t\t\t// we require that each item has the same number of columns so we're padding out with blank strings\n", "\t\t\t// if this item has too few\n", "\t\t\titem.LabelColumns = append(item.LabelColumns, make([]string, maxColumnSize-len(item.LabelColumns))...)\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 33 }
test3
test/integration/pushNoFollowTags/expected/repo/myfile3
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0001797237346181646, 0.0001797237346181646, 0.0001797237346181646, 0.0001797237346181646, 0 ]
{ "id": 7, "code_window": [ "\tfor _, item := range opts.Items {\n", "\t\tif item.OpensMenu && item.LabelColumns != nil {\n", "\t\t\treturn errors.New(\"Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user\")\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(item.LabelColumns) < maxColumnSize {\n", "\t\t\t// we require that each item has the same number of columns so we're padding out with blank strings\n", "\t\t\t// if this item has too few\n", "\t\t\titem.LabelColumns = append(item.LabelColumns, make([]string, maxColumnSize-len(item.LabelColumns))...)\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 33 }
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = true [user] email = [email protected] name = CI
test/integration/undo2/expected/repo/.git_keep/config
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017821589426603168, 0.00017414795001968741, 0.00017008000577334315, 0.00017414795001968741, 0.000004067944246344268 ]
{ "id": 7, "code_window": [ "\tfor _, item := range opts.Items {\n", "\t\tif item.OpensMenu && item.LabelColumns != nil {\n", "\t\t\treturn errors.New(\"Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user\")\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(item.LabelColumns) < maxColumnSize {\n", "\t\t\t// we require that each item has the same number of columns so we're padding out with blank strings\n", "\t\t\t// if this item has too few\n", "\t\t\titem.LabelColumns = append(item.LabelColumns, make([]string, maxColumnSize-len(item.LabelColumns))...)\n" ], "file_path": "pkg/gui/menu_panel.go", "type": "replace", "edit_start_line_idx": 33 }
package controllers import ( "fmt" "regexp" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/filetree" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type FilesController struct { baseController *controllerCommon enterSubmodule func(submodule *models.SubmoduleConfig) error setCommitMessage func(message string) getSavedCommitMessage func() string switchToMergeFn func(path string) error } var _ types.IController = &FilesController{} func NewFilesController( common *controllerCommon, enterSubmodule func(submodule *models.SubmoduleConfig) error, setCommitMessage func(message string), getSavedCommitMessage func() string, switchToMergeFn func(path string) error, ) *FilesController { return &FilesController{ controllerCommon: common, enterSubmodule: enterSubmodule, setCommitMessage: setCommitMessage, getSavedCommitMessage: getSavedCommitMessage, switchToMergeFn: switchToMergeFn, } } func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.checkSelectedFileNode(self.press), Description: self.c.Tr.LcToggleStaged, }, { Key: opts.GetKey(opts.Config.Files.OpenStatusFilter), Handler: self.handleStatusFilterPressed, Description: self.c.Tr.LcFileFilter, }, { Key: opts.GetKey(opts.Config.Files.CommitChanges), Handler: self.HandleCommitPress, Description: self.c.Tr.CommitChanges, }, { Key: opts.GetKey(opts.Config.Files.CommitChangesWithoutHook), Handler: self.HandleWIPCommitPress, Description: self.c.Tr.LcCommitChangesWithoutHook, }, { Key: opts.GetKey(opts.Config.Files.AmendLastCommit), Handler: self.handleAmendCommitPress, Description: self.c.Tr.AmendLastCommit, }, { Key: opts.GetKey(opts.Config.Files.CommitChangesWithEditor), Handler: self.HandleCommitEditorPress, Description: self.c.Tr.CommitChangesWithEditor, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.checkSelectedFileNode(self.edit), Description: self.c.Tr.LcEditFile, }, { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.Open, Description: self.c.Tr.LcOpenFile, }, { Key: opts.GetKey(opts.Config.Files.IgnoreOrExcludeFile), Handler: self.checkSelectedFileNode(self.ignoreOrExcludeMenu), Description: self.c.Tr.Actions.IgnoreExcludeFile, }, { Key: opts.GetKey(opts.Config.Files.RefreshFiles), Handler: self.refresh, Description: self.c.Tr.LcRefreshFiles, }, { Key: opts.GetKey(opts.Config.Files.StashAllChanges), Handler: self.stash, Description: self.c.Tr.LcStashAllChanges, }, { Key: opts.GetKey(opts.Config.Files.ViewStashOptions), Handler: self.createStashMenu, Description: self.c.Tr.LcViewStashOptions, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.ToggleStagedAll), Handler: self.stageAll, Description: self.c.Tr.LcToggleStagedAll, }, { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.enter, Description: self.c.Tr.FileEnter, }, { Key: opts.GetKey(opts.Config.Commits.ViewResetOptions), Handler: self.createResetToUpstreamMenu, Description: self.c.Tr.LcViewResetToUpstreamOptions, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.ViewResetOptions), Handler: self.createResetMenu, Description: self.c.Tr.LcViewResetOptions, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.ToggleTreeView), Handler: self.toggleTreeView, Description: self.c.Tr.LcToggleTreeView, }, { Key: opts.GetKey(opts.Config.Files.OpenMergeTool), Handler: self.helpers.WorkingTree.OpenMergeTool, Description: self.c.Tr.LcOpenMergeTool, }, { Key: opts.GetKey(opts.Config.Files.Fetch), Handler: self.fetch, Description: self.c.Tr.LcFetch, }, } } func (self *FilesController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: "main", Key: gocui.MouseLeft, Handler: self.onClickMain, FromContext: string(self.context().GetKey()), }, { ViewName: "secondary", Key: gocui.MouseLeft, Handler: self.onClickSecondary, FromContext: string(self.context().GetKey()), }, } } func (self *FilesController) GetOnClick() func() error { return self.checkSelectedFileNode(self.press) } func (self *FilesController) press(node *filetree.FileNode) error { if node.IsLeaf() { file := node.File if file.HasInlineMergeConflicts { return self.c.PushContext(self.contexts.Merging) } if file.HasUnstagedChanges { self.c.LogAction(self.c.Tr.Actions.StageFile) if err := self.git.WorkingTree.StageFile(file.Name); err != nil { return self.c.Error(err) } } else { self.c.LogAction(self.c.Tr.Actions.UnstageFile) if err := self.git.WorkingTree.UnStageFile(file.Names(), file.Tracked); err != nil { return self.c.Error(err) } } } else { // if any files within have inline merge conflicts we can't stage or unstage, // or it'll end up with those >>>>>> lines actually staged if node.GetHasInlineMergeConflicts() { return self.c.ErrorMsg(self.c.Tr.ErrStageDirWithInlineMergeConflicts) } if node.GetHasUnstagedChanges() { self.c.LogAction(self.c.Tr.Actions.StageFile) if err := self.git.WorkingTree.StageFile(node.Path); err != nil { return self.c.Error(err) } } else { // pretty sure it doesn't matter that we're always passing true here self.c.LogAction(self.c.Tr.Actions.UnstageFile) if err := self.git.WorkingTree.UnStageFile([]string{node.Path}, true); err != nil { return self.c.Error(err) } } } if err := self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}); err != nil { return err } return self.context().HandleFocus() } func (self *FilesController) checkSelectedFileNode(callback func(*filetree.FileNode) error) func() error { return func() error { node := self.context().GetSelected() if node == nil { return nil } return callback(node) } } func (self *FilesController) Context() types.Context { return self.context() } func (self *FilesController) context() *context.WorkingTreeContext { return self.contexts.Files } func (self *FilesController) getSelectedFile() *models.File { node := self.context().GetSelected() if node == nil { return nil } return node.File } func (self *FilesController) enter() error { return self.EnterFile(types.OnFocusOpts{ClickedViewName: "", ClickedViewLineIdx: -1}) } func (self *FilesController) EnterFile(opts types.OnFocusOpts) error { node := self.context().GetSelected() if node == nil { return nil } if node.File == nil { return self.handleToggleDirCollapsed() } file := node.File submoduleConfigs := self.model.Submodules if file.IsSubmodule(submoduleConfigs) { submoduleConfig := file.SubmoduleConfig(submoduleConfigs) return self.enterSubmodule(submoduleConfig) } if file.HasInlineMergeConflicts { return self.switchToMerge() } if file.HasMergeConflicts { return self.c.ErrorMsg(self.c.Tr.FileStagingRequirements) } return self.c.PushContext(self.contexts.Staging, opts) } func (self *FilesController) allFilesStaged() bool { for _, file := range self.model.Files { if file.HasUnstagedChanges { return false } } return true } func (self *FilesController) stageAll() error { var err error if self.allFilesStaged() { self.c.LogAction(self.c.Tr.Actions.UnstageAllFiles) err = self.git.WorkingTree.UnstageAll() } else { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) err = self.git.WorkingTree.StageAll() } if err != nil { _ = self.c.Error(err) } if err := self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}); err != nil { return err } return self.contexts.Files.HandleFocus() } func (self *FilesController) unstageFiles(node *filetree.FileNode) error { return node.ForEachFile(func(file *models.File) error { if file.HasStagedChanges { if err := self.git.WorkingTree.UnStageFile(file.Names(), file.Tracked); err != nil { return err } } return nil }) } func (self *FilesController) ignoreOrExcludeTracked(node *filetree.FileNode, trAction string, f func(string) error) error { self.c.LogAction(trAction) // not 100% sure if this is necessary but I'll assume it is if err := self.unstageFiles(node); err != nil { return err } if err := self.git.WorkingTree.RemoveTrackedFiles(node.GetPath()); err != nil { return err } if err := f(node.GetPath()); err != nil { return err } return self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) } func (self *FilesController) ignoreOrExcludeUntracked(node *filetree.FileNode, trAction string, f func(string) error) error { self.c.LogAction(trAction) if err := f(node.GetPath()); err != nil { return err } return self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) } func (self *FilesController) ignoreOrExcludeFile(node *filetree.FileNode, trText string, trPrompt string, trAction string, f func(string) error) error { if node.GetIsTracked() { return self.c.Confirm(types.ConfirmOpts{ Title: trText, Prompt: trPrompt, HandleConfirm: func() error { return self.ignoreOrExcludeTracked(node, trAction, f) }, }) } return self.ignoreOrExcludeUntracked(node, trAction, f) } func (self *FilesController) ignore(node *filetree.FileNode) error { if node.GetPath() == ".gitignore" { return self.c.ErrorMsg(self.c.Tr.Actions.IgnoreFileErr) } err := self.ignoreOrExcludeFile(node, self.c.Tr.IgnoreTracked, self.c.Tr.IgnoreTrackedPrompt, self.c.Tr.Actions.IgnoreExcludeFile, self.git.WorkingTree.Ignore) if err != nil { return err } return nil } func (self *FilesController) exclude(node *filetree.FileNode) error { if node.GetPath() == ".git/info/exclude" { return self.c.ErrorMsg(self.c.Tr.Actions.ExcludeFileErr) } if node.GetPath() == ".gitignore" { return self.c.ErrorMsg(self.c.Tr.Actions.ExcludeGitIgnoreErr) } err := self.ignoreOrExcludeFile(node, self.c.Tr.ExcludeTracked, self.c.Tr.ExcludeTrackedPrompt, self.c.Tr.Actions.ExcludeFile, self.git.WorkingTree.Exclude) if err != nil { return err } return nil } func (self *FilesController) ignoreOrExcludeMenu(node *filetree.FileNode) error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Actions.IgnoreExcludeFile, Items: []*types.MenuItem{ { LabelColumns: []string{self.c.Tr.LcIgnoreFile}, OnPress: func() error { if err := self.ignore(node); err != nil { return self.c.Error(err) } return nil }, Key: 'i', }, { LabelColumns: []string{self.c.Tr.LcExcludeFile}, OnPress: func() error { if err := self.exclude(node); err != nil { return self.c.Error(err) } return nil }, Key: 'e', }, }, }) } func (self *FilesController) HandleWIPCommitPress() error { skipHookPrefix := self.c.UserConfig.Git.SkipHookPrefix if skipHookPrefix == "" { return self.c.ErrorMsg(self.c.Tr.SkipHookPrefixNotConfigured) } self.setCommitMessage(skipHookPrefix) return self.HandleCommitPress() } func (self *FilesController) commitPrefixConfigForRepo() *config.CommitPrefixConfig { cfg, ok := self.c.UserConfig.Git.CommitPrefixes[utils.GetCurrentRepoName()] if !ok { return nil } return &cfg } func (self *FilesController) prepareFilesForCommit() error { noStagedFiles := !self.helpers.WorkingTree.AnyStagedFiles() if noStagedFiles && self.c.UserConfig.Gui.SkipNoStagedFilesWarning { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) err := self.git.WorkingTree.StageAll() if err != nil { return err } return self.syncRefresh() } return nil } // for when you need to refetch files before continuing an action. Runs synchronously. func (self *FilesController) syncRefresh() error { return self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) } func (self *FilesController) refresh() error { return self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) } func (self *FilesController) HandleCommitPress() error { if err := self.prepareFilesForCommit(); err != nil { return self.c.Error(err) } if len(self.model.Files) == 0 { return self.c.ErrorMsg(self.c.Tr.NoFilesStagedTitle) } if !self.helpers.WorkingTree.AnyStagedFiles() { return self.promptToStageAllAndRetry(self.HandleCommitPress) } savedCommitMessage := self.getSavedCommitMessage() if len(savedCommitMessage) > 0 { self.setCommitMessage(savedCommitMessage) } else { commitPrefixConfig := self.commitPrefixConfigForRepo() if commitPrefixConfig != nil { prefixPattern := commitPrefixConfig.Pattern prefixReplace := commitPrefixConfig.Replace rgx, err := regexp.Compile(prefixPattern) if err != nil { return self.c.ErrorMsg(fmt.Sprintf("%s: %s", self.c.Tr.LcCommitPrefixPatternError, err.Error())) } prefix := rgx.ReplaceAllString(self.helpers.Refs.GetCheckedOutRef().Name, prefixReplace) self.setCommitMessage(prefix) } } if err := self.c.PushContext(self.contexts.CommitMessage); err != nil { return err } return nil } func (self *FilesController) promptToStageAllAndRetry(retry func() error) error { return self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.NoFilesStagedTitle, Prompt: self.c.Tr.NoFilesStagedPrompt, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) if err := self.git.WorkingTree.StageAll(); err != nil { return self.c.Error(err) } if err := self.syncRefresh(); err != nil { return self.c.Error(err) } return retry() }, }) } func (self *FilesController) handleAmendCommitPress() error { if len(self.model.Files) == 0 { return self.c.ErrorMsg(self.c.Tr.NoFilesStagedTitle) } if !self.helpers.WorkingTree.AnyStagedFiles() { return self.promptToStageAllAndRetry(self.handleAmendCommitPress) } if len(self.model.Commits) == 0 { return self.c.ErrorMsg(self.c.Tr.NoCommitToAmend) } return self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.AmendLastCommitTitle, Prompt: self.c.Tr.SureToAmend, HandleConfirm: func() error { cmdObj := self.git.Commit.AmendHeadCmdObj() self.c.LogAction(self.c.Tr.Actions.AmendCommit) return self.helpers.GPG.WithGpgHandling(cmdObj, self.c.Tr.AmendingStatus, nil) }, }) } // HandleCommitEditorPress - handle when the user wants to commit changes via // their editor rather than via the popup panel func (self *FilesController) HandleCommitEditorPress() error { if len(self.model.Files) == 0 { return self.c.ErrorMsg(self.c.Tr.NoFilesStagedTitle) } if !self.helpers.WorkingTree.AnyStagedFiles() { return self.promptToStageAllAndRetry(self.HandleCommitEditorPress) } self.c.LogAction(self.c.Tr.Actions.Commit) return self.c.RunSubprocessAndRefresh( self.git.Commit.CommitEditorCmdObj(), ) } func (self *FilesController) handleStatusFilterPressed() error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.FilteringMenuTitle, Items: []*types.MenuItem{ { Label: self.c.Tr.FilterStagedFiles, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayStaged) }, }, { Label: self.c.Tr.FilterUnstagedFiles, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayUnstaged) }, }, { Label: self.c.Tr.ResetCommitFilterState, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayAll) }, }, }, }) } func (self *FilesController) setStatusFiltering(filter filetree.FileTreeDisplayFilter) error { self.context().FileTreeViewModel.SetFilter(filter) return self.c.PostRefreshUpdate(self.context()) } func (self *FilesController) edit(node *filetree.FileNode) error { if node.File == nil { return self.c.ErrorMsg(self.c.Tr.ErrCannotEditDirectory) } return self.helpers.Files.EditFile(node.GetPath()) } func (self *FilesController) Open() error { node := self.context().GetSelected() if node == nil { return nil } return self.helpers.Files.OpenFile(node.GetPath()) } func (self *FilesController) switchToMerge() error { file := self.getSelectedFile() if file == nil { return nil } return self.switchToMergeFn(file.Name) } func (self *FilesController) createStashMenu() error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.LcStashOptions, Items: []*types.MenuItem{ { Label: self.c.Tr.LcStashAllChanges, OnPress: func() error { return self.handleStashSave(self.git.Stash.Save, self.c.Tr.Actions.StashAllChanges, self.c.Tr.NoFilesToStash) }, Key: 'a', }, { Label: self.c.Tr.LcStashAllChangesKeepIndex, OnPress: func() error { // if there are no staged files it behaves the same as Stash.Save return self.handleStashSave(self.git.Stash.StashAndKeepIndex, self.c.Tr.Actions.StashAllChangesKeepIndex, self.c.Tr.NoFilesToStash) }, Key: 'i', }, { Label: self.c.Tr.LcStashStagedChanges, OnPress: func() error { // there must be something in staging otherwise the current implementation mucks the stash up if !self.helpers.WorkingTree.AnyStagedFiles() { return self.c.ErrorMsg(self.c.Tr.NoTrackedStagedFilesStash) } return self.handleStashSave(self.git.Stash.SaveStagedChanges, self.c.Tr.Actions.StashStagedChanges, self.c.Tr.NoTrackedStagedFilesStash) }, Key: 's', }, { Label: self.c.Tr.LcStashUnstagedChanges, OnPress: func() error { if self.helpers.WorkingTree.AnyStagedFiles() { return self.handleStashSave(self.git.Stash.StashUnstagedChanges, self.c.Tr.Actions.StashUnstagedChanges, self.c.Tr.NoFilesToStash) } // ordinary stash return self.handleStashSave(self.git.Stash.Save, self.c.Tr.Actions.StashUnstagedChanges, self.c.Tr.NoFilesToStash) }, Key: 'u', }, }, }) } func (self *FilesController) stash() error { return self.handleStashSave(self.git.Stash.Save, self.c.Tr.Actions.StashAllChanges, self.c.Tr.NoTrackedStagedFilesStash) } func (self *FilesController) createResetToUpstreamMenu() error { return self.helpers.Refs.CreateGitResetMenu("@{upstream}") } func (self *FilesController) handleToggleDirCollapsed() error { node := self.context().GetSelected() if node == nil { return nil } self.context().FileTreeViewModel.ToggleCollapsed(node.GetPath()) if err := self.c.PostRefreshUpdate(self.contexts.Files); err != nil { self.c.Log.Error(err) } return nil } func (self *FilesController) toggleTreeView() error { self.context().FileTreeViewModel.ToggleShowTree() return self.c.PostRefreshUpdate(self.context()) } func (self *FilesController) handleStashSave(stashFunc func(message string) error, action string, errorMsg string) error { if !self.helpers.WorkingTree.IsWorkingTreeDirty() { return self.c.ErrorMsg(errorMsg) } return self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.StashChanges, HandleConfirm: func(stashComment string) error { self.c.LogAction(action) if err := stashFunc(stashComment); err != nil { return self.c.Error(err) } return self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH, types.FILES}}) }, }) } func (self *FilesController) onClickMain(opts gocui.ViewMouseBindingOpts) error { return self.EnterFile(types.OnFocusOpts{ClickedViewName: "main", ClickedViewLineIdx: opts.Y}) } func (self *FilesController) onClickSecondary(opts gocui.ViewMouseBindingOpts) error { return self.EnterFile(types.OnFocusOpts{ClickedViewName: "secondary", ClickedViewLineIdx: opts.Y}) } func (self *FilesController) fetch() error { return self.c.WithLoaderPanel(self.c.Tr.FetchWait, func() error { if err := self.fetchAux(); err != nil { _ = self.c.Error(err) } return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) }) } func (self *FilesController) fetchAux() (err error) { self.c.LogAction("Fetch") err = self.git.Sync.Fetch(git_commands.FetchOptions{}) if err != nil && strings.Contains(err.Error(), "exit status 128") { _ = self.c.ErrorMsg(self.c.Tr.PassUnameWrong) } _ = self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.COMMITS, types.REMOTES, types.TAGS}, Mode: types.ASYNC}) return err }
pkg/gui/controllers/files_controller.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0009369574836455286, 0.00020336541638243943, 0.00016424212662968785, 0.00017223041504621506, 0.00012131091352785006 ]
{ "id": 8, "code_window": [ "\t\"log\"\n", "\n", "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/samber/lo\"\n", ")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 7 }
package gui import ( "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" ) func (gui *Gui) getMenuOptions() map[string]string { keybindingConfig := gui.c.UserConfig.Keybinding return map[string]string{ gui.getKeyDisplay(keybindingConfig.Universal.Return): gui.c.Tr.LcClose, fmt.Sprintf("%s %s", gui.getKeyDisplay(keybindingConfig.Universal.PrevItem), gui.getKeyDisplay(keybindingConfig.Universal.NextItem)): gui.c.Tr.LcNavigate, gui.getKeyDisplay(keybindingConfig.Universal.Select): gui.c.Tr.LcExecute, } } // note: items option is mutated by this function func (gui *Gui) createMenu(opts types.CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.c.Tr.LcCancel}, OnPress: func() error { return nil }, }) } for _, item := range opts.Items { if item.OpensMenu && item.LabelColumns != nil { return errors.New("Message for the developer of this app: you've set opensMenu with displaystrings on the menu panel. Bad developer!. Apologies, user") } } gui.State.Contexts.Menu.SetMenuItems(opts.Items) gui.State.Contexts.Menu.SetSelectedLineIdx(0) gui.Views.Menu.Title = opts.Title gui.Views.Menu.FgColor = theme.GocuiDefaultTextColor gui.Views.Menu.SetOnSelectItem(gui.onSelectItemWrapper(func(selectedLine int) error { return nil })) gui.Views.Tooltip.Wrap = true gui.Views.Tooltip.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Visible = true // resetting keybindings so that the menu-specific keybindings are registered if err := gui.resetKeybindings(); err != nil { return err } _ = gui.c.PostRefreshUpdate(gui.State.Contexts.Menu) // TODO: ensure that if we're opened a menu from within a menu that it renders correctly return gui.c.PushContext(gui.State.Contexts.Menu) }
pkg/gui/menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.014503579586744308, 0.002219554502516985, 0.00016573697212152183, 0.00017056755314115435, 0.0050149355083703995 ]
{ "id": 8, "code_window": [ "\t\"log\"\n", "\n", "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/samber/lo\"\n", ")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 7 }
0000000000000000000000000000000000000000 42530e986dbb65877ed8d61ca0c816e425e5c62e Jesse Duffield <[email protected]> 1534792759 +0100 clone: from /Users/jesseduffieldduffield/go/src/github.com/jesseduffield/lazygit/test/integration/submoduleReset/actual/other_repo 42530e986dbb65877ed8d61ca0c816e425e5c62e a50a5125768001a3ea263ffb7cafbc421a508153 Jesse Duffield <[email protected]> 1648348154 +1100 rebase -i (start): checkout a50a5125768001a3ea263ffb7cafbc421a508153 a50a5125768001a3ea263ffb7cafbc421a508153 a50a5125768001a3ea263ffb7cafbc421a508153 Jesse Duffield <[email protected]> 1648348154 +1100 rebase -i (finish): returning to refs/heads/master a50a5125768001a3ea263ffb7cafbc421a508153 a50a5125768001a3ea263ffb7cafbc421a508153 Jesse Duffield <[email protected]> 1648348162 +1100 reset: moving to HEAD a50a5125768001a3ea263ffb7cafbc421a508153 42530e986dbb65877ed8d61ca0c816e425e5c62e Jesse Duffield <[email protected]> 1648348162 +1100 checkout: moving from master to 42530e986dbb65877ed8d61ca0c816e425e5c62e
test/integration/submoduleReset/expected/repo/.git_keep/modules/other_repo/logs/HEAD
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0377369150519371, 0.0377369150519371, 0.0377369150519371, 0.0377369150519371, 0 ]
{ "id": 8, "code_window": [ "\t\"log\"\n", "\n", "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/samber/lo\"\n", ")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 7 }
test
test/integration/filterPath3/expected/repo/.git_keep/COMMIT_EDITMSG
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00017192165250889957, 0.00017192165250889957, 0.00017192165250889957, 0.00017192165250889957, 0 ]
{ "id": 8, "code_window": [ "\t\"log\"\n", "\n", "\t\"github.com/jesseduffield/generics/slices\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/keybindings\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/presentation\"\n", "\t\"github.com/jesseduffield/lazygit/pkg/gui/types\"\n", "\t\"github.com/samber/lo\"\n", ")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 7 }
{ "description": "checking out a commit in the reflog context", "speed": 10 }
test/integration/reflogCheckout/test.json
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016869633691385388, 0.00016869633691385388, 0.00016869633691385388, 0.00016869633691385388, 0 ]
{ "id": 9, "code_window": [ "\treturn lo.UniqBy(bindings, func(binding *types.Binding) string {\n", "\t\treturn binding.Description\n", "\t})\n", "}\n", "\n", "func (gui *Gui) displayDescription(binding *types.Binding) string {\n", "\tif binding.OpensMenu {\n", "\t\treturn presentation.OpensMenuStyle(binding.Description)\n", "\t}\n", "\n", "\treturn binding.Description\n", "}\n", "\n", "func (gui *Gui) handleCreateOptionsMenu() error {\n", "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 52 }
package gui import ( "log" "github.com/jesseduffield/generics/slices" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) func (gui *Gui) getBindings(context types.Context) []*types.Binding { var bindingsGlobal, bindingsPanel, bindingsNavigation []*types.Binding bindings, _ := gui.GetInitialKeybindings() customBindings, err := gui.CustomCommandsClient.GetCustomCommandKeybindings() if err != nil { log.Fatal(err) } bindings = append(customBindings, bindings...) for _, binding := range bindings { if keybindings.GetKeyDisplay(binding.Key) != "" && binding.Description != "" { if len(binding.Contexts) == 0 && binding.ViewName == "" { bindingsGlobal = append(bindingsGlobal, binding) } else if binding.Tag == "navigation" { bindingsNavigation = append(bindingsNavigation, binding) } else if lo.Contains(binding.Contexts, string(context.GetKey())) { bindingsPanel = append(bindingsPanel, binding) } } } resultBindings := []*types.Binding{} resultBindings = append(resultBindings, uniqueBindings(bindingsPanel)...) // adding a separator between the panel-specific bindings and the other bindings resultBindings = append(resultBindings, &types.Binding{}) resultBindings = append(resultBindings, uniqueBindings(bindingsGlobal)...) resultBindings = append(resultBindings, uniqueBindings(bindingsNavigation)...) return resultBindings } // We shouldn't really need to do this. We should define alternative keys for the same // handler in the keybinding struct. func uniqueBindings(bindings []*types.Binding) []*types.Binding { return lo.UniqBy(bindings, func(binding *types.Binding) string { return binding.Description }) } func (gui *Gui) displayDescription(binding *types.Binding) string { if binding.OpensMenu { return presentation.OpensMenuStyle(binding.Description) } return binding.Description } func (gui *Gui) handleCreateOptionsMenu() error { context := gui.currentContext() bindings := gui.getBindings(context) menuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem { return &types.MenuItem{ Label: gui.displayDescription(binding), OnPress: func() error { if binding.Key == nil { return nil } return binding.Handler() }, Key: binding.Key, Tooltip: binding.Tooltip, } }) return gui.c.Menu(types.CreateMenuOptions{ Title: gui.c.Tr.MenuTitle, Items: menuItems, HideCancel: true, }) }
pkg/gui/options_menu_panel.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.9977179765701294, 0.18782013654708862, 0.0001678177941357717, 0.003625081852078438, 0.3261969983577728 ]
{ "id": 9, "code_window": [ "\treturn lo.UniqBy(bindings, func(binding *types.Binding) string {\n", "\t\treturn binding.Description\n", "\t})\n", "}\n", "\n", "func (gui *Gui) displayDescription(binding *types.Binding) string {\n", "\tif binding.OpensMenu {\n", "\t\treturn presentation.OpensMenuStyle(binding.Description)\n", "\t}\n", "\n", "\treturn binding.Description\n", "}\n", "\n", "func (gui *Gui) handleCreateOptionsMenu() error {\n", "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 52 }
0000000000000000000000000000000000000000 75e9e90a1d58c37d97d46a543dfbfd0f33fc52d8 CI <[email protected]> 1617675445 +1000 branch: Created from HEAD
test/integration/branchSuggestions/expected/repo/.git_keep/logs/refs/heads/new-branch
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016786980268079787, 0.00016786980268079787, 0.00016786980268079787, 0.00016786980268079787, 0 ]
{ "id": 9, "code_window": [ "\treturn lo.UniqBy(bindings, func(binding *types.Binding) string {\n", "\t\treturn binding.Description\n", "\t})\n", "}\n", "\n", "func (gui *Gui) displayDescription(binding *types.Binding) string {\n", "\tif binding.OpensMenu {\n", "\t\treturn presentation.OpensMenuStyle(binding.Description)\n", "\t}\n", "\n", "\treturn binding.Description\n", "}\n", "\n", "func (gui *Gui) handleCreateOptionsMenu() error {\n", "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 52 }
package gui import ( "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/controllers" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/modes/cherrypicking" "github.com/jesseduffield/lazygit/pkg/gui/services/custom_commands" ) func (gui *Gui) resetControllers() { helperCommon := gui.c osCommand := gui.os model := gui.State.Model refsHelper := helpers.NewRefsHelper( helperCommon, gui.git, gui.State.Contexts, model, ) rebaseHelper := helpers.NewMergeAndRebaseHelper(helperCommon, gui.State.Contexts, gui.git, gui.takeOverMergeConflictScrolling, refsHelper) suggestionsHelper := helpers.NewSuggestionsHelper(helperCommon, model, gui.refreshSuggestions) gui.helpers = &helpers.Helpers{ Refs: refsHelper, Host: helpers.NewHostHelper(helperCommon, gui.git), PatchBuilding: helpers.NewPatchBuildingHelper(helperCommon, gui.git), Bisect: helpers.NewBisectHelper(helperCommon, gui.git), Suggestions: suggestionsHelper, Files: helpers.NewFilesHelper(helperCommon, gui.git, osCommand), WorkingTree: helpers.NewWorkingTreeHelper(helperCommon, gui.git, model), Tags: helpers.NewTagsHelper(helperCommon, gui.git), GPG: helpers.NewGpgHelper(helperCommon, gui.os, gui.git), MergeAndRebase: rebaseHelper, CherryPick: helpers.NewCherryPickHelper( helperCommon, gui.git, gui.State.Contexts, func() *cherrypicking.CherryPicking { return gui.State.Modes.CherryPicking }, rebaseHelper, ), Upstream: helpers.NewUpstreamHelper(helperCommon, model, suggestionsHelper.GetRemoteBranchesSuggestionsFunc), } gui.CustomCommandsClient = custom_commands.NewClient( helperCommon, gui.os, gui.git, gui.State.Contexts, gui.helpers, gui.getKey, ) common := controllers.NewControllerCommon( helperCommon, osCommand, gui.git, gui.helpers, model, gui.State.Contexts, gui.State.Modes, ) syncController := controllers.NewSyncController( common, ) submodulesController := controllers.NewSubmodulesController( common, gui.enterSubmodule, ) bisectController := controllers.NewBisectController(common) getSavedCommitMessage := func() string { return gui.State.savedCommitMessage } getCommitMessage := func() string { return strings.TrimSpace(gui.Views.CommitMessage.TextArea.GetContent()) } setCommitMessage := gui.getSetTextareaTextFn(func() *gocui.View { return gui.Views.CommitMessage }) onCommitAttempt := func(message string) { gui.State.savedCommitMessage = message gui.Views.CommitMessage.ClearTextArea() } onCommitSuccess := func() { gui.State.savedCommitMessage = "" } commitMessageController := controllers.NewCommitMessageController( common, getCommitMessage, onCommitAttempt, onCommitSuccess, ) remoteBranchesController := controllers.NewRemoteBranchesController(common) menuController := controllers.NewMenuController(common) localCommitsController := controllers.NewLocalCommitsController(common, syncController.HandlePull) tagsController := controllers.NewTagsController(common) filesController := controllers.NewFilesController( common, gui.enterSubmodule, setCommitMessage, getSavedCommitMessage, gui.switchToMerge, ) remotesController := controllers.NewRemotesController( common, func(branches []*models.RemoteBranch) { gui.State.Model.RemoteBranches = branches }, ) undoController := controllers.NewUndoController(common) globalController := controllers.NewGlobalController(common) branchesController := controllers.NewBranchesController(common) gitFlowController := controllers.NewGitFlowController(common) filesRemoveController := controllers.NewFilesRemoveController(common) stashController := controllers.NewStashController(common) commitFilesController := controllers.NewCommitFilesController(common) setSubCommits := func(commits []*models.Commit) { gui.State.Model.SubCommits = commits } for _, context := range []controllers.CanSwitchToSubCommits{ gui.State.Contexts.Branches, gui.State.Contexts.RemoteBranches, gui.State.Contexts.Tags, gui.State.Contexts.ReflogCommits, } { controllers.AttachControllers(context, controllers.NewSwitchToSubCommitsController( common, setSubCommits, context, )) } for _, context := range []controllers.CanSwitchToDiffFiles{ gui.State.Contexts.LocalCommits, gui.State.Contexts.SubCommits, gui.State.Contexts.Stash, } { controllers.AttachControllers(context, controllers.NewSwitchToDiffFilesController( common, gui.SwitchToCommitFilesContext, context, )) } for _, context := range []controllers.ContainsCommits{ gui.State.Contexts.LocalCommits, gui.State.Contexts.ReflogCommits, gui.State.Contexts.SubCommits, } { controllers.AttachControllers(context, controllers.NewBasicCommitsController(common, context)) } controllers.AttachControllers(gui.State.Contexts.Files, filesController, filesRemoveController) controllers.AttachControllers(gui.State.Contexts.Tags, tagsController) controllers.AttachControllers(gui.State.Contexts.Submodules, submodulesController) controllers.AttachControllers(gui.State.Contexts.LocalCommits, localCommitsController, bisectController) controllers.AttachControllers(gui.State.Contexts.Branches, branchesController, gitFlowController) controllers.AttachControllers(gui.State.Contexts.LocalCommits, localCommitsController, bisectController) controllers.AttachControllers(gui.State.Contexts.CommitFiles, commitFilesController) controllers.AttachControllers(gui.State.Contexts.Remotes, remotesController) controllers.AttachControllers(gui.State.Contexts.Stash, stashController) controllers.AttachControllers(gui.State.Contexts.Menu, menuController) controllers.AttachControllers(gui.State.Contexts.CommitMessage, commitMessageController) controllers.AttachControllers(gui.State.Contexts.RemoteBranches, remoteBranchesController) controllers.AttachControllers(gui.State.Contexts.Global, syncController, undoController, globalController) // this must come last so that we've got our click handlers defined against the context listControllerFactory := controllers.NewListControllerFactory(gui.c) for _, context := range gui.getListContexts() { controllers.AttachControllers(context, listControllerFactory.Create(context)) } }
pkg/gui/controllers.go
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0024775629863142967, 0.0003653445455711335, 0.00016470807895530015, 0.00018507763161323965, 0.0005345523240976036 ]
{ "id": 9, "code_window": [ "\treturn lo.UniqBy(bindings, func(binding *types.Binding) string {\n", "\t\treturn binding.Description\n", "\t})\n", "}\n", "\n", "func (gui *Gui) displayDescription(binding *types.Binding) string {\n", "\tif binding.OpensMenu {\n", "\t\treturn presentation.OpensMenuStyle(binding.Description)\n", "\t}\n", "\n", "\treturn binding.Description\n", "}\n", "\n", "func (gui *Gui) handleCreateOptionsMenu() error {\n", "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 52 }
#!/bin/sh set -e cd $1 git init git config user.email "[email protected]" git config user.name "Author1" echo test1 > myfile1 git add . git commit -am "myfile1" echo test2 > myfile2 git add . git commit -am "myfile2" git config user.email "[email protected]" git config user.name "Author2"
test/integration/resetAuthor/setup.sh
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00047066868864931166, 0.0002706608211155981, 0.00017018333892337978, 0.00017113039211835712, 0.00014142745931167156 ]
{ "id": 10, "code_window": [ "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n", "\t\treturn &types.MenuItem{\n", "\t\t\tLabel: gui.displayDescription(binding),\n", "\t\t\tOnPress: func() error {\n", "\t\t\t\tif binding.Key == nil {\n", "\t\t\t\t\treturn nil\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tOpensMenu: binding.OpensMenu,\n", "\t\t\tLabel: binding.Description,\n" ], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 66 }
package context import ( "github.com/jesseduffield/generics/slices" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type MenuContext struct { *MenuViewModel *ListContextTrait } var _ types.IListContext = (*MenuContext)(nil) func NewMenuContext( view *gocui.View, c *types.HelperCommon, getOptionsMap func() map[string]string, renderToDescriptionView func(string), ) *MenuContext { viewModel := NewMenuViewModel() onFocus := func(...types.OnFocusOpts) error { selectedMenuItem := viewModel.GetSelected() renderToDescriptionView(selectedMenuItem.Tooltip) return nil } return &MenuContext{ MenuViewModel: viewModel, ListContextTrait: &ListContextTrait{ Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{ ViewName: "menu", Key: "menu", Kind: types.PERSISTENT_POPUP, OnGetOptionsMap: getOptionsMap, Focusable: true, }), ContextCallbackOpts{ OnFocus: onFocus, }), getDisplayStrings: viewModel.GetDisplayStrings, list: viewModel, viewTrait: NewViewTrait(view), c: c, }, } } // TODO: remove this thing. func (self *MenuContext) GetSelectedItemId() string { item := self.GetSelected() if item == nil { return "" } return item.Label } type MenuViewModel struct { menuItems []*types.MenuItem *BasicViewModel[*types.MenuItem] } func NewMenuViewModel() *MenuViewModel { self := &MenuViewModel{ menuItems: nil, } self.BasicViewModel = NewBasicViewModel(func() []*types.MenuItem { return self.menuItems }) return self } func (self *MenuViewModel) SetMenuItems(items []*types.MenuItem) { self.menuItems = items } // TODO: move into presentation package func (self *MenuViewModel) GetDisplayStrings(_startIdx int, _length int) [][]string { showKeys := slices.Some(self.menuItems, func(item *types.MenuItem) bool { return item.Key != nil }) return slices.Map(self.menuItems, func(item *types.MenuItem) []string { displayStrings := getItemDisplayStrings(item) if showKeys { displayStrings = slices.Prepend(displayStrings, style.FgCyan.Sprint(keybindings.GetKeyDisplay(item.Key))) } return displayStrings }) } func getItemDisplayStrings(item *types.MenuItem) []string { if item.LabelColumns != nil { return item.LabelColumns } styledStr := item.Label if item.OpensMenu { styledStr = presentation.OpensMenuStyle(styledStr) } return []string{styledStr} } func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { basicBindings := self.ListContextTrait.GetKeybindings(opts) menuItemsWithKeys := slices.Filter(self.menuItems, func(item *types.MenuItem) bool { return item.Key != nil }) menuItemBindings := slices.Map(menuItemsWithKeys, func(item *types.MenuItem) *types.Binding { return &types.Binding{ Key: item.Key, Handler: func() error { return self.OnMenuPress(item) }, } }) // appending because that means the menu item bindings have lower precedence. // So if a basic binding is to escape from the menu, we want that to still be // what happens when you press escape. This matters when we're showing the menu // for all keybindings of say the files context. return append(basicBindings, menuItemBindings...) } func (self *MenuContext) OnMenuPress(selectedItem *types.MenuItem) error { if err := self.c.PopContext(); err != nil { return err } if err := selectedItem.OnPress(); err != nil { return err } return nil }
pkg/gui/context/menu_context.go
1
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.2660380005836487, 0.03106064349412918, 0.00016297181718982756, 0.0007183702546171844, 0.07497862726449966 ]
{ "id": 10, "code_window": [ "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n", "\t\treturn &types.MenuItem{\n", "\t\t\tLabel: gui.displayDescription(binding),\n", "\t\t\tOnPress: func() error {\n", "\t\t\t\tif binding.Key == nil {\n", "\t\t\t\t\treturn nil\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tOpensMenu: binding.OpensMenu,\n", "\t\t\tLabel: binding.Description,\n" ], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 66 }
f11c72f0484c803d954446036bf464c3b8523330
test/integration/pullAndSetUpstream/expected/repo/.git_keep/ORIG_HEAD
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.00016281245916616172, 0.00016281245916616172, 0.00016281245916616172, 0.00016281245916616172, 0 ]
{ "id": 10, "code_window": [ "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n", "\t\treturn &types.MenuItem{\n", "\t\t\tLabel: gui.displayDescription(binding),\n", "\t\t\tOnPress: func() error {\n", "\t\t\t\tif binding.Key == nil {\n", "\t\t\t\t\treturn nil\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tOpensMenu: binding.OpensMenu,\n", "\t\t\tLabel: binding.Description,\n" ], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 66 }
0000000000000000000000000000000000000000 5a5a519752ffd367bbd85dfbc19e5b18d44d6223 CI <[email protected]> 1617683609 +1000 commit (initial): file0 5a5a519752ffd367bbd85dfbc19e5b18d44d6223 713ec49844ebad06a5c98fd3c5ce1445f664c3c6 CI <[email protected]> 1617683609 +1000 commit: file1 713ec49844ebad06a5c98fd3c5ce1445f664c3c6 e23253d1f81331e1c94a5a5f68e2d4cc1cbee2fd CI <[email protected]> 1617683609 +1000 commit: file2 e23253d1f81331e1c94a5a5f68e2d4cc1cbee2fd afeb127e4579981e4b852e8aabb44b07f2ea4e09 CI <[email protected]> 1617683609 +1000 commit: file4 afeb127e4579981e4b852e8aabb44b07f2ea4e09 afeb127e4579981e4b852e8aabb44b07f2ea4e09 CI <[email protected]> 1617683609 +1000 checkout: moving from master to branch2 afeb127e4579981e4b852e8aabb44b07f2ea4e09 ac7b38400c8aed050f379f9643b953b9d428fda1 CI <[email protected]> 1617683609 +1000 commit: file4 ac7b38400c8aed050f379f9643b953b9d428fda1 a955e641b00e7e896842122a3537c70476d7b4e0 CI <[email protected]> 1617683609 +1000 commit: file4 a955e641b00e7e896842122a3537c70476d7b4e0 bc8891320172f4cfa3efd7bb8767a46daa200d79 CI <[email protected]> 1617683609 +1000 commit: file2 bc8891320172f4cfa3efd7bb8767a46daa200d79 afeb127e4579981e4b852e8aabb44b07f2ea4e09 CI <[email protected]> 1617683610 +1000 checkout: moving from branch2 to master afeb127e4579981e4b852e8aabb44b07f2ea4e09 afeb127e4579981e4b852e8aabb44b07f2ea4e09 CI <[email protected]> 1617683619 +1000 rebase -i (start): checkout HEAD afeb127e4579981e4b852e8aabb44b07f2ea4e09 35bedc872b1ca9e026e51c4017416acba4b3d64b CI <[email protected]> 1617683619 +1000 rebase -i (pick): file2 35bedc872b1ca9e026e51c4017416acba4b3d64b 35bedc872b1ca9e026e51c4017416acba4b3d64b CI <[email protected]> 1617683619 +1000 rebase -i (finish): returning to refs/heads/master
test/integration/reflogCherryPick/expected/repo/.git_keep/logs/HEAD
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0003466643102001399, 0.0002577755367383361, 0.00016888673417270184, 0.0002577755367383361, 0.00008888878801371902 ]
{ "id": 10, "code_window": [ "\tcontext := gui.currentContext()\n", "\tbindings := gui.getBindings(context)\n", "\n", "\tmenuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {\n", "\t\treturn &types.MenuItem{\n", "\t\t\tLabel: gui.displayDescription(binding),\n", "\t\t\tOnPress: func() error {\n", "\t\t\t\tif binding.Key == nil {\n", "\t\t\t\t\treturn nil\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tOpensMenu: binding.OpensMenu,\n", "\t\t\tLabel: binding.Description,\n" ], "file_path": "pkg/gui/options_menu_panel.go", "type": "replace", "edit_start_line_idx": 66 }
{"KeyEvents":[{"Timestamp":635,"Mod":0,"Key":13,"Ch":13},{"Timestamp":1379,"Mod":0,"Key":256,"Ch":47},{"Timestamp":1683,"Mod":0,"Key":256,"Ch":108},{"Timestamp":1707,"Mod":0,"Key":256,"Ch":105},{"Timestamp":1739,"Mod":0,"Key":256,"Ch":110},{"Timestamp":1812,"Mod":0,"Key":256,"Ch":101},{"Timestamp":1884,"Mod":0,"Key":256,"Ch":32},{"Timestamp":2003,"Mod":0,"Key":256,"Ch":51},{"Timestamp":2172,"Mod":0,"Key":13,"Ch":13},{"Timestamp":2532,"Mod":0,"Key":256,"Ch":32},{"Timestamp":3621,"Mod":0,"Key":258,"Ch":0},{"Timestamp":4209,"Mod":0,"Key":27,"Ch":0},{"Timestamp":4723,"Mod":0,"Key":257,"Ch":0},{"Timestamp":5004,"Mod":0,"Key":256,"Ch":32},{"Timestamp":5188,"Mod":0,"Key":257,"Ch":0},{"Timestamp":5636,"Mod":0,"Key":258,"Ch":0},{"Timestamp":5923,"Mod":0,"Key":256,"Ch":32},{"Timestamp":7412,"Mod":0,"Key":256,"Ch":47},{"Timestamp":8027,"Mod":0,"Key":256,"Ch":108},{"Timestamp":8060,"Mod":0,"Key":256,"Ch":105},{"Timestamp":8084,"Mod":0,"Key":256,"Ch":110},{"Timestamp":8139,"Mod":0,"Key":256,"Ch":101},{"Timestamp":8228,"Mod":0,"Key":256,"Ch":32},{"Timestamp":8315,"Mod":0,"Key":256,"Ch":52},{"Timestamp":8556,"Mod":0,"Key":13,"Ch":13},{"Timestamp":8915,"Mod":0,"Key":256,"Ch":32},{"Timestamp":9622,"Mod":0,"Key":27,"Ch":0},{"Timestamp":10414,"Mod":0,"Key":27,"Ch":0},{"Timestamp":11140,"Mod":0,"Key":256,"Ch":99},{"Timestamp":11419,"Mod":0,"Key":256,"Ch":97},{"Timestamp":11500,"Mod":0,"Key":256,"Ch":115},{"Timestamp":11580,"Mod":0,"Key":256,"Ch":100},{"Timestamp":11813,"Mod":0,"Key":13,"Ch":13},{"Timestamp":12276,"Mod":0,"Key":256,"Ch":113}],"ResizeEvents":[{"Timestamp":0,"Width":127,"Height":35}]}
test/integration/searchingInStagingPanel/recording.json
0
https://github.com/jesseduffield/lazygit/commit/ab5a8091f5d8768406f32260711131ccbcedb195
[ 0.0001669420744292438, 0.0001669420744292438, 0.0001669420744292438, 0.0001669420744292438, 0 ]
{ "id": 0, "code_window": [ "\t\tblocksHashSame := ok && bytes.Equal(ef.BlocksHash, f.BlocksHash)\n", "\n", "\t\tif ok {\n", "\t\t\tif !ef.IsDirectory() && !ef.IsDeleted() && !ef.IsInvalid() {\n", "\t\t\t\tfor _, block := range ef.Blocks {\n", "\t\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\t\tif err != nil {\n", "\t\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif len(ef.Blocks) != 0 && !ef.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 203 }
// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package db import ( "bytes" "context" "encoding/binary" "time" "github.com/greatroar/blobloom" "github.com/syncthing/syncthing/lib/db/backend" "github.com/syncthing/syncthing/lib/protocol" "github.com/syncthing/syncthing/lib/sha256" "github.com/syncthing/syncthing/lib/sync" "github.com/syncthing/syncthing/lib/util" "github.com/thejerf/suture" ) const ( // We set the bloom filter capacity to handle 100k individual items with // a false positive probability of 1% for the first pass. Once we know // how many items we have we will use that number instead, if it's more // than 100k. For fewer than 100k items we will just get better false // positive rate instead. indirectGCBloomCapacity = 100000 indirectGCBloomFalsePositiveRate = 0.01 // 1% indirectGCBloomMaxBytes = 32 << 20 // Use at most 32MiB memory, which covers our desired FP rate at 27 M items indirectGCDefaultInterval = 13 * time.Hour indirectGCTimeKey = "lastIndirectGCTime" // Use indirection for the block list when it exceeds this many entries blocksIndirectionCutoff = 3 // Use indirection for the version vector when it exceeds this many entries versionIndirectionCutoff = 10 recheckDefaultInterval = 30 * 24 * time.Hour ) // Lowlevel is the lowest level database interface. It has a very simple // purpose: hold the actual backend database, and the in-memory state // that belong to that database. In the same way that a single on disk // database can only be opened once, there should be only one Lowlevel for // any given backend. type Lowlevel struct { *suture.Supervisor backend.Backend folderIdx *smallIndex deviceIdx *smallIndex keyer keyer gcMut sync.RWMutex gcKeyCount int indirectGCInterval time.Duration recheckInterval time.Duration } func NewLowlevel(backend backend.Backend, opts ...Option) *Lowlevel { db := &Lowlevel{ Supervisor: suture.New("db.Lowlevel", suture.Spec{ // Only log restarts in debug mode. Log: func(line string) { l.Debugln(line) }, PassThroughPanics: true, }), Backend: backend, folderIdx: newSmallIndex(backend, []byte{KeyTypeFolderIdx}), deviceIdx: newSmallIndex(backend, []byte{KeyTypeDeviceIdx}), gcMut: sync.NewRWMutex(), indirectGCInterval: indirectGCDefaultInterval, recheckInterval: recheckDefaultInterval, } for _, opt := range opts { opt(db) } db.keyer = newDefaultKeyer(db.folderIdx, db.deviceIdx) db.Add(util.AsService(db.gcRunner, "db.Lowlevel/gcRunner")) return db } type Option func(*Lowlevel) // WithRecheckInterval sets the time interval in between metadata recalculations // and consistency checks. func WithRecheckInterval(dur time.Duration) Option { return func(db *Lowlevel) { if dur > 0 { db.recheckInterval = dur } } } // WithIndirectGCInterval sets the time interval in between GC runs. func WithIndirectGCInterval(dur time.Duration) Option { return func(db *Lowlevel) { if dur > 0 { db.indirectGCInterval = dur } } } // ListFolders returns the list of folders currently in the database func (db *Lowlevel) ListFolders() []string { return db.folderIdx.Values() } // updateRemoteFiles adds a list of fileinfos to the database and updates the // global versionlist and metadata. func (db *Lowlevel) updateRemoteFiles(folder, device []byte, fs []protocol.FileInfo, meta *metadataTracker) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk, gk, keyBuf []byte devID := protocol.DeviceIDFromBytes(device) for _, f := range fs { name := []byte(f.Name) dk, err = db.keyer.GenerateDeviceFileKey(dk, folder, device, name) if err != nil { return err } ef, ok, err := t.getFileTrunc(dk, true) if err != nil { return err } if ok && unchanged(f, ef) { continue } if ok { meta.removeFile(devID, ef) } meta.addFile(devID, f) l.Debugf("insert; folder=%q device=%v %v", folder, devID, f) if err := t.putFile(dk, f, false); err != nil { return err } gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } keyBuf, _, err = t.updateGlobal(gk, keyBuf, folder, device, f, meta) if err != nil { return err } if err := t.Checkpoint(func() error { return meta.toDB(t, folder) }); err != nil { return err } } if err := meta.toDB(t, folder); err != nil { return err } return t.Commit() } // updateLocalFiles adds fileinfos to the db, and updates the global versionlist, // metadata, sequence and blockmap buckets. func (db *Lowlevel) updateLocalFiles(folder []byte, fs []protocol.FileInfo, meta *metadataTracker) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk, gk, keyBuf []byte blockBuf := make([]byte, 4) for _, f := range fs { name := []byte(f.Name) dk, err = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], name) if err != nil { return err } ef, ok, err := t.getFileByKey(dk) if err != nil { return err } if ok && unchanged(f, ef) { continue } blocksHashSame := ok && bytes.Equal(ef.BlocksHash, f.BlocksHash) if ok { if !ef.IsDirectory() && !ef.IsDeleted() && !ef.IsInvalid() { for _, block := range ef.Blocks { keyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name) if err != nil { return err } if err := t.Delete(keyBuf); err != nil { return err } } if !blocksHashSame { keyBuf, err := db.keyer.GenerateBlockListMapKey(keyBuf, folder, ef.BlocksHash, name) if err != nil { return err } if err = t.Delete(keyBuf); err != nil { return err } } } keyBuf, err = db.keyer.GenerateSequenceKey(keyBuf, folder, ef.SequenceNo()) if err != nil { return err } if err := t.Delete(keyBuf); err != nil { return err } l.Debugf("removing sequence; folder=%q sequence=%v %v", folder, ef.SequenceNo(), ef.FileName()) } f.Sequence = meta.nextLocalSeq() if ok { meta.removeFile(protocol.LocalDeviceID, ef) } meta.addFile(protocol.LocalDeviceID, f) l.Debugf("insert (local); folder=%q %v", folder, f) if err := t.putFile(dk, f, false); err != nil { return err } gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, []byte(f.Name)) if err != nil { return err } keyBuf, _, err = t.updateGlobal(gk, keyBuf, folder, protocol.LocalDeviceID[:], f, meta) if err != nil { return err } keyBuf, err = db.keyer.GenerateSequenceKey(keyBuf, folder, f.Sequence) if err != nil { return err } if err := t.Put(keyBuf, dk); err != nil { return err } l.Debugf("adding sequence; folder=%q sequence=%v %v", folder, f.Sequence, f.Name) if !f.IsDirectory() && !f.IsDeleted() && !f.IsInvalid() { for i, block := range f.Blocks { binary.BigEndian.PutUint32(blockBuf, uint32(i)) keyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name) if err != nil { return err } if err := t.Put(keyBuf, blockBuf); err != nil { return err } } if !blocksHashSame { keyBuf, err := db.keyer.GenerateBlockListMapKey(keyBuf, folder, f.BlocksHash, name) if err != nil { return err } if err = t.Put(keyBuf, nil); err != nil { return err } } } if err := t.Checkpoint(func() error { return meta.toDB(t, folder) }); err != nil { return err } } if err := meta.toDB(t, folder); err != nil { return err } return t.Commit() } func (db *Lowlevel) dropFolder(folder []byte) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() // Remove all items related to the given folder from the device->file bucket k0, err := db.keyer.GenerateDeviceFileKey(nil, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k0.WithoutNameAndDevice()); err != nil { return err } // Remove all sequences related to the folder k1, err := db.keyer.GenerateSequenceKey(k0, folder, 0) if err != nil { return err } if err := t.deleteKeyPrefix(k1.WithoutSequence()); err != nil { return err } // Remove all items related to the given folder from the global bucket k2, err := db.keyer.GenerateGlobalVersionKey(k1, folder, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k2.WithoutName()); err != nil { return err } // Remove all needs related to the folder k3, err := db.keyer.GenerateNeedFileKey(k2, folder, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k3.WithoutName()); err != nil { return err } // Remove the blockmap of the folder k4, err := db.keyer.GenerateBlockMapKey(k3, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k4.WithoutHashAndName()); err != nil { return err } k5, err := db.keyer.GenerateBlockListMapKey(k4, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k5.WithoutHashAndName()); err != nil { return err } return t.Commit() } func (db *Lowlevel) dropDeviceFolder(device, folder []byte, meta *metadataTracker) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() key, err := db.keyer.GenerateDeviceFileKey(nil, folder, device, nil) if err != nil { return err } dbi, err := t.NewPrefixIterator(key) if err != nil { return err } var gk, keyBuf []byte for dbi.Next() { name := db.keyer.NameFromDeviceFileKey(dbi.Key()) gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } keyBuf, err = t.removeFromGlobal(gk, keyBuf, folder, device, name, meta) if err != nil { return err } if err := t.Delete(dbi.Key()); err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } if err := dbi.Error(); err != nil { return err } dbi.Release() if bytes.Equal(device, protocol.LocalDeviceID[:]) { key, err := db.keyer.GenerateBlockMapKey(nil, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(key.WithoutHashAndName()); err != nil { return err } key2, err := db.keyer.GenerateBlockListMapKey(key, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(key2.WithoutHashAndName()); err != nil { return err } } return t.Commit() } func (db *Lowlevel) checkGlobals(folder []byte, meta *metadataTracker) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() key, err := db.keyer.GenerateGlobalVersionKey(nil, folder, nil) if err != nil { return err } dbi, err := t.NewPrefixIterator(key.WithoutName()) if err != nil { return err } defer dbi.Release() var dk []byte for dbi.Next() { var vl VersionList if err := vl.Unmarshal(dbi.Value()); err != nil || len(vl.Versions) == 0 { if err := t.Delete(dbi.Key()); err != nil { return err } continue } // Check the global version list for consistency. An issue in previous // versions of goleveldb could result in reordered writes so that // there are global entries pointing to no longer existing files. Here // we find those and clear them out. name := db.keyer.NameFromGlobalVersionKey(dbi.Key()) var newVL VersionList for i, version := range vl.Versions { dk, err = db.keyer.GenerateDeviceFileKey(dk, folder, version.Device, name) if err != nil { return err } _, err := t.Get(dk) if backend.IsNotFound(err) { continue } if err != nil { return err } newVL.Versions = append(newVL.Versions, version) if i == 0 { if fi, ok, err := t.getFileTrunc(dk, true); err != nil { return err } else if ok { meta.addFile(protocol.GlobalDeviceID, fi) } } } if newLen := len(newVL.Versions); newLen == 0 { if err := t.Delete(dbi.Key()); err != nil { return err } } else if newLen != len(vl.Versions) { if err := t.Put(dbi.Key(), mustMarshal(&newVL)); err != nil { return err } } } if err := dbi.Error(); err != nil { return err } l.Debugf("db check completed for %q", folder) return t.Commit() } func (db *Lowlevel) getIndexID(device, folder []byte) (protocol.IndexID, error) { key, err := db.keyer.GenerateIndexIDKey(nil, device, folder) if err != nil { return 0, err } cur, err := db.Get(key) if backend.IsNotFound(err) { return 0, nil } else if err != nil { return 0, err } var id protocol.IndexID if err := id.Unmarshal(cur); err != nil { return 0, nil } return id, nil } func (db *Lowlevel) setIndexID(device, folder []byte, id protocol.IndexID) error { bs, _ := id.Marshal() // marshalling can't fail key, err := db.keyer.GenerateIndexIDKey(nil, device, folder) if err != nil { return err } return db.Put(key, bs) } func (db *Lowlevel) dropMtimes(folder []byte) error { key, err := db.keyer.GenerateMtimesKey(nil, folder) if err != nil { return err } return db.dropPrefix(key) } func (db *Lowlevel) dropFolderMeta(folder []byte) error { key, err := db.keyer.GenerateFolderMetaKey(nil, folder) if err != nil { return err } return db.dropPrefix(key) } func (db *Lowlevel) dropPrefix(prefix []byte) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() if err := t.deleteKeyPrefix(prefix); err != nil { return err } return t.Commit() } func (db *Lowlevel) gcRunner(ctx context.Context) { // Calculate the time for the next GC run. Even if we should run GC // directly, give the system a while to get up and running and do other // stuff first. (We might have migrations and stuff which would be // better off running before GC.) next := db.timeUntil(indirectGCTimeKey, db.indirectGCInterval) if next < time.Minute { next = time.Minute } t := time.NewTimer(next) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: if err := db.gcIndirect(ctx); err != nil { l.Warnln("Database indirection GC failed:", err) } db.recordTime(indirectGCTimeKey) t.Reset(db.timeUntil(indirectGCTimeKey, db.indirectGCInterval)) } } } // recordTime records the current time under the given key, affecting the // next call to timeUntil with the same key. func (db *Lowlevel) recordTime(key string) { miscDB := NewMiscDataNamespace(db) _ = miscDB.PutInt64(key, time.Now().Unix()) // error wilfully ignored } // timeUntil returns how long we should wait until the next interval, or // zero if it should happen directly. func (db *Lowlevel) timeUntil(key string, every time.Duration) time.Duration { miscDB := NewMiscDataNamespace(db) lastTime, _, _ := miscDB.Int64(key) // error wilfully ignored nextTime := time.Unix(lastTime, 0).Add(every) sleepTime := time.Until(nextTime) if sleepTime < 0 { sleepTime = 0 } return sleepTime } func (db *Lowlevel) gcIndirect(ctx context.Context) error { // The indirection GC uses bloom filters to track used block lists and // versions. This means iterating over all items, adding their hashes to // the filter, then iterating over the indirected items and removing // those that don't match the filter. The filter will give false // positives so we will keep around one percent of things that we don't // really need (at most). // // Indirection GC needs to run when there are no modifications to the // FileInfos or indirected items. db.gcMut.Lock() defer db.gcMut.Unlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.Release() // Set up the bloom filters with the initial capacity and false positive // rate, or higher capacity if we've done this before and seen lots of // items. For simplicity's sake we track just one count, which is the // highest of the various indirected items. capacity := indirectGCBloomCapacity if db.gcKeyCount > capacity { capacity = db.gcKeyCount } blockFilter := newBloomFilter(capacity) versionFilter := newBloomFilter(capacity) // Iterate the FileInfos, unmarshal the block and version hashes and // add them to the filter. it, err := t.NewPrefixIterator([]byte{KeyTypeDevice}) if err != nil { return err } defer it.Release() for it.Next() { select { case <-ctx.Done(): return ctx.Err() default: } var hashes IndirectionHashesOnly if err := hashes.Unmarshal(it.Value()); err != nil { return err } if len(hashes.BlocksHash) > 0 { blockFilter.Add(bloomHash(hashes.BlocksHash)) } if len(hashes.VersionHash) > 0 { versionFilter.Add(bloomHash(hashes.VersionHash)) } } it.Release() if err := it.Error(); err != nil { return err } // Iterate over block lists, removing keys with hashes that don't match // the filter. it, err = t.NewPrefixIterator([]byte{KeyTypeBlockList}) if err != nil { return err } defer it.Release() matchedBlocks := 0 for it.Next() { select { case <-ctx.Done(): return ctx.Err() default: } key := blockListKey(it.Key()) if blockFilter.Has(bloomHash(key.Hash())) { matchedBlocks++ continue } if err := t.Delete(key); err != nil { return err } } it.Release() if err := it.Error(); err != nil { return err } // Iterate over version lists, removing keys with hashes that don't match // the filter. it, err = db.NewPrefixIterator([]byte{KeyTypeVersion}) if err != nil { return err } matchedVersions := 0 for it.Next() { select { case <-ctx.Done(): return ctx.Err() default: } key := versionKey(it.Key()) if versionFilter.Has(bloomHash(key.Hash())) { matchedVersions++ continue } if err := t.Delete(key); err != nil { return err } } it.Release() if err := it.Error(); err != nil { return err } // Remember the number of unique keys we kept until the next pass. db.gcKeyCount = matchedBlocks if matchedVersions > matchedBlocks { db.gcKeyCount = matchedVersions } if err := t.Commit(); err != nil { return err } return db.Compact() } func newBloomFilter(capacity int) *blobloom.Filter { return blobloom.NewOptimized(blobloom.Config{ Capacity: uint64(capacity), FPRate: indirectGCBloomFalsePositiveRate, MaxBits: 8 * indirectGCBloomMaxBytes, }) } // Hash function for the bloomfilter: first eight bytes of the SHA-256. // Big or little-endian makes no difference, as long as we're consistent. func bloomHash(key []byte) uint64 { if len(key) != sha256.Size { panic("bug: bloomHash passed something not a SHA256 hash") } return binary.BigEndian.Uint64(key) } // CheckRepair checks folder metadata and sequences for miscellaneous errors. func (db *Lowlevel) CheckRepair() { for _, folder := range db.ListFolders() { _ = db.getMetaAndCheck(folder) } } func (db *Lowlevel) getMetaAndCheck(folder string) *metadataTracker { db.gcMut.RLock() defer db.gcMut.RUnlock() meta, err := db.recalcMeta(folder) if err == nil { var fixed int fixed, err = db.repairSequenceGCLocked(folder, meta) if fixed != 0 { l.Infof("Repaired %d sequence entries in database", fixed) } } if backend.IsClosed(err) { return nil } else if err != nil { panic(err) } return meta } func (db *Lowlevel) loadMetadataTracker(folder string) *metadataTracker { meta := newMetadataTracker() if err := meta.fromDB(db, []byte(folder)); err != nil { l.Infof("No stored folder metadata for %q; recalculating", folder) return db.getMetaAndCheck(folder) } curSeq := meta.Sequence(protocol.LocalDeviceID) if metaOK := db.verifyLocalSequence(curSeq, folder); !metaOK { l.Infof("Stored folder metadata for %q is out of date after crash; recalculating", folder) return db.getMetaAndCheck(folder) } if age := time.Since(meta.Created()); age > db.recheckInterval { l.Infof("Stored folder metadata for %q is %v old; recalculating", folder, age) return db.getMetaAndCheck(folder) } return meta } func (db *Lowlevel) recalcMeta(folder string) (*metadataTracker, error) { meta := newMetadataTracker() if err := db.checkGlobals([]byte(folder), meta); err != nil { return nil, err } t, err := db.newReadWriteTransaction() if err != nil { return nil, err } defer t.close() var deviceID protocol.DeviceID err = t.withAllFolderTruncated([]byte(folder), func(device []byte, f FileInfoTruncated) bool { copy(deviceID[:], device) meta.addFile(deviceID, f) return true }) if err != nil { return nil, err } meta.emptyNeeded(protocol.LocalDeviceID) err = t.withNeed([]byte(folder), protocol.LocalDeviceID[:], true, func(f FileIntf) bool { meta.addNeeded(protocol.LocalDeviceID, f) return true }) if err != nil { return nil, err } for _, device := range meta.devices() { meta.emptyNeeded(device) err = t.withNeed([]byte(folder), device[:], true, func(f FileIntf) bool { meta.addNeeded(device, f) return true }) if err != nil { return nil, err } } meta.SetCreated() if err := meta.toDB(t, []byte(folder)); err != nil { return nil, err } if err := t.Commit(); err != nil { return nil, err } return meta, nil } // Verify the local sequence number from actual sequence entries. Returns // true if it was all good, or false if a fixup was necessary. func (db *Lowlevel) verifyLocalSequence(curSeq int64, folder string) bool { // Walk the sequence index from the current (supposedly) highest // sequence number and raise the alarm if we get anything. This recovers // from the occasion where we have written sequence entries to disk but // not yet written new metadata to disk. // // Note that we can have the same thing happen for remote devices but // there it's not a problem -- we'll simply advertise a lower sequence // number than we've actually seen and receive some duplicate updates // and then be in sync again. t, err := db.newReadOnlyTransaction() if err != nil { panic(err) } ok := true if err := t.withHaveSequence([]byte(folder), curSeq+1, func(fi FileIntf) bool { ok = false // we got something, which we should not have return false }); err != nil && !backend.IsClosed(err) { panic(err) } t.close() return ok } // repairSequenceGCLocked makes sure the sequence numbers in the sequence keys // match those in the corresponding file entries. It returns the amount of fixed // entries. func (db *Lowlevel) repairSequenceGCLocked(folderStr string, meta *metadataTracker) (int, error) { t, err := db.newReadWriteTransaction() if err != nil { return 0, err } defer t.close() fixed := 0 folder := []byte(folderStr) // First check that every file entry has a matching sequence entry // (this was previously db schema upgrade to 9). dk, err := t.keyer.GenerateDeviceFileKey(nil, folder, protocol.LocalDeviceID[:], nil) if err != nil { return 0, err } it, err := t.NewPrefixIterator(dk.WithoutName()) if err != nil { return 0, err } defer it.Release() var sk sequenceKey for it.Next() { intf, err := t.unmarshalTrunc(it.Value(), true) if err != nil { return 0, err } fi := intf.(FileInfoTruncated) if sk, err = t.keyer.GenerateSequenceKey(sk, folder, fi.Sequence); err != nil { return 0, err } switch dk, err = t.Get(sk); { case err != nil: if !backend.IsNotFound(err) { return 0, err } fallthrough case !bytes.Equal(it.Key(), dk): fixed++ fi.Sequence = meta.nextLocalSeq() if sk, err = t.keyer.GenerateSequenceKey(sk, folder, fi.Sequence); err != nil { return 0, err } if err := t.Put(sk, it.Key()); err != nil { return 0, err } if err := t.putFile(it.Key(), fi.copyToFileInfo(), true); err != nil { return 0, err } } if err := t.Checkpoint(func() error { return meta.toDB(t, folder) }); err != nil { return 0, err } } if err := it.Error(); err != nil { return 0, err } it.Release() // Secondly check there's no sequence entries pointing at incorrect things. sk, err = t.keyer.GenerateSequenceKey(sk, folder, 0) if err != nil { return 0, err } it, err = t.NewPrefixIterator(sk.WithoutSequence()) if err != nil { return 0, err } defer it.Release() for it.Next() { // Check that the sequence from the key matches the // sequence in the file. fi, ok, err := t.getFileTrunc(it.Value(), true) if err != nil { return 0, err } if ok { if seq := t.keyer.SequenceFromSequenceKey(it.Key()); seq == fi.SequenceNo() { continue } } // Either the file is missing or has a different sequence number fixed++ if err := t.Delete(it.Key()); err != nil { return 0, err } } if err := it.Error(); err != nil { return 0, err } it.Release() if err := meta.toDB(t, folder); err != nil { return 0, err } return fixed, t.Commit() } // unchanged checks if two files are the same and thus don't need to be updated. // Local flags or the invalid bit might change without the version // being bumped. func unchanged(nf, ef FileIntf) bool { return ef.FileVersion().Equal(nf.FileVersion()) && ef.IsInvalid() == nf.IsInvalid() && ef.FileLocalFlags() == nf.FileLocalFlags() }
lib/db/lowlevel.go
1
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.9981080293655396, 0.07447256147861481, 0.00016350866644643247, 0.0004672427021432668, 0.2468711882829666 ]
{ "id": 0, "code_window": [ "\t\tblocksHashSame := ok && bytes.Equal(ef.BlocksHash, f.BlocksHash)\n", "\n", "\t\tif ok {\n", "\t\t\tif !ef.IsDirectory() && !ef.IsDeleted() && !ef.IsInvalid() {\n", "\t\t\t\tfor _, block := range ef.Blocks {\n", "\t\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\t\tif err != nil {\n", "\t\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif len(ef.Blocks) != 0 && !ef.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 203 }
{ "A device with that ID is already added.": "En enhed med dette id er allerede tilføjet.", "A negative number of days doesn't make sense.": "Et negativt antal dage giver ikke mening.", "A new major version may not be compatible with previous versions.": "En ny versionsudgivelse er måske ikke kompatibel med tidligere versioner.", "API Key": "API-nøgle", "About": "Om", "Action": "Handling", "Actions": "Handlinger.", "Add": "Tilføj", "Add Device": "Tilføj enhed", "Add Folder": "Tilføj mappe", "Add Remote Device": "Tilføj fjernenhed", "Add devices from the introducer to our device list, for mutually shared folders.": "Tilføj enheder fra den introducerende enhed til vores enhedsliste for gensidigt delte mapper.", "Add new folder?": "Tilføj ny mappe", "Additionally the full rescan interval will be increased (times 60, i.e. new default of 1h). You can also configure it manually for every folder later after choosing No.": "Derudover vil intervallet for den komplette genskan blive forøget (60 gange, dvs. ny standard er 1 time). Du kan også konfigurere det manuelt for hver mappe senere efter at have valgt Nej.", "Address": "Adresse", "Addresses": "Adresser", "Advanced": "Avanceret", "Advanced Configuration": "Avanceret konfiguration", "Advanced settings": "Avancerede indstillinger", "All Data": "Alt data", "Allow Anonymous Usage Reporting?": "Tillad anonym brugerstatistik?", "Allowed Networks": "Tilladte netværk", "Alphabetic": "Alfabetisk", "An external command handles the versioning. It has to remove the file from the shared folder.": "En ekstern kommando styrer versioneringen. Den skal fjerne filen fra den delte mappe.", "An external command handles the versioning. It has to remove the file from the shared folder. If the path to the application contains spaces, it should be quoted.": "En ekstern kommando styrer versioneringen. Den skal fjerne filen fra den delte mappe. Hvis stien til programmet indeholder mellemrum, bør den sættes i anførselstegn.", "An external command handles the versioning. It has to remove the file from the synced folder.": " ", "Anonymous Usage Reporting": "Anonym brugerstatistik", "Anonymous usage report format has changed. Would you like to move to the new format?": "Formatet for anonym brugerstatistik er ændret. Vil du flytte til det nye format?", "Any devices configured on an introducer device will be added to this device as well.": "Alle enheder som er konfigureret som en introducerende enhed, vil også blive tilføjet til denne enhed.", "Are you sure you want to remove device {%name%}?": "Er du sikker på, at du vil fjerne enheden {{name}}?", "Are you sure you want to remove folder {%label%}?": "Er du sikker på, at du vil fjerne mappen {{label}}?", "Are you sure you want to restore {%count%} files?": "Er du sikker på, at du vil genskabe {{count}} filer?", "Are you sure you want to upgrade?": "Are you sure you want to upgrade?", "Auto Accept": "Autoacceptér", "Automatic Crash Reporting": "Automatic Crash Reporting", "Automatic upgrade now offers the choice between stable releases and release candidates.": "Den automatiske opdatering tilbyder nu valget mellem stabile udgivelser og udgivelseskandidater.", "Automatic upgrades": "Automatisk opdatering", "Automatic upgrades are always enabled for candidate releases.": "Automatic upgrades are always enabled for candidate releases.", "Automatically create or share folders that this device advertises at the default path.": "Opret eller del automatisk mapper på standardstien, som denne enhed tilbyder.", "Available debug logging facilities:": "Tilgængelige faciliteter for fejlretningslogning:", "Be careful!": "Vær forsigtig!", "Bugs": "Fejl", "CPU Utilization": "CPU-forbrug", "Changelog": "Udgivelsesnoter", "Clean out after": "Rens efter", "Click to see discovery failures": "Klik for at se opdagelsesfejl", "Close": "Luk", "Command": "Kommando", "Comment, when used at the start of a line": "Kommentar, når den bruges i starten af en linje", "Compression": "Anvend komprimering", "Configured": "Konfigureret", "Connected (Unused)": "Connected (Unused)", "Connection Error": "Tilslutnings fejl", "Connection Type": "Tilslutningstype", "Connections": "Forbindelser", "Continuously watching for changes is now available within Syncthing. This will detect changes on disk and issue a scan on only the modified paths. The benefits are that changes are propagated quicker and that less full scans are required.": "Løbende overvågning af ændringer er nu tilgængeligt i Syncthing. Dette vil opfange ændringer på disken og igangsætte en skanning, men kun på ændrede stier. Fordelene er, er ændringer forplanter sig hurtigere, og at færre komplette skanninger er nødvendige.", "Copied from elsewhere": "Kopieret fra et andet sted", "Copied from original": "Kopieret fra originalen", "Copyright © 2014-2016 the following Contributors:": "Copyright © 2014-2016 de følgende bidragsydere:", "Copyright © 2014-2017 the following Contributors:": "Copyright © 2014-2017 de følgende bidragsydere:", "Copyright © 2014-2019 the following Contributors:": "Copyright © 2014-2019 de følgende bidragsydere:", "Creating ignore patterns, overwriting an existing file at {%path%}.": "Opretter ignoreringsmønstre; overskriver en eksisterende fil på {{path}}.", "Currently Shared With Devices": "Currently Shared With Devices", "Danger!": "Fare!", "Debugging Facilities": "Faciliteter til fejlretning", "Default Folder Path": "Standardmappesti", "Deleted": "Slettet", "Deselect All": "Fravælg alle", "Deselect devices to stop sharing this folder with.": "Deselect devices to stop sharing this folder with.", "Device": "Enhed", "Device \"{%name%}\" ({%device%} at {%address%}) wants to connect. Add new device?": "Enheden “{{name}}” ({{device}} på {{address}}) vil gerne forbinde. Tilføj denne enhed?", "Device ID": "Enheds-ID", "Device Identification": "Enhedsidentifikation", "Device Name": "Enhedsnavn", "Device rate limits": "Enhedens hastighedsbegrænsning", "Device that last modified the item": "Enhed, som sidst ændrede filen", "Devices": "Enheder", "Disable Crash Reporting": "Disable Crash Reporting", "Disabled": "Deaktiveret", "Disabled periodic scanning and disabled watching for changes": "Deaktiverede periodisk skanning og deaktiverede overvågning af ændringer", "Disabled periodic scanning and enabled watching for changes": "Deaktiverede periodisk skanning og aktiverede overvågning af ændringer", "Disabled periodic scanning and failed setting up watching for changes, retrying every 1m:": "Deaktiverede periodisk skanning fra og lykkedes ikke med at opsætte overvågning af ændringer; prøver igen hvert minut:", "Discard": "Behold ikke", "Disconnected": "Ikke tilsluttet", "Disconnected (Unused)": "Disconnected (Unused)", "Discovered": "Opdaget", "Discovery": "Opslag", "Discovery Failures": "Fejl ved opdagelse", "Do not restore": "Genskab ikke", "Do not restore all": "Genskab ikke alle", "Do you want to enable watching for changes for all your folders?": "Vil du aktivere løbende overvågning af ændringer for alle dine mapper?", "Documentation": "Dokumentation", "Download Rate": "Downloadhastighed", "Downloaded": "Downloadet", "Downloading": "Downloader", "Edit": "Redigér", "Edit Device": "Redigér enhed", "Edit Folder": "Redigér mappe", "Editing": "Redigerer", "Editing {%path%}.": "Redigerer {{path}}.", "Enable Crash Reporting": "Enable Crash Reporting", "Enable NAT traversal": "Aktivér NAT-traversering", "Enable Relaying": "Aktivér videresending", "Enabled": "Aktiveret", "Enter a non-negative number (e.g., \"2.35\") and select a unit. Percentages are as part of the total disk size.": "Indtast et ikke-negativt tal (fx “2,35”) og vælg en enhed. Procentsatser er ud fra total diskstørrelse.", "Enter a non-privileged port number (1024 - 65535).": "Indtast et ikke-priviligeret portnummer (1024–65535).", "Enter comma separated (\"tcp://ip:port\", \"tcp://host:port\") addresses or \"dynamic\" to perform automatic discovery of the address.": "Angiv kommaseparerede adresser (“tcp://ip:port”, “tcp://host:port”) eller “dynamic” for at benytte automatisk opdagelse af adressen.", "Enter comma separated (\"tcp://ip:port\", \"tcp://host:port\") addresses or \"dynamic\" to perform automatic discovery of the address.": "Angiv en kommaadskilt adresseliste (\"tcp://ip:port\", \"tcp://host:port\")  eller \"dynamic\" for automatisk at opdage adressen.", "Enter ignore patterns, one per line.": "Indtast ignoreringsmønstre, ét per linje.", "Enter up to three octal digits.": "Enter up to three octal digits.", "Error": "Fejl", "External File Versioning": "Ekstern filversionering", "Failed Items": "Mislykkede filer", "Failed to load ignore patterns": "Indlæsning af ignoreringsmønstre mislykkedes", "Failed to setup, retrying": "Opsætning mislykkedes; prøver igen", "Failure to connect to IPv6 servers is expected if there is no IPv6 connectivity.": "Fejl i forbindelse med opkobling til IPv6-servere skal forventes, hvis der ikke er IPv6-forbindelse.", "File Pull Order": "Hentningsrækkefølge for filer", "File Versioning": "Filversionering", "File permission bits are ignored when looking for changes. Use on FAT file systems.": "Filtilladelsesbits ignoreres, når der søges efter ændringer. Brug på FAT-filsystemer.", "Files are moved to .stversions directory when replaced or deleted by Syncthing.": "Filer bliver flyttet til .stversions-mappen, når de bliver erstattet eller slettet af Syncthing.", "Files are moved to .stversions folder when replaced or deleted by Syncthing.": "Filer flyttes til .stversions-mappen, når de erstattes eller slettes af Syncthing.", "Files are moved to date stamped versions in a .stversions directory when replaced or deleted by Syncthing.": "Filer flyttes til datostemplede versioner i en .stversions-mappe, når de erstattes eller slettes af Syncthing.", "Files are moved to date stamped versions in a .stversions folder when replaced or deleted by Syncthing.": "Filer flyttes til datostemplede versioner i en .stversions-mappe, når de erstattes eller slettes af Syncthing.", "Files are protected from changes made on other devices, but changes made on this device will be sent to the rest of the cluster.": "Filer beskyttes mod ændringer, foretaget på andre enheder, men ændringerne på denne enhed vil blive sendt til alle andre tilknyttede enheder.", "Files are synchronized from the cluster, but any changes made locally will not be sent to other devices.": "Filer synkroniseres fra tilknyttede enheder, men ændringer på denne enhed sendes ikke til andre enheder.", "Filesystem Notifications": "Filsystemsnotifikationer", "Filesystem Watcher Errors": "Fejl ved filsystemovervågning", "Filter by date": "Filtrér efter dato", "Filter by name": "Filtrér efter navn", "Folder": "Mappe", "Folder ID": "Mappe-ID", "Folder Label": "Mappeetiket", "Folder Path": "Mappesti", "Folder Type": "Mappetype", "Folders": "Mapper", "For the following folders an error occurred while starting to watch for changes. It will be retried every minute, so the errors might go away soon. If they persist, try to fix the underlying issue and ask for help if you can't.": "For de følgende mapper opstod en fejl ved start på overvågning af ændringer. Der prøves igen hvert minut, så fejlene går eventuelt væk snart. Hvis de forbliver, kan du prøve at rette den tilgrundliggende fejl eller spørge efter hjælp, hvis du ikke kan.", "Full Rescan Interval (s)": "Interval for komplet genskan (sek.)", "GUI": "GUI", "GUI Authentication Password": "GUI-adgangskode", "GUI Authentication User": "GUI-brugernavn", "GUI Listen Address": "GUI-lytteadresse", "GUI Listen Addresses": "GUI-lytteadresser", "GUI Theme": "GUI-tema", "General": "Generalt", "Generate": "Opret", "Global Changes": "Globale ændringer", "Global Discovery": "Globalt opslag", "Global Discovery Servers": "Globale opslagsservere", "Global State": "Global tilstand", "Help": "Hjælp", "Home page": "Hjem", "However, your current settings indicate you might not want it enabled. We have disabled automatic crash reporting for you.": "However, your current settings indicate you might not want it enabled. We have disabled automatic crash reporting for you.", "Ignore": "Ignorér", "Ignore Patterns": "Ignoreringsmønstre", "Ignore Permissions": "Ignorér rettigheder", "Ignored Devices": "Ignorerede enheder", "Ignored Folders": "Ignorerede mapper", "Ignored at": "Ignoreret på", "Incoming Rate Limit (KiB/s)": "Indgående hastighedsbegrænsning (KiB/s)", "Incorrect configuration may damage your folder contents and render Syncthing inoperable.": "Ukorrekt opsætning kan skade dine data og gøre Syncthing ude af stand til at fungere.", "Introduced By": "Introduceret af", "Introducer": "Introducerende enhed", "Inversion of the given condition (i.e. do not exclude)": "Det omvendte (dvs. undlad ikke)", "Keep Versions": "Behold versioner", "LDAP": "LDAP", "Largest First": "Største først", "Last File Received": "Senest modtagne fil", "Last Scan": "Seneste skanning", "Last seen": "Sidst set", "Later": "Senere", "Latest Change": "Seneste ændring", "Learn more": "Lær mere", "Limit": "Grænse", "Listeners": "Lyttere", "Loading data...": "Indlæser data ...", "Loading...": "Indlæser ...", "Local Additions": "Local Additions", "Local Discovery": "Lokal opslag", "Local State": "Lokal tilstand", "Local State (Total)": "Lokal tilstand (total)", "Locally Changed Items": "Lokalt ændrede filer", "Log": "Logbog", "Log tailing paused. Click here to continue.": "Logfølgning på pause. Klik her for at fortsætte.", "Log tailing paused. Scroll to bottom continue.": "Logfølgning på pause. Rul til bunden for at fortsætte.", "Log tailing paused. Scroll to the bottom to continue.": "Log tailing paused. Scroll to the bottom to continue.", "Logs": "Logbog", "Major Upgrade": "Opgradering til ny hovedversion", "Mass actions": "Massehandlinger", "Master": "Styrende", "Maximum Age": "Maksimal alder", "Metadata Only": "Kun metadata", "Minimum Free Disk Space": "Mindst ledig diskplads", "Mod. Device": "Enhed for ændring", "Mod. Time": "Tid for ændring", "Move to top of queue": "Flyt til toppen af køen", "Multi level wildcard (matches multiple directory levels)": "Flerniveau-wildcard (matcher flere mappeniveauer)", "Never": "Aldrig", "New Device": "Ny enhed", "New Folder": "Ny mappe", "Newest First": "Nyeste først", "No": "Nej", "No File Versioning": "Ingen filversionering", "No files will be deleted as a result of this operation.": "Ingen filer vil blive slettet som resultat af denne handling.", "No upgrades": "Ingen opgraderinger", "Normal": "Normal", "Notice": "Bemærk", "OK": "OK", "Off": "Deaktiveret", "Oldest First": "Ældste først", "Optional descriptive label for the folder. Can be different on each device.": "En valgfri beskrivende etiket for mappen. Kan være forskellig på hver enkelt enhed.", "Options": "Indstillinger", "Out of Sync": "Ikke synkroniseret", "Out of Sync Items": "Ikke synkroniserede filer", "Outgoing Rate Limit (KiB/s)": "Udgående hastighedsbegrænsning (KiB/s)", "Override Changes": "Overskriv ændringer", "Path": "Sti", "Path to the folder on the local computer. Will be created if it does not exist. The tilde character (~) can be used as a shortcut for": "Sti til den lokale mappe. Vil blive oprettet hvis den ikke findes. Tildetegnet (~) kan bruges som en forkortelse for", "Path where new auto accepted folders will be created, as well as the default suggested path when adding new folders via the UI. Tilde character (~) expands to {%tilde%}.": "Sti hvor nye automatisk accepterede mapper oprettes, så vel som standardstien der foreslås ved tilføjelse af nye mapper gennem brugerfladen. Tildetegnet (~) udvides til {{tilde}}.", "Path where versions should be stored (leave empty for the default .stversions directory in the shared folder).": "Sti hvor versioner skal gemmes (lad være tomt for at bruge .stversions-mappen i den delte mappe).", "Path where versions should be stored (leave empty for the default .stversions folder in the folder).": "Sti hvor versioner skal gemmes (lad være tomt for at bruge .stversions-mappen i den delte mappe).", "Pause": "Pause", "Pause All": "Sæt alt på pause", "Paused": "På pause", "Paused (Unused)": "Paused (Unused)", "Pending changes": "Ventende ændringer", "Periodic scanning at given interval and disabled watching for changes": "Periodisk skanning med et givent interval og deaktiveret overvågning af ændringer", "Periodic scanning at given interval and enabled watching for changes": "Periodisk skanning med et givent interval og aktiveret overvågning af ændringer", "Periodic scanning at given interval and failed setting up watching for changes, retrying every 1m:": "Periodisk skanning med et givent interval og lykkedes ikke med at opsætte overvågning af ændringer; prøver igen hvert minut:", "Permissions": "Tilladelser", "Please consult the release notes before performing a major upgrade.": "Tjek venligst udgivelsesnoterne før opgradering til en ny hovedversion.", "Please set a GUI Authentication User and Password in the Settings dialog.": "Opret venligst en GUI-bruger og -adgangskode i opsætningen.", "Please wait": "Vent venligst", "Prefix indicating that the file can be deleted if preventing directory removal": "Forstavelse, der indikerer, at filen kan slettes, hvis fjernelse at mappe undgåes", "Prefix indicating that the pattern should be matched without case sensitivity": "Forstavelse, der indikerer det mønster, der skal sammenlignes uden versalfølsomhed", "Preparing to Sync": "Preparing to Sync", "Preview": "Forhåndsvisning", "Preview Usage Report": "Forhåndsvisning af forbrugsrapport", "Quick guide to supported patterns": "Kvikguide til understøttede mønstre", "RAM Utilization": "RAM-forbrug", "Random": "Tilfældig", "Receive Only": "Modtag kun", "Recent Changes": "Nylige ændringer", "Reduced by ignore patterns": "Reduceret af ignoreringsmønstre", "Release Notes": "Udgivelsesnoter", "Release candidates contain the latest features and fixes. They are similar to the traditional bi-weekly Syncthing releases.": "Udgivelseskandidater indeholder alle de nyeste funktioner og rettelser. De er det samme som de traditionelle tougers-udgivelser af Syncthing.", "Remote Devices": "Fjernenheder ", "Remove": "Fjern", "Remove Device": "Fjern enhed", "Remove Folder": "Fjern mappe", "Required identifier for the folder. Must be the same on all cluster devices.": "Nødvendig identifikator for mappen. Dette skal være det samme på alle enheder.", "Rescan": "Skan igen", "Rescan All": "Skan alt igen", "Rescan Interval": "Genskanningsinterval", "Rescans": "Genskanninger", "Restart": "Genstart", "Restart Needed": "Genstart påkrævet", "Restarting": "Genstarter", "Restore": "Genskab", "Restore Versions": "Genskab versioner", "Resume": "Genoptag", "Resume All": "Genoptag alt", "Reused": "Genbrugt", "Revert Local Changes": "Opgiv lokale ændringer", "Running": "Kører", "Save": "Gem", "Scan Time Remaining": "Tid tilbage af skanningen", "Scanning": "Skanner", "See external versioner help for supported templated command line parameters.": "Se hjælp til ekstern versionering for understøttede kommandolinjeparametre.", "See external versioning help for supported templated command line parameters.": "Se hjælp til ekstern versionering for understøttede kommandolinjeparametre.", "Select All": "Vælg alle", "Select a version": "Vælg en version", "Select additional devices to share this folder with.": "Select additional devices to share this folder with.", "Select latest version": "Vælg seneste version", "Select oldest version": "Vælg ældste version", "Select the devices to share this folder with.": "Vælg hvilke enheder du vil dele denne mappe med.", "Select the folders to share with this device.": "Vælg hvilke mapper du vil dele med denne enhed.", "Send & Receive": "Send og modtag", "Send Only": "Send kun", "Settings": "Indstillinger", "Share": "Del", "Share Folder": "Del mappe", "Share Folders With Device": "Del mappe med enhed", "Share With Devices": "Del med enheder", "Share this folder?": "Del denne mappe?", "Shared With": "Delt med", "Sharing": "Deler", "Show ID": "Vis ID", "Show QR": "Vis QR", "Show diff with previous version": "Vis forskelle fra tidligere version", "Shown instead of Device ID in the cluster status. Will be advertised to other devices as an optional default name.": "Vises i stedet for enheds-ID i klyngestatus. Vil blive sendt til andre enheder som valgfrit standardnavn.", "Shown instead of Device ID in the cluster status. Will be updated to the name the device advertises if left empty.": "Vises i stedet for enheds-ID i klyngestatus. Vil blive opdateret til det navn, som enheden sender, hvis det ikke er udfyldt.", "Shutdown": "Luk ned", "Shutdown Complete": "Nedlukning fuldført", "Simple File Versioning": "Simpel filversionering", "Single level wildcard (matches within a directory only)": "Enkeltniveau-wildcard (matcher kun inden for en mappe)", "Size": "Størrelse", "Smallest First": "Mindste først", "Some items could not be restored:": "Enkelte filer kunne ikke genskabes:", "Source Code": "Kildekode", "Stable releases and release candidates": "Stabile udgivelser og udgivelseskandidater ", "Stable releases are delayed by about two weeks. During this time they go through testing as release candidates.": "Stabile udgivelser er forsinket med omkring to uger. I denne periode gennemgår de afprøvninger som udgivelseskandidater.", "Stable releases only": "Kun stabile udgivelser", "Staggered File Versioning": "Forskudt filversionering", "Start Browser": "Start browser", "Statistics": "Statistikker", "Stopped": "Stoppet", "Support": "Støt", "Support Bundle": "Støttepakke", "Sync Protocol Listen Addresses": "Lytteadresser for synkroniseringsprotokol", "Syncing": "Synkroniserer", "Syncthing has been shut down.": "Syncthing er lukket ned.", "Syncthing includes the following software or portions thereof:": "Syncthing indeholder følgende software eller dele heraf:", "Syncthing is Free and Open Source Software licensed as MPL v2.0.": "Syncthing is Free and Open Source Software licensed as MPL v2.0.", "Syncthing is restarting.": "Syncthing genstarter.", "Syncthing is upgrading.": "Syncthing opgraderer.", "Syncthing now supports automatically reporting crashes to the developers. This feature is enabled by default.": "Syncthing now supports automatically reporting crashes to the developers. This feature is enabled by default.", "Syncthing seems to be down, or there is a problem with your Internet connection. Retrying…": "Syncthing ser ud til at være stoppet eller oplever problemer med din internetforbindelse. Prøver igen…", "Syncthing seems to be experiencing a problem processing your request. Please refresh the page or restart Syncthing if the problem persists.": "Det ser ud til, at Syncthing har problemer med at udføre opgaven. Prøv at genindlæse siden eller genstarte Synching, hvis problemet vedbliver.", "Take me back": "Tag mig tilbage", "The GUI address is overridden by startup options. Changes here will not take effect while the override is in place.": "The GUI address is overridden by startup options. Changes here will not take effect while the override is in place.", "The Syncthing admin interface is configured to allow remote access without a password.": "Syncthing-administationsfladen er sat op til at kunne fjernstyres uden adgangskode.", "The aggregated statistics are publicly available at the URL below.": "Den indsamlede statistik er offentligt tilgængelig på den nedenstående URL.", "The configuration has been saved but not activated. Syncthing must restart to activate the new configuration.": "Konfigurationen er gemt, men ikke aktiveret. Syncthing skal genstarte for at aktivere den nye konfiguration.", "The device ID cannot be blank.": "Enhedens ID må ikke være tom.", "The device ID to enter here can be found in the \"Actions > Show ID\" dialog on the other device. Spaces and dashes are optional (ignored).": "Det enheds-ID, som skal indtastes her, kan findes under menuen “Handlinger > Vis ID” på den anden enhed. Mellemrum og bindestreger er valgfri (ignoreres).", "The encrypted usage report is sent daily. It is used to track common platforms, folder sizes and app versions. If the reported data set is changed you will be prompted with this dialog again.": "Den krypterede forbrugsrapport sendes dagligt. Den benyttes til at spore anvendte platforme, mappestørrelser og programversioner. Hvis den opsamlede data ændres på et senere tidspunkt, vil du blive spurgt om tilladelse igen.", "The entered device ID does not look valid. It should be a 52 or 56 character string consisting of letters and numbers, with spaces and dashes being optional.": "Det indtastede enheds-ID ser ikke gyldigt ud. Det skal være en streng på 52 eller 56 tegn, der består af tal og bogstaver, eventuelt med mellemrum og bindestreger.", "The first command line parameter is the folder path and the second parameter is the relative path in the folder.": "Den første kommandolinjeparameter er mappestien og den anden parameter er den relative sti inden i mappen.", "The folder ID cannot be blank.": "Mappe-ID må ikke være tom.", "The folder ID must be unique.": "Mappe-ID skal være unik.", "The folder path cannot be blank.": "Mappestien må ikke være tom.", "The following intervals are used: for the first hour a version is kept every 30 seconds, for the first day a version is kept every hour, for the first 30 days a version is kept every day, until the maximum age a version is kept every week.": "De følgende intervaller er brugt: Inden for den første time bliver en version gemt hvert 30. sekund, inden for den første dag bliver en version gemt hver time, inden for de første 30 dage bliver en version gemt hver dag, og indtil den maksimale alder bliver en version gemt hver uge.", "The following items could not be synchronized.": "Følgende filer kunne ikke synkroniseres.", "The following items were changed locally.": "De følgende filer er ændret lokalt.", "The maximum age must be a number and cannot be blank.": "Maksimal alder skal være et tal og feltet må ikke være tomt.", "The maximum time to keep a version (in days, set to 0 to keep versions forever).": "Den maksimale tid, en version skal gemmes (i dage; sæt lig med 0 for at beholde gamle versioner for altid).", "The minimum free disk space percentage must be a non-negative number between 0 and 100 (inclusive).": "Procentsatsen for mindst ledig diskplads skal være et ikke-negativt tal mellem 0 og 100 (inklusive).", "The number of days must be a number and cannot be blank.": "Antallet af dage skal være et tal og feltet må ikke være tomt.", "The number of days to keep files in the trash can. Zero means forever.": "Antal dage, filer gemmes i papirkurven. Nul betyder for evigt.", "The number of old versions to keep, per file.": "Antallet af gamle versioner som gemmes per fil.", "The number of versions must be a number and cannot be blank.": "Antallet af versioner skal være et tal og feltet må ikke være tomt.", "The path cannot be blank.": "Stien må ikke være tom.", "The rate limit must be a non-negative number (0: no limit)": "Hastighedsbegrænsningen skal være et ikke-negativt tal (0: ingen begrænsning)", "The rescan interval must be a non-negative number of seconds.": "Genskanningsintervallet skal være et ikke-negativt antal sekunder.", "There are no devices to share this folder with.": "There are no devices to share this folder with.", "They are retried automatically and will be synced when the error is resolved.": "De prøves igen automatisk og vil blive synkroniseret, når fejlen er løst.", "This Device": "Denne enhed", "This can easily give hackers access to read and change any files on your computer.": "Dette gør det nemt for hackere at få adgang til at læse og ændre filer på din computer.", "This is a major version upgrade.": "Dette er en ny hovedversion.", "This setting controls the free space required on the home (i.e., index database) disk.": "Denne indstilling styrer den krævede ledige plads på hjemmedrevet (dvs. drevet med indeksdatabasen).", "Time": "Tid", "Time the item was last modified": "Tidspunkt for seneste ændring af filen", "Trash Can File Versioning": "Versionering med papirkurv", "Type": "Type", "UNIX Permissions": "UNIX Permissions", "Unavailable": "Ikke tilgængelig", "Unavailable/Disabled by administrator or maintainer": "Ikke tilgængelig / deaktiveret af administrator eller vedligeholder", "Undecided (will prompt)": "Ubestemt (du bliver spurgt)", "Unignore": "Fjern ignorering", "Unknown": "Ukendt", "Unshared": "Ikke delt", "Unshared Devices": "Unshared Devices", "Unused": "Ubrugt", "Up to Date": "Fuldt opdateret", "Updated": "Opdateret", "Upgrade": "Opgradér", "Upgrade To {%version%}": "Opgradér til {{version}}", "Upgrading": "Opgraderer", "Upload Rate": "Uploadhastighed", "Uptime": "Oppetid", "Usage reporting is always enabled for candidate releases.": "Forbrugsraportering er altid aktiveret for udgivelseskandidater.", "Use HTTPS for GUI": "Anvend HTTPS til GUI-adgang", "Use notifications from the filesystem to detect changed items.": "Benyt notifikationer fra filsystemet til at finde filændringer.", "Variable Size Blocks": "Skiftende blokstørrelse", "Variable size blocks (also \"large blocks\") are more efficient for large files.": "Skiftende blokstørrelse (også \"store blokke\") er mere effektivt for større filer.", "Version": "Version", "Versions": "Versioner", "Versions Path": "Versionssti", "Versions are automatically deleted if they are older than the maximum age or exceed the number of files allowed in an interval.": "Versioner slettes automatisk, hvis de er ældre end den givne maksimum alder eller overstiger det tilladte antal filer i et interval.", "Waiting to Scan": "Waiting to Scan", "Waiting to Sync": "Waiting to Sync", "Waiting to scan": "Venter på at skanne", "Warning, this path is a parent directory of an existing folder \"{%otherFolder%}\".": "Advarsel: Denne sti er en forældermappe til den eksisterende mappe “{{otherFolder}}”.", "Warning, this path is a parent directory of an existing folder \"{%otherFolderLabel%}\" ({%otherFolder%}).": "Advarsel: Denne sti er en forældermappe til den eksisterende mappe “{{otherFolderLabel}}” ({{otherFolder}}).", "Warning, this path is a subdirectory of an existing folder \"{%otherFolder%}\".": "Advarsel: Denne sti er en undermappe til den eksisterende mappe “{{otherFolder}}”.", "Warning, this path is a subdirectory of an existing folder \"{%otherFolderLabel%}\" ({%otherFolder%}).": "Advarsel: Denne sti er en undermappe til den eksisterende mappe “{{otherFolderLabel}}” ({{otherFolder}}).", "Warning: If you are using an external watcher like {%syncthingInotify%}, you should make sure it is deactivated.": "Advarsel: Hvis du bruger en ekstern overvågning såsom {{syncthingInotify}}, bør du være sikker på, at den er deaktiveret.", "Watch for Changes": "Overvåg ændringer", "Watching for Changes": "Overvågning af ændringer", "Watching for changes discovers most changes without periodic scanning.": "Overvågning af ændringer finder ændringer uden at skanne fra tid til anden.", "When adding a new device, keep in mind that this device must be added on the other side too.": "Når der tilføjes en ny enhed, vær da opmærksom på, at denne enhed også skal tilføjes i den anden ende.", "When adding a new folder, keep in mind that the Folder ID is used to tie folders together between devices. They are case sensitive and must match exactly between all devices.": "Når der tilføjes en ny enhed, vær da opmærksom på at samme mappe-ID bruges til at forbinde mapper på de forskellige enheder. Der er forskel på store og små bogstaver, og ID skal være fuldstændig identisk på alle enheder.", "Yes": "Ja", "You can also select one of these nearby devices:": "Du kan også vælge en af disse enheder i nærheden:", "You can change your choice at any time in the Settings dialog.": "Du kan altid ændre dit valg under indstillinger.", "You can read more about the two release channels at the link below.": "Du kan læse mere om de to udgivelseskanaler på linket herunder.", "You have no ignored devices.": "Du har ingen ignorerede enheder.", "You have no ignored folders.": "Du har ingen ignorerede mapper.", "You have unsaved changes. Do you really want to discard them?": "Du har ændringer, som ikke er gemt. Er du sikker på, at du ikke vil beholde dem?", "You must keep at least one version.": "Du skal beholde mindst én version.", "days": "dage", "directories": "mapper", "files": "filer", "full documentation": "fuld dokumentation", "items": "filer", "{%device%} wants to share folder \"{%folder%}\".": "{{device}} ønsker at dele mappen “{{folder}}”.", "{%device%} wants to share folder \"{%folderlabel%}\" ({%folder%}).": "{{device}} ønsker at dele mappen “{{folderlabel}}” ({{folder}})." }
gui/default/assets/lang/lang-da.json
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.00017593840311747044, 0.00017055001808330417, 0.00016018141468521208, 0.00017125412705354393, 0.0000035665307223098353 ]
{ "id": 0, "code_window": [ "\t\tblocksHashSame := ok && bytes.Equal(ef.BlocksHash, f.BlocksHash)\n", "\n", "\t\tif ok {\n", "\t\t\tif !ef.IsDirectory() && !ef.IsDeleted() && !ef.IsInvalid() {\n", "\t\t\t\tfor _, block := range ef.Blocks {\n", "\t\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\t\tif err != nil {\n", "\t\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif len(ef.Blocks) != 0 && !ef.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 203 }
{"k":"AAAAAAAAAAABYQ==","v":"CgFhMAFKBwoFCAEQ6AdQAQ=="} {"k":"AAAAAAAAAAABYg==","v":"CgFiSgcKBQgBEOgHUAKCASIaIAABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fggEkEAEaIAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gkgEgC8XkepY1E4woWwAAyi81YItXr5CMuwY6mfvf2iLupTo="} {"k":"AAAAAAAAAAABYw==","v":"CgFjMAFKBwoFCAEQ6AdQAw=="} {"k":"AAAAAAAAAAACYQ==","v":"CgFhMAFKBwoFCAEQ6AdQAQ=="} {"k":"AAAAAAAAAAACYg==","v":"CgFiMAFKFQoFCAEQ6AcKDAi5vtz687f5kQIQAVACggEiGiAAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eH4IBJBABGiABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fIJIBIAvF5HqWNROMKFsAAMovNWCLV6+QjLsGOpn739oi7qU6"} {"k":"AAAAAAAAAAACYw==","v":"CgFjShUKBQgBEOgHCgwIub7c+vO3+ZECEAFQA4IBIhogAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh+SASBjDc0pZsQzZpESVEi7sltP9BKknHMtssirwbhYG9cQ3Q=="} {"k":"AQAAAABh","v":"CisKBwoFCAEQ6AcSIAIj5b8/Vx850vCTKUE+HcWcQZUIgmhv//rEL3j3A/AtCisKBwoFCAEQ6AcSIP//////////////////////////////////////////"} {"k":"AQAAAABi","v":"CjkKFQoFCAEQ6AcKDAi5vtz687f5kQIQARIgAiPlvz9XHznS8JMpQT4dxZxBlQiCaG//+sQvePcD8C0KKwoHCgUIARDoBxIg//////////////////////////////////////////8="} {"k":"AQAAAABj","v":"CjkKFQoFCAEQ6AcKDAi5vtz687f5kQIQARIgAiPlvz9XHznS8JMpQT4dxZxBlQiCaG//+sQvePcD8C0KKwoHCgUIARDoBxIg//////////////////////////////////////////8="} {"k":"AgAAAAAAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eH2I=","v":"AAAAAA=="} {"k":"AgAAAAABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fIGI=","v":"AAAAAQ=="} {"k":"BgAAAAAAAAAA","v":"dGVzdA=="} {"k":"BwAAAAAAAAAA","v":""} {"k":"BwAAAAEAAAAA","v":"//////////////////////////////////////////8="} {"k":"BwAAAAIAAAAA","v":"AiPlvz9XHznS8JMpQT4dxZxBlQiCaG//+sQvePcD8C0="} {"k":"CQAAAAA=","v":"CikIASACMAOKASD//////////////////////////////////////////wonCAEgAooBIPj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4CikIASACMAOKASACI+W/P1cfOdLwkylBPh3FnEGVCIJob//6xC949wPwLRDE7Jrik+mdhhY="} {"k":"CmRiTWluU3luY3RoaW5nVmVyc2lvbg==","v":"djEuNC4w"} {"k":"CmRiVmVyc2lvbg==","v":"AAAAAAAAAAk="} {"k":"Cmxhc3RJbmRpcmVjdEdDVGltZQ==","v":"AAAAAF6yy/Q="} {"k":"CwAAAAAAAAAAAAAAAQ==","v":"AAAAAAAAAAABYQ=="} {"k":"CwAAAAAAAAAAAAAAAg==","v":"AAAAAAAAAAABYg=="} {"k":"CwAAAAAAAAAAAAAAAw==","v":"AAAAAAAAAAABYw=="} {"k":"DAAAAABi","v":""} {"k":"DAAAAABj","v":""}
lib/db/testdata/v1.4.0-updateTo10.json
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.002879961859434843, 0.0010872523998841643, 0.0001725564361549914, 0.00020923909323755652, 0.0012677253689616919 ]
{ "id": 0, "code_window": [ "\t\tblocksHashSame := ok && bytes.Equal(ef.BlocksHash, f.BlocksHash)\n", "\n", "\t\tif ok {\n", "\t\t\tif !ef.IsDirectory() && !ef.IsDeleted() && !ef.IsInvalid() {\n", "\t\t\t\tfor _, block := range ef.Blocks {\n", "\t\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\t\tif err != nil {\n", "\t\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif len(ef.Blocks) != 0 && !ef.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 203 }
// Copyright (C) 2015 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package nat import ( "github.com/syncthing/syncthing/lib/logger" ) var ( l = logger.DefaultLogger.NewFacility("nat", "NAT discovery and port mapping") )
lib/nat/debug.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0001792455732356757, 0.00017202261369675398, 0.00016479965415783226, 0.00017202261369675398, 0.000007222959538921714 ]
{ "id": 1, "code_window": [ "\t\tif err := t.Put(keyBuf, dk); err != nil {\n", "\t\t\treturn err\n", "\t\t}\n", "\t\tl.Debugf(\"adding sequence; folder=%q sequence=%v %v\", folder, f.Sequence, f.Name)\n", "\n", "\t\tif !f.IsDirectory() && !f.IsDeleted() && !f.IsInvalid() {\n", "\t\t\tfor i, block := range f.Blocks {\n", "\t\t\t\tbinary.BigEndian.PutUint32(blockBuf, uint32(i))\n", "\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\tif err != nil {\n", "\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(f.Blocks) != 0 && !f.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 264 }
// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package db import ( "bytes" "context" "encoding/binary" "time" "github.com/greatroar/blobloom" "github.com/syncthing/syncthing/lib/db/backend" "github.com/syncthing/syncthing/lib/protocol" "github.com/syncthing/syncthing/lib/sha256" "github.com/syncthing/syncthing/lib/sync" "github.com/syncthing/syncthing/lib/util" "github.com/thejerf/suture" ) const ( // We set the bloom filter capacity to handle 100k individual items with // a false positive probability of 1% for the first pass. Once we know // how many items we have we will use that number instead, if it's more // than 100k. For fewer than 100k items we will just get better false // positive rate instead. indirectGCBloomCapacity = 100000 indirectGCBloomFalsePositiveRate = 0.01 // 1% indirectGCBloomMaxBytes = 32 << 20 // Use at most 32MiB memory, which covers our desired FP rate at 27 M items indirectGCDefaultInterval = 13 * time.Hour indirectGCTimeKey = "lastIndirectGCTime" // Use indirection for the block list when it exceeds this many entries blocksIndirectionCutoff = 3 // Use indirection for the version vector when it exceeds this many entries versionIndirectionCutoff = 10 recheckDefaultInterval = 30 * 24 * time.Hour ) // Lowlevel is the lowest level database interface. It has a very simple // purpose: hold the actual backend database, and the in-memory state // that belong to that database. In the same way that a single on disk // database can only be opened once, there should be only one Lowlevel for // any given backend. type Lowlevel struct { *suture.Supervisor backend.Backend folderIdx *smallIndex deviceIdx *smallIndex keyer keyer gcMut sync.RWMutex gcKeyCount int indirectGCInterval time.Duration recheckInterval time.Duration } func NewLowlevel(backend backend.Backend, opts ...Option) *Lowlevel { db := &Lowlevel{ Supervisor: suture.New("db.Lowlevel", suture.Spec{ // Only log restarts in debug mode. Log: func(line string) { l.Debugln(line) }, PassThroughPanics: true, }), Backend: backend, folderIdx: newSmallIndex(backend, []byte{KeyTypeFolderIdx}), deviceIdx: newSmallIndex(backend, []byte{KeyTypeDeviceIdx}), gcMut: sync.NewRWMutex(), indirectGCInterval: indirectGCDefaultInterval, recheckInterval: recheckDefaultInterval, } for _, opt := range opts { opt(db) } db.keyer = newDefaultKeyer(db.folderIdx, db.deviceIdx) db.Add(util.AsService(db.gcRunner, "db.Lowlevel/gcRunner")) return db } type Option func(*Lowlevel) // WithRecheckInterval sets the time interval in between metadata recalculations // and consistency checks. func WithRecheckInterval(dur time.Duration) Option { return func(db *Lowlevel) { if dur > 0 { db.recheckInterval = dur } } } // WithIndirectGCInterval sets the time interval in between GC runs. func WithIndirectGCInterval(dur time.Duration) Option { return func(db *Lowlevel) { if dur > 0 { db.indirectGCInterval = dur } } } // ListFolders returns the list of folders currently in the database func (db *Lowlevel) ListFolders() []string { return db.folderIdx.Values() } // updateRemoteFiles adds a list of fileinfos to the database and updates the // global versionlist and metadata. func (db *Lowlevel) updateRemoteFiles(folder, device []byte, fs []protocol.FileInfo, meta *metadataTracker) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk, gk, keyBuf []byte devID := protocol.DeviceIDFromBytes(device) for _, f := range fs { name := []byte(f.Name) dk, err = db.keyer.GenerateDeviceFileKey(dk, folder, device, name) if err != nil { return err } ef, ok, err := t.getFileTrunc(dk, true) if err != nil { return err } if ok && unchanged(f, ef) { continue } if ok { meta.removeFile(devID, ef) } meta.addFile(devID, f) l.Debugf("insert; folder=%q device=%v %v", folder, devID, f) if err := t.putFile(dk, f, false); err != nil { return err } gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } keyBuf, _, err = t.updateGlobal(gk, keyBuf, folder, device, f, meta) if err != nil { return err } if err := t.Checkpoint(func() error { return meta.toDB(t, folder) }); err != nil { return err } } if err := meta.toDB(t, folder); err != nil { return err } return t.Commit() } // updateLocalFiles adds fileinfos to the db, and updates the global versionlist, // metadata, sequence and blockmap buckets. func (db *Lowlevel) updateLocalFiles(folder []byte, fs []protocol.FileInfo, meta *metadataTracker) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk, gk, keyBuf []byte blockBuf := make([]byte, 4) for _, f := range fs { name := []byte(f.Name) dk, err = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], name) if err != nil { return err } ef, ok, err := t.getFileByKey(dk) if err != nil { return err } if ok && unchanged(f, ef) { continue } blocksHashSame := ok && bytes.Equal(ef.BlocksHash, f.BlocksHash) if ok { if !ef.IsDirectory() && !ef.IsDeleted() && !ef.IsInvalid() { for _, block := range ef.Blocks { keyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name) if err != nil { return err } if err := t.Delete(keyBuf); err != nil { return err } } if !blocksHashSame { keyBuf, err := db.keyer.GenerateBlockListMapKey(keyBuf, folder, ef.BlocksHash, name) if err != nil { return err } if err = t.Delete(keyBuf); err != nil { return err } } } keyBuf, err = db.keyer.GenerateSequenceKey(keyBuf, folder, ef.SequenceNo()) if err != nil { return err } if err := t.Delete(keyBuf); err != nil { return err } l.Debugf("removing sequence; folder=%q sequence=%v %v", folder, ef.SequenceNo(), ef.FileName()) } f.Sequence = meta.nextLocalSeq() if ok { meta.removeFile(protocol.LocalDeviceID, ef) } meta.addFile(protocol.LocalDeviceID, f) l.Debugf("insert (local); folder=%q %v", folder, f) if err := t.putFile(dk, f, false); err != nil { return err } gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, []byte(f.Name)) if err != nil { return err } keyBuf, _, err = t.updateGlobal(gk, keyBuf, folder, protocol.LocalDeviceID[:], f, meta) if err != nil { return err } keyBuf, err = db.keyer.GenerateSequenceKey(keyBuf, folder, f.Sequence) if err != nil { return err } if err := t.Put(keyBuf, dk); err != nil { return err } l.Debugf("adding sequence; folder=%q sequence=%v %v", folder, f.Sequence, f.Name) if !f.IsDirectory() && !f.IsDeleted() && !f.IsInvalid() { for i, block := range f.Blocks { binary.BigEndian.PutUint32(blockBuf, uint32(i)) keyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name) if err != nil { return err } if err := t.Put(keyBuf, blockBuf); err != nil { return err } } if !blocksHashSame { keyBuf, err := db.keyer.GenerateBlockListMapKey(keyBuf, folder, f.BlocksHash, name) if err != nil { return err } if err = t.Put(keyBuf, nil); err != nil { return err } } } if err := t.Checkpoint(func() error { return meta.toDB(t, folder) }); err != nil { return err } } if err := meta.toDB(t, folder); err != nil { return err } return t.Commit() } func (db *Lowlevel) dropFolder(folder []byte) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() // Remove all items related to the given folder from the device->file bucket k0, err := db.keyer.GenerateDeviceFileKey(nil, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k0.WithoutNameAndDevice()); err != nil { return err } // Remove all sequences related to the folder k1, err := db.keyer.GenerateSequenceKey(k0, folder, 0) if err != nil { return err } if err := t.deleteKeyPrefix(k1.WithoutSequence()); err != nil { return err } // Remove all items related to the given folder from the global bucket k2, err := db.keyer.GenerateGlobalVersionKey(k1, folder, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k2.WithoutName()); err != nil { return err } // Remove all needs related to the folder k3, err := db.keyer.GenerateNeedFileKey(k2, folder, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k3.WithoutName()); err != nil { return err } // Remove the blockmap of the folder k4, err := db.keyer.GenerateBlockMapKey(k3, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k4.WithoutHashAndName()); err != nil { return err } k5, err := db.keyer.GenerateBlockListMapKey(k4, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(k5.WithoutHashAndName()); err != nil { return err } return t.Commit() } func (db *Lowlevel) dropDeviceFolder(device, folder []byte, meta *metadataTracker) error { db.gcMut.RLock() defer db.gcMut.RUnlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() key, err := db.keyer.GenerateDeviceFileKey(nil, folder, device, nil) if err != nil { return err } dbi, err := t.NewPrefixIterator(key) if err != nil { return err } var gk, keyBuf []byte for dbi.Next() { name := db.keyer.NameFromDeviceFileKey(dbi.Key()) gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } keyBuf, err = t.removeFromGlobal(gk, keyBuf, folder, device, name, meta) if err != nil { return err } if err := t.Delete(dbi.Key()); err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } if err := dbi.Error(); err != nil { return err } dbi.Release() if bytes.Equal(device, protocol.LocalDeviceID[:]) { key, err := db.keyer.GenerateBlockMapKey(nil, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(key.WithoutHashAndName()); err != nil { return err } key2, err := db.keyer.GenerateBlockListMapKey(key, folder, nil, nil) if err != nil { return err } if err := t.deleteKeyPrefix(key2.WithoutHashAndName()); err != nil { return err } } return t.Commit() } func (db *Lowlevel) checkGlobals(folder []byte, meta *metadataTracker) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() key, err := db.keyer.GenerateGlobalVersionKey(nil, folder, nil) if err != nil { return err } dbi, err := t.NewPrefixIterator(key.WithoutName()) if err != nil { return err } defer dbi.Release() var dk []byte for dbi.Next() { var vl VersionList if err := vl.Unmarshal(dbi.Value()); err != nil || len(vl.Versions) == 0 { if err := t.Delete(dbi.Key()); err != nil { return err } continue } // Check the global version list for consistency. An issue in previous // versions of goleveldb could result in reordered writes so that // there are global entries pointing to no longer existing files. Here // we find those and clear them out. name := db.keyer.NameFromGlobalVersionKey(dbi.Key()) var newVL VersionList for i, version := range vl.Versions { dk, err = db.keyer.GenerateDeviceFileKey(dk, folder, version.Device, name) if err != nil { return err } _, err := t.Get(dk) if backend.IsNotFound(err) { continue } if err != nil { return err } newVL.Versions = append(newVL.Versions, version) if i == 0 { if fi, ok, err := t.getFileTrunc(dk, true); err != nil { return err } else if ok { meta.addFile(protocol.GlobalDeviceID, fi) } } } if newLen := len(newVL.Versions); newLen == 0 { if err := t.Delete(dbi.Key()); err != nil { return err } } else if newLen != len(vl.Versions) { if err := t.Put(dbi.Key(), mustMarshal(&newVL)); err != nil { return err } } } if err := dbi.Error(); err != nil { return err } l.Debugf("db check completed for %q", folder) return t.Commit() } func (db *Lowlevel) getIndexID(device, folder []byte) (protocol.IndexID, error) { key, err := db.keyer.GenerateIndexIDKey(nil, device, folder) if err != nil { return 0, err } cur, err := db.Get(key) if backend.IsNotFound(err) { return 0, nil } else if err != nil { return 0, err } var id protocol.IndexID if err := id.Unmarshal(cur); err != nil { return 0, nil } return id, nil } func (db *Lowlevel) setIndexID(device, folder []byte, id protocol.IndexID) error { bs, _ := id.Marshal() // marshalling can't fail key, err := db.keyer.GenerateIndexIDKey(nil, device, folder) if err != nil { return err } return db.Put(key, bs) } func (db *Lowlevel) dropMtimes(folder []byte) error { key, err := db.keyer.GenerateMtimesKey(nil, folder) if err != nil { return err } return db.dropPrefix(key) } func (db *Lowlevel) dropFolderMeta(folder []byte) error { key, err := db.keyer.GenerateFolderMetaKey(nil, folder) if err != nil { return err } return db.dropPrefix(key) } func (db *Lowlevel) dropPrefix(prefix []byte) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() if err := t.deleteKeyPrefix(prefix); err != nil { return err } return t.Commit() } func (db *Lowlevel) gcRunner(ctx context.Context) { // Calculate the time for the next GC run. Even if we should run GC // directly, give the system a while to get up and running and do other // stuff first. (We might have migrations and stuff which would be // better off running before GC.) next := db.timeUntil(indirectGCTimeKey, db.indirectGCInterval) if next < time.Minute { next = time.Minute } t := time.NewTimer(next) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: if err := db.gcIndirect(ctx); err != nil { l.Warnln("Database indirection GC failed:", err) } db.recordTime(indirectGCTimeKey) t.Reset(db.timeUntil(indirectGCTimeKey, db.indirectGCInterval)) } } } // recordTime records the current time under the given key, affecting the // next call to timeUntil with the same key. func (db *Lowlevel) recordTime(key string) { miscDB := NewMiscDataNamespace(db) _ = miscDB.PutInt64(key, time.Now().Unix()) // error wilfully ignored } // timeUntil returns how long we should wait until the next interval, or // zero if it should happen directly. func (db *Lowlevel) timeUntil(key string, every time.Duration) time.Duration { miscDB := NewMiscDataNamespace(db) lastTime, _, _ := miscDB.Int64(key) // error wilfully ignored nextTime := time.Unix(lastTime, 0).Add(every) sleepTime := time.Until(nextTime) if sleepTime < 0 { sleepTime = 0 } return sleepTime } func (db *Lowlevel) gcIndirect(ctx context.Context) error { // The indirection GC uses bloom filters to track used block lists and // versions. This means iterating over all items, adding their hashes to // the filter, then iterating over the indirected items and removing // those that don't match the filter. The filter will give false // positives so we will keep around one percent of things that we don't // really need (at most). // // Indirection GC needs to run when there are no modifications to the // FileInfos or indirected items. db.gcMut.Lock() defer db.gcMut.Unlock() t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.Release() // Set up the bloom filters with the initial capacity and false positive // rate, or higher capacity if we've done this before and seen lots of // items. For simplicity's sake we track just one count, which is the // highest of the various indirected items. capacity := indirectGCBloomCapacity if db.gcKeyCount > capacity { capacity = db.gcKeyCount } blockFilter := newBloomFilter(capacity) versionFilter := newBloomFilter(capacity) // Iterate the FileInfos, unmarshal the block and version hashes and // add them to the filter. it, err := t.NewPrefixIterator([]byte{KeyTypeDevice}) if err != nil { return err } defer it.Release() for it.Next() { select { case <-ctx.Done(): return ctx.Err() default: } var hashes IndirectionHashesOnly if err := hashes.Unmarshal(it.Value()); err != nil { return err } if len(hashes.BlocksHash) > 0 { blockFilter.Add(bloomHash(hashes.BlocksHash)) } if len(hashes.VersionHash) > 0 { versionFilter.Add(bloomHash(hashes.VersionHash)) } } it.Release() if err := it.Error(); err != nil { return err } // Iterate over block lists, removing keys with hashes that don't match // the filter. it, err = t.NewPrefixIterator([]byte{KeyTypeBlockList}) if err != nil { return err } defer it.Release() matchedBlocks := 0 for it.Next() { select { case <-ctx.Done(): return ctx.Err() default: } key := blockListKey(it.Key()) if blockFilter.Has(bloomHash(key.Hash())) { matchedBlocks++ continue } if err := t.Delete(key); err != nil { return err } } it.Release() if err := it.Error(); err != nil { return err } // Iterate over version lists, removing keys with hashes that don't match // the filter. it, err = db.NewPrefixIterator([]byte{KeyTypeVersion}) if err != nil { return err } matchedVersions := 0 for it.Next() { select { case <-ctx.Done(): return ctx.Err() default: } key := versionKey(it.Key()) if versionFilter.Has(bloomHash(key.Hash())) { matchedVersions++ continue } if err := t.Delete(key); err != nil { return err } } it.Release() if err := it.Error(); err != nil { return err } // Remember the number of unique keys we kept until the next pass. db.gcKeyCount = matchedBlocks if matchedVersions > matchedBlocks { db.gcKeyCount = matchedVersions } if err := t.Commit(); err != nil { return err } return db.Compact() } func newBloomFilter(capacity int) *blobloom.Filter { return blobloom.NewOptimized(blobloom.Config{ Capacity: uint64(capacity), FPRate: indirectGCBloomFalsePositiveRate, MaxBits: 8 * indirectGCBloomMaxBytes, }) } // Hash function for the bloomfilter: first eight bytes of the SHA-256. // Big or little-endian makes no difference, as long as we're consistent. func bloomHash(key []byte) uint64 { if len(key) != sha256.Size { panic("bug: bloomHash passed something not a SHA256 hash") } return binary.BigEndian.Uint64(key) } // CheckRepair checks folder metadata and sequences for miscellaneous errors. func (db *Lowlevel) CheckRepair() { for _, folder := range db.ListFolders() { _ = db.getMetaAndCheck(folder) } } func (db *Lowlevel) getMetaAndCheck(folder string) *metadataTracker { db.gcMut.RLock() defer db.gcMut.RUnlock() meta, err := db.recalcMeta(folder) if err == nil { var fixed int fixed, err = db.repairSequenceGCLocked(folder, meta) if fixed != 0 { l.Infof("Repaired %d sequence entries in database", fixed) } } if backend.IsClosed(err) { return nil } else if err != nil { panic(err) } return meta } func (db *Lowlevel) loadMetadataTracker(folder string) *metadataTracker { meta := newMetadataTracker() if err := meta.fromDB(db, []byte(folder)); err != nil { l.Infof("No stored folder metadata for %q; recalculating", folder) return db.getMetaAndCheck(folder) } curSeq := meta.Sequence(protocol.LocalDeviceID) if metaOK := db.verifyLocalSequence(curSeq, folder); !metaOK { l.Infof("Stored folder metadata for %q is out of date after crash; recalculating", folder) return db.getMetaAndCheck(folder) } if age := time.Since(meta.Created()); age > db.recheckInterval { l.Infof("Stored folder metadata for %q is %v old; recalculating", folder, age) return db.getMetaAndCheck(folder) } return meta } func (db *Lowlevel) recalcMeta(folder string) (*metadataTracker, error) { meta := newMetadataTracker() if err := db.checkGlobals([]byte(folder), meta); err != nil { return nil, err } t, err := db.newReadWriteTransaction() if err != nil { return nil, err } defer t.close() var deviceID protocol.DeviceID err = t.withAllFolderTruncated([]byte(folder), func(device []byte, f FileInfoTruncated) bool { copy(deviceID[:], device) meta.addFile(deviceID, f) return true }) if err != nil { return nil, err } meta.emptyNeeded(protocol.LocalDeviceID) err = t.withNeed([]byte(folder), protocol.LocalDeviceID[:], true, func(f FileIntf) bool { meta.addNeeded(protocol.LocalDeviceID, f) return true }) if err != nil { return nil, err } for _, device := range meta.devices() { meta.emptyNeeded(device) err = t.withNeed([]byte(folder), device[:], true, func(f FileIntf) bool { meta.addNeeded(device, f) return true }) if err != nil { return nil, err } } meta.SetCreated() if err := meta.toDB(t, []byte(folder)); err != nil { return nil, err } if err := t.Commit(); err != nil { return nil, err } return meta, nil } // Verify the local sequence number from actual sequence entries. Returns // true if it was all good, or false if a fixup was necessary. func (db *Lowlevel) verifyLocalSequence(curSeq int64, folder string) bool { // Walk the sequence index from the current (supposedly) highest // sequence number and raise the alarm if we get anything. This recovers // from the occasion where we have written sequence entries to disk but // not yet written new metadata to disk. // // Note that we can have the same thing happen for remote devices but // there it's not a problem -- we'll simply advertise a lower sequence // number than we've actually seen and receive some duplicate updates // and then be in sync again. t, err := db.newReadOnlyTransaction() if err != nil { panic(err) } ok := true if err := t.withHaveSequence([]byte(folder), curSeq+1, func(fi FileIntf) bool { ok = false // we got something, which we should not have return false }); err != nil && !backend.IsClosed(err) { panic(err) } t.close() return ok } // repairSequenceGCLocked makes sure the sequence numbers in the sequence keys // match those in the corresponding file entries. It returns the amount of fixed // entries. func (db *Lowlevel) repairSequenceGCLocked(folderStr string, meta *metadataTracker) (int, error) { t, err := db.newReadWriteTransaction() if err != nil { return 0, err } defer t.close() fixed := 0 folder := []byte(folderStr) // First check that every file entry has a matching sequence entry // (this was previously db schema upgrade to 9). dk, err := t.keyer.GenerateDeviceFileKey(nil, folder, protocol.LocalDeviceID[:], nil) if err != nil { return 0, err } it, err := t.NewPrefixIterator(dk.WithoutName()) if err != nil { return 0, err } defer it.Release() var sk sequenceKey for it.Next() { intf, err := t.unmarshalTrunc(it.Value(), true) if err != nil { return 0, err } fi := intf.(FileInfoTruncated) if sk, err = t.keyer.GenerateSequenceKey(sk, folder, fi.Sequence); err != nil { return 0, err } switch dk, err = t.Get(sk); { case err != nil: if !backend.IsNotFound(err) { return 0, err } fallthrough case !bytes.Equal(it.Key(), dk): fixed++ fi.Sequence = meta.nextLocalSeq() if sk, err = t.keyer.GenerateSequenceKey(sk, folder, fi.Sequence); err != nil { return 0, err } if err := t.Put(sk, it.Key()); err != nil { return 0, err } if err := t.putFile(it.Key(), fi.copyToFileInfo(), true); err != nil { return 0, err } } if err := t.Checkpoint(func() error { return meta.toDB(t, folder) }); err != nil { return 0, err } } if err := it.Error(); err != nil { return 0, err } it.Release() // Secondly check there's no sequence entries pointing at incorrect things. sk, err = t.keyer.GenerateSequenceKey(sk, folder, 0) if err != nil { return 0, err } it, err = t.NewPrefixIterator(sk.WithoutSequence()) if err != nil { return 0, err } defer it.Release() for it.Next() { // Check that the sequence from the key matches the // sequence in the file. fi, ok, err := t.getFileTrunc(it.Value(), true) if err != nil { return 0, err } if ok { if seq := t.keyer.SequenceFromSequenceKey(it.Key()); seq == fi.SequenceNo() { continue } } // Either the file is missing or has a different sequence number fixed++ if err := t.Delete(it.Key()); err != nil { return 0, err } } if err := it.Error(); err != nil { return 0, err } it.Release() if err := meta.toDB(t, folder); err != nil { return 0, err } return fixed, t.Commit() } // unchanged checks if two files are the same and thus don't need to be updated. // Local flags or the invalid bit might change without the version // being bumped. func unchanged(nf, ef FileIntf) bool { return ef.FileVersion().Equal(nf.FileVersion()) && ef.IsInvalid() == nf.IsInvalid() && ef.FileLocalFlags() == nf.FileLocalFlags() }
lib/db/lowlevel.go
1
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.9979844093322754, 0.02237868309020996, 0.00016185309505090117, 0.0008415878983214498, 0.1360773742198944 ]
{ "id": 1, "code_window": [ "\t\tif err := t.Put(keyBuf, dk); err != nil {\n", "\t\t\treturn err\n", "\t\t}\n", "\t\tl.Debugf(\"adding sequence; folder=%q sequence=%v %v\", folder, f.Sequence, f.Name)\n", "\n", "\t\tif !f.IsDirectory() && !f.IsDeleted() && !f.IsInvalid() {\n", "\t\t\tfor i, block := range f.Blocks {\n", "\t\t\t\tbinary.BigEndian.PutUint32(blockBuf, uint32(i))\n", "\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\tif err != nil {\n", "\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(f.Blocks) != 0 && !f.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 264 }
// Copyright (C) 2019 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package stun import ( "github.com/syncthing/syncthing/lib/logger" ) var ( l = logger.DefaultLogger.NewFacility("stun", "STUN functionality") )
lib/stun/debug.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0008665628847666085, 0.000521727604791522, 0.00017689232481643558, 0.000521727604791522, 0.00034483527997508645 ]
{ "id": 1, "code_window": [ "\t\tif err := t.Put(keyBuf, dk); err != nil {\n", "\t\t\treturn err\n", "\t\t}\n", "\t\tl.Debugf(\"adding sequence; folder=%q sequence=%v %v\", folder, f.Sequence, f.Name)\n", "\n", "\t\tif !f.IsDirectory() && !f.IsDeleted() && !f.IsInvalid() {\n", "\t\t\tfor i, block := range f.Blocks {\n", "\t\t\t\tbinary.BigEndian.PutUint32(blockBuf, uint32(i))\n", "\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\tif err != nil {\n", "\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(f.Blocks) != 0 && !f.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 264 }
// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. // +build ignore package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "regexp" "sort" "strings" ) type stat struct { Translated int `json:"translated_entities"` Untranslated int `json:"untranslated_entities"` } type translation struct { Content string } func main() { log.SetFlags(log.Lshortfile) if u, p := userPass(); u == "" || p == "" { log.Fatal("Need environment variables TRANSIFEX_USER and TRANSIFEX_PASS") } curValidLangs := map[string]bool{} for _, lang := range loadValidLangs() { curValidLangs[lang] = true } log.Println(curValidLangs) resp := req("https://www.transifex.com/api/2/project/syncthing/resource/gui/stats") var stats map[string]stat err := json.NewDecoder(resp.Body).Decode(&stats) if err != nil { log.Fatal(err) } resp.Body.Close() names := make(map[string]string) var langs []string for code, stat := range stats { code = strings.Replace(code, "_", "-", 1) pct := 100 * stat.Translated / (stat.Translated + stat.Untranslated) if pct < 75 || !curValidLangs[code] && pct < 95 { log.Printf("Skipping language %q (too low completion ratio %d%%)", code, pct) os.Remove("lang-" + code + ".json") continue } langs = append(langs, code) names[code] = languageName(code) if code == "en" { continue } log.Printf("Updating language %q", code) resp := req("https://www.transifex.com/api/2/project/syncthing/resource/gui/translation/" + code) var t translation err := json.NewDecoder(resp.Body).Decode(&t) if err != nil { log.Fatal(err) } resp.Body.Close() fd, err := os.Create("lang-" + code + ".json") if err != nil { log.Fatal(err) } fd.WriteString(t.Content) fd.Close() } saveValidLangs(langs) saveLanguageNames(names) } func saveValidLangs(langs []string) { sort.Strings(langs) fd, err := os.Create("valid-langs.js") if err != nil { log.Fatal(err) } fmt.Fprint(fd, "var validLangs = ") json.NewEncoder(fd).Encode(langs) fd.Close() } func saveLanguageNames(names map[string]string) { fd, err := os.Create("prettyprint.js") if err != nil { log.Fatal(err) } fmt.Fprint(fd, "var langPrettyprint = ") json.NewEncoder(fd).Encode(names) fd.Close() } func userPass() (string, string) { user := os.Getenv("TRANSIFEX_USER") pass := os.Getenv("TRANSIFEX_PASS") return user, pass } func req(url string) *http.Response { user, pass := userPass() req, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } req.SetBasicAuth(user, pass) resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } return resp } func loadValidLangs() []string { fd, err := os.Open("valid-langs.js") if err != nil { log.Fatal(err) } defer fd.Close() bs, err := ioutil.ReadAll(fd) if err != nil { log.Fatal(err) } var langs []string exp := regexp.MustCompile(`\[([a-zA-Z@",-]+)\]`) if matches := exp.FindSubmatch(bs); len(matches) == 2 { langs = strings.Split(string(matches[1]), ",") for i := range langs { // Remove quotes langs[i] = langs[i][1 : len(langs[i])-1] } } return langs } type languageResponse struct { Code string Name string } func languageName(code string) string { var lang languageResponse resp := req("https://www.transifex.com/api/2/language/" + code) defer resp.Body.Close() json.NewDecoder(resp.Body).Decode(&lang) if lang.Name == "" { return code } return lang.Name }
script/transifexdl.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0003883477475028485, 0.0001803399354685098, 0.00015810148033779114, 0.00016960426000878215, 0.000050701521104201674 ]
{ "id": 1, "code_window": [ "\t\tif err := t.Put(keyBuf, dk); err != nil {\n", "\t\t\treturn err\n", "\t\t}\n", "\t\tl.Debugf(\"adding sequence; folder=%q sequence=%v %v\", folder, f.Sequence, f.Name)\n", "\n", "\t\tif !f.IsDirectory() && !f.IsDeleted() && !f.IsInvalid() {\n", "\t\t\tfor i, block := range f.Blocks {\n", "\t\t\t\tbinary.BigEndian.PutUint32(blockBuf, uint32(i))\n", "\t\t\t\tkeyBuf, err = db.keyer.GenerateBlockMapKey(keyBuf, folder, block.Hash, name)\n", "\t\t\t\tif err != nil {\n", "\t\t\t\t\treturn err\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif len(f.Blocks) != 0 && !f.IsInvalid() {\n" ], "file_path": "lib/db/lowlevel.go", "type": "replace", "edit_start_line_idx": 264 }
// Copyright (C) 2019 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package fs import ( "runtime" "testing" ) func TestCommonPrefix(t *testing.T) { test := func(first, second, expect string) { t.Helper() res := CommonPrefix(first, second) if res != expect { t.Errorf("Expected %s got %s", expect, res) } } if runtime.GOOS == "windows" { test(`c:\Audrius\Downloads`, `c:\Audrius\Docs`, `c:\Audrius`) test(`c:\Audrius\Downloads`, `C:\Audrius\Docs`, ``) // Case differences :( test(`C:\Audrius-a\Downloads`, `C:\Audrius-b\Docs`, `C:\`) test(`\\?\C:\Audrius-a\Downloads`, `\\?\C:\Audrius-b\Docs`, `\\?\C:\`) test(`\\?\C:\Audrius\Downloads`, `\\?\C:\Audrius\Docs`, `\\?\C:\Audrius`) test(`Audrius-a\Downloads`, `Audrius-b\Docs`, ``) test(`Audrius\Downloads`, `Audrius\Docs`, `Audrius`) test(`c:\Audrius\Downloads`, `Audrius\Docs`, ``) test(`c:\`, `c:\`, `c:\`) test(`\\?\c:\`, `\\?\c:\`, `\\?\c:\`) } else { test(`/Audrius/Downloads`, `/Audrius/Docs`, `/Audrius`) test(`/Audrius\Downloads`, `/Audrius\Docs`, `/`) test(`/Audrius-a/Downloads`, `/Audrius-b/Docs`, `/`) test(`Audrius\Downloads`, `Audrius\Docs`, ``) // Windows separators test(`Audrius/Downloads`, `Audrius/Docs`, `Audrius`) test(`Audrius-a\Downloads`, `Audrius-b\Docs`, ``) test(`/Audrius/Downloads`, `Audrius/Docs`, ``) test(`/`, `/`, `/`) } test(`Audrius`, `Audrius`, `Audrius`) test(`.`, `.`, `.`) }
lib/fs/util_test.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0001771021052263677, 0.0001723539608065039, 0.00016295969544444233, 0.00017448958533350378, 0.000004942579835187644 ]
{ "id": 2, "code_window": [ "\tfor _, folderStr := range db.ListFolders() {\n", "\t\tfolder := []byte(folderStr)\n", "\t\tvar putErr error\n", "\t\terr := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool {\n", "\t\t\tf := fi.(FileInfoTruncated)\n", "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil {\n", "\t\t\t\treturn true\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsSymlink() || f.IsInvalid() || f.BlocksHash == nil {\n" ], "file_path": "lib/db/schemaupdater.go", "type": "replace", "edit_start_line_idx": 592 }
// Copyright (C) 2018 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package db import ( "fmt" "strings" "github.com/syncthing/syncthing/lib/db/backend" "github.com/syncthing/syncthing/lib/protocol" ) // List of all dbVersion to dbMinSyncthingVersion pairs for convenience // 0: v0.14.0 // 1: v0.14.46 // 2: v0.14.48 // 3-5: v0.14.49 // 6: v0.14.50 // 7: v0.14.53 // 8-9: v1.4.0 // 10-11: v1.6.0 // 12: v1.7.0 const ( dbVersion = 12 dbMinSyncthingVersion = "v1.7.0" ) type databaseDowngradeError struct { minSyncthingVersion string } func (e databaseDowngradeError) Error() string { if e.minSyncthingVersion == "" { return "newer Syncthing required" } return fmt.Sprintf("Syncthing %s required", e.minSyncthingVersion) } func UpdateSchema(db *Lowlevel) error { updater := &schemaUpdater{db} return updater.updateSchema() } type schemaUpdater struct { *Lowlevel } func (db *schemaUpdater) updateSchema() error { // Updating the schema can touch any and all parts of the database. Make // sure we do not run GC concurrently with schema migrations. db.gcMut.Lock() defer db.gcMut.Unlock() miscDB := NewMiscDataNamespace(db.Lowlevel) prevVersion, _, err := miscDB.Int64("dbVersion") if err != nil { return err } if prevVersion > dbVersion { err := databaseDowngradeError{} if minSyncthingVersion, ok, dbErr := miscDB.String("dbMinSyncthingVersion"); dbErr != nil { return dbErr } else if ok { err.minSyncthingVersion = minSyncthingVersion } return err } if prevVersion == dbVersion { return nil } type migration struct { schemaVersion int64 migration func(prevVersion int) error } var migrations = []migration{ {1, db.updateSchema0to1}, {2, db.updateSchema1to2}, {3, db.updateSchema2to3}, {5, db.updateSchemaTo5}, {6, db.updateSchema5to6}, {7, db.updateSchema6to7}, {9, db.updateSchemaTo9}, {10, db.updateSchemaTo10}, {11, db.updateSchemaTo11}, {12, db.updateSchemaTo12}, } for _, m := range migrations { if prevVersion < m.schemaVersion { l.Infof("Migrating database to schema version %d...", m.schemaVersion) if err := m.migration(int(prevVersion)); err != nil { return err } } } if err := miscDB.PutInt64("dbVersion", dbVersion); err != nil { return err } if err := miscDB.PutString("dbMinSyncthingVersion", dbMinSyncthingVersion); err != nil { return err } l.Infoln("Compacting database after migration...") return db.Compact() } func (db *schemaUpdater) updateSchema0to1(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() dbi, err := t.NewPrefixIterator([]byte{KeyTypeDevice}) if err != nil { return err } defer dbi.Release() symlinkConv := 0 changedFolders := make(map[string]struct{}) ignAdded := 0 meta := newMetadataTracker() // dummy metadata tracker var gk, buf []byte for dbi.Next() { folder, ok := db.keyer.FolderFromDeviceFileKey(dbi.Key()) if !ok { // not having the folder in the index is bad; delete and continue if err := t.Delete(dbi.Key()); err != nil { return err } continue } device, ok := db.keyer.DeviceFromDeviceFileKey(dbi.Key()) if !ok { // not having the device in the index is bad; delete and continue if err := t.Delete(dbi.Key()); err != nil { return err } continue } name := db.keyer.NameFromDeviceFileKey(dbi.Key()) // Remove files with absolute path (see #4799) if strings.HasPrefix(string(name), "/") { if _, ok := changedFolders[string(folder)]; !ok { changedFolders[string(folder)] = struct{}{} } gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } // Purposely pass nil file name to remove from global list, // but don't touch meta and needs buf, err = t.removeFromGlobal(gk, buf, folder, device, nil, nil) if err != nil && err != errEntryFromGlobalMissing { return err } if err := t.Delete(dbi.Key()); err != nil { return err } continue } // Change SYMLINK_FILE and SYMLINK_DIRECTORY types to the current SYMLINK // type (previously SYMLINK_UNKNOWN). It does this for all devices, both // local and remote, and does not reset delta indexes. It shouldn't really // matter what the symlink type is, but this cleans it up for a possible // future when SYMLINK_FILE and SYMLINK_DIRECTORY are no longer understood. var f protocol.FileInfo if err := f.Unmarshal(dbi.Value()); err != nil { // probably can't happen continue } if f.Type == protocol.FileInfoTypeDeprecatedSymlinkDirectory || f.Type == protocol.FileInfoTypeDeprecatedSymlinkFile { f.Type = protocol.FileInfoTypeSymlink bs, err := f.Marshal() if err != nil { panic("can't happen: " + err.Error()) } if err := t.Put(dbi.Key(), bs); err != nil { return err } symlinkConv++ } // Add invalid files to global list if f.IsInvalid() { gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } if buf, ok, err = t.updateGlobal(gk, buf, folder, device, f, meta); err != nil { return err } else if ok { if _, ok = changedFolders[string(folder)]; !ok { changedFolders[string(folder)] = struct{}{} } ignAdded++ } } if err := t.Checkpoint(); err != nil { return err } } for folder := range changedFolders { if err := db.dropFolderMeta([]byte(folder)); err != nil { return err } } return t.Commit() } // updateSchema1to2 introduces a sequenceKey->deviceKey bucket for local items // to allow iteration in sequence order (simplifies sending indexes). func (db *schemaUpdater) updateSchema1to2(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var sk []byte var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var putErr error err := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(f FileIntf) bool { sk, putErr = db.keyer.GenerateSequenceKey(sk, folder, f.SequenceNo()) if putErr != nil { return false } dk, putErr = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], []byte(f.FileName())) if putErr != nil { return false } putErr = t.Put(sk, dk) return putErr == nil }) if putErr != nil { return putErr } if err != nil { return err } } return t.Commit() } // updateSchema2to3 introduces a needKey->nil bucket for locally needed files. func (db *schemaUpdater) updateSchema2to3(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var nk []byte var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var putErr error err := t.withGlobal(folder, nil, true, func(f FileIntf) bool { name := []byte(f.FileName()) dk, putErr = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], name) if putErr != nil { return false } var v protocol.Vector haveFile, ok, err := t.getFileTrunc(dk, true) if err != nil { putErr = err return false } if ok { v = haveFile.FileVersion() } fv := FileVersion{ Version: f.FileVersion(), Invalid: f.IsInvalid(), Deleted: f.IsDeleted(), } if !need(fv, ok, v) { return true } nk, putErr = t.keyer.GenerateNeedFileKey(nk, folder, []byte(f.FileName())) if putErr != nil { return false } putErr = t.Put(nk, nil) return putErr == nil }) if putErr != nil { return putErr } if err != nil { return err } } return t.Commit() } // updateSchemaTo5 resets the need bucket due to bugs existing in the v0.14.49 // release candidates (dbVersion 3 and 4) // https://github.com/syncthing/syncthing/issues/5007 // https://github.com/syncthing/syncthing/issues/5053 func (db *schemaUpdater) updateSchemaTo5(prevVersion int) error { if prevVersion != 3 && prevVersion != 4 { return nil } t, err := db.newReadWriteTransaction() if err != nil { return err } var nk []byte for _, folderStr := range db.ListFolders() { nk, err = db.keyer.GenerateNeedFileKey(nk, []byte(folderStr), nil) if err != nil { return err } if err := t.deleteKeyPrefix(nk[:keyPrefixLen+keyFolderLen]); err != nil { return err } } if err := t.Commit(); err != nil { return err } return db.updateSchema2to3(2) } func (db *schemaUpdater) updateSchema5to6(_ int) error { // For every local file with the Invalid bit set, clear the Invalid bit and // set LocalFlags = FlagLocalIgnored. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var iterErr error err := t.withHave(folder, protocol.LocalDeviceID[:], nil, false, func(f FileIntf) bool { if !f.IsInvalid() { return true } fi := f.(protocol.FileInfo) fi.RawInvalid = false fi.LocalFlags = protocol.FlagLocalIgnored bs, _ := fi.Marshal() dk, iterErr = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], []byte(fi.Name)) if iterErr != nil { return false } if iterErr = t.Put(dk, bs); iterErr != nil { return false } iterErr = t.Checkpoint() return iterErr == nil }) if iterErr != nil { return iterErr } if err != nil { return err } } return t.Commit() } // updateSchema6to7 checks whether all currently locally needed files are really // needed and removes them if not. func (db *schemaUpdater) updateSchema6to7(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var gk []byte var nk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var delErr error err := t.withNeedLocal(folder, false, func(f FileIntf) bool { name := []byte(f.FileName()) gk, delErr = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if delErr != nil { return false } svl, err := t.Get(gk) if err != nil { // If there is no global list, we hardly need it. key, err := t.keyer.GenerateNeedFileKey(nk, folder, name) if err != nil { delErr = err return false } delErr = t.Delete(key) return delErr == nil } var fl VersionList err = fl.Unmarshal(svl) if err != nil { // This can't happen, but it's ignored everywhere else too, // so lets not act on it. return true } globalFV := FileVersion{ Version: f.FileVersion(), Invalid: f.IsInvalid(), Deleted: f.IsDeleted(), } if localFV, haveLocalFV := fl.Get(protocol.LocalDeviceID[:]); !need(globalFV, haveLocalFV, localFV.Version) { key, err := t.keyer.GenerateNeedFileKey(nk, folder, name) if err != nil { delErr = err return false } delErr = t.Delete(key) } return delErr == nil }) if delErr != nil { return delErr } if err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } return t.Commit() } func (db *schemaUpdater) updateSchemaTo9(prev int) error { // Loads and rewrites all files with blocks, to deduplicate block lists. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() if err := db.rewriteFiles(t); err != nil { return err } db.recordTime(indirectGCTimeKey) return t.Commit() } func (db *schemaUpdater) rewriteFiles(t readWriteTransaction) error { it, err := t.NewPrefixIterator([]byte{KeyTypeDevice}) if err != nil { return err } for it.Next() { intf, err := t.unmarshalTrunc(it.Value(), false) if backend.IsNotFound(err) { // Unmarshal error due to missing parts (block list), probably // due to a bad migration in a previous RC. Drop this key, as // getFile would anyway return this as a "not found" in the // normal flow of things. if err := t.Delete(it.Key()); err != nil { return err } continue } else if err != nil { return err } fi := intf.(protocol.FileInfo) if fi.Blocks == nil { continue } if err := t.putFile(it.Key(), fi, false); err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } it.Release() return it.Error() } func (db *schemaUpdater) updateSchemaTo10(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var buf []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) buf, err = t.keyer.GenerateGlobalVersionKey(buf, folder, nil) if err != nil { return err } buf = globalVersionKey(buf).WithoutName() dbi, err := t.NewPrefixIterator(buf) if err != nil { return err } defer dbi.Release() for dbi.Next() { var vl VersionList if err := vl.Unmarshal(dbi.Value()); err != nil { return err } changed := false name := t.keyer.NameFromGlobalVersionKey(dbi.Key()) for i, fv := range vl.Versions { buf, err = t.keyer.GenerateDeviceFileKey(buf, folder, fv.Device, name) if err != nil { return err } f, ok, err := t.getFileTrunc(buf, true) if !ok { return errEntryFromGlobalMissing } if err != nil { return err } if f.IsDeleted() { vl.Versions[i].Deleted = true changed = true } } if changed { if err := t.Put(dbi.Key(), mustMarshal(&vl)); err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } } dbi.Release() } // Trigger metadata recalc if err := t.deleteKeyPrefix([]byte{KeyTypeFolderMeta}); err != nil { return err } return t.Commit() } func (db *schemaUpdater) updateSchemaTo11(_ int) error { // Populates block list map for every folder. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var putErr error err := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool { f := fi.(FileInfoTruncated) if f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil { return true } name := []byte(f.FileName()) dk, putErr = db.keyer.GenerateBlockListMapKey(dk, folder, f.BlocksHash, name) if putErr != nil { return false } if putErr = t.Put(dk, nil); putErr != nil { return false } putErr = t.Checkpoint() return putErr == nil }) if putErr != nil { return putErr } if err != nil { return err } } return t.Commit() } func (db *schemaUpdater) updateSchemaTo12(_ int) error { // Loads and rewrites all files, to deduplicate version vectors. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() if err := db.rewriteFiles(t); err != nil { return err } return t.Commit() }
lib/db/schemaupdater.go
1
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.9988256096839905, 0.44559451937675476, 0.000163991455337964, 0.0705736055970192, 0.47256773710250854 ]
{ "id": 2, "code_window": [ "\tfor _, folderStr := range db.ListFolders() {\n", "\t\tfolder := []byte(folderStr)\n", "\t\tvar putErr error\n", "\t\terr := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool {\n", "\t\t\tf := fi.(FileInfoTruncated)\n", "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil {\n", "\t\t\t\treturn true\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsSymlink() || f.IsInvalid() || f.BlocksHash == nil {\n" ], "file_path": "lib/db/schemaupdater.go", "type": "replace", "edit_start_line_idx": 592 }
// Copyright (C) 2015 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. // +build !windows package osutil import ( "runtime" "syscall" ) const ( darwinOpenMax = 10240 ) // MaximizeOpenFileLimit tries to set the resource limit RLIMIT_NOFILE (number // of open file descriptors) to the max (hard limit), if the current (soft // limit) is below the max. Returns the new (though possibly unchanged) limit, // or an error if it could not be changed. func MaximizeOpenFileLimit() (int, error) { // Get the current limit on number of open files. var lim syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil { return 0, err } // If we're already at max, there's no need to try to raise the limit. if lim.Cur >= lim.Max { return int(lim.Cur), nil } // macOS doesn't like a soft limit greater then OPEN_MAX // See also: man setrlimit if runtime.GOOS == "darwin" && lim.Max > darwinOpenMax { lim.Cur = darwinOpenMax } // Try to increase the limit to the max. oldLimit := lim.Cur lim.Cur = lim.Max if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil { return int(oldLimit), err } // If the set succeeded, perform a new get to see what happened. We might // have gotten a value lower than the one in lim.Max, if lim.Max was // something that indicated "unlimited" (i.e. intmax). if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil { // We don't really know the correct value here since Getrlimit // mysteriously failed after working once... Shouldn't ever happen, I // think. return 0, err } return int(lim.Cur), nil }
lib/osutil/rlimit_unix.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0005991048528812826, 0.00023301209148485214, 0.00016747284098528326, 0.00017219694564118981, 0.00014949694741517305 ]
{ "id": 2, "code_window": [ "\tfor _, folderStr := range db.ListFolders() {\n", "\t\tfolder := []byte(folderStr)\n", "\t\tvar putErr error\n", "\t\terr := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool {\n", "\t\t\tf := fi.(FileInfoTruncated)\n", "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil {\n", "\t\t\t\treturn true\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsSymlink() || f.IsInvalid() || f.BlocksHash == nil {\n" ], "file_path": "lib/db/schemaupdater.go", "type": "replace", "edit_start_line_idx": 592 }
/*! * Bootstrap v3.1.1 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}@media print{*{text-shadow:none!important;color:#000!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:before,:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:16px;line-height:1.42857143;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#3498db;text-decoration:none}a:hover,a:focus{color:#1d6fa5;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:3px}.img-thumbnail{padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:3px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.img-circle{border-radius:50%}hr{margin-top:22px;margin-bottom:22px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:inherit;font-weight:400;line-height:1.1;color:inherit}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:400;line-height:1;color:#999}h1,.h1,h2,.h2,h3,.h3{margin-top:22px;margin-bottom:11px}h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small{font-size:65%}h4,.h4,h5,.h5,h6,.h6{margin-top:11px;margin-bottom:11px}h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small{font-size:75%}h1,.h1{font-size:41px}h2,.h2{font-size:34px}h3,.h3{font-size:28px}h4,.h4{font-size:20px}h5,.h5{font-size:16px}h6,.h6{font-size:14px}p{margin:0 0 11px}.lead{margin-bottom:22px;font-size:18px;font-weight:200;line-height:1.4}@media (min-width:768px){.lead{font-size:24px}}small,.small{font-size:85%}cite{font-style:normal}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-muted{color:#999}.text-primary{color:#3498db}a.text-primary:hover{color:#217dbb}.text-success{color:#29b74e}a.text-success:hover{color:#208e3c}.text-info{color:#7f4bab}a.text-info:hover{color:#653b87}.text-warning{color:#da8f0d}a.text-warning:hover{color:#aa6f0a}.text-danger{color:#e42533}a.text-danger:hover{color:#bf1824}.bg-primary{color:#fff;background-color:#3498db}a.bg-primary:hover{background-color:#217dbb}.bg-success{background-color:#2ecc71}a.bg-success:hover{background-color:#25a25a}.bg-info{background-color:#9b59b6}a.bg-info:hover{background-color:#804399}.bg-warning{background-color:#f1c40f}a.bg-warning:hover{background-color:#c29d0b}.bg-danger{background-color:#e74c3c}a.bg-danger:hover{background-color:#d62c1a}.page-header{padding-bottom:10px;margin:44px 0 22px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:11px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none;margin-left:-5px}.list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}dl{margin-top:0;margin-bottom:22px}dt,dd{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:480px){.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:11px 22px;margin:0 0 22px;font-size:20px;border-left:5px solid #eee}blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child{margin-bottom:0}blockquote footer,blockquote small,blockquote .small{display:block;font-size:80%;line-height:1.42857143;color:#999}blockquote footer:before,blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before{content:''}.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}blockquote:before,blockquote:after{content:""}address{margin-bottom:22px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;white-space:nowrap;border-radius:3px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:0;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}pre{display:block;padding:10.5px;margin:0 0 11px;font-size:15px;line-height:1.42857143;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:3px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.row{margin-left:-15px;margin-right:-15px}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:0}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:0}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:0}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:0}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:0}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:0}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:0}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:0}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:22px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:3px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*=col-]{position:static;float:none;display:table-column}table td[class*=col-],table th[class*=col-]{position:static;float:none;display:table-cell}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th{background-color:#e8e8e8}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#2ecc71}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th{background-color:#29b765}.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th{background-color:#9b59b6}.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th{background-color:#8f4bab}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#f1c40f}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th{background-color:#dab10d}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#e74c3c}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th{background-color:#e43725}@media (max-width:767px){.table-responsive{width:100%;margin-bottom:16.5px;overflow-y:hidden;overflow-x:scroll;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd;-webkit-overflow-scrolling:touch}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0;min-width:0}legend{display:block;width:100%;padding:0;margin-bottom:22px;font-size:24px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=radio],input[type=checkbox]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=radio]:focus,input[type=checkbox]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:16px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:36px;padding:6px 12px;font-size:16px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}input[type=date]{line-height:36px}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:22px;margin-top:10px;margin-bottom:10px;padding-left:20px}.radio label,.checkbox label{display:inline;font-weight:400;cursor:pointer}.radio input[type=radio],.radio-inline input[type=radio],.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type=radio][disabled],input[type=checkbox][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type=radio],fieldset[disabled] input[type=checkbox],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:33px;padding:5px 10px;font-size:14px;line-height:1.5;border-radius:0}select.input-sm{height:33px;line-height:33px}textarea.input-sm,select[multiple].input-sm{height:auto}.input-lg{height:49px;padding:10px 16px;font-size:20px;line-height:1.33;border-radius:3px}select.input-lg{height:49px;line-height:49px}textarea.input-lg,select[multiple].input-lg{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:45px}.has-feedback .form-control-feedback{position:absolute;top:27px;right:0;display:block;width:36px;height:36px;line-height:36px;text-align:center}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#29b74e}.has-success .form-control{border-color:#29b74e;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#208e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #69dd87;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #69dd87}.has-success .input-group-addon{color:#29b74e;border-color:#29b74e;background-color:#2ecc71}.has-success .form-control-feedback{color:#29b74e}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#da8f0d}.has-warning .form-control{border-color:#da8f0d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#aa6f0a;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #f5bb57;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #f5bb57}.has-warning .input-group-addon{color:#da8f0d;border-color:#da8f0d;background-color:#f1c40f}.has-warning .form-control-feedback{color:#da8f0d}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#e42533}.has-error .form-control{border-color:#e42533;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#bf1824;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ef8088;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ef8088}.has-error .input-group-addon{color:#e42533;border-color:#e42533;background-color:#e74c3c}.has-error .form-control-feedback{color:#e42533}.form-control-static{margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;padding-left:0;vertical-align:middle}.form-inline .radio input[type=radio],.form-inline .checkbox input[type=checkbox]{float:none;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:29px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-control-static{padding-top:7px}@media (min-width:768px){.form-horizontal .control-label{text-align:right}}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 12px;font-size:16px;line-height:1.42857143;border-radius:3px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#3498db;border-color:#258cd1}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#2383c4;border-color:#1c699d}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#3498db;border-color:#258cd1}.btn-primary .badge{color:#3498db;background-color:#fff}.btn-success{color:#fff;background-color:#2ecc71;border-color:#29b765}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#26ab5f;border-color:#1e854a}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#2ecc71;border-color:#29b765}.btn-success .badge{color:#2ecc71;background-color:#fff}.btn-info{color:#fff;background-color:#9b59b6;border-color:#8f4bab}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#8646a0;border-color:#6b3880}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#9b59b6;border-color:#8f4bab}.btn-info .badge{color:#9b59b6;background-color:#fff}.btn-warning{color:#fff;background-color:#f1c40f;border-color:#dab10d}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#cba50c;border-color:#a08209}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f1c40f;border-color:#dab10d}.btn-warning .badge{color:#f1c40f;background-color:#fff}.btn-danger{color:#fff;background-color:#e74c3c;border-color:#e43725}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#df2e1b;border-color:#b62516}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#e74c3c;border-color:#e43725}.btn-danger .badge{color:#e74c3c;background-color:#fff}.btn-link{color:#3498db;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#1d6fa5;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg,.btn-group-lg>.btn{padding:10px 16px;font-size:20px;line-height:1.33;border-radius:3px}.btn-sm,.btn-group-sm>.btn{padding:5px 10px;font-size:14px;line-height:1.5;border-radius:0}.btn-xs,.btn-group-xs>.btn{padding:1px 5px;font-size:14px;line-height:1.5;border-radius:0}.btn-block{display:block;width:100%;padding-left:0;padding-right:0}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;font-size:16px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:3px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:10px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{text-decoration:none;color:#262626;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;outline:0;background-color:#3498db}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);cursor:not-allowed}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{left:auto;right:0}.dropdown-menu-left{left:0;right:auto}.dropdown-header{display:block;padding:3px 20px;font-size:14px;line-height:1.42857143;color:#999}.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:480px){.navbar-right .dropdown-menu{left:auto;right:0}.navbar-right .dropdown-menu-left{left:0;right:auto}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-left:12px;padding-right:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:3px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-bottom-left-radius:3px;border-top-right-radius:0;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.btn-group-justified>.btn-group .btn{width:100%}[data-toggle=buttons]>.btn>input[type=radio],[data-toggle=buttons]>.btn>input[type=checkbox]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:49px;padding:10px 16px;font-size:20px;line-height:1.33;border-radius:3px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:49px;line-height:49px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn,select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:33px;padding:5px 10px;font-size:14px;line-height:1.5;border-radius:0}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:33px;line-height:33px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn,select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:16px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:3px}.input-group-addon.input-sm{padding:5px 10px;font-size:14px;border-radius:0}.input-group-addon.input-lg{padding:10px 16px;font-size:20px;border-radius:3px}.input-group-addon input[type=radio],.input-group-addon input[type=checkbox]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{margin-bottom:0;padding-left:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;background-color:transparent;cursor:not-allowed}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#3498db}.nav .nav-divider{height:1px;margin:10px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:3px 3px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:3px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:3px 3px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:3px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#3498db}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:3px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:3px 3px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:22px;border:1px solid transparent}@media (min-width:480px){.navbar{border-radius:3px}}@media (min-width:480px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,.1);-webkit-overflow-scrolling:touch}.navbar-collapse.in{overflow-y:auto}@media (min-width:480px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-left:0;padding-right:0}}.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media (min-width:480px){.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:480px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030}@media (min-width:480px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;padding:14px 15px;font-size:20px;line-height:22px;height:50px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media (min-width:480px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:3px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:480px){.navbar-toggle{display:none}}.navbar-nav{margin:7px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:22px}@media (max-width:479px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:22px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media (min-width:480px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:14px;padding-bottom:14px}.navbar-nav.navbar-right:last-child{margin-right:-15px}}@media (min-width:480px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{margin-left:-15px;margin-right:-15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);margin-top:7px;margin-bottom:7px}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;margin-top:0;margin-bottom:0;padding-left:0;vertical-align:middle}.navbar-form .radio input[type=radio],.navbar-form .checkbox input[type=checkbox]{float:none;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:479px){.navbar-form .form-group{margin-bottom:5px}}@media (min-width:480px){.navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;-webkit-box-shadow:none;box-shadow:none}.navbar-form.navbar-right:last-child{margin-right:-15px}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:7px;margin-bottom:7px}.navbar-btn.btn-sm{margin-top:8.5px;margin-bottom:8.5px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:14px;margin-bottom:14px}@media (min-width:480px){.navbar-text{float:left;margin-left:15px;margin-right:15px}.navbar-text.navbar-right:last-child{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#555}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#3b3b3b;background-color:transparent}.navbar-default .navbar-text{color:#555}.navbar-default .navbar-nav>li>a{color:#555}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{background-color:#e7e7e7;color:#555}@media (max-width:479px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#555}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#555}.navbar-default .navbar-link:hover{color:#333}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{background-color:#080808;color:#fff}@media (max-width:479px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#999}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:22px;list-style:none;background-color:#f5f5f5;border-radius:3px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{content:"/\00a0";padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:22px 0;border-radius:3px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.42857143;text-decoration:none;color:#3498db;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{color:#1d6fa5;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#3498db;border-color:#3498db;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:20px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:14px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:0;border-top-left-radius:0}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:0;border-top-right-radius:0}.pager{padding-left:0;margin:22px 0;list-style:none;text-align:center}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;background-color:#fff;cursor:not-allowed}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:gray}.label-primary{background-color:#3498db}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#217dbb}.label-success{background-color:#2ecc71}.label-success[href]:hover,.label-success[href]:focus{background-color:#25a25a}.label-info{background-color:#9b59b6}.label-info[href]:hover,.label-info[href]:focus{background-color:#804399}.label-warning{background-color:#f1c40f}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#c29d0b}.label-danger{background-color:#e74c3c}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#d62c1a}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:14px;font-weight:700;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#999;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#3498db;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:24px;font-weight:200}.container .jumbotron{border-radius:3px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-left:60px;padding-right:60px}.jumbotron h1,.jumbotron .h1{font-size:72px}}.thumbnail{display:block;padding:4px;margin-bottom:22px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:3px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img,.thumbnail a>img{margin-left:auto;margin-right:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#3498db}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:22px;border:1px solid transparent;border-radius:3px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{background-color:#2ecc71;border-color:#29b74e;color:#fff}.alert-success hr{border-top-color:#25a245}.alert-success .alert-link{color:#e6e6e6}.alert-info{background-color:#9b59b6;border-color:#7f4bab;color:#fff}.alert-info hr{border-top-color:#724399}.alert-info .alert-link{color:#e6e6e6}.alert-warning{background-color:#f1c40f;border-color:#da8f0d;color:#fff}.alert-warning hr{border-top-color:#c27f0b}.alert-warning .alert-link{color:#e6e6e6}.alert-danger{background-color:#e74c3c;border-color:#e42533;color:#fff}.alert-danger hr{border-top-color:#d61a28}.alert-danger .alert-link{color:#e6e6e6}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{overflow:hidden;height:22px;margin-bottom:22px;background-color:#f5f5f5;border-radius:3px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:14px;line-height:22px;color:#fff;text-align:center;background-color:#3498db;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#2ecc71}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#9b59b6}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f1c40f}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#e74c3c}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{margin-bottom:20px;padding-left:0}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active,a.list-group-item.active:hover,a.list-group-item.active:focus{z-index:2;color:#fff;background-color:#3498db;border-color:#3498db}a.list-group-item.active .list-group-item-heading,a.list-group-item.active:hover .list-group-item-heading,a.list-group-item.active:focus .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text,a.list-group-item.active:hover .list-group-item-text,a.list-group-item.active:focus .list-group-item-text{color:#e1f0fa}.list-group-item-success{color:#29b74e;background-color:#2ecc71}a.list-group-item-success{color:#29b74e}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:hover,a.list-group-item-success:focus{color:#29b74e;background-color:#29b765}a.list-group-item-success.active,a.list-group-item-success.active:hover,a.list-group-item-success.active:focus{color:#fff;background-color:#29b74e;border-color:#29b74e}.list-group-item-info{color:#7f4bab;background-color:#9b59b6}a.list-group-item-info{color:#7f4bab}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:hover,a.list-group-item-info:focus{color:#7f4bab;background-color:#8f4bab}a.list-group-item-info.active,a.list-group-item-info.active:hover,a.list-group-item-info.active:focus{color:#fff;background-color:#7f4bab;border-color:#7f4bab}.list-group-item-warning{color:#da8f0d;background-color:#f1c40f}a.list-group-item-warning{color:#da8f0d}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:hover,a.list-group-item-warning:focus{color:#da8f0d;background-color:#dab10d}a.list-group-item-warning.active,a.list-group-item-warning.active:hover,a.list-group-item-warning.active:focus{color:#fff;background-color:#da8f0d;border-color:#da8f0d}.list-group-item-danger{color:#e42533;background-color:#e74c3c}a.list-group-item-danger{color:#e42533}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:hover,a.list-group-item-danger:focus{color:#e42533;background-color:#e43725}a.list-group-item-danger.active,a.list-group-item-danger.active:hover,a.list-group-item-danger.active:focus{color:#fff;background-color:#e42533;border-color:#e42533}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:22px;background-color:#fff;border:1px solid transparent;border-radius:3px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:2px;border-top-left-radius:2px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:18px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:2px;border-bottom-left-radius:2px}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:2px;border-top-left-radius:2px}.panel>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:2px;border-bottom-left-radius:2px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.table:first-child,.panel>.table-responsive:first-child>.table:first-child{border-top-right-radius:2px;border-top-left-radius:2px}.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child{border-top-left-radius:2px}.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child{border-top-right-radius:2px}.panel>.table:last-child,.panel>.table-responsive:last-child>.table:last-child{border-bottom-right-radius:2px;border-bottom-left-radius:2px}.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:2px}.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:2px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child th,.panel>.table>tbody:first-child>tr:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{border:0;margin-bottom:0}.panel-group{margin-bottom:22px}.panel-group .panel{margin-bottom:0;border-radius:3px;overflow:hidden}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#3498db}.panel-primary>.panel-heading{color:#fff;background-color:#3498db;border-color:#3498db}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#3498db}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#3498db}.panel-success{border-color:#29b74e}.panel-success>.panel-heading{color:#fff;background-color:#2ecc71;border-color:#29b74e}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#29b74e}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#29b74e}.panel-info{border-color:#7f4bab}.panel-info>.panel-heading{color:#fff;background-color:#9b59b6;border-color:#7f4bab}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#7f4bab}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#7f4bab}.panel-warning{border-color:#da8f0d}.panel-warning>.panel-heading{color:#fff;background-color:#f1c40f;border-color:#da8f0d}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#da8f0d}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#da8f0d}.panel-danger{border-color:#e42533}.panel-danger>.panel-heading{color:#fff;background-color:#e74c3c;border-color:#e42533}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#e42533}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#e42533}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:3px}.well-sm{padding:9px;border-radius:0}.close{float:right;font-size:24px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal{display:none;overflow:auto;overflow-y:scroll;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:3px;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.42857143px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:20px}.modal-footer{margin-top:15px;padding:19px 20px 20px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;font-size:14px;line-height:1.4;opacity:0;filter:alpha(opacity=0)}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{margin-top:-3px;padding:5px 0}.tooltip.right{margin-left:3px;padding:0 5px}.tooltip.bottom{margin-top:3px;padding:5px 0}.tooltip.left{margin-left:-3px;padding:0 5px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:3px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;right:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:3px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);white-space:normal}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{margin:0;padding:8px 14px;font-size:16px;font-weight:400;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{border-width:10px;content:""}.popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.carousel{position:relative}.carousel-inner{position:relative;overflow:hidden;width:100%}.carousel-inner>.item{display:none;position:relative;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-control.left{background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,.5) 0),color-stop(rgba(0,0,0,.0001) 100%));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1)}.carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,.0001) 0),color-stop(rgba(0,0,0,.5) 100%));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1)}.carousel-control:hover,.carousel-control:focus{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0)}.carousel-indicators .active{margin:0;width:12px;height:12px;background-color:#fff}.carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{left:20%;right:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after,.container:before,.container:after,.container-fluid:before,.container-fluid:after,.row:before,.row:after,.form-horizontal .form-group:before,.form-horizontal .form-group:after,.btn-toolbar:before,.btn-toolbar:after,.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after,.nav:before,.nav:after,.navbar:before,.navbar:after,.navbar-header:before,.navbar-header:after,.navbar-collapse:before,.navbar-collapse:after,.pager:before,.pager:after,.panel-body:before,.panel-body:after,.modal-footer:before,.modal-footer:after{content:" ";display:table}.clearfix:after,.container:after,.container-fluid:after,.row:after,.form-horizontal .form-group:after,.btn-toolbar:after,.btn-group-vertical>.btn-group:after,.nav:after,.navbar:after,.navbar-header:after,.navbar-collapse:after,.pager:after,.panel-body:after,.modal-footer:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-xs,.visible-sm,.visible-md,.visible-lg{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}}@media print{.hidden-print{display:none!important}}
cmd/ursrv/static/bootstrap/css/bootstrap.min.css
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.00016973995661828667, 0.00016973995661828667, 0.00016973995661828667, 0.00016973995661828667, 0 ]
{ "id": 2, "code_window": [ "\tfor _, folderStr := range db.ListFolders() {\n", "\t\tfolder := []byte(folderStr)\n", "\t\tvar putErr error\n", "\t\terr := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool {\n", "\t\t\tf := fi.(FileInfoTruncated)\n", "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil {\n", "\t\t\t\treturn true\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif f.IsDirectory() || f.IsDeleted() || f.IsSymlink() || f.IsInvalid() || f.BlocksHash == nil {\n" ], "file_path": "lib/db/schemaupdater.go", "type": "replace", "edit_start_line_idx": 592 }
// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. // +build !noupgrade package upgrade import ( "fmt" "runtime" "strings" "testing" ) var versions = []struct { a, b string r Relation }{ {"0.1.2", "0.1.2", Equal}, {"0.1.3", "0.1.2", Newer}, {"0.1.1", "0.1.2", Older}, {"0.3.0", "0.1.2", Newer}, {"0.0.9", "0.1.2", Older}, {"1.3.0", "1.1.2", Newer}, {"1.0.9", "1.1.2", Older}, {"2.3.0", "1.1.2", MajorNewer}, {"1.0.9", "2.1.2", MajorOlder}, {"1.1.2", "0.1.2", Newer}, {"0.1.2", "1.1.2", Older}, {"2.1.2", "0.1.2", MajorNewer}, {"0.1.2", "2.1.2", MajorOlder}, {"0.1.10", "0.1.9", Newer}, {"0.10.0", "0.2.0", Newer}, {"30.10.0", "4.9.0", MajorNewer}, {"0.9.0-beta7", "0.9.0-beta6", Newer}, {"0.9.0-beta7", "1.0.0-alpha", Older}, {"1.0.0-alpha", "1.0.0-alpha.1", Older}, {"1.0.0-alpha.1", "1.0.0-alpha.beta", Older}, {"1.0.0-alpha.beta", "1.0.0-beta", Older}, {"1.0.0-beta", "1.0.0-beta.2", Older}, {"1.0.0-beta.2", "1.0.0-beta.11", Older}, {"1.0.0-beta.11", "1.0.0-rc.1", Older}, {"1.0.0-rc.1", "1.0.0", Older}, {"1.0.0+45", "1.0.0+23-dev-foo", Equal}, {"1.0.0-beta.23+45", "1.0.0-beta.23+23-dev-foo", Equal}, {"1.0.0-beta.3+99", "1.0.0-beta.24+0", Older}, {"v1.1.2", "1.1.2", Equal}, {"v1.1.2", "V1.1.2", Equal}, {"1.1.2", "V1.1.2", Equal}, } func TestCompareVersions(t *testing.T) { for _, v := range versions { if r := CompareVersions(v.a, v.b); r != v.r { t.Errorf("compareVersions(%q, %q): %d != %d", v.a, v.b, r, v.r) } } } func TestErrorRelease(t *testing.T) { _, err := SelectLatestRelease(nil, "v0.11.0-beta", false) if err == nil { t.Error("Should return an error when no release were available") } } func TestSelectedRelease(t *testing.T) { testcases := []struct { current string upgradeToPre bool candidates []string selected string }{ // Within the same "major" (minor, in this case) select the newest {"v0.12.24", false, []string{"v0.12.23", "v0.12.24", "v0.12.25", "v0.12.26"}, "v0.12.26"}, {"v0.12.24", false, []string{"v0.12.23", "v0.12.24", "v0.12.25", "v0.13.0"}, "v0.13.0"}, {"v0.12.24", false, []string{"v0.12.23", "v0.12.24", "v0.12.25", "v1.0.0"}, "v1.0.0"}, // Do no select beta versions when we are not allowed to {"v0.12.24", false, []string{"v0.12.26", "v0.12.27-beta.42"}, "v0.12.26"}, {"v0.12.24-beta.0", false, []string{"v0.12.26", "v0.12.27-beta.42"}, "v0.12.26"}, // Do select beta versions when we can {"v0.12.24", true, []string{"v0.12.26", "v0.12.27-beta.42"}, "v0.12.27-beta.42"}, {"v0.12.24-beta.0", true, []string{"v0.12.26", "v0.12.27-beta.42"}, "v0.12.27-beta.42"}, // Select the best within the current major when there is a minor upgrade available {"v0.12.24", false, []string{"v1.12.23", "v1.12.24", "v1.14.2", "v2.0.0"}, "v1.14.2"}, {"v1.12.24", false, []string{"v1.12.23", "v1.12.24", "v1.14.2", "v2.0.0"}, "v1.14.2"}, // Select the next major when we are at the best minor {"v0.12.25", true, []string{"v0.12.23", "v0.12.24", "v0.12.25", "v0.13.0"}, "v0.13.0"}, {"v1.14.2", true, []string{"v0.12.23", "v0.12.24", "v1.14.2", "v2.0.0"}, "v2.0.0"}, } for i, tc := range testcases { // Prepare a list of candidate releases var rels []Release for _, c := range tc.candidates { rels = append(rels, Release{ Tag: c, Prerelease: strings.Contains(c, "-"), Assets: []Asset{ // There must be a matching asset or it will not get selected {Name: releaseNames(c)[0]}, }, }) } // Check the selection sel, err := SelectLatestRelease(rels, tc.current, tc.upgradeToPre) if err != nil { t.Fatal("Unexpected error:", err) } if sel.Tag != tc.selected { t.Errorf("Test case %d: expected %s to be selected, but got %s", i, tc.selected, sel.Tag) } } } func TestSelectedReleaseMacOS(t *testing.T) { if runtime.GOOS != "darwin" { t.Skip("macOS only") } // The alternatives that we expect should work assetNames := []string{ fmt.Sprintf("syncthing-macos-%s-v0.14.47.tar.gz", runtime.GOARCH), fmt.Sprintf("syncthing-macosx-%s-v0.14.47.tar.gz", runtime.GOARCH), } for _, assetName := range assetNames { // Provide one release with the given asset name rels := []Release{ { Tag: "v0.14.47", Prerelease: false, Assets: []Asset{ {Name: assetName}, }, }, } // Check that it is selected and the asset is as epected sel, err := SelectLatestRelease(rels, "v0.14.46", false) if err != nil { t.Fatal("Unexpected error:", err) } if sel.Tag != "v0.14.47" { t.Error("wrong tag selected:", sel.Tag) } if sel.Assets[0].Name != assetName { t.Error("wrong asset selected:", sel.Assets[0].Name) } } }
lib/upgrade/upgrade_test.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0005064758588559926, 0.00020589662017300725, 0.00016652078193146735, 0.00017283353372476995, 0.0000845125105115585 ]
{ "id": 3, "code_window": [ "\treturn nil\n", "}\n", "\n", "func (f *folder) findRename(snap *db.Snapshot, mtimefs fs.Filesystem, file protocol.FileInfo) (protocol.FileInfo, bool) {\n", "\tfound := false\n", "\tnf := protocol.FileInfo{}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tif len(file.Blocks) == 0 {\n", "\t\treturn protocol.FileInfo{}, false\n", "\t}\n", "\n" ], "file_path": "lib/model/folder.go", "type": "add", "edit_start_line_idx": 625 }
// Copyright (C) 2018 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package db import ( "fmt" "strings" "github.com/syncthing/syncthing/lib/db/backend" "github.com/syncthing/syncthing/lib/protocol" ) // List of all dbVersion to dbMinSyncthingVersion pairs for convenience // 0: v0.14.0 // 1: v0.14.46 // 2: v0.14.48 // 3-5: v0.14.49 // 6: v0.14.50 // 7: v0.14.53 // 8-9: v1.4.0 // 10-11: v1.6.0 // 12: v1.7.0 const ( dbVersion = 12 dbMinSyncthingVersion = "v1.7.0" ) type databaseDowngradeError struct { minSyncthingVersion string } func (e databaseDowngradeError) Error() string { if e.minSyncthingVersion == "" { return "newer Syncthing required" } return fmt.Sprintf("Syncthing %s required", e.minSyncthingVersion) } func UpdateSchema(db *Lowlevel) error { updater := &schemaUpdater{db} return updater.updateSchema() } type schemaUpdater struct { *Lowlevel } func (db *schemaUpdater) updateSchema() error { // Updating the schema can touch any and all parts of the database. Make // sure we do not run GC concurrently with schema migrations. db.gcMut.Lock() defer db.gcMut.Unlock() miscDB := NewMiscDataNamespace(db.Lowlevel) prevVersion, _, err := miscDB.Int64("dbVersion") if err != nil { return err } if prevVersion > dbVersion { err := databaseDowngradeError{} if minSyncthingVersion, ok, dbErr := miscDB.String("dbMinSyncthingVersion"); dbErr != nil { return dbErr } else if ok { err.minSyncthingVersion = minSyncthingVersion } return err } if prevVersion == dbVersion { return nil } type migration struct { schemaVersion int64 migration func(prevVersion int) error } var migrations = []migration{ {1, db.updateSchema0to1}, {2, db.updateSchema1to2}, {3, db.updateSchema2to3}, {5, db.updateSchemaTo5}, {6, db.updateSchema5to6}, {7, db.updateSchema6to7}, {9, db.updateSchemaTo9}, {10, db.updateSchemaTo10}, {11, db.updateSchemaTo11}, {12, db.updateSchemaTo12}, } for _, m := range migrations { if prevVersion < m.schemaVersion { l.Infof("Migrating database to schema version %d...", m.schemaVersion) if err := m.migration(int(prevVersion)); err != nil { return err } } } if err := miscDB.PutInt64("dbVersion", dbVersion); err != nil { return err } if err := miscDB.PutString("dbMinSyncthingVersion", dbMinSyncthingVersion); err != nil { return err } l.Infoln("Compacting database after migration...") return db.Compact() } func (db *schemaUpdater) updateSchema0to1(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() dbi, err := t.NewPrefixIterator([]byte{KeyTypeDevice}) if err != nil { return err } defer dbi.Release() symlinkConv := 0 changedFolders := make(map[string]struct{}) ignAdded := 0 meta := newMetadataTracker() // dummy metadata tracker var gk, buf []byte for dbi.Next() { folder, ok := db.keyer.FolderFromDeviceFileKey(dbi.Key()) if !ok { // not having the folder in the index is bad; delete and continue if err := t.Delete(dbi.Key()); err != nil { return err } continue } device, ok := db.keyer.DeviceFromDeviceFileKey(dbi.Key()) if !ok { // not having the device in the index is bad; delete and continue if err := t.Delete(dbi.Key()); err != nil { return err } continue } name := db.keyer.NameFromDeviceFileKey(dbi.Key()) // Remove files with absolute path (see #4799) if strings.HasPrefix(string(name), "/") { if _, ok := changedFolders[string(folder)]; !ok { changedFolders[string(folder)] = struct{}{} } gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } // Purposely pass nil file name to remove from global list, // but don't touch meta and needs buf, err = t.removeFromGlobal(gk, buf, folder, device, nil, nil) if err != nil && err != errEntryFromGlobalMissing { return err } if err := t.Delete(dbi.Key()); err != nil { return err } continue } // Change SYMLINK_FILE and SYMLINK_DIRECTORY types to the current SYMLINK // type (previously SYMLINK_UNKNOWN). It does this for all devices, both // local and remote, and does not reset delta indexes. It shouldn't really // matter what the symlink type is, but this cleans it up for a possible // future when SYMLINK_FILE and SYMLINK_DIRECTORY are no longer understood. var f protocol.FileInfo if err := f.Unmarshal(dbi.Value()); err != nil { // probably can't happen continue } if f.Type == protocol.FileInfoTypeDeprecatedSymlinkDirectory || f.Type == protocol.FileInfoTypeDeprecatedSymlinkFile { f.Type = protocol.FileInfoTypeSymlink bs, err := f.Marshal() if err != nil { panic("can't happen: " + err.Error()) } if err := t.Put(dbi.Key(), bs); err != nil { return err } symlinkConv++ } // Add invalid files to global list if f.IsInvalid() { gk, err = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if err != nil { return err } if buf, ok, err = t.updateGlobal(gk, buf, folder, device, f, meta); err != nil { return err } else if ok { if _, ok = changedFolders[string(folder)]; !ok { changedFolders[string(folder)] = struct{}{} } ignAdded++ } } if err := t.Checkpoint(); err != nil { return err } } for folder := range changedFolders { if err := db.dropFolderMeta([]byte(folder)); err != nil { return err } } return t.Commit() } // updateSchema1to2 introduces a sequenceKey->deviceKey bucket for local items // to allow iteration in sequence order (simplifies sending indexes). func (db *schemaUpdater) updateSchema1to2(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var sk []byte var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var putErr error err := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(f FileIntf) bool { sk, putErr = db.keyer.GenerateSequenceKey(sk, folder, f.SequenceNo()) if putErr != nil { return false } dk, putErr = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], []byte(f.FileName())) if putErr != nil { return false } putErr = t.Put(sk, dk) return putErr == nil }) if putErr != nil { return putErr } if err != nil { return err } } return t.Commit() } // updateSchema2to3 introduces a needKey->nil bucket for locally needed files. func (db *schemaUpdater) updateSchema2to3(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var nk []byte var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var putErr error err := t.withGlobal(folder, nil, true, func(f FileIntf) bool { name := []byte(f.FileName()) dk, putErr = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], name) if putErr != nil { return false } var v protocol.Vector haveFile, ok, err := t.getFileTrunc(dk, true) if err != nil { putErr = err return false } if ok { v = haveFile.FileVersion() } fv := FileVersion{ Version: f.FileVersion(), Invalid: f.IsInvalid(), Deleted: f.IsDeleted(), } if !need(fv, ok, v) { return true } nk, putErr = t.keyer.GenerateNeedFileKey(nk, folder, []byte(f.FileName())) if putErr != nil { return false } putErr = t.Put(nk, nil) return putErr == nil }) if putErr != nil { return putErr } if err != nil { return err } } return t.Commit() } // updateSchemaTo5 resets the need bucket due to bugs existing in the v0.14.49 // release candidates (dbVersion 3 and 4) // https://github.com/syncthing/syncthing/issues/5007 // https://github.com/syncthing/syncthing/issues/5053 func (db *schemaUpdater) updateSchemaTo5(prevVersion int) error { if prevVersion != 3 && prevVersion != 4 { return nil } t, err := db.newReadWriteTransaction() if err != nil { return err } var nk []byte for _, folderStr := range db.ListFolders() { nk, err = db.keyer.GenerateNeedFileKey(nk, []byte(folderStr), nil) if err != nil { return err } if err := t.deleteKeyPrefix(nk[:keyPrefixLen+keyFolderLen]); err != nil { return err } } if err := t.Commit(); err != nil { return err } return db.updateSchema2to3(2) } func (db *schemaUpdater) updateSchema5to6(_ int) error { // For every local file with the Invalid bit set, clear the Invalid bit and // set LocalFlags = FlagLocalIgnored. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var iterErr error err := t.withHave(folder, protocol.LocalDeviceID[:], nil, false, func(f FileIntf) bool { if !f.IsInvalid() { return true } fi := f.(protocol.FileInfo) fi.RawInvalid = false fi.LocalFlags = protocol.FlagLocalIgnored bs, _ := fi.Marshal() dk, iterErr = db.keyer.GenerateDeviceFileKey(dk, folder, protocol.LocalDeviceID[:], []byte(fi.Name)) if iterErr != nil { return false } if iterErr = t.Put(dk, bs); iterErr != nil { return false } iterErr = t.Checkpoint() return iterErr == nil }) if iterErr != nil { return iterErr } if err != nil { return err } } return t.Commit() } // updateSchema6to7 checks whether all currently locally needed files are really // needed and removes them if not. func (db *schemaUpdater) updateSchema6to7(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var gk []byte var nk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var delErr error err := t.withNeedLocal(folder, false, func(f FileIntf) bool { name := []byte(f.FileName()) gk, delErr = db.keyer.GenerateGlobalVersionKey(gk, folder, name) if delErr != nil { return false } svl, err := t.Get(gk) if err != nil { // If there is no global list, we hardly need it. key, err := t.keyer.GenerateNeedFileKey(nk, folder, name) if err != nil { delErr = err return false } delErr = t.Delete(key) return delErr == nil } var fl VersionList err = fl.Unmarshal(svl) if err != nil { // This can't happen, but it's ignored everywhere else too, // so lets not act on it. return true } globalFV := FileVersion{ Version: f.FileVersion(), Invalid: f.IsInvalid(), Deleted: f.IsDeleted(), } if localFV, haveLocalFV := fl.Get(protocol.LocalDeviceID[:]); !need(globalFV, haveLocalFV, localFV.Version) { key, err := t.keyer.GenerateNeedFileKey(nk, folder, name) if err != nil { delErr = err return false } delErr = t.Delete(key) } return delErr == nil }) if delErr != nil { return delErr } if err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } return t.Commit() } func (db *schemaUpdater) updateSchemaTo9(prev int) error { // Loads and rewrites all files with blocks, to deduplicate block lists. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() if err := db.rewriteFiles(t); err != nil { return err } db.recordTime(indirectGCTimeKey) return t.Commit() } func (db *schemaUpdater) rewriteFiles(t readWriteTransaction) error { it, err := t.NewPrefixIterator([]byte{KeyTypeDevice}) if err != nil { return err } for it.Next() { intf, err := t.unmarshalTrunc(it.Value(), false) if backend.IsNotFound(err) { // Unmarshal error due to missing parts (block list), probably // due to a bad migration in a previous RC. Drop this key, as // getFile would anyway return this as a "not found" in the // normal flow of things. if err := t.Delete(it.Key()); err != nil { return err } continue } else if err != nil { return err } fi := intf.(protocol.FileInfo) if fi.Blocks == nil { continue } if err := t.putFile(it.Key(), fi, false); err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } it.Release() return it.Error() } func (db *schemaUpdater) updateSchemaTo10(_ int) error { t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var buf []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) buf, err = t.keyer.GenerateGlobalVersionKey(buf, folder, nil) if err != nil { return err } buf = globalVersionKey(buf).WithoutName() dbi, err := t.NewPrefixIterator(buf) if err != nil { return err } defer dbi.Release() for dbi.Next() { var vl VersionList if err := vl.Unmarshal(dbi.Value()); err != nil { return err } changed := false name := t.keyer.NameFromGlobalVersionKey(dbi.Key()) for i, fv := range vl.Versions { buf, err = t.keyer.GenerateDeviceFileKey(buf, folder, fv.Device, name) if err != nil { return err } f, ok, err := t.getFileTrunc(buf, true) if !ok { return errEntryFromGlobalMissing } if err != nil { return err } if f.IsDeleted() { vl.Versions[i].Deleted = true changed = true } } if changed { if err := t.Put(dbi.Key(), mustMarshal(&vl)); err != nil { return err } if err := t.Checkpoint(); err != nil { return err } } } dbi.Release() } // Trigger metadata recalc if err := t.deleteKeyPrefix([]byte{KeyTypeFolderMeta}); err != nil { return err } return t.Commit() } func (db *schemaUpdater) updateSchemaTo11(_ int) error { // Populates block list map for every folder. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() var dk []byte for _, folderStr := range db.ListFolders() { folder := []byte(folderStr) var putErr error err := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool { f := fi.(FileInfoTruncated) if f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil { return true } name := []byte(f.FileName()) dk, putErr = db.keyer.GenerateBlockListMapKey(dk, folder, f.BlocksHash, name) if putErr != nil { return false } if putErr = t.Put(dk, nil); putErr != nil { return false } putErr = t.Checkpoint() return putErr == nil }) if putErr != nil { return putErr } if err != nil { return err } } return t.Commit() } func (db *schemaUpdater) updateSchemaTo12(_ int) error { // Loads and rewrites all files, to deduplicate version vectors. t, err := db.newReadWriteTransaction() if err != nil { return err } defer t.close() if err := db.rewriteFiles(t); err != nil { return err } return t.Commit() }
lib/db/schemaupdater.go
1
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.9944144487380981, 0.1383938193321228, 0.00016277814575005323, 0.0004343902110122144, 0.3197478950023651 ]
{ "id": 3, "code_window": [ "\treturn nil\n", "}\n", "\n", "func (f *folder) findRename(snap *db.Snapshot, mtimefs fs.Filesystem, file protocol.FileInfo) (protocol.FileInfo, bool) {\n", "\tfound := false\n", "\tnf := protocol.FileInfo{}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tif len(file.Blocks) == 0 {\n", "\t\treturn protocol.FileInfo{}, false\n", "\t}\n", "\n" ], "file_path": "lib/model/folder.go", "type": "add", "edit_start_line_idx": 625 }
<modal id="upgrade" status="warning" icon="fas fa-arrow-circle-up" heading="{{'Upgrade' | translate}}" large="no" closeable="yes"> <div class="modal-body"> <p> <span translate>Are you sure you want to upgrade?</span> </p> <p> <a ng-href="https://github.com/syncthing/syncthing/releases/tag/{{upgradeInfo.latest}}" target="_blank" translate>Release Notes</a> </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary btn-sm" ng-click="upgrade()"> <span class="fas fa-check"></span>&nbsp;<span translate>Upgrade</span> </button> <button type="button" class="btn btn-default btn-sm" data-dismiss="modal"> <span class="fas fa-times"></span>&nbsp;<span translate>Close</span> </button> </div> </modal>
gui/default/syncthing/core/upgradeModalView.html
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0001686488976702094, 0.0001675188832450658, 0.00016638888337183744, 0.0001675188832450658, 0.0000011300071491859853 ]
{ "id": 3, "code_window": [ "\treturn nil\n", "}\n", "\n", "func (f *folder) findRename(snap *db.Snapshot, mtimefs fs.Filesystem, file protocol.FileInfo) (protocol.FileInfo, bool) {\n", "\tfound := false\n", "\tnf := protocol.FileInfo{}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tif len(file.Blocks) == 0 {\n", "\t\treturn protocol.FileInfo{}, false\n", "\t}\n", "\n" ], "file_path": "lib/model/folder.go", "type": "add", "edit_start_line_idx": 625 }
// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package ignore import ( "testing" "time" ) func TestCache(t *testing.T) { fc := new(fakeClock) oldClock := clock clock = fc defer func() { clock = oldClock }() c := newCache(nil) res, ok := c.get("nonexistent") if res.IsIgnored() || res.IsDeletable() || ok { t.Errorf("res %v, ok %v for nonexistent item", res, ok) } // Set and check some items c.set("true", resultInclude|resultDeletable) c.set("false", 0) res, ok = c.get("true") if !res.IsIgnored() || !res.IsDeletable() || !ok { t.Errorf("res %v, ok %v for true item", res, ok) } res, ok = c.get("false") if res.IsIgnored() || res.IsDeletable() || !ok { t.Errorf("res %v, ok %v for false item", res, ok) } // Don't clean anything c.clean(time.Second) // Same values should exist res, ok = c.get("true") if !res.IsIgnored() || !res.IsDeletable() || !ok { t.Errorf("res %v, ok %v for true item", res, ok) } res, ok = c.get("false") if res.IsIgnored() || res.IsDeletable() || !ok { t.Errorf("res %v, ok %v for false item", res, ok) } // Sleep and access, to get some data for clean *fc += 500 // milliseconds c.get("true") *fc += 100 // milliseconds // "false" was accessed ~600 ms ago, "true" was accessed ~100 ms ago. // This should clean out "false" but not "true" c.clean(300 * time.Millisecond) // Same values should exist _, ok = c.get("true") if !ok { t.Error("item should still exist") } _, ok = c.get("false") if ok { t.Errorf("item should have been cleaned") } } type fakeClock int64 // milliseconds func (f *fakeClock) Now() time.Time { t := time.Unix(int64(*f)/1000, (int64(*f)%1000)*int64(time.Millisecond)) *f++ return t }
lib/ignore/cache_test.go
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.04251677915453911, 0.0045504095032811165, 0.00016702264838386327, 0.00017264563939534128, 0.012662766501307487 ]
{ "id": 3, "code_window": [ "\treturn nil\n", "}\n", "\n", "func (f *folder) findRename(snap *db.Snapshot, mtimefs fs.Filesystem, file protocol.FileInfo) (protocol.FileInfo, bool) {\n", "\tfound := false\n", "\tnf := protocol.FileInfo{}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tif len(file.Blocks) == 0 {\n", "\t\treturn protocol.FileInfo{}, false\n", "\t}\n", "\n" ], "file_path": "lib/model/folder.go", "type": "add", "edit_start_line_idx": 625 }
{ "A device with that ID is already added.": "該裝置識別碼已被新增。", "A negative number of days doesn't make sense.": "一個負的天數並不合理。", "A new major version may not be compatible with previous versions.": "新的主要版本可能與以前的版本不相容。", "API Key": "API 金鑰", "About": "關於", "Action": "動作", "Actions": "操作", "Add": "增加", "Add Device": "增加裝置", "Add Folder": "增加資料夾", "Add Remote Device": "新增遠端裝置", "Add devices from the introducer to our device list, for mutually shared folders.": "對於共用的資料夾,匯入引入者的裝置清單。", "Add new folder?": "新增資料夾?", "Additionally the full rescan interval will be increased (times 60, i.e. new default of 1h). You can also configure it manually for every folder later after choosing No.": "Additionally the full rescan interval will be increased (times 60, i.e. new default of 1h). You can also configure it manually for every folder later after choosing No.", "Address": "位址", "Addresses": "位址", "Advanced": "進階", "Advanced Configuration": "進階配置", "Advanced settings": "進階設定", "All Data": "全部資料", "Allow Anonymous Usage Reporting?": "允許匿名的使用資訊回報?", "Allowed Networks": "允許的網路", "Alphabetic": "字母順序", "An external command handles the versioning. It has to remove the file from the shared folder.": "處理版本的外部指令。其必須從資料夾中刪除檔案。", "An external command handles the versioning. It has to remove the file from the shared folder. If the path to the application contains spaces, it should be quoted.": "An external command handles the versioning. It has to remove the file from the shared folder. If the path to the application contains spaces, it should be quoted.", "An external command handles the versioning. It has to remove the file from the synced folder.": "處理版本的外部指令。其必須從資料夾中刪除檔案。", "Anonymous Usage Reporting": "匿名的使用資訊回報", "Anonymous usage report format has changed. Would you like to move to the new format?": "匿名的使用資訊回報格式已經改變,你想要移至新格式嗎?", "Any devices configured on an introducer device will be added to this device as well.": "任何在引入者裝置所設置的裝置將會一併新增至此裝置", "Are you sure you want to remove device {%name%}?": "確定要移除 {{name}} 裝置?", "Are you sure you want to remove folder {%label%}?": "確定要移除 {{label}} 資料夾?", "Are you sure you want to restore {%count%} files?": "確定想要還原 {{count}} 個檔案?", "Are you sure you want to upgrade?": "Are you sure you want to upgrade?", "Auto Accept": "自動接受", "Automatic Crash Reporting": "Automatic Crash Reporting", "Automatic upgrade now offers the choice between stable releases and release candidates.": "自動更新目前有穩定發行版及發行候選版可供選擇。", "Automatic upgrades": "自動升級", "Automatic upgrades are always enabled for candidate releases.": "Automatic upgrades are always enabled for candidate releases.", "Automatically create or share folders that this device advertises at the default path.": "自動在預設資料夾路徑建立或分享該裝置推薦的資料夾。", "Available debug logging facilities:": "可用的除錯日誌工具:", "Be careful!": "請小心!", "Bugs": "程式錯誤", "CPU Utilization": "CPU 使用率", "Changelog": "更新日誌", "Clean out after": "於之後清空", "Click to see discovery failures": "點擊以查閱失敗的探索", "Close": "關閉", "Command": "指令", "Comment, when used at the start of a line": "註解,當輸入在一行的開頭時", "Compression": "壓縮", "Configured": "已設定", "Connected (Unused)": "Connected (Unused)", "Connection Error": "連線錯誤", "Connection Type": "連線類型", "Connections": "連線", "Continuously watching for changes is now available within Syncthing. This will detect changes on disk and issue a scan on only the modified paths. The benefits are that changes are propagated quicker and that less full scans are required.": "Syncthing 現在能持續地監視變動了。此機制將偵測到磁碟上的變動並僅對修改過的項目發起掃描。好處是檔案的變動會傳播的更快,並且較不需要完整掃描。", "Copied from elsewhere": "從別處複製", "Copied from original": "從原處複製", "Copyright © 2014-2016 the following Contributors:": "Copyright © 2014-2016 下列貢獻者:", "Copyright © 2014-2017 the following Contributors:": "Copyright © 2014-2017 下列貢獻者:", "Copyright © 2014-2019 the following Contributors:": "Copyright © 2014-2019 下列貢獻者:", "Creating ignore patterns, overwriting an existing file at {%path%}.": "建立忽略樣式,覆蓋已存在的 {{path}}。", "Currently Shared With Devices": "Currently Shared With Devices", "Danger!": "危險!", "Debugging Facilities": "除錯工具", "Default Folder Path": "預設資料夾路徑", "Deleted": "已刪除", "Deselect All": "取消選取全部", "Deselect devices to stop sharing this folder with.": "Deselect devices to stop sharing this folder with.", "Device": "裝置", "Device \"{%name%}\" ({%device%} at {%address%}) wants to connect. Add new device?": "裝置 \"{{name}}\" ({{device}} 位於 {{address}}) 想要連線。要增加新裝置嗎?", "Device ID": "裝置識別碼", "Device Identification": "裝置識別", "Device Name": "裝置名稱", "Device rate limits": "裝置速率限制", "Device that last modified the item": "前次修改裝置", "Devices": "裝置", "Disable Crash Reporting": "Disable Crash Reporting", "Disabled": "停用", "Disabled periodic scanning and disabled watching for changes": "已停用定期掃描及觀察變動", "Disabled periodic scanning and enabled watching for changes": "已停用定期掃描及啟用觀察變動", "Disabled periodic scanning and failed setting up watching for changes, retrying every 1m:": "已停用定期掃描,無法設定觀察變動,每 1 分鐘重試:", "Discard": "忽略", "Disconnected": "斷線", "Disconnected (Unused)": "Disconnected (Unused)", "Discovered": "已發現", "Discovery": "探索", "Discovery Failures": "探索失敗", "Do not restore": "不要還原", "Do not restore all": "不要還原全部", "Do you want to enable watching for changes for all your folders?": "您要對全部的資料夾啟用變動監視嗎?", "Documentation": "說明文件", "Download Rate": "下載速率", "Downloaded": "已下載", "Downloading": "正在下載", "Edit": "編輯", "Edit Device": "編輯裝置", "Edit Folder": "編輯資料夾", "Editing": "正在編輯", "Editing {%path%}.": "正在編輯 {{path}} 。", "Enable Crash Reporting": "Enable Crash Reporting", "Enable NAT traversal": "啟用 NAT 穿透", "Enable Relaying": "啟用中繼", "Enabled": "啟用", "Enter a non-negative number (e.g., \"2.35\") and select a unit. Percentages are as part of the total disk size.": "請輸入一非負數(如:\"2\\.35\")並選擇一個單位。百分比表示佔用磁碟容量的大小。", "Enter a non-privileged port number (1024 - 65535).": "輸入一個非特權通訊埠號 (1024 - 65535)。", "Enter comma separated (\"tcp://ip:port\", \"tcp://host:port\") addresses or \"dynamic\" to perform automatic discovery of the address.": "輸入以半形逗號區隔的位址 (\"tcp://ip:port\", \"tcp://host:port\"),或輸入 \"dynamic\" 以進行位址的自動探索。", "Enter comma separated (\"tcp://ip:port\", \"tcp://host:port\") addresses or \"dynamic\" to perform automatic discovery of the address.": "Enter comma separated (\"tcp://ip:port\", \"tcp://host:port\") addresses or \"dynamic\" to perform automatic discovery of the address.", "Enter ignore patterns, one per line.": "輸入忽略樣式,每行一種。", "Enter up to three octal digits.": "Enter up to three octal digits.", "Error": "錯誤", "External File Versioning": "外部的檔案版本控制", "Failed Items": "失敗的項目", "Failed to load ignore patterns": "無法讀取忽略樣式", "Failed to setup, retrying": "無法設定,正在重試", "Failure to connect to IPv6 servers is expected if there is no IPv6 connectivity.": "若沒有 IPv6 連線能力,則無法連接 IPv6 伺服器係屬正常現象。", "File Pull Order": "提取檔案的順序", "File Versioning": "檔案版本控制", "File permission bits are ignored when looking for changes. Use on FAT file systems.": "當改變時,檔案權限位元(File permission bits)會被忽略。用於 FAT 檔案系統上。", "Files are moved to .stversions directory when replaced or deleted by Syncthing.": "當檔案被 Syncthing 取代或刪除時,它們將被移至 .stversions 資料夾。", "Files are moved to .stversions folder when replaced or deleted by Syncthing.": "當檔案被 Syncthing 取代或刪除時,它們將被移至 .stversions 資料夾。", "Files are moved to date stamped versions in a .stversions directory when replaced or deleted by Syncthing.": "當檔案被 Syncthing 取代或刪除時,它們將被移至 .stversions 資料夾並添加日期戳記。", "Files are moved to date stamped versions in a .stversions folder when replaced or deleted by Syncthing.": "當檔案被 Syncthing 取代或刪除時,它們將被移至 .stversions 資料夾並添加日期戳記。", "Files are protected from changes made on other devices, but changes made on this device will be sent to the rest of the cluster.": "其他裝置做的改變不會影響此裝置上的檔案,但在此裝置上的變動將被發送到叢集的其他部分。", "Files are synchronized from the cluster, but any changes made locally will not be sent to other devices.": "Files are synchronized from the cluster, but any changes made locally will not be sent to other devices.", "Filesystem Notifications": "檔案系統通知", "Filesystem Watcher Errors": "檔案系統監視器錯誤", "Filter by date": "以日期篩選", "Filter by name": "以名稱篩選", "Folder": "資料夾", "Folder ID": "資料夾識別碼", "Folder Label": "資料夾標籤", "Folder Path": "資料夾路徑", "Folder Type": "資料夾類型", "Folders": "資料夾", "For the following folders an error occurred while starting to watch for changes. It will be retried every minute, so the errors might go away soon. If they persist, try to fix the underlying issue and ask for help if you can't.": "For the following folders an error occurred while starting to watch for changes. It will be retried every minute, so the errors might go away soon. If they persist, try to fix the underlying issue and ask for help if you can't.", "Full Rescan Interval (s)": "完全重新掃描間隔 (秒)", "GUI": "GUI", "GUI Authentication Password": "GUI 認證密碼", "GUI Authentication User": "GUI 使用者認證名稱", "GUI Listen Address": "GUI 監聽位址", "GUI Listen Addresses": "GUI 監聽位址", "GUI Theme": "主題", "General": "一般", "Generate": "產生", "Global Changes": "全域變動", "Global Discovery": "全域探索", "Global Discovery Servers": "全域探索伺服器", "Global State": "全域狀態", "Help": "說明", "Home page": "首頁", "However, your current settings indicate you might not want it enabled. We have disabled automatic crash reporting for you.": "However, your current settings indicate you might not want it enabled. We have disabled automatic crash reporting for you.", "Ignore": "忽略", "Ignore Patterns": "忽略樣式", "Ignore Permissions": "忽略權限", "Ignored Devices": "已忽略的裝置", "Ignored Folders": "已忽略的資料夾", "Ignored at": "忽略時間", "Incoming Rate Limit (KiB/s)": "傳入速率限制 (KiB/s)", "Incorrect configuration may damage your folder contents and render Syncthing inoperable.": "不正確的設定可能會損壞您的資料夾內容,並導致 Syncthing 不正常運作。", "Introduced By": "引入自", "Introducer": "引入者", "Inversion of the given condition (i.e. do not exclude)": "反轉給定條件 (即:不要排除)", "Keep Versions": "保留歷史版本數", "LDAP": "LDAP", "Largest First": "最大的優先", "Last File Received": "最後接收的檔案", "Last Scan": "最後掃描", "Last seen": "最後發現時間", "Later": "稍後", "Latest Change": "最近變動", "Learn more": "瞭解更多", "Limit": "限制", "Listeners": "監聽者", "Loading data...": "正在載入資料...", "Loading...": "正在載入...", "Local Additions": "Local Additions", "Local Discovery": "本機探索", "Local State": "本機狀態", "Local State (Total)": "本機狀態 (總結)", "Locally Changed Items": "本地變動項目", "Log": "日誌", "Log tailing paused. Click here to continue.": "跟隨日誌暫停。點選這裡以繼續。", "Log tailing paused. Scroll to bottom continue.": "Log tailing paused. Scroll to bottom continue.", "Log tailing paused. Scroll to the bottom to continue.": "Log tailing paused. Scroll to the bottom to continue.", "Logs": "日誌", "Major Upgrade": "重大更新", "Mass actions": "大量操作", "Master": "主要的", "Maximum Age": "最長保留時間", "Metadata Only": "僅中繼資料", "Minimum Free Disk Space": "最少閒置磁碟空間", "Mod. Device": "修改裝置", "Mod. Time": "修改時間", "Move to top of queue": "移到隊列頂端", "Multi level wildcard (matches multiple directory levels)": "多階層萬用字元 (可比對多層資料夾)", "Never": "從未", "New Device": "新裝置", "New Folder": "新資料夾", "Newest First": "最新的優先", "No": "否", "No File Versioning": "無檔案版本控制", "No files will be deleted as a result of this operation.": "此操作將不會移除您的檔案。", "No upgrades": "不更新", "Normal": "正常的", "Notice": "注意", "OK": "確定", "Off": "關閉", "Oldest First": "最舊的優先", "Optional descriptive label for the folder. Can be different on each device.": "資料夾的說明標籤(選擇性)。在不同裝置上可不一致。", "Options": "選項", "Out of Sync": "未同步", "Out of Sync Items": "未同步項目", "Outgoing Rate Limit (KiB/s)": "連出速率限制 (KiB/s)", "Override Changes": "覆蓋變動", "Path": "路徑", "Path to the folder on the local computer. Will be created if it does not exist. The tilde character (~) can be used as a shortcut for": "資料夾在本機的路徑。若資料夾不存在則會建立。波浪符號 (~) 可用作下列資料夾的捷徑:", "Path where new auto accepted folders will be created, as well as the default suggested path when adding new folders via the UI. Tilde character (~) expands to {%tilde%}.": "新自動接受的資料夾將會建立在此路徑下,從 UI 加入資料夾時也將預設推薦此路徑。波浪符字元 (~) 將被展開為 {{tilde}}。", "Path where versions should be stored (leave empty for the default .stversions directory in the shared folder).": "儲存歷史版本的路徑(若為空,則預設使用資料夾中的 .stversions 資料夾。)", "Path where versions should be stored (leave empty for the default .stversions folder in the folder).": "儲存歷史版本的路徑(若為空,則預設使用資料夾中的 .stversions 資料夾。)", "Pause": "暫停", "Pause All": "全部暫停", "Paused": "暫停", "Paused (Unused)": "Paused (Unused)", "Pending changes": "等待中的變動", "Periodic scanning at given interval and disabled watching for changes": "在一定的時間間隔,定期掃描及關閉觀察變動", "Periodic scanning at given interval and enabled watching for changes": "在一定的時間間隔,定期掃描及啟用觀察變動", "Periodic scanning at given interval and failed setting up watching for changes, retrying every 1m:": "在一定的時間間隔,定期掃描,無法設定觀察變動,每 1 分鐘重試:", "Permissions": "權限", "Please consult the release notes before performing a major upgrade.": "執行重大升級前請先參閱版本資訊。", "Please set a GUI Authentication User and Password in the Settings dialog.": "請在設定對話框內設置 GUI 使用者認證名稱及密碼。", "Please wait": "請稍後", "Prefix indicating that the file can be deleted if preventing directory removal": "前綴表示當此檔案阻礙了資料夾刪除時,可一併刪除此檔", "Prefix indicating that the pattern should be matched without case sensitivity": "前綴表示此樣式不區分大小寫", "Preparing to Sync": "Preparing to Sync", "Preview": "預覽", "Preview Usage Report": "預覽使用資訊報告", "Quick guide to supported patterns": "可支援樣式的快速指南", "RAM Utilization": "記憶體使用量", "Random": "隨機", "Receive Only": "僅接收", "Recent Changes": "最近變動", "Reduced by ignore patterns": "已由忽略樣式縮減", "Release Notes": "版本資訊", "Release candidates contain the latest features and fixes. They are similar to the traditional bi-weekly Syncthing releases.": "發行候選版包含最新的功能及修補。與傳統 Syncthing 雙週發行版相似。", "Remote Devices": "遠端裝置", "Remove": "移除", "Remove Device": "移除裝置", "Remove Folder": "移除資料夾", "Required identifier for the folder. Must be the same on all cluster devices.": "資料夾的識別字。必須在叢集內所有的裝置上皆相同。", "Rescan": "重新掃描", "Rescan All": "全部重新掃描", "Rescan Interval": "重新掃描間隔", "Rescans": "重新掃描", "Restart": "重新啟動", "Restart Needed": "需要重新啟動", "Restarting": "正在重新啟動", "Restore": "還原", "Restore Versions": "還原版本", "Resume": "繼續", "Resume All": "全部繼續", "Reused": "重用", "Revert Local Changes": "Revert Local Changes", "Running": "正在執行", "Save": "儲存", "Scan Time Remaining": "剩餘掃描時間", "Scanning": "正在掃描", "See external versioner help for supported templated command line parameters.": "關於命令列模板參數請參閱外部版本管理說明。", "See external versioning help for supported templated command line parameters.": "查看關於命令列模板參數請參閱外部版本管理說明。", "Select All": "Select All", "Select a version": "選擇一個版本", "Select additional devices to share this folder with.": "Select additional devices to share this folder with.", "Select latest version": "選擇最新的版本", "Select oldest version": "選擇最舊的版本", "Select the devices to share this folder with.": "選擇要共享這個資料夾的裝置。", "Select the folders to share with this device.": "選擇要共享這個資料夾的裝置。", "Send & Receive": "傳送及接收", "Send Only": "僅傳送", "Settings": "設定", "Share": "分享", "Share Folder": "分享資料夾", "Share Folders With Device": "與裝置共享資料夾", "Share With Devices": "與這些裝置共享", "Share this folder?": "分享此資料夾?", "Shared With": "與誰共享", "Sharing": "Sharing", "Show ID": "顯示識別碼", "Show QR": "顯示 QR 碼", "Show diff with previous version": "顯示與前一個版本的差異", "Shown instead of Device ID in the cluster status. Will be advertised to other devices as an optional default name.": "代替裝置識別碼顯示在叢集狀態中。這段文字將會廣播到其他的裝置作為一個可選的預設名稱。", "Shown instead of Device ID in the cluster status. Will be updated to the name the device advertises if left empty.": "代替裝置識別碼顯示在叢集狀態中。本欄若未填寫則將被更新為此裝置所廣播的名稱。", "Shutdown": "關閉", "Shutdown Complete": "關閉完成", "Simple File Versioning": "簡單檔案版本控制", "Single level wildcard (matches within a directory only)": "單階層萬用字元 (只在單個資料夾階層內比對)", "Size": "大小", "Smallest First": "最小的優先", "Some items could not be restored:": "有些項目無法被還原:", "Source Code": "原始碼", "Stable releases and release candidates": "穩定發行版及發行候選版", "Stable releases are delayed by about two weeks. During this time they go through testing as release candidates.": "穩定發行版大約延遲兩週發佈。這段期間將作為發行候選版來測試。", "Stable releases only": "僅穩定發行版", "Staggered File Versioning": "變動式檔案版本控制", "Start Browser": "啟動瀏覽器", "Statistics": "統計", "Stopped": "已停止", "Support": "支援", "Support Bundle": "Support Bundle", "Sync Protocol Listen Addresses": "同步通訊協定監聽位址", "Syncing": "正在同步", "Syncthing has been shut down.": "Syncthing 已經關閉。", "Syncthing includes the following software or portions thereof:": "Syncthing 包括以下軟體或其中的一部分:", "Syncthing is Free and Open Source Software licensed as MPL v2.0.": "Syncthing is Free and Open Source Software licensed as MPL v2.0.", "Syncthing is restarting.": "Syncthing 正在重新啟動。", "Syncthing is upgrading.": "Syncthing 正在進行升級。", "Syncthing now supports automatically reporting crashes to the developers. This feature is enabled by default.": "Syncthing now supports automatically reporting crashes to the developers. This feature is enabled by default.", "Syncthing seems to be down, or there is a problem with your Internet connection. Retrying…": "Syncthing 似乎離線了,或者您的網際網路連線出現問題。正在重試...", "Syncthing seems to be experiencing a problem processing your request. Please refresh the page or restart Syncthing if the problem persists.": "Syncthing 在處理您的請求時似乎遇到了問題。請重新整理本頁面,若問題持續發生,請重新啟動 Syncthing。", "Take me back": "Take me back", "The GUI address is overridden by startup options. Changes here will not take effect while the override is in place.": "The GUI address is overridden by startup options. Changes here will not take effect while the override is in place.", "The Syncthing admin interface is configured to allow remote access without a password.": "Syncthing 管理介面被設定允許無密碼的遠端存取。", "The aggregated statistics are publicly available at the URL below.": "匯總統計資訊可於下方網址取得。", "The configuration has been saved but not activated. Syncthing must restart to activate the new configuration.": "組態已經儲存但尚未啟用。Syncthing 必須重新啟動以便啟用新的組態。", "The device ID cannot be blank.": "裝置識別碼不能為空白。", "The device ID to enter here can be found in the \"Actions > Show ID\" dialog on the other device. Spaces and dashes are optional (ignored).": "其它裝置的裝置識別碼可在它們的 \"操作 > 顯示識別碼\" 對話框找到。空白及連接符號可省略。", "The encrypted usage report is sent daily. It is used to track common platforms, folder sizes and app versions. If the reported data set is changed you will be prompted with this dialog again.": "經過加密的使用資訊報告會每天傳送。報告是用來追蹤常用的平台、資料夾大小以及應用程式版本。若傳送的資料集有異動,您會再次看到這個對話框。", "The entered device ID does not look valid. It should be a 52 or 56 character string consisting of letters and numbers, with spaces and dashes being optional.": "輸入的裝置識別碼似乎無效。它應該為一串長度為 52 或 56 個字元長的半形英文字母及數字,並可能會含有額外的空白或連接符號。", "The first command line parameter is the folder path and the second parameter is the relative path in the folder.": "第一個命令列參數是資料夾路徑,第二個參數是在資料夾中的相對路徑。", "The folder ID cannot be blank.": "資料夾識別碼不能為空白。", "The folder ID must be unique.": "資料夾識別碼必須為獨一無二的。", "The folder path cannot be blank.": "資料夾路徑不能空白。", "The following intervals are used: for the first hour a version is kept every 30 seconds, for the first day a version is kept every hour, for the first 30 days a version is kept every day, until the maximum age a version is kept every week.": "使用下列的間隔:在第一個小時內每 30 秒保留一個版本,在第一天內每小時保留一個版本,在第 30 天內每一天保留一個版本,在達到最長保留時間前每一星期保留一個版本。", "The following items could not be synchronized.": "無法同步以下項目。", "The following items were changed locally.": "The following items were changed locally.", "The maximum age must be a number and cannot be blank.": "最長保留時間必須為一個數字且不得為空。", "The maximum time to keep a version (in days, set to 0 to keep versions forever).": "一個版本被保留的最長時間 (單位為天,若設定為 0 則表示永遠保留)。", "The minimum free disk space percentage must be a non-negative number between 0 and 100 (inclusive).": "最少可用磁碟空間的百分比必須介於 0 到 100(含)。", "The number of days must be a number and cannot be blank.": "天數必須必須為一個數字且不得為空。", "The number of days to keep files in the trash can. Zero means forever.": "檔案在垃圾筒中保留的天數。零表示永遠地保留。", "The number of old versions to keep, per file.": "每個檔案要保留的舊版本數量。", "The number of versions must be a number and cannot be blank.": "每個檔案要保留的舊版本數量必須是數字且不能為空白。", "The path cannot be blank.": "路徑不能空白。", "The rate limit must be a non-negative number (0: no limit)": "限制速率必須為非負的數字 (0: 不設限制)", "The rescan interval must be a non-negative number of seconds.": "重新掃描間隔必須為一個非負數的秒數。", "There are no devices to share this folder with.": "There are no devices to share this folder with.", "They are retried automatically and will be synced when the error is resolved.": "解決問題後,將會自動重試和同步。", "This Device": "本機", "This can easily give hackers access to read and change any files on your computer.": "這能給駭客輕易的來讀取、變更電腦中的任何檔案。", "This is a major version upgrade.": "這是一個重大版本更新。", "This setting controls the free space required on the home (i.e., index database) disk.": "此設定控制家目錄(即:索引資料庫)的必須可用空間。", "Time": "時間", "Time the item was last modified": "前次修改時間", "Trash Can File Versioning": "垃圾筒式檔案版本控制", "Type": "類型", "UNIX Permissions": "UNIX Permissions", "Unavailable": "無法使用", "Unavailable/Disabled by administrator or maintainer": "無法使用 / 被系統管理員或維護者停用", "Undecided (will prompt)": "未決定(將會提示)", "Unignore": "Unignore", "Unknown": "未知", "Unshared": "未共享", "Unshared Devices": "Unshared Devices", "Unused": "未使用", "Up to Date": "最新", "Updated": "已更新", "Upgrade": "升級", "Upgrade To {%version%}": "升級至 {{version}}", "Upgrading": "正在升級", "Upload Rate": "上載速率", "Uptime": "上線時間", "Usage reporting is always enabled for candidate releases.": "發行候選版永遠啟用使用數據回報。", "Use HTTPS for GUI": "為 GUI 使用 HTTPS", "Use notifications from the filesystem to detect changed items.": "Use notifications from the filesystem to detect changed items.", "Variable Size Blocks": "Variable Size Blocks", "Variable size blocks (also \"large blocks\") are more efficient for large files.": "Variable size blocks (also \"large blocks\") are more efficient for large files.", "Version": "版本", "Versions": "版本", "Versions Path": "歷史版本路徑", "Versions are automatically deleted if they are older than the maximum age or exceed the number of files allowed in an interval.": "當檔案歷史版本的存留時間大於設定的最大值,或是其數量在一段時間內超出允許值時,則會被刪除。", "Waiting to Scan": "Waiting to Scan", "Waiting to Sync": "Waiting to Sync", "Waiting to scan": "Waiting to scan", "Warning, this path is a parent directory of an existing folder \"{%otherFolder%}\".": "警告,此路徑是現存資料夾 \"{{otherFolder}}\" 的上級目錄。", "Warning, this path is a parent directory of an existing folder \"{%otherFolderLabel%}\" ({%otherFolder%}).": "警告,此路徑是現存資料夾 \"{{otherFolderLabel}}\" ({{otherFolder}}) 的上級目錄。", "Warning, this path is a subdirectory of an existing folder \"{%otherFolder%}\".": "警告,此路徑是現存資料夾 \"{{otherFolder}}\" 的下級目錄。", "Warning, this path is a subdirectory of an existing folder \"{%otherFolderLabel%}\" ({%otherFolder%}).": "警告,此路徑是現存資料夾 \"{{otherFolderLabel}}\" ({{otherFolder}}) 的下級目錄。", "Warning: If you are using an external watcher like {%syncthingInotify%}, you should make sure it is deactivated.": "警告:如果您正在使用外部監視工具,如 {{syncthingInotify}},您應該確認已經將其關閉。", "Watch for Changes": "監視變動", "Watching for Changes": "正在監視變動", "Watching for changes discovers most changes without periodic scanning.": "Watching for changes discovers most changes without periodic scanning.", "When adding a new device, keep in mind that this device must be added on the other side too.": "當新增一個裝置時,務必記住,當前的這個裝置也同樣必須被添加至另一邊。", "When adding a new folder, keep in mind that the Folder ID is used to tie folders together between devices. They are case sensitive and must match exactly between all devices.": "當新增一個資料夾時,請記住,資料夾識別碼是用來將裝置之間的資料夾綁定在一起的。它們有區分大小寫,且必須在所有裝置之間完全相同。", "Yes": "是", "You can also select one of these nearby devices:": "您亦可從這些附近裝置中擇一:", "You can change your choice at any time in the Settings dialog.": "您可以在設定對話框中隨時更改您的選擇。", "You can read more about the two release channels at the link below.": "您可於下方連結閱讀更多關於發行頻道的說明。", "You have no ignored devices.": "您沒有已忽略的裝置。\n", "You have no ignored folders.": "您沒有已忽略的資料夾。\n", "You have unsaved changes. Do you really want to discard them?": "You have unsaved changes. Do you really want to discard them?", "You must keep at least one version.": "您必須保留至少一個版本。", "days": "日", "directories": "個目錄", "files": "個檔案", "full documentation": "完整說明文件", "items": "個項目", "{%device%} wants to share folder \"{%folder%}\".": "{{device}} 想要分享資料夾 \"{{folder}}\"。", "{%device%} wants to share folder \"{%folderlabel%}\" ({%folder%}).": "{{device}} 想要分享資料夾 \"{{folderlabel}}\" ({{folder}})。" }
gui/default/assets/lang/lang-zh-TW.json
0
https://github.com/syncthing/syncthing/commit/974551375eedd53a799c98467a4a5dbd49d158f5
[ 0.0030971989035606384, 0.0002806686388794333, 0.0001633501669857651, 0.00016870420949999243, 0.0004790224484167993 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tnullBitmaps = data[pos : pos+nullBitmapLen]\n", "\t\tpos += nullBitmapLen\n", "\n", "\t\t//new param bound flag\n", "\t\tif data[pos] == 1 {\n", "\t\t\tpos++\n", "\t\t\tif len(data) < (pos + (numParams << 1)) {\n", "\t\t\t\treturn mysql.ErrMalformPacket\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// new param bound flag\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 143 }
// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package server import ( "fmt" "github.com/pingcap/tidb/util/types" ) // IDriver opens IContext. type IDriver interface { // OpenCtx opens an IContext with connection id, client capability, collation and dbname. OpenCtx(connID uint64, capability uint32, collation uint8, dbname string) (IContext, error) } // IContext is the interface to execute command. type IContext interface { // Status returns server status code. Status() uint16 // LastInsertID returns last inserted ID. LastInsertID() uint64 // AffectedRows returns affected rows of last executed command. AffectedRows() uint64 // Value returns the value associated with this context for key. Value(key fmt.Stringer) interface{} // SetValue saves a value associated with this context for key. SetValue(key fmt.Stringer, value interface{}) // CommitTxn commits the transaction operations. CommitTxn() error // RollbackTxn undoes the transaction operations. RollbackTxn() error // WarningCount returns warning count of last executed command. WarningCount() uint16 // CurrentDB returns current DB. CurrentDB() string // Execute executes a SQL statement. Execute(sql string) ([]ResultSet, error) // SetClientCapability sets client capability flags SetClientCapability(uint32) // Prepare prepares a statement. Prepare(sql string) (statement IStatement, columns, params []*ColumnInfo, err error) // GetStatement gets IStatement by statement ID. GetStatement(stmtID int) IStatement // FieldList returns columns of a table. FieldList(tableName string) (columns []*ColumnInfo, err error) // Close closes the IContext. Close() error // Auth verifies user's authentication. Auth(user string, auth []byte, salt []byte) bool } // IStatement is the interface to use a prepared statement. type IStatement interface { // ID returns statement ID ID() int // Execute executes the statement. Execute(args ...interface{}) (ResultSet, error) // AppendParam appends parameter to the statement. AppendParam(paramID int, data []byte) error // NumParams returns number of parameters. NumParams() int // BoundParams returns bound parameters. BoundParams() [][]byte // Reset removes all bound parameters. Reset() // Close closes the statement. Close() error } // ResultSet is the result set of an query. type ResultSet interface { Columns() ([]*ColumnInfo, error) Next() ([]types.Datum, error) Close() error }
server/driver.go
1
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.003220227314159274, 0.0005880080861970782, 0.00016556830087210983, 0.00016958286869339645, 0.0009442603914067149 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tnullBitmaps = data[pos : pos+nullBitmapLen]\n", "\t\tpos += nullBitmapLen\n", "\n", "\t\t//new param bound flag\n", "\t\tif data[pos] == 1 {\n", "\t\t\tpos++\n", "\t\t\tif len(data) < (pos + (numParams << 1)) {\n", "\t\t\t\treturn mysql.ErrMalformPacket\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// new param bound flag\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 143 }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Routines for decoding protocol buffer data to construct in-memory representations. */ import ( "errors" "fmt" "io" "os" "reflect" ) // errOverflow is returned when an integer is too large to be represented. var errOverflow = errors.New("proto: integer overflow") // ErrInternalBadWireType is returned by generated code when an incorrect // wire type is encountered. It does not get returned to user code. var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") // The fundamental decoders that interpret bytes on the wire. // Those that take integer types all return uint64 and are // therefore of type valueDecoder. // DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func DecodeVarint(buf []byte) (x uint64, n int) { // x, n already 0 for shift := uint(0); shift < 64; shift += 7 { if n >= len(buf) { return 0, 0 } b := uint64(buf[n]) n++ x |= (b & 0x7F) << shift if (b & 0x80) == 0 { return x, n } } // The number is too large to represent in a 64-bit value. return 0, 0 } // DecodeVarint reads a varint-encoded integer from the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) DecodeVarint() (x uint64, err error) { // x, err already 0 i := p.index l := len(p.buf) for shift := uint(0); shift < 64; shift += 7 { if i >= l { err = io.ErrUnexpectedEOF return } b := p.buf[i] i++ x |= (uint64(b) & 0x7F) << shift if b < 0x80 { p.index = i return } } // The number is too large to represent in a 64-bit value. err = errOverflow return } // DecodeFixed64 reads a 64-bit integer from the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. func (p *Buffer) DecodeFixed64() (x uint64, err error) { // x, err already 0 i := p.index + 8 if i < 0 || i > len(p.buf) { err = io.ErrUnexpectedEOF return } p.index = i x = uint64(p.buf[i-8]) x |= uint64(p.buf[i-7]) << 8 x |= uint64(p.buf[i-6]) << 16 x |= uint64(p.buf[i-5]) << 24 x |= uint64(p.buf[i-4]) << 32 x |= uint64(p.buf[i-3]) << 40 x |= uint64(p.buf[i-2]) << 48 x |= uint64(p.buf[i-1]) << 56 return } // DecodeFixed32 reads a 32-bit integer from the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. func (p *Buffer) DecodeFixed32() (x uint64, err error) { // x, err already 0 i := p.index + 4 if i < 0 || i > len(p.buf) { err = io.ErrUnexpectedEOF return } p.index = i x = uint64(p.buf[i-4]) x |= uint64(p.buf[i-3]) << 8 x |= uint64(p.buf[i-2]) << 16 x |= uint64(p.buf[i-1]) << 24 return } // DecodeZigzag64 reads a zigzag-encoded 64-bit integer // from the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) DecodeZigzag64() (x uint64, err error) { x, err = p.DecodeVarint() if err != nil { return } x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) return } // DecodeZigzag32 reads a zigzag-encoded 32-bit integer // from the Buffer. // This is the format used for the sint32 protocol buffer type. func (p *Buffer) DecodeZigzag32() (x uint64, err error) { x, err = p.DecodeVarint() if err != nil { return } x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) return } // These are not ValueDecoders: they produce an array of bytes or a string. // bytes, embedded messages // DecodeRawBytes reads a count-delimited byte buffer from the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { n, err := p.DecodeVarint() if err != nil { return nil, err } nb := int(n) if nb < 0 { return nil, fmt.Errorf("proto: bad byte length %d", nb) } end := p.index + nb if end < p.index || end > len(p.buf) { return nil, io.ErrUnexpectedEOF } if !alloc { // todo: check if can get more uses of alloc=false buf = p.buf[p.index:end] p.index += nb return } buf = make([]byte, nb) copy(buf, p.buf[p.index:]) p.index += nb return } // DecodeStringBytes reads an encoded string from the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) DecodeStringBytes() (s string, err error) { buf, err := p.DecodeRawBytes(false) if err != nil { return } return string(buf), nil } // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. // If the protocol buffer has extensions, and the field matches, add it as an extension. // Otherwise, if the XXX_unrecognized field exists, append the skipped data there. func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { oi := o.index err := o.skip(t, tag, wire) if err != nil { return err } if !unrecField.IsValid() { return nil } ptr := structPointer_Bytes(base, unrecField) // Add the skipped field to struct field obuf := o.buf o.buf = *ptr o.EncodeVarint(uint64(tag<<3 | wire)) *ptr = append(o.buf, obuf[oi:o.index]...) o.buf = obuf return nil } // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. func (o *Buffer) skip(t reflect.Type, tag, wire int) error { var u uint64 var err error switch wire { case WireVarint: _, err = o.DecodeVarint() case WireFixed64: _, err = o.DecodeFixed64() case WireBytes: _, err = o.DecodeRawBytes(false) case WireFixed32: _, err = o.DecodeFixed32() case WireStartGroup: for { u, err = o.DecodeVarint() if err != nil { break } fwire := int(u & 0x7) if fwire == WireEndGroup { break } ftag := int(u >> 3) err = o.skip(t, ftag, fwire) if err != nil { break } } default: err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) } return err } // Unmarshaler is the interface representing objects that can // unmarshal themselves. The method should reset the receiver before // decoding starts. The argument points to data that may be // overwritten, so implementations should not keep references to the // buffer. type Unmarshaler interface { Unmarshal([]byte) error } // Unmarshal parses the protocol buffer representation in buf and places the // decoded result in pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. // // Unmarshal resets pb before starting to unmarshal, so any // existing data in pb is always removed. Use UnmarshalMerge // to preserve and append to existing data. func Unmarshal(buf []byte, pb Message) error { pb.Reset() return UnmarshalMerge(buf, pb) } // UnmarshalMerge parses the protocol buffer representation in buf and // writes the decoded result to pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. // // UnmarshalMerge merges into existing data in pb. // Most code should use Unmarshal instead. func UnmarshalMerge(buf []byte, pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { return u.Unmarshal(buf) } return NewBuffer(buf).Unmarshal(pb) } // DecodeMessage reads a count-delimited message from the Buffer. func (p *Buffer) DecodeMessage(pb Message) error { enc, err := p.DecodeRawBytes(false) if err != nil { return err } return NewBuffer(enc).Unmarshal(pb) } // DecodeGroup reads a tag-delimited group from the Buffer. func (p *Buffer) DecodeGroup(pb Message) error { typ, base, err := getbase(pb) if err != nil { return err } return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) } // Unmarshal parses the protocol buffer representation in the // Buffer and places the decoded result in pb. If the struct // underlying pb does not match the data in the buffer, the results can be // unpredictable. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { err := u.Unmarshal(p.buf[p.index:]) p.index = len(p.buf) return err } typ, base, err := getbase(pb) if err != nil { return err } err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) if collectStats { stats.Decode++ } return err } // unmarshalType does the work of unmarshaling a structure. func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { var state errorState required, reqFields := prop.reqCount, uint64(0) var err error for err == nil && o.index < len(o.buf) { oi := o.index var u uint64 u, err = o.DecodeVarint() if err != nil { break } wire := int(u & 0x7) if wire == WireEndGroup { if is_group { if required > 0 { // Not enough information to determine the exact field. // (See below.) return &RequiredNotSetError{"{Unknown}"} } return nil // input is satisfied } return fmt.Errorf("proto: %s: wiretype end group for non-group", st) } tag := int(u >> 3) if tag <= 0 { return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) } fieldnum, ok := prop.decoderTags.get(tag) if !ok { // Maybe it's an extension? if prop.extendable { if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { if err = o.skip(st, tag, wire); err == nil { extmap := e.extensionsWrite() ext := extmap[int32(tag)] // may be missing ext.enc = append(ext.enc, o.buf[oi:o.index]...) extmap[int32(tag)] = ext } continue } } // Maybe it's a oneof? if prop.oneofUnmarshaler != nil { m := structPointer_Interface(base, st).(Message) // First return value indicates whether tag is a oneof field. ok, err = prop.oneofUnmarshaler(m, tag, wire, o) if err == ErrInternalBadWireType { // Map the error to something more descriptive. // Do the formatting here to save generated code space. err = fmt.Errorf("bad wiretype for oneof field in %T", m) } if ok { continue } } err = o.skipAndSave(st, tag, wire, base, prop.unrecField) continue } p := prop.Prop[fieldnum] if p.dec == nil { fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) continue } dec := p.dec if wire != WireStartGroup && wire != p.WireType { if wire == WireBytes && p.packedDec != nil { // a packable field dec = p.packedDec } else { err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) continue } } decErr := dec(o, p, base) if decErr != nil && !state.shouldContinue(decErr, p) { err = decErr } if err == nil && p.Required { // Successfully decoded a required field. if tag <= 64 { // use bitmap for fields 1-64 to catch field reuse. var mask uint64 = 1 << uint64(tag-1) if reqFields&mask == 0 { // new required field reqFields |= mask required-- } } else { // This is imprecise. It can be fooled by a required field // with a tag > 64 that is encoded twice; that's very rare. // A fully correct implementation would require allocating // a data structure, which we would like to avoid. required-- } } } if err == nil { if is_group { return io.ErrUnexpectedEOF } if state.err != nil { return state.err } if required > 0 { // Not enough information to determine the exact field. If we use extra // CPU, we could determine the field only if the missing required field // has a tag <= 64 and we check reqFields. return &RequiredNotSetError{"{Unknown}"} } } return err } // Individual type decoders // For each, // u is the decoded value, // v is a pointer to the field (pointer) in the struct // Sizes of the pools to allocate inside the Buffer. // The goal is modest amortization and allocation // on at least 16-byte boundaries. const ( boolPoolSize = 16 uint32PoolSize = 8 uint64PoolSize = 4 ) // Decode a bool. func (o *Buffer) dec_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } if len(o.bools) == 0 { o.bools = make([]bool, boolPoolSize) } o.bools[0] = u != 0 *structPointer_Bool(base, p.field) = &o.bools[0] o.bools = o.bools[1:] return nil } func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } *structPointer_BoolVal(base, p.field) = u != 0 return nil } // Decode an int32. func (o *Buffer) dec_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) return nil } func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) return nil } // Decode an int64. func (o *Buffer) dec_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word64_Set(structPointer_Word64(base, p.field), o, u) return nil } func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word64Val_Set(structPointer_Word64Val(base, p.field), o, u) return nil } // Decode a string. func (o *Buffer) dec_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } *structPointer_String(base, p.field) = &s return nil } func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } *structPointer_StringVal(base, p.field) = s return nil } // Decode a slice of bytes ([]byte). func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { b, err := o.DecodeRawBytes(true) if err != nil { return err } *structPointer_Bytes(base, p.field) = b return nil } // Decode a slice of bools ([]bool). func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } v := structPointer_BoolSlice(base, p.field) *v = append(*v, u != 0) return nil } // Decode a slice of bools ([]bool) in packed format. func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { v := structPointer_BoolSlice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded bools fin := o.index + nb if fin < o.index { return errOverflow } y := *v for o.index < fin { u, err := p.valDec(o) if err != nil { return err } y = append(y, u != 0) } *v = y return nil } // Decode a slice of int32s ([]int32). func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } structPointer_Word32Slice(base, p.field).Append(uint32(u)) return nil } // Decode a slice of int32s ([]int32) in packed format. func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { v := structPointer_Word32Slice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded int32s fin := o.index + nb if fin < o.index { return errOverflow } for o.index < fin { u, err := p.valDec(o) if err != nil { return err } v.Append(uint32(u)) } return nil } // Decode a slice of int64s ([]int64). func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } structPointer_Word64Slice(base, p.field).Append(u) return nil } // Decode a slice of int64s ([]int64) in packed format. func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { v := structPointer_Word64Slice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded int64s fin := o.index + nb if fin < o.index { return errOverflow } for o.index < fin { u, err := p.valDec(o) if err != nil { return err } v.Append(u) } return nil } // Decode a slice of strings ([]string). func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } v := structPointer_StringSlice(base, p.field) *v = append(*v, s) return nil } // Decode a slice of slice of bytes ([][]byte). func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { b, err := o.DecodeRawBytes(true) if err != nil { return err } v := structPointer_BytesSlice(base, p.field) *v = append(*v, b) return nil } // Decode a map field. func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { raw, err := o.DecodeRawBytes(false) if err != nil { return err } oi := o.index // index at the end of this map entry o.index -= len(raw) // move buffer back to start of map entry mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V if mptr.Elem().IsNil() { mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) } v := mptr.Elem() // map[K]V // Prepare addressable doubly-indirect placeholders for the key and value types. // See enc_new_map for why. keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K keybase := toStructPointer(keyptr.Addr()) // **K var valbase structPointer var valptr reflect.Value switch p.mtype.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valptr = reflect.ValueOf(&dummy) // *[]byte valbase = toStructPointer(valptr) // *[]byte case reflect.Ptr: // message; valptr is **Msg; need to allocate the intermediate pointer valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V valptr.Set(reflect.New(valptr.Type().Elem())) valbase = toStructPointer(valptr) default: // everything else valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V valbase = toStructPointer(valptr.Addr()) // **V } // Decode. // This parses a restricted wire format, namely the encoding of a message // with two fields. See enc_new_map for the format. for o.index < oi { // tagcode for key and value properties are always a single byte // because they have tags 1 and 2. tagcode := o.buf[o.index] o.index++ switch tagcode { case p.mkeyprop.tagcode[0]: if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { return err } case p.mvalprop.tagcode[0]: if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { return err } default: // TODO: Should we silently skip this instead? return fmt.Errorf("proto: bad map data tag %d", raw[0]) } } keyelem, valelem := keyptr.Elem(), valptr.Elem() if !keyelem.IsValid() { keyelem = reflect.Zero(p.mtype.Key()) } if !valelem.IsValid() { valelem = reflect.Zero(p.mtype.Elem()) } v.SetMapIndex(keyelem, valelem) return nil } // Decode a group. func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { bas := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(bas) { // allocate new nested message bas = toStructPointer(reflect.New(p.stype)) structPointer_SetStructPointer(base, p.field, bas) } return o.unmarshalType(p.stype, p.sprop, true, bas) } // Decode an embedded message. func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { raw, e := o.DecodeRawBytes(false) if e != nil { return e } bas := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(bas) { // allocate new nested message bas = toStructPointer(reflect.New(p.stype)) structPointer_SetStructPointer(base, p.field, bas) } // If the object can unmarshal itself, let it. if p.isUnmarshaler { iv := structPointer_Interface(bas, p.stype) return iv.(Unmarshaler).Unmarshal(raw) } obuf := o.buf oi := o.index o.buf = raw o.index = 0 err = o.unmarshalType(p.stype, p.sprop, false, bas) o.buf = obuf o.index = oi return err } // Decode a slice of embedded messages. func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { return o.dec_slice_struct(p, false, base) } // Decode a slice of embedded groups. func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { return o.dec_slice_struct(p, true, base) } // Decode a slice of structs ([]*struct). func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { v := reflect.New(p.stype) bas := toStructPointer(v) structPointer_StructPointerSlice(base, p.field).Append(bas) if is_group { err := o.unmarshalType(p.stype, p.sprop, is_group, bas) return err } raw, err := o.DecodeRawBytes(false) if err != nil { return err } // If the object can unmarshal itself, let it. if p.isUnmarshaler { iv := v.Interface() return iv.(Unmarshaler).Unmarshal(raw) } obuf := o.buf oi := o.index o.buf = raw o.index = 0 err = o.unmarshalType(p.stype, p.sprop, is_group, bas) o.buf = obuf o.index = oi return err }
_vendor/src/github.com/golang/protobuf/proto/decode.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.0003433458332438022, 0.00017574994126334786, 0.00016053894069045782, 0.0001696150575298816, 0.000027522308300831355 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tnullBitmaps = data[pos : pos+nullBitmapLen]\n", "\t\tpos += nullBitmapLen\n", "\n", "\t\t//new param bound flag\n", "\t\tif data[pos] == 1 {\n", "\t\t\tpos++\n", "\t\t\tif len(data) < (pos + (numParams << 1)) {\n", "\t\t\t\treturn mysql.ErrMalformPacket\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// new param bound flag\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 143 }
// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package plan import ( "fmt" "math" "sort" "github.com/juju/errors" "github.com/pingcap/tidb/ast" "github.com/pingcap/tidb/expression" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/util/types" ) type rangePoint struct { value types.Datum excl bool // exclude start bool } func (rp rangePoint) String() string { val := rp.value.GetValue() if rp.value.Kind() == types.KindMinNotNull { val = "-inf" } else if rp.value.Kind() == types.KindMaxValue { val = "+inf" } if rp.start { symbol := "[" if rp.excl { symbol = "(" } return fmt.Sprintf("%s%v", symbol, val) } symbol := "]" if rp.excl { symbol = ")" } return fmt.Sprintf("%v%s", val, symbol) } type rangePointSorter struct { points []rangePoint err error sc *variable.StatementContext } func (r *rangePointSorter) Len() int { return len(r.points) } func (r *rangePointSorter) Less(i, j int) bool { a := r.points[i] b := r.points[j] less, err := rangePointLess(r.sc, a, b) if err != nil { r.err = err } return less } func rangePointLess(sc *variable.StatementContext, a, b rangePoint) (bool, error) { cmp, err := a.value.CompareDatum(sc, b.value) if cmp != 0 { return cmp < 0, nil } return rangePointEqualValueLess(a, b), errors.Trace(err) } func rangePointEqualValueLess(a, b rangePoint) bool { if a.start && b.start { return !a.excl && b.excl } else if a.start { return !a.excl && !b.excl } else if b.start { return a.excl || b.excl } return a.excl && !b.excl } func (r *rangePointSorter) Swap(i, j int) { r.points[i], r.points[j] = r.points[j], r.points[i] } type rangeBuilder struct { err error sc *variable.StatementContext } func (r *rangeBuilder) build(expr expression.Expression) []rangePoint { switch x := expr.(type) { case *expression.Column: return r.buildFromColumn(x) case *expression.ScalarFunction: return r.buildFromScalarFunc(x) case *expression.Constant: return r.buildFromConstant(x) } return fullRange } func (r *rangeBuilder) buildFromConstant(expr *expression.Constant) []rangePoint { if expr.Value.IsNull() { return nil } val, err := expr.Value.ToBool(r.sc) if err != nil { r.err = err return nil } if val == 0 { return nil } return fullRange } func (r *rangeBuilder) buildFromColumn(expr *expression.Column) []rangePoint { // column name expression is equivalent to column name is true. startPoint1 := rangePoint{value: types.MinNotNullDatum(), start: true} endPoint1 := rangePoint{excl: true} endPoint1.value.SetInt64(0) startPoint2 := rangePoint{excl: true, start: true} startPoint2.value.SetInt64(0) endPoint2 := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint1, endPoint1, startPoint2, endPoint2} } func (r *rangeBuilder) buildFormBinOp(expr *expression.ScalarFunction) []rangePoint { // This has been checked that the binary operation is comparison operation, and one of // the operand is column name expression. var value types.Datum var op string if v, ok := expr.GetArgs()[0].(*expression.Constant); ok { value = v.Value switch expr.FuncName.L { case ast.GE: op = ast.LE case ast.GT: op = ast.LT case ast.LT: op = ast.GT case ast.LE: op = ast.GE default: op = expr.FuncName.L } } else { value = expr.GetArgs()[1].(*expression.Constant).Value op = expr.FuncName.L } if value.IsNull() { return nil } switch op { case ast.EQ: startPoint := rangePoint{value: value, start: true} endPoint := rangePoint{value: value} return []rangePoint{startPoint, endPoint} case ast.NE: startPoint1 := rangePoint{value: types.MinNotNullDatum(), start: true} endPoint1 := rangePoint{value: value, excl: true} startPoint2 := rangePoint{value: value, start: true, excl: true} endPoint2 := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint1, endPoint1, startPoint2, endPoint2} case ast.LT: startPoint := rangePoint{value: types.MinNotNullDatum(), start: true} endPoint := rangePoint{value: value, excl: true} return []rangePoint{startPoint, endPoint} case ast.LE: startPoint := rangePoint{value: types.MinNotNullDatum(), start: true} endPoint := rangePoint{value: value} return []rangePoint{startPoint, endPoint} case ast.GT: startPoint := rangePoint{value: value, start: true, excl: true} endPoint := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint, endPoint} case ast.GE: startPoint := rangePoint{value: value, start: true} endPoint := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint, endPoint} } return nil } func (r *rangeBuilder) buildFromIsTrue(expr *expression.ScalarFunction, isNot int) []rangePoint { if isNot == 1 { // NOT TRUE range is {[null null] [0, 0]} startPoint1 := rangePoint{start: true} endPoint1 := rangePoint{} startPoint2 := rangePoint{start: true} startPoint2.value.SetInt64(0) endPoint2 := rangePoint{} endPoint2.value.SetInt64(0) return []rangePoint{startPoint1, endPoint1, startPoint2, endPoint2} } // TRUE range is {[-inf 0) (0 +inf]} startPoint1 := rangePoint{value: types.MinNotNullDatum(), start: true} endPoint1 := rangePoint{excl: true} endPoint1.value.SetInt64(0) startPoint2 := rangePoint{excl: true, start: true} startPoint2.value.SetInt64(0) endPoint2 := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint1, endPoint1, startPoint2, endPoint2} } func (r *rangeBuilder) buildFromIsFalse(expr *expression.ScalarFunction, isNot int) []rangePoint { if isNot == 1 { // NOT FALSE range is {[-inf, 0), (0, +inf], [null, null]} startPoint1 := rangePoint{start: true} endPoint1 := rangePoint{excl: true} endPoint1.value.SetInt64(0) startPoint2 := rangePoint{start: true, excl: true} startPoint2.value.SetInt64(0) endPoint2 := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint1, endPoint1, startPoint2, endPoint2} } // FALSE range is {[0, 0]} startPoint := rangePoint{start: true} startPoint.value.SetInt64(0) endPoint := rangePoint{} endPoint.value.SetInt64(0) return []rangePoint{startPoint, endPoint} } func (r *rangeBuilder) newBuildFromIn(expr *expression.ScalarFunction) []rangePoint { var rangePoints []rangePoint list := expr.GetArgs()[1:] for _, e := range list { v, ok := e.(*expression.Constant) if !ok { r.err = ErrUnsupportedType.Gen("expr:%v is not constant", e) return fullRange } startPoint := rangePoint{value: types.NewDatum(v.Value.GetValue()), start: true} endPoint := rangePoint{value: types.NewDatum(v.Value.GetValue())} rangePoints = append(rangePoints, startPoint, endPoint) } sorter := rangePointSorter{points: rangePoints, sc: r.sc} sort.Sort(&sorter) if sorter.err != nil { r.err = sorter.err } // check duplicates hasDuplicate := false isStart := false for _, v := range rangePoints { if isStart == v.start { hasDuplicate = true break } isStart = v.start } if !hasDuplicate { return rangePoints } // remove duplicates distinctRangePoints := make([]rangePoint, 0, len(rangePoints)) isStart = false for i := 0; i < len(rangePoints); i++ { current := rangePoints[i] if isStart == current.start { continue } distinctRangePoints = append(distinctRangePoints, current) isStart = current.start } return distinctRangePoints } func (r *rangeBuilder) newBuildFromPatternLike(expr *expression.ScalarFunction) []rangePoint { pattern, err := expr.GetArgs()[1].(*expression.Constant).Value.ToString() if err != nil { r.err = errors.Trace(err) return fullRange } if pattern == "" { startPoint := rangePoint{value: types.NewStringDatum(""), start: true} endPoint := rangePoint{value: types.NewStringDatum("")} return []rangePoint{startPoint, endPoint} } lowValue := make([]byte, 0, len(pattern)) escape := byte(expr.GetArgs()[2].(*expression.Constant).Value.GetInt64()) var exclude bool isExactMatch := true for i := 0; i < len(pattern); i++ { if pattern[i] == escape { i++ if i < len(pattern) { lowValue = append(lowValue, pattern[i]) } else { lowValue = append(lowValue, escape) } continue } if pattern[i] == '%' { // Get the prefix. isExactMatch = false break } else if pattern[i] == '_' { // Get the prefix, but exclude the prefix. // e.g., "abc_x", the start point exclude "abc", // because the string length is more than 3. exclude = true isExactMatch = false break } lowValue = append(lowValue, pattern[i]) } if len(lowValue) == 0 { return []rangePoint{{value: types.MinNotNullDatum(), start: true}, {value: types.MaxValueDatum()}} } if isExactMatch { val := types.NewStringDatum(string(lowValue)) return []rangePoint{{value: val, start: true}, {value: val}} } startPoint := rangePoint{start: true, excl: exclude} startPoint.value.SetBytesAsString(lowValue) highValue := make([]byte, len(lowValue)) copy(highValue, lowValue) endPoint := rangePoint{excl: true} for i := len(highValue) - 1; i >= 0; i-- { // Make the end point value more than the start point value, // and the length of the end point value is the same as the length of the start point value. // e.g., the start point value is "abc", so the end point value is "abd". highValue[i]++ if highValue[i] != 0 { endPoint.value.SetBytesAsString(highValue) break } // If highValue[i] is 255 and highValue[i]++ is 0, then the end point value is max value. if i == 0 { endPoint.value = types.MaxValueDatum() } } return []rangePoint{startPoint, endPoint} } func (r *rangeBuilder) buildFromNot(expr *expression.ScalarFunction) []rangePoint { switch n := expr.FuncName.L; n { case ast.IsTruth: return r.buildFromIsTrue(expr, 1) case ast.IsFalsity: return r.buildFromIsFalse(expr, 1) case ast.In: // Pattern not in is not supported. r.err = ErrUnsupportedType.Gen("NOT IN is not supported") return fullRange case ast.Like: // Pattern not like is not supported. r.err = ErrUnsupportedType.Gen("NOT LIKE is not supported.") return fullRange case ast.IsNull: startPoint := rangePoint{value: types.MinNotNullDatum(), start: true} endPoint := rangePoint{value: types.MaxValueDatum()} return []rangePoint{startPoint, endPoint} } return nil } func (r *rangeBuilder) buildFromScalarFunc(expr *expression.ScalarFunction) []rangePoint { switch op := expr.FuncName.L; op { case ast.GE, ast.GT, ast.LT, ast.LE, ast.EQ, ast.NE: return r.buildFormBinOp(expr) case ast.AndAnd: return r.intersection(r.build(expr.GetArgs()[0]), r.build(expr.GetArgs()[1])) case ast.OrOr: return r.union(r.build(expr.GetArgs()[0]), r.build(expr.GetArgs()[1])) case ast.IsTruth: return r.buildFromIsTrue(expr, 0) case ast.IsFalsity: return r.buildFromIsFalse(expr, 0) case ast.In: return r.newBuildFromIn(expr) case ast.Like: return r.newBuildFromPatternLike(expr) case ast.IsNull: startPoint := rangePoint{start: true} endPoint := rangePoint{} return []rangePoint{startPoint, endPoint} case ast.UnaryNot: return r.buildFromNot(expr.GetArgs()[0].(*expression.ScalarFunction)) } return nil } func (r *rangeBuilder) intersection(a, b []rangePoint) []rangePoint { return r.merge(a, b, false) } func (r *rangeBuilder) union(a, b []rangePoint) []rangePoint { return r.merge(a, b, true) } func (r *rangeBuilder) merge(a, b []rangePoint, union bool) []rangePoint { sorter := rangePointSorter{points: append(a, b...), sc: r.sc} sort.Sort(&sorter) if sorter.err != nil { r.err = sorter.err return nil } var ( merged []rangePoint inRangeCount int requiredInRangeCount int ) if union { requiredInRangeCount = 1 } else { requiredInRangeCount = 2 } for _, val := range sorter.points { if val.start { inRangeCount++ if inRangeCount == requiredInRangeCount { // just reached the required in range count, a new range started. merged = append(merged, val) } } else { if inRangeCount == requiredInRangeCount { // just about to leave the required in range count, the range is ended. merged = append(merged, val) } inRangeCount-- } } return merged } // buildIndexRanges build index ranges from range points. // Only the first column in the index is built, extra column ranges will be appended by // appendIndexRanges. func (r *rangeBuilder) buildIndexRanges(rangePoints []rangePoint, tp *types.FieldType) []*IndexRange { indexRanges := make([]*IndexRange, 0, len(rangePoints)/2) for i := 0; i < len(rangePoints); i += 2 { startPoint := r.convertPoint(rangePoints[i], tp) endPoint := r.convertPoint(rangePoints[i+1], tp) less, err := rangePointLess(r.sc, startPoint, endPoint) if err != nil { r.err = errors.Trace(err) } if !less { continue } ir := &IndexRange{ LowVal: []types.Datum{startPoint.value}, LowExclude: startPoint.excl, HighVal: []types.Datum{endPoint.value}, HighExclude: endPoint.excl, } indexRanges = append(indexRanges, ir) } return indexRanges } func (r *rangeBuilder) convertPoint(point rangePoint, tp *types.FieldType) rangePoint { switch point.value.Kind() { case types.KindMaxValue, types.KindMinNotNull: return point } casted, err := point.value.ConvertTo(r.sc, tp) if err != nil { r.err = errors.Trace(err) } valCmpCasted, err := point.value.CompareDatum(r.sc, casted) if err != nil { r.err = errors.Trace(err) } point.value = casted if valCmpCasted == 0 { return point } if point.start { if point.excl { if valCmpCasted < 0 { // e.g. "a > 1.9" convert to "a >= 2". point.excl = false } } else { if valCmpCasted > 0 { // e.g. "a >= 1.1 convert to "a > 1" point.excl = true } } } else { if point.excl { if valCmpCasted > 0 { // e.g. "a < 1.1" convert to "a <= 1" point.excl = false } } else { if valCmpCasted < 0 { // e.g. "a <= 1.9" convert to "a < 2" point.excl = true } } } return point } // appendIndexRanges appends additional column ranges for multi-column index. // The additional column ranges can only be appended to point ranges. // for example we have an index (a, b), if the condition is (a > 1 and b = 2) // then we can not build a conjunctive ranges for this index. func (r *rangeBuilder) appendIndexRanges(origin []*IndexRange, rangePoints []rangePoint, ft *types.FieldType) []*IndexRange { var newIndexRanges []*IndexRange for i := 0; i < len(origin); i++ { oRange := origin[i] if !oRange.IsPoint(r.sc) { newIndexRanges = append(newIndexRanges, oRange) } else { newIndexRanges = append(newIndexRanges, r.appendIndexRange(oRange, rangePoints, ft)...) } } return newIndexRanges } func (r *rangeBuilder) appendIndexRange(origin *IndexRange, rangePoints []rangePoint, ft *types.FieldType) []*IndexRange { newRanges := make([]*IndexRange, 0, len(rangePoints)/2) for i := 0; i < len(rangePoints); i += 2 { startPoint := r.convertPoint(rangePoints[i], ft) endPoint := r.convertPoint(rangePoints[i+1], ft) less, err := rangePointLess(r.sc, startPoint, endPoint) if err != nil { r.err = errors.Trace(err) } if !less { continue } lowVal := make([]types.Datum, len(origin.LowVal)+1) copy(lowVal, origin.LowVal) lowVal[len(origin.LowVal)] = startPoint.value highVal := make([]types.Datum, len(origin.HighVal)+1) copy(highVal, origin.HighVal) highVal[len(origin.HighVal)] = endPoint.value ir := &IndexRange{ LowVal: lowVal, LowExclude: startPoint.excl, HighVal: highVal, HighExclude: endPoint.excl, } newRanges = append(newRanges, ir) } return newRanges } func (r *rangeBuilder) buildTableRanges(rangePoints []rangePoint) []TableRange { tableRanges := make([]TableRange, 0, len(rangePoints)/2) for i := 0; i < len(rangePoints); i += 2 { startPoint := rangePoints[i] if startPoint.value.IsNull() || startPoint.value.Kind() == types.KindMinNotNull { startPoint.value.SetInt64(math.MinInt64) } startInt, err := startPoint.value.ToInt64(r.sc) if err != nil { r.err = errors.Trace(err) return tableRanges } startDatum := types.NewDatum(startInt) cmp, err := startDatum.CompareDatum(r.sc, startPoint.value) if err != nil { r.err = errors.Trace(err) return tableRanges } if cmp < 0 || (cmp == 0 && startPoint.excl) { startInt++ } endPoint := rangePoints[i+1] if endPoint.value.IsNull() { endPoint.value.SetInt64(math.MinInt64) } else if endPoint.value.Kind() == types.KindMaxValue { endPoint.value.SetInt64(math.MaxInt64) } endInt, err := endPoint.value.ToInt64(r.sc) if err != nil { r.err = errors.Trace(err) return tableRanges } endDatum := types.NewDatum(endInt) cmp, err = endDatum.CompareDatum(r.sc, endPoint.value) if err != nil { r.err = errors.Trace(err) return tableRanges } if cmp > 0 || (cmp == 0 && endPoint.excl) { endInt-- } if startInt > endInt { continue } tableRanges = append(tableRanges, TableRange{LowVal: startInt, HighVal: endInt}) } return tableRanges }
plan/range.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.0007049852283671498, 0.000178903152118437, 0.0001617648231331259, 0.0001699527638265863, 0.00006747588486177847 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tnullBitmaps = data[pos : pos+nullBitmapLen]\n", "\t\tpos += nullBitmapLen\n", "\n", "\t\t//new param bound flag\n", "\t\tif data[pos] == 1 {\n", "\t\t\tpos++\n", "\t\t\tif len(data) < (pos + (numParams << 1)) {\n", "\t\t\t\treturn mysql.ErrMalformPacket\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// new param bound flag\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 143 }
// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package types import ( . "github.com/pingcap/check" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/util/testleak" ) var _ = Suite(&testFieldTypeSuite{}) type testFieldTypeSuite struct { } func (s *testFieldTypeSuite) TestFieldType(c *C) { defer testleak.AfterTest(c)() ft := NewFieldType(mysql.TypeDuration) c.Assert(ft.Flen, Equals, UnspecifiedLength) c.Assert(ft.Decimal, Equals, UnspecifiedLength) ft.Decimal = 5 c.Assert(ft.String(), Equals, "time(5)") ft.Tp = mysql.TypeLong ft.Flag |= mysql.UnsignedFlag | mysql.ZerofillFlag c.Assert(ft.String(), Equals, "int(5) UNSIGNED ZEROFILL") ft = NewFieldType(mysql.TypeFloat) ft.Flen = 10 ft.Decimal = 3 c.Assert(ft.String(), Equals, "float(10,3)") ft = NewFieldType(mysql.TypeFloat) ft.Flen = 10 ft.Decimal = -1 c.Assert(ft.String(), Equals, "float") ft = NewFieldType(mysql.TypeDouble) ft.Flen = 10 ft.Decimal = 3 c.Assert(ft.String(), Equals, "double(10,3)") ft = NewFieldType(mysql.TypeDouble) ft.Flen = 10 ft.Decimal = -1 c.Assert(ft.String(), Equals, "double") ft = NewFieldType(mysql.TypeBlob) ft.Flen = 10 ft.Charset = "UTF8" ft.Collate = "UTF8_UNICODE_GI" c.Assert(ft.String(), Equals, "text(10) CHARACTER SET UTF8 COLLATE UTF8_UNICODE_GI") ft = NewFieldType(mysql.TypeVarchar) ft.Flen = 10 ft.Flag |= mysql.BinaryFlag c.Assert(ft.String(), Equals, "varchar(10) BINARY") ft = NewFieldType(mysql.TypeEnum) ft.Elems = []string{"a", "b"} c.Assert(ft.String(), Equals, "enum('a','b')") ft = NewFieldType(mysql.TypeEnum) ft.Elems = []string{"'a'", "'b'"} c.Assert(ft.String(), Equals, "enum('''a''','''b''')") ft = NewFieldType(mysql.TypeSet) ft.Elems = []string{"a", "b"} c.Assert(ft.String(), Equals, "set('a','b')") ft = NewFieldType(mysql.TypeSet) ft.Elems = []string{"'a'", "'b'"} c.Assert(ft.String(), Equals, "set('''a''','''b''')") ft = NewFieldType(mysql.TypeTimestamp) ft.Flen = 8 ft.Decimal = 2 c.Assert(ft.String(), Equals, "timestamp(2)") ft = NewFieldType(mysql.TypeTimestamp) ft.Flen = 8 ft.Decimal = 0 c.Assert(ft.String(), Equals, "timestamp") ft = NewFieldType(mysql.TypeDatetime) ft.Flen = 8 ft.Decimal = 2 c.Assert(ft.String(), Equals, "datetime(2)") ft = NewFieldType(mysql.TypeDatetime) ft.Flen = 8 ft.Decimal = 0 c.Assert(ft.String(), Equals, "datetime") ft = NewFieldType(mysql.TypeDate) ft.Flen = 8 ft.Decimal = 2 c.Assert(ft.String(), Equals, "date(2)") ft = NewFieldType(mysql.TypeDate) ft.Flen = 8 ft.Decimal = 0 c.Assert(ft.String(), Equals, "date") } func (s *testFieldTypeSuite) TestDefaultTypeForValue(c *C) { defer testleak.AfterTest(c)() cases := []struct { value interface{} tp byte }{ {nil, mysql.TypeNull}, {1, mysql.TypeLonglong}, {uint64(1), mysql.TypeLonglong}, {"abc", mysql.TypeVarString}, {1.1, mysql.TypeNewDecimal}, {[]byte("abc"), mysql.TypeBlob}, {Bit{}, mysql.TypeBit}, {Hex{}, mysql.TypeVarchar}, {Time{Type: mysql.TypeDatetime}, mysql.TypeDatetime}, {Duration{}, mysql.TypeDuration}, {&MyDecimal{}, mysql.TypeNewDecimal}, {Enum{}, mysql.TypeEnum}, {Set{}, mysql.TypeSet}, {nil, mysql.TypeNull}, } for _, ca := range cases { var ft FieldType DefaultTypeForValue(ca.value, &ft) c.Assert(ft.Tp, Equals, ca.tp, Commentf("%v %v", ft, ca)) } }
util/types/field_type_test.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00017705989012029022, 0.00017156444664578885, 0.0001662497961660847, 0.00017238533473573625, 0.0000033563885608600685 ]
{ "id": 1, "code_window": [ "\n", "\t\t\tparamTypes = data[pos : pos+(numParams<<1)]\n", "\t\t\tpos += (numParams << 1)\n", "\t\t\tparamValues = data[pos:]\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t\t// Just the first StmtExecute packet contain parameters type,\n", "\t\t\t// we need save it for further use.\n", "\t\t\tstmt.SetParamsType(paramTypes)\n", "\t\t} else {\n", "\t\t\tparamValues = data[pos+1:]\n" ], "file_path": "server/conn_stmt.go", "type": "add", "edit_start_line_idx": 153 }
// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package server import ( "fmt" "github.com/pingcap/tidb/util/types" ) // IDriver opens IContext. type IDriver interface { // OpenCtx opens an IContext with connection id, client capability, collation and dbname. OpenCtx(connID uint64, capability uint32, collation uint8, dbname string) (IContext, error) } // IContext is the interface to execute command. type IContext interface { // Status returns server status code. Status() uint16 // LastInsertID returns last inserted ID. LastInsertID() uint64 // AffectedRows returns affected rows of last executed command. AffectedRows() uint64 // Value returns the value associated with this context for key. Value(key fmt.Stringer) interface{} // SetValue saves a value associated with this context for key. SetValue(key fmt.Stringer, value interface{}) // CommitTxn commits the transaction operations. CommitTxn() error // RollbackTxn undoes the transaction operations. RollbackTxn() error // WarningCount returns warning count of last executed command. WarningCount() uint16 // CurrentDB returns current DB. CurrentDB() string // Execute executes a SQL statement. Execute(sql string) ([]ResultSet, error) // SetClientCapability sets client capability flags SetClientCapability(uint32) // Prepare prepares a statement. Prepare(sql string) (statement IStatement, columns, params []*ColumnInfo, err error) // GetStatement gets IStatement by statement ID. GetStatement(stmtID int) IStatement // FieldList returns columns of a table. FieldList(tableName string) (columns []*ColumnInfo, err error) // Close closes the IContext. Close() error // Auth verifies user's authentication. Auth(user string, auth []byte, salt []byte) bool } // IStatement is the interface to use a prepared statement. type IStatement interface { // ID returns statement ID ID() int // Execute executes the statement. Execute(args ...interface{}) (ResultSet, error) // AppendParam appends parameter to the statement. AppendParam(paramID int, data []byte) error // NumParams returns number of parameters. NumParams() int // BoundParams returns bound parameters. BoundParams() [][]byte // Reset removes all bound parameters. Reset() // Close closes the statement. Close() error } // ResultSet is the result set of an query. type ResultSet interface { Columns() ([]*ColumnInfo, error) Next() ([]types.Datum, error) Close() error }
server/driver.go
1
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00352324265986681, 0.0007325720507651567, 0.00016563571989536285, 0.00016952271107584238, 0.0011985802557319403 ]
{ "id": 1, "code_window": [ "\n", "\t\t\tparamTypes = data[pos : pos+(numParams<<1)]\n", "\t\t\tpos += (numParams << 1)\n", "\t\t\tparamValues = data[pos:]\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t\t// Just the first StmtExecute packet contain parameters type,\n", "\t\t\t// we need save it for further use.\n", "\t\t\tstmt.SetParamsType(paramTypes)\n", "\t\t} else {\n", "\t\t\tparamValues = data[pos+1:]\n" ], "file_path": "server/conn_stmt.go", "type": "add", "edit_start_line_idx": 153 }
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package perfschema import ( "fmt" "reflect" "runtime" "sync/atomic" "time" "github.com/juju/errors" "github.com/ngaut/log" "github.com/pingcap/tidb/ast" "github.com/pingcap/tidb/util/types" ) // statementInfo defines statement instrument information. type statementInfo struct { // The registered statement key key uint64 // The name of the statement instrument to register name string } // StatementState provides temporary storage to a statement runtime statistics. // TODO: // 1. support statement digest. // 2. support prepared statement. type StatementState struct { // Connection identifier connID uint64 // Statement information info *statementInfo // Statement type stmtType reflect.Type // Source file and line number source string // Timer name timerName enumTimerName // Timer start timerStart int64 // Timer end timerEnd int64 // Locked time lockTime int64 // SQL statement string sqlText string // Current schema name schemaName string // Number of errors errNum uint32 // Number of warnings warnNum uint32 // Rows affected rowsAffected uint64 // Rows sent rowsSent uint64 // Rows examined rowsExamined uint64 // Metric, temporary tables created on disk createdTmpDiskTables uint32 // Metric, temproray tables created createdTmpTables uint32 // Metric, number of select full join selectFullJoin uint32 // Metric, number of select full range join selectFullRangeJoin uint32 // Metric, number of select range selectRange uint32 // Metric, number of select range check selectRangeCheck uint32 // Metric, number of select scan selectScan uint32 // Metric, number of sort merge passes sortMergePasses uint32 // Metric, number of sort merge sortRange uint32 // Metric, number of sort rows sortRows uint32 // Metric, number of sort scans sortScan uint32 // Metric, no index used flag noIndexUsed uint8 // Metric, no good index used flag noGoodIndexUsed uint8 } func (ps *perfSchema) RegisterStatement(category, name string, elem interface{}) { instrumentName := fmt.Sprintf("%s%s/%s", statementInstrumentPrefix, category, name) key, err := ps.addInstrument(instrumentName) if err != nil { // just ignore, do nothing else. log.Errorf("Unable to register instrument %s", instrumentName) return } ps.stmtInfos[reflect.TypeOf(elem)] = &statementInfo{ key: key, name: instrumentName, } } func (ps *perfSchema) StartStatement(sql string, connID uint64, callerName EnumCallerName, elem interface{}) *StatementState { if !enablePerfSchema { return nil } stmtType := reflect.TypeOf(elem) info, ok := ps.stmtInfos[stmtType] if !ok { // just ignore, do nothing else. log.Errorf("No instrument registered for statement %s", stmtType) return nil } // check and apply the configuration parameter in table setup_timers. timerName, err := ps.getTimerName(flagStatement) if err != nil { // just ignore, do nothing else. log.Error("Unable to check setup_timers table") return nil } var timerStart int64 switch timerName { case timerNameNanosec: timerStart = time.Now().UnixNano() case timerNameMicrosec: timerStart = time.Now().UnixNano() / int64(time.Microsecond) case timerNameMillisec: timerStart = time.Now().UnixNano() / int64(time.Millisecond) default: return nil } // TODO: check and apply the additional configuration parameters in: // - table setup_actors // - table setup_setup_consumers // - table setup_instruments // - table setup_objects var source string callerLock.RLock() source, ok = callerNames[callerName] callerLock.RUnlock() if !ok { _, fileName, fileLine, ok := runtime.Caller(1) if !ok { // just ignore, do nothing else. log.Error("Unable to get runtime.Caller(1)") return nil } source = fmt.Sprintf("%s:%d", fileName, fileLine) callerLock.Lock() callerNames[callerName] = source callerLock.Unlock() } return &StatementState{ connID: connID, info: info, stmtType: stmtType, source: source, timerName: timerName, timerStart: timerStart, sqlText: sql, } } func (ps *perfSchema) EndStatement(state *StatementState) { if !enablePerfSchema { return } if state == nil { return } switch state.timerName { case timerNameNanosec: state.timerEnd = time.Now().UnixNano() case timerNameMicrosec: state.timerEnd = time.Now().UnixNano() / int64(time.Microsecond) case timerNameMillisec: state.timerEnd = time.Now().UnixNano() / int64(time.Millisecond) default: return } log.Debugf("EndStatement: sql %s, connection id %d, type %s", state.sqlText, state.connID, state.stmtType) record := state2Record(state) err := ps.updateEventsStmtsCurrent(state.connID, record) if err != nil { log.Error("Unable to update events_statements_current table") } err = ps.appendEventsStmtsHistory(record) if err != nil { log.Errorf("Unable to append to events_statements_history table %v", errors.ErrorStack(err)) } } func state2Record(state *StatementState) []types.Datum { return types.MakeDatums( state.connID, // THREAD_ID state.info.key, // EVENT_ID nil, // END_EVENT_ID state.info.name, // EVENT_NAME state.source, // SOURCE uint64(state.timerStart), // TIMER_START uint64(state.timerEnd), // TIMER_END nil, // TIMER_WAIT uint64(state.lockTime), // LOCK_TIME state.sqlText, // SQL_TEXT nil, // DIGEST nil, // DIGEST_TEXT state.schemaName, // CURRENT_SCHEMA nil, // OBJECT_TYPE nil, // OBJECT_SCHEMA nil, // OBJECT_NAME nil, // OBJECT_INSTANCE_BEGIN nil, // MYSQL_ERRNO, nil, // RETURNED_SQLSTATE nil, // MESSAGE_TEXT uint64(state.errNum), // ERRORS uint64(state.warnNum), // WARNINGS state.rowsAffected, // ROWS_AFFECTED state.rowsSent, // ROWS_SENT state.rowsExamined, // ROWS_EXAMINED uint64(state.createdTmpDiskTables), // CREATED_TMP_DISK_TABLES uint64(state.createdTmpTables), // CREATED_TMP_TABLES uint64(state.selectFullJoin), // SELECT_FULL_JOIN uint64(state.selectFullRangeJoin), // SELECT_FULL_RANGE_JOIN uint64(state.selectRange), // SELECT_RANGE uint64(state.selectRangeCheck), // SELECT_RANGE_CHECK uint64(state.selectScan), // SELECT_SCAN uint64(state.sortMergePasses), // SORT_MERGE_PASSES uint64(state.sortRange), // SORT_RANGE uint64(state.sortRows), // SORT_ROWS uint64(state.sortScan), // SORT_SCAN uint64(state.noIndexUsed), // NO_INDEX_USED uint64(state.noGoodIndexUsed), // NO_GOOD_INDEX_USED nil, // NESTING_EVENT_ID nil, // NESTING_EVENT_TYPE nil, // NESTING_EVENT_LEVEL ) } func (ps *perfSchema) updateEventsStmtsCurrent(connID uint64, record []types.Datum) error { tbl := ps.mTables[TableStmtsCurrent] if tbl == nil { return nil } index := connID % uint64(currentElemMax) handle := atomic.LoadInt64(&ps.stmtHandles[index]) if handle == 0 { newHandle, err := tbl.AddRecord(nil, record) if err != nil { return errors.Trace(err) } atomic.StoreInt64(&ps.stmtHandles[index], newHandle) return nil } err := tbl.UpdateRecord(nil, handle, nil, record, nil) if err != nil { return errors.Trace(err) } return nil } func (ps *perfSchema) appendEventsStmtsHistory(record []types.Datum) error { tbl := ps.mTables[TableStmtsHistory] if tbl == nil { return nil } _, err := tbl.AddRecord(nil, record) if err != nil { return errors.Trace(err) } return nil } func (ps *perfSchema) registerStatements() { ps.stmtInfos = make(map[reflect.Type]*statementInfo) // Existing instrument names are the same as MySQL 5.7 ps.RegisterStatement("sql", "alter_table", (*ast.AlterTableStmt)(nil)) ps.RegisterStatement("sql", "begin", (*ast.BeginStmt)(nil)) ps.RegisterStatement("sql", "commit", (*ast.CommitStmt)(nil)) ps.RegisterStatement("sql", "create_db", (*ast.CreateDatabaseStmt)(nil)) ps.RegisterStatement("sql", "create_index", (*ast.CreateIndexStmt)(nil)) ps.RegisterStatement("sql", "create_table", (*ast.CreateTableStmt)(nil)) ps.RegisterStatement("sql", "create_user", (*ast.CreateUserStmt)(nil)) ps.RegisterStatement("sql", "deallocate", (*ast.DeallocateStmt)(nil)) ps.RegisterStatement("sql", "delete", (*ast.DeleteStmt)(nil)) ps.RegisterStatement("sql", "do", (*ast.DoStmt)(nil)) ps.RegisterStatement("sql", "drop_db", (*ast.DropDatabaseStmt)(nil)) ps.RegisterStatement("sql", "drop_table", (*ast.DropTableStmt)(nil)) ps.RegisterStatement("sql", "drop_index", (*ast.DropIndexStmt)(nil)) ps.RegisterStatement("sql", "execute", (*ast.ExecuteStmt)(nil)) ps.RegisterStatement("sql", "explain", (*ast.ExplainStmt)(nil)) ps.RegisterStatement("sql", "grant", (*ast.GrantStmt)(nil)) ps.RegisterStatement("sql", "insert", (*ast.InsertStmt)(nil)) ps.RegisterStatement("sql", "prepare", (*ast.PrepareStmt)(nil)) ps.RegisterStatement("sql", "rollback", (*ast.RollbackStmt)(nil)) ps.RegisterStatement("sql", "select", (*ast.SelectStmt)(nil)) ps.RegisterStatement("sql", "set", (*ast.SetStmt)(nil)) ps.RegisterStatement("sql", "set_password", (*ast.SetPwdStmt)(nil)) ps.RegisterStatement("sql", "show", (*ast.ShowStmt)(nil)) ps.RegisterStatement("sql", "truncate", (*ast.TruncateTableStmt)(nil)) ps.RegisterStatement("sql", "union", (*ast.UnionStmt)(nil)) ps.RegisterStatement("sql", "update", (*ast.UpdateStmt)(nil)) ps.RegisterStatement("sql", "use", (*ast.UseStmt)(nil)) ps.RegisterStatement("sql", "analyze", (*ast.AnalyzeTableStmt)(nil)) }
perfschema/statement.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.0002221660251962021, 0.00017235400446224958, 0.0001643480354687199, 0.00017024176486302167, 0.000009303478691435885 ]
{ "id": 1, "code_window": [ "\n", "\t\t\tparamTypes = data[pos : pos+(numParams<<1)]\n", "\t\t\tpos += (numParams << 1)\n", "\t\t\tparamValues = data[pos:]\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t\t// Just the first StmtExecute packet contain parameters type,\n", "\t\t\t// we need save it for further use.\n", "\t\t\tstmt.SetParamsType(paramTypes)\n", "\t\t} else {\n", "\t\t\tparamValues = data[pos+1:]\n" ], "file_path": "server/conn_stmt.go", "type": "add", "edit_start_line_idx": 153 }
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package tikv import ( "fmt" "os" "strconv" "time" "github.com/juju/errors" "github.com/ngaut/log" "github.com/pingcap/kvproto/pkg/kvrpcpb" "github.com/pingcap/tidb" "github.com/pingcap/tidb/context" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/store/tikv/oracle" "github.com/pingcap/tidb/util/sqlexec" goctx "golang.org/x/net/context" ) // GCWorker periodically triggers GC process on tikv server. type GCWorker struct { uuid string desc string store *tikvStore session tidb.Session gcIsRunning bool lastFinish time.Time quit chan struct{} done chan error } // NewGCWorker creates a GCWorker instance. func NewGCWorker(store kv.Storage) (*GCWorker, error) { session, err := tidb.CreateSession(store) if err != nil { return nil, errors.Trace(err) } ver, err := store.CurrentVersion() if err != nil { return nil, errors.Trace(err) } hostName, err := os.Hostname() if err != nil { hostName = "unknown" } worker := &GCWorker{ uuid: strconv.FormatUint(ver.Ver, 16), desc: fmt.Sprintf("host:%s, pid:%d, start at %s", hostName, os.Getpid(), time.Now()), store: store.(*tikvStore), session: session, gcIsRunning: false, lastFinish: time.Now(), quit: make(chan struct{}), done: make(chan error), } go worker.start() return worker, nil } // Close stops backgroud goroutines. func (w *GCWorker) Close() { close(w.quit) } const ( gcTimeFormat = "20060102-15:04:05 -0700 MST" gcWorkerTickInterval = time.Minute gcWorkerLease = time.Minute * 2 gcLeaderUUIDKey = "tikv_gc_leader_uuid" gcLeaderDescKey = "tikv_gc_leader_desc" gcLeaderLeaseKey = "tikv_gc_leader_lease" gcLastRunTimeKey = "tikv_gc_last_run_time" gcRunIntervalKey = "tikv_gc_run_interval" gcDefaultRunInterval = time.Minute * 10 gcWaitTime = time.Minute * 10 gcLifeTimeKey = "tikv_gc_life_time" gcDefaultLifeTime = time.Minute * 10 gcSafePointKey = "tikv_gc_safe_point" ) var gcVariableComments = map[string]string{ gcLeaderUUIDKey: "Current GC worker leader UUID. (DO NOT EDIT)", gcLeaderDescKey: "Host name and pid of current GC leader. (DO NOT EDIT)", gcLeaderLeaseKey: "Current GC worker leader lease. (DO NOT EDIT)", gcLastRunTimeKey: "The time when last GC starts. (DO NOT EDIT)", gcRunIntervalKey: "GC run interval, at least 10m, in Go format.", gcLifeTimeKey: "All versions within life time will not be collected by GC, at least 10m, in Go format.", gcSafePointKey: "All versions after safe point can be accessed. (DO NOT EDIT)", } func (w *GCWorker) start() { log.Infof("[gc worker] %s start.", w.uuid) ticker := time.NewTicker(gcWorkerTickInterval) for { select { case <-ticker.C: isLeader, err := w.checkLeader() if err != nil { log.Warnf("[gc worker] check leader err: %v", err) break } if isLeader { err = w.leaderTick() if err != nil { log.Warnf("[gc worker] leader tick err: %v", err) } } case err := <-w.done: w.gcIsRunning = false w.lastFinish = time.Now() if err != nil { log.Errorf("[gc worker] runGCJob error: %v", err) break } case <-w.quit: log.Infof("[gc worker] (%s) quit.", w.uuid) return } } } // Leader of GC worker checks if it should start a GC job every tick. func (w *GCWorker) leaderTick() error { if w.gcIsRunning { return nil } // When the worker is just started, or an old GC job has just finished, // wait a while before starting a new job. if time.Since(w.lastFinish) < gcWaitTime { return nil } ok, safePoint, err := w.prepare() if err != nil || !ok { return errors.Trace(err) } w.gcIsRunning = true log.Infof("[gc worker] %s starts GC job, safePoint: %v", w.uuid, safePoint) go w.runGCJob(safePoint) return nil } // prepare checks required conditions for starting a GC job. It returns a bool // that indicates whether the GC job should start and the new safePoint. func (w *GCWorker) prepare() (bool, uint64, error) { now, err := w.getOracleTime() if err != nil { return false, 0, errors.Trace(err) } ok, err := w.checkGCInterval(now) if err != nil || !ok { return false, 0, errors.Trace(err) } newSafePoint, err := w.calculateNewSafePoint(now) if err != nil || newSafePoint == nil { return false, 0, errors.Trace(err) } err = w.saveTime(gcLastRunTimeKey, now) if err != nil { return false, 0, errors.Trace(err) } err = w.saveTime(gcSafePointKey, *newSafePoint) if err != nil { return false, 0, errors.Trace(err) } return true, oracle.ComposeTS(oracle.GetPhysical(*newSafePoint), 0), nil } func (w *GCWorker) getOracleTime() (time.Time, error) { currentVer, err := w.store.CurrentVersion() if err != nil { return time.Time{}, errors.Trace(err) } physical := oracle.ExtractPhysical(currentVer.Ver) sec, nsec := physical/1e3, (physical%1e3)*1e6 return time.Unix(sec, nsec), nil } func (w *GCWorker) checkGCInterval(now time.Time) (bool, error) { runInterval, err := w.loadDurationWithDefault(gcRunIntervalKey, gcDefaultRunInterval) if err != nil { return false, errors.Trace(err) } gcConfigGauge.WithLabelValues(gcRunIntervalKey).Set(float64(runInterval.Seconds())) lastRun, err := w.loadTime(gcLastRunTimeKey) if err != nil { return false, errors.Trace(err) } if lastRun != nil && lastRun.Add(*runInterval).After(now) { return false, nil } return true, nil } func (w *GCWorker) calculateNewSafePoint(now time.Time) (*time.Time, error) { lifeTime, err := w.loadDurationWithDefault(gcLifeTimeKey, gcDefaultLifeTime) if err != nil { return nil, errors.Trace(err) } gcConfigGauge.WithLabelValues(gcLifeTimeKey).Set(float64(lifeTime.Seconds())) lastSafePoint, err := w.loadTime(gcSafePointKey) if err != nil { return nil, errors.Trace(err) } safePoint := now.Add(-*lifeTime) // We should never decrease safePoint. if lastSafePoint != nil && safePoint.Before(*lastSafePoint) { return nil, nil } return &safePoint, nil } func (w *GCWorker) runGCJob(safePoint uint64) { gcWorkerCounter.WithLabelValues("run_job").Inc() err := w.resolveLocks(safePoint) if err != nil { w.done <- errors.Trace(err) return } err = w.DoGC(safePoint) if err != nil { w.done <- errors.Trace(err) } w.done <- nil } func (w *GCWorker) resolveLocks(safePoint uint64) error { gcWorkerCounter.WithLabelValues("resolve_locks").Inc() req := &kvrpcpb.Request{ Type: kvrpcpb.MessageType_CmdScanLock, CmdScanLockReq: &kvrpcpb.CmdScanLockRequest{ MaxVersion: safePoint, }, } bo := NewBackoffer(gcResolveLockMaxBackoff, goctx.Background()) log.Infof("[gc worker] %s start resolve locks, safePoint: %v.", w.uuid, safePoint) startTime := time.Now() regions, totalResolvedLocks := 0, 0 var key []byte for { select { case <-w.quit: return errors.New("[gc worker] gc job canceled") default: } loc, err := w.store.regionCache.LocateKey(bo, key) if err != nil { return errors.Trace(err) } resp, err := w.store.SendKVReq(bo, req, loc.Region, readTimeoutMedium) if err != nil { return errors.Trace(err) } if regionErr := resp.GetRegionError(); regionErr != nil { err = bo.Backoff(boRegionMiss, errors.New(regionErr.String())) if err != nil { return errors.Trace(err) } continue } locksResp := resp.GetCmdScanLockResp() if locksResp == nil { return errors.Trace(errBodyMissing) } if locksResp.GetError() != nil { return errors.Errorf("unexpected scanlock error: %s", locksResp) } locksInfo := locksResp.GetLocks() locks := make([]*Lock, len(locksInfo)) for i := range locksInfo { locks[i] = newLock(locksInfo[i]) } ok, err1 := w.store.lockResolver.ResolveLocks(bo, locks) if err1 != nil { return errors.Trace(err1) } if !ok { err = bo.Backoff(boTxnLock, errors.Errorf("remain locks: %d", len(locks))) if err != nil { return errors.Trace(err) } continue } regions++ totalResolvedLocks += len(locks) key = loc.EndKey if len(key) == 0 { break } } log.Infof("[gc worker] %s finish resolve locks, safePoint: %v, regions: %v, total resolved: %v, cost time: %s", w.uuid, safePoint, regions, totalResolvedLocks, time.Since(startTime)) gcHistogram.WithLabelValues("resolve_locks").Observe(time.Since(startTime).Seconds()) return nil } // DoGC sends GC command to KV, it is exported for testing purpose. func (w *GCWorker) DoGC(safePoint uint64) error { gcWorkerCounter.WithLabelValues("do_gc").Inc() req := &kvrpcpb.Request{ Type: kvrpcpb.MessageType_CmdGC, CmdGcReq: &kvrpcpb.CmdGCRequest{ SafePoint: safePoint, }, } bo := NewBackoffer(gcMaxBackoff, goctx.Background()) log.Infof("[gc worker] %s start gc, safePoint: %v.", w.uuid, safePoint) startTime := time.Now() regions := 0 var key []byte for { select { case <-w.quit: return errors.New("[gc worker] gc job canceled") default: } loc, err := w.store.regionCache.LocateKey(bo, key) if err != nil { return errors.Trace(err) } resp, err := w.store.SendKVReq(bo, req, loc.Region, readTimeoutLong) if err != nil { return errors.Trace(err) } if regionErr := resp.GetRegionError(); regionErr != nil { err = bo.Backoff(boRegionMiss, errors.New(regionErr.String())) if err != nil { return errors.Trace(err) } continue } gcResp := resp.GetCmdGcResp() if gcResp == nil { return errors.Trace(errBodyMissing) } if gcResp.GetError() != nil { return errors.Errorf("unexpected gc error: %s", gcResp.GetError()) } regions++ key = loc.EndKey if len(key) == 0 { break } } log.Infof("[gc worker] %s finish gc, safePoint: %v, regions: %v, cost time: %s", w.uuid, safePoint, regions, time.Since(startTime)) gcHistogram.WithLabelValues("do_gc").Observe(time.Since(startTime).Seconds()) return nil } func (w *GCWorker) checkLeader() (bool, error) { gcWorkerCounter.WithLabelValues("check_leader").Inc() _, err := w.session.Execute("BEGIN") if err != nil { return false, errors.Trace(err) } leader, err := w.loadValueFromSysTable(gcLeaderUUIDKey) if err != nil { w.session.Execute("ROLLBACK") return false, errors.Trace(err) } log.Debugf("[gc worker] got leader: %s", leader) if leader == w.uuid { err = w.saveTime(gcLeaderLeaseKey, time.Now().Add(gcWorkerLease)) if err != nil { w.session.Execute("ROLLBACK") return false, errors.Trace(err) } _, err = w.session.Execute("COMMIT") if err != nil { return false, errors.Trace(err) } return true, nil } lease, err := w.loadTime(gcLeaderLeaseKey) if err != nil { return false, errors.Trace(err) } if lease == nil || lease.Before(time.Now()) { log.Debugf("[gc worker] register %s as leader", w.uuid) gcWorkerCounter.WithLabelValues("register_leader").Inc() err = w.saveValueToSysTable(gcLeaderUUIDKey, w.uuid) if err != nil { w.session.Execute("ROLLBACK") return false, errors.Trace(err) } err = w.saveValueToSysTable(gcLeaderDescKey, w.desc) if err != nil { w.session.Execute("ROLLBACK") return false, errors.Trace(err) } err = w.saveTime(gcLeaderLeaseKey, time.Now().Add(gcWorkerLease)) if err != nil { w.session.Execute("ROLLBACK") return false, errors.Trace(err) } _, err = w.session.Execute("COMMIT") if err != nil { return false, errors.Trace(err) } return true, nil } w.session.Execute("ROLLBACK") return false, nil } func (w *GCWorker) saveTime(key string, t time.Time) error { err := w.saveValueToSysTable(key, t.Format(gcTimeFormat)) return errors.Trace(err) } func (w *GCWorker) loadTime(key string) (*time.Time, error) { str, err := w.loadValueFromSysTable(key) if err != nil { return nil, errors.Trace(err) } if str == "" { return nil, nil } t, err := time.Parse(gcTimeFormat, str) if err != nil { return nil, errors.Trace(err) } return &t, nil } func (w *GCWorker) saveDuration(key string, d time.Duration) error { err := w.saveValueToSysTable(key, d.String()) return errors.Trace(err) } func (w *GCWorker) loadDuration(key string) (*time.Duration, error) { str, err := w.loadValueFromSysTable(key) if err != nil { return nil, errors.Trace(err) } if str == "" { return nil, nil } d, err := time.ParseDuration(str) if err != nil { return nil, errors.Trace(err) } return &d, nil } func (w *GCWorker) loadDurationWithDefault(key string, def time.Duration) (*time.Duration, error) { d, err := w.loadDuration(key) if err != nil { return nil, errors.Trace(err) } if d == nil { err = w.saveDuration(key, def) if err != nil { return nil, errors.Trace(err) } return &def, nil } return d, nil } func (w *GCWorker) loadValueFromSysTable(key string) (string, error) { stmt := fmt.Sprintf(`SELECT (variable_value) FROM mysql.tidb WHERE variable_name='%s' FOR UPDATE`, key) restrictExecutor := w.session.(sqlexec.RestrictedSQLExecutor) ctx := w.session.(context.Context) rs, err := restrictExecutor.ExecRestrictedSQL(ctx, stmt) if err != nil { return "", errors.Trace(err) } row, err := rs.Next() if err != nil { return "", errors.Trace(err) } if row == nil { log.Debugf("[gc worker] load kv, %s:nil", key) return "", nil } value := row.Data[0].GetString() log.Debugf("[gc worker] load kv, %s:%s", key, value) return value, nil } func (w *GCWorker) saveValueToSysTable(key, value string) error { stmt := fmt.Sprintf(`INSERT INTO mysql.tidb VALUES ('%[1]s', '%[2]s', '%[3]s') ON DUPLICATE KEY UPDATE variable_value = '%[2]s', comment = '%[3]s'`, key, value, gcVariableComments[key]) restrictExecutor := w.session.(sqlexec.RestrictedSQLExecutor) ctx := w.session.(context.Context) _, err := restrictExecutor.ExecRestrictedSQL(ctx, stmt) log.Debugf("[gc worker] save kv, %s:%s %v", key, value, err) return errors.Trace(err) }
store/tikv/gc_worker.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.0007520305225625634, 0.0001861041528172791, 0.00016498818877153099, 0.00017284661589656025, 0.00008071156480582431 ]
{ "id": 1, "code_window": [ "\n", "\t\t\tparamTypes = data[pos : pos+(numParams<<1)]\n", "\t\t\tpos += (numParams << 1)\n", "\t\t\tparamValues = data[pos:]\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t\t// Just the first StmtExecute packet contain parameters type,\n", "\t\t\t// we need save it for further use.\n", "\t\t\tstmt.SetParamsType(paramTypes)\n", "\t\t} else {\n", "\t\t\tparamValues = data[pos+1:]\n" ], "file_path": "server/conn_stmt.go", "type": "add", "edit_start_line_idx": 153 }
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package expression import ( "strings" "github.com/juju/errors" "github.com/pingcap/tidb/ast" ) // Schema stands for the row schema get from input. type Schema struct { Columns []*Column } // String implements fmt.Stringer interface. func (s Schema) String() string { colStrs := make([]string, 0, len(s.Columns)) for _, col := range s.Columns { colStrs = append(colStrs, col.String()) } return "[" + strings.Join(colStrs, ",") + "]" } // Clone copies the total schema. func (s Schema) Clone() Schema { result := NewSchema(make([]*Column, 0, s.Len())) for _, col := range s.Columns { newCol := *col result.Append(&newCol) } return result } // FindColumn finds an Column from schema for a ast.ColumnName. It compares the db/table/column names. // If there are more than one result, it will raise ambiguous error. func (s Schema) FindColumn(astCol *ast.ColumnName) (*Column, error) { dbName, tblName, colName := astCol.Schema, astCol.Table, astCol.Name idx := -1 for i, col := range s.Columns { if (dbName.L == "" || dbName.L == col.DBName.L) && (tblName.L == "" || tblName.L == col.TblName.L) && (colName.L == col.ColName.L) { if idx == -1 { idx = i } else { return nil, errors.Errorf("Column %s is ambiguous", col.String()) } } } if idx == -1 { return nil, nil } return s.Columns[idx], nil } // InitColumnIndices sets indices for columns in schema. func (s Schema) InitColumnIndices() { for i, c := range s.Columns { c.Index = i } } // RetrieveColumn retrieves column in expression from the columns in schema. func (s Schema) RetrieveColumn(col *Column) *Column { index := s.GetColumnIndex(col) if index != -1 { return s.Columns[index] } return nil } // GetColumnIndex finds the index for a column. func (s Schema) GetColumnIndex(col *Column) int { for i, c := range s.Columns { if c.FromID == col.FromID && c.Position == col.Position { return i } } return -1 } // Len returns the number of columns in schema. func (s Schema) Len() int { return len(s.Columns) } // Append append new column to the columns stored in schema. func (s *Schema) Append(col *Column) { s.Columns = append(s.Columns, col) } // MergeSchema will merge two schema into one schema. func MergeSchema(lSchema, rSchema Schema) Schema { return NewSchema(append(lSchema.Clone().Columns, rSchema.Clone().Columns...)) } // NewSchema returns a schema made by its parameter. func NewSchema(cols []*Column) Schema { return Schema{Columns: cols} }
expression/schema.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00040182951488532126, 0.00019747046462725848, 0.00016836771101225168, 0.00017543035210110247, 0.0000633571544312872 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\n", "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, paramTypes, paramValues)\n", "\t\tif err != nil {\n", "\t\t\treturn errors.Trace(err)\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, stmt.GetParamsType(), paramValues)\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 155 }
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. // The MIT License (MIT) // // Copyright (c) 2014 wandoulabs // Copyright (c) 2014 siddontang // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package server import ( "encoding/binary" "math" "strconv" "github.com/juju/errors" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/util/hack" ) func (cc *clientConn) handleStmtPrepare(sql string) error { stmt, columns, params, err := cc.ctx.Prepare(sql) if err != nil { return errors.Trace(err) } data := make([]byte, 4, 128) //status ok data = append(data, 0) //stmt id data = append(data, dumpUint32(uint32(stmt.ID()))...) //number columns data = append(data, dumpUint16(uint16(len(columns)))...) //number params data = append(data, dumpUint16(uint16(len(params)))...) //filter [00] data = append(data, 0) //warning count data = append(data, 0, 0) //TODO support warning count if err := cc.writePacket(data); err != nil { return errors.Trace(err) } if len(params) > 0 { for i := 0; i < len(params); i++ { data = data[0:4] data = append(data, params[i].Dump(cc.alloc)...) if err := cc.writePacket(data); err != nil { return errors.Trace(err) } } if err := cc.writeEOF(false); err != nil { return errors.Trace(err) } } if len(columns) > 0 { for i := 0; i < len(columns); i++ { data = data[0:4] data = append(data, columns[i].Dump(cc.alloc)...) if err := cc.writePacket(data); err != nil { return errors.Trace(err) } } if err := cc.writeEOF(false); err != nil { return errors.Trace(err) } } return errors.Trace(cc.flush()) } func (cc *clientConn) handleStmtExecute(data []byte) (err error) { if len(data) < 9 { return mysql.ErrMalformPacket } pos := 0 stmtID := binary.LittleEndian.Uint32(data[0:4]) pos += 4 stmt := cc.ctx.GetStatement(int(stmtID)) if stmt == nil { return mysql.NewErr(mysql.ErrUnknownStmtHandler, strconv.FormatUint(uint64(stmtID), 10), "stmt_execute") } flag := data[pos] pos++ //now we only support CURSOR_TYPE_NO_CURSOR flag if flag != 0 { return mysql.NewErrf(mysql.ErrUnknown, "unsupported flag %d", flag) } //skip iteration-count, always 1 pos += 4 var ( nullBitmaps []byte paramTypes []byte paramValues []byte ) numParams := stmt.NumParams() args := make([]interface{}, numParams) if numParams > 0 { nullBitmapLen := (numParams + 7) >> 3 if len(data) < (pos + nullBitmapLen + 1) { return mysql.ErrMalformPacket } nullBitmaps = data[pos : pos+nullBitmapLen] pos += nullBitmapLen //new param bound flag if data[pos] == 1 { pos++ if len(data) < (pos + (numParams << 1)) { return mysql.ErrMalformPacket } paramTypes = data[pos : pos+(numParams<<1)] pos += (numParams << 1) paramValues = data[pos:] } err = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, paramTypes, paramValues) if err != nil { return errors.Trace(err) } } rs, err := stmt.Execute(args...) if err != nil { return errors.Trace(err) } if rs == nil { return errors.Trace(cc.writeOK()) } return errors.Trace(cc.writeResultset(rs, true, false)) } func parseStmtArgs(args []interface{}, boundParams [][]byte, nullBitmap, paramTypes, paramValues []byte) (err error) { pos := 0 var v []byte var n int var isNull bool for i := 0; i < len(args); i++ { if nullBitmap[i>>3]&(1<<(uint(i)%8)) > 0 { args[i] = nil continue } if boundParams[i] != nil { args[i] = boundParams[i] continue } if (i<<1)+1 >= len(paramTypes) { return mysql.ErrMalformPacket } tp := paramTypes[i<<1] isUnsigned := (paramTypes[(i<<1)+1] & 0x80) > 0 switch tp { case mysql.TypeNull: args[i] = nil continue case mysql.TypeTiny: if len(paramValues) < (pos + 1) { err = mysql.ErrMalformPacket return } if isUnsigned { args[i] = uint64(paramValues[pos]) } else { args[i] = int64(paramValues[pos]) } pos++ continue case mysql.TypeShort, mysql.TypeYear: if len(paramValues) < (pos + 2) { err = mysql.ErrMalformPacket return } valU16 := binary.LittleEndian.Uint16(paramValues[pos : pos+2]) if isUnsigned { args[i] = uint64(valU16) } else { args[i] = int64(valU16) } pos += 2 continue case mysql.TypeInt24, mysql.TypeLong: if len(paramValues) < (pos + 4) { err = mysql.ErrMalformPacket return } valU32 := binary.LittleEndian.Uint32(paramValues[pos : pos+4]) if isUnsigned { args[i] = uint64(valU32) } else { args[i] = int64(valU32) } pos += 4 continue case mysql.TypeLonglong: if len(paramValues) < (pos + 8) { err = mysql.ErrMalformPacket return } valU64 := binary.LittleEndian.Uint64(paramValues[pos : pos+8]) if isUnsigned { args[i] = valU64 } else { args[i] = int64(valU64) } pos += 8 continue case mysql.TypeFloat: if len(paramValues) < (pos + 4) { err = mysql.ErrMalformPacket return } args[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(paramValues[pos : pos+4]))) pos += 4 continue case mysql.TypeDouble: if len(paramValues) < (pos + 8) { err = mysql.ErrMalformPacket return } args[i] = math.Float64frombits(binary.LittleEndian.Uint64(paramValues[pos : pos+8])) pos += 8 continue case mysql.TypeDecimal, mysql.TypeNewDecimal, mysql.TypeVarchar, mysql.TypeBit, mysql.TypeEnum, mysql.TypeSet, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob, mysql.TypeBlob, mysql.TypeVarString, mysql.TypeString, mysql.TypeGeometry, mysql.TypeDate, mysql.TypeNewDate, mysql.TypeTimestamp, mysql.TypeDatetime, mysql.TypeDuration: if len(paramValues) < (pos + 1) { err = mysql.ErrMalformPacket return } v, isNull, n, err = parseLengthEncodedBytes(paramValues[pos:]) pos += n if err != nil { return } if !isNull { args[i] = hack.String(v) } else { args[i] = nil } continue default: err = errUnknownFieldType.Gen("stmt unknown field type %d", tp) return } } return } func (cc *clientConn) handleStmtClose(data []byte) (err error) { if len(data) < 4 { return } stmtID := int(binary.LittleEndian.Uint32(data[0:4])) stmt := cc.ctx.GetStatement(stmtID) if stmt != nil { return errors.Trace(stmt.Close()) } return } func (cc *clientConn) handleStmtSendLongData(data []byte) (err error) { if len(data) < 6 { return mysql.ErrMalformPacket } stmtID := int(binary.LittleEndian.Uint32(data[0:4])) stmt := cc.ctx.GetStatement(stmtID) if stmt == nil { return mysql.NewErr(mysql.ErrUnknownStmtHandler, strconv.Itoa(stmtID), "stmt_send_longdata") } paramID := int(binary.LittleEndian.Uint16(data[4:6])) return stmt.AppendParam(paramID, data[6:]) } func (cc *clientConn) handleStmtReset(data []byte) (err error) { if len(data) < 4 { return mysql.ErrMalformPacket } stmtID := int(binary.LittleEndian.Uint32(data[0:4])) stmt := cc.ctx.GetStatement(stmtID) if stmt == nil { return mysql.NewErr(mysql.ErrUnknownStmtHandler, strconv.Itoa(stmtID), "stmt_reset") } stmt.Reset() return cc.writeOK() } // See https://dev.mysql.com/doc/internals/en/com-set-option.html func (cc *clientConn) handleSetOption(data []byte) (err error) { if len(data) < 2 { return mysql.ErrMalformPacket } switch binary.LittleEndian.Uint16(data[:2]) { case 0: cc.capability |= mysql.ClientMultiStatements cc.ctx.SetClientCapability(cc.capability) case 1: cc.capability &^= mysql.ClientMultiStatements cc.ctx.SetClientCapability(cc.capability) default: return mysql.ErrMalformPacket } if err = cc.writeEOF(false); err != nil { return errors.Trace(err) } return errors.Trace(cc.flush()) }
server/conn_stmt.go
1
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.9963359832763672, 0.08792295306921005, 0.00016659082029946148, 0.0009558225865475833, 0.25055575370788574 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\n", "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, paramTypes, paramValues)\n", "\t\tif err != nil {\n", "\t\t\treturn errors.Trace(err)\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, stmt.GetParamsType(), paramValues)\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 155 }
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package // // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql import ( "fmt" "io" "os" "strings" ) var ( fileRegister map[string]bool readerRegister map[string]func() io.Reader ) // RegisterLocalFile adds the given file to the file whitelist, // so that it can be used by "LOAD DATA LOCAL INFILE <filepath>". // Alternatively you can allow the use of all local files with // the DSN parameter 'allowAllFiles=true' // // filePath := "/home/gopher/data.csv" // mysql.RegisterLocalFile(filePath) // err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") // if err != nil { // ... // func RegisterLocalFile(filePath string) { // lazy map init if fileRegister == nil { fileRegister = make(map[string]bool) } fileRegister[strings.Trim(filePath, `"`)] = true } // DeregisterLocalFile removes the given filepath from the whitelist. func DeregisterLocalFile(filePath string) { delete(fileRegister, strings.Trim(filePath, `"`)) } // RegisterReaderHandler registers a handler function which is used // to receive a io.Reader. // The Reader can be used by "LOAD DATA LOCAL INFILE Reader::<name>". // If the handler returns a io.ReadCloser Close() is called when the // request is finished. // // mysql.RegisterReaderHandler("data", func() io.Reader { // var csvReader io.Reader // Some Reader that returns CSV data // ... // Open Reader here // return csvReader // }) // err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") // if err != nil { // ... // func RegisterReaderHandler(name string, handler func() io.Reader) { // lazy map init if readerRegister == nil { readerRegister = make(map[string]func() io.Reader) } readerRegister[name] = handler } // DeregisterReaderHandler removes the ReaderHandler function with // the given name from the registry. func DeregisterReaderHandler(name string) { delete(readerRegister, name) } func deferredClose(err *error, closer io.Closer) { closeErr := closer.Close() if *err == nil { *err = closeErr } } func (mc *mysqlConn) handleInFileRequest(name string) (err error) { var rdr io.Reader var data []byte if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader // The server might return an an absolute path. See issue #355. name = name[idx+8:] if handler, inMap := readerRegister[name]; inMap { rdr = handler() if rdr != nil { data = make([]byte, 4+mc.maxWriteSize) if cl, ok := rdr.(io.Closer); ok { defer deferredClose(&err, cl) } } else { err = fmt.Errorf("Reader '%s' is <nil>", name) } } else { err = fmt.Errorf("Reader '%s' is not registered", name) } } else { // File name = strings.Trim(name, `"`) if mc.cfg.allowAllFiles || fileRegister[name] { var file *os.File var fi os.FileInfo if file, err = os.Open(name); err == nil { defer deferredClose(&err, file) // get file size if fi, err = file.Stat(); err == nil { rdr = file if fileSize := int(fi.Size()); fileSize <= mc.maxWriteSize { data = make([]byte, 4+fileSize) } else if fileSize <= mc.maxPacketAllowed { data = make([]byte, 4+mc.maxWriteSize) } else { err = fmt.Errorf("Local File '%s' too large: Size: %d, Max: %d", name, fileSize, mc.maxPacketAllowed) } } } } else { err = fmt.Errorf("Local File '%s' is not registered. Use the DSN parameter 'allowAllFiles=true' to allow all files", name) } } // send content packets if err == nil { var n int for err == nil { n, err = rdr.Read(data[4:]) if n > 0 { if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { return ioErr } } } if err == io.EOF { err = nil } } // send empty packet (termination) if data == nil { data = make([]byte, 4) } if ioErr := mc.writePacket(data[:4]); ioErr != nil { return ioErr } // read OK packet if err == nil { return mc.readResultOK() } else { mc.readPacket() } return err }
_vendor/src/github.com/go-sql-driver/mysql/infile.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00045878515811637044, 0.00021669799752999097, 0.00016255587979685515, 0.00017449408187530935, 0.0000777673049014993 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\n", "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, paramTypes, paramValues)\n", "\t\tif err != nil {\n", "\t\t\treturn errors.Trace(err)\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, stmt.GetParamsType(), paramValues)\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 155 }
// Copyright 2013 The ql Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSES/QL-LICENSE file. // Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package ddl import ( "fmt" "sync" "time" "github.com/juju/errors" "github.com/ngaut/log" "github.com/pingcap/tidb/ast" "github.com/pingcap/tidb/context" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/meta" "github.com/pingcap/tidb/model" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/terror" "github.com/twinj/uuid" ) var ( // errWorkerClosed means we have already closed the DDL worker. errInvalidWorker = terror.ClassDDL.New(codeInvalidWorker, "invalid worker") // errNotOwner means we are not owner and can't handle DDL jobs. errNotOwner = terror.ClassDDL.New(codeNotOwner, "not Owner") errInvalidDDLJob = terror.ClassDDL.New(codeInvalidDDLJob, "invalid ddl job") errInvalidBgJob = terror.ClassDDL.New(codeInvalidBgJob, "invalid background job") errInvalidJobFlag = terror.ClassDDL.New(codeInvalidJobFlag, "invalid job flag") errRunMultiSchemaChanges = terror.ClassDDL.New(codeRunMultiSchemaChanges, "can't run multi schema change") errWaitReorgTimeout = terror.ClassDDL.New(codeWaitReorgTimeout, "wait for reorganization timeout") errInvalidStoreVer = terror.ClassDDL.New(codeInvalidStoreVer, "invalid storage current version") // We don't support dropping column with index covered now. errCantDropColWithIndex = terror.ClassDDL.New(codeCantDropColWithIndex, "can't drop column with index") errUnsupportedAddColumn = terror.ClassDDL.New(codeUnsupportedAddColumn, "unsupported add column") errUnsupportedModifyColumn = terror.ClassDDL.New(codeUnsupportedModifyColumn, "unsupported modify column") errUnsupportedPKHandle = terror.ClassDDL.New(codeUnsupportedDropPKHandle, "unsupported drop integer primary key") errBlobKeyWithoutLength = terror.ClassDDL.New(codeBlobKeyWithoutLength, "index for BLOB/TEXT column must specificate a key length") errIncorrectPrefixKey = terror.ClassDDL.New(codeIncorrectPrefixKey, "Incorrect prefix key; the used key part isn't a string, the used length is longer than the key part, or the storage engine doesn't support unique prefix keys") errTooLongKey = terror.ClassDDL.New(codeTooLongKey, fmt.Sprintf("Specified key was too long; max key length is %d bytes", maxPrefixLength)) errKeyColumnDoesNotExits = terror.ClassDDL.New(codeKeyColumnDoesNotExits, "this key column doesn't exist in table") errDupKeyName = terror.ClassDDL.New(codeDupKeyName, "duplicate key name") errWrongDBName = terror.ClassDDL.New(codeWrongDBName, "Incorrect database name '%s'") errWrongTableName = terror.ClassDDL.New(codeWrongTableName, "Incorrect table name '%s'") // ErrInvalidDBState returns for invalid database state. ErrInvalidDBState = terror.ClassDDL.New(codeInvalidDBState, "invalid database state") // ErrInvalidTableState returns for invalid Table state. ErrInvalidTableState = terror.ClassDDL.New(codeInvalidTableState, "invalid table state") // ErrInvalidColumnState returns for invalid column state. ErrInvalidColumnState = terror.ClassDDL.New(codeInvalidColumnState, "invalid column state") // ErrInvalidIndexState returns for invalid index state. ErrInvalidIndexState = terror.ClassDDL.New(codeInvalidIndexState, "invalid index state") // ErrInvalidForeignKeyState returns for invalid foreign key state. ErrInvalidForeignKeyState = terror.ClassDDL.New(codeInvalidForeignKeyState, "invalid foreign key state") // ErrColumnBadNull returns for a bad null value. ErrColumnBadNull = terror.ClassDDL.New(codeBadNull, "column cann't be null") // ErrCantRemoveAllFields returns for deleting all columns. ErrCantRemoveAllFields = terror.ClassDDL.New(codeCantRemoveAllFields, "can't delete all columns with ALTER TABLE") // ErrCantDropFieldOrKey returns for dropping a non-existent field or key. ErrCantDropFieldOrKey = terror.ClassDDL.New(codeCantDropFieldOrKey, "can't drop field; check that column/key exists") // ErrInvalidOnUpdate returns for invalid ON UPDATE clause. ErrInvalidOnUpdate = terror.ClassDDL.New(codeInvalidOnUpdate, "invalid ON UPDATE clause for the column") // ErrTooLongIdent returns for too long name of database/table/column. ErrTooLongIdent = terror.ClassDDL.New(codeTooLongIdent, "Identifier name too long") ) // DDL is responsible for updating schema in data store and maintaining in-memory InfoSchema cache. type DDL interface { CreateSchema(ctx context.Context, name model.CIStr, charsetInfo *ast.CharsetOpt) error DropSchema(ctx context.Context, schema model.CIStr) error CreateTable(ctx context.Context, ident ast.Ident, cols []*ast.ColumnDef, constrs []*ast.Constraint, options []*ast.TableOption) error DropTable(ctx context.Context, tableIdent ast.Ident) (err error) CreateIndex(ctx context.Context, tableIdent ast.Ident, unique bool, indexName model.CIStr, columnNames []*ast.IndexColName) error DropIndex(ctx context.Context, tableIdent ast.Ident, indexName model.CIStr) error GetInformationSchema() infoschema.InfoSchema AlterTable(ctx context.Context, tableIdent ast.Ident, spec []*ast.AlterTableSpec) error TruncateTable(ctx context.Context, tableIdent ast.Ident) error // SetLease will reset the lease time for online DDL change, // it's a very dangerous function and you must guarantee that all servers have the same lease time. SetLease(lease time.Duration) // GetLease returns current schema lease time. GetLease() time.Duration // Stats returns the DDL statistics. Stats() (map[string]interface{}, error) // GetScope gets the status variables scope. GetScope(status string) variable.ScopeFlag // Stop stops DDL worker. Stop() error // Start starts DDL worker. Start() error } type ddl struct { m sync.RWMutex infoHandle *infoschema.Handle hook Callback hookMu sync.RWMutex store kv.Storage // Schema lease seconds. lease time.Duration uuid string ddlJobCh chan struct{} ddlJobDoneCh chan struct{} // Drop database/table job that runs in the background. bgJobCh chan struct{} // reorgDoneCh is for reorganization, if the reorganization job is done, // we will use this channel to notify outer. // TODO: Now we use goroutine to simulate reorganization jobs, later we may // use a persistent job list. reorgDoneCh chan error quitCh chan struct{} wait sync.WaitGroup } // NewDDL creates a new DDL. func NewDDL(store kv.Storage, infoHandle *infoschema.Handle, hook Callback, lease time.Duration) DDL { return newDDL(store, infoHandle, hook, lease) } func newDDL(store kv.Storage, infoHandle *infoschema.Handle, hook Callback, lease time.Duration) *ddl { if hook == nil { hook = &BaseCallback{} } d := &ddl{ infoHandle: infoHandle, hook: hook, store: store, lease: lease, uuid: uuid.NewV4().String(), ddlJobCh: make(chan struct{}, 1), ddlJobDoneCh: make(chan struct{}, 1), bgJobCh: make(chan struct{}, 1), } d.start() variable.RegisterStatistics(d) return d } func (d *ddl) Stop() error { d.m.Lock() defer d.m.Unlock() d.close() err := kv.RunInNewTxn(d.store, true, func(txn kv.Transaction) error { t := meta.NewMeta(txn) owner, err1 := t.GetDDLJobOwner() if err1 != nil { return errors.Trace(err1) } if owner == nil || owner.OwnerID != d.uuid { return nil } // DDL job's owner is me, clean it so other servers can complete it quickly. return t.SetDDLJobOwner(&model.Owner{}) }) if err != nil { return errors.Trace(err) } err = kv.RunInNewTxn(d.store, true, func(txn kv.Transaction) error { t := meta.NewMeta(txn) owner, err1 := t.GetBgJobOwner() if err1 != nil { return errors.Trace(err1) } if owner == nil || owner.OwnerID != d.uuid { return nil } // Background job's owner is me, clean it so other servers can complete it quickly. return t.SetBgJobOwner(&model.Owner{}) }) return errors.Trace(err) } func (d *ddl) Start() error { d.m.Lock() defer d.m.Unlock() if !d.isClosed() { return nil } d.start() return nil } func (d *ddl) start() { d.quitCh = make(chan struct{}) d.wait.Add(2) go d.onBackgroundWorker() go d.onDDLWorker() // For every start, we will send a fake job to let worker // check owner firstly and try to find whether a job exists and run. asyncNotify(d.ddlJobCh) asyncNotify(d.bgJobCh) } func (d *ddl) close() { if d.isClosed() { return } close(d.quitCh) d.wait.Wait() } func (d *ddl) isClosed() bool { select { case <-d.quitCh: return true default: return false } } func (d *ddl) SetLease(lease time.Duration) { d.m.Lock() defer d.m.Unlock() if lease == d.lease { return } log.Warnf("[ddl] change schema lease %s -> %s", d.lease, lease) if d.isClosed() { // If already closed, just set lease and return. d.lease = lease return } // Close the running worker and start again. d.close() d.lease = lease d.start() } func (d *ddl) GetLease() time.Duration { d.m.RLock() lease := d.lease d.m.RUnlock() return lease } func (d *ddl) GetInformationSchema() infoschema.InfoSchema { return d.infoHandle.Get() } func (d *ddl) genGlobalID() (int64, error) { var globalID int64 err := kv.RunInNewTxn(d.store, true, func(txn kv.Transaction) error { var err error globalID, err = meta.NewMeta(txn).GenGlobalID() return errors.Trace(err) }) return globalID, errors.Trace(err) } func (d *ddl) doDDLJob(ctx context.Context, job *model.Job) error { // For every DDL, we must commit current transaction. if err := ctx.NewTxn(); err != nil { return errors.Trace(err) } // Get a global job ID and put the DDL job in the queue. err := d.addDDLJob(ctx, job) if err != nil { return errors.Trace(err) } // Notice worker that we push a new job and wait the job done. asyncNotify(d.ddlJobCh) log.Infof("[ddl] start DDL job %s", job) var historyJob *model.Job jobID := job.ID // For a job from start to end, the state of it will be none -> delete only -> write only -> reorganization -> public // For every state changes, we will wait as lease 2 * lease time, so here the ticker check is 10 * lease. ticker := time.NewTicker(chooseLeaseTime(10*d.lease, 10*time.Second)) startTime := time.Now() jobsGauge.WithLabelValues(JobType(ddlJobFlag).String(), job.Type.String()).Inc() defer func() { ticker.Stop() jobsGauge.WithLabelValues(JobType(ddlJobFlag).String(), job.Type.String()).Dec() retLabel := handleJobSucc if err != nil { retLabel = handleJobFailed } handleJobHistogram.WithLabelValues(JobType(ddlJobFlag).String(), job.Type.String(), retLabel).Observe(time.Since(startTime).Seconds()) }() for { select { case <-d.ddlJobDoneCh: case <-ticker.C: } historyJob, err = d.getHistoryDDLJob(jobID) if err != nil { log.Errorf("[ddl] get history DDL job err %v, check again", err) continue } else if historyJob == nil { log.Warnf("[ddl] DDL job %d is not in history, maybe not run", jobID) continue } // If a job is a history job, the state must be JobDone or JobCancel. if historyJob.State == model.JobDone { log.Infof("[ddl] DDL job %d is finished", jobID) return nil } return errors.Trace(historyJob.Error) } } func (d *ddl) callHookOnChanged(err error) error { d.hookMu.Lock() defer d.hookMu.Unlock() err = d.hook.OnChanged(err) return errors.Trace(err) } func (d *ddl) setHook(h Callback) { d.hookMu.Lock() defer d.hookMu.Unlock() d.hook = h } // DDL error codes. const ( codeInvalidWorker terror.ErrCode = 1 codeNotOwner = 2 codeInvalidDDLJob = 3 codeInvalidBgJob = 4 codeInvalidJobFlag = 5 codeRunMultiSchemaChanges = 6 codeWaitReorgTimeout = 7 codeInvalidStoreVer = 8 codeInvalidDBState = 100 codeInvalidTableState = 101 codeInvalidColumnState = 102 codeInvalidIndexState = 103 codeInvalidForeignKeyState = 104 codeCantDropColWithIndex = 201 codeUnsupportedAddColumn = 202 codeUnsupportedModifyColumn = 203 codeUnsupportedDropPKHandle = 204 codeBadNull = 1048 codeTooLongIdent = 1059 codeDupKeyName = 1061 codeTooLongKey = 1071 codeKeyColumnDoesNotExits = 1072 codeIncorrectPrefixKey = 1089 codeCantRemoveAllFields = 1090 codeCantDropFieldOrKey = 1091 codeWrongDBName = 1102 codeWrongTableName = 1103 codeBlobKeyWithoutLength = 1170 codeInvalidOnUpdate = 1294 ) func init() { ddlMySQLErrCodes := map[terror.ErrCode]uint16{ codeBadNull: mysql.ErrBadNull, codeCantRemoveAllFields: mysql.ErrCantRemoveAllFields, codeCantDropFieldOrKey: mysql.ErrCantDropFieldOrKey, codeInvalidOnUpdate: mysql.ErrInvalidOnUpdate, codeBlobKeyWithoutLength: mysql.ErrBlobKeyWithoutLength, codeIncorrectPrefixKey: mysql.ErrWrongSubKey, codeTooLongIdent: mysql.ErrTooLongIdent, codeTooLongKey: mysql.ErrTooLongKey, codeKeyColumnDoesNotExits: mysql.ErrKeyColumnDoesNotExits, codeDupKeyName: mysql.ErrDupKeyName, codeWrongDBName: mysql.ErrWrongDBName, codeWrongTableName: mysql.ErrWrongTableName, } terror.ErrClassToMySQLCodes[terror.ClassDDL] = ddlMySQLErrCodes }
ddl/ddl.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00026340477052144706, 0.000177265697857365, 0.00016470084665343165, 0.0001701951987342909, 0.00001970253106264863 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\n", "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, paramTypes, paramValues)\n", "\t\tif err != nil {\n", "\t\t\treturn errors.Trace(err)\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\terr = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, stmt.GetParamsType(), paramValues)\n" ], "file_path": "server/conn_stmt.go", "type": "replace", "edit_start_line_idx": 155 }
// Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Build only when actually fuzzing // +build gofuzz package expfmt import "bytes" // Fuzz text metric parser with with github.com/dvyukov/go-fuzz: // // go-fuzz-build github.com/prometheus/common/expfmt // go-fuzz -bin expfmt-fuzz.zip -workdir fuzz // // Further input samples should go in the folder fuzz/corpus. func Fuzz(in []byte) int { parser := TextParser{} _, err := parser.TextToMetricFamilies(bytes.NewReader(in)) if err != nil { return 0 } return 1 }
_vendor/src/github.com/prometheus/common/expfmt/fuzz.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.0004304885515011847, 0.0002741135540418327, 0.0001763327163644135, 0.0002448165032546967, 0.00010566538549028337 ]
{ "id": 3, "code_window": [ "\tNumParams() int\n", "\n", "\t// BoundParams returns bound parameters.\n", "\tBoundParams() [][]byte\n", "\n", "\t// Reset removes all bound parameters.\n", "\tReset()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// SetParamsType sets type for parameters.\n", "\tSetParamsType([]byte)\n", "\n", "\t// GetParamsType returns the type for parameters.\n", "\tGetParamsType() []byte\n", "\n" ], "file_path": "server/driver.go", "type": "add", "edit_start_line_idx": 95 }
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. // The MIT License (MIT) // // Copyright (c) 2014 wandoulabs // Copyright (c) 2014 siddontang // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package server import ( "encoding/binary" "math" "strconv" "github.com/juju/errors" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/util/hack" ) func (cc *clientConn) handleStmtPrepare(sql string) error { stmt, columns, params, err := cc.ctx.Prepare(sql) if err != nil { return errors.Trace(err) } data := make([]byte, 4, 128) //status ok data = append(data, 0) //stmt id data = append(data, dumpUint32(uint32(stmt.ID()))...) //number columns data = append(data, dumpUint16(uint16(len(columns)))...) //number params data = append(data, dumpUint16(uint16(len(params)))...) //filter [00] data = append(data, 0) //warning count data = append(data, 0, 0) //TODO support warning count if err := cc.writePacket(data); err != nil { return errors.Trace(err) } if len(params) > 0 { for i := 0; i < len(params); i++ { data = data[0:4] data = append(data, params[i].Dump(cc.alloc)...) if err := cc.writePacket(data); err != nil { return errors.Trace(err) } } if err := cc.writeEOF(false); err != nil { return errors.Trace(err) } } if len(columns) > 0 { for i := 0; i < len(columns); i++ { data = data[0:4] data = append(data, columns[i].Dump(cc.alloc)...) if err := cc.writePacket(data); err != nil { return errors.Trace(err) } } if err := cc.writeEOF(false); err != nil { return errors.Trace(err) } } return errors.Trace(cc.flush()) } func (cc *clientConn) handleStmtExecute(data []byte) (err error) { if len(data) < 9 { return mysql.ErrMalformPacket } pos := 0 stmtID := binary.LittleEndian.Uint32(data[0:4]) pos += 4 stmt := cc.ctx.GetStatement(int(stmtID)) if stmt == nil { return mysql.NewErr(mysql.ErrUnknownStmtHandler, strconv.FormatUint(uint64(stmtID), 10), "stmt_execute") } flag := data[pos] pos++ //now we only support CURSOR_TYPE_NO_CURSOR flag if flag != 0 { return mysql.NewErrf(mysql.ErrUnknown, "unsupported flag %d", flag) } //skip iteration-count, always 1 pos += 4 var ( nullBitmaps []byte paramTypes []byte paramValues []byte ) numParams := stmt.NumParams() args := make([]interface{}, numParams) if numParams > 0 { nullBitmapLen := (numParams + 7) >> 3 if len(data) < (pos + nullBitmapLen + 1) { return mysql.ErrMalformPacket } nullBitmaps = data[pos : pos+nullBitmapLen] pos += nullBitmapLen //new param bound flag if data[pos] == 1 { pos++ if len(data) < (pos + (numParams << 1)) { return mysql.ErrMalformPacket } paramTypes = data[pos : pos+(numParams<<1)] pos += (numParams << 1) paramValues = data[pos:] } err = parseStmtArgs(args, stmt.BoundParams(), nullBitmaps, paramTypes, paramValues) if err != nil { return errors.Trace(err) } } rs, err := stmt.Execute(args...) if err != nil { return errors.Trace(err) } if rs == nil { return errors.Trace(cc.writeOK()) } return errors.Trace(cc.writeResultset(rs, true, false)) } func parseStmtArgs(args []interface{}, boundParams [][]byte, nullBitmap, paramTypes, paramValues []byte) (err error) { pos := 0 var v []byte var n int var isNull bool for i := 0; i < len(args); i++ { if nullBitmap[i>>3]&(1<<(uint(i)%8)) > 0 { args[i] = nil continue } if boundParams[i] != nil { args[i] = boundParams[i] continue } if (i<<1)+1 >= len(paramTypes) { return mysql.ErrMalformPacket } tp := paramTypes[i<<1] isUnsigned := (paramTypes[(i<<1)+1] & 0x80) > 0 switch tp { case mysql.TypeNull: args[i] = nil continue case mysql.TypeTiny: if len(paramValues) < (pos + 1) { err = mysql.ErrMalformPacket return } if isUnsigned { args[i] = uint64(paramValues[pos]) } else { args[i] = int64(paramValues[pos]) } pos++ continue case mysql.TypeShort, mysql.TypeYear: if len(paramValues) < (pos + 2) { err = mysql.ErrMalformPacket return } valU16 := binary.LittleEndian.Uint16(paramValues[pos : pos+2]) if isUnsigned { args[i] = uint64(valU16) } else { args[i] = int64(valU16) } pos += 2 continue case mysql.TypeInt24, mysql.TypeLong: if len(paramValues) < (pos + 4) { err = mysql.ErrMalformPacket return } valU32 := binary.LittleEndian.Uint32(paramValues[pos : pos+4]) if isUnsigned { args[i] = uint64(valU32) } else { args[i] = int64(valU32) } pos += 4 continue case mysql.TypeLonglong: if len(paramValues) < (pos + 8) { err = mysql.ErrMalformPacket return } valU64 := binary.LittleEndian.Uint64(paramValues[pos : pos+8]) if isUnsigned { args[i] = valU64 } else { args[i] = int64(valU64) } pos += 8 continue case mysql.TypeFloat: if len(paramValues) < (pos + 4) { err = mysql.ErrMalformPacket return } args[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(paramValues[pos : pos+4]))) pos += 4 continue case mysql.TypeDouble: if len(paramValues) < (pos + 8) { err = mysql.ErrMalformPacket return } args[i] = math.Float64frombits(binary.LittleEndian.Uint64(paramValues[pos : pos+8])) pos += 8 continue case mysql.TypeDecimal, mysql.TypeNewDecimal, mysql.TypeVarchar, mysql.TypeBit, mysql.TypeEnum, mysql.TypeSet, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob, mysql.TypeBlob, mysql.TypeVarString, mysql.TypeString, mysql.TypeGeometry, mysql.TypeDate, mysql.TypeNewDate, mysql.TypeTimestamp, mysql.TypeDatetime, mysql.TypeDuration: if len(paramValues) < (pos + 1) { err = mysql.ErrMalformPacket return } v, isNull, n, err = parseLengthEncodedBytes(paramValues[pos:]) pos += n if err != nil { return } if !isNull { args[i] = hack.String(v) } else { args[i] = nil } continue default: err = errUnknownFieldType.Gen("stmt unknown field type %d", tp) return } } return } func (cc *clientConn) handleStmtClose(data []byte) (err error) { if len(data) < 4 { return } stmtID := int(binary.LittleEndian.Uint32(data[0:4])) stmt := cc.ctx.GetStatement(stmtID) if stmt != nil { return errors.Trace(stmt.Close()) } return } func (cc *clientConn) handleStmtSendLongData(data []byte) (err error) { if len(data) < 6 { return mysql.ErrMalformPacket } stmtID := int(binary.LittleEndian.Uint32(data[0:4])) stmt := cc.ctx.GetStatement(stmtID) if stmt == nil { return mysql.NewErr(mysql.ErrUnknownStmtHandler, strconv.Itoa(stmtID), "stmt_send_longdata") } paramID := int(binary.LittleEndian.Uint16(data[4:6])) return stmt.AppendParam(paramID, data[6:]) } func (cc *clientConn) handleStmtReset(data []byte) (err error) { if len(data) < 4 { return mysql.ErrMalformPacket } stmtID := int(binary.LittleEndian.Uint32(data[0:4])) stmt := cc.ctx.GetStatement(stmtID) if stmt == nil { return mysql.NewErr(mysql.ErrUnknownStmtHandler, strconv.Itoa(stmtID), "stmt_reset") } stmt.Reset() return cc.writeOK() } // See https://dev.mysql.com/doc/internals/en/com-set-option.html func (cc *clientConn) handleSetOption(data []byte) (err error) { if len(data) < 2 { return mysql.ErrMalformPacket } switch binary.LittleEndian.Uint16(data[:2]) { case 0: cc.capability |= mysql.ClientMultiStatements cc.ctx.SetClientCapability(cc.capability) case 1: cc.capability &^= mysql.ClientMultiStatements cc.ctx.SetClientCapability(cc.capability) default: return mysql.ErrMalformPacket } if err = cc.writeEOF(false); err != nil { return errors.Trace(err) } return errors.Trace(cc.flush()) }
server/conn_stmt.go
1
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.997954249382019, 0.11550736427307129, 0.00016827510262373835, 0.00017847372510004789, 0.3019118010997772 ]
{ "id": 3, "code_window": [ "\tNumParams() int\n", "\n", "\t// BoundParams returns bound parameters.\n", "\tBoundParams() [][]byte\n", "\n", "\t// Reset removes all bound parameters.\n", "\tReset()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// SetParamsType sets type for parameters.\n", "\tSetParamsType([]byte)\n", "\n", "\t// GetParamsType returns the type for parameters.\n", "\tGetParamsType() []byte\n", "\n" ], "file_path": "server/driver.go", "type": "add", "edit_start_line_idx": 95 }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Transport code. package http2 import ( "bufio" "bytes" "compress/gzip" "crypto/tls" "errors" "fmt" "io" "io/ioutil" "log" "net" "net/http" "sort" "strconv" "strings" "sync" "time" "golang.org/x/net/http2/hpack" "golang.org/x/net/lex/httplex" ) const ( // transportDefaultConnFlow is how many connection-level flow control // tokens we give the server at start-up, past the default 64k. transportDefaultConnFlow = 1 << 30 // transportDefaultStreamFlow is how many stream-level flow // control tokens we announce to the peer, and how many bytes // we buffer per stream. transportDefaultStreamFlow = 4 << 20 // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send // a stream-level WINDOW_UPDATE for at a time. transportDefaultStreamMinRefresh = 4 << 10 defaultUserAgent = "Go-http-client/2.0" ) // Transport is an HTTP/2 Transport. // // A Transport internally caches connections to servers. It is safe // for concurrent use by multiple goroutines. type Transport struct { // DialTLS specifies an optional dial function for creating // TLS connections for requests. // // If DialTLS is nil, tls.Dial is used. // // If the returned net.Conn has a ConnectionState method like tls.Conn, // it will be used to set http.Response.TLS. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config // ConnPool optionally specifies an alternate connection pool to use. // If nil, the default is used. ConnPool ClientConnPool // DisableCompression, if true, prevents the Transport from // requesting compression with an "Accept-Encoding: gzip" // request header when the Request contains no existing // Accept-Encoding value. If the Transport requests gzip on // its own and gets a gzipped response, it's transparently // decoded in the Response.Body. However, if the user // explicitly requested gzip it is not automatically // uncompressed. DisableCompression bool // AllowHTTP, if true, permits HTTP/2 requests using the insecure, // plain-text "http" scheme. Note that this does not enable h2c support. AllowHTTP bool // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to // send in the initial settings frame. It is how many bytes // of response headers are allow. Unlike the http2 spec, zero here // means to use a default limit (currently 10MB). If you actually // want to advertise an ulimited value to the peer, Transport // interprets the highest possible value here (0xffffffff or 1<<32-1) // to mean no limit. MaxHeaderListSize uint32 // t1, if non-nil, is the standard library Transport using // this transport. Its settings are used (but not its // RoundTrip method, etc). t1 *http.Transport connPoolOnce sync.Once connPoolOrDef ClientConnPool // non-nil version of ConnPool } func (t *Transport) maxHeaderListSize() uint32 { if t.MaxHeaderListSize == 0 { return 10 << 20 } if t.MaxHeaderListSize == 0xffffffff { return 0 } return t.MaxHeaderListSize } func (t *Transport) disableCompression() bool { return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression) } var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6") // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2. // It requires Go 1.6 or later and returns an error if the net/http package is too old // or if t1 has already been HTTP/2-enabled. func ConfigureTransport(t1 *http.Transport) error { _, err := configureTransport(t1) // in configure_transport.go (go1.6) or not_go16.go return err } func (t *Transport) connPool() ClientConnPool { t.connPoolOnce.Do(t.initConnPool) return t.connPoolOrDef } func (t *Transport) initConnPool() { if t.ConnPool != nil { t.connPoolOrDef = t.ConnPool } else { t.connPoolOrDef = &clientConnPool{t: t} } } // ClientConn is the state of a single HTTP/2 client connection to an // HTTP/2 server. type ClientConn struct { t *Transport tconn net.Conn // usually *tls.Conn, except specialized impls tlsState *tls.ConnectionState // nil only for specialized impls singleUse bool // whether being used for a single http.Request // readLoop goroutine fields: readerDone chan struct{} // closed on error readerErr error // set before readerDone is closed mu sync.Mutex // guards following cond *sync.Cond // hold mu; broadcast on flow/closed changes flow flow // our conn-level flow control quota (cs.flow is per stream) inflow flow // peer's conn-level flow control closed bool goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received goAwayDebug string // goAway frame's debug data, retained as a string streams map[uint32]*clientStream // client-initiated nextStreamID uint32 bw *bufio.Writer br *bufio.Reader fr *Framer lastActive time.Time // Settings from peer: maxFrameSize uint32 maxConcurrentStreams uint32 initialWindowSize uint32 hbuf bytes.Buffer // HPACK encoder writes into this henc *hpack.Encoder freeBuf [][]byte wmu sync.Mutex // held while writing; acquire AFTER mu if holding both werr error // first write error that has occurred } // clientStream is the state for a single HTTP/2 stream. One of these // is created for each Transport.RoundTrip call. type clientStream struct { cc *ClientConn req *http.Request trace *clientTrace // or nil ID uint32 resc chan resAndError bufPipe pipe // buffered pipe with the flow-controlled response payload requestedGzip bool on100 func() // optional code to run if get a 100 continue response flow flow // guarded by cc.mu inflow flow // guarded by cc.mu bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read readErr error // sticky read error; owned by transportResponseBody.Read stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu peerReset chan struct{} // closed on peer reset resetErr error // populated before peerReset is closed done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu // owned by clientConnReadLoop: firstByte bool // got the first response byte pastHeaders bool // got first MetaHeadersFrame (actual headers) pastTrailers bool // got optional second MetaHeadersFrame (trailers) trailer http.Header // accumulated trailers resTrailer *http.Header // client's Response.Trailer } // awaitRequestCancel runs in its own goroutine and waits for the user // to cancel a RoundTrip request, its context to expire, or for the // request to be done (any way it might be removed from the cc.streams // map: peer reset, successful completion, TCP connection breakage, // etc) func (cs *clientStream) awaitRequestCancel(req *http.Request) { ctx := reqContext(req) if req.Cancel == nil && ctx.Done() == nil { return } select { case <-req.Cancel: cs.bufPipe.CloseWithError(errRequestCanceled) cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) case <-ctx.Done(): cs.bufPipe.CloseWithError(ctx.Err()) cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) case <-cs.done: } } // checkResetOrDone reports any error sent in a RST_STREAM frame by the // server, or errStreamClosed if the stream is complete. func (cs *clientStream) checkResetOrDone() error { select { case <-cs.peerReset: return cs.resetErr case <-cs.done: return errStreamClosed default: return nil } } func (cs *clientStream) abortRequestBodyWrite(err error) { if err == nil { panic("nil error") } cc := cs.cc cc.mu.Lock() cs.stopReqBody = err cc.cond.Broadcast() cc.mu.Unlock() } type stickyErrWriter struct { w io.Writer err *error } func (sew stickyErrWriter) Write(p []byte) (n int, err error) { if *sew.err != nil { return 0, *sew.err } n, err = sew.w.Write(p) *sew.err = err return } var ErrNoCachedConn = errors.New("http2: no cached connection was available") // RoundTripOpt are options for the Transport.RoundTripOpt method. type RoundTripOpt struct { // OnlyCachedConn controls whether RoundTripOpt may // create a new TCP connection. If set true and // no cached connection is available, RoundTripOpt // will return ErrNoCachedConn. OnlyCachedConn bool } func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return t.RoundTripOpt(req, RoundTripOpt{}) } // authorityAddr returns a given authority (a host/IP, or host:port / ip:port) // and returns a host:port. The port 443 is added if needed. func authorityAddr(scheme string, authority string) (addr string) { if _, _, err := net.SplitHostPort(authority); err == nil { return authority } port := "443" if scheme == "http" { port = "80" } return net.JoinHostPort(authority, port) } // RoundTripOpt is like RoundTrip, but takes options. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) { return nil, errors.New("http2: unsupported scheme") } addr := authorityAddr(req.URL.Scheme, req.URL.Host) for { cc, err := t.connPool().GetClientConn(req, addr) if err != nil { t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err) return nil, err } traceGotConn(req, cc) res, err := cc.RoundTrip(req) if shouldRetryRequest(req, err) { continue } if err != nil { t.vlogf("RoundTrip failure: %v", err) return nil, err } return res, nil } } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle. // It does not interrupt any connections currently in use. func (t *Transport) CloseIdleConnections() { if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok { cp.closeIdleConnections() } } var ( errClientConnClosed = errors.New("http2: client conn is closed") errClientConnUnusable = errors.New("http2: client conn not usable") ) func shouldRetryRequest(req *http.Request, err error) bool { // TODO: retry GET requests (no bodies) more aggressively, if shutdown // before response. return err == errClientConnUnusable } func (t *Transport) dialClientConn(addr string) (*ClientConn, error) { host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err } tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host)) if err != nil { return nil, err } return t.NewClientConn(tconn) } func (t *Transport) newTLSConfig(host string) *tls.Config { cfg := new(tls.Config) if t.TLSClientConfig != nil { *cfg = *t.TLSClientConfig } if !strSliceContains(cfg.NextProtos, NextProtoTLS) { cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...) } if cfg.ServerName == "" { cfg.ServerName = host } return cfg } func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) { if t.DialTLS != nil { return t.DialTLS } return t.dialTLSDefault } func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) { cn, err := tls.Dial(network, addr, cfg) if err != nil { return nil, err } if err := cn.Handshake(); err != nil { return nil, err } if !cfg.InsecureSkipVerify { if err := cn.VerifyHostname(cfg.ServerName); err != nil { return nil, err } } state := cn.ConnectionState() if p := state.NegotiatedProtocol; p != NextProtoTLS { return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS) } if !state.NegotiatedProtocolIsMutual { return nil, errors.New("http2: could not negotiate protocol mutually") } return cn, nil } // disableKeepAlives reports whether connections should be closed as // soon as possible after handling the first request. func (t *Transport) disableKeepAlives() bool { return t.t1 != nil && t.t1.DisableKeepAlives } func (t *Transport) expectContinueTimeout() time.Duration { if t.t1 == nil { return 0 } return transportExpectContinueTimeout(t.t1) } func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { if VerboseLogs { t.vlogf("http2: Transport creating client conn to %v", c.RemoteAddr()) } if _, err := c.Write(clientPreface); err != nil { t.vlogf("client preface write error: %v", err) return nil, err } cc := &ClientConn{ t: t, tconn: c, readerDone: make(chan struct{}), nextStreamID: 1, maxFrameSize: 16 << 10, // spec default initialWindowSize: 65535, // spec default maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough. streams: make(map[uint32]*clientStream), } cc.cond = sync.NewCond(&cc.mu) cc.flow.add(int32(initialWindowSize)) // TODO: adjust this writer size to account for frame size + // MTU + crypto/tls record padding. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr}) cc.br = bufio.NewReader(c) cc.fr = NewFramer(cc.bw, cc.br) cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) cc.fr.MaxHeaderListSize = t.maxHeaderListSize() // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on // henc in response to SETTINGS frames? cc.henc = hpack.NewEncoder(&cc.hbuf) if cs, ok := c.(connectionStater); ok { state := cs.ConnectionState() cc.tlsState = &state } initialSettings := []Setting{ {ID: SettingEnablePush, Val: 0}, {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow}, } if max := t.maxHeaderListSize(); max != 0 { initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max}) } cc.fr.WriteSettings(initialSettings...) cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow) cc.inflow.add(transportDefaultConnFlow + initialWindowSize) cc.bw.Flush() if cc.werr != nil { return nil, cc.werr } // Read the obligatory SETTINGS frame f, err := cc.fr.ReadFrame() if err != nil { return nil, err } sf, ok := f.(*SettingsFrame) if !ok { return nil, fmt.Errorf("expected settings frame, got: %T", f) } cc.fr.WriteSettingsAck() cc.bw.Flush() sf.ForeachSetting(func(s Setting) error { switch s.ID { case SettingMaxFrameSize: cc.maxFrameSize = s.Val case SettingMaxConcurrentStreams: cc.maxConcurrentStreams = s.Val case SettingInitialWindowSize: cc.initialWindowSize = s.Val default: // TODO(bradfitz): handle more; at least SETTINGS_HEADER_TABLE_SIZE? t.vlogf("Unhandled Setting: %v", s) } return nil }) go cc.readLoop() return cc, nil } func (cc *ClientConn) setGoAway(f *GoAwayFrame) { cc.mu.Lock() defer cc.mu.Unlock() old := cc.goAway cc.goAway = f // Merge the previous and current GoAway error frames. if cc.goAwayDebug == "" { cc.goAwayDebug = string(f.DebugData()) } if old != nil && old.ErrCode != ErrCodeNo { cc.goAway.ErrCode = old.ErrCode } } func (cc *ClientConn) CanTakeNewRequest() bool { cc.mu.Lock() defer cc.mu.Unlock() return cc.canTakeNewRequestLocked() } func (cc *ClientConn) canTakeNewRequestLocked() bool { if cc.singleUse && cc.nextStreamID > 1 { return false } return cc.goAway == nil && !cc.closed && int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) && cc.nextStreamID < 2147483647 } func (cc *ClientConn) closeIfIdle() { cc.mu.Lock() if len(cc.streams) > 0 { cc.mu.Unlock() return } cc.closed = true // TODO: do clients send GOAWAY too? maybe? Just Close: cc.mu.Unlock() cc.tconn.Close() } const maxAllocFrameSize = 512 << 10 // frameBuffer returns a scratch buffer suitable for writing DATA frames. // They're capped at the min of the peer's max frame size or 512KB // (kinda arbitrarily), but definitely capped so we don't allocate 4GB // bufers. func (cc *ClientConn) frameScratchBuffer() []byte { cc.mu.Lock() size := cc.maxFrameSize if size > maxAllocFrameSize { size = maxAllocFrameSize } for i, buf := range cc.freeBuf { if len(buf) >= int(size) { cc.freeBuf[i] = nil cc.mu.Unlock() return buf[:size] } } cc.mu.Unlock() return make([]byte, size) } func (cc *ClientConn) putFrameScratchBuffer(buf []byte) { cc.mu.Lock() defer cc.mu.Unlock() const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate. if len(cc.freeBuf) < maxBufs { cc.freeBuf = append(cc.freeBuf, buf) return } for i, old := range cc.freeBuf { if old == nil { cc.freeBuf[i] = buf return } } // forget about it. } // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests. var errRequestCanceled = errors.New("net/http: request canceled") func commaSeparatedTrailers(req *http.Request) (string, error) { keys := make([]string, 0, len(req.Trailer)) for k := range req.Trailer { k = http.CanonicalHeaderKey(k) switch k { case "Transfer-Encoding", "Trailer", "Content-Length": return "", &badStringError{"invalid Trailer key", k} } keys = append(keys, k) } if len(keys) > 0 { sort.Strings(keys) // TODO: could do better allocation-wise here, but trailers are rare, // so being lazy for now. return strings.Join(keys, ","), nil } return "", nil } func (cc *ClientConn) responseHeaderTimeout() time.Duration { if cc.t.t1 != nil { return cc.t.t1.ResponseHeaderTimeout } // No way to do this (yet?) with just an http2.Transport. Probably // no need. Request.Cancel this is the new way. We only need to support // this for compatibility with the old http.Transport fields when // we're doing transparent http2. return 0 } // checkConnHeaders checks whether req has any invalid connection-level headers. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields. // Certain headers are special-cased as okay but not transmitted later. func checkConnHeaders(req *http.Request) error { if v := req.Header.Get("Upgrade"); v != "" { return errors.New("http2: invalid Upgrade request header") } if v := req.Header.Get("Transfer-Encoding"); (v != "" && v != "chunked") || len(req.Header["Transfer-Encoding"]) > 1 { return errors.New("http2: invalid Transfer-Encoding request header") } if v := req.Header.Get("Connection"); (v != "" && v != "close" && v != "keep-alive") || len(req.Header["Connection"]) > 1 { return errors.New("http2: invalid Connection request header") } return nil } func bodyAndLength(req *http.Request) (body io.Reader, contentLen int64) { body = req.Body if body == nil { return nil, 0 } if req.ContentLength != 0 { return req.Body, req.ContentLength } // We have a body but a zero content length. Test to see if // it's actually zero or just unset. var buf [1]byte n, rerr := io.ReadFull(body, buf[:]) if rerr != nil && rerr != io.EOF { return errorReader{rerr}, -1 } if n == 1 { // Oh, guess there is data in this Body Reader after all. // The ContentLength field just wasn't set. // Stich the Body back together again, re-attaching our // consumed byte. return io.MultiReader(bytes.NewReader(buf[:]), body), -1 } // Body is actually zero bytes. return nil, 0 } func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { if err := checkConnHeaders(req); err != nil { return nil, err } trailers, err := commaSeparatedTrailers(req) if err != nil { return nil, err } hasTrailers := trailers != "" body, contentLen := bodyAndLength(req) hasBody := body != nil cc.mu.Lock() cc.lastActive = time.Now() if cc.closed || !cc.canTakeNewRequestLocked() { cc.mu.Unlock() return nil, errClientConnUnusable } // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere? var requestedGzip bool if !cc.t.disableCompression() && req.Header.Get("Accept-Encoding") == "" && req.Header.Get("Range") == "" && req.Method != "HEAD" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 // // Note that we don't request this for HEAD requests, // due to a bug in nginx: // http://trac.nginx.org/nginx/ticket/358 // https://golang.org/issue/5522 // // We don't request gzip if the request is for a range, since // auto-decoding a portion of a gzipped document will just fail // anyway. See https://golang.org/issue/8923 requestedGzip = true } // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is // sent by writeRequestBody below, along with any Trailers, // again in form HEADERS{1}, CONTINUATION{0,}) hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen) if err != nil { cc.mu.Unlock() return nil, err } cs := cc.newStream() cs.req = req cs.trace = requestTrace(req) cs.requestedGzip = requestedGzip bodyWriter := cc.t.getBodyWriterState(cs, body) cs.on100 = bodyWriter.on100 cc.wmu.Lock() endStream := !hasBody && !hasTrailers werr := cc.writeHeaders(cs.ID, endStream, hdrs) cc.wmu.Unlock() traceWroteHeaders(cs.trace) cc.mu.Unlock() if werr != nil { if hasBody { req.Body.Close() // per RoundTripper contract bodyWriter.cancel() } cc.forgetStreamID(cs.ID) // Don't bother sending a RST_STREAM (our write already failed; // no need to keep writing) traceWroteRequest(cs.trace, werr) return nil, werr } var respHeaderTimer <-chan time.Time if hasBody { bodyWriter.scheduleBodyWrite() } else { traceWroteRequest(cs.trace, nil) if d := cc.responseHeaderTimeout(); d != 0 { timer := time.NewTimer(d) defer timer.Stop() respHeaderTimer = timer.C } } readLoopResCh := cs.resc bodyWritten := false ctx := reqContext(req) for { select { case re := <-readLoopResCh: res := re.res if re.err != nil || res.StatusCode > 299 { // On error or status code 3xx, 4xx, 5xx, etc abort any // ongoing write, assuming that the server doesn't care // about our request body. If the server replied with 1xx or // 2xx, however, then assume the server DOES potentially // want our body (e.g. full-duplex streaming: // golang.org/issue/13444). If it turns out the server // doesn't, they'll RST_STREAM us soon enough. This is a // heuristic to avoid adding knobs to Transport. Hopefully // we can keep it. bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWrite) } if re.err != nil { cc.forgetStreamID(cs.ID) return nil, re.err } res.Request = req res.TLS = cc.tlsState return res, nil case <-respHeaderTimer: cc.forgetStreamID(cs.ID) if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } return nil, errTimeout case <-ctx.Done(): cc.forgetStreamID(cs.ID) if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } return nil, ctx.Err() case <-req.Cancel: cc.forgetStreamID(cs.ID) if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } return nil, errRequestCanceled case <-cs.peerReset: // processResetStream already removed the // stream from the streams map; no need for // forgetStreamID. return nil, cs.resetErr case err := <-bodyWriter.resc: if err != nil { return nil, err } bodyWritten = true if d := cc.responseHeaderTimeout(); d != 0 { timer := time.NewTimer(d) defer timer.Stop() respHeaderTimer = timer.C } } } } // requires cc.wmu be held func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error { first := true // first frame written (HEADERS is first, then CONTINUATION) frameSize := int(cc.maxFrameSize) for len(hdrs) > 0 && cc.werr == nil { chunk := hdrs if len(chunk) > frameSize { chunk = chunk[:frameSize] } hdrs = hdrs[len(chunk):] endHeaders := len(hdrs) == 0 if first { cc.fr.WriteHeaders(HeadersFrameParam{ StreamID: streamID, BlockFragment: chunk, EndStream: endStream, EndHeaders: endHeaders, }) first = false } else { cc.fr.WriteContinuation(streamID, endHeaders, chunk) } } // TODO(bradfitz): this Flush could potentially block (as // could the WriteHeaders call(s) above), which means they // wouldn't respond to Request.Cancel being readable. That's // rare, but this should probably be in a goroutine. cc.bw.Flush() return cc.werr } // internal error values; they don't escape to callers var ( // abort request body write; don't send cancel errStopReqBodyWrite = errors.New("http2: aborting request body write") // abort request body write, but send stream reset of cancel. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request") ) func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) { cc := cs.cc sentEnd := false // whether we sent the final DATA frame w/ END_STREAM buf := cc.frameScratchBuffer() defer cc.putFrameScratchBuffer(buf) defer func() { traceWroteRequest(cs.trace, err) // TODO: write h12Compare test showing whether // Request.Body is closed by the Transport, // and in multiple cases: server replies <=299 and >299 // while still writing request body cerr := bodyCloser.Close() if err == nil { err = cerr } }() req := cs.req hasTrailers := req.Trailer != nil var sawEOF bool for !sawEOF { n, err := body.Read(buf) if err == io.EOF { sawEOF = true err = nil } else if err != nil { return err } remain := buf[:n] for len(remain) > 0 && err == nil { var allowed int32 allowed, err = cs.awaitFlowControl(len(remain)) switch { case err == errStopReqBodyWrite: return err case err == errStopReqBodyWriteAndCancel: cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) return err case err != nil: return err } cc.wmu.Lock() data := remain[:allowed] remain = remain[allowed:] sentEnd = sawEOF && len(remain) == 0 && !hasTrailers err = cc.fr.WriteData(cs.ID, sentEnd, data) if err == nil { // TODO(bradfitz): this flush is for latency, not bandwidth. // Most requests won't need this. Make this opt-in or opt-out? // Use some heuristic on the body type? Nagel-like timers? // Based on 'n'? Only last chunk of this for loop, unless flow control // tokens are low? For now, always: err = cc.bw.Flush() } cc.wmu.Unlock() } if err != nil { return err } } cc.wmu.Lock() if !sentEnd { var trls []byte if hasTrailers { cc.mu.Lock() trls = cc.encodeTrailers(req) cc.mu.Unlock() } // Avoid forgetting to send an END_STREAM if the encoded // trailers are 0 bytes. Both results produce and END_STREAM. if len(trls) > 0 { err = cc.writeHeaders(cs.ID, true, trls) } else { err = cc.fr.WriteData(cs.ID, true, nil) } } if ferr := cc.bw.Flush(); ferr != nil && err == nil { err = ferr } cc.wmu.Unlock() return err } // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow // control tokens from the server. // It returns either the non-zero number of tokens taken or an error // if the stream is dead. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) { cc := cs.cc cc.mu.Lock() defer cc.mu.Unlock() for { if cc.closed { return 0, errClientConnClosed } if cs.stopReqBody != nil { return 0, cs.stopReqBody } if err := cs.checkResetOrDone(); err != nil { return 0, err } if a := cs.flow.available(); a > 0 { take := a if int(take) > maxBytes { take = int32(maxBytes) // can't truncate int; take is int32 } if take > int32(cc.maxFrameSize) { take = int32(cc.maxFrameSize) } cs.flow.take(take) return take, nil } cc.cond.Wait() } } type badStringError struct { what string str string } func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } // requires cc.mu be held. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) { cc.hbuf.Reset() host := req.Host if host == "" { host = req.URL.Host } // Check for any invalid headers and return an error before we // potentially pollute our hpack state. (We want to be able to // continue to reuse the hpack encoder for future requests) for k, vv := range req.Header { if !httplex.ValidHeaderFieldName(k) { return nil, fmt.Errorf("invalid HTTP header name %q", k) } for _, v := range vv { if !httplex.ValidHeaderFieldValue(v) { return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k) } } } // 8.1.2.3 Request Pseudo-Header Fields // The :path pseudo-header field includes the path and query parts of the // target URI (the path-absolute production and optionally a '?' character // followed by the query production (see Sections 3.3 and 3.4 of // [RFC3986]). cc.writeHeader(":authority", host) cc.writeHeader(":method", req.Method) if req.Method != "CONNECT" { cc.writeHeader(":path", req.URL.RequestURI()) cc.writeHeader(":scheme", "https") } if trailers != "" { cc.writeHeader("trailer", trailers) } var didUA bool for k, vv := range req.Header { lowKey := strings.ToLower(k) switch lowKey { case "host", "content-length": // Host is :authority, already sent. // Content-Length is automatic, set below. continue case "connection", "proxy-connection", "transfer-encoding", "upgrade", "keep-alive": // Per 8.1.2.2 Connection-Specific Header // Fields, don't send connection-specific // fields. We have already checked if any // are error-worthy so just ignore the rest. continue case "user-agent": // Match Go's http1 behavior: at most one // User-Agent. If set to nil or empty string, // then omit it. Otherwise if not mentioned, // include the default (below). didUA = true if len(vv) < 1 { continue } vv = vv[:1] if vv[0] == "" { continue } } for _, v := range vv { cc.writeHeader(lowKey, v) } } if shouldSendReqContentLength(req.Method, contentLength) { cc.writeHeader("content-length", strconv.FormatInt(contentLength, 10)) } if addGzipHeader { cc.writeHeader("accept-encoding", "gzip") } if !didUA { cc.writeHeader("user-agent", defaultUserAgent) } return cc.hbuf.Bytes(), nil } // shouldSendReqContentLength reports whether the http2.Transport should send // a "content-length" request header. This logic is basically a copy of the net/http // transferWriter.shouldSendContentLength. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown). // -1 means unknown. func shouldSendReqContentLength(method string, contentLength int64) bool { if contentLength > 0 { return true } if contentLength < 0 { return false } // For zero bodies, whether we send a content-length depends on the method. // It also kinda doesn't matter for http2 either way, with END_STREAM. switch method { case "POST", "PUT", "PATCH": return true default: return false } } // requires cc.mu be held. func (cc *ClientConn) encodeTrailers(req *http.Request) []byte { cc.hbuf.Reset() for k, vv := range req.Trailer { // Transfer-Encoding, etc.. have already been filter at the // start of RoundTrip lowKey := strings.ToLower(k) for _, v := range vv { cc.writeHeader(lowKey, v) } } return cc.hbuf.Bytes() } func (cc *ClientConn) writeHeader(name, value string) { if VerboseLogs { log.Printf("http2: Transport encoding header %q = %q", name, value) } cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) } type resAndError struct { res *http.Response err error } // requires cc.mu be held. func (cc *ClientConn) newStream() *clientStream { cs := &clientStream{ cc: cc, ID: cc.nextStreamID, resc: make(chan resAndError, 1), peerReset: make(chan struct{}), done: make(chan struct{}), } cs.flow.add(int32(cc.initialWindowSize)) cs.flow.setConnFlow(&cc.flow) cs.inflow.add(transportDefaultStreamFlow) cs.inflow.setConnFlow(&cc.inflow) cc.nextStreamID += 2 cc.streams[cs.ID] = cs return cs } func (cc *ClientConn) forgetStreamID(id uint32) { cc.streamByID(id, true) } func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream { cc.mu.Lock() defer cc.mu.Unlock() cs := cc.streams[id] if andRemove && cs != nil && !cc.closed { cc.lastActive = time.Now() delete(cc.streams, id) close(cs.done) cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl } return cs } // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop. type clientConnReadLoop struct { cc *ClientConn activeRes map[uint32]*clientStream // keyed by streamID closeWhenIdle bool } // readLoop runs in its own goroutine and reads and dispatches frames. func (cc *ClientConn) readLoop() { rl := &clientConnReadLoop{ cc: cc, activeRes: make(map[uint32]*clientStream), } defer rl.cleanup() cc.readerErr = rl.run() if ce, ok := cc.readerErr.(ConnectionError); ok { cc.wmu.Lock() cc.fr.WriteGoAway(0, ErrCode(ce), nil) cc.wmu.Unlock() } } // GoAwayError is returned by the Transport when the server closes the // TCP connection after sending a GOAWAY frame. type GoAwayError struct { LastStreamID uint32 ErrCode ErrCode DebugData string } func (e GoAwayError) Error() string { return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q", e.LastStreamID, e.ErrCode, e.DebugData) } func (rl *clientConnReadLoop) cleanup() { cc := rl.cc defer cc.tconn.Close() defer cc.t.connPool().MarkDead(cc) defer close(cc.readerDone) // Close any response bodies if the server closes prematurely. // TODO: also do this if we've written the headers but not // gotten a response yet. err := cc.readerErr cc.mu.Lock() if err == io.EOF { if cc.goAway != nil { err = GoAwayError{ LastStreamID: cc.goAway.LastStreamID, ErrCode: cc.goAway.ErrCode, DebugData: cc.goAwayDebug, } } else { err = io.ErrUnexpectedEOF } } for _, cs := range rl.activeRes { cs.bufPipe.CloseWithError(err) } for _, cs := range cc.streams { select { case cs.resc <- resAndError{err: err}: default: } close(cs.done) } cc.closed = true cc.cond.Broadcast() cc.mu.Unlock() } func (rl *clientConnReadLoop) run() error { cc := rl.cc rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse gotReply := false // ever saw a reply for { f, err := cc.fr.ReadFrame() if err != nil { cc.vlogf("Transport readFrame error: (%T) %v", err, err) } if se, ok := err.(StreamError); ok { if cs := cc.streamByID(se.StreamID, true /*ended; remove it*/); cs != nil { rl.endStreamError(cs, cc.fr.errDetail) } continue } else if err != nil { return err } if VerboseLogs { cc.vlogf("http2: Transport received %s", summarizeFrame(f)) } maybeIdle := false // whether frame might transition us to idle switch f := f.(type) { case *MetaHeadersFrame: err = rl.processHeaders(f) maybeIdle = true gotReply = true case *DataFrame: err = rl.processData(f) maybeIdle = true case *GoAwayFrame: err = rl.processGoAway(f) maybeIdle = true case *RSTStreamFrame: err = rl.processResetStream(f) maybeIdle = true case *SettingsFrame: err = rl.processSettings(f) case *PushPromiseFrame: err = rl.processPushPromise(f) case *WindowUpdateFrame: err = rl.processWindowUpdate(f) case *PingFrame: err = rl.processPing(f) default: cc.logf("Transport: unhandled response frame type %T", f) } if err != nil { return err } if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 { cc.closeIfIdle() } } } func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { cc := rl.cc cs := cc.streamByID(f.StreamID, f.StreamEnded()) if cs == nil { // We'd get here if we canceled a request while the // server had its response still in flight. So if this // was just something we canceled, ignore it. return nil } if !cs.firstByte { if cs.trace != nil { // TODO(bradfitz): move first response byte earlier, // when we first read the 9 byte header, not waiting // until all the HEADERS+CONTINUATION frames have been // merged. This works for now. traceFirstResponseByte(cs.trace) } cs.firstByte = true } if !cs.pastHeaders { cs.pastHeaders = true } else { return rl.processTrailers(cs, f) } res, err := rl.handleResponse(cs, f) if err != nil { if _, ok := err.(ConnectionError); ok { return err } // Any other error type is a stream error. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err) cs.resc <- resAndError{err: err} return nil // return nil from process* funcs to keep conn alive } if res == nil { // (nil, nil) special case. See handleResponse docs. return nil } if res.Body != noBody { rl.activeRes[cs.ID] = cs } cs.resTrailer = &res.Trailer cs.resc <- resAndError{res: res} return nil } // may return error types nil, or ConnectionError. Any other error value // is a StreamError of type ErrCodeProtocol. The returned error in that case // is the detail. // // As a special case, handleResponse may return (nil, nil) to skip the // frame (currently only used for 100 expect continue). This special // case is going away after Issue 13851 is fixed. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) { if f.Truncated { return nil, errResponseHeaderListSize } status := f.PseudoValue("status") if status == "" { return nil, errors.New("missing status pseudo header") } statusCode, err := strconv.Atoi(status) if err != nil { return nil, errors.New("malformed non-numeric status pseudo header") } if statusCode == 100 { traceGot100Continue(cs.trace) if cs.on100 != nil { cs.on100() // forces any write delay timer to fire } cs.pastHeaders = false // do it all again return nil, nil } header := make(http.Header) res := &http.Response{ Proto: "HTTP/2.0", ProtoMajor: 2, Header: header, StatusCode: statusCode, Status: status + " " + http.StatusText(statusCode), } for _, hf := range f.RegularFields() { key := http.CanonicalHeaderKey(hf.Name) if key == "Trailer" { t := res.Trailer if t == nil { t = make(http.Header) res.Trailer = t } foreachHeaderElement(hf.Value, func(v string) { t[http.CanonicalHeaderKey(v)] = nil }) } else { header[key] = append(header[key], hf.Value) } } streamEnded := f.StreamEnded() isHead := cs.req.Method == "HEAD" if !streamEnded || isHead { res.ContentLength = -1 if clens := res.Header["Content-Length"]; len(clens) == 1 { if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil { res.ContentLength = clen64 } else { // TODO: care? unlike http/1, it won't mess up our framing, so it's // more safe smuggling-wise to ignore. } } else if len(clens) > 1 { // TODO: care? unlike http/1, it won't mess up our framing, so it's // more safe smuggling-wise to ignore. } } if streamEnded || isHead { res.Body = noBody return res, nil } buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage cs.bufPipe = pipe{b: buf} cs.bytesRemain = res.ContentLength res.Body = transportResponseBody{cs} go cs.awaitRequestCancel(cs.req) if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" { res.Header.Del("Content-Encoding") res.Header.Del("Content-Length") res.ContentLength = -1 res.Body = &gzipReader{body: res.Body} setResponseUncompressed(res) } return res, nil } func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error { if cs.pastTrailers { // Too many HEADERS frames for this stream. return ConnectionError(ErrCodeProtocol) } cs.pastTrailers = true if !f.StreamEnded() { // We expect that any headers for trailers also // has END_STREAM. return ConnectionError(ErrCodeProtocol) } if len(f.PseudoFields()) > 0 { // No pseudo header fields are defined for trailers. // TODO: ConnectionError might be overly harsh? Check. return ConnectionError(ErrCodeProtocol) } trailer := make(http.Header) for _, hf := range f.RegularFields() { key := http.CanonicalHeaderKey(hf.Name) trailer[key] = append(trailer[key], hf.Value) } cs.trailer = trailer rl.endStream(cs) return nil } // transportResponseBody is the concrete type of Transport.RoundTrip's // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body. // On Close it sends RST_STREAM if EOF wasn't already seen. type transportResponseBody struct { cs *clientStream } func (b transportResponseBody) Read(p []byte) (n int, err error) { cs := b.cs cc := cs.cc if cs.readErr != nil { return 0, cs.readErr } n, err = b.cs.bufPipe.Read(p) if cs.bytesRemain != -1 { if int64(n) > cs.bytesRemain { n = int(cs.bytesRemain) if err == nil { err = errors.New("net/http: server replied with more than declared Content-Length; truncated") cc.writeStreamReset(cs.ID, ErrCodeProtocol, err) } cs.readErr = err return int(cs.bytesRemain), err } cs.bytesRemain -= int64(n) if err == io.EOF && cs.bytesRemain > 0 { err = io.ErrUnexpectedEOF cs.readErr = err return n, err } } if n == 0 { // No flow control tokens to send back. return } cc.mu.Lock() defer cc.mu.Unlock() var connAdd, streamAdd int32 // Check the conn-level first, before the stream-level. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 { connAdd = transportDefaultConnFlow - v cc.inflow.add(connAdd) } if err == nil { // No need to refresh if the stream is over or failed. // Consider any buffered body data (read from the conn but not // consumed by the client) when computing flow control for this // stream. v := int(cs.inflow.available()) + cs.bufPipe.Len() if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh { streamAdd = int32(transportDefaultStreamFlow - v) cs.inflow.add(streamAdd) } } if connAdd != 0 || streamAdd != 0 { cc.wmu.Lock() defer cc.wmu.Unlock() if connAdd != 0 { cc.fr.WriteWindowUpdate(0, mustUint31(connAdd)) } if streamAdd != 0 { cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd)) } cc.bw.Flush() } return } var errClosedResponseBody = errors.New("http2: response body closed") func (b transportResponseBody) Close() error { cs := b.cs if cs.bufPipe.Err() != io.EOF { // TODO: write test for this cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } cs.bufPipe.BreakWithError(errClosedResponseBody) return nil } func (rl *clientConnReadLoop) processData(f *DataFrame) error { cc := rl.cc cs := cc.streamByID(f.StreamID, f.StreamEnded()) if cs == nil { cc.mu.Lock() neverSent := cc.nextStreamID cc.mu.Unlock() if f.StreamID >= neverSent { // We never asked for this. cc.logf("http2: Transport received unsolicited DATA frame; closing connection") return ConnectionError(ErrCodeProtocol) } // We probably did ask for this, but canceled. Just ignore it. // TODO: be stricter here? only silently ignore things which // we canceled, but not things which were closed normally // by the peer? Tough without accumulating too much state. return nil } if data := f.Data(); len(data) > 0 { if cs.bufPipe.b == nil { // Data frame after it's already closed? cc.logf("http2: Transport received DATA frame for closed stream; closing connection") return ConnectionError(ErrCodeProtocol) } // Check connection-level flow control. cc.mu.Lock() if cs.inflow.available() >= int32(len(data)) { cs.inflow.take(int32(len(data))) } else { cc.mu.Unlock() return ConnectionError(ErrCodeFlowControl) } cc.mu.Unlock() if _, err := cs.bufPipe.Write(data); err != nil { rl.endStreamError(cs, err) return err } } if f.StreamEnded() { rl.endStream(cs) } return nil } var errInvalidTrailers = errors.New("http2: invalid trailers") func (rl *clientConnReadLoop) endStream(cs *clientStream) { // TODO: check that any declared content-length matches, like // server.go's (*stream).endStream method. rl.endStreamError(cs, nil) } func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) { var code func() if err == nil { err = io.EOF code = cs.copyTrailers } cs.bufPipe.closeWithErrorAndCode(err, code) delete(rl.activeRes, cs.ID) if cs.req.Close || cs.req.Header.Get("Connection") == "close" { rl.closeWhenIdle = true } } func (cs *clientStream) copyTrailers() { for k, vv := range cs.trailer { t := cs.resTrailer if *t == nil { *t = make(http.Header) } (*t)[k] = vv } } func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error { cc := rl.cc cc.t.connPool().MarkDead(cc) if f.ErrCode != 0 { // TODO: deal with GOAWAY more. particularly the error code cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode) } cc.setGoAway(f) return nil } func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error { cc := rl.cc cc.mu.Lock() defer cc.mu.Unlock() return f.ForeachSetting(func(s Setting) error { switch s.ID { case SettingMaxFrameSize: cc.maxFrameSize = s.Val case SettingMaxConcurrentStreams: cc.maxConcurrentStreams = s.Val case SettingInitialWindowSize: // TODO: error if this is too large. // TODO: adjust flow control of still-open // frames by the difference of the old initial // window size and this one. cc.initialWindowSize = s.Val default: // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably. cc.vlogf("Unhandled Setting: %v", s) } return nil }) } func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error { cc := rl.cc cs := cc.streamByID(f.StreamID, false) if f.StreamID != 0 && cs == nil { return nil } cc.mu.Lock() defer cc.mu.Unlock() fl := &cc.flow if cs != nil { fl = &cs.flow } if !fl.add(int32(f.Increment)) { return ConnectionError(ErrCodeFlowControl) } cc.cond.Broadcast() return nil } func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error { cs := rl.cc.streamByID(f.StreamID, true) if cs == nil { // TODO: return error if server tries to RST_STEAM an idle stream return nil } select { case <-cs.peerReset: // Already reset. // This is the only goroutine // which closes this, so there // isn't a race. default: err := StreamError{cs.ID, f.ErrCode} cs.resetErr = err close(cs.peerReset) cs.bufPipe.CloseWithError(err) cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl } delete(rl.activeRes, cs.ID) return nil } func (rl *clientConnReadLoop) processPing(f *PingFrame) error { if f.IsAck() { // 6.7 PING: " An endpoint MUST NOT respond to PING frames // containing this flag." return nil } cc := rl.cc cc.wmu.Lock() defer cc.wmu.Unlock() if err := cc.fr.WritePing(true, f.Data); err != nil { return err } return cc.bw.Flush() } func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error { // We told the peer we don't want them. // Spec says: // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH // setting of the peer endpoint is set to 0. An endpoint that // has set this setting and has received acknowledgement MUST // treat the receipt of a PUSH_PROMISE frame as a connection // error (Section 5.4.1) of type PROTOCOL_ERROR." return ConnectionError(ErrCodeProtocol) } func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) { // TODO: do something with err? send it as a debug frame to the peer? // But that's only in GOAWAY. Invent a new frame type? Is there one already? cc.wmu.Lock() cc.fr.WriteRSTStream(streamID, code) cc.bw.Flush() cc.wmu.Unlock() } var ( errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit") errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers") ) func (cc *ClientConn) logf(format string, args ...interface{}) { cc.t.logf(format, args...) } func (cc *ClientConn) vlogf(format string, args ...interface{}) { cc.t.vlogf(format, args...) } func (t *Transport) vlogf(format string, args ...interface{}) { if VerboseLogs { t.logf(format, args...) } } func (t *Transport) logf(format string, args ...interface{}) { log.Printf(format, args...) } var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil)) func strSliceContains(ss []string, s string) bool { for _, v := range ss { if v == s { return true } } return false } type erringRoundTripper struct{ err error } func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err } // gzipReader wraps a response body so it can lazily // call gzip.NewReader on the first call to Read type gzipReader struct { body io.ReadCloser // underlying Response.Body zr *gzip.Reader // lazily-initialized gzip reader zerr error // sticky error } func (gz *gzipReader) Read(p []byte) (n int, err error) { if gz.zerr != nil { return 0, gz.zerr } if gz.zr == nil { gz.zr, err = gzip.NewReader(gz.body) if err != nil { gz.zerr = err return 0, err } } return gz.zr.Read(p) } func (gz *gzipReader) Close() error { return gz.body.Close() } type errorReader struct{ err error } func (r errorReader) Read(p []byte) (int, error) { return 0, r.err } // bodyWriterState encapsulates various state around the Transport's writing // of the request body, particularly regarding doing delayed writes of the body // when the request contains "Expect: 100-continue". type bodyWriterState struct { cs *clientStream timer *time.Timer // if non-nil, we're doing a delayed write fnonce *sync.Once // to call fn with fn func() // the code to run in the goroutine, writing the body resc chan error // result of fn's execution delay time.Duration // how long we should delay a delayed write for } func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) { s.cs = cs if body == nil { return } resc := make(chan error, 1) s.resc = resc s.fn = func() { resc <- cs.writeRequestBody(body, cs.req.Body) } s.delay = t.expectContinueTimeout() if s.delay == 0 || !httplex.HeaderValuesContainsToken( cs.req.Header["Expect"], "100-continue") { return } s.fnonce = new(sync.Once) // Arm the timer with a very large duration, which we'll // intentionally lower later. It has to be large now because // we need a handle to it before writing the headers, but the // s.delay value is defined to not start until after the // request headers were written. const hugeDuration = 365 * 24 * time.Hour s.timer = time.AfterFunc(hugeDuration, func() { s.fnonce.Do(s.fn) }) return } func (s bodyWriterState) cancel() { if s.timer != nil { s.timer.Stop() } } func (s bodyWriterState) on100() { if s.timer == nil { // If we didn't do a delayed write, ignore the server's // bogus 100 continue response. return } s.timer.Stop() go func() { s.fnonce.Do(s.fn) }() } // scheduleBodyWrite starts writing the body, either immediately (in // the common case) or after the delay timeout. It should not be // called until after the headers have been written. func (s bodyWriterState) scheduleBodyWrite() { if s.timer == nil { // We're not doing a delayed write (see // getBodyWriterState), so just start the writing // goroutine immediately. go s.fn() return } traceWait100Continue(s.cs.trace) if s.timer.Stop() { s.timer.Reset(s.delay) } }
_vendor/src/golang.org/x/net/http2/transport.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00458452757447958, 0.000297496939310804, 0.00016551413864362985, 0.00017079491226468235, 0.0004903558292426169 ]
{ "id": 3, "code_window": [ "\tNumParams() int\n", "\n", "\t// BoundParams returns bound parameters.\n", "\tBoundParams() [][]byte\n", "\n", "\t// Reset removes all bound parameters.\n", "\tReset()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// SetParamsType sets type for parameters.\n", "\tSetParamsType([]byte)\n", "\n", "\t// GetParamsType returns the type for parameters.\n", "\tGetParamsType() []byte\n", "\n" ], "file_path": "server/driver.go", "type": "add", "edit_start_line_idx": 95 }
Additional IP Rights Grant (Patents) "This implementation" means the copyrightable works distributed by Google as part of the Go project. Google hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer and otherwise run, modify and propagate the contents of this implementation of Go, where such license applies only to those patent claims, both currently owned or controlled by Google and acquired in the future, licensable by Google that are necessarily infringed by this implementation of Go. This grant does not include claims that would be infringed only as a consequence of further modification of this implementation. If you or your agent or exclusive licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that this implementation of Go or any code incorporated within this implementation of Go constitutes direct or contributory patent infringement, or inducement of patent infringement, then any patent rights granted to you under this License for this implementation of Go shall terminate as of the date such litigation is filed.
_vendor/src/golang.org/x/net/PATENTS
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.0001785868953447789, 0.00017530964396428317, 0.00017363880760967731, 0.0001737032289383933, 0.0000023175157366495114 ]
{ "id": 3, "code_window": [ "\tNumParams() int\n", "\n", "\t// BoundParams returns bound parameters.\n", "\tBoundParams() [][]byte\n", "\n", "\t// Reset removes all bound parameters.\n", "\tReset()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// SetParamsType sets type for parameters.\n", "\tSetParamsType([]byte)\n", "\n", "\t// GetParamsType returns the type for parameters.\n", "\tGetParamsType() []byte\n", "\n" ], "file_path": "server/driver.go", "type": "add", "edit_start_line_idx": 95 }
package bolt import "errors" // These errors can be returned when opening or calling methods on a DB. var ( // ErrDatabaseNotOpen is returned when a DB instance is accessed before it // is opened or after it is closed. ErrDatabaseNotOpen = errors.New("database not open") // ErrDatabaseOpen is returned when opening a database that is // already open. ErrDatabaseOpen = errors.New("database already open") // ErrInvalid is returned when both meta pages on a database are invalid. // This typically occurs when a file is not a bolt database. ErrInvalid = errors.New("invalid database") // ErrVersionMismatch is returned when the data file was created with a // different version of Bolt. ErrVersionMismatch = errors.New("version mismatch") // ErrChecksum is returned when either meta page checksum does not match. ErrChecksum = errors.New("checksum error") // ErrTimeout is returned when a database cannot obtain an exclusive lock // on the data file after the timeout passed to Open(). ErrTimeout = errors.New("timeout") ) // These errors can occur when beginning or committing a Tx. var ( // ErrTxNotWritable is returned when performing a write operation on a // read-only transaction. ErrTxNotWritable = errors.New("tx not writable") // ErrTxClosed is returned when committing or rolling back a transaction // that has already been committed or rolled back. ErrTxClosed = errors.New("tx closed") // ErrDatabaseReadOnly is returned when a mutating transaction is started on a // read-only database. ErrDatabaseReadOnly = errors.New("database is in read-only mode") ) // These errors can occur when putting or deleting a value or a bucket. var ( // ErrBucketNotFound is returned when trying to access a bucket that has // not been created yet. ErrBucketNotFound = errors.New("bucket not found") // ErrBucketExists is returned when creating a bucket that already exists. ErrBucketExists = errors.New("bucket already exists") // ErrBucketNameRequired is returned when creating a bucket with a blank name. ErrBucketNameRequired = errors.New("bucket name required") // ErrKeyRequired is returned when inserting a zero-length key. ErrKeyRequired = errors.New("key required") // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize. ErrKeyTooLarge = errors.New("key too large") // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize. ErrValueTooLarge = errors.New("value too large") // ErrIncompatibleValue is returned when trying create or delete a bucket // on an existing non-bucket key or when trying to create or delete a // non-bucket key on an existing bucket key. ErrIncompatibleValue = errors.New("incompatible value") )
_vendor/src/github.com/boltdb/bolt/errors.go
0
https://github.com/pingcap/tidb/commit/b18033423193c39749403b34d87f80acdd5ced07
[ 0.00017544117872603238, 0.00016902884817682207, 0.00016641044931020588, 0.00016804247570689768, 0.0000028857482448074734 ]