/** * parse split chars and return value */ func parse_split(split string) (id byte, value int, err error) { split = strings.ToLower(split) switch split { case "day": id, value = SPLIT_DAY, 1 default: if strings.HasSuffix(split, "hour") { id = SPLIT_HOUR value, err = strconv.Atoi(strings.TrimSuffix(split, "hour")) //fix illegal hour if err == nil && (value < 1 || value > 23) { value = 1 } } else if strings.HasSuffix(split, "min") { id = SPLIT_MIN value, err = strconv.Atoi(strings.TrimSuffix(split, "min")) //fix illegal minute if err == nil && (value > 60 || value < 5) { value = 5 } } else if strings.HasSuffix(split, "m") { id = SPLIT_SIZE value, err = strconv.Atoi(strings.TrimSuffix(split, "m")) //fix illegal size if err == nil && value < 1 { value = 1 } } else { err = errors.New("unknow split") } } return }
func removeTrailingSlash(u *url.URL) { if l := len(u.Path); l > 0 && strings.HasSuffix(u.Path, "/") { u.Path = u.Path[:l-1] } else if l = len(u.Host); l > 0 && strings.HasSuffix(u.Host, "/") { u.Host = u.Host[:l-1] } }
func addTrailingSlash(u *url.URL) { if l := len(u.Path); l > 0 && !strings.HasSuffix(u.Path, "/") { u.Path += "/" } else if l = len(u.Host); l > 0 && !strings.HasSuffix(u.Host, "/") { u.Host += "/" } }
func init() { dir, err := ioutil.TempDir("", "index_pack") if err != nil { panic(fmt.Sprintf("unable to create temp directory: %v", err)) } tempDir = dir // Populate required inputs and source files for the test compilations. for _, unit := range testUnits { for path, data := range testFiles { unit.RequiredInput = append(unit.RequiredInput, &cpb.CompilationUnit_FileInput{ Info: &cpb.FileInfo{ Path: path, Digest: hexDigest([]byte(data)), }, }) switch unit.VName.Language { case "go": if strings.HasSuffix(path, ".go") { unit.SourceFile = append(unit.SourceFile, path) } case "java": if strings.HasSuffix(path, ".java") { unit.SourceFile = append(unit.SourceFile, path) } } } } }
func TestSanitizeURL(t *testing.T) { tests := []struct { input string expected string }{ {"http://foo.bar/", "http://foo.bar"}, {"http://foo.bar", "http://foo.bar"}, // issue #1105 {"http://foo.bar/zoo/", "http://foo.bar/zoo"}, // issue #931 } for i, test := range tests { o1 := SanitizeURL(test.input) o2 := SanitizeURLKeepTrailingSlash(test.input) expected2 := test.expected if strings.HasSuffix(test.input, "/") && !strings.HasSuffix(expected2, "/") { expected2 += "/" } if o1 != test.expected { t.Errorf("[%d] 1: Expected %#v, got %#v\n", i, test.expected, o1) } if o2 != expected2 { t.Errorf("[%d] 2: Expected %#v, got %#v\n", i, expected2, o2) } } }
// ResourceAliases returns the resource shortcuts and plural forms for the given resources. func ResourceAliases(rs []string) []string { as := make([]string, 0, len(rs)) plurals := make(map[string]struct{}, len(rs)) for _, r := range rs { var plural string switch { case r == "endpoints": plural = r // exception. "endpoint" does not exist. Why? case strings.HasSuffix(r, "y"): plural = r[0:len(r)-1] + "ies" case strings.HasSuffix(r, "s"): plural = r + "es" default: plural = r + "s" } as = append(as, plural) plurals[plural] = struct{}{} } for sf, r := range shortForms { if _, found := plurals[r]; found { as = append(as, sf) } } return as }
// ConfigKeyChecker returns a function that will check whether or not // a provide value is valid for the associate config key. Returns an // error if the key is not known. The checker function only performs // syntactic checking of the value, semantic and usage checking must // be done by the caller. User defined keys are always considered to // be valid, e.g. user.* and environment.* keys. func ConfigKeyChecker(key string) (func(value string) error, error) { if f, ok := KnownContainerConfigKeys[key]; ok { return f, nil } if strings.HasPrefix(key, "volatile.") { if strings.HasSuffix(key, ".hwaddr") { return IsAny, nil } if strings.HasSuffix(key, ".name") { return IsAny, nil } } if strings.HasPrefix(key, "environment.") { return IsAny, nil } if strings.HasPrefix(key, "user.") { return IsAny, nil } if strings.HasPrefix(key, "image.") { return IsAny, nil } return nil, fmt.Errorf("Bad key: %s", key) }
func fileExtImpliesText(ext string) (yes, unknown bool) { defer func() { glog.V(2).Infof("'%s' -> yes=%v unknown=%v", ext, yes, unknown) }() if ext == "" { unknown = true return } mt := mime.TypeByExtension(ext) if strings.HasPrefix(mt, "text/") || strings.HasSuffix(mt, "+xml") || strings.HasSuffix(mt, ".json") || strings.HasSuffix(mt, "+json") { // Most likely text. yes = true glog.V(1).Infof("Most likely a text extension: %s", ext) return } if strings.HasPrefix(mt, "audio/") || strings.HasPrefix(mt, "image/") || strings.HasPrefix(mt, "video/") { // Almost certainly not text. glog.V(1).Infof("Most likely a binary extension: %s", ext) return } unknown = true return }
func (r *resolver) handlePTRQuery(ptr string, query *dns.Msg) (*dns.Msg, error) { parts := []string{} if strings.HasSuffix(ptr, ptrIPv4domain) { parts = strings.Split(ptr, ptrIPv4domain) } else if strings.HasSuffix(ptr, ptrIPv6domain) { parts = strings.Split(ptr, ptrIPv6domain) } else { return nil, fmt.Errorf("invalid PTR query, %v", ptr) } host := r.backend.ResolveIP(parts[0]) if len(host) == 0 { return nil, nil } logrus.Debugf("Lookup for IP %s: name %s", parts[0], host) fqdn := dns.Fqdn(host) resp := new(dns.Msg) resp.SetReply(query) setCommonFlags(resp) rr := new(dns.PTR) rr.Hdr = dns.RR_Header{Name: ptr, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL} rr.Ptr = fqdn resp.Answer = append(resp.Answer, rr) return resp, nil }
func scanFolder(url string) { doc, err := goquery.NewDocument(url) if err != nil { log.Fatal(err) } doc.Find("a").Each(func(i int, s *goquery.Selection) { href, _ := s.Attr("href") if strings.HasSuffix(href, ".zip") { c := pool.Borrow() go func() { defer pool.Return(c) filename := download(url, href) if filename != "" { process(filename) } }() } if !strings.HasPrefix(href, "/") && strings.HasSuffix(href, "/") { log.Printf("%+v", href) scanFolder(url + href) } }) }
func makeGoMethod(fun *CFunc, class *Class, name string) *BridgeFunc { gofunc := new(BridgeFunc) gofunc.CFunc = fun gofunc.Receiver = "*" + class.Name gofunc.Name = name gofunc.CgoArguments = append(gofunc.CgoArguments, "self.obj") if len(fun.ParamNames) > 1 { for i, paramName := range fun.ParamNames[1:] { paramType := fun.ParamTypes[i+1] if strings.HasSuffix(paramType, "_Cb") || paramName == "cb" { // does not support callback type return nil } if NOT_SUPPORTED_TYPES.Has(paramType) { return nil } if _, has := RETURN_PARAM_MAPPINGS[paramType]; (strings.HasSuffix(fun.Name, "_get") || FUNCS_WITH_RETURN_PARAM.Has(fun.Name)) && has { // return params gofunc.ConvertReturnParam(paramName, paramType) } else { gofunc.ConvertParam(paramName, paramType) } } } if NOT_SUPPORTED_TYPES.Has(fun.ReturnType) { return nil } if fun.ReturnType != "void" { gofunc.ConvertReturnType(fun.ReturnType) } gofunc.CgoFunc = fun.Name return gofunc }
func convertGlobs(patterns []string) (*regexp.Regexp, error) { if len(patterns) == 0 { return nil, nil } exprs := make([]string, len(patterns)) for i, pattern := range patterns { var prefix, suffix string if strings.HasPrefix(pattern, "**/") { prefix = "(.+/)?" pattern = pattern[len("**/"):] } if strings.HasSuffix(pattern, "/") { suffix = "(/.+)?" pattern = pattern[:len(pattern)-len("/")] } else if strings.HasSuffix(pattern, "/**") { suffix = "(/.+)?" pattern = pattern[:len(pattern)-len("/**")] } exprs[i] = prefix + replacer.Replace(pattern) + suffix } return regexp.Compile(`\A(` + strings.Join(exprs, "|") + `)\z`) }
func (s *localServerSuite) assertGetImageMetadataSources(c *gc.C, stream, officialSourcePath string) { // Create a config that matches s.TestConfig but with the specified stream. envAttrs := s.TestConfig if stream != "" { envAttrs = envAttrs.Merge(coretesting.Attrs{"image-stream": stream}) } cfg, err := config.New(config.NoDefaults, envAttrs) c.Assert(err, gc.IsNil) env, err := environs.New(cfg) c.Assert(err, gc.IsNil) sources, err := imagemetadata.GetMetadataSources(env) c.Assert(err, gc.IsNil) c.Assert(sources, gc.HasLen, 4) var urls = make([]string, len(sources)) for i, source := range sources { url, err := source.URL("") c.Assert(err, gc.IsNil) urls[i] = url } // The image-metadata-url ends with "/juju-dist-test/". c.Check(strings.HasSuffix(urls[0], "/juju-dist-test/"), jc.IsTrue) // The control bucket URL contains the bucket name. c.Check(strings.Contains(urls[1], openstack.ControlBucketName(env)+"/images"), jc.IsTrue) // The product-streams URL ends with "/imagemetadata". c.Check(strings.HasSuffix(urls[2], "/imagemetadata/"), jc.IsTrue) c.Assert(urls[3], gc.Equals, fmt.Sprintf("http://cloud-images.ubuntu.com/%s/", officialSourcePath)) }
func (s *S) TestDirectToUnknownStateMember(c *C) { session, err := mgo.Dial("localhost:40041?connect=direct") c.Assert(err, IsNil) defer session.Close() session.SetMode(mgo.Monotonic, true) result := &struct{ Host string }{} err = session.Run("serverStatus", result) c.Assert(err, IsNil) c.Assert(strings.HasSuffix(result.Host, ":40041"), Equals, true) // We've got no master, so it'll timeout. session.SetSyncTimeout(5e8 * time.Nanosecond) coll := session.DB("mydb").C("mycoll") err = coll.Insert(M{"test": 1}) c.Assert(err, ErrorMatches, "no reachable servers") // Slave is still reachable. result.Host = "" err = session.Run("serverStatus", result) c.Assert(err, IsNil) c.Assert(strings.HasSuffix(result.Host, ":40041"), Equals, true) }
func (e *MergeEnvSuite) TestMergeEnviron(c *gc.C) { // environment does not get fully cleared on Windows // when using testing.IsolationSuite origEnv := os.Environ() extraExpected := []string{ "DUMMYVAR=foo", "DUMMYVAR2=bar", "NEWVAR=ImNew", } expectEnv := make([]string, 0, len(origEnv)+len(extraExpected)) // os.Environ prepends some garbage on Windows that we need to strip out. // All the garbage starts and ends with = (for example "=C:="). for _, v := range origEnv { if !(strings.HasPrefix(v, "=") && strings.HasSuffix(v, "=")) { expectEnv = append(expectEnv, v) } } expectEnv = append(expectEnv, extraExpected...) os.Setenv("DUMMYVAR2", "ChangeMe") os.Setenv("DUMMYVAR", "foo") newEnv := make([]string, 0, len(expectEnv)) for _, v := range runner.MergeWindowsEnvironment([]string{"dummyvar2=bar", "NEWVAR=ImNew"}, os.Environ()) { if !(strings.HasPrefix(v, "=") && strings.HasSuffix(v, "=")) { newEnv = append(newEnv, v) } } c.Assert(expectEnv, jc.SameContents, newEnv) }
func parseSpeed(s string) (float32, bool) { var times float64 = 1 s = strings.ToLower(s) if strings.HasSuffix(s, "/s") { s = s[:len(s)-2] } if strings.HasSuffix(s, "b") { s = s[:len(s)-1] } if strings.HasSuffix(s, "g") { s = s[:len(s)-1] times = 1024 * 1024 * 1024 } else if strings.HasSuffix(s, "m") { s = s[:len(s)-1] times = 1024 * 1024 } else if strings.HasSuffix(s, "k") { s = s[:len(s)-1] times = 1024 } f, err := strconv.ParseFloat(s, 32) if err != nil { return -1, false } else { return float32(f * times), true } }
func NewArchiveFileSystem(name string) (mfs *MemTreeFs, err error) { mfs = &MemTreeFs{ Name: fmt.Sprintf("fs(%s)", name), } if strings.HasSuffix(name, ".zip") { mfs.files, err = NewZipTree(name) } if strings.HasSuffix(name, ".tar.gz") { mfs.files, err = NewTarCompressedTree(name, "gz") } if strings.HasSuffix(name, ".tar.bz2") { mfs.files, err = NewTarCompressedTree(name, "bz2") } if strings.HasSuffix(name, ".tar") { f, err := os.Open(name) if err != nil { return nil, err } mfs.files = NewTarTree(f) } if err != nil { return nil, err } if mfs.files == nil { return nil, errors.New(fmt.Sprintf("Unknown type for %v", name)) } return mfs, nil }
func (b *buildFile) addRemote(container *Container, orig, dest string) error { file, err := utils.Download(orig, ioutil.Discard) if err != nil { return err } defer file.Body.Close() // If the destination is a directory, figure out the filename. if strings.HasSuffix(dest, "/") { u, err := url.Parse(orig) if err != nil { return err } path := u.Path if strings.HasSuffix(path, "/") { path = path[:len(path)-1] } parts := strings.Split(path, "/") filename := parts[len(parts)-1] if filename == "" { return fmt.Errorf("cannot determine filename from url: %s", u) } dest = dest + filename } return container.Inject(file.Body, dest) }
func validateS3BucketName(bucket string) error { // if it's an expandable string, we can't expand yet since we don't have // access to the task config expansions. So, we defer till during runtime // to do the validation if plugin.IsExpandable(bucket) { return nil } if len(bucket) < 3 { return fmt.Errorf("must be at least 3 characters") } if len(bucket) > 63 { return fmt.Errorf("must be no more than 63 characters") } if strings.HasPrefix(bucket, ".") || strings.HasPrefix(bucket, "-") { return fmt.Errorf("must not begin with a period or hyphen") } if strings.HasSuffix(bucket, ".") || strings.HasSuffix(bucket, "-") { return fmt.Errorf("must not end with a period or hyphen") } if strings.Contains(bucket, "..") { return fmt.Errorf("must not have two consecutive periods") } /* if !BucketNameRegex.MatchString(bucket) { return fmt.Errorf("must contain only lowercase letters, numbers," + " hyphens, and periods") } */ return nil }
func TestWalkSkipDirOnFile(t *testing.T) { td, err := ioutil.TempDir("", "walktest") if err != nil { t.Fatal(err) } defer os.RemoveAll(td) if err := os.MkdirAll(filepath.Join(td, "dir"), 0755); err != nil { t.Fatal(err) } touch(t, filepath.Join(td, "dir/foo1")) touch(t, filepath.Join(td, "dir/foo2")) sawFoo2 := false filepath.Walk(td, func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, "foo2") { sawFoo2 = true } if strings.HasSuffix(path, "foo1") { return filepath.SkipDir } return nil }) if sawFoo2 { t.Errorf("SkipDir on file foo1 did not block processing of foo2") } }
func TestLookupGoogleSRV(t *testing.T) { if testing.Short() || !*testExternal { t.Skip("avoid external network") } if !supportsIPv4 || !*testIPv4 { t.Skip("IPv4 is required") } for _, tt := range lookupGoogleSRVTests { cname, srvs, err := LookupSRV(tt.service, tt.proto, tt.name) if err != nil { t.Fatal(err) } if len(srvs) == 0 { t.Error("got no record") } if !strings.HasSuffix(cname, tt.cname) && !strings.HasSuffix(cname, tt.cname+".") { t.Errorf("got %s; want %s", cname, tt.cname) } for _, srv := range srvs { if !strings.HasSuffix(srv.Target, tt.target) && !strings.HasSuffix(srv.Target, tt.target+".") { t.Errorf("got %v; want a record containing %s", srv, tt.target) } } } }
func serveResource(w http.ResponseWriter, req *http.Request) { //log.Println("serveResource") path := "public" + req.URL.Path var contentType string if strings.HasSuffix(path, ".css") { contentType = "text/css" } else if strings.HasSuffix(path, ".png") { contentType = "image/png" } else if strings.HasSuffix(path, ".jpg") { contentType = "image/jpg" } else if strings.HasSuffix(path, ".svg") { contentType = "image/svg+xml" } else if strings.HasSuffix(path, ".js") { contentType = "application/javascript" } else { contentType = "text/plain" } // log.Println(path) // log.Println(contentType) f, err := os.Open(path) if err == nil { defer f.Close() w.Header().Add("Content Type", contentType) br := bufio.NewReader(f) br.WriteTo(w) } else { w.WriteHeader(404) } }
// Lexes a string in single quotes, whitespaces in the string are permitted. // Example: 'foo bar is great' func lexQuotedString(l *lexer) stateFn { // the string only consists of the current fild if strings.HasPrefix(l.input[l.start], "'") && strings.HasSuffix(l.input[l.start], "'") { out := strings.TrimPrefix(l.input[l.start], "'") out = strings.TrimRight(out, "'") l.emit(STRING, out) return lexAttributes } // the string consists of multiple fields out := make([]string, 0) out = append(out, strings.TrimPrefix(l.input[l.start], "'")) l.pos++ for { if l.pos == len(l.input) { l.eof("QuotedString") } if strings.HasSuffix(l.input[l.pos], "'") { out = append(out, strings.TrimRight(l.input[l.pos], "'")) l.emit(STRING, strings.Join(out, " ")) return lexAttributes } out = append(out, l.input[l.pos]) l.pos++ } }
func (s *httpServer) embeddedAssetHandler(w http.ResponseWriter, req *http.Request) { var urlRegex = regexp.MustCompile(`^/static/(.+)$`) matches := urlRegex.FindStringSubmatch(req.URL.Path) if len(matches) == 0 { s.ctx.nsqadmin.logf("ERROR: No embedded asset name for url - %s", req.URL.Path) http.NotFound(w, req) return } assetName := matches[1] s.ctx.nsqadmin.logf("INFO: Requesting embedded asset - %s", assetName) asset, error := templates.Asset(assetName) if error != nil { s.ctx.nsqadmin.logf("ERROR: embedded asset access - %s : %s", assetName, error) http.NotFound(w, req) return } assetLen := len(asset) if strings.HasSuffix(assetName, ".js") { w.Header().Set("Content-Type", "text/javascript") } else if strings.HasSuffix(assetName, ".css") { w.Header().Set("Content-Type", "text/css") } w.Header().Set("Content-Length", fmt.Sprintf("%d", assetLen)) w.Write(asset) }
// setMatch extracts the variables from the URL once a route matches. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { // Store host variables. if v.host != nil { hostVars := v.host.regexp.FindStringSubmatch(getHost(req)) if hostVars != nil { for k, v := range v.host.varsN { m.Vars[v] = hostVars[k+1] } } } // Store path variables. if v.path != nil { pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path) if pathVars != nil { for k, v := range v.path.varsN { m.Vars[v] = pathVars[k+1] } // Check if we should redirect. if r.strictSlash { p1 := strings.HasSuffix(req.URL.Path, "/") p2 := strings.HasSuffix(v.path.template, "/") if p1 != p2 { u, _ := url.Parse(req.URL.String()) if p1 { u.Path = u.Path[:len(u.Path)-1] } else { u.Path += "/" } m.Handler = http.RedirectHandler(u.String(), 301) } } } } }
func stripFlags(args []string) []string { if len(args) < 1 { return args } commands := []string{} inQuote := false for _, y := range args { if !inQuote { switch { case strings.HasPrefix(y, "\""): inQuote = true case strings.Contains(y, "=\""): inQuote = true case !strings.HasPrefix(y, "-"): commands = append(commands, y) } } if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") { inQuote = false } } return commands }
func (s *apiService) getSystemBrowse(w http.ResponseWriter, r *http.Request) { qs := r.URL.Query() current := qs.Get("current") if current == "" { if roots, err := osutil.GetFilesystemRoots(); err == nil { sendJSON(w, roots) } else { http.Error(w, err.Error(), 500) } return } search, _ := osutil.ExpandTilde(current) pathSeparator := string(os.PathSeparator) if strings.HasSuffix(current, pathSeparator) && !strings.HasSuffix(search, pathSeparator) { search = search + pathSeparator } subdirectories, _ := osutil.Glob(search + "*") ret := make([]string, 0, len(subdirectories)) for _, subdirectory := range subdirectories { info, err := os.Stat(subdirectory) if err == nil && info.IsDir() { ret = append(ret, subdirectory+pathSeparator) } } sendJSON(w, ret) }
func (s *S) TestDirect(c *C) { session, err := mgo.Dial("localhost:40012?connect=direct") c.Assert(err, IsNil) defer session.Close() // We know that server is a slave. session.SetMode(mgo.Monotonic, true) result := &struct{ Host string }{} err = session.Run("serverStatus", result) c.Assert(err, IsNil) c.Assert(strings.HasSuffix(result.Host, ":40012"), Equals, true) stats := mgo.GetStats() c.Assert(stats.SocketsAlive, Equals, 1) c.Assert(stats.SocketsInUse, Equals, 1) c.Assert(stats.SocketRefs, Equals, 1) // We've got no master, so it'll timeout. session.SetSyncTimeout(5e8 * time.Nanosecond) coll := session.DB("mydb").C("mycoll") err = coll.Insert(M{"test": 1}) c.Assert(err, ErrorMatches, "no reachable servers") // Slave is still reachable. result.Host = "" err = session.Run("serverStatus", result) c.Assert(err, IsNil) c.Assert(strings.HasSuffix(result.Host, ":40012"), Equals, true) }
// KindToResource converts Kind to a resource name. func KindToResource(kind unversioned.GroupVersionKind, mixedCase bool) (plural, singular unversioned.GroupVersionResource) { kindName := kind.Kind if len(kindName) == 0 { return } if mixedCase { // Legacy support for mixed case names singular = kind.GroupVersion().WithResource(strings.ToLower(kindName[:1]) + kindName[1:]) } else { singular = kind.GroupVersion().WithResource(strings.ToLower(kindName)) } singularName := singular.Resource if strings.HasSuffix(singularName, "endpoints") || strings.HasSuffix(singularName, "securitycontextconstraints") { plural = singular } else { switch string(singularName[len(singularName)-1]) { case "s": plural = kind.GroupVersion().WithResource(singularName + "es") case "y": plural = kind.GroupVersion().WithResource(strings.TrimSuffix(singularName, "y") + "ies") default: plural = kind.GroupVersion().WithResource(singularName + "s") } } return }
func Profile(ctx *middleware.Context) { ctx.Data["Title"] = "Profile" ctx.Data["PageIsUserProfile"] = true uname := ctx.Params(":username") // Special handle for FireFox requests favicon.ico. if uname == "favicon.ico" { ctx.Redirect(setting.AppSubUrl + "/img/favicon.png") return } else if strings.HasSuffix(uname, ".png") { ctx.Error(404) return } isShowKeys := false if strings.HasSuffix(uname, ".keys") { isShowKeys = true uname = strings.TrimSuffix(uname, ".keys") } u, err := models.GetUserByName(uname) if err != nil { if models.IsErrUserNotExist(err) { ctx.Handle(404, "GetUserByName", err) } else { ctx.Handle(500, "GetUserByName", err) } return } // Show SSH keys. if isShowKeys { ShowSSHKeys(ctx, u.Id) return } if u.IsOrganization() { showOrgProfile(ctx) return } ctx.Data["Owner"] = u tab := ctx.Query("tab") ctx.Data["TabName"] = tab switch tab { case "activity": retrieveFeeds(ctx, u.Id, 0, true) if ctx.Written() { return } default: ctx.Data["Repos"], err = models.GetRepositories(u.Id, ctx.IsSigned && ctx.User.Id == u.Id) if err != nil { ctx.Handle(500, "GetRepositories", err) return } } ctx.HTML(200, PROFILE) }