// A few CVEs contain characters that break Jira's text formatting func escape_text(s string) string { result := strings.Replace(s, "[", "\\[", -1) result = strings.Replace(result, "]", "\\]", -1) result = strings.Replace(result, "~", "\\~", -1) return result }
// path can be "" func InitLog(path string, debug bool) { config := ` <seelog type="sync" minlevel="${minlevel}"> <outputs formatid="main"> <console/> <!-- ${extra} --> </outputs> <formats> <format id="main" format="[EQ-%LEV] %Date(15:04:05.00): %Msg (at %File:%Line) %n"/> </formats> </seelog>` if path != "" { extra := fmt.Sprintf("<file path=\"%s\"/>", path) config = strings.Replace(config, "<!-- ${extra} -->", extra, -1) } Debug = debug if debug { config = strings.Replace(config, "${minlevel}", "debug", -1) } else { config = strings.Replace(config, "${minlevel}", "info", -1) } logger, err := seelog.LoggerFromConfigAsBytes([]byte(config)) if err != nil { panic(err) } seelog.ReplaceLogger(logger) if path != "" { seelog.Debugf("Initialized the logger for %s", path) } }
func (c *JoinCommand) Run(v *View, e *Edit) error { sel := v.Sel() for i := 0; i < sel.Len(); i++ { r := sel.Get(i) // Removing new line and triming in the selection t := v.Buffer().Substr(r) t = strings.Replace(t, "\r", "\n", -1) slice := strings.Split(t, "\n") t = "" for j, s := range slice { if j == 0 { t += s continue } t += " " + strings.TrimLeft(s, " \t") } v.Replace(e, r, t) // Removing the first new line after selection liner := v.Buffer().FullLine(r.End()) line := v.Buffer().Substr(liner) line = strings.Replace(line, "\n", "", -1) line = strings.Replace(line, "\r", "", -1) line = strings.TrimRight(line, " \t") // Triming the line after nextline := liner.End() + 1 nextliner := v.Buffer().FullLine(nextline) nline := v.Buffer().Substr(nextliner) if nline != "" { v.Replace(e, nextliner, " "+strings.TrimLeft(nline, " \t")) } v.Replace(e, liner, line) } return nil }
func isTeamCreationAllowed(c *Context, email string) bool { email = strings.ToLower(email) if !utils.Cfg.TeamSettings.EnableTeamCreation && !HasPermissionToContext(c, model.PERMISSION_MANAGE_SYSTEM) { c.Err = model.NewLocAppError("isTeamCreationAllowed", "api.team.is_team_creation_allowed.disabled.app_error", nil, "") return false } if result := <-Srv.Store.User().GetByEmail(email); result.Err == nil { user := result.Data.(*model.User) if len(user.AuthService) > 0 && len(*user.AuthData) > 0 { return true } } // commas and @ signs are optional // can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1)))) matched := false for _, d := range domains { if strings.HasSuffix(email, "@"+d) { matched = true break } } if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched { c.Err = model.NewLocAppError("isTeamCreationAllowed", "api.team.is_team_creation_allowed.domain.app_error", nil, "") return false } return true }
func NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat, topic string) (*FileLogger, error) { if gzipEnabled && strings.Index(filenameFormat, "<GZIPREV>") == -1 { return nil, errors.New("missing <GZIPREV> in filenameFormat") } hostname, err := os.Hostname() if err != nil { return nil, err } shortHostname := strings.Split(hostname, ".")[0] identifier := shortHostname if len(*hostIdentifier) != 0 { identifier = strings.Replace(*hostIdentifier, "<SHORT_HOST>", shortHostname, -1) identifier = strings.Replace(identifier, "<HOSTNAME>", hostname, -1) } filenameFormat = strings.Replace(filenameFormat, "<TOPIC>", topic, -1) filenameFormat = strings.Replace(filenameFormat, "<HOST>", identifier, -1) if gzipEnabled && !strings.HasSuffix(filenameFormat, ".gz") { filenameFormat = filenameFormat + ".gz" } f := &FileLogger{ logChan: make(chan *Message, 1), compressionLevel: compressionLevel, filenameFormat: filenameFormat, gzipEnabled: gzipEnabled, ExitChan: make(chan int), termChan: make(chan bool), hupChan: make(chan bool), } return f, nil }
func parseHost(str string) (*Host, error) { host := &Host{ Addr: str, Port: "22", } if str != "" && str[0] == '[' { i := strings.LastIndex(str, ":") if i == -1 || i-1 < 1 { return nil, fmt.Errorf("knownhosts: Invalid host: %#v", str) } host.Addr = str[1 : i-1] host.Port = str[i+1:] } else if strings.ContainsAny(str, "*?") { pattern := str if pattern[0] == '!' { pattern = pattern[1:] host.PatternNegated = true } pattern = strings.Replace(pattern, ".", "\\.", -1) pattern = strings.Replace(pattern, "*", ".*", -1) pattern = strings.Replace(pattern, "?", ".", -1) r, err := regexp.Compile("^" + pattern + "$") if err != nil { return nil, err } host.Addr = "" host.Pattern = r host.PatternRaw = str } return host, nil }
func GetSubDomain(s string) (string, string) { s = strings.Replace(s, "http://", "", 1) s = strings.Replace(s, "https://", "", 1) match := wwwStart.MatchString(s) if match { return "", "" } match = betaStart.MatchString(s) if match { return "", "" } match = ciStart.MatchString(s) if match { return "", "" } parts := strings.Split(s, ".") if len(parts) != 3 { return "", "" } return parts[0], parts[1] }
// VersionPackage computes a given version package name. // v1 => v1, V1 => v1, 1 => v1, 1.0 => v1 if unique - v1dot0 otherwise. func VersionPackage(version string) string { var others []string design.Design.IterateVersions(func(v *design.APIVersionDefinition) error { others = append(others, v.Version) return nil }) idx := strings.Index(version, ".") if idx == 0 { // weird but OK version = strings.Replace(version, ".", "dot", -1) } else if idx > 0 { uniqueMajor := true match := majorRegex.FindStringSubmatch(version) if len(match) > 1 { major := match[1] for _, o := range others { match = majorRegex.FindStringSubmatch(o) if len(match) > 1 && major != match[1] { uniqueMajor = false break } } } if uniqueMajor { version = version[:idx] } else { strings.Replace(version, ".", "dot", -1) } } if digitPrefixRegex.MatchString(version) { version = "v" + version } return Goify(version, false) }
func ProcessRename(page *Page, args []string) { if len(args) < 1 { errhandle(fmt.Errorf("'rename' rule needs an argument")) } dest := args[0] if strings.Contains(dest, "*") { if !strings.Contains(page.Pattern, "*") { errhandle(fmt.Errorf( "'rename' rule cannot rename '%s' to '%s'", page.Pattern, dest)) } group := fmt.Sprintf("([^%c]*)", filepath.Separator) base := filepath.Base(page.Pattern) pat := strings.Replace(regexp.QuoteMeta(base), "\\*", group, 1) re, err := regexp.Compile(pat) errhandle(err) m := re.FindStringSubmatch(filepath.Base(page.Path)) dest = strings.Replace(dest, "*", m[1], 1) } page.Path = filepath.Join(filepath.Dir(page.Path), dest) }
func moveGitFiles(src, dest string, errLog io.Writer) error { cmd := exec.Command("git", "ls-files") cmd.Dir = dest cmd.Stderr = errLog out, err := cmd.Output() if err != nil { return err } tracked := make(map[string]bool) for _, filename := range strings.Split(string(out), "\n") { if strings.TrimSpace(filename) == "" { continue } tracked[filename] = true } return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if info.IsDir() { return os.MkdirAll(strings.Replace(path, src, dest, 1), info.Mode()) } if !info.Mode().IsRegular() { return nil } relative := strings.Replace(path, src+"/", "", 1) if !tracked[relative] { return nil } return os.Rename(path, dest+"/"+relative) }) }
// Write one edge func (rw *RefWriter) WriteEdge(from, to key.Key, linkname string) error { if rw.Ctx != nil { select { case <-rw.Ctx.Done(): // just in case. return rw.Ctx.Err() default: } } var s string switch { case rw.PrintFmt != "": s = rw.PrintFmt s = strings.Replace(s, "<src>", from.Pretty(), -1) s = strings.Replace(s, "<dst>", to.Pretty(), -1) s = strings.Replace(s, "<linkname>", linkname, -1) case rw.PrintEdge: s = from.Pretty() + " -> " + to.Pretty() default: s += to.Pretty() } rw.out <- &RefWrapper{Ref: s} return nil }
// winPath converts a path into a windows safe path func winPath(s string) string { s = strings.Replace(s, "?", "_", -1) s = strings.Replace(s, `"`, "_", -1) s = strings.Replace(s, "<", "_", -1) s = strings.Replace(s, ">", "_", -1) return s }
func CleanTeamName(s string) string { s = strings.ToLower(strings.Replace(s, " ", "-", -1)) for _, value := range reservedName { if strings.Index(s, value) == 0 { s = strings.Replace(s, value, "", -1) } } s = strings.TrimSpace(s) for _, c := range s { char := fmt.Sprintf("%c", c) if !validTeamNameCharacter.MatchString(char) { s = strings.Replace(s, char, "", -1) } } s = strings.Trim(s, "-") if !IsValidTeamName(s) { s = NewId() } return s }
func parse(s string) ([]string, error) { if s == "" { return nil, nil } if s[0] != Separator { return nil, ErrInvalidPointer } prev := 0 tokens := []string{} for i := 1; i < len(s); i++ { switch s[i] { case Separator: tokens = append(tokens, s[prev+1:i]) prev = i } } if prev != len(s) { tokens = append(tokens, s[prev+1:]) } dtokens := make([]string, 0, len(tokens)) for _, t := range tokens { t = strings.Replace(strings.Replace(t, EncodedSlash, "/", -1), EncodedTilde, "~", -1) dtokens = append(dtokens, t) } return dtokens, nil }
func isTreamCreationAllowed(c *Context, email string) bool { email = strings.ToLower(email) if utils.Cfg.TeamSettings.DisableTeamCreation { c.Err = model.NewAppError("isTreamCreationAllowed", "Team creation has been disabled. Please ask your systems administrator for details.", "") return false } // commas and @ signs are optional // can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1)))) matched := false for _, d := range domains { if strings.HasSuffix(email, "@"+d) { matched = true break } } if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched { c.Err = model.NewAppError("isTreamCreationAllowed", "Email must be from a specific domain (e.g. @example.com). Please ask your systems administrator for details.", "") return false } return true }
func string_f() { // Here's a sample of the functions available in // `strings`. Note that these are all functions from // package, not methods on the string object itself. // This means that we need pass the string in question // as the first argument to the function. p("Contains :", s.Contains("test", "es")) p("Count :", s.Count("test", "t")) p("HasPrefix :", s.HasPrefix("test", "te")) p("HasSuffix :", s.HasSuffix("test", "st")) p("Index :", s.Index("test", "e")) p("Join :", s.Join([]string{"a", "b"}, "-")) p("Repeat :", s.Repeat("a", 5)) p("Replace :", s.Replace("foo", "o", "0", -1)) p("Replace :", s.Replace("foo", "o", "0", 1)) p("Split :", s.Split("a-b-c-d-e", "-")) p("ToLower :", s.ToLower("TEST-test")) p("ToUpper :", s.ToUpper("TEST-test")) p() // You can find more functions in the `strings`package docs. // Not part of `strings` but worth mentioning here are // the mechanisms for getting the length of a string // and getting a character by index. p("Len: ", len("Hello")) p("Char: ", "hello"[1]) }
func luaMakeMvcs(tPath, ePath string) { dir := fmt.Sprintf(appPath+V3_EXPORT_MODULE, moduleName) if !IsDir(dir) { os.Mkdir(dir, 0777) } exportPath := fmt.Sprintf(appPath+ePath, moduleName, moduleName) lines, err := ReadLines(tPath) if err != nil { fmt.Println("Error:%s\n", err) return } var result []string for _, line := range lines { newLine := strings.Replace(line, "{{name}}", moduleName, -1) newLine = strings.Replace(newLine, "{{time}}", time.Now().Format("2006-01-02"), -1) result = append(result, newLine) // fmt.Println(line) } err = WriteLines(result, exportPath) // fmt.Println(err) }
func GetLinuxInfo() (distribution, version, kernel_version string) { // Getting Linux distribution var ( version_buf bytes.Buffer ) version_cmd := exec.Command("lsb_release", "-a") version_cmd.Stdout = &version_buf version_cmd.Run() version_details := strings.Split(strings.ToLower(version_buf.String()), "\n") for _, d := range version_details { switch { case strings.Contains(d, "distributor id:"): { distribution = strings.Replace(strings.Replace(d, "distributor id:", "", -1), " ", "", -1) } case strings.Contains(d, "release:"): { version = strings.Replace(strings.Replace(d, "distributor id:", "", -1), " ", "", -1) } } } version_buf = bytes.Buffer{} version_cmd = exec.Command("uname", "-r") version_cmd.Stdout = &version_buf version_cmd.Run() kernel_version = version_buf.String() return }
func sanitize(contents string) string { output := contents output = strings.Replace(output, pivnetAPIToken, "***sanitized-api-token***", -1) output = strings.Replace(output, awsAccessKeyID, "***sanitized-aws-access-key-id***", -1) output = strings.Replace(output, awsSecretAccessKey, "***sanitized-aws-secret-access-key***", -1) return output }
func buildTags(metric telegraf.Metric) string { var keys []string tags := metric.Tags() for k := range tags { if k == "host" { continue } keys = append(keys, k) } sort.Strings(keys) var tag_str string if host, ok := tags["host"]; ok { if len(keys) > 0 { tag_str = strings.Replace(host, ".", "_", -1) + "." } else { tag_str = strings.Replace(host, ".", "_", -1) } } for i, k := range keys { tag_value := strings.Replace(tags[k], ".", "_", -1) if i == 0 { tag_str += tag_value } else { tag_str += "." + tag_value } } return sanitizedChars.Replace(tag_str) }
// unitPrintf is analogous to systemd's `unit_name_printf`. It will take the // given string and replace the following specifiers with the values from the // provided UnitNameInfo: // %n: the full name of the unit ([email protected]) // %N: the name of the unit without the suffix (foo@bar) // %p: the prefix (foo) // %i: the instance (bar) func unitPrintf(s string, nu unit.UnitNameInfo) (out string) { out = strings.Replace(s, "%n", nu.FullName, -1) out = strings.Replace(out, "%N", nu.Name, -1) out = strings.Replace(out, "%p", nu.Prefix, -1) out = strings.Replace(out, "%i", nu.Instance, -1) return }
func CreateGraphitePublisher() (*GraphitePublisher, error) { graphiteSection, err := setting.Cfg.GetSection("metrics.graphite") if err != nil { return nil, nil } address := graphiteSection.Key("address").String() if address == "" { return nil, nil } publisher := &GraphitePublisher{} publisher.prevCounts = make(map[string]int64) publisher.protocol = "tcp" publisher.prefix = graphiteSection.Key("prefix").MustString("prod.grafana.%(instance_name)s") publisher.address = address safeInstanceName := strings.Replace(setting.InstanceName, ".", "_", -1) prefix := graphiteSection.Key("prefix").Value() if prefix == "" { prefix = "prod.grafana.%(instance_name)s." } publisher.prefix = strings.Replace(prefix, "%(instance_name)s", safeInstanceName, -1) return publisher, nil }
// RunFile returns the directory and file location where the binary generated // for sourcefile should be put. In case the directory does not yet exist, it // will be created by RunDir. func RunFile(sourcefile string) (rundir, runfile string, err os.Error) { rundir, err = RunDir() if err != nil { return "", "", err } sourcefile, err = filepath.Abs(sourcefile) if err != nil { return "", "", err } sourcefile, err = filepath.EvalSymlinks(sourcefile) if err != nil { return "", "", err } runfile = strings.Replace(sourcefile, "%", "%%", -1) if os.Getenv("GOOS") != "windows" { runfile = strings.Replace(runfile, string(filepath.Separator), "%", -1) runfile = runfile } else { runfile = strings.Replace(runfile, string(filepath.Separator), "_", -1) runfile = strings.Replace(runfile, ":", "_", -1) } runfile = filepath.Join(rundir, runfile) return rundir, runfile, nil }
func done(obj *ast.Object, typ types.Type) { defer os.Exit(0) pos := types.FileSet.Position(types.DeclPos(obj)) fmt.Printf("%v\n", pos) if typ.Kind == ast.Bad || !*tflag { return } fmt.Printf("%s\n", strings.Replace(typeStr(obj, typ), "\n", "\n\t", -1)) if *aflag || *Aflag { var m orderedObjects for obj := range typ.Iter(types.DefaultImporter) { m = append(m, obj) } sort.Sort(m) for _, obj := range m { // Ignore unexported members unless Aflag is set. if !*Aflag && (typ.Pkg != "" || !ast.IsExported(obj.Name)) { continue } id := ast.NewIdent(obj.Name) id.Obj = obj _, mt := types.ExprType(id, types.DefaultImporter) fmt.Printf("\t%s\n", strings.Replace(typeStr(obj, mt), "\n", "\n\t\t", -1)) fmt.Printf("\t\t%v\n", types.FileSet.Position(types.DeclPos(obj))) } } }
func BackgroundContext() netcontext.Context { ctxs.Lock() defer ctxs.Unlock() if ctxs.bg != nil { return toContext(ctxs.bg) } // Compute background security ticket. appID := partitionlessAppID() escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1) majVersion := VersionID(nil) if i := strings.Index(majVersion, "."); i > 0 { majVersion = majVersion[:i] } ticket := fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID()) ctxs.bg = &context{ req: &http.Request{ Header: http.Header{ ticketHeader: []string{ticket}, }, }, apiURL: apiURL(), } // TODO(dsymonds): Wire up the shutdown handler to do a final flush. go ctxs.bg.logFlusher(make(chan int)) return toContext(ctxs.bg) }
func String2XML(value string) string { value = strings.Replace(value, "&", "&", -1) value = strings.Replace(value, "\"", """, -1) value = strings.Replace(value, "<", "<", -1) value = strings.Replace(value, ">", ">", -1) return fmt.Sprintf("<string>%s</string>", value) }
func SendEmail(to, subject, title, body string) bool { hp := strings.Split(host, ":") auth := smtp.PlainAuth("", username, password, hp[0]) var content_type string mailtype := "html" if mailtype == "html" { content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8" } else { content_type = "Content-Type: text/plain" + "; charset=UTF-8" } // 登录之 body = strings.Replace(bodyTpl, "$body", body, 1) body = strings.Replace(body, "$title", title, 1) msg := []byte("To: " + to + "\r\nFrom: " + username + "<" + username + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body) send_to := strings.Split(to, ";") err := smtp.SendMail(host+":"+port, auth, username, send_to, msg) if err != nil { return false } return true }
func IsVerifyHashRequired(user *model.User, team *model.Team, hash string) bool { shouldVerifyHash := true if team.Type == model.TEAM_INVITE && len(team.AllowedDomains) > 0 && len(hash) == 0 && user != nil { domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(team.AllowedDomains, "@", " ", -1), ",", " ", -1)))) matched := false for _, d := range domains { if strings.HasSuffix(user.Email, "@"+d) { matched = true break } } if matched { shouldVerifyHash = false } else { return true } } if team.Type == model.TEAM_OPEN { shouldVerifyHash = false } if len(hash) > 0 { shouldVerifyHash = true } return shouldVerifyHash }
func getUberCost(start locationStruct, end locationStruct) (int, int, float64, string) { uberURL := strings.Replace(uberRequestURL, startLatitude, strconv.FormatFloat(start.Coordinate.Lat, 'f', -1, 64), -1) uberURL = strings.Replace(uberURL, startLongitude, strconv.FormatFloat(start.Coordinate.Lng, 'f', -1, 64), -1) uberURL = strings.Replace(uberURL, endLatitude, strconv.FormatFloat(end.Coordinate.Lat, 'f', -1, 64), -1) uberURL = strings.Replace(uberURL, endLongitude, strconv.FormatFloat(end.Coordinate.Lng, 'f', -1, 64), -1) res, err := http.Get(uberURL) if err != nil { //w.Write([]byte(`{ "error": "Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75"}`)) fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75") panic(err.Error()) } body, err := ioutil.ReadAll(res.Body) if err != nil { //w.Write([]byte(`{ "error": "Unable to parse data from Google. body, err := ioutil.ReadAll(res.Body) -- line 84"}`)) fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 84") panic(err.Error()) } var uberResult UberResults _ = json.Unmarshal(body, &uberResult) return uberResult.Prices[0].LowEstimate, uberResult.Prices[0].Duration, uberResult.Prices[0].Distance, uberResult.Prices[0].ProductID }
func (conf *PacmanConfig) CreateHandle() (*Handle, error) { h, err := Init(conf.RootDir, conf.DBPath) if err != nil { return nil, err } if conf.Architecture == "auto" { conf.Architecture, err = getArch() if err != nil { return nil, fmt.Errorf("architecture is 'auto' but couldn't uname()") } } for _, repoconf := range conf.Repos { // TODO: set SigLevel db, err := h.RegisterSyncDb(repoconf.Name, 0) if err == nil { for i, addr := range repoconf.Servers { addr = strings.Replace(addr, "$repo", repoconf.Name, -1) addr = strings.Replace(addr, "$arch", conf.Architecture, -1) repoconf.Servers[i] = addr } db.SetServers(repoconf.Servers) } } return h, nil }