Exemple #1
1
func urlShortenerMain(client *http.Client, argv []string) {
	if len(argv) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx     (to look up details)\n")
		fmt.Fprintf(os.Stderr, "       urlshortener http://example.com/long (to shorten)\n")
		return
	}

	svc, _ := urlshortener.New(client)
	urlstr := argv[0]

	// short -> long
	if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
		url, err := svc.Url.Get(urlstr).Do()
		if err != nil {
			log.Fatalf("URL Get: %v", err)
		}
		fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
		return
	}

	// long -> short
	url, err := svc.Url.Insert(&urlshortener.Url{
		Kind:    "urlshortener#url", // Not really needed
		LongUrl: urlstr,
	}).Do()
	if err != nil {
		log.Fatalf("URL Insert: %v", err)
	}
	fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
// When a test is skipped or fails, runtime.Goexit() is called which destroys the callstack.
// This means the name of the test case is lost, so we need to grab a copy of pc before.
func Report(t testing.TB) {
	// If the goroutine panics, Fatal()s, or Skip()s, the function name is at the 3rd callstack
	// layer.  On success, its at 1st.  Since it's hard to check which happened, just try both.
	pcs := make([]uintptr, 10)
	total := runtime.Callers(1, pcs)
	var name string
	for _, pc := range pcs[:total] {
		fn := runtime.FuncForPC(pc)
		fullName := fn.Name()
		if strings.HasPrefix(path.Ext(fullName), ".Test") {
			// Skip the leading .
			name = string([]byte(path.Ext(fullName))[1:])
			break
		}
	}
	if name == "" {
		return
	}

	allCaseInfos.lock.Lock()
	defer allCaseInfos.lock.Unlock()
	allCaseInfos.Cases = append(allCaseInfos.Cases, &caseInfo{
		Name:    name,
		Passed:  !t.Failed() && !t.Skipped(),
		Skipped: t.Skipped(),
		Fatal:   t.Failed() && !strings.HasPrefix(name, "TestSoon"),
	})
}
Exemple #3
0
//export setScreen
func setScreen(scale int) {
	C.uname(&C.sysInfo)
	name := C.GoString(&C.sysInfo.machine[0])

	var v float32

	switch {
	case strings.HasPrefix(name, "iPhone"):
		v = 163
	case strings.HasPrefix(name, "iPad"):
		// TODO: is there a better way to distinguish the iPad Mini?
		switch name {
		case "iPad2,5", "iPad2,6", "iPad2,7", "iPad4,4", "iPad4,5", "iPad4,6", "iPad4,7":
			v = 163 // iPad Mini
		default:
			v = 132
		}
	default:
		v = 163 // names like i386 and x86_64 are the simulator
	}

	if v == 0 {
		log.Printf("unknown machine: %s", name)
		v = 163 // emergency fallback
	}

	pixelsPerPt = v * float32(scale) / 72
	screenScale = scale
}
Exemple #4
0
// checkSourceURI performs a check on the URI associated with the build
// to make sure that it is live before proceeding with the build.
func (d *DockerBuilder) checkSourceURI() error {
	rawurl := d.build.Spec.Source.Git.URI
	if !d.git.ValidCloneSpec(rawurl) {
		return fmt.Errorf("Invalid git source url: %s", rawurl)
	}
	if strings.HasPrefix(rawurl, "git://") || strings.HasPrefix(rawurl, "git@") {
		return nil
	}
	if !strings.HasPrefix(rawurl, "http://") && !strings.HasPrefix(rawurl, "https://") {
		rawurl = fmt.Sprintf("https://%s", rawurl)
	}
	srcURL, err := url.Parse(rawurl)
	if err != nil {
		return err
	}
	host := srcURL.Host
	if strings.Index(host, ":") == -1 {
		switch srcURL.Scheme {
		case "http":
			host += ":80"
		case "https":
			host += ":443"
		}
	}
	dialer := net.Dialer{Timeout: d.urlTimeout}
	conn, err := dialer.Dial("tcp", host)
	if err != nil {
		return err
	}
	return conn.Close()

}
func (app *AppPlugin) initApp() {
	app.initFrontendPlugin()

	// check if we have child panels
	for _, panel := range Panels {
		if strings.HasPrefix(panel.PluginDir, app.PluginDir) {
			panel.setPathsBasedOnApp(app)
			app.FoundChildPlugins = append(app.FoundChildPlugins, &PluginInclude{
				Name: panel.Name,
				Id:   panel.Id,
				Type: panel.Type,
			})
		}
	}

	// check if we have child datasources
	for _, ds := range DataSources {
		if strings.HasPrefix(ds.PluginDir, app.PluginDir) {
			ds.setPathsBasedOnApp(app)
			app.FoundChildPlugins = append(app.FoundChildPlugins, &PluginInclude{
				Name: ds.Name,
				Id:   ds.Id,
				Type: ds.Type,
			})
		}
	}

	// slugify pages
	for _, page := range app.Pages {
		if page.Slug == "" {
			page.Slug = slug.Make(page.Name)
		}
	}
}
Exemple #6
0
func (g *gajimImporter) importAccounts(f string) (map[string]gajimAccountInfo, bool) {
	file, err := os.Open(f)
	if err != nil {
		return nil, false
	}

	defer file.Close()
	sc := bufio.NewScanner(file)

	accountSettings := make(map[string]map[string]string)
	proxies := make(map[string]map[string]string)

	for sc.Scan() {
		val := sc.Text()
		ln := strings.SplitN(val, " = ", 2)
		if len(ln) == 2 {
			key := ln[0]
			switch {
			case strings.HasPrefix(key, "accounts."):
				addNamedValue(accountSettings, ln, "accounts.")
			case strings.HasPrefix(key, "proxies."):
				addNamedValue(proxies, ln, "proxies.")
			}
		}
	}

	accountInfo := make(map[string]gajimAccountInfo)

	for k, v := range accountSettings {
		accountInfo[k] = transformSettingsIntoAccount(k, v, proxies)
	}

	return accountInfo, true
}
Exemple #7
0
func (self *Table) AddColumn(name string, columnType string, defval sqltypes.Value, extra string, isPk, nullable bool) {
	index := len(self.Columns)
	self.Columns = append(self.Columns, TableColumn{Name: name})
	self.Columns[index].IsPk = isPk
	self.Columns[index].Nullable = nullable
	if strings.Contains(columnType, "int") {
		self.Columns[index].Category = CAT_NUMBER
	} else if strings.HasPrefix(columnType, "varbinary") {
		self.Columns[index].Category = CAT_VARBINARY
	} else if strings.HasPrefix(columnType, "fractional") {
		self.Columns[index].Category = CAT_FRACTIONAL
	} else {
		self.Columns[index].Category = CAT_OTHER
	}

	if extra == "auto_increment" {
		self.Columns[index].IsAuto = true
		self.Columns[index].NextId = 0
		// Ignore default value, if any
		return
	} else if extra == "uuid" {
		self.Columns[index].IsUUID = true
	}

	if defval.IsNull() {
		return
	}
	if self.Columns[index].Category == CAT_NUMBER {
		self.Columns[index].Default = sqltypes.MakeNumeric(defval.Raw())
	} else {
		self.Columns[index].Default = sqltypes.MakeString(defval.Raw())
	}
}
Exemple #8
0
func (m *manager) registerCollectors(collectorConfigs map[string]string, cont *containerData) error {
	for k, v := range collectorConfigs {
		configFile, err := cont.ReadFile(v, m.inHostNamespace)
		if err != nil {
			return fmt.Errorf("failed to read config file %q for config %q, container %q: %v", k, v, cont.info.Name, err)
		}
		glog.V(3).Infof("Got config from %q: %q", v, configFile)

		if strings.HasPrefix(k, "prometheus") || strings.HasPrefix(k, "Prometheus") {
			newCollector, err := collector.NewPrometheusCollector(k, configFile)
			if err != nil {
				glog.Infof("failed to create collector for container %q, config %q: %v", cont.info.Name, k, err)
				return err
			}
			err = cont.collectorManager.RegisterCollector(newCollector)
			if err != nil {
				glog.Infof("failed to register collector for container %q, config %q: %v", cont.info.Name, k, err)
				return err
			}
		} else {
			newCollector, err := collector.NewCollector(k, configFile)
			if err != nil {
				glog.Infof("failed to create collector for container %q, config %q: %v", cont.info.Name, k, err)
				return err
			}
			err = cont.collectorManager.RegisterCollector(newCollector)
			if err != nil {
				glog.Infof("failed to register collector for container %q, config %q: %v", cont.info.Name, k, err)
				return err
			}
		}
	}
	return nil
}
Exemple #9
0
func enable(c *cli.Context) {
	changed := false
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatal(err)
	}

	for _, service := range c.Args() {
		if val, ok := cfg.Rancher.ServicesInclude[service]; !ok || !val {
			if strings.HasPrefix(service, "/") && !strings.HasPrefix(service, "/var/lib/rancher/conf") {
				log.Fatalf("ERROR: Service should be in path /var/lib/rancher/conf")
			}
			if _, err := compose.LoadServiceResource(service, true, cfg); err != nil {
				log.Fatalf("could not load service %s", service)
			}
			cfg.Rancher.ServicesInclude[service] = true
			changed = true
		}
	}

	if changed {
		if err := cfg.Set("rancher.services_include", cfg.Rancher.ServicesInclude); err != nil {
			log.Fatal(err)
		}
	}
}
Exemple #10
0
func (vtc *VtConn) handleErr(err error) (int, error) {
	now := time.Now()
	if vtc.timeFailed.IsZero() {
		vtc.timeFailed = now
	} else if now.Sub(vtc.timeFailed) > vtc.recoveryTimeout() {
		vtc.Close()
		return ErrTypeFatal, fmt.Errorf("vt: max recovery time exceeded: %v", err)
	}

	errType := ErrTypeApp
	if tabletErr, ok := err.(TabletError); ok {
		msg := strings.ToLower(tabletErr.err.Error())
		if strings.HasPrefix(msg, "fatal") {
			errType = ErrTypeFatal
		} else if strings.HasPrefix(msg, "retry") {
			errType = ErrTypeRetry
		}
	} else if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
		errType = ErrTypeRetry
	}

	if errType == ErrTypeRetry && vtc.TransactionId != 0 {
		errType = ErrTypeApp
		err = fmt.Errorf("vt: cannot retry within a transaction: %v", err)
		time.Sleep(vtc.reconnectDelay)
		vtc.Close()
		dialErr := vtc.dial()
		log.Warningf("vt: redial error %v", dialErr)
	}

	return errType, err
}
Exemple #11
0
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
}
// URLsFromText extracts URLs from the email text bodies
func URLsFromText(con *data.Context, em *Email) ([]string, error) {
	if em == nil {
		return nil, nil
	}

	for _, t := range em.Texts {
		if strings.HasPrefix(t.ContentType, contentTypeHTML) {
			u, err := parseHTMLBody(con, t.Body)
			if err != nil {
				con.Log.Debugf("URLsFromText error while parsing HTML", err)
				continue
			}
			return u, nil
		}

		if strings.HasPrefix(t.ContentType, contentTypeText) {
			u, err := parseTextBody(con, t.Body)
			if err != nil {
				con.Log.Debugf("URLsFromText error while parsing Text", err)
				continue
			}
			return u, nil
		}
	}

	return nil, fmt.Errorf("Could not find an URL in the body.")
}
Exemple #13
0
func darwinFuseCheckVersion(node *core.IpfsNode) error {
	// on OSX, check FUSE version.
	if runtime.GOOS != "darwin" {
		return nil
	}

	ov, errGFV := tryGFV()
	if errGFV != nil {
		// if we failed AND the user has told us to ignore the check we
		// continue. this is in case fuse-version breaks or the user cannot
		// install it, but is sure their fuse version will work.
		if skip, err := userAskedToSkipFuseCheck(node); err != nil {
			return err
		} else if skip {
			return nil // user told us not to check version... ok....
		} else {
			return errGFV
		}
	}

	log.Debug("mount: osxfuse version:", ov)
	if strings.HasPrefix(ov, "2.7.") || strings.HasPrefix(ov, "2.8.") {
		return nil
	}

	return fmt.Errorf(errStrUpgradeFuse, ov)
}
Exemple #14
0
func (conf *Config) EnvListForEndpoint(dockerEndpoint, poolName string) ([]string, error) {
	tsuruEndpoint, _ := config.GetString("host")
	if !strings.HasPrefix(tsuruEndpoint, "http://") && !strings.HasPrefix(tsuruEndpoint, "https://") {
		tsuruEndpoint = "http://" + tsuruEndpoint
	}
	tsuruEndpoint = strings.TrimRight(tsuruEndpoint, "/") + "/"
	endpoint := dockerEndpoint
	socket, _ := config.GetString("docker:bs:socket")
	if socket != "" {
		endpoint = "unix:///var/run/docker.sock"
	}
	token, err := conf.getToken()
	if err != nil {
		return nil, err
	}
	envList := []string{
		"DOCKER_ENDPOINT=" + endpoint,
		"TSURU_ENDPOINT=" + tsuruEndpoint,
		"TSURU_TOKEN=" + token,
		"SYSLOG_LISTEN_ADDRESS=udp://0.0.0.0:" + strconv.Itoa(container.BsSysLogPort()),
	}
	envMap := EnvMap{}
	poolEnvMap := PoolEnvMap{}
	err = conf.UpdateEnvMaps(envMap, poolEnvMap)
	if err != nil {
		return nil, err
	}
	for envName, envValue := range envMap {
		envList = append(envList, fmt.Sprintf("%s=%s", envName, envValue))
	}
	for envName, envValue := range poolEnvMap[poolName] {
		envList = append(envList, fmt.Sprintf("%s=%s", envName, envValue))
	}
	return envList, nil
}
Exemple #15
0
// ServeHTTP implements the httpserver.Handler interface and serves requests,
// setting headers on the response according to the configured rules.
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	replacer := httpserver.NewReplacer(r, nil, "")
	rww := &responseWriterWrapper{w: w}
	for _, rule := range h.Rules {
		if httpserver.Path(r.URL.Path).Matches(rule.Path) {
			for name := range rule.Headers {

				// One can either delete a header, add multiple values to a header, or simply
				// set a header.

				if strings.HasPrefix(name, "-") {
					rww.delHeader(strings.TrimLeft(name, "-"))
				} else if strings.HasPrefix(name, "+") {
					for _, value := range rule.Headers[name] {
						rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
					}
				} else {
					for _, value := range rule.Headers[name] {
						rww.Header().Set(name, replacer.Replace(value))
					}
				}
			}
		}
	}
	return h.Next.ServeHTTP(rww, r)
}
Exemple #16
0
func (s *Site) appendThemeTemplates(in []string) []string {
	if s.hasTheme() {
		out := []string{}
		// First place all non internal templates
		for _, t := range in {
			if !strings.HasPrefix(t, "_internal/") {
				out = append(out, t)
			}
		}

		// Then place theme templates with the same names
		for _, t := range in {
			if !strings.HasPrefix(t, "_internal/") {
				out = append(out, "theme/"+t)
			}
		}

		// Lastly place internal templates
		for _, t := range in {
			if strings.HasPrefix(t, "_internal/") {
				out = append(out, t)
			}
		}
		return out
	} else {
		return in
	}
}
Exemple #17
0
func absPathify(inPath string) string {
	jww.INFO.Println("Trying to resolve absolute path to", inPath)

	if strings.HasPrefix(inPath, "$HOME") {
		inPath = userHomeDir() + inPath[5:]
	}

	if strings.HasPrefix(inPath, "$") {
		end := strings.Index(inPath, string(os.PathSeparator))
		inPath = os.Getenv(inPath[1:end]) + inPath[end:]
	}

	if filepath.IsAbs(inPath) {
		return filepath.Clean(inPath)
	}

	p, err := filepath.Abs(inPath)
	if err == nil {
		return filepath.Clean(p)
	} else {
		jww.ERROR.Println("Couldn't discover absolute path")
		jww.ERROR.Println(err)
	}
	return ""
}
Exemple #18
0
// parsePath parses an XPath-like string describing a path
// through an element tree and returns a slice of segment
// descriptors.
func (c *compiler) parsePath(path string) []segment {
	// If path starts or ends with //, fix it
	if strings.HasPrefix(path, "//") {
		path = "." + path
	}
	if strings.HasSuffix(path, "//") {
		path = path + "*"
	}

	// Paths cannot be absolute
	if strings.HasPrefix(path, "/") {
		c.err = ErrPath("paths cannot be absolute.")
		return nil
	}

	// Split path into segment objects
	var segments []segment
	for _, s := range splitPath(path) {
		segments = append(segments, c.parseSegment(s))
		if c.err != ErrPath("") {
			break
		}
	}
	return segments
}
Exemple #19
0
// number returns a parsable number string, along with its base.
func (p ParamList) number(index int) (string, int) {
	var sign string
	value := strings.ToLower(p[index])

	if len(value) == 0 {
		return "", 0
	}

	if value[0] == '-' || value[0] == '+' {
		sign = value[:1]
		value = value[1:]
	}

	if strings.HasPrefix(value, "0b") {
		return sign + value[2:], 2
	}

	if strings.HasPrefix(value, "0x") {
		return sign + value[2:], 16
	}

	if strings.HasPrefix(value, "0") {
		return sign + value, 8
	}

	return sign + value, 10
}
// Split a version into parts.
// "1.2.3-beta.2" -> []int{1, 2, 3}, []interface{}{"beta", 2}
func versionParts(v string) ([]int, []interface{}) {
	if strings.HasPrefix(v, "v") || strings.HasPrefix(v, "V") {
		// Strip initial 'v' or 'V' prefix if present.
		v = v[1:]
	}
	parts := strings.SplitN(v, "+", 2)
	parts = strings.SplitN(parts[0], "-", 2)
	fields := strings.Split(parts[0], ".")

	release := make([]int, len(fields))
	for i, s := range fields {
		v, _ := strconv.Atoi(s)
		release[i] = v
	}

	var prerelease []interface{}
	if len(parts) > 1 {
		fields = strings.Split(parts[1], ".")
		prerelease = make([]interface{}, len(fields))
		for i, s := range fields {
			v, err := strconv.Atoi(s)
			if err == nil {
				prerelease[i] = v
			} else {
				prerelease[i] = s
			}
		}
	}

	return release, prerelease
}
Exemple #21
0
func cmdPipe() {
	for {
		message, ok := <-CmdChan
		if !ok {
			continue
		}

		if strings.HasPrefix(message, "Welcome,") || strings.HasPrefix(message, "ERROR") || message == "" {
			continue
		}

		Debug("Command: " + message)

		message = words2Int(cmdStopWords(message))

		re := regexp.MustCompile("[ ]{2,}")
		message = re.ReplaceAllString(strings.TrimSpace(message), " ")

		Debug("Normalized Command: " + message)

		args := strings.Split(message, " ")

		if event, ok := EventList[args[0]]; ok {
			event.Run(args[1:]...)
		} else {
			Debug("Invalid command!")
			EventList["notify"].Fn("Invalid command from Echo Tunnel.")
		}
	}
}
Exemple #22
0
func subj(m *imap.Msg) string {
	s := m.Hdr.Subject
	for strings.HasPrefix(s, "Re: ") || strings.HasPrefix(s, "RE: ") {
		s = s[4:]
	}
	return s
}
Exemple #23
0
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
}
Exemple #24
0
func isartificial(n *Node) bool {
	// compiler-emitted artificial things that we do not want to instrument,
	// cant' possibly participate in a data race.
	if n.Op == ONAME && n.Sym != nil && n.Sym.Name != "" {
		if n.Sym.Name == "_" {
			return true
		}

		// autotmp's are always local
		if strings.HasPrefix(n.Sym.Name, "autotmp_") {
			return true
		}

		// statictmp's are read-only
		if strings.HasPrefix(n.Sym.Name, "statictmp_") {
			return true
		}

		// go.itab is accessed only by the compiler and runtime (assume safe)
		if n.Sym.Pkg != nil && n.Sym.Pkg.Name != "" && n.Sym.Pkg.Name == "go.itab" {
			return true
		}
	}

	return false
}
Exemple #25
0
func getExternalIPByURL(url string) net.IP {
	if verbose {
		fmt.Printf("Connecting to %v...\n", url)
	}

	if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
		url = "http://" + url
	}

	content, err := getResponse(url)
	if err != nil {
		if verbose {
			fmt.Printf("%v\n", err)
		}
		return nil
	}

	ip := regex.FindString(content)

	currentIP := net.ParseIP(ip)

	if currentIP != nil {
		return currentIP
	}

	return nil
}
Exemple #26
0
func (repo RemoteEndpointRepository) UpdateEndpoint(endpoint string) (finalEndpoint string, apiErr error) {
	defer func() {
		if apiErr != nil {
			repo.config.SetApiEndpoint("")
		}
	}()

	endpointMissingScheme := !strings.HasPrefix(endpoint, "https://") && !strings.HasPrefix(endpoint, "http://")

	if endpointMissingScheme {
		finalEndpoint := "https://" + endpoint
		apiErr := repo.attemptUpdate(finalEndpoint)

		switch apiErr.(type) {
		case nil:
		case *errors.InvalidSSLCert:
			return endpoint, apiErr
		default:
			finalEndpoint = "http://" + endpoint
			apiErr = repo.attemptUpdate(finalEndpoint)
		}

		return finalEndpoint, apiErr
	} else {
		apiErr := repo.attemptUpdate(endpoint)
		return endpoint, apiErr
	}
}
Exemple #27
0
// ResolveImageID returns latest TagEvent for specified imageID and an error if
// there's more than one image matching the ID or when one does not exist.
func ResolveImageID(stream *ImageStream, imageID string) (*TagEvent, error) {
	var event *TagEvent
	set := sets.NewString()
	for _, history := range stream.Status.Tags {
		for i := range history.Items {
			tagging := &history.Items[i]
			if d, err := digest.ParseDigest(tagging.Image); err == nil {
				if strings.HasPrefix(d.Hex(), imageID) || strings.HasPrefix(tagging.Image, imageID) {
					event = tagging
					set.Insert(tagging.Image)
				}
				continue
			}
			if strings.HasPrefix(tagging.Image, imageID) {
				event = tagging
				set.Insert(tagging.Image)
			}
		}
	}
	switch len(set) {
	case 1:
		return &TagEvent{
			Created:              unversioned.Now(),
			DockerImageReference: event.DockerImageReference,
			Image:                event.Image,
		}, nil
	case 0:
		return nil, errors.NewNotFound(Resource("imagestreamimage"), imageID)
	default:
		return nil, errors.NewConflict(Resource("imagestreamimage"), imageID, fmt.Errorf("multiple images match the prefix %q: %s", imageID, strings.Join(set.List(), ", ")))
	}
}
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
}
Exemple #29
0
// Test key consistency
func TestKeyMatch(t *testing.T) {
	tree1 := new(MemPrefixTree)
	tree1.Init()
	for i := 1; i < 100; i++ {
		tree1.Insert(Zi(P_SKS, 65537*i+i))
	}
	// Some extra samples
	for i := 1; i < 50; i++ {
		tree1.Insert(Zi(P_SKS, 68111*i))
	}
	tree2 := new(MemPrefixTree)
	tree2.Init()
	for i := 1; i < 100; i++ {
		tree2.Insert(Zi(P_SKS, 65537*i))
	}
	// One extra sample
	for i := 1; i < 20; i++ {
		tree2.Insert(Zi(P_SKS, 70001*i))
	}
	for i := 1; i < 100; i++ {
		zi := Zi(P_SKS, 65537*i)
		bs := NewZpBitstring(zi)
		node1, err := Find(tree1, zi)
		assert.Equal(t, err, nil)
		node2, err := Find(tree2, zi)
		assert.Equal(t, err, nil)
		t.Logf("node1=%v, node2=%v (%b) full=%v", node1.Key(), node2.Key(), zi.Int64(), bs)
		// If keys are different, one must prefix the other.
		assert.T(t, strings.HasPrefix(node1.Key().String(), node2.Key().String()) ||
			strings.HasPrefix(node2.Key().String(), node1.Key().String()))
	}
}
Exemple #30
0
func (p *prefixFileSystem) ReadDir(name string) ([]os.FileInfo, error) {
	if strings.HasPrefix(name, p.prefix) {
		return p.real.ReadDir(p.innerPath(name))
		/*fis, err := p.real.ReadDir(p.innerPath(name))
		goon.DumpExpr(len(fis))
		goon.DumpExpr(fis[0].Name())
		goon.DumpExpr(fis[0].Size())
		goon.DumpExpr(fis[0].Mode())
		goon.DumpExpr(fis[0].ModTime())
		goon.DumpExpr(fis[0].IsDir())
		goon.DumpExpr(fis[0].Sys())
		return fis, err*/
	}

	if !strings.HasPrefix(p.prefix, name) {
		return nil, errors.New(name + " doesn't exist")
	}

	// TODO.
	return []os.FileInfo{&util.FileInfo{
		Name_: antibase(strings.TrimPrefix(p.prefix, name)),
		Mode_: os.ModeDir,
		/*Size_: 0,
		ModTime_ : time.Now().UTC(),
		Sys_: nil,*/
	}}, nil
}