func (c *client) purge(host string, f gfind.File, k int, id int) { var Url *url.URL Url, err := url.Parse(host) chkErr(err) Url.Path += "/purge" Url.Path += f.Relpath var u string u = Url.String() if security != "" { u += "?" + ParseNgxSecurityLink(security, host, f) } req, err := http.NewRequest("HEAD", u, nil) req.Close = true if vhost != "client.com" { req.Host = vhost } resp, err := c.c.Do(req) chkErr(err) if resp.StatusCode == 200 { color.Printf("%6v-%-2d @{g}%-17v@{|} %v %v\n", k, id, "PURGE:SUCCESS", Url.String(), f.Size()) } else if resp.StatusCode == 404 { color.Printf("%6v-%-2d @{y}%-17v@{|} %v %v\n", k, id, "PURGE:NOFILE", Url.String(), f.Size()) } }
func output(hostname, servicename, v interface{}) { // define quick color/graphic view of output var s, m, a string if state(v) == 0 { s = color.Sprintf("@{g}%-10s", "[OK]") } else if state(v) == 1 { s = color.Sprintf("@{y}%-10s", "[WARNING]") } else if state(v) == 2 { s = color.Sprintf("@{r}%-10s", "[CRITICAL]") } if notifications(v) { m = color.Sprintf("@{g} %v ", ` `) } else { m = color.Sprintf("@{r} %v ", `Ø`) } if acknowledged(v) { a = color.Sprintf("@{g} %v ", `√`) } else { a = color.Sprintf("@{g} %v ", ` `) } // this just incase if change mind use different syntax switch v := v.(type) { default: case *nagiosToJson.Hoststatus: // color.Printf("%-10s: %v %v %v %v %v\n", hostname, m, s, a, v.Plugin_output, time.Since(str2time(v.Last_check))) color.Printf("%-10s: %-10v %v %v %v %v %v\n", hostname, servicename, m, s, a, v.Plugin_output, time.Since(str2time(v.Last_check))) case *nagiosToJson.Servicestatus: color.Printf("%-10s: %-10v %v %v %v %v %v\n", hostname, servicename, m, s, a, v.Plugin_output, time.Since(str2time(v.Last_check))) } }
func readWholeNumber(prompt string, bits int, unsigned bool, allowBlank bool, defaultValue int64) (out int64, err error) { var iu uint64 var i int64 loop: for { fmt.Print(prompt) line, err := readLine() if strings.TrimSpace(line) == "" && allowBlank { if unsigned { iu = uint64(defaultValue) } else { i = defaultValue } break loop } if unsigned { iu, err = strconv.ParseUint(string(line), 10, bits) } else { i, err = strconv.ParseInt(string(line), 10, bits) } if err != nil { numError := err.(*strconv.NumError) switch numError.Err { case strconv.ErrSyntax: if unsigned { color.Printf("@{r}%s is not a non-negative integer\n", numError.Num) } else { color.Printf("@{r}%s is not a integer\n", numError.Num) } continue loop case strconv.ErrRange: color.Printf("@{r}%s does not fit in %d bits\n", numError.Num, bits) continue loop default: color.Printf("@{r}Unknown error %s\n", numError) continue loop } } break loop } if unsigned { out = int64(iu) } else { out = i } return }
// dump request , body true/false, print true/false func dumpResponse(r *http.Response, b, p bool, host string) []byte { dump, err := httputil.DumpResponse(r, b) if err != nil { log.Println(err.Error()) } // isGzip := false // if v, ok := r.Header["Accept-Encoding"]; ok { // if strings.Contains(v[0], "gzip") { // isGzip = true // log.Println("is gzip") // } // } if p { index := bytes.Index(dump, []byte("\r\n\r\n")) headers := dump[:index] body := bytes.TrimLeft(dump[index:], "\r\n\r\n") // body = bytes.TrimLeft(body, string([]byte{13, 10, 13, 10})) // if isGzip { // reader := bytes.NewReader(body) // g, err := gzip.NewReader(reader) // if err != nil { // log.Println(err.Error()) // } // body, err = ioutil.ReadAll(g) // if err != nil { // log.Println(err.Error()) // } // } if *veryverbose { now := time.Now() dirname := "/tmp/stfdump/" + host if _, err := os.Stat(dirname); err != nil { if err := os.MkdirAll(dirname, 0755); err != nil { log.Fatalln(err.Error()) } } filename := fmt.Sprintf("%s/%d<", dirname, now.UnixNano()) ioutil.WriteFile(filename, body, 0644) } if *colors { // color.Printf("@{b}%s@{|}", string(dump)) color.Printf("@{c}%v@{|}\n", string(headers)) if *showBody { color.Printf("@{g}%v@{|}\n", string(body)) } // color.Printf("@{g}%v@{|}\n", ehex.EncodeToString(body)) // color.Printf("@{g}%v@{|}\n", body) } else { // fmt.Print(string(dump)) fmt.Println(string(headers)) fmt.Println(string(body)) } } return dump }
func (self *Case) reportFailWithDiff(lhs, rhs interface{}) { if lhs != nil && rhs != nil { if s1, ok := lhs.(string); ok { s2 := rhs.(string) self.printDiff(s1, s2) return } } color.Printf("@r...@| expected @g%s = %v@|\n", mustTypeName(lhs), lhs) color.Printf("@r...@| actual @r%s = %v@|\n", mustTypeName(rhs), rhs) }
func query(name, qtype string) { start := time.Now() qname, err := idna.ToASCII(name) if err != nil { color.Fprintf(os.Stderr, "Invalid IDN domain name: %s\n", name) os.Exit(1) } rrs, err := resolver.ResolveErr(qname, qtype) color.Printf("\n") if len(rrs) > 0 { color.Printf("@{g};; RESULTS:\n") } for _, rr := range rrs { color.Printf("@{g}%s\n", rr.String()) } if err != nil { color.Printf("@{r};; %s\t%s\t%s\n", err, name, qtype) } else if rrs == nil { color.Printf("@{y};; NIL\t%s\t%s\n", name, qtype) } else if len(rrs) > 0 { color.Printf("@{g};; TRUE\t%s\t%s\n", name, qtype) } else { color.Printf("@{r};; FALSE\t%s\t%s\n", name, qtype) } color.Printf("@{.w};; Elapsed: %s\n", time.Since(start).String()) }
func (self *Case) reportFail(depth int, lhs, rhs interface{}, msg string, op int) { self.location(depth + 1) color.Printf("@r---@| FAIL %s\n", msg) switch op { case eq: fallthrough case throw: self.reportFailWithDiff(lhs, rhs) case ne: color.Printf("@r...@| expected @g%s = %v@|\n", mustTypeName(lhs), lhs) color.Printf("@r...@| but is @requals@|\n") } self.numFail++ }
func observeChannel(resultRepository <-chan *github.Repository, networkErr <-chan error) (*github.Repository, error) { var repository *github.Repository var err error getLoop: for { select { case repository = <-resultRepository: break getLoop case getErr := <-networkErr: fmt.Printf("\n\n") color.Printf("@{r} !!! Error Occuered !!! ") fmt.Printf("\n\n") fmt.Println(getErr) fmt.Printf("\n\n") break getLoop case <-time.After(time.Minute): fmt.Println(" @{r} !!! Timeout !!! ") break getLoop default: time.Sleep(time.Second / 2) fmt.Printf(".") } } return repository, err }
func main() { flag.Usage = func() { color.Fprintf(os.Stderr, "Usage: %s [arguments] <name> [type]\n\nAvailable arguments:\n", os.Args[0]) flag.PrintDefaults() os.Exit(1) } flag.Parse() qtype := "" args := flag.Args() if len(args) == 0 { flag.Usage() } else if _, isType := dns.StringToType[args[len(args)-1]]; len(args) > 1 && isType { qtype, args = args[len(args)-1], args[:len(args)-1] } if verbose { dnsr.DebugLogger = os.Stderr } var wg sync.WaitGroup start := time.Now() for _, name := range args { wg.Add(1) go func(name string, qtype string) { query(name, qtype) wg.Done() }(name, qtype) } wg.Wait() if len(args) > 1 { color.Printf("\n@{.w};; Total elapsed: %s\n", time.Since(start).String()) } }
// Update project details // http://docs.gemnasium.apiary.io/#patch-%2Fprojects%2F%7Bslug%7D func (p *Project) Update(name, desc *string, monitored *bool) error { if name == nil && desc == nil && monitored == nil { return errors.New("Please specify at least one thing to update (name, desc, or monitored") } update := make(map[string]interface{}) if name != nil { update["name"] = *name } if desc != nil { update["desc"] = *desc } if monitored != nil { update["monitored"] = *monitored } opts := &gemnasium.APIRequestOptions{ Method: "PATCH", URI: fmt.Sprintf("/projects/%s", p.Slug), Body: update, } err := gemnasium.APIRequest(opts) if err != nil { return err } color.Printf("@gProject %s updated succesfully\n", p.Slug) return nil }
func (self *Case) Fail() { self.location(2) color.Printf("@r---@| FAIL %s\n", self.what) self.what = "" self.numFail++ panic(self) }
func (p *Printer) Printf(fmtstr string, args ...interface{}) { if p.NoColors { fmtstr = removeMeta.ReplaceAllLiteralString(fmtstr, "") fmt.Printf(fmtstr, args...) } else { color.Printf(fmtstr, args...) } }
func (v *GRVisitor) SearchFile(fn string, content []byte) { lines := IntList([]int{}) binary := false if bytes.IndexByte(content, 0) != -1 { binary = true } for _, info := range v.FindAllIndex(content) { if lines.Contains(info.num) { continue } if v.prependNewLine { fmt.Println("") v.prependNewLine = false } first := len(lines) == 0 lines = append(lines, info.num) if first { if binary && !*onlyName { fmt.Printf("Binary file %s matches\n", fn) break } else { color.Printf("@g%s\n", fn) } } if *onlyName { return } color.Printf("@!@y%d:", info.num) coloredLine := v.pattern.ReplaceAllStringFunc(string(info.line), func(wrap string) string { return color.Sprintf("@Y%s", wrap) }) fmt.Printf("%s\n", coloredLine) } if len(lines) > 0 { v.prependNewLine = true } }
func doCreate(c *cli.Context) { name := c.Args().First() if len(name) == 0 { return } // check configuration configuration, err := OpenConfiguration() if err != nil { fmt.Println(err) return } if configuration.GithubToken == "" { configuration.GithubToken = PromptPersonalGithubToken() configuration.Persist() } // set repository attributes newRepository := github.Repository{Name: &name} prompt := c.Bool(flagDetail) if description := GetRepositryField(flagDesc, c.String(flagDesc), prompt).(string); description != "" { newRepository.Description = &description } if homepage := GetRepositryField(flagHP, c.String(flagHP), prompt).(string); homepage != "" { newRepository.Homepage = &homepage } if teamid := GetRepositryField(flagTeamID, c.Int(flagTeamID), prompt).(int); teamid != 0 { newRepository.TeamID = &teamid } private := GetRepositryField(flagPrivate, c.Bool(flagPrivate), prompt).(bool) newRepository.Private = &private issue := GetRepositryField(flagIssue, c.Bool(flagIssue), prompt).(bool) newRepository.HasIssues = &issue wiki := GetRepositryField(flagWiki, c.Bool(flagWiki), prompt).(bool) newRepository.HasWiki = &wiki download := GetRepositryField(flagDownload, c.Bool(flagDownload), prompt).(bool) newRepository.HasDownloads = &download // create repository org := c.String(flagOrg) client := NewClient(configuration) repository, _ := observeChannel(client.CreateRepository(org, &newRepository)) if repository == nil { return } output := "\n\n" + "=========================\n" + " \n" + "@{g}* We are sccessful in Creating a repository! Push an existing repository from the command line@{|}\n" + " \n" + "git remote add origin %s \n" + "git push -u origin master\n" + " \n" + "=========================\n" + "\n\n" color.Printf(output, *repository.GitURL) }
func (p *Printer) Printf(colorfmt, plainfmt string, args ...interface{}) { if p.NoColors { fmt.Printf(plainfmt, args...) } else { color.Printf(colorfmt, args...) } }
// define output in one place, make it clean func title() { // use HOST as host check servicename // if *mutehost != "" { // color.Printf("%-10s: %v %-10v %v %v\n", "hostname", "alert", "state", "acked", "output") // } // if *muteservice != "" { color.Printf("%-10s: %-10v %v %-10v %v %v\n", "hostname", "srvname", "alert", "state", "acked", "output") // } }
func (self *Batch) val() interface{} { if self.index >= len(self.returnVals) { self.c.location(1) color.Printf("@r---@| FAIL: too many check values, max: %v\n", len(self.returnVals)) self.c.numFail++ panic(self.c) } return self.returnVals[self.index] }
func (c *BalanceCommand) Run() error { user := &models.User{} user.Id = db.USERID amount, err := user.GetBalance() if err != nil { return err } color.Printf("@gBalance: %f\n", amount) return nil }
func (v *GRVisitor) ReplaceInFile(fn string, content []byte) (changed bool, result []byte) { changed = false binary := false changenum := 0 if *singleline { errhandle( fmt.Errorf("Can't handle singleline replacements yet"), true, "") } if *plaintext { errhandle( fmt.Errorf("Can't handle plain text replacements yet"), true, "") } if bytes.IndexByte(content, 0) != -1 { binary = true } result = v.pattern.ReplaceAllFunc(content, func(s []byte) []byte { if binary && !*force { errhandle( fmt.Errorf("supply --force to force change of binary file"), false, "") } if !changed { changed = true color.Printf("@g%s", fn) } changenum += 1 return []byte(*replace) }) if changenum > 0 { color.Printf("@!@y - %d change%s made\n", changenum, getSuffix(changenum)) } return changed, result }
// uses color if availible func smartPrintf(format string, a ...interface{}) (cnt int, err error) { pattern := regexp.MustCompile(`@.`) if useColor { cnt, err = color.Printf(format, a...) } else { rawFormat := pattern.ReplaceAll([]byte(format), []byte("")) cnt, err = fmt.Printf(string(rawFormat), a...) } return }
func (s *LoggingServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { s.mu.RLock() defer s.mu.RUnlock() if i := sort.SearchStrings(s.ExcludePaths, req.URL.Path); i < len(s.ExcludePaths) && req.URL.Path == s.ExcludePaths[i] { return } req.ParseForm() // Log request var data string for key, _ := range req.Form { data += "\n " if value := req.Form.Get(key); value != "" { data += color.Sprintf("@.%s@|@w = @|%s", key, value) } else { data += color.Sprintf("%s", key) } } log.Print(color.Sprintf("@c%s @{!y}%s", req.Method, req.RequestURI)) if data != "" { color.Printf(" @bRequest@|%s\n", data) } // Find matcher matcher := s.findMatcher(req) if matcher != nil { matcher.Write(w, req) // TODO Better response logging response := matcher.Response color.Printf(" @gResponse@|\n %+v\n", response) } else { color.Print(" @rUnmatched@|\n") w.WriteHeader(http.StatusNotFound) w.Header().Set("Content-Type", "text/html") io.WriteString(w, "<html><body>Unmatched request, please configure a mock request for path "+req.URL.Path+" and method "+req.Method+"</body></html>\n") } }
func (self *Case) location(depth int) { if _, file, line, ok := runtime.Caller(depth); ok { lines, err := self.cache.Put(file) if err != io.EOF { panic(err) } file = self.fileName(file) color.Printf("@r---@| %s.%s %s:%d:\n%s\n", self.suiteName, self.name, file, line, lines[line-1]) } }
func printDCR(dcr *epp.DomainCheckResponse) { if dcr == nil { return } av := make(map[string]bool) for _, c := range dcr.Checks { av[c.Domain] = c.Available if c.Available { color.Printf("@{g}%s\tavail=%t\treason=%q\n", c.Domain, c.Available, c.Reason) } else { color.Printf("@{y}%s\tavail=%t\treason=%q\n", c.Domain, c.Available, c.Reason) } } for _, c := range dcr.Charges { if av[c.Domain] { color.Printf("@{g}%s\tcategory=%s\tname=%q\n", c.Domain, c.Category, c.CategoryName) } else { color.Printf("@{y}%s\tcategory=%s\tname=%q\n", c.Domain, c.Category, c.CategoryName) } } }
func largestWithNodes(c *cli.Context) { debug := true command := "find / ! -readable -prune -type f -printf '%s %p\n' 2> /dev/null | sort -nr | head -n 15" if c.Bool("sudo") == true { command = fmt.Sprintf("/usr/bin/sudo -n bash <<CMD\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n%s\nCMD", command) } else { command = fmt.Sprintf("/bin/bash <<CMD\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n%s\nCMD", command) } if debug { color.Printf("@{b}%s\n", command) } var conns []string if c.IsSet("nodes") { conns = filterHosts(strings.Split(c.String("nodes"), ",")) } else if c.IsSet("node") { conns = filterHosts(c.StringSlice("node")) } else { fmt.Errorf("Node or Nodes must be specified") } pathToSizeAndNodes := make(map[string]sizeByNodes) results := runSsh(conns, command, debug) for _, r := range results { lines := strings.Split(r.Res, "\n") for _, line := range lines { items := strings.Fields(line) fmt.Println(items[0]) fmt.Println(items[1]) path := items[1] if _, ok := pathToSizeAndNodes[path]; ok == false { size, err := strconv.ParseUint(items[0], 0, 0) if err != nil { panic(err) } pathToSizeAndNodes[path] = sizeByNodes{Size: size, Nodes: []string{r.Host}} } else { nodes := append(pathToSizeAndNodes[path].Nodes, r.Host) pathToSizeAndNodes[path] = sizeByNodes{Size: pathToSizeAndNodes[path].Size, Nodes: nodes} } } } for _, res := range sortedKeys(pathToSizeAndNodes) { fmt.Printf("%s\t%s\t%v\n", humanize.Bytes(pathToSizeAndNodes[res].Size), res, pathToSizeAndNodes[res].Nodes) } }
func (self *Case) printDiff(s1, s2 string) { s1, s2 = formatize(" ", s1), formatize(" ", s2) color.Printf("@r...@| expected @gstring =@|\n%v\n", s1) color.Printf("@r...@| actual @rstring =@|\n%v\n", s2) color.Printf("@r...@| diff is\n") state := dmp.New() diffs := state.DiffMain(s1, s2, false) for _, diff := range diffs { switch diff.Type { case dmp.DiffEqual: fmt.Print(diff.Text) case dmp.DiffDelete: color.Printf("@r[-%s]@|", diff.Text) case dmp.DiffInsert: color.Printf("@g[+%s]@|", diff.Text) } } fmt.Println() }
// Start project synchronization // http://docs.gemnasium.apiary.io/#post-%2Fprojects%2F%7Bslug%7D%2Fsync func (p *Project) Sync() error { opts := &gemnasium.APIRequestOptions{ Method: "POST", URI: fmt.Sprintf("/projects/%s/sync", p.Slug), } err := gemnasium.APIRequest(opts) if err != nil { return err } color.Printf("@gSynchronization started for project %s\n", p.Slug) return nil }
func showHelp() { fmt.Println() color.Printf( ` * HELP * @{Kg}/chat [ID]@{|} Start a chat with [ID] @{Kg}/end @{|} End current chat @{Kg}/add [ID]@{|} Add [ID] to roster @{Kg}/mkg @{|} Generate new group id @{Kg}/help @{|} Show this message @{Kg}/stat @{|} Show node status @{Kg}/exit @{|} Exit this program`) fmt.Println() }
/** * Central function for printing */ func print(level int, message string) { if !beenhere { startTime = time.Now() beenhere = true } if _level >= level { // // Escape newlines and carriage returns // message = strings.Replace(message, "\n", "\\n", -1) message = strings.Replace(message, "\r", "\\r", -1) // // Escape anything else that is below ASCII 32 (space) // This is done because backspace (ASCII 8) is especially evil, // as an attrack could inject backspaces to hide their tracks // re, _ := regexp.Compile("([\x00-\x1f])") message = re.ReplaceAllStringFunc(message, func(in string) string { return (fmt.Sprintf("[0x%x]", in)) }) // // If displayTime is uninitialized, default to true // if displayTime == 0 || displayTime == 2 { now := time.Now() elapsed := now.Sub(startTime) if UseColor() { color_string := getColor(level) color.Printf(color_string+"[%s] %s\n", elapsed, message) } else { fmt.Printf("[%s] %s\n", elapsed, message) } } else { if UseColor() { color_string := getColor(level) color.Println(color_string + message) } else { fmt.Println(message) } } } } // End of print()
func printGitlabProjectIssues(gitlab *gogitlab.Gitlab, projectId int) { page := 1 for { issues, err := gitlab.ProjectIssues(projectId, page) if err != nil { log.Fatal(err.Error()) return } if len(issues) == 0 { break } for _, issue := range issues { if issue.State == "closed" { color.Printf("@r[%4d(%d)] [%s] %s state=%s\n", issue.Id, issue.LocalId, issue.Title, issue.Description, issue.State) } else { color.Printf("@g[%4d(%d)] [%s] %s state=%s\n", issue.Id, issue.LocalId, issue.Title, issue.Description, issue.State) } } page++ } }
func AddLocations(zones map[string]*Zone, locations []string) { var added, modified int for _, z := range zones { s := NewSet(z.Locations...) n := len(s) s.Add(locations...) m := len(s) - n if m != 0 { z.Locations = s.Values() added += m modified++ } } color.Printf("@{.}Added %d locations(s) to %d zone(s)\n", added, modified) }