id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
1,800
manifoldco/torus-cli
daemon/updates/updates.go
performCheck
func (e *Engine) performCheck() { log.Printf("Checking for updates to Torus") latest, err := e.getLatestVersion() if err != nil { log.Printf("Could not retrieve latest version of Tours: %s", err) return } e.targetVersion = latest if err := e.storeLastCheck(); err != nil { log.Printf("Cannot store the last check date: %s", err) } log.Printf("Successfully checked for updates; available version: %s", latest) }
go
func (e *Engine) performCheck() { log.Printf("Checking for updates to Torus") latest, err := e.getLatestVersion() if err != nil { log.Printf("Could not retrieve latest version of Tours: %s", err) return } e.targetVersion = latest if err := e.storeLastCheck(); err != nil { log.Printf("Cannot store the last check date: %s", err) } log.Printf("Successfully checked for updates; available version: %s", latest) }
[ "func", "(", "e", "*", "Engine", ")", "performCheck", "(", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ")", "\n\n", "latest", ",", "err", ":=", "e", ".", "getLatestVersion", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "e", ".", "targetVersion", "=", "latest", "\n", "if", "err", ":=", "e", ".", "storeLastCheck", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "latest", ")", "\n", "}" ]
// performCheck retrieves the latest version of Torus from the manifest and then
[ "performCheck", "retrieves", "the", "latest", "version", "of", "Torus", "from", "the", "manifest", "and", "then" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L124-L139
1,801
manifoldco/torus-cli
daemon/updates/updates.go
nextCheck
func (e *Engine) nextCheck() time.Duration { if !e.lastCheckValid() { return minCheckDuration } return e.hoursToNextRelease() }
go
func (e *Engine) nextCheck() time.Duration { if !e.lastCheckValid() { return minCheckDuration } return e.hoursToNextRelease() }
[ "func", "(", "e", "*", "Engine", ")", "nextCheck", "(", ")", "time", ".", "Duration", "{", "if", "!", "e", ".", "lastCheckValid", "(", ")", "{", "return", "minCheckDuration", "\n", "}", "\n", "return", "e", ".", "hoursToNextRelease", "(", ")", "\n", "}" ]
// nextCheck returns the time duration to wait before triggering an update check. // It is calculated based on wether there already were a check or enough time // has passed. By default the check is performed at the `releaseHourCheck`-th hour // of the `releaseDay` weekday.
[ "nextCheck", "returns", "the", "time", "duration", "to", "wait", "before", "triggering", "an", "update", "check", ".", "It", "is", "calculated", "based", "on", "wether", "there", "already", "were", "a", "check", "or", "enough", "time", "has", "passed", ".", "By", "default", "the", "check", "is", "performed", "at", "the", "releaseHourCheck", "-", "th", "hour", "of", "the", "releaseDay", "weekday", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L145-L150
1,802
manifoldco/torus-cli
daemon/updates/updates.go
lastCheckValid
func (e *Engine) lastCheckValid() bool { if e.lastCheck.IsZero() { return false } return e.lastCheck.Unix()-e.prevReleaseDay().Unix() >= 0 }
go
func (e *Engine) lastCheckValid() bool { if e.lastCheck.IsZero() { return false } return e.lastCheck.Unix()-e.prevReleaseDay().Unix() >= 0 }
[ "func", "(", "e", "*", "Engine", ")", "lastCheckValid", "(", ")", "bool", "{", "if", "e", ".", "lastCheck", ".", "IsZero", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "e", ".", "lastCheck", ".", "Unix", "(", ")", "-", "e", ".", "prevReleaseDay", "(", ")", ".", "Unix", "(", ")", ">=", "0", "\n", "}" ]
// lastCheckValid checks if the last update check contains the most recent // update info.
[ "lastCheckValid", "checks", "if", "the", "last", "update", "check", "contains", "the", "most", "recent", "update", "info", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L154-L159
1,803
manifoldco/torus-cli
daemon/updates/updates.go
prevReleaseDay
func (e *Engine) prevReleaseDay() time.Time { prevRelease := e.midnight(e.timeManager.Now()) day := prevRelease.Weekday() var dayHours int if day < releaseDay || (day == releaseDay && prevRelease.Hour() < releaseHourCheck) { dayHours = 24 * (7 - int(releaseDay-day)) } else if day > releaseDay || (day == releaseDay && prevRelease.Hour() > releaseHourCheck) { dayHours = 24 * int(day-releaseDay) } hours := releaseHourCheck - dayHours - prevRelease.Hour() prevRelease = prevRelease.Add(time.Duration(hours) * time.Hour) return prevRelease }
go
func (e *Engine) prevReleaseDay() time.Time { prevRelease := e.midnight(e.timeManager.Now()) day := prevRelease.Weekday() var dayHours int if day < releaseDay || (day == releaseDay && prevRelease.Hour() < releaseHourCheck) { dayHours = 24 * (7 - int(releaseDay-day)) } else if day > releaseDay || (day == releaseDay && prevRelease.Hour() > releaseHourCheck) { dayHours = 24 * int(day-releaseDay) } hours := releaseHourCheck - dayHours - prevRelease.Hour() prevRelease = prevRelease.Add(time.Duration(hours) * time.Hour) return prevRelease }
[ "func", "(", "e", "*", "Engine", ")", "prevReleaseDay", "(", ")", "time", ".", "Time", "{", "prevRelease", ":=", "e", ".", "midnight", "(", "e", ".", "timeManager", ".", "Now", "(", ")", ")", "\n", "day", ":=", "prevRelease", ".", "Weekday", "(", ")", "\n", "var", "dayHours", "int", "\n", "if", "day", "<", "releaseDay", "||", "(", "day", "==", "releaseDay", "&&", "prevRelease", ".", "Hour", "(", ")", "<", "releaseHourCheck", ")", "{", "dayHours", "=", "24", "*", "(", "7", "-", "int", "(", "releaseDay", "-", "day", ")", ")", "\n", "}", "else", "if", "day", ">", "releaseDay", "||", "(", "day", "==", "releaseDay", "&&", "prevRelease", ".", "Hour", "(", ")", ">", "releaseHourCheck", ")", "{", "dayHours", "=", "24", "*", "int", "(", "day", "-", "releaseDay", ")", "\n", "}", "\n", "hours", ":=", "releaseHourCheck", "-", "dayHours", "-", "prevRelease", ".", "Hour", "(", ")", "\n", "prevRelease", "=", "prevRelease", ".", "Add", "(", "time", ".", "Duration", "(", "hours", ")", "*", "time", ".", "Hour", ")", "\n", "return", "prevRelease", "\n", "}" ]
// prevReleaseDay returns the date of the last release day, calculated based on // the `releaseHourCheck`-th hour of the previous `releaseDay` weekday.
[ "prevReleaseDay", "returns", "the", "date", "of", "the", "last", "release", "day", "calculated", "based", "on", "the", "releaseHourCheck", "-", "th", "hour", "of", "the", "previous", "releaseDay", "weekday", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L163-L175
1,804
manifoldco/torus-cli
daemon/updates/updates.go
hoursToNextRelease
func (e *Engine) hoursToNextRelease() time.Duration { return e.nextReleaseDay().Sub(e.timeManager.Now()) }
go
func (e *Engine) hoursToNextRelease() time.Duration { return e.nextReleaseDay().Sub(e.timeManager.Now()) }
[ "func", "(", "e", "*", "Engine", ")", "hoursToNextRelease", "(", ")", "time", ".", "Duration", "{", "return", "e", ".", "nextReleaseDay", "(", ")", ".", "Sub", "(", "e", ".", "timeManager", ".", "Now", "(", ")", ")", "\n", "}" ]
// hoursToNextRelease returns the time delta before the next update check.
[ "hoursToNextRelease", "returns", "the", "time", "delta", "before", "the", "next", "update", "check", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L178-L180
1,805
manifoldco/torus-cli
daemon/updates/updates.go
nextReleaseDay
func (e *Engine) nextReleaseDay() time.Time { now := e.timeManager.Now() nextRelease := e.midnight(now).Add(releaseHourCheck * time.Hour) if nextRelease.Weekday() == releaseDay { if nextRelease.Unix() <= now.Unix() { nextRelease = nextRelease.Add(24 * 7 * time.Hour) } return nextRelease } daysDue := int(nextRelease.Weekday()) - int(releaseDay) if daysDue <= 0 { daysDue = -daysDue } else { daysDue = 7 - daysDue } return nextRelease.Add(time.Duration(daysDue*24) * time.Hour) }
go
func (e *Engine) nextReleaseDay() time.Time { now := e.timeManager.Now() nextRelease := e.midnight(now).Add(releaseHourCheck * time.Hour) if nextRelease.Weekday() == releaseDay { if nextRelease.Unix() <= now.Unix() { nextRelease = nextRelease.Add(24 * 7 * time.Hour) } return nextRelease } daysDue := int(nextRelease.Weekday()) - int(releaseDay) if daysDue <= 0 { daysDue = -daysDue } else { daysDue = 7 - daysDue } return nextRelease.Add(time.Duration(daysDue*24) * time.Hour) }
[ "func", "(", "e", "*", "Engine", ")", "nextReleaseDay", "(", ")", "time", ".", "Time", "{", "now", ":=", "e", ".", "timeManager", ".", "Now", "(", ")", "\n", "nextRelease", ":=", "e", ".", "midnight", "(", "now", ")", ".", "Add", "(", "releaseHourCheck", "*", "time", ".", "Hour", ")", "\n", "if", "nextRelease", ".", "Weekday", "(", ")", "==", "releaseDay", "{", "if", "nextRelease", ".", "Unix", "(", ")", "<=", "now", ".", "Unix", "(", ")", "{", "nextRelease", "=", "nextRelease", ".", "Add", "(", "24", "*", "7", "*", "time", ".", "Hour", ")", "\n", "}", "\n", "return", "nextRelease", "\n", "}", "\n\n", "daysDue", ":=", "int", "(", "nextRelease", ".", "Weekday", "(", ")", ")", "-", "int", "(", "releaseDay", ")", "\n", "if", "daysDue", "<=", "0", "{", "daysDue", "=", "-", "daysDue", "\n", "}", "else", "{", "daysDue", "=", "7", "-", "daysDue", "\n", "}", "\n\n", "return", "nextRelease", ".", "Add", "(", "time", ".", "Duration", "(", "daysDue", "*", "24", ")", "*", "time", ".", "Hour", ")", "\n", "}" ]
// nextReleaseDay returns the date of the next release day, calculated based on // the `releaseHourCheck`-th hour of the next `releaseDay` weekday
[ "nextReleaseDay", "returns", "the", "date", "of", "the", "next", "release", "day", "calculated", "based", "on", "the", "releaseHourCheck", "-", "th", "hour", "of", "the", "next", "releaseDay", "weekday" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L184-L202
1,806
manifoldco/torus-cli
daemon/updates/updates.go
midnight
func (e Engine) midnight(t time.Time) time.Time { y, m, d := t.Date() return time.Date(y, m, d, 0, 0, 0, 0, t.Location()) }
go
func (e Engine) midnight(t time.Time) time.Time { y, m, d := t.Date() return time.Date(y, m, d, 0, 0, 0, 0, t.Location()) }
[ "func", "(", "e", "Engine", ")", "midnight", "(", "t", "time", ".", "Time", ")", "time", ".", "Time", "{", "y", ",", "m", ",", "d", ":=", "t", ".", "Date", "(", ")", "\n", "return", "time", ".", "Date", "(", "y", ",", "m", ",", "d", ",", "0", ",", "0", ",", "0", ",", "0", ",", "t", ".", "Location", "(", ")", ")", "\n", "}" ]
// midnight returns the date of the midnight of the provided time.
[ "midnight", "returns", "the", "date", "of", "the", "midnight", "of", "the", "provided", "time", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/updates/updates.go#L205-L208
1,807
manifoldco/torus-cli
envelope/envelope.go
ConvertUser
func ConvertUser(e *Unsigned) (UserInf, error) { var user UserInf switch e.Version { case 1: user = &UserV1{ ID: e.ID, Version: e.Version, Body: e.Body.(*primitive.UserV1), } case 2: user = &User{ ID: e.ID, Version: e.Version, Body: e.Body.(*primitive.User), } default: return nil, fmt.Errorf("Unknown User Schema Version: %d", e.Version) } return user, nil }
go
func ConvertUser(e *Unsigned) (UserInf, error) { var user UserInf switch e.Version { case 1: user = &UserV1{ ID: e.ID, Version: e.Version, Body: e.Body.(*primitive.UserV1), } case 2: user = &User{ ID: e.ID, Version: e.Version, Body: e.Body.(*primitive.User), } default: return nil, fmt.Errorf("Unknown User Schema Version: %d", e.Version) } return user, nil }
[ "func", "ConvertUser", "(", "e", "*", "Unsigned", ")", "(", "UserInf", ",", "error", ")", "{", "var", "user", "UserInf", "\n", "switch", "e", ".", "Version", "{", "case", "1", ":", "user", "=", "&", "UserV1", "{", "ID", ":", "e", ".", "ID", ",", "Version", ":", "e", ".", "Version", ",", "Body", ":", "e", ".", "Body", ".", "(", "*", "primitive", ".", "UserV1", ")", ",", "}", "\n", "case", "2", ":", "user", "=", "&", "User", "{", "ID", ":", "e", ".", "ID", ",", "Version", ":", "e", ".", "Version", ",", "Body", ":", "e", ".", "Body", ".", "(", "*", "primitive", ".", "User", ")", ",", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "e", ".", "Version", ")", "\n", "}", "\n\n", "return", "user", ",", "nil", "\n", "}" ]
// ConvertUser converts an unsigned envelope to a UserInf interface which // provides a common interface for all user versions.
[ "ConvertUser", "converts", "an", "unsigned", "envelope", "to", "a", "UserInf", "interface", "which", "provides", "a", "common", "interface", "for", "all", "user", "versions", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/envelope/envelope.go#L138-L158
1,808
manifoldco/torus-cli
envelope/envelope.go
Unset
func (c *Credential) Unset() bool { return c.Body.State != nil && *c.Body.State == "unset" }
go
func (c *Credential) Unset() bool { return c.Body.State != nil && *c.Body.State == "unset" }
[ "func", "(", "c", "*", "Credential", ")", "Unset", "(", ")", "bool", "{", "return", "c", ".", "Body", ".", "State", "!=", "nil", "&&", "*", "c", ".", "Body", ".", "State", "==", "\"", "\"", "\n", "}" ]
// Unset returns a bool indicating if this Credential has been explicitly unset.
[ "Unset", "returns", "a", "bool", "indicating", "if", "this", "Credential", "has", "been", "explicitly", "unset", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/envelope/envelope.go#L300-L302
1,809
manifoldco/torus-cli
registry/keypairs.go
NewKeypairs
func NewKeypairs() *Keypairs { return &Keypairs{ keypairs: map[identity.ID][]ClaimedKeyPair{}, idIndex: map[identity.ID]ClaimedKeyPair{}, } }
go
func NewKeypairs() *Keypairs { return &Keypairs{ keypairs: map[identity.ID][]ClaimedKeyPair{}, idIndex: map[identity.ID]ClaimedKeyPair{}, } }
[ "func", "NewKeypairs", "(", ")", "*", "Keypairs", "{", "return", "&", "Keypairs", "{", "keypairs", ":", "map", "[", "identity", ".", "ID", "]", "[", "]", "ClaimedKeyPair", "{", "}", ",", "idIndex", ":", "map", "[", "identity", ".", "ID", "]", "ClaimedKeyPair", "{", "}", ",", "}", "\n", "}" ]
// NewKeypairs returns an empty keypairs struct
[ "NewKeypairs", "returns", "an", "empty", "keypairs", "struct" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/keypairs.go#L43-L48
1,810
manifoldco/torus-cli
registry/keypairs.go
Add
func (kp *Keypairs) Add(keypairs ...ClaimedKeyPair) error { for _, k := range keypairs { kp.idIndex[*k.PublicKey.ID] = k orgID := *k.PublicKey.Body.OrgID _, ok := kp.keypairs[orgID] if !ok { kp.keypairs[orgID] = []ClaimedKeyPair{k} continue } kp.keypairs[orgID] = append(kp.keypairs[orgID], k) } return nil }
go
func (kp *Keypairs) Add(keypairs ...ClaimedKeyPair) error { for _, k := range keypairs { kp.idIndex[*k.PublicKey.ID] = k orgID := *k.PublicKey.Body.OrgID _, ok := kp.keypairs[orgID] if !ok { kp.keypairs[orgID] = []ClaimedKeyPair{k} continue } kp.keypairs[orgID] = append(kp.keypairs[orgID], k) } return nil }
[ "func", "(", "kp", "*", "Keypairs", ")", "Add", "(", "keypairs", "...", "ClaimedKeyPair", ")", "error", "{", "for", "_", ",", "k", ":=", "range", "keypairs", "{", "kp", ".", "idIndex", "[", "*", "k", ".", "PublicKey", ".", "ID", "]", "=", "k", "\n\n", "orgID", ":=", "*", "k", ".", "PublicKey", ".", "Body", ".", "OrgID", "\n", "_", ",", "ok", ":=", "kp", ".", "keypairs", "[", "orgID", "]", "\n", "if", "!", "ok", "{", "kp", ".", "keypairs", "[", "orgID", "]", "=", "[", "]", "ClaimedKeyPair", "{", "k", "}", "\n", "continue", "\n", "}", "\n\n", "kp", ".", "keypairs", "[", "orgID", "]", "=", "append", "(", "kp", ".", "keypairs", "[", "orgID", "]", ",", "k", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Add adds the given keypairs to the list of keypairs
[ "Add", "adds", "the", "given", "keypairs", "to", "the", "list", "of", "keypairs" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/keypairs.go#L51-L66
1,811
manifoldco/torus-cli
registry/keypairs.go
Get
func (kp *Keypairs) Get(publicKeyID *identity.ID) (*ClaimedKeyPair, error) { if publicKeyID == nil { return nil, errors.New("Invalid PublicKeyID provided to get keypair") } ckp, ok := kp.idIndex[*publicKeyID] if !ok { return nil, ErrPublicKeyNotFound } return &ckp, nil }
go
func (kp *Keypairs) Get(publicKeyID *identity.ID) (*ClaimedKeyPair, error) { if publicKeyID == nil { return nil, errors.New("Invalid PublicKeyID provided to get keypair") } ckp, ok := kp.idIndex[*publicKeyID] if !ok { return nil, ErrPublicKeyNotFound } return &ckp, nil }
[ "func", "(", "kp", "*", "Keypairs", ")", "Get", "(", "publicKeyID", "*", "identity", ".", "ID", ")", "(", "*", "ClaimedKeyPair", ",", "error", ")", "{", "if", "publicKeyID", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ckp", ",", "ok", ":=", "kp", ".", "idIndex", "[", "*", "publicKeyID", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "ErrPublicKeyNotFound", "\n", "}", "\n\n", "return", "&", "ckp", ",", "nil", "\n", "}" ]
// Get returns the ClaimedKeyPair for the given public key id
[ "Get", "returns", "the", "ClaimedKeyPair", "for", "the", "given", "public", "key", "id" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/keypairs.go#L69-L80
1,812
manifoldco/torus-cli
registry/keypairs.go
All
func (kp *Keypairs) All() []ClaimedKeyPair { out := []ClaimedKeyPair{} for _, ckp := range kp.idIndex { out = append(out, ckp) } return out }
go
func (kp *Keypairs) All() []ClaimedKeyPair { out := []ClaimedKeyPair{} for _, ckp := range kp.idIndex { out = append(out, ckp) } return out }
[ "func", "(", "kp", "*", "Keypairs", ")", "All", "(", ")", "[", "]", "ClaimedKeyPair", "{", "out", ":=", "[", "]", "ClaimedKeyPair", "{", "}", "\n", "for", "_", ",", "ckp", ":=", "range", "kp", ".", "idIndex", "{", "out", "=", "append", "(", "out", ",", "ckp", ")", "\n", "}", "\n\n", "return", "out", "\n", "}" ]
// All returns all keypairs including those which have been revoked.
[ "All", "returns", "all", "keypairs", "including", "those", "which", "have", "been", "revoked", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/keypairs.go#L105-L112
1,813
manifoldco/torus-cli
registry/keypairs.go
Create
func (k *KeyPairsClient) Create(ctx context.Context, pubKey *envelope.PublicKey, privKey *envelope.PrivateKey, claim *envelope.Claim) (*envelope.PublicKey, *envelope.PrivateKey, []envelope.Claim, error) { req := ClaimedKeyPair{ PublicKeySegment: apitypes.PublicKeySegment{ PublicKey: pubKey, Claims: []envelope.Claim{*claim}, }, PrivateKey: privKey, } resp := ClaimedKeyPair{} err := k.client.RoundTrip(ctx, "POST", "/keypairs", nil, &req, &resp) if err != nil { return nil, nil, nil, err } return resp.PublicKey, resp.PrivateKey, resp.Claims, nil }
go
func (k *KeyPairsClient) Create(ctx context.Context, pubKey *envelope.PublicKey, privKey *envelope.PrivateKey, claim *envelope.Claim) (*envelope.PublicKey, *envelope.PrivateKey, []envelope.Claim, error) { req := ClaimedKeyPair{ PublicKeySegment: apitypes.PublicKeySegment{ PublicKey: pubKey, Claims: []envelope.Claim{*claim}, }, PrivateKey: privKey, } resp := ClaimedKeyPair{} err := k.client.RoundTrip(ctx, "POST", "/keypairs", nil, &req, &resp) if err != nil { return nil, nil, nil, err } return resp.PublicKey, resp.PrivateKey, resp.Claims, nil }
[ "func", "(", "k", "*", "KeyPairsClient", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "pubKey", "*", "envelope", ".", "PublicKey", ",", "privKey", "*", "envelope", ".", "PrivateKey", ",", "claim", "*", "envelope", ".", "Claim", ")", "(", "*", "envelope", ".", "PublicKey", ",", "*", "envelope", ".", "PrivateKey", ",", "[", "]", "envelope", ".", "Claim", ",", "error", ")", "{", "req", ":=", "ClaimedKeyPair", "{", "PublicKeySegment", ":", "apitypes", ".", "PublicKeySegment", "{", "PublicKey", ":", "pubKey", ",", "Claims", ":", "[", "]", "envelope", ".", "Claim", "{", "*", "claim", "}", ",", "}", ",", "PrivateKey", ":", "privKey", ",", "}", "\n", "resp", ":=", "ClaimedKeyPair", "{", "}", "\n", "err", ":=", "k", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "&", "req", ",", "&", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "resp", ".", "PublicKey", ",", "resp", ".", "PrivateKey", ",", "resp", ".", "Claims", ",", "nil", "\n", "}" ]
// Create creates a new keypair on the registry. // // The keypair includes the user's public key, private key, and a self-signed // claim on the public key. // // keys may be either signing or encryption keys.
[ "Create", "creates", "a", "new", "keypair", "on", "the", "registry", ".", "The", "keypair", "includes", "the", "user", "s", "public", "key", "private", "key", "and", "a", "self", "-", "signed", "claim", "on", "the", "public", "key", ".", "keys", "may", "be", "either", "signing", "or", "encryption", "keys", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/keypairs.go#L133-L151
1,814
manifoldco/torus-cli
registry/keypairs.go
List
func (k *KeyPairsClient) List(ctx context.Context, orgID *identity.ID) (*Keypairs, error) { query := &url.Values{} if orgID != nil { query.Set("org_id", orgID.String()) } var resp []ClaimedKeyPair err := k.client.RoundTrip(ctx, "GET", "/keypairs", query, nil, &resp) if err != nil { return nil, err } kp := NewKeypairs() err = kp.Add(resp...) if err != nil { return nil, err } return kp, nil }
go
func (k *KeyPairsClient) List(ctx context.Context, orgID *identity.ID) (*Keypairs, error) { query := &url.Values{} if orgID != nil { query.Set("org_id", orgID.String()) } var resp []ClaimedKeyPair err := k.client.RoundTrip(ctx, "GET", "/keypairs", query, nil, &resp) if err != nil { return nil, err } kp := NewKeypairs() err = kp.Add(resp...) if err != nil { return nil, err } return kp, nil }
[ "func", "(", "k", "*", "KeyPairsClient", ")", "List", "(", "ctx", "context", ".", "Context", ",", "orgID", "*", "identity", ".", "ID", ")", "(", "*", "Keypairs", ",", "error", ")", "{", "query", ":=", "&", "url", ".", "Values", "{", "}", "\n", "if", "orgID", "!=", "nil", "{", "query", ".", "Set", "(", "\"", "\"", ",", "orgID", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "var", "resp", "[", "]", "ClaimedKeyPair", "\n", "err", ":=", "k", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "query", ",", "nil", ",", "&", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "kp", ":=", "NewKeypairs", "(", ")", "\n", "err", "=", "kp", ".", "Add", "(", "resp", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "kp", ",", "nil", "\n", "}" ]
// List returns all KeyPairs for the logged in user in the given, or all orgs // if orgID is nil.
[ "List", "returns", "all", "KeyPairs", "for", "the", "logged", "in", "user", "in", "the", "given", "or", "all", "orgs", "if", "orgID", "is", "nil", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/keypairs.go#L155-L174
1,815
manifoldco/torus-cli
cmd/machines.go
bootstrapCmd
func bootstrapCmd(ctx *cli.Context) error { cloud := ctx.String("auth") resp, err := bootstrap.Do( bootstrap.Provider(cloud), ctx.String("url"), ctx.String("machine"), ctx.String("org"), ctx.String("role"), ctx.String("ca"), ) if err != nil { return fmt.Errorf("bootstrap provision failed: %s", err) } envFile := filepath.Join(GlobalRoot, EnvironmentFile) err = writeEnvironmentFile(resp.Token, resp.Secret) if err != nil { return fmt.Errorf("failed to write environment file[%s]: %s", envFile, err) } fmt.Printf("Machine bootstrapped. Environment configuration saved in %s\n", envFile) return nil }
go
func bootstrapCmd(ctx *cli.Context) error { cloud := ctx.String("auth") resp, err := bootstrap.Do( bootstrap.Provider(cloud), ctx.String("url"), ctx.String("machine"), ctx.String("org"), ctx.String("role"), ctx.String("ca"), ) if err != nil { return fmt.Errorf("bootstrap provision failed: %s", err) } envFile := filepath.Join(GlobalRoot, EnvironmentFile) err = writeEnvironmentFile(resp.Token, resp.Secret) if err != nil { return fmt.Errorf("failed to write environment file[%s]: %s", envFile, err) } fmt.Printf("Machine bootstrapped. Environment configuration saved in %s\n", envFile) return nil }
[ "func", "bootstrapCmd", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "cloud", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n\n", "resp", ",", "err", ":=", "bootstrap", ".", "Do", "(", "bootstrap", ".", "Provider", "(", "cloud", ")", ",", "ctx", ".", "String", "(", "\"", "\"", ")", ",", "ctx", ".", "String", "(", "\"", "\"", ")", ",", "ctx", ".", "String", "(", "\"", "\"", ")", ",", "ctx", ".", "String", "(", "\"", "\"", ")", ",", "ctx", ".", "String", "(", "\"", "\"", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "envFile", ":=", "filepath", ".", "Join", "(", "GlobalRoot", ",", "EnvironmentFile", ")", "\n", "err", "=", "writeEnvironmentFile", "(", "resp", ".", "Token", ",", "resp", ".", "Secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "envFile", ",", "err", ")", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "envFile", ")", "\n", "return", "nil", "\n", "}" ]
// bootstrapCmd is the cli.Command for Bootstrapping machine configuration from the Gatekeeper
[ "bootstrapCmd", "is", "the", "cli", ".", "Command", "for", "Bootstrapping", "machine", "configuration", "from", "the", "Gatekeeper" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/machines.go#L446-L469
1,816
manifoldco/torus-cli
registry/machines.go
Create
func (m *MachinesClient) Create(ctx context.Context, machine *envelope.Machine, memberships []envelope.Membership, token *MachineTokenCreationSegment) (*apitypes.MachineSegment, error) { segment := MachineCreationSegment{ MachineSegment: apitypes.MachineSegment{ Machine: machine, Memberships: memberships, }, Tokens: []MachineTokenCreationSegment{*token}, } resp := &apitypes.MachineSegment{} err := m.client.RoundTrip(ctx, "POST", "/machines", nil, &segment, &resp) return resp, err }
go
func (m *MachinesClient) Create(ctx context.Context, machine *envelope.Machine, memberships []envelope.Membership, token *MachineTokenCreationSegment) (*apitypes.MachineSegment, error) { segment := MachineCreationSegment{ MachineSegment: apitypes.MachineSegment{ Machine: machine, Memberships: memberships, }, Tokens: []MachineTokenCreationSegment{*token}, } resp := &apitypes.MachineSegment{} err := m.client.RoundTrip(ctx, "POST", "/machines", nil, &segment, &resp) return resp, err }
[ "func", "(", "m", "*", "MachinesClient", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "machine", "*", "envelope", ".", "Machine", ",", "memberships", "[", "]", "envelope", ".", "Membership", ",", "token", "*", "MachineTokenCreationSegment", ")", "(", "*", "apitypes", ".", "MachineSegment", ",", "error", ")", "{", "segment", ":=", "MachineCreationSegment", "{", "MachineSegment", ":", "apitypes", ".", "MachineSegment", "{", "Machine", ":", "machine", ",", "Memberships", ":", "memberships", ",", "}", ",", "Tokens", ":", "[", "]", "MachineTokenCreationSegment", "{", "*", "token", "}", ",", "}", "\n\n", "resp", ":=", "&", "apitypes", ".", "MachineSegment", "{", "}", "\n", "err", ":=", "m", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "&", "segment", ",", "&", "resp", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Create requests the registry to create a MachineSegment. // // The MachineSegment includes the Machine, it's Memberships, and authorization // tokens.
[ "Create", "requests", "the", "registry", "to", "create", "a", "MachineSegment", ".", "The", "MachineSegment", "includes", "the", "Machine", "it", "s", "Memberships", "and", "authorization", "tokens", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/machines.go#L36-L50
1,817
manifoldco/torus-cli
registry/machines.go
Get
func (m *MachinesClient) Get(ctx context.Context, machineID *identity.ID) (*apitypes.MachineSegment, error) { resp := &apitypes.MachineSegment{} err := m.client.RoundTrip(ctx, "GET", "/machines/"+(*machineID).String(), nil, nil, &resp) return resp, err }
go
func (m *MachinesClient) Get(ctx context.Context, machineID *identity.ID) (*apitypes.MachineSegment, error) { resp := &apitypes.MachineSegment{} err := m.client.RoundTrip(ctx, "GET", "/machines/"+(*machineID).String(), nil, nil, &resp) return resp, err }
[ "func", "(", "m", "*", "MachinesClient", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "machineID", "*", "identity", ".", "ID", ")", "(", "*", "apitypes", ".", "MachineSegment", ",", "error", ")", "{", "resp", ":=", "&", "apitypes", ".", "MachineSegment", "{", "}", "\n", "err", ":=", "m", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", "+", "(", "*", "machineID", ")", ".", "String", "(", ")", ",", "nil", ",", "nil", ",", "&", "resp", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Get requests a single machine from the registry
[ "Get", "requests", "a", "single", "machine", "from", "the", "registry" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/machines.go#L53-L57
1,818
manifoldco/torus-cli
registry/machines.go
List
func (m *MachinesClient) List(ctx context.Context, orgID *identity.ID, state *string, name *string, teamID *identity.ID) ([]apitypes.MachineSegment, error) { v := &url.Values{} if orgID != nil { v.Add("org_id", (*orgID).String()) } if state != nil { v.Add("state", *state) } if teamID != nil { v.Add("team_id", (*teamID).String()) } if name != nil { v.Add("name", *name) } var results []apitypes.MachineSegment err := m.client.RoundTrip(ctx, "GET", "/machines", v, nil, &results) return results, err }
go
func (m *MachinesClient) List(ctx context.Context, orgID *identity.ID, state *string, name *string, teamID *identity.ID) ([]apitypes.MachineSegment, error) { v := &url.Values{} if orgID != nil { v.Add("org_id", (*orgID).String()) } if state != nil { v.Add("state", *state) } if teamID != nil { v.Add("team_id", (*teamID).String()) } if name != nil { v.Add("name", *name) } var results []apitypes.MachineSegment err := m.client.RoundTrip(ctx, "GET", "/machines", v, nil, &results) return results, err }
[ "func", "(", "m", "*", "MachinesClient", ")", "List", "(", "ctx", "context", ".", "Context", ",", "orgID", "*", "identity", ".", "ID", ",", "state", "*", "string", ",", "name", "*", "string", ",", "teamID", "*", "identity", ".", "ID", ")", "(", "[", "]", "apitypes", ".", "MachineSegment", ",", "error", ")", "{", "v", ":=", "&", "url", ".", "Values", "{", "}", "\n", "if", "orgID", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "(", "*", "orgID", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "state", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "*", "state", ")", "\n", "}", "\n", "if", "teamID", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "(", "*", "teamID", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "name", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "*", "name", ")", "\n", "}", "\n\n", "var", "results", "[", "]", "apitypes", ".", "MachineSegment", "\n", "err", ":=", "m", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "v", ",", "nil", ",", "&", "results", ")", "\n", "return", "results", ",", "err", "\n", "}" ]
// List machines in the given org and state
[ "List", "machines", "in", "the", "given", "org", "and", "state" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/machines.go#L60-L78
1,819
manifoldco/torus-cli
registry/machines.go
Destroy
func (m *MachinesClient) Destroy(ctx context.Context, machineID *identity.ID) error { return m.client.RoundTrip(ctx, "DELETE", "/machines/"+machineID.String(), nil, nil, nil) }
go
func (m *MachinesClient) Destroy(ctx context.Context, machineID *identity.ID) error { return m.client.RoundTrip(ctx, "DELETE", "/machines/"+machineID.String(), nil, nil, nil) }
[ "func", "(", "m", "*", "MachinesClient", ")", "Destroy", "(", "ctx", "context", ".", "Context", ",", "machineID", "*", "identity", ".", "ID", ")", "error", "{", "return", "m", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", "+", "machineID", ".", "String", "(", ")", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "}" ]
// Destroy machine by ID
[ "Destroy", "machine", "by", "ID" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/machines.go#L81-L83
1,820
manifoldco/torus-cli
registry/profiles.go
ListByName
func (p *ProfilesClient) ListByName(ctx context.Context, name string) (*apitypes.Profile, error) { result := &apitypes.Profile{} err := p.client.RoundTrip(ctx, "GET", "/profiles/"+name, nil, nil, &result) return result, err }
go
func (p *ProfilesClient) ListByName(ctx context.Context, name string) (*apitypes.Profile, error) { result := &apitypes.Profile{} err := p.client.RoundTrip(ctx, "GET", "/profiles/"+name, nil, nil, &result) return result, err }
[ "func", "(", "p", "*", "ProfilesClient", ")", "ListByName", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "(", "*", "apitypes", ".", "Profile", ",", "error", ")", "{", "result", ":=", "&", "apitypes", ".", "Profile", "{", "}", "\n", "err", ":=", "p", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", "+", "name", ",", "nil", ",", "nil", ",", "&", "result", ")", "\n", "return", "result", ",", "err", "\n", "}" ]
// ListByName returns profiles looked up by username
[ "ListByName", "returns", "profiles", "looked", "up", "by", "username" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/profiles.go#L17-L21
1,821
manifoldco/torus-cli
registry/profiles.go
ListByID
func (p *ProfilesClient) ListByID(ctx context.Context, userIDs []identity.ID) ([]apitypes.Profile, error) { v := &url.Values{} for _, id := range userIDs { v.Add("id", id.String()) } var results []apitypes.Profile err := p.client.RoundTrip(ctx, "GET", "/profiles", v, nil, &results) return results, err }
go
func (p *ProfilesClient) ListByID(ctx context.Context, userIDs []identity.ID) ([]apitypes.Profile, error) { v := &url.Values{} for _, id := range userIDs { v.Add("id", id.String()) } var results []apitypes.Profile err := p.client.RoundTrip(ctx, "GET", "/profiles", v, nil, &results) return results, err }
[ "func", "(", "p", "*", "ProfilesClient", ")", "ListByID", "(", "ctx", "context", ".", "Context", ",", "userIDs", "[", "]", "identity", ".", "ID", ")", "(", "[", "]", "apitypes", ".", "Profile", ",", "error", ")", "{", "v", ":=", "&", "url", ".", "Values", "{", "}", "\n", "for", "_", ",", "id", ":=", "range", "userIDs", "{", "v", ".", "Add", "(", "\"", "\"", ",", "id", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "var", "results", "[", "]", "apitypes", ".", "Profile", "\n", "err", ":=", "p", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "v", ",", "nil", ",", "&", "results", ")", "\n", "return", "results", ",", "err", "\n", "}" ]
// ListByID returns profiles looked up by User ID
[ "ListByID", "returns", "profiles", "looked", "up", "by", "User", "ID" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/profiles.go#L24-L33
1,822
manifoldco/torus-cli
cmd/daemon.go
stopDaemon
func stopDaemon(proc *os.Process) (bool, error) { err := proc.Signal(syscall.Signal(syscall.SIGTERM)) if err == nil { // no need to wait for the SIGTERM if the signal failed increment := 50 * time.Millisecond for d := increment; d < 3*time.Second; d += increment { time.Sleep(d) if _, err := findProcess(proc.Pid); err != nil { return true, nil } } } err = proc.Kill() if err != nil { return false, errs.NewErrorExitError("Could not stop daemon.", err) } return false, nil }
go
func stopDaemon(proc *os.Process) (bool, error) { err := proc.Signal(syscall.Signal(syscall.SIGTERM)) if err == nil { // no need to wait for the SIGTERM if the signal failed increment := 50 * time.Millisecond for d := increment; d < 3*time.Second; d += increment { time.Sleep(d) if _, err := findProcess(proc.Pid); err != nil { return true, nil } } } err = proc.Kill() if err != nil { return false, errs.NewErrorExitError("Could not stop daemon.", err) } return false, nil }
[ "func", "stopDaemon", "(", "proc", "*", "os", ".", "Process", ")", "(", "bool", ",", "error", ")", "{", "err", ":=", "proc", ".", "Signal", "(", "syscall", ".", "Signal", "(", "syscall", ".", "SIGTERM", ")", ")", "\n\n", "if", "err", "==", "nil", "{", "// no need to wait for the SIGTERM if the signal failed", "increment", ":=", "50", "*", "time", ".", "Millisecond", "\n", "for", "d", ":=", "increment", ";", "d", "<", "3", "*", "time", ".", "Second", ";", "d", "+=", "increment", "{", "time", ".", "Sleep", "(", "d", ")", "\n", "if", "_", ",", "err", ":=", "findProcess", "(", "proc", ".", "Pid", ")", ";", "err", "!=", "nil", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "err", "=", "proc", ".", "Kill", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errs", ".", "NewErrorExitError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "}" ]
// stopDaemon stops the daemon process. It returns a bool indicating if the // shutdown was graceful.
[ "stopDaemon", "stops", "the", "daemon", "process", ".", "It", "returns", "a", "bool", "indicating", "if", "the", "shutdown", "was", "graceful", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/daemon.go#L240-L259
1,823
manifoldco/torus-cli
cmd/daemon.go
findDaemon
func findDaemon(cfg *config.Config) (*os.Process, error) { lock, err := lockfile.New(cfg.PidPath) if err != nil { return nil, err } proc, err := lock.GetOwner() if err != nil { // happy path cases. the pid doesn't exist, or it contains garbage, // or the previous owner is gone. if os.IsNotExist(err) || err == lockfile.ErrInvalidPid || err == lockfile.ErrDeadOwner { return nil, nil } return nil, err } return proc, nil }
go
func findDaemon(cfg *config.Config) (*os.Process, error) { lock, err := lockfile.New(cfg.PidPath) if err != nil { return nil, err } proc, err := lock.GetOwner() if err != nil { // happy path cases. the pid doesn't exist, or it contains garbage, // or the previous owner is gone. if os.IsNotExist(err) || err == lockfile.ErrInvalidPid || err == lockfile.ErrDeadOwner { return nil, nil } return nil, err } return proc, nil }
[ "func", "findDaemon", "(", "cfg", "*", "config", ".", "Config", ")", "(", "*", "os", ".", "Process", ",", "error", ")", "{", "lock", ",", "err", ":=", "lockfile", ".", "New", "(", "cfg", ".", "PidPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "proc", ",", "err", ":=", "lock", ".", "GetOwner", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// happy path cases. the pid doesn't exist, or it contains garbage,", "// or the previous owner is gone.", "if", "os", ".", "IsNotExist", "(", "err", ")", "||", "err", "==", "lockfile", ".", "ErrInvalidPid", "||", "err", "==", "lockfile", ".", "ErrDeadOwner", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "proc", ",", "nil", "\n", "}" ]
// findDaemon returns an os.Process for a running daemon, or nil if it is not // running. It returns an error if the pid file location is invalid in the // config, or there was an error reading the pid file.
[ "findDaemon", "returns", "an", "os", ".", "Process", "for", "a", "running", "daemon", "or", "nil", "if", "it", "is", "not", "running", ".", "It", "returns", "an", "error", "if", "the", "pid", "file", "location", "is", "invalid", "in", "the", "config", "or", "there", "was", "an", "error", "reading", "the", "pid", "file", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/daemon.go#L264-L282
1,824
manifoldco/torus-cli
daemon/session/session.go
NewSession
func NewSession(guard *secure.Guard) Session { return &session{ mutex: &sync.Mutex{}, sessionType: apitypes.NotLoggedIn, guard: guard, } }
go
func NewSession(guard *secure.Guard) Session { return &session{ mutex: &sync.Mutex{}, sessionType: apitypes.NotLoggedIn, guard: guard, } }
[ "func", "NewSession", "(", "guard", "*", "secure", ".", "Guard", ")", "Session", "{", "return", "&", "session", "{", "mutex", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "sessionType", ":", "apitypes", ".", "NotLoggedIn", ",", "guard", ":", "guard", ",", "}", "\n", "}" ]
// NewSession returns the default implementation of the Session interface // for a user or machine depending on the passed type.
[ "NewSession", "returns", "the", "default", "implementation", "of", "the", "Session", "interface", "for", "a", "user", "or", "machine", "depending", "on", "the", "passed", "type", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L52-L58
1,825
manifoldco/torus-cli
daemon/session/session.go
Token
func (s *session) Token() []byte { s.mutex.Lock() defer s.mutex.Unlock() return s.token.Buffer() }
go
func (s *session) Token() []byte { s.mutex.Lock() defer s.mutex.Unlock() return s.token.Buffer() }
[ "func", "(", "s", "*", "session", ")", "Token", "(", ")", "[", "]", "byte", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "s", ".", "token", ".", "Buffer", "(", ")", "\n", "}" ]
// Token returns the auth token stored in this session.
[ "Token", "returns", "the", "auth", "token", "stored", "in", "this", "session", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L93-L98
1,826
manifoldco/torus-cli
daemon/session/session.go
Passphrase
func (s *session) Passphrase() []byte { s.mutex.Lock() defer s.mutex.Unlock() return s.passphrase.Buffer() }
go
func (s *session) Passphrase() []byte { s.mutex.Lock() defer s.mutex.Unlock() return s.passphrase.Buffer() }
[ "func", "(", "s", "*", "session", ")", "Passphrase", "(", ")", "[", "]", "byte", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "s", ".", "passphrase", ".", "Buffer", "(", ")", "\n", "}" ]
// Passphrase returns the user's passphrase.
[ "Passphrase", "returns", "the", "user", "s", "passphrase", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L101-L106
1,827
manifoldco/torus-cli
daemon/session/session.go
Set
func (s *session) Set(sessionType apitypes.SessionType, identity, auth envelope.Envelope, passphrase []byte, token []byte) error { s.mutex.Lock() defer s.mutex.Unlock() err := checkSessionType(sessionType, identity, auth) if err != nil { return err } if len(passphrase) == 0 { return errors.New("Passphrase must not be empty") } if len(token) == 0 && sessionType == apitypes.UserSession { return errors.New("Token must not be empty") } s.sessionType = sessionType s.passphrase, err = s.guard.Secret(passphrase) if err != nil { return err } s.token, err = s.guard.Secret(token) if err != nil { return err } s.identity = identity s.auth = auth return nil }
go
func (s *session) Set(sessionType apitypes.SessionType, identity, auth envelope.Envelope, passphrase []byte, token []byte) error { s.mutex.Lock() defer s.mutex.Unlock() err := checkSessionType(sessionType, identity, auth) if err != nil { return err } if len(passphrase) == 0 { return errors.New("Passphrase must not be empty") } if len(token) == 0 && sessionType == apitypes.UserSession { return errors.New("Token must not be empty") } s.sessionType = sessionType s.passphrase, err = s.guard.Secret(passphrase) if err != nil { return err } s.token, err = s.guard.Secret(token) if err != nil { return err } s.identity = identity s.auth = auth return nil }
[ "func", "(", "s", "*", "session", ")", "Set", "(", "sessionType", "apitypes", ".", "SessionType", ",", "identity", ",", "auth", "envelope", ".", "Envelope", ",", "passphrase", "[", "]", "byte", ",", "token", "[", "]", "byte", ")", "error", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "err", ":=", "checkSessionType", "(", "sessionType", ",", "identity", ",", "auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "len", "(", "passphrase", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "token", ")", "==", "0", "&&", "sessionType", "==", "apitypes", ".", "UserSession", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "s", ".", "sessionType", "=", "sessionType", "\n", "s", ".", "passphrase", ",", "err", "=", "s", ".", "guard", ".", "Secret", "(", "passphrase", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "token", ",", "err", "=", "s", ".", "guard", ".", "Secret", "(", "token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "identity", "=", "identity", "\n", "s", ".", "auth", "=", "auth", "\n\n", "return", "nil", "\n", "}" ]
// Set atomically sets all relevant session details. // // It returns an error if any values are empty.
[ "Set", "atomically", "sets", "all", "relevant", "session", "details", ".", "It", "returns", "an", "error", "if", "any", "values", "are", "empty", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L156-L189
1,828
manifoldco/torus-cli
daemon/session/session.go
SetIdentity
func (s *session) SetIdentity(sessionType apitypes.SessionType, identity, auth envelope.Envelope) error { s.mutex.Lock() defer s.mutex.Unlock() err := checkSessionType(sessionType, identity, auth) if err != nil { return err } s.identity = identity s.auth = auth return nil }
go
func (s *session) SetIdentity(sessionType apitypes.SessionType, identity, auth envelope.Envelope) error { s.mutex.Lock() defer s.mutex.Unlock() err := checkSessionType(sessionType, identity, auth) if err != nil { return err } s.identity = identity s.auth = auth return nil }
[ "func", "(", "s", "*", "session", ")", "SetIdentity", "(", "sessionType", "apitypes", ".", "SessionType", ",", "identity", ",", "auth", "envelope", ".", "Envelope", ")", "error", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "err", ":=", "checkSessionType", "(", "sessionType", ",", "identity", ",", "auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "identity", "=", "identity", "\n", "s", ".", "auth", "=", "auth", "\n\n", "return", "nil", "\n", "}" ]
// SetIdentity updates the session identity
[ "SetIdentity", "updates", "the", "session", "identity" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L192-L205
1,829
manifoldco/torus-cli
daemon/session/session.go
MasterKey
func (s *session) MasterKey() (*base64.Value, error) { s.mutex.Lock() defer s.mutex.Unlock() if s.Type() == apitypes.NotLoggedIn { return nil, createNotLoggedInError() } if s.Type() == apitypes.UserSession { return s.auth.(envelope.UserInf).Master().Value, nil } return s.auth.(*envelope.MachineToken).Body.Master.Value, nil }
go
func (s *session) MasterKey() (*base64.Value, error) { s.mutex.Lock() defer s.mutex.Unlock() if s.Type() == apitypes.NotLoggedIn { return nil, createNotLoggedInError() } if s.Type() == apitypes.UserSession { return s.auth.(envelope.UserInf).Master().Value, nil } return s.auth.(*envelope.MachineToken).Body.Master.Value, nil }
[ "func", "(", "s", "*", "session", ")", "MasterKey", "(", ")", "(", "*", "base64", ".", "Value", ",", "error", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "Type", "(", ")", "==", "apitypes", ".", "NotLoggedIn", "{", "return", "nil", ",", "createNotLoggedInError", "(", ")", "\n", "}", "\n\n", "if", "s", ".", "Type", "(", ")", "==", "apitypes", ".", "UserSession", "{", "return", "s", ".", "auth", ".", "(", "envelope", ".", "UserInf", ")", ".", "Master", "(", ")", ".", "Value", ",", "nil", "\n", "}", "\n\n", "return", "s", ".", "auth", ".", "(", "*", "envelope", ".", "MachineToken", ")", ".", "Body", ".", "Master", ".", "Value", ",", "nil", "\n", "}" ]
// Returns the base64 representation of the identities encrypted master key
[ "Returns", "the", "base64", "representation", "of", "the", "identities", "encrypted", "master", "key" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L215-L228
1,830
manifoldco/torus-cli
daemon/session/session.go
Self
func (s *session) Self() *apitypes.Self { return &apitypes.Self{ Type: s.Type(), Identity: s.identity, Auth: s.auth, } }
go
func (s *session) Self() *apitypes.Self { return &apitypes.Self{ Type: s.Type(), Identity: s.identity, Auth: s.auth, } }
[ "func", "(", "s", "*", "session", ")", "Self", "(", ")", "*", "apitypes", ".", "Self", "{", "return", "&", "apitypes", ".", "Self", "{", "Type", ":", "s", ".", "Type", "(", ")", ",", "Identity", ":", "s", ".", "identity", ",", "Auth", ":", "s", ".", "auth", ",", "}", "\n", "}" ]
// Self returns the Self apitype which represents the current sessions state
[ "Self", "returns", "the", "Self", "apitype", "which", "represents", "the", "current", "sessions", "state" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L231-L237
1,831
manifoldco/torus-cli
daemon/session/session.go
Logout
func (s *session) Logout() error { s.mutex.Lock() defer s.mutex.Unlock() if s.Type() == apitypes.NotLoggedIn { return createNotLoggedInError() } s.sessionType = apitypes.NotLoggedIn s.identity = nil s.auth = nil s.token.Destroy() s.passphrase.Destroy() s.token = nil s.passphrase = nil return nil }
go
func (s *session) Logout() error { s.mutex.Lock() defer s.mutex.Unlock() if s.Type() == apitypes.NotLoggedIn { return createNotLoggedInError() } s.sessionType = apitypes.NotLoggedIn s.identity = nil s.auth = nil s.token.Destroy() s.passphrase.Destroy() s.token = nil s.passphrase = nil return nil }
[ "func", "(", "s", "*", "session", ")", "Logout", "(", ")", "error", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "Type", "(", ")", "==", "apitypes", ".", "NotLoggedIn", "{", "return", "createNotLoggedInError", "(", ")", "\n", "}", "\n\n", "s", ".", "sessionType", "=", "apitypes", ".", "NotLoggedIn", "\n", "s", ".", "identity", "=", "nil", "\n", "s", ".", "auth", "=", "nil", "\n\n", "s", ".", "token", ".", "Destroy", "(", ")", "\n", "s", ".", "passphrase", ".", "Destroy", "(", ")", "\n", "s", ".", "token", "=", "nil", "\n", "s", ".", "passphrase", "=", "nil", "\n\n", "return", "nil", "\n", "}" ]
// Logout resets all values to the logged out state
[ "Logout", "resets", "all", "values", "to", "the", "logged", "out", "state" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/session/session.go#L240-L258
1,832
manifoldco/torus-cli
ui/ui.go
Init
func Init(preferences *prefs.Preferences) { enableColours := preferences.Core.EnableColors if !Attached() { enableColours = false } defUI = &UI{ Indent: 0, Cols: screenWidth(), EnableProgress: preferences.Core.EnableProgress, EnableHints: preferences.Core.EnableHints, EnableColors: enableColours, } }
go
func Init(preferences *prefs.Preferences) { enableColours := preferences.Core.EnableColors if !Attached() { enableColours = false } defUI = &UI{ Indent: 0, Cols: screenWidth(), EnableProgress: preferences.Core.EnableProgress, EnableHints: preferences.Core.EnableHints, EnableColors: enableColours, } }
[ "func", "Init", "(", "preferences", "*", "prefs", ".", "Preferences", ")", "{", "enableColours", ":=", "preferences", ".", "Core", ".", "EnableColors", "\n\n", "if", "!", "Attached", "(", ")", "{", "enableColours", "=", "false", "\n", "}", "\n\n", "defUI", "=", "&", "UI", "{", "Indent", ":", "0", ",", "Cols", ":", "screenWidth", "(", ")", ",", "EnableProgress", ":", "preferences", ".", "Core", ".", "EnableProgress", ",", "EnableHints", ":", "preferences", ".", "Core", ".", "EnableHints", ",", "EnableColors", ":", "enableColours", ",", "}", "\n", "}" ]
// Init initializes a default global UI, accessible via the package functions.
[ "Init", "initializes", "a", "default", "global", "UI", "accessible", "via", "the", "package", "functions", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L23-L38
1,833
manifoldco/torus-cli
ui/ui.go
Line
func (u *UI) Line(format string, a ...interface{}) { u.LineIndent(0, format, a...) }
go
func (u *UI) Line(format string, a ...interface{}) { u.LineIndent(0, format, a...) }
[ "func", "(", "u", "*", "UI", ")", "Line", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "u", ".", "LineIndent", "(", "0", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Line writes a formatted string followed by a newline to stdout. Output is // word wrapped, and terminated by a newline.
[ "Line", "writes", "a", "formatted", "string", "followed", "by", "a", "newline", "to", "stdout", ".", "Output", "is", "word", "wrapped", "and", "terminated", "by", "a", "newline", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L74-L76
1,834
manifoldco/torus-cli
ui/ui.go
LineIndent
func (u *UI) LineIndent(indent int, format string, a ...interface{}) { o := fmt.Sprintf(format, a...) fmt.Fprintln(readline.Stdout, ansiwrap.WrapIndent(o, u.Cols, u.Indent, u.Indent+indent)) }
go
func (u *UI) LineIndent(indent int, format string, a ...interface{}) { o := fmt.Sprintf(format, a...) fmt.Fprintln(readline.Stdout, ansiwrap.WrapIndent(o, u.Cols, u.Indent, u.Indent+indent)) }
[ "func", "(", "u", "*", "UI", ")", "LineIndent", "(", "indent", "int", ",", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "o", ":=", "fmt", ".", "Sprintf", "(", "format", ",", "a", "...", ")", "\n", "fmt", ".", "Fprintln", "(", "readline", ".", "Stdout", ",", "ansiwrap", ".", "WrapIndent", "(", "o", ",", "u", ".", "Cols", ",", "u", ".", "Indent", ",", "u", ".", "Indent", "+", "indent", ")", ")", "\n", "}" ]
// LineIndent writes a formatted string followed by a newline to stdout. Output // is word wrapped, and terminated by a newline. All lines after the first are // indented by indent number of spaces (in addition to the indenting enforced // by this UI instance.
[ "LineIndent", "writes", "a", "formatted", "string", "followed", "by", "a", "newline", "to", "stdout", ".", "Output", "is", "word", "wrapped", "and", "terminated", "by", "a", "newline", ".", "All", "lines", "after", "the", "first", "are", "indented", "by", "indent", "number", "of", "spaces", "(", "in", "addition", "to", "the", "indenting", "enforced", "by", "this", "UI", "instance", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L85-L88
1,835
manifoldco/torus-cli
ui/ui.go
Info
func (u *UI) Info(format string, args ...interface{}) { if !Attached() { return } u.Line(format, args...) }
go
func (u *UI) Info(format string, args ...interface{}) { if !Attached() { return } u.Line(format, args...) }
[ "func", "(", "u", "*", "UI", ")", "Info", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "!", "Attached", "(", ")", "{", "return", "\n", "}", "\n\n", "u", ".", "Line", "(", "format", ",", "args", "...", ")", "\n", "}" ]
// Info handles outputting secondary information to the user such as messages // about progress but are the actual result of an operation. For example, // printing out that we're attempting to log a user in using the specific // environment variables. // // Only printed if stdout is attached to a terminal.
[ "Info", "handles", "outputting", "secondary", "information", "to", "the", "user", "such", "as", "messages", "about", "progress", "but", "are", "the", "actual", "result", "of", "an", "operation", ".", "For", "example", "printing", "out", "that", "we", "re", "attempting", "to", "log", "a", "user", "in", "using", "the", "specific", "environment", "variables", ".", "Only", "printed", "if", "stdout", "is", "attached", "to", "a", "terminal", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L130-L136
1,836
manifoldco/torus-cli
ui/ui.go
Warn
func (u *UI) Warn(format string, args ...interface{}) { var w io.Writer = readline.Stdout icon := u.BoldColorString(Yellow, "⚠ ") if !Attached() { w = readline.Stderr icon = "" } o := fmt.Sprintf(icon+format, args...) fmt.Fprintln(w, ansiwrap.WrapIndent(o, u.Cols, u.Indent, u.Indent)) }
go
func (u *UI) Warn(format string, args ...interface{}) { var w io.Writer = readline.Stdout icon := u.BoldColorString(Yellow, "⚠ ") if !Attached() { w = readline.Stderr icon = "" } o := fmt.Sprintf(icon+format, args...) fmt.Fprintln(w, ansiwrap.WrapIndent(o, u.Cols, u.Indent, u.Indent)) }
[ "func", "(", "u", "*", "UI", ")", "Warn", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "var", "w", "io", ".", "Writer", "=", "readline", ".", "Stdout", "\n", "icon", ":=", "u", ".", "BoldColorString", "(", "Yellow", ",", "\"", "", "", "\n", "if", "!", "Attached", "(", ")", "{", "w", "=", "readline", ".", "Stderr", "\n", "icon", "=", "\"", "\"", "\n", "}", "\n\n", "o", ":=", "fmt", ".", "Sprintf", "(", "icon", "+", "format", ",", "args", "...", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ",", "ansiwrap", ".", "WrapIndent", "(", "o", ",", "u", ".", "Cols", ",", "u", ".", "Indent", ",", "u", ".", "Indent", ")", ")", "\n", "}" ]
// Warn handles outputting warning information to the user such as // messages about needing to be logged in. // // The warning is printed out to stderr if stdout is not attached to a // terminal.
[ "Warn", "handles", "outputting", "warning", "information", "to", "the", "user", "such", "as", "messages", "about", "needing", "to", "be", "logged", "in", ".", "The", "warning", "is", "printed", "out", "to", "stderr", "if", "stdout", "is", "not", "attached", "to", "a", "terminal", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L146-L156
1,837
manifoldco/torus-cli
ui/ui.go
Child
func (u *UI) Child(indent int) *UI { return &UI{ Indent: u.Indent + indent, Cols: u.Cols, EnableProgress: u.EnableProgress, EnableHints: u.EnableHints, } }
go
func (u *UI) Child(indent int) *UI { return &UI{ Indent: u.Indent + indent, Cols: u.Cols, EnableProgress: u.EnableProgress, EnableHints: u.EnableHints, } }
[ "func", "(", "u", "*", "UI", ")", "Child", "(", "indent", "int", ")", "*", "UI", "{", "return", "&", "UI", "{", "Indent", ":", "u", ".", "Indent", "+", "indent", ",", "Cols", ":", "u", ".", "Cols", ",", "EnableProgress", ":", "u", ".", "EnableProgress", ",", "EnableHints", ":", "u", ".", "EnableHints", ",", "}", "\n", "}" ]
// Child returns a new UI, with settings from the receiver UI, and Indent // increased by the provided value.
[ "Child", "returns", "a", "new", "UI", "with", "settings", "from", "the", "receiver", "UI", "and", "Indent", "increased", "by", "the", "provided", "value", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L182-L190
1,838
manifoldco/torus-cli
ui/ui.go
Write
func (u *UI) Write(p []byte) (n int, err error) { parts := bytes.Split(p, []byte{'\n'}) indent := bytes.Repeat([]byte{' '}, u.Indent) for i, part := range parts { if len(part) > 0 { part = append(indent, part...) } os.Stdout.Write(part) if i < len(parts)-1 { fmt.Println() } } return len(p), nil }
go
func (u *UI) Write(p []byte) (n int, err error) { parts := bytes.Split(p, []byte{'\n'}) indent := bytes.Repeat([]byte{' '}, u.Indent) for i, part := range parts { if len(part) > 0 { part = append(indent, part...) } os.Stdout.Write(part) if i < len(parts)-1 { fmt.Println() } } return len(p), nil }
[ "func", "(", "u", "*", "UI", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "parts", ":=", "bytes", ".", "Split", "(", "p", ",", "[", "]", "byte", "{", "'\\n'", "}", ")", "\n\n", "indent", ":=", "bytes", ".", "Repeat", "(", "[", "]", "byte", "{", "' '", "}", ",", "u", ".", "Indent", ")", "\n", "for", "i", ",", "part", ":=", "range", "parts", "{", "if", "len", "(", "part", ")", ">", "0", "{", "part", "=", "append", "(", "indent", ",", "part", "...", ")", "\n", "}", "\n", "os", ".", "Stdout", ".", "Write", "(", "part", ")", "\n", "if", "i", "<", "len", "(", "parts", ")", "-", "1", "{", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "len", "(", "p", ")", ",", "nil", "\n", "}" ]
// Write implements the io.Writer interface // The provided bytes are split on newlines, and written with the UI's // configured indent.
[ "Write", "implements", "the", "io", ".", "Writer", "interface", "The", "provided", "bytes", "are", "split", "on", "newlines", "and", "written", "with", "the", "UI", "s", "configured", "indent", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/ui.go#L195-L210
1,839
manifoldco/torus-cli
gatekeeper/bootstrap/aws/bootstrap.go
Bootstrap
func Bootstrap(url, name, org, role, caFile string) (*apitypes.BootstrapResponse, error) { var err error client, err := client.NewClient(url, caFile) if err != nil { return nil, fmt.Errorf("cannot initialize bootstrap client: %s", err) } identity, err := metadata() if err != nil { return nil, err } sig, err := signature() if err != nil { return nil, err } v := Verifier{ Identity: identity, Signature: sig, } if err := v.Verify(); err != nil { return nil, err } var identityDoc identityDocument json.Unmarshal(identity, &identityDoc) if name == "" { name = identityDoc.InstanceID } bootreq := apitypes.AWSBootstrapRequest{ Identity: identity, Signature: sig, ProvisionTime: identityDoc.PendingTime, Machine: apitypes.MachineBootstrap{ Name: name, Org: org, Team: role, }, } return client.Bootstrap("aws", bootreq) }
go
func Bootstrap(url, name, org, role, caFile string) (*apitypes.BootstrapResponse, error) { var err error client, err := client.NewClient(url, caFile) if err != nil { return nil, fmt.Errorf("cannot initialize bootstrap client: %s", err) } identity, err := metadata() if err != nil { return nil, err } sig, err := signature() if err != nil { return nil, err } v := Verifier{ Identity: identity, Signature: sig, } if err := v.Verify(); err != nil { return nil, err } var identityDoc identityDocument json.Unmarshal(identity, &identityDoc) if name == "" { name = identityDoc.InstanceID } bootreq := apitypes.AWSBootstrapRequest{ Identity: identity, Signature: sig, ProvisionTime: identityDoc.PendingTime, Machine: apitypes.MachineBootstrap{ Name: name, Org: org, Team: role, }, } return client.Bootstrap("aws", bootreq) }
[ "func", "Bootstrap", "(", "url", ",", "name", ",", "org", ",", "role", ",", "caFile", "string", ")", "(", "*", "apitypes", ".", "BootstrapResponse", ",", "error", ")", "{", "var", "err", "error", "\n", "client", ",", "err", ":=", "client", ".", "NewClient", "(", "url", ",", "caFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "identity", ",", "err", ":=", "metadata", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sig", ",", "err", ":=", "signature", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "v", ":=", "Verifier", "{", "Identity", ":", "identity", ",", "Signature", ":", "sig", ",", "}", "\n\n", "if", "err", ":=", "v", ".", "Verify", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "identityDoc", "identityDocument", "\n", "json", ".", "Unmarshal", "(", "identity", ",", "&", "identityDoc", ")", "\n\n", "if", "name", "==", "\"", "\"", "{", "name", "=", "identityDoc", ".", "InstanceID", "\n", "}", "\n\n", "bootreq", ":=", "apitypes", ".", "AWSBootstrapRequest", "{", "Identity", ":", "identity", ",", "Signature", ":", "sig", ",", "ProvisionTime", ":", "identityDoc", ".", "PendingTime", ",", "Machine", ":", "apitypes", ".", "MachineBootstrap", "{", "Name", ":", "name", ",", "Org", ":", "org", ",", "Team", ":", "role", ",", "}", ",", "}", "\n\n", "return", "client", ".", "Bootstrap", "(", "\"", "\"", ",", "bootreq", ")", "\n", "}" ]
// Bootstrap bootstraps a the AWS instance into a role to a given Gatekeeper instance
[ "Bootstrap", "bootstraps", "a", "the", "AWS", "instance", "into", "a", "role", "to", "a", "given", "Gatekeeper", "instance" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/gatekeeper/bootstrap/aws/bootstrap.go#L20-L66
1,840
manifoldco/torus-cli
gatekeeper/bootstrap/bootstrap.go
Do
func Do(provider Provider, url, name, org, role, caFile string) (*apitypes.BootstrapResponse, error) { switch provider { case AWSPublic: return aws.Bootstrap(url, name, org, role, caFile) default: return nil, fmt.Errorf("invalid provider: %s", provider) } }
go
func Do(provider Provider, url, name, org, role, caFile string) (*apitypes.BootstrapResponse, error) { switch provider { case AWSPublic: return aws.Bootstrap(url, name, org, role, caFile) default: return nil, fmt.Errorf("invalid provider: %s", provider) } }
[ "func", "Do", "(", "provider", "Provider", ",", "url", ",", "name", ",", "org", ",", "role", ",", "caFile", "string", ")", "(", "*", "apitypes", ".", "BootstrapResponse", ",", "error", ")", "{", "switch", "provider", "{", "case", "AWSPublic", ":", "return", "aws", ".", "Bootstrap", "(", "url", ",", "name", ",", "org", ",", "role", ",", "caFile", ")", "\n\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "provider", ")", "\n", "}", "\n", "}" ]
// Do will execute the bootstrap request for the given provider
[ "Do", "will", "execute", "the", "bootstrap", "request", "for", "the", "given", "provider" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/gatekeeper/bootstrap/bootstrap.go#L20-L28
1,841
manifoldco/torus-cli
ui/spinner.go
newSpinner
func newSpinner(text string, enabled bool) *Spinner { s := spinner.New(spinner.CharSets[9], 100*time.Millisecond) s.Suffix = " " + text return &Spinner{ s, text, enabled, } }
go
func newSpinner(text string, enabled bool) *Spinner { s := spinner.New(spinner.CharSets[9], 100*time.Millisecond) s.Suffix = " " + text return &Spinner{ s, text, enabled, } }
[ "func", "newSpinner", "(", "text", "string", ",", "enabled", "bool", ")", "*", "Spinner", "{", "s", ":=", "spinner", ".", "New", "(", "spinner", ".", "CharSets", "[", "9", "]", ",", "100", "*", "time", ".", "Millisecond", ")", "\n", "s", ".", "Suffix", "=", "\"", "\"", "+", "text", "\n", "return", "&", "Spinner", "{", "s", ",", "text", ",", "enabled", ",", "}", "\n", "}" ]
// newSpinner creates a new Spinner struct
[ "newSpinner", "creates", "a", "new", "Spinner", "struct" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/ui/spinner.go#L17-L25
1,842
manifoldco/torus-cli
registry/claims.go
Create
func (c ClaimsClient) Create(ctx context.Context, claim *envelope.Claim) (*envelope.Claim, error) { resp := &envelope.Claim{} err := c.client.RoundTrip(ctx, "POST", "/claims", nil, claim, &resp) return resp, err }
go
func (c ClaimsClient) Create(ctx context.Context, claim *envelope.Claim) (*envelope.Claim, error) { resp := &envelope.Claim{} err := c.client.RoundTrip(ctx, "POST", "/claims", nil, claim, &resp) return resp, err }
[ "func", "(", "c", "ClaimsClient", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "claim", "*", "envelope", ".", "Claim", ")", "(", "*", "envelope", ".", "Claim", ",", "error", ")", "{", "resp", ":=", "&", "envelope", ".", "Claim", "{", "}", "\n", "err", ":=", "c", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "claim", ",", "&", "resp", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Create creates a a new signed claim on the server
[ "Create", "creates", "a", "a", "new", "signed", "claim", "on", "the", "server" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/claims.go#L16-L20
1,843
manifoldco/torus-cli
prefs/prefs.go
CountFields
func (prefs Preferences) CountFields(fieldName string) int { value, err := reflections.GetField(prefs, fieldName) count := 0 if err != nil { return count } items, _ := reflections.Items(value) for i := range items { value, _ := reflections.GetField(value, i) if value != nil && value != "" { count++ } } return count }
go
func (prefs Preferences) CountFields(fieldName string) int { value, err := reflections.GetField(prefs, fieldName) count := 0 if err != nil { return count } items, _ := reflections.Items(value) for i := range items { value, _ := reflections.GetField(value, i) if value != nil && value != "" { count++ } } return count }
[ "func", "(", "prefs", "Preferences", ")", "CountFields", "(", "fieldName", "string", ")", "int", "{", "value", ",", "err", ":=", "reflections", ".", "GetField", "(", "prefs", ",", "fieldName", ")", "\n", "count", ":=", "0", "\n", "if", "err", "!=", "nil", "{", "return", "count", "\n", "}", "\n", "items", ",", "_", ":=", "reflections", ".", "Items", "(", "value", ")", "\n", "for", "i", ":=", "range", "items", "{", "value", ",", "_", ":=", "reflections", ".", "GetField", "(", "value", ",", "i", ")", "\n", "if", "value", "!=", "nil", "&&", "value", "!=", "\"", "\"", "{", "count", "++", "\n", "}", "\n", "}", "\n", "return", "count", "\n", "}" ]
// CountFields returns the number of defined fields on sub-field struct
[ "CountFields", "returns", "the", "number", "of", "defined", "fields", "on", "sub", "-", "field", "struct" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/prefs/prefs.go#L28-L42
1,844
manifoldco/torus-cli
prefs/prefs.go
SetValue
func (prefs Preferences) SetValue(key string, value string) (Preferences, error) { parts := strings.Split(key, ".") section := parts[0] // [Core|Default] key = parts[1] // Rest of the property name // Identify category struct by ini tag name [Core|Default] values := reflect.ValueOf(&prefs).Elem() target := findElemByName(values, section) // Identify field to update by ini tag name values = reflect.ValueOf(&prefs).Elem().FieldByName(target) if values == reflect.Zero(reflect.TypeOf(values)).Interface() { return prefs, errs.NewExitError("error: unknown section `" + section + "`") } property := findElemByName(values, key) // Ensure the field is not zero field := values.Addr().Elem().FieldByName(property) if field == reflect.Zero(reflect.TypeOf(field)).Interface() { return prefs, errs.NewExitError("error: unknown property `" + key + "`") } switch field.Type() { case reflect.TypeOf(true): v := true if value != "true" && value != "1" { v = false } field.SetBool(v) default: field.SetString(value) } return prefs, nil }
go
func (prefs Preferences) SetValue(key string, value string) (Preferences, error) { parts := strings.Split(key, ".") section := parts[0] // [Core|Default] key = parts[1] // Rest of the property name // Identify category struct by ini tag name [Core|Default] values := reflect.ValueOf(&prefs).Elem() target := findElemByName(values, section) // Identify field to update by ini tag name values = reflect.ValueOf(&prefs).Elem().FieldByName(target) if values == reflect.Zero(reflect.TypeOf(values)).Interface() { return prefs, errs.NewExitError("error: unknown section `" + section + "`") } property := findElemByName(values, key) // Ensure the field is not zero field := values.Addr().Elem().FieldByName(property) if field == reflect.Zero(reflect.TypeOf(field)).Interface() { return prefs, errs.NewExitError("error: unknown property `" + key + "`") } switch field.Type() { case reflect.TypeOf(true): v := true if value != "true" && value != "1" { v = false } field.SetBool(v) default: field.SetString(value) } return prefs, nil }
[ "func", "(", "prefs", "Preferences", ")", "SetValue", "(", "key", "string", ",", "value", "string", ")", "(", "Preferences", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "key", ",", "\"", "\"", ")", "\n", "section", ":=", "parts", "[", "0", "]", "// [Core|Default]", "\n", "key", "=", "parts", "[", "1", "]", "// Rest of the property name", "\n\n", "// Identify category struct by ini tag name [Core|Default]", "values", ":=", "reflect", ".", "ValueOf", "(", "&", "prefs", ")", ".", "Elem", "(", ")", "\n", "target", ":=", "findElemByName", "(", "values", ",", "section", ")", "\n\n", "// Identify field to update by ini tag name", "values", "=", "reflect", ".", "ValueOf", "(", "&", "prefs", ")", ".", "Elem", "(", ")", ".", "FieldByName", "(", "target", ")", "\n", "if", "values", "==", "reflect", ".", "Zero", "(", "reflect", ".", "TypeOf", "(", "values", ")", ")", ".", "Interface", "(", ")", "{", "return", "prefs", ",", "errs", ".", "NewExitError", "(", "\"", "\"", "+", "section", "+", "\"", "\"", ")", "\n", "}", "\n", "property", ":=", "findElemByName", "(", "values", ",", "key", ")", "\n\n", "// Ensure the field is not zero", "field", ":=", "values", ".", "Addr", "(", ")", ".", "Elem", "(", ")", ".", "FieldByName", "(", "property", ")", "\n", "if", "field", "==", "reflect", ".", "Zero", "(", "reflect", ".", "TypeOf", "(", "field", ")", ")", ".", "Interface", "(", ")", "{", "return", "prefs", ",", "errs", ".", "NewExitError", "(", "\"", "\"", "+", "key", "+", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "field", ".", "Type", "(", ")", "{", "case", "reflect", ".", "TypeOf", "(", "true", ")", ":", "v", ":=", "true", "\n", "if", "value", "!=", "\"", "\"", "&&", "value", "!=", "\"", "\"", "{", "v", "=", "false", "\n", "}", "\n", "field", ".", "SetBool", "(", "v", ")", "\n", "default", ":", "field", ".", "SetString", "(", "value", ")", "\n", "}", "\n\n", "return", "prefs", ",", "nil", "\n", "}" ]
// SetValue for ini key on preferences struct
[ "SetValue", "for", "ini", "key", "on", "preferences", "struct" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/prefs/prefs.go#L69-L103
1,845
manifoldco/torus-cli
prefs/prefs.go
NewPreferences
func NewPreferences() (*Preferences, error) { prefs := &Preferences{ Core: Core{ RegistryURI: registryURI, ManifestURI: manifestURI, GatekeeperAddress: gatekeeperAddress, Context: true, EnableHints: true, EnableProgress: true, EnableCheckUpdates: true, EnableColors: true, }, } filePath, _ := RcPath() _, err := os.Stat(filePath) if os.IsNotExist(err) { return prefs, nil } if err != nil { return prefs, err } err = ini.MapTo(prefs, filePath) return prefs, err }
go
func NewPreferences() (*Preferences, error) { prefs := &Preferences{ Core: Core{ RegistryURI: registryURI, ManifestURI: manifestURI, GatekeeperAddress: gatekeeperAddress, Context: true, EnableHints: true, EnableProgress: true, EnableCheckUpdates: true, EnableColors: true, }, } filePath, _ := RcPath() _, err := os.Stat(filePath) if os.IsNotExist(err) { return prefs, nil } if err != nil { return prefs, err } err = ini.MapTo(prefs, filePath) return prefs, err }
[ "func", "NewPreferences", "(", ")", "(", "*", "Preferences", ",", "error", ")", "{", "prefs", ":=", "&", "Preferences", "{", "Core", ":", "Core", "{", "RegistryURI", ":", "registryURI", ",", "ManifestURI", ":", "manifestURI", ",", "GatekeeperAddress", ":", "gatekeeperAddress", ",", "Context", ":", "true", ",", "EnableHints", ":", "true", ",", "EnableProgress", ":", "true", ",", "EnableCheckUpdates", ":", "true", ",", "EnableColors", ":", "true", ",", "}", ",", "}", "\n\n", "filePath", ",", "_", ":=", "RcPath", "(", ")", "\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filePath", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "prefs", ",", "nil", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "prefs", ",", "err", "\n", "}", "\n\n", "err", "=", "ini", ".", "MapTo", "(", "prefs", ",", "filePath", ")", "\n", "return", "prefs", ",", "err", "\n", "}" ]
// NewPreferences returns a new instance of preferences struct
[ "NewPreferences", "returns", "a", "new", "instance", "of", "preferences", "struct" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/prefs/prefs.go#L120-L146
1,846
manifoldco/torus-cli
registry/credentialgraph.go
Post
func (c *CredentialGraphClient) Post(ctx context.Context, t *CredentialGraph) (CredentialGraph, error) { resp := rawGraph{} err := c.client.RoundTrip(ctx, "POST", "/credentialgraph", nil, t, &resp) if err != nil { return nil, err } return resp.convert() }
go
func (c *CredentialGraphClient) Post(ctx context.Context, t *CredentialGraph) (CredentialGraph, error) { resp := rawGraph{} err := c.client.RoundTrip(ctx, "POST", "/credentialgraph", nil, t, &resp) if err != nil { return nil, err } return resp.convert() }
[ "func", "(", "c", "*", "CredentialGraphClient", ")", "Post", "(", "ctx", "context", ".", "Context", ",", "t", "*", "CredentialGraph", ")", "(", "CredentialGraph", ",", "error", ")", "{", "resp", ":=", "rawGraph", "{", "}", "\n", "err", ":=", "c", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "t", ",", "&", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "resp", ".", "convert", "(", ")", "\n", "}" ]
// Post creates a new CredentialGraph on the registry. // // The CredentialGraph includes the keyring, it's members, and credentials.
[ "Post", "creates", "a", "new", "CredentialGraph", "on", "the", "registry", ".", "The", "CredentialGraph", "includes", "the", "keyring", "it", "s", "members", "and", "credentials", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/credentialgraph.go#L120-L128
1,847
manifoldco/torus-cli
cmd/middleware.go
chain
func chain(funcs ...actionFunc) func(*cli.Context) error { return wrap(func(ctx *cli.Context) error { for _, f := range funcs { err := f(ctx) if err != nil { return err } } return nil }) }
go
func chain(funcs ...actionFunc) func(*cli.Context) error { return wrap(func(ctx *cli.Context) error { for _, f := range funcs { err := f(ctx) if err != nil { return err } } return nil }) }
[ "func", "chain", "(", "funcs", "...", "actionFunc", ")", "func", "(", "*", "cli", ".", "Context", ")", "error", "{", "return", "wrap", "(", "func", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "for", "_", ",", "f", ":=", "range", "funcs", "{", "err", ":=", "f", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// chain allows easy sequential calling of BeforeFuncs and AfterFuncs. // chain will exit on the first error seen.
[ "chain", "allows", "easy", "sequential", "calling", "of", "BeforeFuncs", "and", "AfterFuncs", ".", "chain", "will", "exit", "on", "the", "first", "error", "seen", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L28-L40
1,848
manifoldco/torus-cli
cmd/middleware.go
wrap
func wrap(cmd actionFunc) actionFunc { return func(ctx *cli.Context) error { return errs.ToError(cmd(ctx)) } }
go
func wrap(cmd actionFunc) actionFunc { return func(ctx *cli.Context) error { return errs.ToError(cmd(ctx)) } }
[ "func", "wrap", "(", "cmd", "actionFunc", ")", "actionFunc", "{", "return", "func", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "return", "errs", ".", "ToError", "(", "cmd", "(", "ctx", ")", ")", "\n", "}", "\n", "}" ]
// wrap wraps the given actionfunc and converts any of the received errors into // cli.ExitErrors ensuring that we never have a silent failure.
[ "wrap", "wraps", "the", "given", "actionfunc", "and", "converts", "any", "of", "the", "received", "errors", "into", "cli", ".", "ExitErrors", "ensuring", "that", "we", "never", "have", "a", "silent", "failure", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L44-L48
1,849
manifoldco/torus-cli
cmd/middleware.go
ensureSession
func ensureSession(ctx *cli.Context) error { cfg, err := config.LoadConfig() if err != nil { return err } bgCtx := context.Background() client := api.NewClient(cfg) _, err = client.Session.Get(bgCtx) hasSession := true if err != nil { if cerr, ok := err.(*apitypes.Error); ok { if cerr.Type == apitypes.UnauthorizedError { hasSession = false } } if hasSession { return errs.NewErrorExitError("Could not communicate with daemon.", err) } } if hasSession { return nil } email, hasEmail := os.LookupEnv("TORUS_EMAIL") password, hasPassword := os.LookupEnv("TORUS_PASSWORD") tokenID, hasTokenID := os.LookupEnv("TORUS_TOKEN_ID") tokenSecret, hasTokenSecret := os.LookupEnv("TORUS_TOKEN_SECRET") if hasEmail && hasPassword { ui.Info("Attempting to login as a user with email: %s", email) err := client.Session.UserLogin(bgCtx, email, password) if err != nil { ui.Error("Could not log in, encountered an error: %s", err) } else { return nil } } if hasTokenID && hasTokenSecret { ui.Info("Attempting to login with machine token id: %s", tokenID) err := client.Session.MachineLogin(bgCtx, tokenID, tokenSecret) if err != nil { ui.Error("Could not log in, encountered an error: %s", err) } else { return nil } } msg := "\nYou must be logged in to run '" + ctx.Command.FullName() + "'.\n" + "Login using 'login' or create an account using 'signup'." return errs.NewExitError(msg) }
go
func ensureSession(ctx *cli.Context) error { cfg, err := config.LoadConfig() if err != nil { return err } bgCtx := context.Background() client := api.NewClient(cfg) _, err = client.Session.Get(bgCtx) hasSession := true if err != nil { if cerr, ok := err.(*apitypes.Error); ok { if cerr.Type == apitypes.UnauthorizedError { hasSession = false } } if hasSession { return errs.NewErrorExitError("Could not communicate with daemon.", err) } } if hasSession { return nil } email, hasEmail := os.LookupEnv("TORUS_EMAIL") password, hasPassword := os.LookupEnv("TORUS_PASSWORD") tokenID, hasTokenID := os.LookupEnv("TORUS_TOKEN_ID") tokenSecret, hasTokenSecret := os.LookupEnv("TORUS_TOKEN_SECRET") if hasEmail && hasPassword { ui.Info("Attempting to login as a user with email: %s", email) err := client.Session.UserLogin(bgCtx, email, password) if err != nil { ui.Error("Could not log in, encountered an error: %s", err) } else { return nil } } if hasTokenID && hasTokenSecret { ui.Info("Attempting to login with machine token id: %s", tokenID) err := client.Session.MachineLogin(bgCtx, tokenID, tokenSecret) if err != nil { ui.Error("Could not log in, encountered an error: %s", err) } else { return nil } } msg := "\nYou must be logged in to run '" + ctx.Command.FullName() + "'.\n" + "Login using 'login' or create an account using 'signup'." return errs.NewExitError(msg) }
[ "func", "ensureSession", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "cfg", ",", "err", ":=", "config", ".", "LoadConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bgCtx", ":=", "context", ".", "Background", "(", ")", "\n", "client", ":=", "api", ".", "NewClient", "(", "cfg", ")", "\n", "_", ",", "err", "=", "client", ".", "Session", ".", "Get", "(", "bgCtx", ")", "\n\n", "hasSession", ":=", "true", "\n", "if", "err", "!=", "nil", "{", "if", "cerr", ",", "ok", ":=", "err", ".", "(", "*", "apitypes", ".", "Error", ")", ";", "ok", "{", "if", "cerr", ".", "Type", "==", "apitypes", ".", "UnauthorizedError", "{", "hasSession", "=", "false", "\n", "}", "\n", "}", "\n", "if", "hasSession", "{", "return", "errs", ".", "NewErrorExitError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "hasSession", "{", "return", "nil", "\n", "}", "\n\n", "email", ",", "hasEmail", ":=", "os", ".", "LookupEnv", "(", "\"", "\"", ")", "\n", "password", ",", "hasPassword", ":=", "os", ".", "LookupEnv", "(", "\"", "\"", ")", "\n", "tokenID", ",", "hasTokenID", ":=", "os", ".", "LookupEnv", "(", "\"", "\"", ")", "\n", "tokenSecret", ",", "hasTokenSecret", ":=", "os", ".", "LookupEnv", "(", "\"", "\"", ")", "\n\n", "if", "hasEmail", "&&", "hasPassword", "{", "ui", ".", "Info", "(", "\"", "\"", ",", "email", ")", "\n\n", "err", ":=", "client", ".", "Session", ".", "UserLogin", "(", "bgCtx", ",", "email", ",", "password", ")", "\n", "if", "err", "!=", "nil", "{", "ui", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "if", "hasTokenID", "&&", "hasTokenSecret", "{", "ui", ".", "Info", "(", "\"", "\"", ",", "tokenID", ")", "\n\n", "err", ":=", "client", ".", "Session", ".", "MachineLogin", "(", "bgCtx", ",", "tokenID", ",", "tokenSecret", ")", "\n", "if", "err", "!=", "nil", "{", "ui", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "msg", ":=", "\"", "\\n", "\"", "+", "ctx", ".", "Command", ".", "FullName", "(", ")", "+", "\"", "\\n", "\"", "+", "\"", "\"", "\n", "return", "errs", ".", "NewExitError", "(", "msg", ")", "\n", "}" ]
// ensureSession ensures that the user is logged in with the daemon and has a // valid session. If not, it will attempt to log the user in via environment // variables. If they do not exist, of the login fails, it will abort the // command.
[ "ensureSession", "ensures", "that", "the", "user", "is", "logged", "in", "with", "the", "daemon", "and", "has", "a", "valid", "session", ".", "If", "not", "it", "will", "attempt", "to", "log", "the", "user", "in", "via", "environment", "variables", ".", "If", "they", "do", "not", "exist", "of", "the", "login", "fails", "it", "will", "abort", "the", "command", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L114-L170
1,850
manifoldco/torus-cli
cmd/middleware.go
loadDirPrefs
func loadDirPrefs(ctx *cli.Context) error { p, err := prefs.NewPreferences() if err != nil { return err } d, err := dirprefs.Load(true) if err != nil { return err } return reflectArgs(ctx, p, d, "json") }
go
func loadDirPrefs(ctx *cli.Context) error { p, err := prefs.NewPreferences() if err != nil { return err } d, err := dirprefs.Load(true) if err != nil { return err } return reflectArgs(ctx, p, d, "json") }
[ "func", "loadDirPrefs", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "p", ",", "err", ":=", "prefs", ".", "NewPreferences", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "d", ",", "err", ":=", "dirprefs", ".", "Load", "(", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "reflectArgs", "(", "ctx", ",", "p", ",", "d", ",", "\"", "\"", ")", "\n", "}" ]
// loadDirPrefs loads argument values from the .torus.json file
[ "loadDirPrefs", "loads", "argument", "values", "from", "the", ".", "torus", ".", "json", "file" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L173-L185
1,851
manifoldco/torus-cli
cmd/middleware.go
loadPrefDefaults
func loadPrefDefaults(ctx *cli.Context) error { p, err := prefs.NewPreferences() if err != nil { return err } return reflectArgs(ctx, p, p.Defaults, "ini") }
go
func loadPrefDefaults(ctx *cli.Context) error { p, err := prefs.NewPreferences() if err != nil { return err } return reflectArgs(ctx, p, p.Defaults, "ini") }
[ "func", "loadPrefDefaults", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "p", ",", "err", ":=", "prefs", ".", "NewPreferences", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "reflectArgs", "(", "ctx", ",", "p", ",", "p", ".", "Defaults", ",", "\"", "\"", ")", "\n", "}" ]
// loadPrefDefaults loads default argument values from the .torusrc // preferences file defaults section, inserting them into any unset flag values
[ "loadPrefDefaults", "loads", "default", "argument", "values", "from", "the", ".", "torusrc", "preferences", "file", "defaults", "section", "inserting", "them", "into", "any", "unset", "flag", "values" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L189-L196
1,852
manifoldco/torus-cli
cmd/middleware.go
setUserEnv
func setUserEnv(ctx *cli.Context) error { argName := "environment" // Check for env flag, just in case this middleware is misused hasEnvFlag := false for _, name := range ctx.FlagNames() { if name == argName { hasEnvFlag = true break } } if !hasEnvFlag { return nil } if isSet(ctx, argName) { return nil } cfg, err := config.LoadConfig() if err != nil { return err } client := api.NewClient(cfg) session, err := client.Session.Who(context.Background()) if err != nil { return err } if session.Type() == apitypes.UserSession { ctx.Set(argName, "dev-"+session.Username()) } return nil }
go
func setUserEnv(ctx *cli.Context) error { argName := "environment" // Check for env flag, just in case this middleware is misused hasEnvFlag := false for _, name := range ctx.FlagNames() { if name == argName { hasEnvFlag = true break } } if !hasEnvFlag { return nil } if isSet(ctx, argName) { return nil } cfg, err := config.LoadConfig() if err != nil { return err } client := api.NewClient(cfg) session, err := client.Session.Who(context.Background()) if err != nil { return err } if session.Type() == apitypes.UserSession { ctx.Set(argName, "dev-"+session.Username()) } return nil }
[ "func", "setUserEnv", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "argName", ":=", "\"", "\"", "\n", "// Check for env flag, just in case this middleware is misused", "hasEnvFlag", ":=", "false", "\n", "for", "_", ",", "name", ":=", "range", "ctx", ".", "FlagNames", "(", ")", "{", "if", "name", "==", "argName", "{", "hasEnvFlag", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "hasEnvFlag", "{", "return", "nil", "\n", "}", "\n\n", "if", "isSet", "(", "ctx", ",", "argName", ")", "{", "return", "nil", "\n", "}", "\n\n", "cfg", ",", "err", ":=", "config", ".", "LoadConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "client", ":=", "api", ".", "NewClient", "(", "cfg", ")", "\n", "session", ",", "err", ":=", "client", ".", "Session", ".", "Who", "(", "context", ".", "Background", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "session", ".", "Type", "(", ")", "==", "apitypes", ".", "UserSession", "{", "ctx", ".", "Set", "(", "argName", ",", "\"", "\"", "+", "session", ".", "Username", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// setUserEnv populates the env argument, if present and unset, // with dev-USERNAME
[ "setUserEnv", "populates", "the", "env", "argument", "if", "present", "and", "unset", "with", "dev", "-", "USERNAME" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L241-L275
1,853
manifoldco/torus-cli
cmd/middleware.go
setSliceDefaults
func setSliceDefaults(ctx *cli.Context) error { for _, f := range ctx.Command.Flags { if psf, ok := f.(placeHolderStringSliceFlag); ok { name := strings.SplitN(psf.GetName(), ",", 2)[0] if psf.Default != "" && len(ctx.StringSlice(name)) == 0 { ctx.Set(name, psf.Default) } } } return nil }
go
func setSliceDefaults(ctx *cli.Context) error { for _, f := range ctx.Command.Flags { if psf, ok := f.(placeHolderStringSliceFlag); ok { name := strings.SplitN(psf.GetName(), ",", 2)[0] if psf.Default != "" && len(ctx.StringSlice(name)) == 0 { ctx.Set(name, psf.Default) } } } return nil }
[ "func", "setSliceDefaults", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "for", "_", ",", "f", ":=", "range", "ctx", ".", "Command", ".", "Flags", "{", "if", "psf", ",", "ok", ":=", "f", ".", "(", "placeHolderStringSliceFlag", ")", ";", "ok", "{", "name", ":=", "strings", ".", "SplitN", "(", "psf", ".", "GetName", "(", ")", ",", "\"", "\"", ",", "2", ")", "[", "0", "]", "\n", "if", "psf", ".", "Default", "!=", "\"", "\"", "&&", "len", "(", "ctx", ".", "StringSlice", "(", "name", ")", ")", "==", "0", "{", "ctx", ".", "Set", "(", "name", ",", "psf", ".", "Default", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// setSliceDefaults populates any string slice flags with the default value // if nothing else is set. This is different from the default urfave default // Value, which will always be included in the string slice options.
[ "setSliceDefaults", "populates", "any", "string", "slice", "flags", "with", "the", "default", "value", "if", "nothing", "else", "is", "set", ".", "This", "is", "different", "from", "the", "default", "urfave", "default", "Value", "which", "will", "always", "be", "included", "in", "the", "string", "slice", "options", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L280-L291
1,854
manifoldco/torus-cli
cmd/middleware.go
checkUpdates
func checkUpdates(ctx *cli.Context) error { cfg, err := config.LoadConfig() if err != nil { return err } client := api.NewClient(cfg) c := context.Background() updateInfo, err := client.Updates.Check(c) if err != nil { return err } if updateInfo.NeedsUpdate { ui.Info("A new version of Torus is available (%s)! You can download it from %s.", updateInfo.Version, downloadURL) } return nil }
go
func checkUpdates(ctx *cli.Context) error { cfg, err := config.LoadConfig() if err != nil { return err } client := api.NewClient(cfg) c := context.Background() updateInfo, err := client.Updates.Check(c) if err != nil { return err } if updateInfo.NeedsUpdate { ui.Info("A new version of Torus is available (%s)! You can download it from %s.", updateInfo.Version, downloadURL) } return nil }
[ "func", "checkUpdates", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "cfg", ",", "err", ":=", "config", ".", "LoadConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "client", ":=", "api", ".", "NewClient", "(", "cfg", ")", "\n", "c", ":=", "context", ".", "Background", "(", ")", "\n\n", "updateInfo", ",", "err", ":=", "client", ".", "Updates", ".", "Check", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "updateInfo", ".", "NeedsUpdate", "{", "ui", ".", "Info", "(", "\"", "\"", ",", "updateInfo", ".", "Version", ",", "downloadURL", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkUpdates checks if there's a torus update available. If so, // it prints a message to the stdout with the download URL if so.
[ "checkUpdates", "checks", "if", "there", "s", "a", "torus", "update", "available", ".", "If", "so", "it", "prints", "a", "message", "to", "the", "stdout", "with", "the", "download", "URL", "if", "so", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/cmd/middleware.go#L348-L367
1,855
manifoldco/torus-cli
apitypes/apitypes.go
LookupErrorType
func LookupErrorType(code int) ErrorType { for t, c := range errorTypeToStatusCodeMap { if c == code { return t } } return UnknownError }
go
func LookupErrorType(code int) ErrorType { for t, c := range errorTypeToStatusCodeMap { if c == code { return t } } return UnknownError }
[ "func", "LookupErrorType", "(", "code", "int", ")", "ErrorType", "{", "for", "t", ",", "c", ":=", "range", "errorTypeToStatusCodeMap", "{", "if", "c", "==", "code", "{", "return", "t", "\n", "}", "\n", "}", "\n\n", "return", "UnknownError", "\n", "}" ]
// LookupErrorType returns the ErrorType for the given HTTP StatusCode, // UnknownError is returned if the error type could not be found.
[ "LookupErrorType", "returns", "the", "ErrorType", "for", "the", "given", "HTTP", "StatusCode", "UnknownError", "is", "returned", "if", "the", "error", "type", "could", "not", "be", "found", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L40-L48
1,856
manifoldco/torus-cli
apitypes/apitypes.go
Error
func (e *Error) Error() string { segments := strings.Split(string(e.Type), "_") errType := strings.Join(segments, " ") return strings.Title(errType) + ": " + strings.Join(e.Err, " ") }
go
func (e *Error) Error() string { segments := strings.Split(string(e.Type), "_") errType := strings.Join(segments, " ") return strings.Title(errType) + ": " + strings.Join(e.Err, " ") }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "segments", ":=", "strings", ".", "Split", "(", "string", "(", "e", ".", "Type", ")", ",", "\"", "\"", ")", "\n", "errType", ":=", "strings", ".", "Join", "(", "segments", ",", "\"", "\"", ")", "\n", "return", "strings", ".", "Title", "(", "errType", ")", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "e", ".", "Err", ",", "\"", "\"", ")", "\n", "}" ]
// Error implements the error interface for formatted API errors.
[ "Error", "implements", "the", "error", "interface", "for", "formatted", "API", "errors", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L57-L61
1,857
manifoldco/torus-cli
apitypes/apitypes.go
StatusCode
func (e *Error) StatusCode() int { code, ok := errorTypeToStatusCodeMap[e.Type] if !ok || code == 0 { return 500 } return code }
go
func (e *Error) StatusCode() int { code, ok := errorTypeToStatusCodeMap[e.Type] if !ok || code == 0 { return 500 } return code }
[ "func", "(", "e", "*", "Error", ")", "StatusCode", "(", ")", "int", "{", "code", ",", "ok", ":=", "errorTypeToStatusCodeMap", "[", "e", ".", "Type", "]", "\n", "if", "!", "ok", "||", "code", "==", "0", "{", "return", "500", "\n", "}", "\n\n", "return", "code", "\n", "}" ]
// StatusCode returns the http status code associated with the underlying error type
[ "StatusCode", "returns", "the", "http", "status", "code", "associated", "with", "the", "underlying", "error", "type" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L64-L71
1,858
manifoldco/torus-cli
apitypes/apitypes.go
FormatError
func FormatError(err error) error { if err == nil { return nil } if apiErr, ok := err.(*Error); ok { if apiErr.Type == UnauthorizedError { for _, m := range apiErr.Err { if strings.Contains(m, "wrong identity state: unverified") { return NewUnverifiedError() } } return &Error{ Type: UnauthorizedError, Err: []string{"You are unauthorized to perform this action."}, } } } return err }
go
func FormatError(err error) error { if err == nil { return nil } if apiErr, ok := err.(*Error); ok { if apiErr.Type == UnauthorizedError { for _, m := range apiErr.Err { if strings.Contains(m, "wrong identity state: unverified") { return NewUnverifiedError() } } return &Error{ Type: UnauthorizedError, Err: []string{"You are unauthorized to perform this action."}, } } } return err }
[ "func", "FormatError", "(", "err", "error", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "apiErr", ",", "ok", ":=", "err", ".", "(", "*", "Error", ")", ";", "ok", "{", "if", "apiErr", ".", "Type", "==", "UnauthorizedError", "{", "for", "_", ",", "m", ":=", "range", "apiErr", ".", "Err", "{", "if", "strings", ".", "Contains", "(", "m", ",", "\"", "\"", ")", "{", "return", "NewUnverifiedError", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "Error", "{", "Type", ":", "UnauthorizedError", ",", "Err", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "}", "\n", "}", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// FormatError updates an error to contain more context
[ "FormatError", "updates", "an", "error", "to", "contain", "more", "context" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L74-L95
1,859
manifoldco/torus-cli
apitypes/apitypes.go
IsNotFoundError
func IsNotFoundError(err error) bool { if err == nil { return false } if apiErr, ok := err.(*Error); ok { return apiErr.Type == NotFoundError } return false }
go
func IsNotFoundError(err error) bool { if err == nil { return false } if apiErr, ok := err.(*Error); ok { return apiErr.Type == NotFoundError } return false }
[ "func", "IsNotFoundError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "if", "apiErr", ",", "ok", ":=", "err", ".", "(", "*", "Error", ")", ";", "ok", "{", "return", "apiErr", ".", "Type", "==", "NotFoundError", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// IsNotFoundError returns whether or not an error is a 404 result from the api.
[ "IsNotFoundError", "returns", "whether", "or", "not", "an", "error", "is", "a", "404", "result", "from", "the", "api", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L108-L118
1,860
manifoldco/torus-cli
apitypes/apitypes.go
IsUnauthorizedError
func IsUnauthorizedError(err error) bool { if err == nil { return false } if apiErr, ok := err.(*Error); ok { return apiErr.Type == UnauthorizedError } return false }
go
func IsUnauthorizedError(err error) bool { if err == nil { return false } if apiErr, ok := err.(*Error); ok { return apiErr.Type == UnauthorizedError } return false }
[ "func", "IsUnauthorizedError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "if", "apiErr", ",", "ok", ":=", "err", ".", "(", "*", "Error", ")", ";", "ok", "{", "return", "apiErr", ".", "Type", "==", "UnauthorizedError", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// IsUnauthorizedError returns whether or not an error is a 401 result from the api.
[ "IsUnauthorizedError", "returns", "whether", "or", "not", "an", "error", "is", "a", "401", "result", "from", "the", "api", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L121-L131
1,861
manifoldco/torus-cli
apitypes/apitypes.go
Valid
func (m *MachineLogin) Valid() bool { return m.TokenID != nil && m.Secret != nil && m.Secret.String() != "" }
go
func (m *MachineLogin) Valid() bool { return m.TokenID != nil && m.Secret != nil && m.Secret.String() != "" }
[ "func", "(", "m", "*", "MachineLogin", ")", "Valid", "(", ")", "bool", "{", "return", "m", ".", "TokenID", "!=", "nil", "&&", "m", ".", "Secret", "!=", "nil", "&&", "m", ".", "Secret", ".", "String", "(", ")", "!=", "\"", "\"", "\n", "}" ]
// Valid returns whether or not this is a valid machine login request
[ "Valid", "returns", "whether", "or", "not", "this", "is", "a", "valid", "machine", "login", "request" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/apitypes/apitypes.go#L217-L219
1,862
manifoldco/torus-cli
registry/credentials.go
Create
func (c *Credentials) Create(ctx context.Context, creds []envelope.CredentialInf) ([]*envelope.Credential, error) { resp := []*envelope.Credential{} err := c.client.RoundTrip(ctx, "POST", "/credentials", nil, creds, &resp) return resp, err }
go
func (c *Credentials) Create(ctx context.Context, creds []envelope.CredentialInf) ([]*envelope.Credential, error) { resp := []*envelope.Credential{} err := c.client.RoundTrip(ctx, "POST", "/credentials", nil, creds, &resp) return resp, err }
[ "func", "(", "c", "*", "Credentials", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "creds", "[", "]", "envelope", ".", "CredentialInf", ")", "(", "[", "]", "*", "envelope", ".", "Credential", ",", "error", ")", "{", "resp", ":=", "[", "]", "*", "envelope", ".", "Credential", "{", "}", "\n", "err", ":=", "c", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "creds", ",", "&", "resp", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Create creates the provided credential in the registry.
[ "Create", "creates", "the", "provided", "credential", "in", "the", "registry", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/credentials.go#L16-L20
1,863
manifoldco/torus-cli
api/machines.go
Create
func (m *MachinesClient) Create(ctx context.Context, orgID, teamID *identity.ID, name string, output ProgressFunc) (*apitypes.MachineSegment, *base64.Value, error) { secret, err := createTokenSecret() if err != nil { return nil, nil, err } mcr := apitypes.MachinesCreateRequest{ Name: name, OrgID: orgID, TeamID: teamID, Secret: secret, } result := &apitypes.MachineSegment{} err = m.client.DaemonRoundTrip(ctx, "POST", "/machines", nil, &mcr, &result, output) return result, secret, err }
go
func (m *MachinesClient) Create(ctx context.Context, orgID, teamID *identity.ID, name string, output ProgressFunc) (*apitypes.MachineSegment, *base64.Value, error) { secret, err := createTokenSecret() if err != nil { return nil, nil, err } mcr := apitypes.MachinesCreateRequest{ Name: name, OrgID: orgID, TeamID: teamID, Secret: secret, } result := &apitypes.MachineSegment{} err = m.client.DaemonRoundTrip(ctx, "POST", "/machines", nil, &mcr, &result, output) return result, secret, err }
[ "func", "(", "m", "*", "MachinesClient", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "orgID", ",", "teamID", "*", "identity", ".", "ID", ",", "name", "string", ",", "output", "ProgressFunc", ")", "(", "*", "apitypes", ".", "MachineSegment", ",", "*", "base64", ".", "Value", ",", "error", ")", "{", "secret", ",", "err", ":=", "createTokenSecret", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "mcr", ":=", "apitypes", ".", "MachinesCreateRequest", "{", "Name", ":", "name", ",", "OrgID", ":", "orgID", ",", "TeamID", ":", "teamID", ",", "Secret", ":", "secret", ",", "}", "\n\n", "result", ":=", "&", "apitypes", ".", "MachineSegment", "{", "}", "\n", "err", "=", "m", ".", "client", ".", "DaemonRoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "&", "mcr", ",", "&", "result", ",", "output", ")", "\n", "return", "result", ",", "secret", ",", "err", "\n", "}" ]
// Create a new machine in the given org
[ "Create", "a", "new", "machine", "in", "the", "given", "org" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/api/machines.go#L28-L46
1,864
manifoldco/torus-cli
registry/round_tripper.go
NewRequest
func (rt *DefaultRequestDoer) NewRequest(method, path string, query *url.Values, body interface{}) (*http.Request, error) { b := &bytes.Buffer{} if body != nil { enc := json.NewEncoder(b) err := enc.Encode(body) if err != nil { return nil, err } } if query == nil { query = &url.Values{} } if q := query.Encode(); q != "" { path += "?" + q } req, err := http.NewRequest(method, rt.Host+path, b) if err != nil { return nil, err } req.Header.Set("Host", rt.Host) if body != nil { req.Header.Set("Content-type", "application/json") } return req, nil }
go
func (rt *DefaultRequestDoer) NewRequest(method, path string, query *url.Values, body interface{}) (*http.Request, error) { b := &bytes.Buffer{} if body != nil { enc := json.NewEncoder(b) err := enc.Encode(body) if err != nil { return nil, err } } if query == nil { query = &url.Values{} } if q := query.Encode(); q != "" { path += "?" + q } req, err := http.NewRequest(method, rt.Host+path, b) if err != nil { return nil, err } req.Header.Set("Host", rt.Host) if body != nil { req.Header.Set("Content-type", "application/json") } return req, nil }
[ "func", "(", "rt", "*", "DefaultRequestDoer", ")", "NewRequest", "(", "method", ",", "path", "string", ",", "query", "*", "url", ".", "Values", ",", "body", "interface", "{", "}", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "b", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "body", "!=", "nil", "{", "enc", ":=", "json", ".", "NewEncoder", "(", "b", ")", "\n", "err", ":=", "enc", ".", "Encode", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "query", "==", "nil", "{", "query", "=", "&", "url", ".", "Values", "{", "}", "\n", "}", "\n\n", "if", "q", ":=", "query", ".", "Encode", "(", ")", ";", "q", "!=", "\"", "\"", "{", "path", "+=", "\"", "\"", "+", "q", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "rt", ".", "Host", "+", "path", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "rt", ".", "Host", ")", "\n\n", "if", "body", "!=", "nil", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// NewRequest constructs a new http.Request, with a body containing the json // representation of body, if provided.
[ "NewRequest", "constructs", "a", "new", "http", ".", "Request", "with", "a", "body", "containing", "the", "json", "representation", "of", "body", "if", "provided", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/round_tripper.go#L40-L72
1,865
manifoldco/torus-cli
registry/round_tripper.go
Do
func (rt *DefaultRequestDoer) Do(ctx context.Context, r *http.Request, v interface{}) (*http.Response, error) { resp, err := rt.Client.Do(r) if err != nil { return nil, err } defer resp.Body.Close() err = checkResponseCode(resp) if err != nil { return resp, err } if v != nil { dec := json.NewDecoder(resp.Body) err = dec.Decode(v) if err != nil { return nil, err } } return resp, nil }
go
func (rt *DefaultRequestDoer) Do(ctx context.Context, r *http.Request, v interface{}) (*http.Response, error) { resp, err := rt.Client.Do(r) if err != nil { return nil, err } defer resp.Body.Close() err = checkResponseCode(resp) if err != nil { return resp, err } if v != nil { dec := json.NewDecoder(resp.Body) err = dec.Decode(v) if err != nil { return nil, err } } return resp, nil }
[ "func", "(", "rt", "*", "DefaultRequestDoer", ")", "Do", "(", "ctx", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ",", "v", "interface", "{", "}", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "resp", ",", "err", ":=", "rt", ".", "Client", ".", "Do", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "err", "=", "checkResponseCode", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resp", ",", "err", "\n", "}", "\n\n", "if", "v", "!=", "nil", "{", "dec", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", "\n", "err", "=", "dec", ".", "Decode", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}" ]
// Do executes an http.Request, populating v with the JSON response // on success. // // If the request errors with a JSON formatted response body, it will be // unmarshaled into the returned error.
[ "Do", "executes", "an", "http", ".", "Request", "populating", "v", "with", "the", "JSON", "response", "on", "success", ".", "If", "the", "request", "errors", "with", "a", "JSON", "formatted", "response", "body", "it", "will", "be", "unmarshaled", "into", "the", "returned", "error", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/round_tripper.go#L79-L103
1,866
manifoldco/torus-cli
registry/round_tripper.go
checkResponseCode
func checkResponseCode(r *http.Response) error { if r.StatusCode >= 200 && r.StatusCode < 300 { return nil } rErr := &apitypes.Error{Type: apitypes.LookupErrorType(r.StatusCode)} if r.ContentLength != 0 { dec := json.NewDecoder(r.Body) err := dec.Decode(rErr) if err != nil { return errBadResponse } return rErr } return fmt.Errorf("unknown error response from server with status code %d", r.StatusCode) }
go
func checkResponseCode(r *http.Response) error { if r.StatusCode >= 200 && r.StatusCode < 300 { return nil } rErr := &apitypes.Error{Type: apitypes.LookupErrorType(r.StatusCode)} if r.ContentLength != 0 { dec := json.NewDecoder(r.Body) err := dec.Decode(rErr) if err != nil { return errBadResponse } return rErr } return fmt.Errorf("unknown error response from server with status code %d", r.StatusCode) }
[ "func", "checkResponseCode", "(", "r", "*", "http", ".", "Response", ")", "error", "{", "if", "r", ".", "StatusCode", ">=", "200", "&&", "r", ".", "StatusCode", "<", "300", "{", "return", "nil", "\n", "}", "\n\n", "rErr", ":=", "&", "apitypes", ".", "Error", "{", "Type", ":", "apitypes", ".", "LookupErrorType", "(", "r", ".", "StatusCode", ")", "}", "\n", "if", "r", ".", "ContentLength", "!=", "0", "{", "dec", ":=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", "\n", "err", ":=", "dec", ".", "Decode", "(", "rErr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errBadResponse", "\n", "}", "\n\n", "return", "rErr", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ".", "StatusCode", ")", "\n", "}" ]
// checkReponseCode checks if the response from the server is an error, // and if so, attempts to marshal the response into the error type.
[ "checkReponseCode", "checks", "if", "the", "response", "from", "the", "server", "is", "an", "error", "and", "if", "so", "attempts", "to", "marshal", "the", "response", "into", "the", "error", "type", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/round_tripper.go#L107-L125
1,867
0xAX/notificator
notification.go
CheckTermNotif
func CheckTermNotif() bool { // Checks if terminal-notifier exists, and is accessible. if err := exec.Command("which", "terminal-notifier").Run(); err != nil { return false } // no error, so return true. (terminal-notifier exists) return true }
go
func CheckTermNotif() bool { // Checks if terminal-notifier exists, and is accessible. if err := exec.Command("which", "terminal-notifier").Run(); err != nil { return false } // no error, so return true. (terminal-notifier exists) return true }
[ "func", "CheckTermNotif", "(", ")", "bool", "{", "// Checks if terminal-notifier exists, and is accessible.", "if", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "// no error, so return true. (terminal-notifier exists)", "return", "true", "\n", "}" ]
// Helper function for macOS
[ "Helper", "function", "for", "macOS" ]
d81462e38c2145023f9ecf5414fc84d45d5bfe82
https://github.com/0xAX/notificator/blob/d81462e38c2145023f9ecf5414fc84d45d5bfe82/notification.go#L137-L144
1,868
prashantv/gostub
env.go
SetEnv
func (s *Stubs) SetEnv(k, v string) *Stubs { s.checkEnvKey(k) os.Setenv(k, v) return s }
go
func (s *Stubs) SetEnv(k, v string) *Stubs { s.checkEnvKey(k) os.Setenv(k, v) return s }
[ "func", "(", "s", "*", "Stubs", ")", "SetEnv", "(", "k", ",", "v", "string", ")", "*", "Stubs", "{", "s", ".", "checkEnvKey", "(", "k", ")", "\n\n", "os", ".", "Setenv", "(", "k", ",", "v", ")", "\n", "return", "s", "\n", "}" ]
// SetEnv the specified environent variable to the specified value.
[ "SetEnv", "the", "specified", "environent", "variable", "to", "the", "specified", "value", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/env.go#L13-L18
1,869
prashantv/gostub
env.go
UnsetEnv
func (s *Stubs) UnsetEnv(k string) *Stubs { s.checkEnvKey(k) os.Unsetenv(k) return s }
go
func (s *Stubs) UnsetEnv(k string) *Stubs { s.checkEnvKey(k) os.Unsetenv(k) return s }
[ "func", "(", "s", "*", "Stubs", ")", "UnsetEnv", "(", "k", "string", ")", "*", "Stubs", "{", "s", ".", "checkEnvKey", "(", "k", ")", "\n\n", "os", ".", "Unsetenv", "(", "k", ")", "\n", "return", "s", "\n", "}" ]
// UnsetEnv unsets the specified environent variable.
[ "UnsetEnv", "unsets", "the", "specified", "environent", "variable", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/env.go#L21-L26
1,870
prashantv/gostub
gostub.go
New
func New() *Stubs { return &Stubs{ stubs: make(map[reflect.Value]reflect.Value), origEnv: make(map[string]envVal), } }
go
func New() *Stubs { return &Stubs{ stubs: make(map[reflect.Value]reflect.Value), origEnv: make(map[string]envVal), } }
[ "func", "New", "(", ")", "*", "Stubs", "{", "return", "&", "Stubs", "{", "stubs", ":", "make", "(", "map", "[", "reflect", ".", "Value", "]", "reflect", ".", "Value", ")", ",", "origEnv", ":", "make", "(", "map", "[", "string", "]", "envVal", ")", ",", "}", "\n", "}" ]
// New returns Stubs that can be used to stub out variables.
[ "New", "returns", "Stubs", "that", "can", "be", "used", "to", "stub", "out", "variables", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/gostub.go#L36-L41
1,871
prashantv/gostub
gostub.go
Stub
func (s *Stubs) Stub(varToStub interface{}, stubVal interface{}) *Stubs { v := reflect.ValueOf(varToStub) stub := reflect.ValueOf(stubVal) // Ensure varToStub is a pointer to the variable. if v.Type().Kind() != reflect.Ptr { panic("variable to stub is expected to be a pointer") } if _, ok := s.stubs[v]; !ok { // Store the original value if this is the first time varPtr is being stubbed. s.stubs[v] = reflect.ValueOf(v.Elem().Interface()) } // *varToStub = stubVal v.Elem().Set(stub) return s }
go
func (s *Stubs) Stub(varToStub interface{}, stubVal interface{}) *Stubs { v := reflect.ValueOf(varToStub) stub := reflect.ValueOf(stubVal) // Ensure varToStub is a pointer to the variable. if v.Type().Kind() != reflect.Ptr { panic("variable to stub is expected to be a pointer") } if _, ok := s.stubs[v]; !ok { // Store the original value if this is the first time varPtr is being stubbed. s.stubs[v] = reflect.ValueOf(v.Elem().Interface()) } // *varToStub = stubVal v.Elem().Set(stub) return s }
[ "func", "(", "s", "*", "Stubs", ")", "Stub", "(", "varToStub", "interface", "{", "}", ",", "stubVal", "interface", "{", "}", ")", "*", "Stubs", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "varToStub", ")", "\n", "stub", ":=", "reflect", ".", "ValueOf", "(", "stubVal", ")", "\n\n", "// Ensure varToStub is a pointer to the variable.", "if", "v", ".", "Type", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "s", ".", "stubs", "[", "v", "]", ";", "!", "ok", "{", "// Store the original value if this is the first time varPtr is being stubbed.", "s", ".", "stubs", "[", "v", "]", "=", "reflect", ".", "ValueOf", "(", "v", ".", "Elem", "(", ")", ".", "Interface", "(", ")", ")", "\n", "}", "\n\n", "// *varToStub = stubVal", "v", ".", "Elem", "(", ")", ".", "Set", "(", "stub", ")", "\n", "return", "s", "\n", "}" ]
// Stub replaces the value stored at varToStub with stubVal. // varToStub must be a pointer to the variable. stubVal should have a type // that is assignable to the variable.
[ "Stub", "replaces", "the", "value", "stored", "at", "varToStub", "with", "stubVal", ".", "varToStub", "must", "be", "a", "pointer", "to", "the", "variable", ".", "stubVal", "should", "have", "a", "type", "that", "is", "assignable", "to", "the", "variable", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/gostub.go#L46-L63
1,872
prashantv/gostub
gostub.go
StubFunc
func (s *Stubs) StubFunc(funcVarToStub interface{}, stubVal ...interface{}) *Stubs { funcPtrType := reflect.TypeOf(funcVarToStub) if funcPtrType.Kind() != reflect.Ptr || funcPtrType.Elem().Kind() != reflect.Func { panic("func variable to stub must be a pointer to a function") } funcType := funcPtrType.Elem() if funcType.NumOut() != len(stubVal) { panic(fmt.Sprintf("func type has %v return values, but only %v stub values provided", funcType.NumOut(), len(stubVal))) } return s.Stub(funcVarToStub, FuncReturning(funcPtrType.Elem(), stubVal...).Interface()) }
go
func (s *Stubs) StubFunc(funcVarToStub interface{}, stubVal ...interface{}) *Stubs { funcPtrType := reflect.TypeOf(funcVarToStub) if funcPtrType.Kind() != reflect.Ptr || funcPtrType.Elem().Kind() != reflect.Func { panic("func variable to stub must be a pointer to a function") } funcType := funcPtrType.Elem() if funcType.NumOut() != len(stubVal) { panic(fmt.Sprintf("func type has %v return values, but only %v stub values provided", funcType.NumOut(), len(stubVal))) } return s.Stub(funcVarToStub, FuncReturning(funcPtrType.Elem(), stubVal...).Interface()) }
[ "func", "(", "s", "*", "Stubs", ")", "StubFunc", "(", "funcVarToStub", "interface", "{", "}", ",", "stubVal", "...", "interface", "{", "}", ")", "*", "Stubs", "{", "funcPtrType", ":=", "reflect", ".", "TypeOf", "(", "funcVarToStub", ")", "\n", "if", "funcPtrType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "||", "funcPtrType", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "funcType", ":=", "funcPtrType", ".", "Elem", "(", ")", "\n", "if", "funcType", ".", "NumOut", "(", ")", "!=", "len", "(", "stubVal", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "funcType", ".", "NumOut", "(", ")", ",", "len", "(", "stubVal", ")", ")", ")", "\n", "}", "\n\n", "return", "s", ".", "Stub", "(", "funcVarToStub", ",", "FuncReturning", "(", "funcPtrType", ".", "Elem", "(", ")", ",", "stubVal", "...", ")", ".", "Interface", "(", ")", ")", "\n", "}" ]
// StubFunc replaces a function variable with a function that returns stubVal. // funcVarToStub must be a pointer to a function variable. If the function // returns multiple values, then multiple values should be passed to stubFunc. // The values must match be assignable to the return values' types.
[ "StubFunc", "replaces", "a", "function", "variable", "with", "a", "function", "that", "returns", "stubVal", ".", "funcVarToStub", "must", "be", "a", "pointer", "to", "a", "function", "variable", ".", "If", "the", "function", "returns", "multiple", "values", "then", "multiple", "values", "should", "be", "passed", "to", "stubFunc", ".", "The", "values", "must", "match", "be", "assignable", "to", "the", "return", "values", "types", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/gostub.go#L69-L82
1,873
prashantv/gostub
gostub.go
FuncReturning
func FuncReturning(funcType reflect.Type, results ...interface{}) reflect.Value { var resultValues []reflect.Value for i, r := range results { var retValue reflect.Value if r == nil { // We can't use reflect.ValueOf(nil), so we need to create the zero value. retValue = reflect.Zero(funcType.Out(i)) } else { // We cannot simply use reflect.ValueOf(r) as that does not work for // interface types, as reflect.ValueOf receives the dynamic type, which // is the underlying type. e.g. for an error, it may *errors.errorString. // Instead, we make the return type's expected interface value using // reflect.New, and set the data to the passed in value. tempV := reflect.New(funcType.Out(i)) tempV.Elem().Set(reflect.ValueOf(r)) retValue = tempV.Elem() } resultValues = append(resultValues, retValue) } return reflect.MakeFunc(funcType, func(_ []reflect.Value) []reflect.Value { return resultValues }) }
go
func FuncReturning(funcType reflect.Type, results ...interface{}) reflect.Value { var resultValues []reflect.Value for i, r := range results { var retValue reflect.Value if r == nil { // We can't use reflect.ValueOf(nil), so we need to create the zero value. retValue = reflect.Zero(funcType.Out(i)) } else { // We cannot simply use reflect.ValueOf(r) as that does not work for // interface types, as reflect.ValueOf receives the dynamic type, which // is the underlying type. e.g. for an error, it may *errors.errorString. // Instead, we make the return type's expected interface value using // reflect.New, and set the data to the passed in value. tempV := reflect.New(funcType.Out(i)) tempV.Elem().Set(reflect.ValueOf(r)) retValue = tempV.Elem() } resultValues = append(resultValues, retValue) } return reflect.MakeFunc(funcType, func(_ []reflect.Value) []reflect.Value { return resultValues }) }
[ "func", "FuncReturning", "(", "funcType", "reflect", ".", "Type", ",", "results", "...", "interface", "{", "}", ")", "reflect", ".", "Value", "{", "var", "resultValues", "[", "]", "reflect", ".", "Value", "\n", "for", "i", ",", "r", ":=", "range", "results", "{", "var", "retValue", "reflect", ".", "Value", "\n", "if", "r", "==", "nil", "{", "// We can't use reflect.ValueOf(nil), so we need to create the zero value.", "retValue", "=", "reflect", ".", "Zero", "(", "funcType", ".", "Out", "(", "i", ")", ")", "\n", "}", "else", "{", "// We cannot simply use reflect.ValueOf(r) as that does not work for", "// interface types, as reflect.ValueOf receives the dynamic type, which", "// is the underlying type. e.g. for an error, it may *errors.errorString.", "// Instead, we make the return type's expected interface value using", "// reflect.New, and set the data to the passed in value.", "tempV", ":=", "reflect", ".", "New", "(", "funcType", ".", "Out", "(", "i", ")", ")", "\n", "tempV", ".", "Elem", "(", ")", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "r", ")", ")", "\n", "retValue", "=", "tempV", ".", "Elem", "(", ")", "\n", "}", "\n", "resultValues", "=", "append", "(", "resultValues", ",", "retValue", ")", "\n", "}", "\n", "return", "reflect", ".", "MakeFunc", "(", "funcType", ",", "func", "(", "_", "[", "]", "reflect", ".", "Value", ")", "[", "]", "reflect", ".", "Value", "{", "return", "resultValues", "\n", "}", ")", "\n", "}" ]
// FuncReturning creates a new function with type funcType that returns results.
[ "FuncReturning", "creates", "a", "new", "function", "with", "type", "funcType", "that", "returns", "results", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/gostub.go#L85-L107
1,874
prashantv/gostub
gostub.go
Reset
func (s *Stubs) Reset() { for v, originalVal := range s.stubs { v.Elem().Set(originalVal) } s.resetEnv() }
go
func (s *Stubs) Reset() { for v, originalVal := range s.stubs { v.Elem().Set(originalVal) } s.resetEnv() }
[ "func", "(", "s", "*", "Stubs", ")", "Reset", "(", ")", "{", "for", "v", ",", "originalVal", ":=", "range", "s", ".", "stubs", "{", "v", ".", "Elem", "(", ")", ".", "Set", "(", "originalVal", ")", "\n", "}", "\n", "s", ".", "resetEnv", "(", ")", "\n", "}" ]
// Reset resets all stubbed variables back to their original values.
[ "Reset", "resets", "all", "stubbed", "variables", "back", "to", "their", "original", "values", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/gostub.go#L110-L115
1,875
prashantv/gostub
gostub.go
ResetSingle
func (s *Stubs) ResetSingle(varToStub interface{}) { v := reflect.ValueOf(varToStub) originalVal, ok := s.stubs[v] if !ok { panic("cannot reset variable as it has not been stubbed yet") } v.Elem().Set(originalVal) }
go
func (s *Stubs) ResetSingle(varToStub interface{}) { v := reflect.ValueOf(varToStub) originalVal, ok := s.stubs[v] if !ok { panic("cannot reset variable as it has not been stubbed yet") } v.Elem().Set(originalVal) }
[ "func", "(", "s", "*", "Stubs", ")", "ResetSingle", "(", "varToStub", "interface", "{", "}", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "varToStub", ")", "\n", "originalVal", ",", "ok", ":=", "s", ".", "stubs", "[", "v", "]", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "v", ".", "Elem", "(", ")", ".", "Set", "(", "originalVal", ")", "\n", "}" ]
// ResetSingle resets a single stubbed variable back to its original value.
[ "ResetSingle", "resets", "a", "single", "stubbed", "variable", "back", "to", "its", "original", "value", "." ]
24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3
https://github.com/prashantv/gostub/blob/24ed9cdea43de1d52ea20cab2b7a38e7ed6886b3/gostub.go#L118-L126
1,876
cloudfoundry/garden
server/streamer/streamer.go
New
func New(graceTime time.Duration) *Streamer { return &Streamer{ graceTime: graceTime, streams: sync.Map{}, idGen: new(syncStreamIDGenerator), } }
go
func New(graceTime time.Duration) *Streamer { return &Streamer{ graceTime: graceTime, streams: sync.Map{}, idGen: new(syncStreamIDGenerator), } }
[ "func", "New", "(", "graceTime", "time", ".", "Duration", ")", "*", "Streamer", "{", "return", "&", "Streamer", "{", "graceTime", ":", "graceTime", ",", "streams", ":", "sync", ".", "Map", "{", "}", ",", "idGen", ":", "new", "(", "syncStreamIDGenerator", ")", ",", "}", "\n", "}" ]
// New creates a Streamer with the specified grace time which limits the duration of memory consumption by a stopped stream.
[ "New", "creates", "a", "Streamer", "with", "the", "specified", "grace", "time", "which", "limits", "the", "duration", "of", "memory", "consumption", "by", "a", "stopped", "stream", "." ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/server/streamer/streamer.go#L15-L21
1,877
cloudfoundry/garden
server/streamer/streamer.go
Stream
func (m *Streamer) Stream(stdout, stderr chan []byte) StreamID { sid := m.idGen.next() m.streams.Store(sid, newStream(stdout, stderr)) return sid }
go
func (m *Streamer) Stream(stdout, stderr chan []byte) StreamID { sid := m.idGen.next() m.streams.Store(sid, newStream(stdout, stderr)) return sid }
[ "func", "(", "m", "*", "Streamer", ")", "Stream", "(", "stdout", ",", "stderr", "chan", "[", "]", "byte", ")", "StreamID", "{", "sid", ":=", "m", ".", "idGen", ".", "next", "(", ")", "\n", "m", ".", "streams", ".", "Store", "(", "sid", ",", "newStream", "(", "stdout", ",", "stderr", ")", ")", "\n\n", "return", "sid", "\n", "}" ]
// Stream sets up streaming for the given pair of channels and returns a StreamID to identify the pair. // The caller must call Stop to avoid leaking memory.
[ "Stream", "sets", "up", "streaming", "for", "the", "given", "pair", "of", "channels", "and", "returns", "a", "StreamID", "to", "identify", "the", "pair", ".", "The", "caller", "must", "call", "Stop", "to", "avoid", "leaking", "memory", "." ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/server/streamer/streamer.go#L45-L50
1,878
cloudfoundry/garden
server/streamer/streamer.go
ServeStdout
func (m *Streamer) ServeStdout(streamID StreamID, writer io.Writer) { strm, ok := m.loadStream(streamID) if !ok { return } m.serve(writer, strm.stdout, strm.done) }
go
func (m *Streamer) ServeStdout(streamID StreamID, writer io.Writer) { strm, ok := m.loadStream(streamID) if !ok { return } m.serve(writer, strm.stdout, strm.done) }
[ "func", "(", "m", "*", "Streamer", ")", "ServeStdout", "(", "streamID", "StreamID", ",", "writer", "io", ".", "Writer", ")", "{", "strm", ",", "ok", ":=", "m", ".", "loadStream", "(", "streamID", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "m", ".", "serve", "(", "writer", ",", "strm", ".", "stdout", ",", "strm", ".", "done", ")", "\n", "}" ]
// StreamStdout streams to the specified writer from the standard output channel of the specified pair of channels.
[ "StreamStdout", "streams", "to", "the", "specified", "writer", "from", "the", "standard", "output", "channel", "of", "the", "specified", "pair", "of", "channels", "." ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/server/streamer/streamer.go#L53-L59
1,879
cloudfoundry/garden
server/streamer/streamer.go
ServeStderr
func (m *Streamer) ServeStderr(streamID StreamID, writer io.Writer) { strm, ok := m.loadStream(streamID) if !ok { return } m.serve(writer, strm.stderr, strm.done) }
go
func (m *Streamer) ServeStderr(streamID StreamID, writer io.Writer) { strm, ok := m.loadStream(streamID) if !ok { return } m.serve(writer, strm.stderr, strm.done) }
[ "func", "(", "m", "*", "Streamer", ")", "ServeStderr", "(", "streamID", "StreamID", ",", "writer", "io", ".", "Writer", ")", "{", "strm", ",", "ok", ":=", "m", ".", "loadStream", "(", "streamID", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "m", ".", "serve", "(", "writer", ",", "strm", ".", "stderr", ",", "strm", ".", "done", ")", "\n", "}" ]
// StreamStderr streams to the specified writer from the standard error channel of the specified pair of channels.
[ "StreamStderr", "streams", "to", "the", "specified", "writer", "from", "the", "standard", "error", "channel", "of", "the", "specified", "pair", "of", "channels", "." ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/server/streamer/streamer.go#L62-L68
1,880
cloudfoundry/garden
server/streamer/streamer.go
Stop
func (m *Streamer) Stop(streamID StreamID) { strm, ok := m.loadStream(streamID) if !ok { return } close(strm.done) go func() { // wait some time to ensure clients have connected, once they've // retrieved the stream from the map it's safe to delete the key time.Sleep(m.graceTime) m.streams.Delete(streamID) }() }
go
func (m *Streamer) Stop(streamID StreamID) { strm, ok := m.loadStream(streamID) if !ok { return } close(strm.done) go func() { // wait some time to ensure clients have connected, once they've // retrieved the stream from the map it's safe to delete the key time.Sleep(m.graceTime) m.streams.Delete(streamID) }() }
[ "func", "(", "m", "*", "Streamer", ")", "Stop", "(", "streamID", "StreamID", ")", "{", "strm", ",", "ok", ":=", "m", ".", "loadStream", "(", "streamID", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "close", "(", "strm", ".", "done", ")", "\n\n", "go", "func", "(", ")", "{", "// wait some time to ensure clients have connected, once they've", "// retrieved the stream from the map it's safe to delete the key", "time", ".", "Sleep", "(", "m", ".", "graceTime", ")", "\n\n", "m", ".", "streams", ".", "Delete", "(", "streamID", ")", "\n", "}", "(", ")", "\n", "}" ]
// Stop stops streaming from the specified pair of channels.
[ "Stop", "stops", "streaming", "from", "the", "specified", "pair", "of", "channels", "." ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/server/streamer/streamer.go#L96-L111
1,881
cloudfoundry/garden
net_out_rule.go
IPRangeFromIP
func IPRangeFromIP(ip net.IP) IPRange { return IPRange{Start: ip, End: ip} }
go
func IPRangeFromIP(ip net.IP) IPRange { return IPRange{Start: ip, End: ip} }
[ "func", "IPRangeFromIP", "(", "ip", "net", ".", "IP", ")", "IPRange", "{", "return", "IPRange", "{", "Start", ":", "ip", ",", "End", ":", "ip", "}", "\n", "}" ]
// IPRangeFromIP creates an IPRange containing a single IP
[ "IPRangeFromIP", "creates", "an", "IPRange", "containing", "a", "single", "IP" ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/net_out_rule.go#L50-L52
1,882
cloudfoundry/garden
net_out_rule.go
IPRangeFromIPNet
func IPRangeFromIPNet(ipNet *net.IPNet) IPRange { return IPRange{Start: ipNet.IP, End: lastIP(ipNet)} }
go
func IPRangeFromIPNet(ipNet *net.IPNet) IPRange { return IPRange{Start: ipNet.IP, End: lastIP(ipNet)} }
[ "func", "IPRangeFromIPNet", "(", "ipNet", "*", "net", ".", "IPNet", ")", "IPRange", "{", "return", "IPRange", "{", "Start", ":", "ipNet", ".", "IP", ",", "End", ":", "lastIP", "(", "ipNet", ")", "}", "\n", "}" ]
// IPRangeFromIPNet creates an IPRange containing the same IPs as a given IPNet
[ "IPRangeFromIPNet", "creates", "an", "IPRange", "containing", "the", "same", "IPs", "as", "a", "given", "IPNet" ]
a4e51d29c0e54370a8a2c7ba72bae8354baab5a8
https://github.com/cloudfoundry/garden/blob/a4e51d29c0e54370a8a2c7ba72bae8354baab5a8/net_out_rule.go#L55-L57
1,883
docker/go-plugins-helpers
sdk/encoder.go
DecodeRequest
func DecodeRequest(w http.ResponseWriter, r *http.Request, req interface{}) (err error) { if err = json.NewDecoder(r.Body).Decode(req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } return }
go
func DecodeRequest(w http.ResponseWriter, r *http.Request, req interface{}) (err error) { if err = json.NewDecoder(r.Body).Decode(req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } return }
[ "func", "DecodeRequest", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "req", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "if", "err", "=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", ".", "Decode", "(", "req", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "}", "\n", "return", "\n", "}" ]
// DecodeRequest decodes an http request into a given structure.
[ "DecodeRequest", "decodes", "an", "http", "request", "into", "a", "given", "structure", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/encoder.go#L14-L19
1,884
docker/go-plugins-helpers
sdk/encoder.go
EncodeResponse
func EncodeResponse(w http.ResponseWriter, res interface{}, err bool) { w.Header().Set("Content-Type", DefaultContentTypeV1_1) if err { w.WriteHeader(http.StatusInternalServerError) } json.NewEncoder(w).Encode(res) }
go
func EncodeResponse(w http.ResponseWriter, res interface{}, err bool) { w.Header().Set("Content-Type", DefaultContentTypeV1_1) if err { w.WriteHeader(http.StatusInternalServerError) } json.NewEncoder(w).Encode(res) }
[ "func", "EncodeResponse", "(", "w", "http", ".", "ResponseWriter", ",", "res", "interface", "{", "}", ",", "err", "bool", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "DefaultContentTypeV1_1", ")", "\n", "if", "err", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "res", ")", "\n", "}" ]
// EncodeResponse encodes the given structure into an http response.
[ "EncodeResponse", "encodes", "the", "given", "structure", "into", "an", "http", "response", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/encoder.go#L22-L28
1,885
docker/go-plugins-helpers
sdk/encoder.go
StreamResponse
func StreamResponse(w http.ResponseWriter, data io.ReadCloser) { w.Header().Set("Content-Type", DefaultContentTypeV1_1) if _, err := copyBuf(w, data); err != nil { fmt.Printf("ERROR in stream: %v\n", err) } data.Close() }
go
func StreamResponse(w http.ResponseWriter, data io.ReadCloser) { w.Header().Set("Content-Type", DefaultContentTypeV1_1) if _, err := copyBuf(w, data); err != nil { fmt.Printf("ERROR in stream: %v\n", err) } data.Close() }
[ "func", "StreamResponse", "(", "w", "http", ".", "ResponseWriter", ",", "data", "io", ".", "ReadCloser", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "DefaultContentTypeV1_1", ")", "\n", "if", "_", ",", "err", ":=", "copyBuf", "(", "w", ",", "data", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "data", ".", "Close", "(", ")", "\n", "}" ]
// StreamResponse streams a response object to the client
[ "StreamResponse", "streams", "a", "response", "object", "to", "the", "client" ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/encoder.go#L31-L37
1,886
docker/go-plugins-helpers
sdk/pool.go
copyBuf
func copyBuf(w io.Writer, r io.Reader) (int64, error) { buf := buffer32KPool.Get().([]byte) written, err := io.CopyBuffer(w, r, buf) buffer32KPool.Put(buf) return written, err }
go
func copyBuf(w io.Writer, r io.Reader) (int64, error) { buf := buffer32KPool.Get().([]byte) written, err := io.CopyBuffer(w, r, buf) buffer32KPool.Put(buf) return written, err }
[ "func", "copyBuf", "(", "w", "io", ".", "Writer", ",", "r", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "buf", ":=", "buffer32KPool", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "\n", "written", ",", "err", ":=", "io", ".", "CopyBuffer", "(", "w", ",", "r", ",", "buf", ")", "\n", "buffer32KPool", ".", "Put", "(", "buf", ")", "\n", "return", "written", ",", "err", "\n", "}" ]
// copyBuf uses a shared buffer pool with io.CopyBuffer
[ "copyBuf", "uses", "a", "shared", "buffer", "pool", "with", "io", ".", "CopyBuffer" ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/pool.go#L13-L18
1,887
docker/go-plugins-helpers
graphdriver/shim/shim.go
NewHandlerFromGraphDriver
func NewHandlerFromGraphDriver(init graphDriver.InitFunc) *graphPlugin.Handler { return graphPlugin.NewHandler(&shimDriver{driver: nil, init: init}) }
go
func NewHandlerFromGraphDriver(init graphDriver.InitFunc) *graphPlugin.Handler { return graphPlugin.NewHandler(&shimDriver{driver: nil, init: init}) }
[ "func", "NewHandlerFromGraphDriver", "(", "init", "graphDriver", ".", "InitFunc", ")", "*", "graphPlugin", ".", "Handler", "{", "return", "graphPlugin", ".", "NewHandler", "(", "&", "shimDriver", "{", "driver", ":", "nil", ",", "init", ":", "init", "}", ")", "\n", "}" ]
// NewHandlerFromGraphDriver creates a plugin handler from an existing graph // driver. This could be used, for instance, by the `overlayfs` graph driver // built-in to Docker Engine and it would create a plugin from it that maps // plugin API calls directly to any volume driver that satifies the // graphdriver.Driver interface from Docker Engine.
[ "NewHandlerFromGraphDriver", "creates", "a", "plugin", "handler", "from", "an", "existing", "graph", "driver", ".", "This", "could", "be", "used", "for", "instance", "by", "the", "overlayfs", "graph", "driver", "built", "-", "in", "to", "Docker", "Engine", "and", "it", "would", "create", "a", "plugin", "from", "it", "that", "maps", "plugin", "API", "calls", "directly", "to", "any", "volume", "driver", "that", "satifies", "the", "graphdriver", ".", "Driver", "interface", "from", "Docker", "Engine", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/graphdriver/shim/shim.go#L25-L27
1,888
docker/go-plugins-helpers
sdk/handler.go
NewHandler
func NewHandler(manifest string) Handler { mux := http.NewServeMux() mux.HandleFunc(activatePath, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", DefaultContentTypeV1_1) fmt.Fprintln(w, manifest) }) return Handler{mux: mux} }
go
func NewHandler(manifest string) Handler { mux := http.NewServeMux() mux.HandleFunc(activatePath, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", DefaultContentTypeV1_1) fmt.Fprintln(w, manifest) }) return Handler{mux: mux} }
[ "func", "NewHandler", "(", "manifest", "string", ")", "Handler", "{", "mux", ":=", "http", ".", "NewServeMux", "(", ")", "\n\n", "mux", ".", "HandleFunc", "(", "activatePath", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "DefaultContentTypeV1_1", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ",", "manifest", ")", "\n", "}", ")", "\n\n", "return", "Handler", "{", "mux", ":", "mux", "}", "\n", "}" ]
// NewHandler creates a new Handler with an http mux.
[ "NewHandler", "creates", "a", "new", "Handler", "with", "an", "http", "mux", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/handler.go#L20-L29
1,889
docker/go-plugins-helpers
sdk/handler.go
Serve
func (h Handler) Serve(l net.Listener) error { server := http.Server{ Addr: l.Addr().String(), Handler: h.mux, } return server.Serve(l) }
go
func (h Handler) Serve(l net.Listener) error { server := http.Server{ Addr: l.Addr().String(), Handler: h.mux, } return server.Serve(l) }
[ "func", "(", "h", "Handler", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "server", ":=", "http", ".", "Server", "{", "Addr", ":", "l", ".", "Addr", "(", ")", ".", "String", "(", ")", ",", "Handler", ":", "h", ".", "mux", ",", "}", "\n", "return", "server", ".", "Serve", "(", "l", ")", "\n", "}" ]
// Serve sets up the handler to serve requests on the passed in listener
[ "Serve", "sets", "up", "the", "handler", "to", "serve", "requests", "on", "the", "passed", "in", "listener" ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/handler.go#L32-L38
1,890
docker/go-plugins-helpers
sdk/handler.go
ServeUnix
func (h Handler) ServeUnix(addr string, gid int) error { l, spec, err := newUnixListener(addr, gid) if err != nil { return err } if spec != "" { defer os.Remove(spec) } return h.Serve(l) }
go
func (h Handler) ServeUnix(addr string, gid int) error { l, spec, err := newUnixListener(addr, gid) if err != nil { return err } if spec != "" { defer os.Remove(spec) } return h.Serve(l) }
[ "func", "(", "h", "Handler", ")", "ServeUnix", "(", "addr", "string", ",", "gid", "int", ")", "error", "{", "l", ",", "spec", ",", "err", ":=", "newUnixListener", "(", "addr", ",", "gid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "spec", "!=", "\"", "\"", "{", "defer", "os", ".", "Remove", "(", "spec", ")", "\n", "}", "\n", "return", "h", ".", "Serve", "(", "l", ")", "\n", "}" ]
// ServeUnix makes the handler to listen for requests in a unix socket. // It also creates the socket file in the right directory for docker to read.
[ "ServeUnix", "makes", "the", "handler", "to", "listen", "for", "requests", "in", "a", "unix", "socket", ".", "It", "also", "creates", "the", "socket", "file", "in", "the", "right", "directory", "for", "docker", "to", "read", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/handler.go#L58-L67
1,891
docker/go-plugins-helpers
sdk/handler.go
HandleFunc
func (h Handler) HandleFunc(path string, fn func(w http.ResponseWriter, r *http.Request)) { h.mux.HandleFunc(path, fn) }
go
func (h Handler) HandleFunc(path string, fn func(w http.ResponseWriter, r *http.Request)) { h.mux.HandleFunc(path, fn) }
[ "func", "(", "h", "Handler", ")", "HandleFunc", "(", "path", "string", ",", "fn", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", ")", "{", "h", ".", "mux", ".", "HandleFunc", "(", "path", ",", "fn", ")", "\n", "}" ]
// HandleFunc registers a function to handle a request path with.
[ "HandleFunc", "registers", "a", "function", "to", "handle", "a", "request", "path", "with", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/sdk/handler.go#L86-L88
1,892
docker/go-plugins-helpers
volume/shim/shim.go
NewHandlerFromVolumeDriver
func NewHandlerFromVolumeDriver(d volume.Driver) *volumeplugin.Handler { return volumeplugin.NewHandler(&shimDriver{d}) }
go
func NewHandlerFromVolumeDriver(d volume.Driver) *volumeplugin.Handler { return volumeplugin.NewHandler(&shimDriver{d}) }
[ "func", "NewHandlerFromVolumeDriver", "(", "d", "volume", ".", "Driver", ")", "*", "volumeplugin", ".", "Handler", "{", "return", "volumeplugin", ".", "NewHandler", "(", "&", "shimDriver", "{", "d", "}", ")", "\n", "}" ]
// NewHandlerFromVolumeDriver creates a plugin handler from an existing volume // driver. This could be used, for instance, by the `local` volume driver built-in // to Docker Engine and it would create a plugin from it that maps plugin API calls // directly to any volume driver that satifies the volume.Driver interface from // Docker Engine.
[ "NewHandlerFromVolumeDriver", "creates", "a", "plugin", "handler", "from", "an", "existing", "volume", "driver", ".", "This", "could", "be", "used", "for", "instance", "by", "the", "local", "volume", "driver", "built", "-", "in", "to", "Docker", "Engine", "and", "it", "would", "create", "a", "plugin", "from", "it", "that", "maps", "plugin", "API", "calls", "directly", "to", "any", "volume", "driver", "that", "satifies", "the", "volume", ".", "Driver", "interface", "from", "Docker", "Engine", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/volume/shim/shim.go#L17-L19
1,893
docker/go-plugins-helpers
authorization/api.go
NewHandler
func NewHandler(plugin Plugin) *Handler { h := &Handler{plugin, sdk.NewHandler(manifest)} h.initMux() return h }
go
func NewHandler(plugin Plugin) *Handler { h := &Handler{plugin, sdk.NewHandler(manifest)} h.initMux() return h }
[ "func", "NewHandler", "(", "plugin", "Plugin", ")", "*", "Handler", "{", "h", ":=", "&", "Handler", "{", "plugin", ",", "sdk", ".", "NewHandler", "(", "manifest", ")", "}", "\n", "h", ".", "initMux", "(", ")", "\n", "return", "h", "\n", "}" ]
// NewHandler initializes the request handler with a plugin implementation.
[ "NewHandler", "initializes", "the", "request", "handler", "with", "a", "plugin", "implementation", "." ]
1e6269c305b8c75cfda1c8aa91349c38d7335814
https://github.com/docker/go-plugins-helpers/blob/1e6269c305b8c75cfda1c8aa91349c38d7335814/authorization/api.go#L110-L114
1,894
matryer/try
try.go
Do
func Do(fn Func) error { var err error var cont bool attempt := 1 for { cont, err = fn(attempt) if !cont || err == nil { break } attempt++ if attempt > MaxRetries { return errMaxRetriesReached } } return err }
go
func Do(fn Func) error { var err error var cont bool attempt := 1 for { cont, err = fn(attempt) if !cont || err == nil { break } attempt++ if attempt > MaxRetries { return errMaxRetriesReached } } return err }
[ "func", "Do", "(", "fn", "Func", ")", "error", "{", "var", "err", "error", "\n", "var", "cont", "bool", "\n", "attempt", ":=", "1", "\n", "for", "{", "cont", ",", "err", "=", "fn", "(", "attempt", ")", "\n", "if", "!", "cont", "||", "err", "==", "nil", "{", "break", "\n", "}", "\n", "attempt", "++", "\n", "if", "attempt", ">", "MaxRetries", "{", "return", "errMaxRetriesReached", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Do keeps trying the function until the second argument // returns false, or no error is returned.
[ "Do", "keeps", "trying", "the", "function", "until", "the", "second", "argument", "returns", "false", "or", "no", "error", "is", "returned", "." ]
9ac251b645a2628ef89dbd2986987cc1299408ff
https://github.com/matryer/try/blob/9ac251b645a2628ef89dbd2986987cc1299408ff/try.go#L15-L30
1,895
ajg/form
decode.go
NewDecoder
func NewDecoder(r io.Reader) *Decoder { return &Decoder{r, defaultDelimiter, defaultEscape, false, false} }
go
func NewDecoder(r io.Reader) *Decoder { return &Decoder{r, defaultDelimiter, defaultEscape, false, false} }
[ "func", "NewDecoder", "(", "r", "io", ".", "Reader", ")", "*", "Decoder", "{", "return", "&", "Decoder", "{", "r", ",", "defaultDelimiter", ",", "defaultEscape", ",", "false", ",", "false", "}", "\n", "}" ]
// NewDecoder returns a new form Decoder.
[ "NewDecoder", "returns", "a", "new", "form", "Decoder", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/decode.go#L18-L20
1,896
ajg/form
decode.go
DelimitWith
func (d *Decoder) DelimitWith(r rune) *Decoder { d.d = r return d }
go
func (d *Decoder) DelimitWith(r rune) *Decoder { d.d = r return d }
[ "func", "(", "d", "*", "Decoder", ")", "DelimitWith", "(", "r", "rune", ")", "*", "Decoder", "{", "d", ".", "d", "=", "r", "\n", "return", "d", "\n", "}" ]
// DelimitWith sets r as the delimiter used for composite keys by Decoder d and returns the latter; it is '.' by default.
[ "DelimitWith", "sets", "r", "as", "the", "delimiter", "used", "for", "composite", "keys", "by", "Decoder", "d", "and", "returns", "the", "latter", ";", "it", "is", ".", "by", "default", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/decode.go#L32-L35
1,897
ajg/form
decode.go
Decode
func (d Decoder) Decode(dst interface{}) error { bs, err := ioutil.ReadAll(d.r) if err != nil { return err } vs, err := url.ParseQuery(string(bs)) if err != nil { return err } v := reflect.ValueOf(dst) return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v))) }
go
func (d Decoder) Decode(dst interface{}) error { bs, err := ioutil.ReadAll(d.r) if err != nil { return err } vs, err := url.ParseQuery(string(bs)) if err != nil { return err } v := reflect.ValueOf(dst) return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v))) }
[ "func", "(", "d", "Decoder", ")", "Decode", "(", "dst", "interface", "{", "}", ")", "error", "{", "bs", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "d", ".", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "vs", ",", "err", ":=", "url", ".", "ParseQuery", "(", "string", "(", "bs", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "v", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", "\n", "return", "d", ".", "decodeNode", "(", "v", ",", "parseValues", "(", "d", ".", "d", ",", "d", ".", "e", ",", "vs", ",", "canIndexOrdinally", "(", "v", ")", ")", ")", "\n", "}" ]
// Decode reads in and decodes form-encoded data into dst.
[ "Decode", "reads", "in", "and", "decodes", "form", "-", "encoded", "data", "into", "dst", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/decode.go#L44-L55
1,898
ajg/form
encode.go
NewEncoder
func NewEncoder(w io.Writer) *Encoder { return &Encoder{w, defaultDelimiter, defaultEscape, false} }
go
func NewEncoder(w io.Writer) *Encoder { return &Encoder{w, defaultDelimiter, defaultEscape, false} }
[ "func", "NewEncoder", "(", "w", "io", ".", "Writer", ")", "*", "Encoder", "{", "return", "&", "Encoder", "{", "w", ",", "defaultDelimiter", ",", "defaultEscape", ",", "false", "}", "\n", "}" ]
// NewEncoder returns a new form Encoder.
[ "NewEncoder", "returns", "a", "new", "form", "Encoder", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/encode.go#L20-L22
1,899
ajg/form
encode.go
DelimitWith
func (e *Encoder) DelimitWith(r rune) *Encoder { e.d = r return e }
go
func (e *Encoder) DelimitWith(r rune) *Encoder { e.d = r return e }
[ "func", "(", "e", "*", "Encoder", ")", "DelimitWith", "(", "r", "rune", ")", "*", "Encoder", "{", "e", ".", "d", "=", "r", "\n", "return", "e", "\n", "}" ]
// DelimitWith sets r as the delimiter used for composite keys by Encoder e and returns the latter; it is '.' by default.
[ "DelimitWith", "sets", "r", "as", "the", "delimiter", "used", "for", "composite", "keys", "by", "Encoder", "e", "and", "returns", "the", "latter", ";", "it", "is", ".", "by", "default", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/encode.go#L33-L36