Exemple #1
0
func renderMarkdown(appDir string, path string, markdownContent string, jsonContent map[string]interface{}) {
	renderer, extensions := configureBlackFriday(path)
	content := blackfriday.Markdown([]byte(markdownContent), renderer, extensions)

	re2 := regexp.MustCompile("/content/")
	src := []byte(path)
	replacement := []byte("/views/")
	htmlPath := re2.ReplaceAll(src, replacement)
	template, _ := loadHTML(appDir, string(htmlPath))

	result, err := ParseAndInsert(appDir, string(content), jsonContent, template)
	if err != nil {
		log.Fatal(err)
	}

	re := regexp.MustCompile("/content/(.+)")
	if matches := re.FindStringSubmatch(path); matches != nil && len(matches) == 2 {
		oldPath := matches[1]
		//tmpPath is the expected location before some manipulation around the filename, e.g. convert
		// blah.fuel to blah.html
		tmpPath := fmt.Sprintf("%s/public/%s", appDir, oldPath)
		//convert from .fuel to .html
		newDir, newPath := convertFromFuelToHTML(tmpPath)
		//make the new dir in public
		os.MkdirAll(newDir, 0777)
		//output is a []byte -- write it to a file
		ioutil.WriteFile(newPath, []byte(result), 0644)
	}
}
Exemple #2
0
func TestProjectType(t *testing.T) {
	t.Parallel()
	h := parsecli.NewHarness(t)
	defer h.Stop()

	h.MakeEmptyRoot()
	ensure.Nil(t, parsecli.CloneSampleCloudCode(h.Env, false))

	c := &configureCmd{}
	err := c.projectType(h.Env, []string{"1", "2"})
	ensure.Err(t, err, regexp.MustCompile("only an optional project type argument is expected"))

	h.Env.In = ioutil.NopCloser(strings.NewReader("invalid\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Err.String(), "Invalid selection. Please enter a number")
	ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
	h.Err.Reset()
	h.Out.Reset()

	h.Env.In = ioutil.NopCloser(strings.NewReader("0\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Err.String(), "Please enter a number between 1 and")
	ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
	h.Err.Reset()
	h.Out.Reset()

	h.Env.In = ioutil.NopCloser(strings.NewReader("1\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Out.String(), "Successfully set project type to: parse")
	ensure.Nil(t, err)
}
Exemple #3
0
func TestParserEmail(t *testing.T) {
	t.Parallel()

	h := parsecli.NewTokenHarness(t)
	h.MakeEmptyRoot()
	defer h.Stop()

	ensure.Nil(t, parsecli.CreateConfigWithContent(filepath.Join(h.Env.Root, parsecli.ParseLocal), "{}"))
	ensure.Nil(t,
		parsecli.CreateConfigWithContent(
			filepath.Join(h.Env.Root, parsecli.ParseProject),
			`{"project_type": 1}`,
		),
	)

	var c configureCmd
	ensure.Nil(t, c.parserEmail(h.Env, []string{"email2"}))
	ensure.DeepEqual(
		t,
		h.Out.String(),
		`Successfully configured email for current project to: "email2"
`,
	)

	ensure.Err(t, c.parserEmail(h.Env, nil), regexp.MustCompile("Invalid args:"))
	ensure.Err(t, c.parserEmail(h.Env, []string{"a", "b"}), regexp.MustCompile("Invalid args:"))
}
Exemple #4
0
// agentDoing returns what hook or action, if any,
// the agent is currently executing.
// The hook name or action is extracted from the agent message.
func agentDoing(status statusInfoContents) string {
	if status.Current != params.StatusExecuting {
		return ""
	}
	// First see if we can determine a hook name.
	var hookNames []string
	for _, h := range hooks.UnitHooks() {
		hookNames = append(hookNames, string(h))
	}
	for _, h := range hooks.RelationHooks() {
		hookNames = append(hookNames, string(h))
	}
	hookExp := regexp.MustCompile(fmt.Sprintf(`running (?P<hook>%s?) hook`, strings.Join(hookNames, "|")))
	match := hookExp.FindStringSubmatch(status.Message)
	if len(match) > 0 {
		return match[1]
	}
	// Now try for an action name.
	actionExp := regexp.MustCompile(`running action (?P<action>.*)`)
	match = actionExp.FindStringSubmatch(status.Message)
	if len(match) > 0 {
		return match[1]
	}
	return ""
}
Exemple #5
0
// Parse the given path to return a regex and slice of param names.
//
// Path: /foo/:param1/bar/:param2/baz
// => ^/foo/(.*)/bar/(.*)/baz$
// => [":param1", :param2]
func (this *Route) CompileRegex(path string) *regexp.Regexp {
	// Compile the the param finder.
	finder := regexp.MustCompile(`:[a-zA-Z0-9]+`)
	// Find param names.
	this.ParamNames = finder.FindAllString(path, -1)
	// Clean the param names we got.
	for i, name := range this.ParamNames {
		this.ParamNames[i] = name[1:]
	}
	// If the route is not case-sensitive then add the regex flag for case-insensitive.
	if this.CaseSensitive == false {
		path = "(?i)" + path
	}
	// For each param name found, replace it with a regex group.
	for _, param := range this.ParamNames {
		path = strings.Replace(path, ":"+param, "([^/]+)", 1)
	}
	// If the path does not end in with "*", then force a line end match.
	if path[len(path)-1:] != "*" {
		if this.Strict == false && path[len(path)-1:] == "/" {
			path = path + "?"
		}
		path = path + "$"
	}
	// Build the regexp used for all future request to this route.
	matcher := regexp.MustCompile("^" + path)
	return matcher
}
func TestLowerPercentile(t *testing.T) {
	// Some data with expected mean of 20
	d := []byte("time:0|ms\ntime:1|ms\ntime:2|ms\ntime:3|ms")
	packets := udp.ParseMessage(d, prefix_internal, output, udp.ParseLine)

	pct, _ := timers.NewPercentiles("-75")
	ti := timers.New("", *pct)

	for _, p := range packets {
		ti.Add(p)
	}

	var buff bytes.Buffer
	var num int64
	num += ti.Process(&buff, time.Now().Unix(), 10)

	assert.Equal(t, num, int64(1))
	dataForGraphite := buff.String()

	meanRegexp := regexp.MustCompile(`time\.upper_75 1\.`)
	matched := meanRegexp.MatchString(dataForGraphite)
	assert.Equal(t, matched, false)

	meanRegexp = regexp.MustCompile(`time\.lower_75 1\.`)
	matched = meanRegexp.MatchString(dataForGraphite)
	assert.Equal(t, matched, true)
}
Exemple #7
0
func handleMessage(conn *net.UDPConn, remaddr net.Addr, buf *bytes.Buffer) {
	var packet Packet
	var value string
	var sanitizeRegexp = regexp.MustCompile("[^a-zA-Z0-9\\-_\\.:\\|@]")
	var packetRegexp = regexp.MustCompile("([a-zA-Z0-9_]+):(\\-?[0-9\\.]+)\\|(c|ms)(\\|@([0-9\\.]+))?")
	s := sanitizeRegexp.ReplaceAllString(buf.String(), "")
	for _, item := range packetRegexp.FindAllStringSubmatch(s, -1) {
		value = item[2]
		if item[3] == "ms" {
			_, err := strconv.ParseFloat(item[2], 32)
			if err != nil {
				value = "0"
			}
		}

		sampleRate, err := strconv.ParseFloat(item[5], 32)
		if err != nil {
			sampleRate = 1
		}

		packet.Bucket = item[1]
		packet.Value = value
		packet.Modifier = item[3]
		packet.Sampling = float32(sampleRate)

		if *debug {
			log.Println("Packet: bucket = %s, value = %s, modifier = %s, sampling = %f\n", packet.Bucket, packet.Value, packet.Modifier, packet.Sampling)
		}

		In <- packet
	}
}
Exemple #8
0
func (rte *route) buildPatterns(prefix string) {
	// Don't bother generating fancy regexps if we're looking at '/'
	if rte.segment == "" {
		rte.indexPattern = regexp.MustCompile(`^$`)
	} else {
		basePattern := prefix + rte.segment
		rte.indexPattern = regexp.MustCompile("^" + basePattern + "$")
		if rte.controller != nil {
			patternWithId := fmt.Sprintf(`^%s(?:/(?P<%s_id>%s))?$`, basePattern, strings.Replace(NameFromController(rte.controller), "-", "_", -1), rte.controller.IdPattern())
			rte.objectPattern = regexp.MustCompile(patternWithId)
			actions := rte.controller.extraActionNames()
			if len(actions) > 0 {
				actionPatternString := fmt.Sprintf(`^%s/(?:%s)$`, basePattern, strings.Join(actions, "|"))
				rte.actionPattern = regexp.MustCompile(actionPatternString)
			}
		}
	}
	// Calls to Prefixed generate routes without controllers, and the value of prefix is already all set for those
	if rte.controller != nil {
		prefix += fmt.Sprintf(`%s/(?P<%s_id>%s)/`, rte.segment, NameFromController(rte.controller), rte.controller.IdPattern())
	} else {
		prefix += "/"
	}
	for _, r := range rte.subroutes {
		r.buildPatterns(prefix)
	}
}
func TestNewRSRField1(t *testing.T) {
	// Normal case
	expRSRField1 := &RSRField{Id: "sip_redirected_to",
		RSRules: []*ReSearchReplace{&ReSearchReplace{SearchRegexp: regexp.MustCompile(`sip:\+49(\d+)@`), ReplaceTemplate: "0$1"}}}
	if rsrField, err := NewRSRField(`~sip_redirected_to:s/sip:\+49(\d+)@/0$1/`); err != nil {
		t.Error("Unexpected error: ", err.Error())
	} else if !reflect.DeepEqual(expRSRField1, rsrField) {
		t.Errorf("Expecting: %v, received: %v", expRSRField1, rsrField)
	}
	// With filter
	filter, _ := NewRSRFilter("086517174963")
	expRSRField2 := &RSRField{Id: "sip_redirected_to", filters: []*RSRFilter{filter},
		RSRules: []*ReSearchReplace{&ReSearchReplace{SearchRegexp: regexp.MustCompile(`sip:\+49(\d+)@`), ReplaceTemplate: "0$1"}}}
	if rsrField, err := NewRSRField(`~sip_redirected_to:s/sip:\+49(\d+)@/0$1/(086517174963)`); err != nil {
		t.Error("Unexpected error: ", err.Error())
	} else if !reflect.DeepEqual(expRSRField2, rsrField) {
		t.Errorf("Expecting: %v, received: %v", expRSRField2, rsrField)
	}
	// Separator escaped
	if rsrField, err := NewRSRField(`~sip_redirected_to:s\/sip:\+49(\d+)@/0$1/`); err == nil {
		t.Errorf("Parse error, field rule does not contain correct number of separators, received: %v", rsrField)
	}
	// One extra separator but escaped
	expRSRField3 := &RSRField{Id: "sip_redirected_to",
		RSRules: []*ReSearchReplace{&ReSearchReplace{SearchRegexp: regexp.MustCompile(`sip:\+49(\d+)\/@`), ReplaceTemplate: "0$1"}}}
	if rsrField, err := NewRSRField(`~sip_redirected_to:s/sip:\+49(\d+)\/@/0$1/`); err != nil {
		t.Error("Unexpected error: ", err.Error())
	} else if !reflect.DeepEqual(expRSRField3, rsrField) {
		t.Errorf("Expecting: %v, received: %v", expRSRField3, rsrField)
	}
}
Exemple #10
0
func FindTaskId(index string, autoFirst bool) string {
	if index == "" {
		if autoFirst == false {
			log.Fatal("fatal: Task index is required.")
		} else {
			index = "0"
		}
	}

	var id string
	txt, err := ioutil.ReadFile(utils.CacheFile())

	if err != nil { // cache file not exist
		ind, parseErr := strconv.Atoi(index)
		utils.Check(parseErr)
		task := Tasks(url.Values{}, false)[ind]
		id = strconv.Itoa(task.Id)
	} else {
		lines := regexp.MustCompile("\n").Split(string(txt), -1)
		for i, line := range lines {
			if index == strconv.Itoa(i) {
				line = regexp.MustCompile("^[0-9]*:").ReplaceAllString(line, "") // remove index
				id = regexp.MustCompile("^[0-9]*").FindString(line)
			}
		}
	}
	return id
}
Exemple #11
0
func (b *BotClient) Run() {
	// Regexes
	// Add the matcher here
	privmsgRegexp := regexp.MustCompile("^:(.+?)!(.+?)@(.+?)\\sPRIVMSG\\s(.+?)\\s:(.+)$")
	modeRegexp := regexp.MustCompile("^:(.+?)!(.+?)@(.+?)\\sMODE\\s(.+?)\\s(.+)$")

	for {
		str := <-b.ReadChan
		if str[0:6] == "PING :" {
			if b.debug {
				fmt.Printf("\033[34mSERVER PING\033[0m\n")
			}
			b.WriteChan <- "PONG :" + str[7:]
		}

		data := privmsgRegexp.FindAllStringSubmatch(str, 1)
		if data != nil {
			b.processPrivMsg(data)
		}

		data = modeRegexp.FindAllStringSubmatch(str, 1)
		if data != nil {
			b.processModeMsg(data)
		}

		// and add the handler function here
	}
}
Exemple #12
0
func (this *gowatch) Watch() (err error) {
	if this.w, err = fsnotify.NewWatcher(); err != nil {
		return
	}
	for _, path := range this.Paths {
		if err = this.watchDirAndChildren(os.ExpandEnv(path)); err != nil {
			log.Fatal(err)
		}
	}
	this.modtime = make(map[string]time.Time)
	this.sig = make(chan string)
	for _, patten := range this.Exclude {
		this.reExclude = append(this.reExclude, regexp.MustCompile(patten))
	}
	for _, patten := range this.Include {
		this.reInclude = append(this.reInclude, regexp.MustCompile(patten))
	}

	this.sigOS = make(chan os.Signal, 1)
	signal.Notify(this.sigOS, syscall.SIGINT)

	go this.drainExec()
	this.drainEvent()
	return
}
func (e *Exporter) setMetrics(scrapes <-chan []string) {
	var comRegex = regexp.MustCompile(`^com_(.*)$`)
	var connectionErrorRegex = regexp.MustCompile(`^connection_errors_(.*)$`)
	var innodbRowRegex = regexp.MustCompile(`^innodb_rows_(.*)$`)
	var performanceSchemaRegex = regexp.MustCompile(`^performance_schema_(.*)$`)

	for row := range scrapes {
		name := strings.ToLower(row[0])
		value, err := strconv.ParseFloat(row[1], 64)
		if err != nil {
			// convert/serve text values here ?
			continue
		}

		command := comRegex.FindStringSubmatch(name)
		connectionError := connectionErrorRegex.FindStringSubmatch(name)
		innodbRow := innodbRowRegex.FindStringSubmatch(name)
		performanceSchema := performanceSchemaRegex.FindStringSubmatch(name)

		switch {
		case len(command) > 0:
			e.commands.With(prometheus.Labels{"command": command[1]}).Set(value)
		case len(connectionError) > 0:
			e.connectionErrors.With(prometheus.Labels{"error": connectionError[1]}).Set(value)
		case len(innodbRow) > 0:
			e.innodbRows.With(prometheus.Labels{"operation": innodbRow[1]}).Set(value)
		case len(performanceSchema) > 0:
			e.performanceSchema.With(prometheus.Labels{"instrumentation": performanceSchema[1]}).Set(value)
		default:
			e.setGenericMetric(name, value)
		}
	}
}
Exemple #14
0
func validateDbParamGroupName(v interface{}, k string) (ws []string, errors []error) {
	value := v.(string)
	if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) {
		errors = append(errors, fmt.Errorf(
			"only lowercase alphanumeric characters and hyphens allowed in %q", k))
	}
	if !regexp.MustCompile(`^[a-z]`).MatchString(value) {
		errors = append(errors, fmt.Errorf(
			"first character of %q must be a letter", k))
	}
	if regexp.MustCompile(`--`).MatchString(value) {
		errors = append(errors, fmt.Errorf(
			"%q cannot contain two consecutive hyphens", k))
	}
	if regexp.MustCompile(`-$`).MatchString(value) {
		errors = append(errors, fmt.Errorf(
			"%q cannot end with a hyphen", k))
	}
	if len(value) > 255 {
		errors = append(errors, fmt.Errorf(
			"%q cannot be greater than 255 characters", k))
	}
	return

}
Exemple #15
0
func (plug *Autoban) Setup(write chan IRCMessage, conf PluginConf) {
	plug.user = conf.UserName
	plug.write = write
	plug.event = make(chan IRCMessage, 1000)

	var buffer bytes.Buffer
	buffer.WriteString(`(?i:`)
	// Because range copies the elements, which is totally idiotic
	matches := conf.Autoban.Matches
	for i := 0; i < len(matches); i++ {
		buffer.WriteString(matches[i].Regex)
		if i != len(matches)-1 {
			buffer.WriteString(`|`)
		}
		matches[i].Matcher = regexp.MustCompile(matches[i].Regex)
	}
	buffer.WriteString(`)`)

	plug.match = regexp.MustCompile(buffer.String())

	plug.autoBans = conf.Autoban.Matches

	go plug.Action()
	return
}
Exemple #16
0
func (this *OCRResult) removeNonWords(blob string) string {
	speller, err := aspell.NewSpeller(map[string]string{
		"lang": "en_US",
	})
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
		return ""
	}
	defer speller.Delete()

	singleCharWords := regexp.MustCompile("(a|i)")
	numberRegex := regexp.MustCompile("\\d{3,}")
	wordRegexp := regexp.MustCompile("\\b(\\w+)\\b")
	words := wordRegexp.FindAllString(blob, -1)

	str := ""

	for _, word := range words {
		if numberRegex.MatchString(word) {
			str += " " + word
		} else if len(word) == 1 {
			if singleCharWords.MatchString(word) {
				str += " " + word
			}
		} else if speller.Check(word) {
			str += " " + word
		}
	}

	return strings.TrimSpace(str)
}
Exemple #17
0
func SuitesInDir(dir string, recurse bool) []TestSuite {
	suites := []TestSuite{}

	if vendorExperimentCheck(dir) {
		return suites
	}

	files, _ := ioutil.ReadDir(dir)
	re := regexp.MustCompile(`_test\.go$`)
	for _, file := range files {
		if !file.IsDir() && re.Match([]byte(file.Name())) {
			suites = append(suites, New(dir, files))
			break
		}
	}

	if recurse {
		re = regexp.MustCompile(`^[._]`)
		for _, file := range files {
			if file.IsDir() && !re.Match([]byte(file.Name())) {
				suites = append(suites, SuitesInDir(dir+"/"+file.Name(), recurse)...)
			}
		}
	}

	return suites
}
Exemple #18
0
func filterStriptags(value interface{}, args []interface{}, ctx *FilterChainContext) (interface{}, error) {
	str, is_str := value.(string)
	if !is_str {
		return nil, errors.New(fmt.Sprintf("%v is not of type string", value))
	}

	if len(args) > 1 {
		return nil, errors.New("Please provide a comma-seperated string with tags (or no string to remove all tags).")
	}

	if len(args) == 1 {
		taglist, is_string := args[0].(string)
		if !is_string {
			return nil, errors.New(fmt.Sprintf("Taglist must be a string, not %T ('%v')", args[0], args[0]))
		}

		tags := strings.Split(taglist, ",")

		for _, tag := range tags {
			re := regexp.MustCompile(fmt.Sprintf("</?%s/?>", tag))
			str = re.ReplaceAllString(str, "")
		}
	} else {
		re := regexp.MustCompile("<[^>]*?>")
		str = re.ReplaceAllString(str, "")
	}

	return strings.TrimSpace(str), nil
}
Exemple #19
0
// parseBenchmarkOutput fetches metrics and artifacts from benchmark output.
func parseBenchmarkOutput(out io.Reader) (metrics []PerfMetric, artifacts []PerfArtifact, err error) {
	s := bufio.NewScanner(out)
	metricRe := regexp.MustCompile("^GOPERF-METRIC:([a-z,0-9,-]+)=([0-9]+)$")
	fileRe := regexp.MustCompile("^GOPERF-FILE:([a-z,0-9,-]+)=(.+)$")
	for s.Scan() {
		ln := s.Text()
		if ss := metricRe.FindStringSubmatch(ln); ss != nil {
			var v uint64
			v, err = strconv.ParseUint(ss[2], 10, 64)
			if err != nil {
				err = fmt.Errorf("Failed to parse metric '%v=%v': %v", ss[1], ss[2], err)
				return
			}
			metrics = append(metrics, PerfMetric{Type: ss[1], Val: v})
		} else if ss := fileRe.FindStringSubmatch(ln); ss != nil {
			var buf []byte
			buf, err = ioutil.ReadFile(ss[2])
			if err != nil {
				err = fmt.Errorf("Failed to read file '%v': %v", ss[2], err)
				return
			}
			artifacts = append(artifacts, PerfArtifact{ss[1], string(buf)})
		}
	}
	return
}
Exemple #20
0
func TestCornerCases(t *testing.T) {
	testRule1 := Rule{regexp.MustCompile(`(?P<first>\w+)(?:/(?P<second>\w+))?`), V{Corpus: "${first}", Path: "${second}"}.pb()}
	testRule2 := Rule{regexp.MustCompile(`x/(?P<sig>\w+)/y/(?P<tail>.+)$`), V{Path: "${tail}", Sig: "|${sig}|"}.pb()}
	tests := []struct {
		rule  Rule
		input string
		want  *spb.VName
	}{
		// Optional portions of the pattern should be handled correctly.
		{testRule1, "alpha/bravo", V{Corpus: "alpha", Path: "bravo"}.pb()},
		{testRule1, "alpha", V{Corpus: "alpha"}.pb()},

		// Substitution of signature fields should work.
		{testRule2, "x/kanga/y/roo.txt", V{Path: "roo.txt", Sig: "|kanga|"}.pb()},
	}
	for _, test := range tests {
		got, ok := test.rule.Apply(test.input)
		if !ok {
			t.Errorf("Apply %v failed", test.rule)
		} else if !proto.Equal(got, test.want) {
			t.Errorf("Apply %v: got {%+v}, want {%+v}", test.rule, got, test.want)
		} else {
			t.Logf("Apply %v properly returned {%+v}", test.rule, got)
		}
	}
}
Exemple #21
0
// Types are off
func Test_typeArr(t *testing.T) {
	var re *regexp.Regexp
	var b bool
	arr := []string{
		"float64",
		"int",
		"bool",
	}

	ts := typeArr(arr)

	re = regexp.MustCompile(`[1-9]\d*`)
	b = re.MatchString(ts[0].(string))
	if !b {
		t.Errorf("Expected line protocol float64 got %v", ts[0])
	}

	re = regexp.MustCompile(`[1-9]\d*i`)
	b = re.MatchString(ts[1].(string))
	if !b {
		t.Errorf("Expected line protocol int got %v", ts[1])
	}

	re = regexp.MustCompile(`true|false`)
	b = re.MatchString(ts[2].(string))
	if !b {
		t.Errorf("Expected line protocol bool got %v", ts[2])
	}

}
func (calc *Calculator) singleCalculation(calculation string, scope map[string]string) *big.Int {
	regex := regexp.MustCompile(`[\*\+\-\%\/\$\&]`)

	foundOperators := regex.FindAllString(calculation, -1)
	if len(foundOperators) > 1 {
		log.Fatal("Too many operators" + calculation)
		return nil
	}
	operator := foundOperators[0]

	parts := regex.Split(calculation, -1)
	if operator == "+" || operator == "-" || operator == "*" || operator == "%" || operator == "/" || operator == "$" {
		return calc.twoValueCalculation(
			calc.resolveToInt(parts[0], scope),
			calc.resolveToInt(parts[1], scope),
			operator,
		)
	} else if operator == "&" {
		regex = regexp.MustCompile(",")
		g := regex.Split(parts[1], -1)
		return calc.threeValueCalculation(
			calc.resolveToInt(parts[0], scope),
			calc.resolveToInt(g[0], scope),
			calc.resolveToInt(g[1], scope),
			operator,
		)
	}

	return nil
}
// getCloudFormationFailures returns ResourceStatusReason(s)
// of events that should be failures based on regexp match of status
func getCloudFormationFailures(stackName *string, afterTime time.Time,
	conn *cloudformation.CloudFormation) ([]string, error) {
	var failures []string
	// Only catching failures from last 100 events
	// Some extra iteration logic via NextToken could be added
	// but in reality it's nearly impossible to generate >100
	// events by a single stack update
	events, err := conn.DescribeStackEvents(&cloudformation.DescribeStackEventsInput{
		StackName: stackName,
	})

	if err != nil {
		return nil, err
	}

	failRe := regexp.MustCompile("_FAILED$")
	rollbackRe := regexp.MustCompile("^ROLLBACK_")

	for _, e := range events.StackEvents {
		if (failRe.MatchString(*e.ResourceStatus) || rollbackRe.MatchString(*e.ResourceStatus)) &&
			e.Timestamp.After(afterTime) && e.ResourceStatusReason != nil {
			failures = append(failures, *e.ResourceStatusReason)
		}
	}

	return failures, nil
}
Exemple #24
0
func createExceptionNoun() {
	name := "verb"
	buf := bytes.NewBuffer(nil)
	f, _ := os.Open("/home/serega/Copy/database/dict/" + name + ".exc") // Error handling elided for brevity.
	io.Copy(buf, f)                                                     // Error handling elided for brevity.
	f.Close()
	sentense := (buf.String())
	buf.Reset()
	rubbx = frub.NewRubAr()
	sentense = strings.ToLower(sentense)
	lin := regexp.MustCompile(`\n`).Split(sentense, -1)
	//word := make(ByLength, 2000)
	//wordArray := make([]string, 2000)
	findIsh := make(map[string]string)
	//findForm := make(map[string]map[string]string)
	//fmt.Println(sentense)

	for _, s := range lin {
		words := regexp.MustCompile(` `).Split(s, -1)
		if len(words) == 2 {
			findIsh[words[0]] = words[1]
		}
	}
	fmt.Println(len(findIsh))
	frub.CreateByZn(findIsh, "file/englishLemm/find"+name+".gob")
	wodfFile, _ := os.Create("file/englishLemm/find" + name)
	frub.Encode(findIsh, wodfFile)
	//frub.CreateByZn(findForm, "file/englishLemm/form" + name + ".gob")
	//wodfFile, _ = os.Create("file/englishLemm/form" + name)
	//frub.Encode(findForm, wodfFile)
}
Exemple #25
0
func (context *Context) loadActions(action string) template.HTML {
	var actions = map[string]string{}
	var actionKeys = []string{}
	var viewPaths = context.getViewPaths()

	for j := len(viewPaths); j > 0; j-- {
		view := viewPaths[j-1]
		globalfiles, _ := filepath.Glob(path.Join(view, "actions/*.tmpl"))
		files, _ := filepath.Glob(path.Join(view, "actions", action, "*.tmpl"))

		for _, file := range append(globalfiles, files...) {
			if _, ok := actions[path.Base(file)]; !ok {
				actionKeys = append(actionKeys, path.Base(file))
			}
			base := regexp.MustCompile("^\\d+\\.").ReplaceAllString(path.Base(file), "")
			actions[base] = file
		}
	}

	sort.Strings(actionKeys)

	var result = bytes.NewBufferString("")
	for _, key := range actionKeys {
		base := regexp.MustCompile("^\\d+\\.").ReplaceAllString(key, "")
		file := actions[base]
		if tmpl, err := template.New(path.Base(file)).Funcs(context.FuncMap()).ParseFiles(file); err == nil {
			if err := tmpl.Execute(result, context); err != nil {
				panic(err)
			}
		}
	}
	return template.HTML(strings.TrimSpace(result.String()))
}
Exemple #26
0
func compareTraces(expected, actual events) bool {
	if len(expected) != len(actual) {
		return false
	}
	for i, ev := range expected {
		if ev == actual[i] {
			continue
		}
		// Try to strip file:line from a span event, e.g. from:
		//   span:path/file:line msg
		// to:
		//   span:msg
		groups := regexp.MustCompile(`^(.*):.*:[0-9]* (.*)$`).FindStringSubmatch(actual[i])
		if len(groups) == 3 && fmt.Sprintf("%s:%s", groups[1], groups[2]) == ev {
			continue
		}
		// Try to strip file:line from a non-span event, e.g. from:
		//   path/file:line msg
		// to:
		//   msg
		groups = regexp.MustCompile(`^.*:[0-9]* (.*)$`).FindStringSubmatch(actual[i])
		if len(groups) == 2 && groups[1] == ev {
			continue
		}
		return false
	}
	return true
}
func TestReadTriggerParams(t *testing.T) {
	t.Parallel()

	h := newHarness(t)
	defer h.Stop()

	h.env.In = ioutil.NopCloser(strings.NewReader("\n"))
	_, err := readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Class name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\n"))
	_, err = readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Trigger name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave"))
	hook, err := readTriggerName(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{ClassName: "foo", TriggerName: "beforeSave"})

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/foo/beforeSave\n"))
	hook, err = readTriggerParams(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{
		ClassName:   "foo",
		TriggerName: "beforeSave",
		URL:         "https://api.example.com/foo/beforeSave",
	})
}
Exemple #28
0
func TestLoggerMiddleware(t *testing.T) {
	var buf bytes.Buffer
	Logger = log.New(&buf, "", 0)

	router := New(Context{})
	router.Middleware(LoggerMiddleware)
	router.Get("/action", (*Context).A)

	// Hit an action:
	rw, req := newTestRequest("GET", "/action")
	router.ServeHTTP(rw, req)
	assertResponse(t, rw, "context-A", 200)

	// Make sure our buf has something good:
	logRegexp := regexp.MustCompile("\\[\\d+ .{2}\\] 200 '/action'")
	if !logRegexp.MatchString(buf.String()) {
		t.Error("Got invalid log entry: ", buf.String())
	}

	// Do a 404:
	buf.Reset()
	rw, req = newTestRequest("GET", "/wat")
	router.ServeHTTP(rw, req)
	assertResponse(t, rw, "Not Found", 404)

	// Make sure our buf has something good:
	logRegexpNotFound := regexp.MustCompile("\\[\\d+ .{2}\\] 404 '/wat'")
	if !logRegexpNotFound.MatchString(buf.String()) {
		t.Error("Got invalid log entry: ", buf.String())
	}
}
// Regression for https://github.com/hashicorp/terraform/issues/2427
func TestAccAWSEcsServiceWithRenamedCluster(t *testing.T) {
	originalRegexp := regexp.MustCompile(
		"^arn:aws:ecs:[^:]+:[0-9]+:cluster/terraformecstest3$")
	modifiedRegexp := regexp.MustCompile(
		"^arn:aws:ecs:[^:]+:[0-9]+:cluster/terraformecstest3modified$")

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEcsServiceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSEcsServiceWithRenamedCluster,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSEcsServiceExists("aws_ecs_service.ghost"),
					resource.TestMatchResourceAttr(
						"aws_ecs_service.ghost", "cluster", originalRegexp),
				),
			},

			resource.TestStep{
				Config: testAccAWSEcsServiceWithRenamedClusterModified,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSEcsServiceExists("aws_ecs_service.ghost"),
					resource.TestMatchResourceAttr(
						"aws_ecs_service.ghost", "cluster", modifiedRegexp),
				),
			},
		},
	})
}
Exemple #30
-1
func validateCmdArgs(cmd *commander.Command, args []string) error {
	mustVal := 0
	optionVal := 0
	must := regexp.MustCompile(`<\w+>`)
	option := regexp.MustCompile(`\[\w+\]`)

	for _, action := range strings.Split(cmd.UsageLine, " ") {
		if must.MatchString(action) {
			mustVal++
		}
		if option.MatchString(action) {
			optionVal++
		}
		// skip arguments validation
		if action == "..." {
			if mustVal <= len(args) {
				return nil
			}
		}
	}
	if mustVal <= len(args) && len(args) <= mustVal+optionVal {
		return nil
	}
	return errors.New("invalid argument\nUsage: " + cmd.UsageLine)
}