本文整理匯總了Golang中github.com/fatih/color.YellowString函數的典型用法代碼示例。如果您正苦於以下問題:Golang YellowString函數的具體用法?Golang YellowString怎麽用?Golang YellowString使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了YellowString函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Run
func (j roleBuildJob) Run() {
select {
case <-j.abort:
j.resultsCh <- nil
return
default:
}
roleImageName := GetRoleDevImageName(j.repository, j.role, j.role.GetRoleDevVersion())
if !j.force {
if hasImage, err := j.dockerManager.HasImage(roleImageName); err != nil {
j.resultsCh <- err
return
} else if hasImage {
j.ui.Printf("Skipping build of role image %s because it exists\n", color.YellowString(j.role.Name))
j.resultsCh <- nil
return
}
}
if j.builder.metricsPath != "" {
seriesName := fmt.Sprintf("create-role-images::%s", roleImageName)
stampy.Stamp(j.builder.metricsPath, "fissile", seriesName, "start")
defer stampy.Stamp(j.builder.metricsPath, "fissile", seriesName, "done")
}
j.ui.Printf("Creating Dockerfile for role %s ...\n", color.YellowString(j.role.Name))
dockerfileDir, err := j.builder.CreateDockerfileDir(j.role, j.baseImageName)
if err != nil {
j.resultsCh <- fmt.Errorf("Error creating Dockerfile and/or assets for role %s: %s", j.role.Name, err.Error())
return
}
if j.noBuild {
j.ui.Printf("Skipping build of role image %s because of flag\n", color.YellowString(j.role.Name))
j.resultsCh <- nil
return
}
if !strings.HasSuffix(dockerfileDir, string(os.PathSeparator)) {
dockerfileDir = fmt.Sprintf("%s%c", dockerfileDir, os.PathSeparator)
}
j.ui.Printf("Building docker image of %s in %s ...\n", color.YellowString(j.role.Name), color.YellowString(dockerfileDir))
log := new(bytes.Buffer)
stdoutWriter := docker.NewFormattingWriter(
log,
docker.ColoredBuildStringFunc(roleImageName),
)
err = j.dockerManager.BuildImage(dockerfileDir, roleImageName, stdoutWriter)
if err != nil {
log.WriteTo(j.ui)
j.resultsCh <- fmt.Errorf("Error building image: %s", err.Error())
return
}
j.resultsCh <- nil
}
示例2: 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
}
示例3: 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)
}
}
示例4: cacheHandler
func (c container) cacheHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
var cacheStatus string
var urlComponents = []string{
"http://",
config.backend,
r.URL.Path,
}
backendURL := strings.Join(urlComponents, "")
body, _ := ioutil.ReadAll(r.Body)
identifier := []byte(fmt.Sprintf("%s%s", body, r.URL.Path))
sum := md5.Sum(identifier)
hash := hex.EncodeToString(sum[:16])
redisConn := c.pool.Get()
defer redisConn.Close()
repl, err := redisConn.Do("GET", hash)
if err != nil {
log.Error(err.Error())
return
}
if repl == nil {
log.Debug(fmt.Sprintf("%s %s", hash, color.YellowString("MISS")))
w.Header().Set("X-postcache", "MISS")
response, cacheError := c.updateCache(hash, string(body), backendURL, false)
if cacheError != nil {
log.Error(cacheError.Error())
}
w.Write([]byte(response))
} else {
ttlrepl, ttlerr := redisConn.Do("TTL", hash)
if ttlerr != nil {
log.Error("key is gone? maybe the TTL expired before we got here.")
} else {
if ttlrepl.(int64) < int64((config.expire - config.freshness)) {
cacheStatus = color.YellowString("STALE")
go c.updateCache(hash, string(body), backendURL, true)
} else {
cacheStatus = color.CyanString("HIT")
}
}
log.Debug(fmt.Sprintf("%s %s ", hash, cacheStatus))
w.Header().Set("X-postcache", cacheStatus)
w.Write(repl.([]byte))
}
} else {
w.Header().Set("X-postcache", "CANT-CACHE")
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = config.backend
},
}
proxy.ServeHTTP(w, r)
}
}
示例5: 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
}
示例6: 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
},
}
}
示例7: GeneratePackagesRoleImage
// GeneratePackagesRoleImage builds the docker image for the packages layer
// where all packages are included
func (f *Fissile) GeneratePackagesRoleImage(repository string, roleManifest *model.RoleManifest, noBuild, force bool, packagesImageBuilder *builder.PackagesImageBuilder) error {
if len(f.releases) == 0 {
return fmt.Errorf("Releases not loaded")
}
dockerManager, err := docker.NewImageManager()
if err != nil {
return fmt.Errorf("Error connecting to docker: %s", err.Error())
}
packagesLayerImageName := packagesImageBuilder.GetRolePackageImageName(roleManifest)
if !force {
if hasImage, err := dockerManager.HasImage(packagesLayerImageName); err == nil && hasImage {
f.UI.Printf("Packages layer %s already exists. Skipping ...\n", color.YellowString(packagesLayerImageName))
return nil
}
}
baseImageName := builder.GetBaseImageName(repository, f.Version)
if hasImage, err := dockerManager.HasImage(baseImageName); err != nil {
return fmt.Errorf("Error getting base image: %s", err)
} else if !hasImage {
return fmt.Errorf("Failed to find role base %s, did you build it first?", baseImageName)
}
if noBuild {
f.UI.Println("Skipping packages layer docker image build because of --no-build flag.")
return nil
}
f.UI.Printf("Building packages layer docker image %s ...\n",
color.YellowString(packagesLayerImageName))
log := new(bytes.Buffer)
stdoutWriter := docker.NewFormattingWriter(
log,
docker.ColoredBuildStringFunc(packagesLayerImageName),
)
tarPopulator := packagesImageBuilder.NewDockerPopulator(roleManifest, force)
err = dockerManager.BuildImageFromCallback(packagesLayerImageName, stdoutWriter, tarPopulator)
if err != nil {
log.WriteTo(f.UI)
return fmt.Errorf("Error building packages layer docker image: %s", err.Error())
}
f.UI.Println(color.GreenString("Done."))
return nil
}
示例8: 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)
}
示例9: 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
}
示例10: 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)
}
}
示例11: FindPlugins
func (m Manifest) FindPlugins(plugin string) ([]PluginData, error) {
tree := m.tree.Path(plugin)
result := make([]PluginData, 0)
if tree.Data() == nil {
return nil, fmt.Errorf("Plugin `%s` not found in manifest!", plugin)
}
if _, ok := tree.Data().([]interface{}); ok {
arr, _ := tree.Children()
for _, item := range arr {
if _, ok := item.Data().(string); ok {
result = append(result, makePluginPair(plugin, item))
} else if res, err := item.ChildrenMap(); err == nil {
if len(res) == 1 {
for subplugin, data := range res {
result = append(result, makePluginPair(plugin+"."+subplugin, data))
break
}
} else {
result = append(result, makePluginPair(plugin, item))
}
}
}
} else if PluginRegestry.Has(plugin) {
result = append(result, makePluginPair(plugin, tree))
} else {
log.Println(color.YellowString("Plugins for `%s` section not specified, skip...", plugin))
}
return result, nil
}
示例12: dump
func dump(w http.ResponseWriter, r *http.Request) {
var jsonData interface{}
defer r.Body.Close()
r.Header.Set("Host", r.Host)
for _, header := range sortHeaderKeys(r.Header) {
fmt.Printf("%s %s: %s\n", color.YellowString("[H]"), header, r.Header.Get(header))
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("error: unable to read request body: %s", err)
return
}
if getContentType(r) == "application/json" {
if err := json.Unmarshal(body, &jsonData); err != nil {
fmt.Printf("%s error: request Content-Type is application/json, but unable to process JSON %s\n", color.RedString("[!]"), err)
fmt.Printf("%s %s\n", color.CyanString("[B]"), body)
} else {
jf := prettyjson.NewFormatter()
j, _ := jf.Format(body)
fmt.Printf("%s %s\n", color.CyanString("[B]"), j)
}
} else {
fmt.Printf("%s %s\n", color.CyanString("[B]"), body)
}
}
示例13: getSearchOpt
func getSearchOpt() (SearchType, FilterType) {
var (
search SearchType = SearchBySubject
filter FilterType = SearchFilterAll
)
for {
color.White("Please select search range:\n")
for k := SearchFilterAll; k <= SearchConference; k++ {
fmt.Fprintf(color.Output, "\t %s: %s\n", color.CyanString("%d", k), searchFilterHints[k])
}
fmt.Fprintf(color.Output, "$ %s", color.YellowString("select: "))
s := getInputString()
if len(s) > 0 {
selected, err := strconv.ParseInt(s, 16, 32)
if err != nil || selected < int64(SearchFilterAll) || selected > int64(SearchConference) {
color.Red("Invalid selection\n")
continue
}
filter = FilterType(selected)
}
break
}
return search, filter
}
示例14: listPropertiesForHuman
func (f *Fissile) listPropertiesForHuman() {
// Human readable output.
for _, release := range f.releases {
f.UI.Println(color.GreenString("Dev release %s (%s)",
color.YellowString(release.Name), color.MagentaString(release.Version)))
for _, job := range release.Jobs {
f.UI.Printf("%s (%s): %s\n", color.YellowString(job.Name),
color.WhiteString(job.Version), job.Description)
for _, property := range job.Properties {
f.UI.Printf("\t%s: %v\n", color.YellowString(property.Name),
property.Default)
}
}
}
}
示例15: 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())))
}
}
}
}
}
}
}