func main() { var ui *termui.UI if runtime.GOOS == "windows" { ui = termui.New( os.Stdin, color.Output, nil, ) } else { ui = termui.New( os.Stdin, os.Stdout, nil, ) } switch { case version == "": ui.Println(color.RedString("Fissile was built incorrectly and its version string is empty.")) sigint.DefaultHandler.Exit(1) case version == "0": ui.Println(color.RedString("Fissile was built incorrectly and it doesn't have a proper version string.")) } f := app.NewFissileApplication(version, ui) if err := cmd.Execute(f, version); err != nil { ui.Println(color.RedString("%v", err)) sigint.DefaultHandler.Exit(1) } }
func (this *WorkerQueue) worker(death chan<- bool) { for work := range this.Input { contents, err := ioutil.ReadFile(work.File) if err != nil { fmt.Fprintln(os.Stderr, color.RedString(err.Error())) this.Group.Done() continue } newContents := strings.Replace(string(contents), work.From, work.To, -1) if newContents != string(contents) { err = ioutil.WriteFile(work.File, []byte(newContents), 0) if err != nil { fmt.Fprintln(os.Stderr, color.RedString(err.Error())) this.Group.Done() continue } this.Output.Console <- work.File } this.Group.Done() } death <- true }
func (fa *FairnessAnalysis) Visit(fn *ssa.Function) { visitedBlk := make(map[*ssa.BasicBlock]bool) fa.logger.Printf("Visiting: %s", fn.String()) for _, blk := range fn.Blocks { if _, visited := visitedBlk[blk]; !visited { visitedBlk[blk] = true fa.logger.Printf(" block %d %s", blk.Index, blk.Comment) // First consider blocks with loop initialisation blocks. if blk.Comment == "rangeindex.loop" { fa.total++ fa.logger.Println(color.GreenString("✓ range loops are fair")) } else if blk.Comment == "rangechan.loop" { fa.total++ hasClose := false for _, ch := range fa.info.FindChan(blk.Instrs[0].(*ssa.UnOp).X) { if ch.Type == ssabuilder.ChanClose { fa.logger.Println(color.GreenString("✓ found corresponding close() - channel range likely fair")) hasClose = true } } if !hasClose { fa.logger.Println(color.RedString("❌ range over channel w/o close() likely unfair (%s)", fa.info.FSet.Position(blk.Instrs[0].Pos()))) fa.unsafe++ } } else if blk.Comment == "for.loop" { fa.total++ if fa.isLikelyUnsafe(blk) { fa.logger.Println(color.RedString("❌ for.loop maybe bad")) fa.unsafe++ } else { fa.logger.Println(color.GreenString("✓ for.loop is ok")) } } else { // Normal blocks (or loops without initialisation blocks). if len(blk.Instrs) > 1 { if ifInst, ok := blk.Instrs[len(blk.Instrs)-1].(*ssa.If); ok { _, thenVisited := visitedBlk[ifInst.Block().Succs[0]] _, elseVisited := visitedBlk[ifInst.Block().Succs[1]] if thenVisited || elseVisited { // there is a loop! fa.total++ if !fa.isCondFair(ifInst.Cond) { fa.logger.Println(color.YellowString("Warning: recurring block condition probably unfair")) fa.unsafe++ } else { fa.logger.Println(color.GreenString("✓ recurring block is ok")) } } } else if jInst, ok := blk.Instrs[len(blk.Instrs)-1].(*ssa.Jump); ok { if _, visited := visitedBlk[jInst.Block().Succs[0]]; visited { fa.total++ fa.unsafe++ fa.logger.Println(color.RedString("❌ infinite loop or recurring block, probably bad (%s)", fa.info.FSet.Position(blk.Instrs[0].Pos()))) } } } } } } }
func testFiles(t *testing.T, files []string, loader *Loader) { var passing, total, schemaErrors int for _, file := range files { f, err := os.Open(file) if err != nil { t.Fatalf("Failed to open %q: %s", file, err) } v, err := json.Parse(f) f.Close() if err != nil { t.Fatalf("Failed to parse %q: %s", file, err) } tests, ok := v.(*json.Array) if !ok { t.Fatalf("Content of %q is not an array: %T", file, v) } for i, tt := range tests.Value { test, ok := tt.(*json.Object) if !ok { t.Fatalf("Test %d in %q is not an object", i, file) } t.Logf(color.BlueString("=====> Testing %s, case %d: %s", file, i, test.Find("description"))) schema := test.Find("schema") err := ValidateDraft04Schema(schema) if err != nil { t.Errorf(color.RedString("schema does not pass validation: %s", err)) schemaErrors++ } v, _ := NewValidator(schema, loader) // not checking the error since schema is already validated cases := test.Find("tests").(*json.Array) for _, c := range cases.Value { total++ case_ := c.(*json.Object) valid := case_.Find("valid").(*json.Bool).Value err := v.Validate(case_.Find("data")) switch { case err == nil && valid: passing++ t.Logf("%s %s", color.GreenString("PASSED"), case_.Find("description")) case err != nil && !valid: passing++ t.Logf("%s %s: %s", color.GreenString("PASSED"), case_.Find("description"), err) case err != nil && valid: t.Errorf("%s %s: %s", color.RedString("FAILED"), case_.Find("description"), err) case err == nil && !valid: t.Errorf("%s %s", color.RedString("FAILED"), case_.Find("description")) } } } } t.Logf("Passing %d out of %d tests (%g%%)", passing, total, float64(passing)/float64(total)*100) if schemaErrors > 0 { t.Logf("%d schemas failed validation", schemaErrors) } }
func main() { manifestFile := kingpin.Flag("manifest", "Path to manifest.yml file.").Default("manifest.yml").String() plugin := kingpin.Arg("plugin", "Plugin name for run.").String() vars := *kingpin.Flag("var", "key=value pairs with manifest vars.").StringMap() dryRun := kingpin.Flag("dry-run", "Show manifest section only").Bool() noColor := kingpin.Flag("no-color", "Disable colored output").Bool() pluginData := kingpin.Flag("plugin-data", "Data for plugin").String() kingpin.Version(version) kingpin.Parse() var plugins []manifest.PluginData var err error var manifestData *manifest.Manifest color.NoColor = *noColor if *pluginData != "" { manifestData = manifest.LoadJSON(*pluginData) } else { manifestData = manifest.Load(*manifestFile, vars) } if *plugin == "" && *dryRun { fmt.Printf("%s\n%s\n%s\n", color.GreenString(">>> manifest:"), manifestData.String(), color.GreenString("<<< manifest: OK\n")) return } if *pluginData != "" { plugins = []manifest.PluginData{manifestData.GetPluginWithData(*plugin)} } else { plugins, err = manifestData.FindPlugins(*plugin) } if err != nil { log.Fatalln(color.RedString("Error find plugins for '%s': %v", *plugin, err)) } for _, pair := range plugins { log.Printf("%s\n%s\n\n", color.GreenString(">>> %s:", pair.PluginName), color.CyanString("%s", pair.Data)) if !*dryRun { if err := pair.Plugin.Run(pair.Data); err != nil { fmt.Println("") log.Fatalln(color.RedString("Error on run plugin `%s`: %v", pair.PluginName, err)) } else { log.Println(color.GreenString("<<< %s: OK", pair.PluginName)) } } } }
func LoadFile(path string) (*gabs.Container, error) { data, err := ioutil.ReadFile(path) if err != nil { return nil, errors.New(color.RedString("Manifest file `%s` not found: %v", path, err)) } if jsonData, err := yaml.YAMLToJSON(data); err != nil { return nil, errors.New(color.RedString("Error on parse manifest %s: %v!", path, err)) } else { return gabs.ParseJSON(jsonData) } }
func SupervisorCommand() cli.Command { return cli.Command{ Name: "supervisor", SkipFlagParsing: true, Action: func(c *cli.Context) error { var cmd *exec.Cmd = nil go func() { backoff.Retry(func() error { log.Println(color.GreenString("supervisor: Starting %v", c.Args())) cmd = exec.Command(c.Args().First(), c.Args().Tail()...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Start(); err != nil { log.Println(color.RedString("supervisor: Error on process staring %v", err)) return err } err := cmd.Wait() if err != nil { log.Println(color.RedString("supervisor: Command exit with error: %v", err)) } else { log.Println(color.YellowString("supervisor: Command completed.")) os.Exit(0) } return err }, backoff.NewConstantBackOff(time.Second*3)) }() // Handle shutdown signals and kill child process ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) log.Println("supervisor: receive signal", <-ch) if cmd != nil { log.Println("supervisor: send SIGTERM to subprocess") cmd.Process.Signal(syscall.SIGTERM) res, err := cmd.Process.Wait() log.Println("supervisor: subprocess stopped with", res, err) } log.Println(color.YellowString("supervisor: Stopped.")) os.Exit(143) return nil }, } }
func loadConfig() { b, err := ioutil.ReadFile("config.json") if err != nil { log.Fatal(color.RedString("Couldn't load config.json data.")) } c := &config{} err = json.Unmarshal(b, c) if err != nil { log.Fatal(color.RedString("Couldn't unmarshal config.json data.")) } cfg = c log.Println(color.MagentaString("Loaded config.json file from disk.")) }
func runPluginCommand(command func(commandLine CommandLine) error) func(context *cli.Context) { return func(context *cli.Context) { cmd := &contextCommandLine{context} if err := command(cmd); err != nil { logger.Errorf("\n%s: ", color.RedString("Error")) logger.Errorf("%s %s\n\n", color.RedString("✗"), err) cmd.ShowHelp() os.Exit(1) } else { logger.Info("\nRestart grafana after installing plugins . <service grafana-server restart>\n\n") } } }
func (f *Fissile) reportHashDiffs(hashDiffs *HashDiffs) { if len(hashDiffs.DeletedKeys) > 0 { f.UI.Println(color.RedString("Dropped keys:")) sort.Strings(hashDiffs.DeletedKeys) for _, v := range hashDiffs.DeletedKeys { f.UI.Printf(" %s\n", v) } } if len(hashDiffs.AddedKeys) > 0 { f.UI.Println(color.GreenString("Added keys:")) sort.Strings(hashDiffs.AddedKeys) for _, v := range hashDiffs.AddedKeys { f.UI.Printf(" %s\n", v) } } if len(hashDiffs.ChangedValues) > 0 { f.UI.Println(color.BlueString("Changed values:")) sortedKeys := make([]string, len(hashDiffs.ChangedValues)) i := 0 for k := range hashDiffs.ChangedValues { sortedKeys[i] = k i++ } sort.Strings(sortedKeys) for _, k := range sortedKeys { v := hashDiffs.ChangedValues[k] f.UI.Printf(" %s: %s => %s\n", k, v[0], v[1]) } } }
func TestErrorPrinter_Printing(t *testing.T) { saveExitFunction := exitFunction defer func() { exitFunction = saveExitFunction }() exitCode := -1 exitFunction = func(code int) { exitCode = codeUnsupportedOSError } in, out := &bytes.Buffer{}, &bytes.Buffer{} ui := New(in, out, nil) printer := NewErrorPrinter(ui) err1 := UnsupportedOSError("windows") err2 := fmt.Errorf("Generic error") printer.PrintAndExit(err1) exp := color.RedString("Error (%d): Unsupported OS: windows", codeUnsupportedOSError) if got := strings.TrimSpace(out.String()); got != exp { t.Error("wrong error message:", got) } if exitCode != codeUnsupportedOSError { t.Error("wrong exit code:", exitCode) } out.Reset() printer.PrintWarning(err2) exp = color.YellowString("Warning (%d): Generic error", CodeUnknownError) if got := strings.TrimSpace(out.String()); got != exp { t.Error("wrong error message:", got) } }
// PrintAndExit prints the error to the ui and exits the program. func PrintAndExit(ui *UI, err error) { errCode := getErrorCode(err) errMsg := color.RedString("Error (%d): %s", errCode, err) ui.Println(errMsg) exitFunction(errCode) }
// FatalIfError logs the error, then exits 1 func FatalIfError(message string, err error) { if err == nil { return } log.Fatalln(color.RedString(message), err.Error()) }
// Format formats the log message. func (f Custom) Format(msg *gol.LogMessage) (string, error) { lmsg := msg.FieldLength() buffer := make([]string, lmsg, lmsg) i := 0 for k, v := range *msg { if k != fields.Severity && k != fields.Timestamp { buffer[i] = fmt.Sprintf("%s:'%s'", k, v) i += 1 } } t, _ := msg.Timestamp() if severity, err := msg.Severity(); err != nil { return fmt.Sprintf("%s UNKNOWN %s\n", t.String(), strings.Join(buffer, " ")), nil } else { switch severity >= field_severity.Error { case true: return fmt.Sprintf("%s %s %s\n", t.String(), color.RedString("%s", severity), strings.Join(buffer, " ")), nil default: return fmt.Sprintf("%s %s %s\n", t.String(), severity, strings.Join(buffer, " ")), nil } } }
func (s *Server) sendPeerRequest(conn *Conn) error { msg := &protocol.Message{Message: &protocol.Message_PeerRequest{ PeerRequest: &protocol.PeerRequest{ //Keyspace: s.LocalPeer().Keyspace, }}} conn.peerRequest = make(chan bool, 1) timeout := make(chan bool, 1) go func() { time.Sleep(10 * time.Second) timeout <- true }() go func() { select { case <-conn.peerRequest: case <-timeout: msg := color.RedString("Peer timed out! %s %+v", conn.PrettyID(), conn) conn.peerRequestRetries++ if conn.peerRequestRetries >= 3 { s.peersLock.Lock() delete(s.Peers, conn.Peer.Id) s.peersLock.Unlock() conn.Close() } else { msg += "Retrying..." s.sendPeerRequest(conn) } s.Printf(msg) } }() if err := conn.Send(msg); err != nil { return err } return nil }
func failColor(format string, args ...interface{}) string { if *flag_color { return color.RedString(format, args...) } else { return fmt.Sprintf(format, args...) } }
func (fs *fsSort) sortAllFiles() error { fs.verbf("sorting files...") //perform sort if fs.DryRun { log.Println(color.CyanString("[Dryrun]")) } //sort concurrency-many files at a time, //wait for all to complete and show errors queue := make(chan bool, fs.Concurrency) wg := &sync.WaitGroup{} sortFile := func(file *fileSort) { if err := fs.sortFile(file); err != nil { log.Printf("[#%d/%d] %s\n └─> %s\n", file.id, len(fs.sorts), color.RedString(file.path), err) } <-queue wg.Done() } for _, file := range fs.sorts { wg.Add(1) queue <- true go sortFile(file) } wg.Wait() return nil }
func (s *Server) sendPeerRequest(conn *Conn) error { msg := &protocol.Message{Message: &protocol.Message_PeerRequest{ PeerRequest: &protocol.PeerRequest{ Limit: -1, //Keyspace: s.LocalPeer().Keyspace, }}} conn.peerRequest = make(chan bool, 1) timeout := make(chan bool, 1) go func() { time.Sleep(10 * time.Second) timeout <- true }() go func() { select { case <-conn.peerRequest: case <-timeout: id := conn.Peer.Id s.Printf(color.RedString("Peer timed out! %s %+v", conn.PrettyID(), conn)) delete(s.Peers, id) conn.Close() } }() if err := conn.Send(msg); err != nil { return err } return nil }
func main() { app := cli.NewApp() app.Name = "serve-tools" app.Version = version app.Usage = "Serve tools" app.Commands = []cli.Command{ { Name: "consul", Subcommands: []cli.Command{ consul.SupervisorCommand(), consul.NginxTemplateContextCommand(), consul.RouteCommand(), consul.KvPatchCommand(), consul.DeregisterCommand(), { Name: "kv", Subcommands: []cli.Command{ consul.KvPatchCommand(), consul.KvRenameCommand(), }, }, }, }, supervisor.SupervisorCommand(), testrunner.TestRunnerCommand(), } if err := app.Run(os.Args); err != nil { log.Fatalln(color.RedString("Exit: %v", err)) } }
func (rl *ResponseLogWriter) logCode(code int, status string) { var codestr string switch { case code >= 200 && code < 300: codestr = color.GreenString("%d %s", code, status) case code >= 300 && code < 400: codestr = color.BlueString("%d %s", code, status) case code >= 400 && code < 500: codestr = color.YellowString("%d %s", code, status) case code >= 500 && code < 600: codestr = color.RedString("%d %s", code, status) default: codestr = fmt.Sprintf("%d %s", code, status) } cl := rl.Header().Get("content-length") if cl != "" { cli, err := strconv.Atoi(cl) if err != nil { cl = "invalid content length header" } else { cl = fmt.Sprintf("%s", humanize.Bytes(uint64(cli))) } } rl.Log.Say("<- %s %s", codestr, cl) }
func main() { l := termlog.NewLog() testpatt(l) g := l.Group() g.Say("This is a group...") testpatt(g) g.Done() g = l.Group() g.Say("Here are some composed colours...") g.Say( "%s %s %s", color.RedString("red"), color.GreenString("green"), color.BlueString("blue"), ) g.Done() l.Enable("demo") g = l.Group() g.SayAs("disabled", "These don't show...") g.SayAs("demo", "Some named log entries...") g.SayAs("demo", "This is a test") g.SayAs("disabled", "This is a test") g.Done() g = l.Group() g.Say("Disabled colour output...") l.NoColor() testpatt(g) g.Done() }
func (r *pluginRegestry) Get(name string) Plugin { p, ok := r.plugins[name] if !ok { log.Fatalf(color.RedString("Plugin '%s' doesn't exist!", name)) } return p }
func perr(fstr string, args ...interface{}) { if !strings.HasSuffix(fstr, "\n") { fstr += "\n" } args = append([]interface{}{color.RedString("ERROR:")}, args...) fmt.Printf("%s "+fstr, args...) }
func printError(err error) { if err != nil { output := color.RedString("%s\n", err.Error()) os.Stderr.WriteString(output) } }
func (s *StdOutLogger) Error(message string, err error) { var str string if runtime.GOOS == "windows" { str = fmt.Sprintf("%s %s Error: %v", s.errPrefix, message, err) } else { str = fmt.Sprintf("%s", color.RedString("%s %s Error: %v", s.errPrefix, message, err)) } fmt.Printf("%s\n", str) }
func exitIf(err error) { if err == nil { return } fmt.Println(color.RedString("ERROR:"), err, emoji.Sprint(":fire:")) os.Exit(1) }
func isPushed(remote string, err error) { if err == nil { fmt.Printf("\t%s: %s\n", remote, color.GreenString("OK")) return } fmt.Printf("\t%s: %s\n", remote, color.RedString("NG")) }
func (a Samidare) Do() error { fmt.Fprintf(color.Output, "TestName : %s \n", color.GreenString("%s", a.Name)) for idx, testCase := range a.GetTestCases() { fmt.Fprintf(color.Output, "TestCaseName: [%d] %s\n", idx+1, color.GreenString("%s", testCase.Name)) req, err := testCase.Request.BuildRequest() if err != nil { fmt.Fprintf(color.Output, "%s\n", color.RedString("%s", err.Error())) continue } resp, err := a.client.Do(req) if err != nil { fmt.Fprintf(color.Output, "%s\n", color.RedString("%s", err.Error())) continue } if resp.StatusCode != testCase.Response.Status { fmt.Fprintf(color.Output, "NG status: %s\n", color.RedString("%d != %d", resp.StatusCode, testCase.Response.Status)) } else { fmt.Fprintf(color.Output, "OK status: %s\n", color.BlueString("%d == %d", resp.StatusCode, testCase.Response.Status)) } for k, v := range testCase.Response.Headers { if resp.Header[k][0] != fmt.Sprintf("%v", v) { fmt.Fprintf(color.Output, "OK %s: %s\n", k, color.RedString("%v != %v", resp.Header[k][0], v)) } else { fmt.Fprintf(color.Output, "OK %s: %s\n", k, color.BlueString("%v == %v", resp.Header[k][0], v)) } } data, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { log.Println(err) } else { // TODO: Option // fmt.Println(string(data)) _ = data } } return nil }
func (c container) updateCache(hash string, body string, backendURL string, async bool) (string, error) { var response string var err error if c.lockUpdate(hash) == false { if async == true { log.Debug(fmt.Sprintf("%s %s", hash, color.RedString("LOCKED"))) return response, err } } redisConn := c.pool.Get() defer redisConn.Close() log.Debug("%s %s", hash, color.BlueString("UPDATE")) httpClient := http.Client{Timeout: time.Duration(600 * time.Second)} resp, httperror := httpClient.Post(backendURL, "application/JSON", strings.NewReader(body)) if httperror == nil { if resp.StatusCode != 200 { log.Error(fmt.Sprintf("Backend error code: %v ", resp.StatusCode)) return response, err } requestBody, err := ioutil.ReadAll(resp.Body) if err != nil { log.Error(fmt.Sprintf("body read failed: %s : %s", hash, err.Error())) } response = string(requestBody) if response != "" { _, err = redisConn.Do("SET", hash, string(requestBody)) if err != nil { log.Error(fmt.Sprintf("key set failed: %s : %s", hash, err.Error())) return response, err } log.Debug(fmt.Sprintf("%s %s", hash, color.GreenString("SET"))) _, err = redisConn.Do("EXPIRE", hash, config.expire) if err != nil { log.Error(fmt.Sprintf("key expire set failed: %s : %s", hash, err.Error())) return response, err } } else { log.Error("Empty backend response") fmt.Println(resp) } } else { log.Error(fmt.Sprintf("Backend request failure: %s", httperror.Error())) } c.unlockUpdate(hash) return response, err }
func (app *App) Interactive() { rl, err := readline.NewEx(&readline.Config{ Prompt: color.BlueString("say » "), HistoryFile: app.Config.HistoryFile, }) if err != nil { log.Fatal(err) } defer rl.Close() app.Log.SetOutput(rl.Stderr()) log.SetOutput(rl.Stderr()) color.Output = ansicolor.NewAnsiColorWriter(rl.Stderr()) pings := make(map[string]time.Time) // Subscribe to all replies and print them to stdout app.Client.Subscribe("", "self", func(msg sarif.Message) { text := msg.Text if text == "" { text = msg.Action + " from " + msg.Source } if msg.IsAction("err") { text = color.RedString(text) } if sent, ok := pings[msg.CorrId]; ok { text += color.YellowString("[%.1fms]", time.Since(sent).Seconds()*1e3) } log.Println(color.GreenString(" « ") + strings.Replace(text, "\n", "\n ", -1)) }) // Interactive mode sends all lines from stdin. for { line, err := rl.Readline() if err != nil { if err == io.EOF { return } log.Fatal(err) } if len(line) == 0 { continue } // Publish natural message msg := sarif.Message{ Id: sarif.GenerateId(), Action: "natural/handle", Text: line, } if *profile { pings[msg.Id] = time.Now() } app.Client.Publish(msg) } }