本文整理匯總了Golang中github.com/fatih/color.GreenString函數的典型用法代碼示例。如果您正苦於以下問題:Golang GreenString函數的具體用法?Golang GreenString怎麽用?Golang GreenString使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了GreenString函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ShowBaseImage
// ShowBaseImage will show details about the base BOSH images
func (f *Fissile) ShowBaseImage(repository string) error {
dockerManager, err := docker.NewImageManager()
if err != nil {
return fmt.Errorf("Error connecting to docker: %s", err.Error())
}
comp, err := compilator.NewCompilator(dockerManager, "", "", repository, compilation.UbuntuBase, f.Version, false, f.UI)
if err != nil {
return fmt.Errorf("Error creating a new compilator: %s", err.Error())
}
image, err := dockerManager.FindImage(comp.BaseImageName())
if err != nil {
return fmt.Errorf("Error looking up base image %s: %s", comp.BaseImageName(), err.Error())
}
f.UI.Printf("\nCompilation Layer: %s\n", color.GreenString(comp.BaseImageName()))
f.UI.Printf("ID: %s\n", color.GreenString(image.ID))
f.UI.Printf("Virtual Size: %sMB\n", color.YellowString("%.2f", float64(image.VirtualSize)/(1024*1024)))
baseImageName := builder.GetBaseImageName(repository, f.Version)
image, err = dockerManager.FindImage(baseImageName)
f.UI.Printf("\nStemcell Layer: %s\n", color.GreenString(baseImageName))
f.UI.Printf("ID: %s\n", color.GreenString(image.ID))
f.UI.Printf("Virtual Size: %sMB\n", color.YellowString("%.2f", float64(image.VirtualSize)/(1024*1024)))
return nil
}
示例2: 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())))
}
}
}
}
}
}
}
示例3: 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)
}
}
示例4: GenerateBaseDockerImage
// GenerateBaseDockerImage generates a base docker image to be used as a FROM for role images
func (f *Fissile) GenerateBaseDockerImage(targetPath, baseImage, metricsPath string, noBuild bool, repository string) error {
if metricsPath != "" {
stampy.Stamp(metricsPath, "fissile", "create-role-base", "start")
defer stampy.Stamp(metricsPath, "fissile", "create-role-base", "done")
}
dockerManager, err := docker.NewImageManager()
if err != nil {
return fmt.Errorf("Error connecting to docker: %s", err.Error())
}
baseImageName := builder.GetBaseImageName(repository, f.Version)
image, err := dockerManager.FindImage(baseImageName)
if err == docker.ErrImageNotFound {
f.UI.Println("Image doesn't exist, it will be created ...")
} else if err != nil {
return fmt.Errorf("Error looking up image: %s", err.Error())
} else {
f.UI.Println(color.GreenString(
"Base role image %s with ID %s already exists. Doing nothing.",
color.YellowString(baseImageName),
color.YellowString(image.ID),
))
return nil
}
if !strings.HasSuffix(targetPath, string(os.PathSeparator)) {
targetPath = fmt.Sprintf("%s%c", targetPath, os.PathSeparator)
}
baseImageBuilder := builder.NewBaseImageBuilder(baseImage)
if noBuild {
f.UI.Println("Skipping image build because of flag.")
return nil
}
f.UI.Println("Building base docker image ...")
log := new(bytes.Buffer)
stdoutWriter := docker.NewFormattingWriter(
log,
docker.ColoredBuildStringFunc(baseImageName),
)
tarPopulator := baseImageBuilder.NewDockerPopulator()
err = dockerManager.BuildImageFromCallback(baseImageName, stdoutWriter, tarPopulator)
if err != nil {
log.WriteTo(f.UI)
return fmt.Errorf("Error building base image: %s", err)
}
f.UI.Println(color.GreenString("Done."))
return nil
}
示例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: NickListString
func (channel *Channel) NickListString(v *gocui.View) {
sort.Sort(NickSorter(channel.Users))
fmt.Fprintf(v, "\n%s", color.GreenString("== NICK LIST START\n"))
for i, u := range channel.Users {
if i == len(channel.Users)-1 {
fmt.Fprintf(v, "%s%s", u.Mode, u.Nick)
} else {
fmt.Fprintf(v, "%s%s, ", u.Mode, u.Nick)
}
}
fmt.Fprintf(v, "\n%s", color.GreenString("== NICK LIST END\n\n"))
}
示例7: checkOutdatedPackages
func checkOutdatedPackages(b *BunchFile) error {
err := setVendorEnv()
if err != nil {
return errors.Trace(err)
}
for _, pack := range b.Packages {
if pack.IsSelf {
continue
}
fmt.Printf("package %s ... ", pack.Repo)
err := fetchPackage(pack.Repo)
if err != nil {
return errors.Trace(err)
}
needsUpdate, recency, err := checkPackageRecency(pack)
if err != nil {
return errors.Trace(err)
}
if !needsUpdate {
if recency.UpstreamDiffCount == 0 {
fmt.Printf("\rpackage %s ... %s\n", pack.Repo, color.GreenString("up to date"))
} else {
if pack.LockedVersion == "" {
fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.YellowString("behind upstream"), commitsPlural(recency.UpstreamDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestUpstreamCommit))
} else {
fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.YellowString("locked, but behind upstream"), commitsPlural(recency.UpstreamDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestUpstreamCommit))
}
}
} else {
if recency.InstalledDiffCount == 0 {
fmt.Printf("\rpackage %s ... %s\n", pack.Repo, color.GreenString("up to date"))
} else {
if pack.LockedVersion == "" {
fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.RedString("outdated"), commitsPlural(recency.InstalledDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestCommit))
} else {
fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.YellowString("locked, but outdated"), commitsPlural(recency.InstalledDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestCommit))
}
}
}
}
return nil
}
示例8: main
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()
}
示例9: Test_Format
func Test_Format(t *testing.T) {
bar := New(5000).Format(strings.Join([]string{
color.GreenString("["),
color.New(color.BgGreen).SprintFunc()("o"),
color.New(color.BgHiGreen).SprintFunc()("o"),
color.New(color.BgRed).SprintFunc()("o"),
color.GreenString("]"),
}, "\x00"))
w := colorable.NewColorableStdout()
bar.Callback = func(out string) {
w.Write([]byte(out))
}
bar.Add(2000)
bar.Finish()
bar.Finish()
}
示例10: CreateBaseCompilationImage
// CreateBaseCompilationImage will recompile the base BOSH image for a release
func (f *Fissile) CreateBaseCompilationImage(baseImageName, repository, metricsPath string, keepContainer bool) error {
if metricsPath != "" {
stampy.Stamp(metricsPath, "fissile", "create-compilation-image", "start")
defer stampy.Stamp(metricsPath, "fissile", "create-compilation-image", "done")
}
dockerManager, err := docker.NewImageManager()
if err != nil {
return fmt.Errorf("Error connecting to docker: %s", err.Error())
}
baseImage, err := dockerManager.FindImage(baseImageName)
if err != nil {
return fmt.Errorf("Error looking up base image %s: %s", baseImageName, err)
}
f.UI.Println(color.GreenString("Base image with ID %s found", color.YellowString(baseImage.ID)))
comp, err := compilator.NewCompilator(dockerManager, "", "", repository, compilation.UbuntuBase, f.Version, keepContainer, f.UI)
if err != nil {
return fmt.Errorf("Error creating a new compilator: %s", err.Error())
}
if _, err := comp.CreateCompilationBase(baseImageName); err != nil {
return fmt.Errorf("Error creating compilation base image: %s", err.Error())
}
return nil
}
示例11: resetPasswordCommand
func resetPasswordCommand(c CommandLine) error {
newPassword := c.Args().First()
password := models.Password(newPassword)
if password.IsWeak() {
return fmt.Errorf("New password is too short")
}
userQuery := models.GetUserByIdQuery{Id: AdminUserId}
if err := bus.Dispatch(&userQuery); err != nil {
return fmt.Errorf("Could not read user from database. Error: %v", err)
}
passwordHashed := util.EncodePassword(newPassword, userQuery.Result.Salt)
cmd := models.ChangeUserPasswordCommand{
UserId: AdminUserId,
NewPassword: passwordHashed,
}
if err := bus.Dispatch(&cmd); err != nil {
return fmt.Errorf("Failed to update user password")
}
logger.Infof("\n")
logger.Infof("Admin password changed successfully %s", color.GreenString("✔"))
return nil
}
示例12: printProject
func printProject(project *Project, depth int, buffer *bytes.Buffer, noColor bool, showpath bool) {
color.NoColor = noColor
buffer.WriteString(strings.Repeat(" ", depth))
buffer.WriteString(color.GreenString(project.ArtifactID))
buffer.WriteString(" (")
buffer.WriteString(project.Version)
buffer.WriteString(")")
if project.MismatchParentVersion != "" {
buffer.WriteString(color.YellowString(" Warning: looking for parent version: "))
buffer.WriteString(project.MismatchParentVersion)
} else if project.MissingParent != "" {
buffer.WriteString(color.YellowString(" Warning: parent not found: "))
buffer.WriteString(project.MissingParent)
}
if showpath {
buffer.WriteString(color.CyanString(" " + project.FullPath))
}
buffer.WriteString("\n")
sort.Sort(project.Children)
for _, child := range project.Children {
printProject(child, depth+1, buffer, noColor, showpath)
}
}
示例13: 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])
}
}
}
示例14: okColor
func okColor(format string, args ...interface{}) string {
if *flag_color {
return color.GreenString(format, args...)
} else {
return fmt.Sprintf(format, args...)
}
}
示例15: logCode
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)
}