How to use Format method of cmd Package

Best K6 code snippet using cmd.Format

redis.go

Source:redis.go Github

copy

Full Screen

...104 defer tx.Close()105 now := util.MakeTimestamp() / 1000106 _, err := tx.Exec(func() error {107 tx.HSet(r.formatKey("nodes"), join(id, "name"), id)108 tx.HSet(r.formatKey("nodes"), join(id, "height"), strconv.FormatUint(height, 10))109 tx.HSet(r.formatKey("nodes"), join(id, "difficulty"), diff.String())110 tx.HSet(r.formatKey("nodes"), join(id, "lastBeat"), strconv.FormatInt(now, 10))111 return nil112 })113 return err114}115func (r *RedisClient) GetNodeStates() ([]map[string]interface{}, error) {116 cmd := r.client.HGetAllMap(r.formatKey("nodes"))117 if cmd.Err() != nil {118 return nil, cmd.Err()119 }120 m := make(map[string]map[string]interface{})121 for key, value := range cmd.Val() {122 parts := strings.Split(key, ":")123 if val, ok := m[parts[0]]; ok {124 val[parts[1]] = value125 } else {126 node := make(map[string]interface{})127 node[parts[1]] = value128 m[parts[0]] = node129 }130 }131 v := make([]map[string]interface{}, len(m), len(m))132 i := 0133 for _, value := range m {134 v[i] = value135 i++136 }137 return v, nil138}139func (r *RedisClient) checkPoWExist(height uint64, params []string) (bool, error) {140 // Sweep PoW backlog for previous blocks, we have 3 templates back in RAM141 r.client.ZRemRangeByScore(r.formatKey("pow"), "-inf", fmt.Sprint("(", height-8))142 val, err := r.client.ZAdd(r.formatKey("pow"), redis.Z{Score: float64(height), Member: strings.Join(params, ":")}).Result()143 return val == 0, err144}145func (r *RedisClient) WriteShare(login, id string, params []string, diff int64, height uint64, window time.Duration) (bool, error) {146 exist, err := r.checkPoWExist(height, params)147 if err != nil {148 return false, err149 }150 // Duplicate share, (nonce, powHash, mixDigest) pair exist151 if exist {152 return true, nil153 }154 tx := r.client.Multi()155 defer tx.Close()156 ms := util.MakeTimestamp()157 ts := ms / 1000158 _, err = tx.Exec(func() error {159 r.writeShare(tx, ms, ts, login, id, diff, window)160 tx.HIncrBy(r.formatKey("stats"), "roundShares", diff)161 return nil162 })163 return false, err164}165func (r *RedisClient) WriteBlock(login, id string, params []string, diff, roundDiff int64, height uint64, window time.Duration) (bool, error) {166 exist, err := r.checkPoWExist(height, params)167 if err != nil {168 return false, err169 }170 // Duplicate share, (nonce, powHash, mixDigest) pair exist171 if exist {172 return true, nil173 }174 tx := r.client.Multi()175 defer tx.Close()176 ms := util.MakeTimestamp()177 ts := ms / 1000178 cmds, err := tx.Exec(func() error {179 r.writeShare(tx, ms, ts, login, id, diff, window)180 tx.HSet(r.formatKey("stats"), "lastBlockFound", strconv.FormatInt(ts, 10))181 tx.HDel(r.formatKey("stats"), "roundShares")182 tx.ZIncrBy(r.formatKey("finders"), 1, login)183 tx.HIncrBy(r.formatKey("miners", login), "blocksFound", 1)184 tx.Rename(r.formatKey("shares", "roundCurrent"), r.formatRound(int64(height), params[0]))185 tx.HGetAllMap(r.formatRound(int64(height), params[0]))186 return nil187 })188 if err != nil {189 return false, err190 } else {191 sharesMap, _ := cmds[10].(*redis.StringStringMapCmd).Result()192 totalShares := int64(0)193 for _, v := range sharesMap {194 n, _ := strconv.ParseInt(v, 10, 64)195 totalShares += n196 }197 hashHex := strings.Join(params, ":")198 s := join(hashHex, ts, roundDiff, totalShares)199 cmd := r.client.ZAdd(r.formatKey("blocks", "candidates"), redis.Z{Score: float64(height), Member: s})200 return false, cmd.Err()201 }202}203func (r *RedisClient) writeShare(tx *redis.Multi, ms, ts int64, login, id string, diff int64, expire time.Duration) {204 tx.HIncrBy(r.formatKey("shares", "roundCurrent"), login, diff)205 tx.ZAdd(r.formatKey("hashrate"), redis.Z{Score: float64(ts), Member: join(diff, login, id, ms)})206 tx.ZAdd(r.formatKey("hashrate", login), redis.Z{Score: float64(ts), Member: join(diff, id, ms)})207 tx.Expire(r.formatKey("hashrate", login), expire) // Will delete hashrates for miners that gone208 tx.HSet(r.formatKey("miners", login), "lastShare", strconv.FormatInt(ts, 10))209}210func (r *RedisClient) formatKey(args ...interface{}) string {211 return join(r.prefix, join(args...))212}213func (r *RedisClient) formatRound(height int64, nonce string) string {214 return r.formatKey("shares", "round"+strconv.FormatInt(height, 10), nonce)215}216func join(args ...interface{}) string {217 s := make([]string, len(args))218 for i, v := range args {219 switch v.(type) {220 case string:221 s[i] = v.(string)222 case int64:223 s[i] = strconv.FormatInt(v.(int64), 10)224 case uint64:225 s[i] = strconv.FormatUint(v.(uint64), 10)226 case float64:227 s[i] = strconv.FormatFloat(v.(float64), 'f', 0, 64)228 case bool:229 if v.(bool) {230 s[i] = "1"231 } else {232 s[i] = "0"233 }234 case *big.Int:235 n := v.(*big.Int)236 if n != nil {237 s[i] = n.String()238 } else {239 s[i] = "0"240 }241 default:242 panic("Invalid type specified for conversion")243 }244 }245 return strings.Join(s, ":")246}247func (r *RedisClient) GetCandidates(maxHeight int64) ([]*BlockData, error) {248 option := redis.ZRangeByScore{Min: "0", Max: strconv.FormatInt(maxHeight, 10)}249 cmd := r.client.ZRangeByScoreWithScores(r.formatKey("blocks", "candidates"), option)250 if cmd.Err() != nil {251 return nil, cmd.Err()252 }253 return convertCandidateResults(cmd), nil254}255func (r *RedisClient) GetImmatureBlocks(maxHeight int64) ([]*BlockData, error) {256 option := redis.ZRangeByScore{Min: "0", Max: strconv.FormatInt(maxHeight, 10)}257 cmd := r.client.ZRangeByScoreWithScores(r.formatKey("blocks", "immature"), option)258 if cmd.Err() != nil {259 return nil, cmd.Err()260 }261 return convertBlockResults(cmd), nil262}263func (r *RedisClient) GetRoundShares(height int64, nonce string) (map[string]int64, error) {264 result := make(map[string]int64)265 cmd := r.client.HGetAllMap(r.formatRound(height, nonce))266 if cmd.Err() != nil {267 return nil, cmd.Err()268 }269 sharesMap, _ := cmd.Result()270 for login, v := range sharesMap {271 n, _ := strconv.ParseInt(v, 10, 64)272 result[login] = n273 }274 return result, nil275}276func (r *RedisClient) GetPayees() ([]string, error) {277 payees := make(map[string]struct{})278 var result []string279 var c int64280 for {281 var keys []string282 var err error283 c, keys, err = r.client.Scan(c, r.formatKey("miners", "*"), 100).Result()284 if err != nil {285 return nil, err286 }287 for _, row := range keys {288 login := strings.Split(row, ":")[2]289 payees[login] = struct{}{}290 }291 if c == 0 {292 break293 }294 }295 for login, _ := range payees {296 result = append(result, login)297 }298 return result, nil299}300func (r *RedisClient) GetBalance(login string) (int64, error) {301 cmd := r.client.HGet(r.formatKey("miners", login), "balance")302 if cmd.Err() == redis.Nil {303 return 0, nil304 } else if cmd.Err() != nil {305 return 0, cmd.Err()306 }307 return cmd.Int64()308}309func (r *RedisClient) LockPayouts(login string, amount int64) error {310 key := r.formatKey("payments", "lock")311 result := r.client.SetNX(key, join(login, amount), 0).Val()312 if !result {313 return fmt.Errorf("Unable to acquire lock '%s'", key)314 }315 return nil316}317func (r *RedisClient) UnlockPayouts() error {318 key := r.formatKey("payments", "lock")319 _, err := r.client.Del(key).Result()320 return err321}322func (r *RedisClient) IsPayoutsLocked() (bool, error) {323 _, err := r.client.Get(r.formatKey("payments", "lock")).Result()324 if err == redis.Nil {325 return false, nil326 } else if err != nil {327 return false, err328 } else {329 return true, nil330 }331}332type PendingPayment struct {333 Timestamp int64 `json:"timestamp"`334 Amount int64 `json:"amount"`335 Address string `json:"login"`336}337func (r *RedisClient) GetPendingPayments() []*PendingPayment {338 raw := r.client.ZRevRangeWithScores(r.formatKey("payments", "pending"), 0, -1)339 var result []*PendingPayment340 for _, v := range raw.Val() {341 // timestamp -> "address:amount"342 payment := PendingPayment{}343 payment.Timestamp = int64(v.Score)344 fields := strings.Split(v.Member.(string), ":")345 payment.Address = fields[0]346 payment.Amount, _ = strconv.ParseInt(fields[1], 10, 64)347 result = append(result, &payment)348 }349 return result350}351// Deduct miner's balance for payment352func (r *RedisClient) UpdateBalance(login string, amount int64) error {353 tx := r.client.Multi()354 defer tx.Close()355 ts := util.MakeTimestamp() / 1000356 _, err := tx.Exec(func() error {357 tx.HIncrBy(r.formatKey("miners", login), "balance", (amount * -1))358 tx.HIncrBy(r.formatKey("miners", login), "pending", amount)359 tx.HIncrBy(r.formatKey("finances"), "balance", (amount * -1))360 tx.HIncrBy(r.formatKey("finances"), "pending", amount)361 tx.ZAdd(r.formatKey("payments", "pending"), redis.Z{Score: float64(ts), Member: join(login, amount)})362 return nil363 })364 return err365}366func (r *RedisClient) RollbackBalance(login string, amount int64) error {367 tx := r.client.Multi()368 defer tx.Close()369 _, err := tx.Exec(func() error {370 tx.HIncrBy(r.formatKey("miners", login), "balance", amount)371 tx.HIncrBy(r.formatKey("miners", login), "pending", (amount * -1))372 tx.HIncrBy(r.formatKey("finances"), "balance", amount)373 tx.HIncrBy(r.formatKey("finances"), "pending", (amount * -1))374 tx.ZRem(r.formatKey("payments", "pending"), join(login, amount))375 return nil376 })377 return err378}379func (r *RedisClient) WritePayment(login, txHash string, amount int64) error {380 tx := r.client.Multi()381 defer tx.Close()382 ts := util.MakeTimestamp() / 1000383 _, err := tx.Exec(func() error {384 tx.HIncrBy(r.formatKey("miners", login), "pending", (amount * -1))385 tx.HIncrBy(r.formatKey("miners", login), "paid", amount)386 tx.HIncrBy(r.formatKey("finances"), "pending", (amount * -1))387 tx.HIncrBy(r.formatKey("finances"), "paid", amount)388 tx.ZAdd(r.formatKey("payments", "all"), redis.Z{Score: float64(ts), Member: join(txHash, login, amount)})389 tx.ZAdd(r.formatKey("payments", login), redis.Z{Score: float64(ts), Member: join(txHash, amount)})390 tx.ZRem(r.formatKey("payments", "pending"), join(login, amount))391 tx.Del(r.formatKey("payments", "lock"))392 return nil393 })394 return err395}396func (r *RedisClient) WriteImmatureBlock(block *BlockData, roundRewards map[string]int64) error {397 tx := r.client.Multi()398 defer tx.Close()399 _, err := tx.Exec(func() error {400 r.writeImmatureBlock(tx, block)401 total := int64(0)402 for login, amount := range roundRewards {403 total += amount404 tx.HIncrBy(r.formatKey("miners", login), "immature", amount)405 tx.HSetNX(r.formatKey("credits", "immature", block.Height, block.Hash), login, strconv.FormatInt(amount, 10))406 }407 tx.HIncrBy(r.formatKey("finances"), "immature", total)408 return nil409 })410 return err411}412func (r *RedisClient) WriteMaturedBlock(block *BlockData, roundRewards map[string]int64) error {413 creditKey := r.formatKey("credits", "immature", block.RoundHeight, block.Hash)414 tx, err := r.client.Watch(creditKey)415 // Must decrement immatures using existing log entry416 immatureCredits := tx.HGetAllMap(creditKey)417 if err != nil {418 return err419 }420 defer tx.Close()421 ts := util.MakeTimestamp() / 1000422 value := join(block.Hash, ts, block.Reward)423 _, err = tx.Exec(func() error {424 r.writeMaturedBlock(tx, block)425 tx.ZAdd(r.formatKey("credits", "all"), redis.Z{Score: float64(block.Height), Member: value})426 // Decrement immature balances427 totalImmature := int64(0)428 for login, amountString := range immatureCredits.Val() {429 amount, _ := strconv.ParseInt(amountString, 10, 64)430 totalImmature += amount431 tx.HIncrBy(r.formatKey("miners", login), "immature", (amount * -1))432 }433 // Increment balances434 total := int64(0)435 for login, amount := range roundRewards {436 total += amount437 // NOTICE: Maybe expire round reward entry in 604800 (a week)?438 tx.HIncrBy(r.formatKey("miners", login), "balance", amount)439 tx.HSetNX(r.formatKey("credits", block.Height, block.Hash), login, strconv.FormatInt(amount, 10))440 }441 tx.Del(creditKey)442 tx.HIncrBy(r.formatKey("finances"), "balance", total)443 tx.HIncrBy(r.formatKey("finances"), "immature", (totalImmature * -1))444 tx.HSet(r.formatKey("finances"), "lastCreditHeight", strconv.FormatInt(block.Height, 10))445 tx.HSet(r.formatKey("finances"), "lastCreditHash", block.Hash)446 tx.HIncrBy(r.formatKey("finances"), "totalMined", block.RewardInShannon())447 return nil448 })449 return err450}451func (r *RedisClient) WriteOrphan(block *BlockData) error {452 creditKey := r.formatKey("credits", "immature", block.RoundHeight, block.Hash)453 tx, err := r.client.Watch(creditKey)454 // Must decrement immatures using existing log entry455 immatureCredits := tx.HGetAllMap(creditKey)456 if err != nil {457 return err458 }...

Full Screen

Full Screen

fmt_test.go

Source:fmt_test.go Github

copy

Full Screen

1// Copyright 2016 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4// This file implements TestFormats; a test that verifies5// format strings in the compiler (this directory and all6// subdirectories, recursively).7//8// TestFormats finds potential (Printf, etc.) format strings.9// If they are used in a call, the format verbs are verified10// based on the matching argument type against a precomputed11// table of valid formats. The knownFormats table can be used12// to automatically rewrite format strings with the -u flag.13//14// A new knownFormats table based on the found formats is printed15// when the test is run in verbose mode (-v flag). The table16// needs to be updated whenever a new (type, format) combination17// is found and the format verb is not 'v' or 'T' (as in "%v" or18// "%T").19//20// Run as: go test -run Formats [-u][-v]21//22// Known bugs:23// - indexed format strings ("%[2]s", etc.) are not supported24// (the test will fail)25// - format strings that are not simple string literals cannot26// be updated automatically27// (the test will fail with respective warnings)28// - format strings in _test packages outside the current29// package are not processed30// (the test will report those files)31//32package main_test33import (34 "bytes"35 "flag"36 "fmt"37 "go/ast"38 "go/build"39 "go/constant"40 "go/format"41 "go/importer"42 "go/parser"43 "go/token"44 "go/types"45 "internal/testenv"46 "io/ioutil"47 "log"48 "os"49 "path/filepath"50 "sort"51 "strconv"52 "strings"53 "testing"54 "unicode/utf8"55)56var update = flag.Bool("u", false, "update format strings")57// The following variables collect information across all processed files.58var (59 fset = token.NewFileSet()60 formatStrings = make(map[*ast.BasicLit]bool) // set of all potential format strings found61 foundFormats = make(map[string]bool) // set of all formats found62 callSites = make(map[*ast.CallExpr]*callSite) // map of all calls63)64// A File is a corresponding (filename, ast) pair.65type File struct {66 name string67 ast *ast.File68}69func TestFormats(t *testing.T) {70 testenv.MustHaveGoBuild(t) // more restrictive than necessary, but that's ok71 // process all directories72 filepath.Walk(".", func(path string, info os.FileInfo, err error) error {73 if info.IsDir() {74 if info.Name() == "testdata" {75 return filepath.SkipDir76 }77 importPath := filepath.Join("cmd/compile", path)78 if blacklistedPackages[filepath.ToSlash(importPath)] {79 return filepath.SkipDir80 }81 pkg, err := build.Import(importPath, path, 0)82 if err != nil {83 if _, ok := err.(*build.NoGoError); ok {84 return nil // nothing to do here85 }86 t.Fatal(err)87 }88 collectPkgFormats(t, pkg)89 }90 return nil91 })92 // test and rewrite formats93 updatedFiles := make(map[string]File) // files that were rewritten94 for _, p := range callSites {95 // test current format literal and determine updated one96 out := formatReplace(p.str, func(index int, in string) string {97 if in == "*" {98 return in // cannot rewrite '*' (as in "%*d")99 }100 // in != '*'101 typ := p.types[index]102 format := typ + " " + in // e.g., "*Node %n"103 // check if format is known104 out, known := knownFormats[format]105 // record format if not yet found106 _, found := foundFormats[format]107 if !found {108 foundFormats[format] = true109 }110 // report an error if the format is unknown and this is the first111 // time we see it; ignore "%v" and "%T" which are always valid112 if !known && !found && in != "%v" && in != "%T" {113 t.Errorf("%s: unknown format %q for %s argument", posString(p.arg), in, typ)114 }115 if out == "" {116 out = in117 }118 return out119 })120 // replace existing format literal if it changed121 if out != p.str {122 // we cannot replace the argument if it's not a string literal for now123 // (e.g., it may be "foo" + "bar")124 lit, ok := p.arg.(*ast.BasicLit)125 if !ok {126 delete(callSites, p.call) // treat as if we hadn't found this site127 continue128 }129 if testing.Verbose() {130 fmt.Printf("%s:\n\t- %q\n\t+ %q\n", posString(p.arg), p.str, out)131 }132 // find argument index of format argument133 index := -1134 for i, arg := range p.call.Args {135 if p.arg == arg {136 index = i137 break138 }139 }140 if index < 0 {141 // we may have processed the same call site twice,142 // but that shouldn't happen143 panic("internal error: matching argument not found")144 }145 // replace literal146 new := *lit // make a copy147 new.Value = strconv.Quote(out) // this may introduce "-quotes where there were `-quotes148 p.call.Args[index] = &new149 updatedFiles[p.file.name] = p.file150 }151 }152 // write dirty files back153 var filesUpdated bool154 if len(updatedFiles) > 0 && *update {155 for _, file := range updatedFiles {156 var buf bytes.Buffer157 if err := format.Node(&buf, fset, file.ast); err != nil {158 t.Errorf("WARNING: formatting %s failed: %v", file.name, err)159 continue160 }161 if err := ioutil.WriteFile(file.name, buf.Bytes(), 0x666); err != nil {162 t.Errorf("WARNING: writing %s failed: %v", file.name, err)163 continue164 }165 fmt.Printf("updated %s\n", file.name)166 filesUpdated = true167 }168 }169 // report all function names containing a format string170 if len(callSites) > 0 && testing.Verbose() {171 set := make(map[string]bool)172 for _, p := range callSites {173 set[nodeString(p.call.Fun)] = true174 }175 var list []string176 for s := range set {177 list = append(list, s)178 }179 fmt.Println("\nFunctions")180 printList(list)181 }182 // report all formats found183 if len(foundFormats) > 0 && testing.Verbose() {184 var list []string185 for s := range foundFormats {186 list = append(list, fmt.Sprintf("%q: \"\",", s))187 }188 fmt.Println("\nvar knownFormats = map[string]string{")189 printList(list)190 fmt.Println("}")191 }192 // all format strings of calls must be in the formatStrings set (self-verification)193 for _, p := range callSites {194 if lit, ok := p.arg.(*ast.BasicLit); ok && lit.Kind == token.STRING {195 if formatStrings[lit] {196 // ok197 delete(formatStrings, lit)198 } else {199 // this should never happen200 panic(fmt.Sprintf("internal error: format string not found (%s)", posString(lit)))201 }202 }203 }204 // if we have any strings left, we may need to update them manually205 if len(formatStrings) > 0 && filesUpdated {206 var list []string207 for lit := range formatStrings {208 list = append(list, fmt.Sprintf("%s: %s", posString(lit), nodeString(lit)))209 }210 fmt.Println("\nWARNING: Potentially missed format strings")211 printList(list)212 t.Fail()213 }214 fmt.Println()215}216// A callSite describes a function call that appears to contain217// a format string.218type callSite struct {219 file File220 call *ast.CallExpr // call containing the format string221 arg ast.Expr // format argument (string literal or constant)222 str string // unquoted format string223 types []string // argument types224}225func collectPkgFormats(t *testing.T, pkg *build.Package) {226 // collect all files227 var filenames []string228 filenames = append(filenames, pkg.GoFiles...)229 filenames = append(filenames, pkg.CgoFiles...)230 filenames = append(filenames, pkg.TestGoFiles...)231 // TODO(gri) verify _test files outside package232 for _, name := range pkg.XTestGoFiles {233 // don't process this test itself234 if name != "fmt_test.go" && testing.Verbose() {235 fmt.Printf("WARNING: %s not processed\n", filepath.Join(pkg.Dir, name))236 }237 }238 // make filenames relative to .239 for i, name := range filenames {240 filenames[i] = filepath.Join(pkg.Dir, name)241 }242 // parse all files243 files := make([]*ast.File, len(filenames))244 for i, filename := range filenames {245 f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)246 if err != nil {247 t.Fatal(err)248 }249 files[i] = f250 }251 // typecheck package252 conf := types.Config{Importer: importer.Default()}253 etypes := make(map[ast.Expr]types.TypeAndValue)254 if _, err := conf.Check(pkg.ImportPath, fset, files, &types.Info{Types: etypes}); err != nil {255 t.Fatal(err)256 }257 // collect all potential format strings (for extra verification later)258 for _, file := range files {259 ast.Inspect(file, func(n ast.Node) bool {260 if s, ok := stringLit(n); ok && isFormat(s) {261 formatStrings[n.(*ast.BasicLit)] = true262 }263 return true264 })265 }266 // collect all formats/arguments of calls with format strings267 for index, file := range files {268 ast.Inspect(file, func(n ast.Node) bool {269 if call, ok := n.(*ast.CallExpr); ok {270 // ignore blacklisted functions271 if blacklistedFunctions[nodeString(call.Fun)] {272 return true273 }274 // look for an arguments that might be a format string275 for i, arg := range call.Args {276 if s, ok := stringVal(etypes[arg]); ok && isFormat(s) {277 // make sure we have enough arguments278 n := numFormatArgs(s)279 if i+1+n > len(call.Args) {280 t.Errorf("%s: not enough format args (blacklist %s?)", posString(call), nodeString(call.Fun))281 break // ignore this call282 }283 // assume last n arguments are to be formatted;284 // determine their types285 argTypes := make([]string, n)286 for i, arg := range call.Args[len(call.Args)-n:] {287 if tv, ok := etypes[arg]; ok {288 argTypes[i] = typeString(tv.Type)289 }290 }291 // collect call site292 if callSites[call] != nil {293 panic("internal error: file processed twice?")294 }295 callSites[call] = &callSite{296 file: File{filenames[index], file},297 call: call,298 arg: arg,299 str: s,300 types: argTypes,301 }302 break // at most one format per argument list303 }304 }305 }306 return true307 })308 }309}310// printList prints list in sorted order.311func printList(list []string) {312 sort.Strings(list)313 for _, s := range list {314 fmt.Println("\t", s)315 }316}317// posString returns a string representation of n's position318// in the form filename:line:col: .319func posString(n ast.Node) string {320 if n == nil {321 return ""322 }323 return fset.Position(n.Pos()).String()324}325// nodeString returns a string representation of n.326func nodeString(n ast.Node) string {327 var buf bytes.Buffer328 if err := format.Node(&buf, fset, n); err != nil {329 log.Fatal(err) // should always succeed330 }331 return buf.String()332}333// typeString returns a string representation of n.334func typeString(typ types.Type) string {335 return filepath.ToSlash(typ.String())336}337// stringLit returns the unquoted string value and true if338// n represents a string literal; otherwise it returns ""339// and false.340func stringLit(n ast.Node) (string, bool) {341 if lit, ok := n.(*ast.BasicLit); ok && lit.Kind == token.STRING {342 s, err := strconv.Unquote(lit.Value)343 if err != nil {344 log.Fatal(err) // should not happen with correct ASTs345 }346 return s, true347 }348 return "", false349}350// stringVal returns the (unquoted) string value and true if351// tv is a string constant; otherwise it returns "" and false.352func stringVal(tv types.TypeAndValue) (string, bool) {353 if tv.IsValue() && tv.Value != nil && tv.Value.Kind() == constant.String {354 return constant.StringVal(tv.Value), true355 }356 return "", false357}358// formatIter iterates through the string s in increasing359// index order and calls f for each format specifier '%..v'.360// The arguments for f describe the specifier's index range.361// If a format specifier contains a "*", f is called with362// the index range for "*" alone, before being called for363// the entire specifier. The result of f is the index of364// the rune at which iteration continues.365func formatIter(s string, f func(i, j int) int) {366 i := 0 // index after current rune367 var r rune // current rune368 next := func() {369 r1, w := utf8.DecodeRuneInString(s[i:])370 if w == 0 {371 r1 = -1 // signal end-of-string372 }373 r = r1374 i += w375 }376 flags := func() {377 for r == ' ' || r == '#' || r == '+' || r == '-' || r == '0' {378 next()379 }380 }381 index := func() {382 if r == '[' {383 log.Fatalf("cannot handle indexed arguments: %s", s)384 }385 }386 digits := func() {387 index()388 if r == '*' {389 i = f(i-1, i)390 next()391 return392 }393 for '0' <= r && r <= '9' {394 next()395 }396 }397 for next(); r >= 0; next() {398 if r == '%' {399 i0 := i400 next()401 flags()402 digits()403 if r == '.' {404 next()405 digits()406 }407 index()408 // accept any letter (a-z, A-Z) as format verb;409 // ignore anything else410 if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' {411 i = f(i0-1, i)412 }413 }414 }415}416// isFormat reports whether s contains format specifiers.417func isFormat(s string) (yes bool) {418 formatIter(s, func(i, j int) int {419 yes = true420 return len(s) // stop iteration421 })422 return423}424// oneFormat reports whether s is exactly one format specifier.425func oneFormat(s string) (yes bool) {426 formatIter(s, func(i, j int) int {427 yes = i == 0 && j == len(s)428 return j429 })430 return431}432// numFormatArgs returns the number of format specifiers in s.433func numFormatArgs(s string) int {434 count := 0435 formatIter(s, func(i, j int) int {436 count++437 return j438 })439 return count440}441// formatReplace replaces the i'th format specifier s in the incoming442// string in with the result of f(i, s) and returns the new string.443func formatReplace(in string, f func(i int, s string) string) string {444 var buf []byte445 i0 := 0446 index := 0447 formatIter(in, func(i, j int) int {448 if sub := in[i:j]; sub != "*" { // ignore calls for "*" width/length specifiers449 buf = append(buf, in[i0:i]...)450 buf = append(buf, f(index, sub)...)451 i0 = j452 }453 index++454 return j455 })456 return string(append(buf, in[i0:]...))457}458// blacklistedPackages is the set of packages which can459// be ignored.460var blacklistedPackages = map[string]bool{461 "cmd/compile/internal/big": true,462}463// blacklistedFunctions is the set of functions which may have464// format-like arguments but which don't do any formatting and465// thus may be ignored.466var blacklistedFunctions = map[string]bool{}467func init() {468 // verify that knownFormats entries are correctly formatted469 for key, val := range knownFormats {470 // key must be "typename format", and format starts with a '%'471 // (formats containing '*' alone are not collected in this table)472 i := strings.Index(key, "%")473 if i < 0 || !oneFormat(key[i:]) {474 log.Fatalf("incorrect knownFormats key: %q", key)475 }476 // val must be "format" or ""477 if val != "" && !oneFormat(val) {478 log.Fatalf("incorrect knownFormats value: %q (key = %q)", val, key)479 }480 }481}482// knownFormats entries are of the form "typename format" -> "newformat".483// An absent entry means that the format is not recognized as valid.484// An empty new format means that the format should remain unchanged.485// To print out a new table, run: go test -run Formats -v.486var knownFormats = map[string]string{487 "*bytes.Buffer %s": "",488 "*cmd/compile/internal/big.Int %#x": "",489 "*cmd/compile/internal/gc.Bits %v": "",490 "*cmd/compile/internal/gc.Field %p": "",491 "*cmd/compile/internal/gc.Field %v": "",492 "*cmd/compile/internal/gc.Mpflt %v": "",493 "*cmd/compile/internal/gc.Mpint %v": "",494 "*cmd/compile/internal/gc.Node %#v": "",495 "*cmd/compile/internal/gc.Node %+S": "",496 "*cmd/compile/internal/gc.Node %+v": "",497 "*cmd/compile/internal/gc.Node %0j": "",498 "*cmd/compile/internal/gc.Node %L": "",499 "*cmd/compile/internal/gc.Node %S": "",500 "*cmd/compile/internal/gc.Node %j": "",...

Full Screen

Full Screen

model.go

Source:model.go Github

copy

Full Screen

...59 },60 }61 flags := cmd.Flags()62 flags.StringVar(&opts.Class, "class", "config", "Filter by model class")63 flags.StringVarP(&opts.Format, "format", "f", "", "Format output")64 return cmd65}66type ModelListOptions struct {67 Class string68 Refs []string69 Format string70}71func runModelList(cli agentcli.Cli, opts ModelListOptions) error {72 ctx, cancel := context.WithCancel(context.Background())73 defer cancel()74 allModels, err := cli.Client().ModelList(ctx, types.ModelListOptions{75 Class: opts.Class,76 })77 if err != nil {78 return err79 }80 models := filterModelsByRefs(allModels, opts.Refs)81 format := opts.Format82 if len(format) == 0 {83 printModelTable(cli.Out(), models)84 } else {85 if err := formatAsTemplate(cli.Out(), format, models); err != nil {86 return err87 }88 }89 return nil90}91func printModelTable(out io.Writer, models []types.Model) {92 var buf bytes.Buffer93 w := tabwriter.NewWriter(&buf, 0, 0, 2, ' ', 0)94 fmt.Fprintf(w, "MODEL NAME\tCLASS\tPROTO MESSAGE\tKEY PREFIX\t\n")95 for _, model := range models {96 fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n",97 model.Name, model.Class, model.ProtoName, model.KeyPrefix)98 }99 if err := w.Flush(); err != nil {100 panic(err)101 }102 fmt.Fprint(out, buf.String())103}104func filterModelsByPrefix(models []types.Model, prefixes []string) ([]types.Model, error) {105 if len(prefixes) == 0 {106 return models, nil107 }108 var filtered []types.Model109 for _, pref := range prefixes {110 var model types.Model111 for _, m := range models {112 if !strings.HasPrefix(m.Name, pref) {113 continue114 }115 if model.Name != "" {116 return nil, fmt.Errorf("multiple models found with provided prefix: %s", pref)117 }118 model = m119 }120 if model.Name == "" {121 return nil, fmt.Errorf("no model found for provided prefix: %s", pref)122 }123 filtered = append(filtered, model)124 }125 return filtered, nil126}127func filterModelsByRefs(models []types.Model, refs []string) []types.Model {128 var filtered []types.Model129 for _, model := range models {130 if !matchAnyRef(model, refs) {131 continue132 }133 filtered = append(filtered, model)134 }135 return filtered136}137func matchAnyRef(model types.Model, refs []string) bool {138 if len(refs) == 0 {139 return true140 }141 for _, ref := range refs {142 if ok, _ := path.Match(ref, model.Name); ok {143 return true144 }145 }146 return false147}148func newModelInspectCommand(cli agentcli.Cli) *cobra.Command {149 var (150 opts ModelInspectOptions151 )152 cmd := &cobra.Command{153 Use: "inspect MODEL [MODEL...]",154 Aliases: []string{"i"},155 Short: "Display detailed information on one or more models",156 Args: cobra.MinimumNArgs(1),157 RunE: func(cmd *cobra.Command, args []string) error {158 opts.Names = args159 return runModelInspect(cli, opts)160 },161 }162 cmd.Flags().StringVarP(&opts.Format, "format", "f", "", "Format for the output")163 return cmd164}165type ModelInspectOptions struct {166 Names []string167 Format string168}169func runModelInspect(cli agentcli.Cli, opts ModelInspectOptions) error {170 ctx, cancel := context.WithCancel(context.Background())171 defer cancel()172 allModels, err := cli.Client().ModelList(ctx, types.ModelListOptions{})173 if err != nil {174 return err175 }176 models, err := filterModelsByPrefix(allModels, opts.Names)177 if err != nil {178 return err179 }180 logrus.Debugf("models: %+v", models)181 format := opts.Format182 if len(format) == 0 {183 format = "json"184 }185 if err := formatAsTemplate(cli.Out(), format, models); err != nil {186 return err187 }188 return nil189}...

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ls", "-l")4 out, err := cmd.Output()5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(out))9}10import (11func main() {12 cmd := exec.Command("ls", "-l")13 out, err := cmd.Output()14 if err != nil {15 fmt.Println(err)16 }17 fmt.Println(string(out))18}19import (20func main() {21 cmd := exec.Command("ls", "-l")22 out, err := cmd.Output()23 if err != nil {24 fmt.Println(err)25 }26 fmt.Println(string(out))27}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ls", "-l")4 out, err := cmd.Output()5 if err != nil {6 fmt.Println(err)7 }8 fmt.Printf("The date is %s", out)9}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ls", "-l")4 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}5 fmt.Println(cmd.Format())6}7import (8func main() {9 cmd := exec.Command("ls", "-l")10 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}11 fmt.Println(cmd.String())12}13import (14func main() {15 cmd := exec.Command("ls", "-l")16 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}17 fmt.Println(cmd.Args)18}19import (20func main() {21 cmd := exec.Command("ls", "-l")22 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}23 fmt.Println(cmd.Path)24}25import (26func main() {27 cmd := exec.Command("ls", "-l")28 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}29 fmt.Println(cmd.Env)30}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1func main() {2 cmd := exec.Command("ls", "-al")3 output, err := cmd.Output()4 if err != nil {5 fmt.Println(err.Error())6 }7 fmt.Println(string(output))8}9func main() {10 cmd := exec.Command("ls", "-al")11 err := cmd.Run()12 if err != nil {13 fmt.Println(err.Error())14 }15}16func main() {17 cmd := exec.Command("ls", "-al")18 err := cmd.Start()19 if err != nil {20 fmt.Println(err.Error())21 }22}23func main() {24 cmd := exec.Command("ls", "-al")25 err := cmd.Start()26 if err != nil {27 fmt.Println(err.Error())28 }29 err = cmd.Wait()30 if err != nil {31 fmt.Println(err.Error())32 }33}34func main() {35 cmd := exec.Command("ls", "-al")36 stdout, err := cmd.StdoutPipe()37 if err != nil {38 fmt.Println(err.Error())39 }40 err = cmd.Start()41 if err != nil {42 fmt.Println(err.Error())43 }44 output, err := ioutil.ReadAll(stdout)45 if err != nil {46 fmt.Println(err.Error())47 }48 err = cmd.Wait()49 if err != nil {50 fmt.Println(err.Error())51 }52 fmt.Println(string(output))53}54func main() {55 cmd := exec.Command("ls", "-al")56 stderr, err := cmd.StderrPipe()57 if err != nil {58 fmt.Println(err.Error())59 }60 err = cmd.Start()61 if err != nil {62 fmt.Println(err.Error())63 }64 output, err := ioutil.ReadAll(stderr)65 if err != nil {66 fmt.Println(err.Error())67 }68 err = cmd.Wait()69 if err != nil {

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "os"3func main() {4cmd := exec.Command("cmd", "/c", "dir")5out, err := cmd.Output()6if err != nil {7fmt.Println(err.Error())8}9fmt.Println(string(out))10}11 1 File(s) 217 bytes12 2 Dir(s) 27,808,738,048 bytes free13import (14func main() {15cmd := exec.Command("cmd", "/c", "echo", "hello world")16out, err := cmd.Output()17if err != nil {18fmt.Println(err.Error())19}20fmt.Println(string(out))21}22import (23func main() {24cmd := exec.Command("cmd", "/c", "echo", "hello world")25out, err := cmd.Output()26if err != nil {27fmt.Println(err.Error())28}29fmt.Println(string(out))30}31import (32func main() {33cmd := exec.Command("cmd", "/c", "echo",

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("echo", "hello")4 fmt.Println(cmd.Format())5}6import (7func main() {8 cmd := exec.Command("ls", "-l")9 out, _ := cmd.Output()10 fmt.Println(string(out))11}12import (13func main() {14 cmd := exec.Command("ls", "-l")15 out, _ := cmd.StdoutPipe()16 cmd.Start()17 reader := bufio.NewReader(out)18 for line, _, _ := reader.ReadLine(); line != nil; line, _, _ = reader.ReadLine() {19 fmt.Println(string(line))20 }21 cmd.Wait()22}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful