// TestWorkflow runs certstrap in the normal workflow // and traverses all commands func TestWorkflow(t *testing.T) { os.RemoveAll(depotDir) defer os.RemoveAll(depotDir) stdout, stderr, err := run(binPath, "init", "--passphrase", passphrase, "--common-name", "CA") if stderr != "" || err != nil { t.Fatalf("Received unexpected error: %v, %v", stderr, err) } if strings.Count(stdout, "Created") != 2 { t.Fatalf("Received insufficient create: %v", stdout) } stdout, stderr, err = run(binPath, "request-cert", "--passphrase", passphrase, "--common-name", hostname) if stderr != "" || err != nil { t.Fatalf("Received unexpected error: %v, %v", stderr, err) } if strings.Count(stdout, "Created") != 2 { t.Fatalf("Received insufficient create: %v", stdout) } stdout, stderr, err = run(binPath, "sign", "--passphrase", passphrase, "--CA", "CA", hostname) if stderr != "" || err != nil { t.Fatalf("Received unexpected error: %v, %v", stderr, err) } if strings.Count(stdout, "Created") != 1 { t.Fatalf("Received insufficient create: %v", stdout) } }
func (p *parser) linesof(offsetFrom int, offsetTo int) SourceRange { strFrom := string(p.source[:offsetFrom]) posFrom := strings.Count(strFrom, "\n") strTo := string(p.source[:offsetTo]) posTo := strings.Count(strTo, "\n") return SourceRange{posFrom, posTo} }
func CreateTable(tbl PicklesTableArgument) string { Html := "" if len(tbl.HeaderRow) > 0 { Html += "<table>" for n, y := range tbl.DataRows { if n == 1 && y[0] == strings.Repeat("-", strings.Count(y[0], "")-1) { continue } if n == len(tbl.DataRows)-1 && y[0] == strings.Repeat("-", strings.Count(y[0], "")-1) { continue } //fmt.Printf("ligne %d grp[%s] chaine lue [%s] taille:[%d] chaine de tiret [%s]\n",n,y,y[0],strings.Count(y[0],""),strings.Repeat("-", strings.Count(y[0],""))) Html += "<tr>" for _, z := range y { if n == 0 { Html += fmt.Sprintf("<th>%s</th>", z) } else { Html += fmt.Sprintf("<td>%s</td>", z) } } Html += "</tr>" //fmt.Printf("TableArgument.DataRows[%d]: %v\n", n,y) } Html += "</table>" // debug log.Fatalf("Stop %s",Html) } return Html }
func findFiles(path string, depth int, skips []*regexp.Regexp) ([]string, error) { baseNumSeps := strings.Count(path, string(os.PathSeparator)) var files []string err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if err != nil { log.Debugf("filewalk: %s", err) return nil } if info.IsDir() { pathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps if pathDepth > depth { return filepath.SkipDir } } name := info.Name() isSkip := false for _, skip := range skips { if skip.MatchString(name) { isSkip = true break } } // log.Println(isSkip, name) if !isSkip { files = append(files, path) } if isSkip && info.IsDir() { return filepath.SkipDir } return nil }) return files, err }
// Add dir and children (recursively) to watcher func (this *gowatch) watchDirAndChildren(path string) error { if err := this.w.Watch(path); err != nil { return err } baseNumSeps := strings.Count(path, string(os.PathSeparator)) return filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if info.IsDir() { base := info.Name() if base != "." && strings.HasPrefix(base, ".") { // ignore hidden dir return filepath.SkipDir } pathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps if pathDepth > this.Depth { return filepath.SkipDir } if *verbose { fmt.Println(">>> watch dir: ", path) } if err := this.w.Watch(path); err != nil { return err } } return nil }) }
func main() { args := ArgumentList(os.Args) if githubRepo := args.GetArgument("--github", ""); githubRepo != "" { if strings.Count(githubRepo, "/") != 1 { fmt.Fprintf(os.Stderr, "Invalid GitHub repo: %s\n", githubRepo) os.Exit(2) } pieces := strings.Split(githubRepo, "/") githubImport(pieces[0], pieces[1]) } else if args.GetArgument("--be", "") != "" { beImport() } else { if strings.Count(githubRepo, "/") != 1 { fmt.Fprintf(os.Stderr, "Usage: %s --github user/repo\n", os.Args[0]) fmt.Fprintf(os.Stderr, " %s --be\n", os.Args[0]) fmt.Fprintf(os.Stderr, ` Use this tool to import an external bug database into the local issues/ directory. Either "--github user/repo" is required to import GitHub issues, from GitHub, or "--be" is required to import a local BugsEverywhere database. `) os.Exit(2) } } }
func TestLogBacktraceAt(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) // The peculiar style of this code simplifies line counting and maintenance of the // tracing block below. var infoLine string setTraceLocation := func(file string, line int, ok bool, delta int) { if !ok { t.Fatal("could not get file:line") } _, file = filepath.Split(file) infoLine = fmt.Sprintf("%s:%d", file, line+delta) err := logging.traceLocation.Set(infoLine) if err != nil { t.Fatal("error setting log_backtrace_at: ", err) } } { // Start of tracing block. These lines know about each other's relative position. _, file, line, ok := runtime.Caller(0) setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. Info("we want a stack trace here") logging.wait() } numAppearances := strings.Count(contents(infoLog), infoLine) numLines := strings.Count(contents(infoLog), "\n") if numAppearances < 1 || numLines < 3 { // Need both the expected lines and enough more lines. Since we assume we have // no knowledge of the stacktrace format or the actual code stack being called, // we can't check for a higher number of lines. t.Fatal("got no trace back; log is ", contents(infoLog)) } }
func Walk(root string, level int, exclude ...string) (list []string) { visit := func(path string, f os.FileInfo, err error) error { if strings.HasPrefix(f.Name(), ".") && f.IsDir() { return filepath.SkipDir } for _, ex := range exclude { if strings.HasSuffix(path, ex) && f.IsDir() { return filepath.SkipDir } } if f.IsDir() { list = append(list, path) } return nil } filepath.Walk(root, visit) sort.Sort(Path(list)) end := len(list) for i, v := range list { if strings.Count(v, "/")-strings.Count(root, "/") > level { end = i break } } list = list[0:end] return }
func TestBatchSizeOnDump(t *testing.T) { c, clean, err := aetest.NewContext() if err != nil { t.Fatal(err) } defer clean() for _, i := range []int{10, 20, 50, 99, 100, 101} { t.Logf("Testing %d entities ...", i) if err := createSampleEntities(c, i); err != nil { t.Fatal(err) } w := new(bytes.Buffer) err := Dump(c, w, &Options{Kind: "User", PrettyPrint: false}) if err != nil { t.Fatal(err) } count := strings.Count(w.String(), "__key__") if count != i { t.Errorf("Unexpected number of __key__'s %d: expected %d", count, i) } // t.Logf(w.String()) // Check if we have all keys for id := 1; id <= i; id++ { sep := fmt.Sprintf(`["User",%d]`, id) occ := strings.Count(w.String(), sep) if occ != 1 { t.Errorf("Unexpected ocorrences of entity id %d: %d, expected 1", id, occ) } } } }
func parseSerialString(input string) (*big.Int, error) { ret := &big.Int{} switch { case strings.Count(input, ":") > 0: serialBytes := certutil.ParseHexFormatted(input, ":") if serialBytes == nil { return nil, fmt.Errorf("error parsing serial %s", input) } ret.SetBytes(serialBytes) case strings.Count(input, "-") > 0: serialBytes := certutil.ParseHexFormatted(input, "-") if serialBytes == nil { return nil, fmt.Errorf("error parsing serial %s", input) } ret.SetBytes(serialBytes) default: var success bool ret, success = ret.SetString(input, 0) if !success { return nil, fmt.Errorf("error parsing serial %s", input) } } return ret, nil }
func (this *toml) parseNext() error { str, err := readln(this.r) if err != nil { return err } str = strings.TrimSpace(str) if str == "" { //blank line return nil } if strings.HasPrefix(str, "#") { // comment line return nil } if strings.HasPrefix(str, "[") { //change the key str = strings.TrimLeft(str, "[") str = strings.TrimRight(str, "]") // allways have a trailing dot this.key = fmt.Sprintf("%s.", str) return nil } //we are parsing a key value! tmp := strings.SplitN(str, "=", 2) if len(tmp) != 2 { return fmt.Errorf("Error on line: %s, no equals sign!", str) } key := strings.TrimSpace(tmp[0]) value := strings.TrimSpace(tmp[1]) if !strings.HasPrefix(value, "[") { //its not an array v, ok := toVal(value) if !ok { return fmt.Errorf("Error on line: %s, unable to parse value %s", str, value) } this.output.PutWithDot(fmt.Sprintf("%s%s", this.key, key), v) return nil } //ok parse the damn array //arrays can contain multiple lines // so we count the opening and closing brackets. for strings.Count(str, "[") != strings.Count(str, "]") { ln, err := readln(this.r) if err != nil { return err } str = fmt.Sprintf("%s %s", str, ln) } return nil }
// Generate a poem with the given number of strophes and lines per strophe. func generatePoem(strophes int, linesPerStrophe int) { // Find a catchy title title := strings.Trim(strings.Title(niall.Talk()), ".,;:!?_") if strings.Count(title, " ") > 4 { words := strings.Split(title, " ") title = strings.Join(words[:4], " ") } // Generate an appropriate amount of dashes dashes := "" for i := 0; i < len(title); i++ { dashes += "-" } // Output the header fmt.Printf("\n%s\n%s\n\n", title, dashes) // Generate and output all the srophes var line string for reps := 0; reps < strophes; reps++ { for i := 0; i < linesPerStrophe; i++ { // Try to get more than just a few words, up to 5 times for i2 := 0; i2 < 5; i2++ { line = niall.Talk() if strings.Count(line, " ") >= 3 { break } } fmt.Println(line) } fmt.Println() } }
func removeComments(line string) string { // ditch the comments (but keep quoted hashes) if strings.Contains(line, "#") { segmentsBetweenHashes := strings.Split(line, "#") quotesAreOpen := false var segmentsToKeep []string for _, segment := range segmentsBetweenHashes { if strings.Count(segment, "\"") == 1 || strings.Count(segment, "'") == 1 { if quotesAreOpen { quotesAreOpen = false segmentsToKeep = append(segmentsToKeep, segment) } else { quotesAreOpen = true } } if len(segmentsToKeep) == 0 || quotesAreOpen { segmentsToKeep = append(segmentsToKeep, segment) } } line = strings.Join(segmentsToKeep, "#") } return line }
func ExampleCount() { fmt.Println(strings.Count("cheese", "e")) fmt.Println(strings.Count("five", "")) // before & after each rune // Output: // 3 // 5 }
func (target *Target) CheckPreconditions() error { if err := ValidPath(target.File, target.FileFormat, ""); err != nil { return err } if strings.Count(target.File, "*") > 0 { return fmt.Errorf( "File pattern for 'pull' cannot include any 'stars' *. Please specify direct and valid paths with file name!", "http://docs.phraseapp.com/developers/cli/configuration/#targets", ) } duplicatedPlaceholders := []string{} for _, name := range []string{"<locale_name>", "<locale_code>", "<tag>"} { if strings.Count(target.File, name) > 1 { duplicatedPlaceholders = append(duplicatedPlaceholders, name) } } if len(duplicatedPlaceholders) > 0 { dups := strings.Join(duplicatedPlaceholders, ", ") return fmt.Errorf(fmt.Sprintf("%s can only occur once in a file pattern!", dups)) } return nil }
func h_gen_valdict_switch_str(indent string, values [][2]string) string { o := make([]string, 0, len(values)) o = append(o, "[") for _, v := range values { tags := w_gen_taglist(v[0]) key_fmt := "(%s)" if strings.Count(v[0], "&") <= 0 { key_fmt = "%s" } val_fmt := "%s" if strings.Count(v[1], ",") > 0 { val_fmt = "[%s]" } if len(v[1]) == 0 { val_fmt = "%q" } o = append(o, fmt.Sprintf( "%s {%s: %s},", indent, fmt.Sprintf(key_fmt, w_py_strlist(tags)), fmt.Sprintf(val_fmt, v[1]), ), ) } o = append(o, indent+"]") return strings.Join(o, "\n") }
func getcityname(city string) string { if strings.Contains(city, "县") { citys = strings.SplitAfterN(city, "市", 2)[1] } if strings.Contains(city, "市") { if strings.Count(city, "市") >= 2 { citys = strings.SplitAfterN(city, "市", 2)[1] } else { citys = strings.SplitAfterN(city, "省", 2)[1] } } if strings.Contains(city, "区") { if strings.Count(city, "区") >= 2 { citys = strings.SplitAfterN(city, "区", 2)[1] } else { if strings.Contains(city, "特别行政区") { citys, _ = SubstringIndex(city, "特别行政区") } if strings.Contains(city, "市") { citys = strings.SplitAfterN(city, "市", 2)[1] } } } return "" }
func (cnt ByPath) Less(i, j int) bool { cti, ctj := strings.Count(cnt.controllers[i].urlPath, "/"), strings.Count(cnt.controllers[j].urlPath, "/") if cti == ctj { return len(cnt.controllers[i].vars) > len(cnt.controllers[j].vars) } return cti > ctj }
func (s *DockerSuite) TestRmiImgIDForce(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'") containerID := strings.TrimSpace(out) dockerCmd(c, "commit", containerID, "busybox-test") imagesBefore, _ := dockerCmd(c, "images", "-a") dockerCmd(c, "tag", "busybox-test", "utest:tag1") dockerCmd(c, "tag", "busybox-test", "utest:tag2") dockerCmd(c, "tag", "busybox-test", "utest/docker:tag3") dockerCmd(c, "tag", "busybox-test", "utest:5000/docker:tag4") { imagesAfter, _ := dockerCmd(c, "images", "-a") c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n")+4, check.Commentf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) } imgID, err := inspectField("busybox-test", "Id") c.Assert(err, checker.IsNil) // first checkout without force it fails out, _, err = dockerCmdWithError("rmi", imgID) // rmi tagged in multiple repos should have failed without force c.Assert(err, checker.NotNil) // rmi tagged in multiple repos should have failed without force c.Assert(out, checker.Contains, "(must be forced) - image is referenced in one or more repositories", check.Commentf("out: %s; err: %v;", out, err)) dockerCmd(c, "rmi", "-f", imgID) { imagesAfter, _ := dockerCmd(c, "images", "-a") // rmi failed, image still exists c.Assert(imagesAfter, checker.Not(checker.Contains), imgID[:12]) } }
func importLine(line string) (bool, error) { var size int if strings.Count(line, "|") == 4 { data := strings.Split(line, "|") if len(data[0]) != 40 { return false, errors.New("Probably not a torrent archive") } if data[2] == "" { data[2] = "Other" } return torrentDB.Insert(data[0], data[1], data[2], 0, data[3]) } else if strings.Count(line, "|") == 6 { data := strings.Split(line, "|") if len(data[2]) != 40 { return false, errors.New("Probably not a torrent archive") } if data[4] == "" { data[4] = "Other" } size, _ = strconv.Atoi(data[1]) return torrentDB.Insert(data[2], data[0], data[4], size, "") } else { return false, errors.New("Something's up with this torrent.") } }
// TestFatalStacktraceStderr verifies that a full stacktrace is output. // This test would be more interesting if -logtostderr could actually // be tested. Well, it wasn't, and it looked like stack trace dumping // was broken when that option was used. This is fixed now, and perhaps // in the future clog and this test can be adapted to actually test that; // right now clog writes straight to os.StdErr. func TestFatalStacktraceStderr(t *testing.T) { setFlags() logging.stderrThreshold = NumSeverity logging.toStderr = false SetExitFunc(func(int) {}) defer setFlags() defer logging.swap(logging.newBuffers()) for _, level := range []int{tracebackNone, tracebackSingle, tracebackAll} { traceback = level Fatalf(context.Background(), "cinap") cont := contents(FatalLog) if !strings.Contains(cont, " cinap") { t.Fatalf("panic output does not contain cinap:\n%s", cont) } if !strings.Contains(cont, "clog_test") { t.Fatalf("stack trace does not contain file name: %s", cont) } switch traceback { case tracebackNone: if strings.Count(cont, "goroutine ") > 0 { t.Fatalf("unexpected stack trace:\n%s", cont) } case tracebackSingle: if strings.Count(cont, "goroutine ") != 1 { t.Fatalf("stack trace contains too many goroutines: %s", cont) } case tracebackAll: if strings.Count(cont, "goroutine ") < 2 { t.Fatalf("stack trace contains less than two goroutines: %s", cont) } } } }
func main() { root := filepath.Join(os.Getenv("HOME"), "Projects") if len(os.Args) == 1 { fmt.Println(root) return } arg := os.Args[1] for _, c := range strings.Split(arg, "/") { components = append(components, c) } matches, err := quirkyGlob(root, 0) if err != nil || len(matches) == 0 { fmt.Println(root) return } shortest := matches[0] jumps := strings.Count(shortest, "/") for _, path := range matches { if j := strings.Count(path, "/"); j < jumps { shortest = path jumps = j } } fmt.Println(shortest) }
func cleanGitignore(input string) (output string, err error) { if len(input) == 0 { return input, nil } if strings.Contains(input, delimiterStart) { if strings.Count(input, delimiterStart) > 1 { return input, errors.New("multiple instances of start delimiter") } if strings.Contains(input, delimiterEnd) { if strings.Count(input, delimiterEnd) > 1 { return input, errors.New("multiple instances of closing delimiter") } startPos := strings.Index(input, delimiterStart) endPos := strings.Index(input, delimiterEnd) + len(delimiterEnd) if startPos-2 >= 0 && input[startPos-2] == '\n' { startPos-- } if endPos+1 < len(input) && input[endPos+1] == '\n' { endPos++ } output = input[:startPos] + input[endPos:] } else { return input, errors.New("found no closing delimiter") } } else { output = input } return output, nil }
// insertInWithin places before/after advice around a statement func (wb *WithinBlock) insertInWithin(a ast.Stmt, w *Weave) string { rout := "" mName := grabMethodName(a) // begin line begin := wb.fset.Position(a.Pos()).Line - 1 after := wb.fset.Position(a.End()).Line + 1 // until this is refactored - any lines we add in our // advice need to be accounted for w/begin before_advice := formatAdvice(wb.aspect.advize.before, mName) after_advice := formatAdvice(wb.aspect.advize.after, mName) if before_advice != "" { rout = w.writeAtLine(wb.fname, begin+wb.linecnt, before_advice) wb.linecnt += strings.Count(before_advice, "\n") + 1 } if after_advice != "" { rout = w.writeAtLine(wb.fname, after+wb.linecnt-1, after_advice) wb.linecnt += strings.Count(after_advice, "\n") + 1 } for t := 0; t < len(wb.aspect.importz); t++ { wb.importsNeeded = append(wb.importsNeeded, wb.aspect.importz[t]) } return rout }
func (s *DockerSuite) TestEventsFilters(c *check.C) { testRequires(c, DaemonIsLinux) parseEvents := func(out, match string) { events := strings.Split(out, "\n") events = events[:len(events)-1] for _, event := range events { eventFields := strings.Fields(event) eventName := eventFields[len(eventFields)-1] c.Assert(eventName, checker.Matches, match) } } since := daemonTime(c).Unix() dockerCmd(c, "run", "--rm", "busybox", "true") dockerCmd(c, "run", "--rm", "busybox", "true") out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die") parseEvents(out, "die") out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die", "--filter", "event=start") parseEvents(out, "((die)|(start))") // make sure we at least got 2 start events count := strings.Count(out, "start") c.Assert(strings.Count(out, "start"), checker.GreaterOrEqualThan, 2, check.Commentf("should have had 2 start events but had %d, out: %s", count, out)) }
func parseLine(line string) (key string, value string, err error) { if len(line) == 0 { err = errors.New("zero length string") return } splitString := strings.SplitN(line, "=", 2) if len(splitString) != 2 { err = errors.New("Can't separate key from value") return } key = splitString[0] key = strings.Trim(key, " ") value = splitString[1] value = strings.Trim(value, " ") if strings.Count(value, "\"") == 2 || strings.Count(value, "'") == 2 { value = strings.Trim(value, "\"'") value = strings.Replace(value, "\\\"", "\"", -1) value = strings.Replace(value, "\\n", "\n", -1) } return }
// Use firstTime=true if this is the first time calling printMongoOutput() after startMongo() func (sh *QShell) printMongoOutput(firstTime bool) error { maxBytesReadAtOnce := 10000 buf := make([]byte, maxBytesReadAtOnce) var recBytes []byte for { n, err := sh.mongoStateHolder.getPty().Read(buf) if err != nil && err != io.EOF { return err } if n == maxBytesReadAtOnce { if err := sh.print("\nWARNING: Probably missing some of mongo's output"); err != nil { return err } } recBytes = append(recBytes, buf[:n]...) rec := string(recBytes) // Very fast in Golang // Terrible hacks to determine when mongo is finished printing output if strings.Count(rec, "\r\n> ") == 2 || firstTime && strings.Count(rec, "\r\n> ") == 1 { // Remove the "\r\n> " that mongo outputs msg := strings.TrimSuffix(strings.TrimSpace(strings.Replace(rec, "\r\n> ", "\n", -1)), "\n") if !firstTime { // Remove the first line of mongo output, which is an echo of the user's input msg = strings.SplitAfterN(msg, "\n", 2)[1] } if firstTime { msg += "\n" } if err := sh.print(msg); err != nil { return err } break } } return nil }
func (this *Lexicon) AddSpaces() { tokenizer := strutils.NewStrTokens(this.buffer.String()) buf := strutils.NewStringBuffer("") for tokenizer.HasMoreTokens() { next := strutils.NewStringBuffer(tokenizer.NextToken()) for _, op := range operators { count := strings.Count(next.String(), op) index := 0 for i := 0; i < count; i++ { index := strings.Index(next.String()[index:], op) next.Replace(index, index+len(op), " "+op+" ") index += 2 } } for _, sp := range separators { count := strings.Count(next.String(), sp) index := 0 for i := 0; i < count; i++ { index := strings.Index(next.String()[index:], sp) next.Replace(index, index+len(sp), " "+sp+" ") index += 2 } } buf.Append(next.String() + " ") } this.buffer = buf }
func (source *Source) CheckPreconditions() error { if err := ValidPath(source.File, source.FileFormat, ""); err != nil { return err } duplicatedPlaceholders := []string{} for _, name := range []string{"<locale_name>", "<locale_code>", "<tag>"} { if strings.Count(source.File, name) > 1 { duplicatedPlaceholders = append(duplicatedPlaceholders, name) } } starCount := strings.Count(source.File, "*") recCount := strings.Count(source.File, "**") if recCount == 0 && starCount > 1 || starCount-(recCount*2) > 1 { duplicatedPlaceholders = append(duplicatedPlaceholders, "*") } if recCount > 1 { duplicatedPlaceholders = append(duplicatedPlaceholders, "**") } if len(duplicatedPlaceholders) > 0 { dups := strings.Join(duplicatedPlaceholders, ", ") return fmt.Errorf(fmt.Sprintf("%s can only occur once in a file pattern!", dups)) } return nil }
func (s *GeneratorSuite) TestNewLine(c *C) { c.Logf("running test with %s backend", s.Builder()) var result string c.Assert(s.Len(), Equals, 0) s.NewLine() c.Assert(s.Len(), Equals, 1) s.Reset() for i := 0; i < 10; i++ { s.NewLine() } c.Assert(s.Len(), Equals, 10) result, _ = s.Resolve() c.Assert(strings.Count(result, "\n"), Equals, 10) s.Reset() s.NewLines(10) c.Assert(s.Len(), Equals, 10) result, _ = s.Resolve() c.Assert(strings.Count(result, "\n"), Equals, 10) // s.Reset() }