本文整理匯總了Golang中github.com/fatih/color.RedString函數的典型用法代碼示例。如果您正苦於以下問題:Golang RedString函數的具體用法?Golang RedString怎麽用?Golang RedString使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了RedString函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
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)
}
}
示例2: worker
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
}
示例3: Visit
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())))
}
}
}
}
}
}
}
示例4: testFiles
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)
}
}
示例5: main
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))
}
}
}
}
示例6: LoadFile
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)
}
}
示例7: SupervisorCommand
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
},
}
}
示例8: loadConfig
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."))
}
示例9: runPluginCommand
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")
}
}
}
示例10: reportHashDiffs
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])
}
}
}
示例11: TestErrorPrinter_Printing
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)
}
}
示例12: PrintAndExit
// 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)
}
示例13: FatalIfError
// FatalIfError logs the error, then exits 1
func FatalIfError(message string, err error) {
if err == nil {
return
}
log.Fatalln(color.RedString(message), err.Error())
}
示例14: Format
// 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
}
}
}
示例15: sendPeerRequest
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
}