本文整理匯總了Golang中github.com/fatih/color.Red函數的典型用法代碼示例。如果您正苦於以下問題:Golang Red函數的具體用法?Golang Red怎麽用?Golang Red使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Red函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestAnchorMerger
func TestAnchorMerger(t *testing.T) {
color.NoColor = false
in := []byte(`---
vars: &v
env: qa
deploy:
env: live`)
expect := `{"deploy":{"env":"live"},"vars":{"env":"qa"}}`
if err := ioutil.WriteFile("/tmp/test", in, 0644); err != nil {
color.Red("Error file not create")
t.Error("Error file not create")
t.Fail()
}
defer os.Remove("/tmp/test")
if g, err := LoadFile("/tmp/test"); err != nil {
color.Red("%v\n", err)
t.Error(err)
t.Fail()
} else {
if g.String() == expect {
color.Green("\n%s: OK\n", "FileLoad")
} else {
color.Red("%s != %s", g.String(), expect)
t.Error(fmt.Errorf("%s != %s", g.String(), expect))
t.Fail()
}
}
}
示例2: getClientCredentials
func getClientCredentials(c *cli.Context) []string {
credentials := []string{c.GlobalString("client-id"), c.GlobalString("client-secret")}
if credentials[0] == "" || credentials[1] == "" {
color.Yellow("No client credentials given. Fallback to builtin default...")
color.Yellow("Keep in mind that your document might be visible to other users.")
color.Yellow("Your unique user-id is the only secret to protect your data.\n\n")
superSecretSecret := []byte("V;4nJvuANmoywKNYk.yewNhqwmAQctc3BvByxeozQVpiK")
// Decode HEX default credentials
credentialsBytes, err := hex.DecodeString(defaultClientCredentials)
if err != nil {
color.Red("Error: client-id and client-secret missing and fallback decoding (step 1) failed: %s\n\n", err)
cli.ShowCommandHelp(c, c.Command.FullName())
os.Exit(1)
}
decodedCredentials := strings.Split(string(xorBytes(credentialsBytes, superSecretSecret)), ":")
if len(decodedCredentials) < 2 {
color.Red("Error: client-id and client-secret missing and fallback decoding (step 2) failed: %s\n\n", err)
cli.ShowCommandHelp(c, c.Command.FullName())
os.Exit(1)
}
credentials = decodedCredentials
}
return credentials
}
示例3: Build
// Build listens watch events from Watcher and sends messages to Runner
// when new changes are built.
func (b *Builder) Build(p *Params) {
go b.registerSignalHandler()
go func() {
b.watcher.update <- true
}()
for <-b.watcher.Wait() {
fileName := p.createBinaryName()
pkg := p.GetPackage()
color.Cyan("Building %s...\n", pkg)
// build package
cmd, err := runCommand("go", "build", "-o", fileName, pkg)
if err != nil {
log.Fatalf("Could not run 'go build' command: %s", err)
continue
}
if err := cmd.Wait(); err != nil {
if err := interpretError(err); err != nil {
color.Red("An error occurred while building: %s", err)
} else {
color.Red("A build error occurred. Please update your code...")
}
continue
}
// and start the new process
b.runner.restart(fileName)
}
}
示例4: runAllProcessorTests
func runAllProcessorTests(t *testing.T, cases map[string]processorTestCase) {
color.NoColor = false
json := `{
"var1": "var1",
"var-var": "var-var",
"var": {"var": "1"},
"version": "{{ feature }}-{{ feature-suffix }}",
"feature": "value-unknown",
"feature-suffix": "{{ feature }}",
"list": [1, 2, 3]
}`
tree, err := gabs.ParseJSON([]byte(json))
if err != nil {
color.Red("%v: failed!\n", err)
t.Fail()
}
for name, test := range cases {
if res, err := Template(test.in, tree); err == nil {
if test.expect == res {
color.Green("%v: Ok\n", name)
} else {
color.Red("%v: %v != %v: failed!\n", name, test.expect, res)
t.Fail()
}
} else {
color.Red("error %v\n: failed!", err)
t.Fail()
}
}
}
示例5: Run
func (n *Notifier) Run(message string) {
switch n.Name {
case "slack":
if slack_api == nil {
color.Red("[!] Slack used as a notifier, but not configured with ENV vars.")
return
}
err = slack_api.ChatPostMessage(slack_channel.Id, message, &slack.ChatPostMessageOpt{IconEmoji: ":fire:"})
if err != nil {
color.Red(fmt.Sprintf("[!] Error posting to Slack: %s", err))
}
case "hipchat":
if hipchat_api == nil {
color.Red("[!] HipChat used as a notifier, but not configured with ENV vars.")
return
}
_, err = hipchat_api.Room.Notification(os.Getenv("HIPCHAT_ROOM_ID"), &hipchat.NotificationRequest{Message: "Testing", Color: "red"})
if err != nil {
color.Red(fmt.Sprintf("[!] Error posting to HipChat: %s", err))
}
case n.Name: // default
color.Yellow(fmt.Sprintf("[>] Unknown notifier: %s", n.Name))
}
}
示例6: variables
func variables(v *vaulted.Vault) {
exit := false
for exit == false {
printVariables(v)
input := readMenu("\nEdit environment variables: [a,D,?,b]: ")
switch input {
case "a":
variableKey := readValue("Name: ")
variableValue := readValue("Value: ")
if v.Vars == nil {
v.Vars = make(map[string]string)
}
v.Vars[variableKey] = variableValue
case "D":
variable := readValue("Variable name: ")
_, ok := v.Vars[variable]
if ok {
delete(v.Vars, variable)
} else {
color.Red("Variable '%s' not found", variable)
}
case "b":
exit = true
case "?", "help":
variableMenu()
default:
color.Red("Command not recognized")
}
}
}
示例7: sshKeysMenu
func sshKeysMenu(v *vaulted.Vault) {
exit := false
for exit == false {
printSSHKeys(v)
input := readMenu("\nEdit ssh keys: [a,D,?,b]: ")
switch input {
case "a":
addSSHKey(v)
case "D":
key := readValue("Key: ")
_, ok := v.SSHKeys[key]
if ok {
delete(v.SSHKeys, key)
} else {
color.Red("Key '%s' not found", key)
}
case "b":
exit = true
case "?", "help":
sshKeysHelp()
default:
color.Red("Command not recognized")
}
}
}
示例8: Output
func (r Documentation) Output(results <-chan []resource.TestResult) (hasFail bool) {
testCount := 0
var failed []resource.TestResult
for resultGroup := range results {
for _, testResult := range resultGroup {
if testResult.Successful {
fmt.Println(humanizeResult(testResult))
testCount++
} else {
fmt.Println(humanizeResult(testResult))
failed = append(failed, testResult)
testCount++
}
}
fmt.Println("")
}
fmt.Print("\n")
if len(failed) > 0 {
color.Red("Failures:")
for _, testResult := range failed {
fmt.Println(humanizeResult(testResult))
}
fmt.Print("\n")
}
if len(failed) > 0 {
color.Red("Count: %d failed: %d\n", testCount, len(failed))
return true
}
color.Green("Count: %d failed: %d\n", testCount, len(failed))
return false
}
示例9: getOpts
func getOpts(context *cli.Context) (string, string, string, string, string) {
etcdURI := context.String("etcd-uri")
redisURI := context.String("redis-uri")
redisQueue := context.String("redis-queue")
deployStateUri := context.String("deploy-state-uri")
cluster := context.String("cluster")
if etcdURI == "" || redisURI == "" || redisQueue == "" || deployStateUri == "" || cluster == "" {
cli.ShowAppHelp(context)
if etcdURI == "" {
color.Red(" Missing required flag --etcd-uri or GOVERNATOR_ETCD_URI")
}
if redisURI == "" {
color.Red(" Missing required flag --redis-uri or GOVERNATOR_REDIS_URI")
}
if redisQueue == "" {
color.Red(" Missing required flag --redis-queue or GOVERNATOR_REDIS_QUEUE")
}
if deployStateUri == "" {
color.Red(" Missing required flag --deploy-state-uri or DEPLOY_STATE_URI")
}
if cluster == "" {
color.Red(" Missing required flag --cluster or CLUSTER")
}
os.Exit(1)
}
return etcdURI, redisURI, redisQueue, deployStateUri, cluster
}
示例10: Validate
func Validate(c *cli.Context, startTime time.Time) {
gossConfig := getGossConfig(c)
sys := system.New(c)
outputer := getOutputer(c)
sleep := c.Duration("sleep")
retryTimeout := c.Duration("retry-timeout")
i := 1
for {
iStartTime := time.Now()
out := validate(sys, gossConfig, c.Int("max-concurrent"))
exitCode := outputer.Output(os.Stdout, out, iStartTime)
if retryTimeout == 0 || exitCode == 0 {
os.Exit(exitCode)
}
elapsed := time.Since(startTime)
if elapsed+sleep > retryTimeout {
color.Red("\nERROR: Timeout of %s reached before tests entered a passing state", retryTimeout)
os.Exit(3)
}
color.Red("Retrying in %s (elapsed/timeout time: %.3fs/%s)\n\n\n", sleep, elapsed.Seconds(), retryTimeout)
// Reset cache
sys = system.New(c)
time.Sleep(sleep)
i++
fmt.Printf("Attempt #%d:\n", i)
}
}
示例11: init
func init() {
// Verifies the existance of an anirip folder in our temp directory
_, err := os.Stat(tempDir)
if err != nil {
os.Mkdir(tempDir, 0777)
}
// Checks for the existance of our AdobeHDS script which we will get if we don't have it
_, err = os.Stat(tempDir + string(os.PathSeparator) + "AdobeHDS.php")
if err != nil {
adobeHDSResp, err := anirip.GetHTTPResponse("GET", "https://raw.githubusercontent.com/K-S-V/Scripts/master/AdobeHDS.php", nil, nil, nil)
if err != nil {
color.Red("[anirip] There was an error retrieving AdobeHDS.php script from GitHub...")
return
}
defer adobeHDSResp.Body.Close()
adobeHDSBody, err := ioutil.ReadAll(adobeHDSResp.Body)
if err != nil {
color.Red("[anirip] There was an error reading the AdobeHDS.php body...")
return
}
err = ioutil.WriteFile(tempDir+string(os.PathSeparator)+"AdobeHDS.php", adobeHDSBody, 0777)
if err != nil {
color.Red("[anirip] There was an error writing AdobeHDS.php to file...")
return
}
}
}
示例12: main
func main() {
flag.Usage = usageExit
flag.Parse()
if *fversion {
fmt.Printf("Stash: Version - %s\n", Version)
return
}
log.SetFlags(0)
log.SetPrefix("DEBUG: ")
args := flag.Args()
if len(args) < 1 {
usageExit()
}
switch args[0] {
case "help":
help(args[1:])
return
case "destination", "dest":
runCmd(subcmd.Destination, args[1:])
return
case "folder", "fold":
runCmd(subcmd.Folder, args[1:])
return
case "daemon", "daem":
runCmd(subcmd.Daemon, args[1:])
return
}
color.Red("stash: unknown subcommand %q\n", args[0])
color.Red("Run 'stash help' for usage.\n")
os.Exit(2)
}
示例13: Output
func (r Rspecish) Output(results <-chan []resource.TestResult, startTime time.Time) (exitCode int) {
testCount := 0
var failed []resource.TestResult
for resultGroup := range results {
for _, testResult := range resultGroup {
if testResult.Successful {
fmt.Printf(green("."))
} else {
fmt.Printf(red("F"))
failed = append(failed, testResult)
}
testCount++
}
}
fmt.Print("\n\n")
if len(failed) > 0 {
color.Red("Failures:")
for _, testResult := range failed {
fmt.Println(humanizeResult(testResult))
}
fmt.Print("\n")
}
fmt.Printf("Total Duration: %.3fs\n", time.Since(startTime).Seconds())
if len(failed) > 0 {
color.Red("Count: %d, Failed: %d\n", testCount, len(failed))
return 1
}
color.Green("Count: %d, Failed: %d\n", testCount, len(failed))
return 0
}
示例14: CopyFile
func CopyFile(conn *ssh.Client, FileName, DirectoryPath string) bool {
defer conn.Close()
if !strings.HasSuffix(DirectoryPath, "/") {
DirectoryPath = DirectoryPath + "/"
}
con, err := sftp.NewClient(conn, sftp.MaxPacket(5e9))
if err != nil {
color.Red("%s傳輸文件新建會話錯誤: %s\n", conn.RemoteAddr(), err)
return false
}
sFile, _ := os.Open(FileName)
defer sFile.Close()
dFile := DirectoryPath + FileName
fmt.Printf("%s 目標路徑:%s\n", conn.RemoteAddr(), dFile)
File, err := con.OpenFile(dFile, os.O_CREATE|os.O_TRUNC|os.O_RDWR)
if err != nil {
color.Red("%s 創建文件%s錯誤: %s \n", conn.RemoteAddr(), dFile, err)
return false
}
defer File.Close()
for {
buf := make([]byte, 1024)
n, err := sFile.Read(buf)
if err != nil {
if err.Error() == "EOF" {
break
}
return false
}
File.Write(buf[:n])
}
Result <- fmt.Sprintf("上傳%s到%s成功.\n", FileName, conn.RemoteAddr())
return true
}
示例15: copyfile
func copyfile() {
color.Yellow("開始執行文件發送:")
info, err := os.Lstat(all_ssh.ArgsInfo.File)
if err != nil || info.IsDir() {
color.Blue("檢查要發送的文件.")
return
}
for _, v := range all_ssh.ServerList {
go func() {
client := all_ssh.Connection(v)
if client != nil {
all_ssh.CopyFile(client, all_ssh.ArgsInfo.File, all_ssh.ArgsInfo.Dir)
}
}()
}
var num int
var Over chan os.Signal = make(chan os.Signal, 1)
go signal.Notify(Over, os.Interrupt, os.Kill)
go result(&num, Over)
<-Over
color.Yellow("一共有%d條錯誤.\n", len(all_ssh.ErrorList))
for _, v := range all_ssh.ErrorList {
color.Red(v)
}
color.Red("收到結果:%d條\n", num)
}