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
partition
stringclasses
1 value
gopasspw/gopass
pkg/config/secrets/config.go
save
func save(filename, passphrase string, data map[string]string) error { buf, err := seal(data, passphrase) if err != nil { return err } return ioutil.WriteFile(filename, buf, 0600) }
go
func save(filename, passphrase string, data map[string]string) error { buf, err := seal(data, passphrase) if err != nil { return err } return ioutil.WriteFile(filename, buf, 0600) }
[ "func", "save", "(", "filename", ",", "passphrase", "string", ",", "data", "map", "[", "string", "]", "string", ")", "error", "{", "buf", ",", "err", ":=", "seal", "(", "data", ",", "passphrase", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "filename", ",", "buf", ",", "0600", ")", "\n", "}" ]
// save will try to marshal, seal and write to disk
[ "save", "will", "try", "to", "marshal", "seal", "and", "write", "to", "disk" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/config/secrets/config.go#L121-L127
train
gopasspw/gopass
pkg/config/secrets/config.go
seal
func seal(data map[string]string, passphrase string) ([]byte, error) { jstr, err := json.Marshal(data) if err != nil { return nil, err } var nonce [nonceLength]byte if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil { return nil, err } salt := make([]byte, saltLength) if _, err := crypto_rand.Read(salt); err != nil { return nil, err } secretKey := deriveKey(passphrase, salt) prefix := append(salt, nonce[:]...) return secretbox.Seal(prefix, jstr, &nonce, &secretKey), nil }
go
func seal(data map[string]string, passphrase string) ([]byte, error) { jstr, err := json.Marshal(data) if err != nil { return nil, err } var nonce [nonceLength]byte if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil { return nil, err } salt := make([]byte, saltLength) if _, err := crypto_rand.Read(salt); err != nil { return nil, err } secretKey := deriveKey(passphrase, salt) prefix := append(salt, nonce[:]...) return secretbox.Seal(prefix, jstr, &nonce, &secretKey), nil }
[ "func", "seal", "(", "data", "map", "[", "string", "]", "string", ",", "passphrase", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "jstr", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "nonce", "[", "nonceLength", "]", "byte", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "crypto_rand", ".", "Reader", ",", "nonce", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "salt", ":=", "make", "(", "[", "]", "byte", ",", "saltLength", ")", "\n", "if", "_", ",", "err", ":=", "crypto_rand", ".", "Read", "(", "salt", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "secretKey", ":=", "deriveKey", "(", "passphrase", ",", "salt", ")", "\n", "prefix", ":=", "append", "(", "salt", ",", "nonce", "[", ":", "]", "...", ")", "\n", "return", "secretbox", ".", "Seal", "(", "prefix", ",", "jstr", ",", "&", "nonce", ",", "&", "secretKey", ")", ",", "nil", "\n", "}" ]
// seal will try to marshal and seal the given data
[ "seal", "will", "try", "to", "marshal", "and", "seal", "the", "given", "data" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/config/secrets/config.go#L130-L146
train
gopasspw/gopass
pkg/cui/recipients.go
AskForPrivateKey
func AskForPrivateKey(ctx context.Context, crypto backend.Crypto, name, prompt string) (string, error) { if !ctxutil.IsInteractive(ctx) { return "", errors.New("can not select private key without terminal") } if crypto == nil { return "", errors.New("can not select private key without valid crypto backend") } kl, err := crypto.ListPrivateKeyIDs(gpg.WithAlwaysTrust(ctx, false)) if err != nil { return "", err } if len(kl) < 1 { return "", errors.New("no useable private keys found") } for i := 0; i < maxTries; i++ { if !ctxutil.IsTerminal(ctx) { return kl[0], nil } // check for context cancelation select { case <-ctx.Done(): return "", errors.New("user aborted") default: } fmt.Fprintln(Stdout, prompt) for i, k := range kl { fmt.Fprintf(Stdout, "[%d] %s - %s\n", i, crypto.Name(), crypto.FormatKey(ctx, k)) } iv, err := termio.AskForInt(ctx, fmt.Sprintf("Please enter the number of a key (0-%d, [q]uit)", len(kl)-1), 0) if err != nil { if err.Error() == "user aborted" { return "", err } continue } if iv >= 0 && iv < len(kl) { return kl[iv], nil } } return "", errors.New("no valid user input") }
go
func AskForPrivateKey(ctx context.Context, crypto backend.Crypto, name, prompt string) (string, error) { if !ctxutil.IsInteractive(ctx) { return "", errors.New("can not select private key without terminal") } if crypto == nil { return "", errors.New("can not select private key without valid crypto backend") } kl, err := crypto.ListPrivateKeyIDs(gpg.WithAlwaysTrust(ctx, false)) if err != nil { return "", err } if len(kl) < 1 { return "", errors.New("no useable private keys found") } for i := 0; i < maxTries; i++ { if !ctxutil.IsTerminal(ctx) { return kl[0], nil } // check for context cancelation select { case <-ctx.Done(): return "", errors.New("user aborted") default: } fmt.Fprintln(Stdout, prompt) for i, k := range kl { fmt.Fprintf(Stdout, "[%d] %s - %s\n", i, crypto.Name(), crypto.FormatKey(ctx, k)) } iv, err := termio.AskForInt(ctx, fmt.Sprintf("Please enter the number of a key (0-%d, [q]uit)", len(kl)-1), 0) if err != nil { if err.Error() == "user aborted" { return "", err } continue } if iv >= 0 && iv < len(kl) { return kl[iv], nil } } return "", errors.New("no valid user input") }
[ "func", "AskForPrivateKey", "(", "ctx", "context", ".", "Context", ",", "crypto", "backend", ".", "Crypto", ",", "name", ",", "prompt", "string", ")", "(", "string", ",", "error", ")", "{", "if", "!", "ctxutil", ".", "IsInteractive", "(", "ctx", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "crypto", "==", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "kl", ",", "err", ":=", "crypto", ".", "ListPrivateKeyIDs", "(", "gpg", ".", "WithAlwaysTrust", "(", "ctx", ",", "false", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "len", "(", "kl", ")", "<", "1", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "maxTries", ";", "i", "++", "{", "if", "!", "ctxutil", ".", "IsTerminal", "(", "ctx", ")", "{", "return", "kl", "[", "0", "]", ",", "nil", "\n", "}", "\n", "// check for context cancelation", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "default", ":", "}", "\n\n", "fmt", ".", "Fprintln", "(", "Stdout", ",", "prompt", ")", "\n", "for", "i", ",", "k", ":=", "range", "kl", "{", "fmt", ".", "Fprintf", "(", "Stdout", ",", "\"", "\\n", "\"", ",", "i", ",", "crypto", ".", "Name", "(", ")", ",", "crypto", ".", "FormatKey", "(", "ctx", ",", "k", ")", ")", "\n", "}", "\n", "iv", ",", "err", ":=", "termio", ".", "AskForInt", "(", "ctx", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "kl", ")", "-", "1", ")", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "continue", "\n", "}", "\n", "if", "iv", ">=", "0", "&&", "iv", "<", "len", "(", "kl", ")", "{", "return", "kl", "[", "iv", "]", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// AskForPrivateKey promts the user to select from a list of private keys
[ "AskForPrivateKey", "promts", "the", "user", "to", "select", "from", "a", "list", "of", "private", "keys" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/cui/recipients.go#L184-L228
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
NewSecring
func NewSecring() *Secring { return &Secring{ data: &xcpb.Secring{ PrivateKeys: make([]*xcpb.PrivateKey, 0, 10), }, } }
go
func NewSecring() *Secring { return &Secring{ data: &xcpb.Secring{ PrivateKeys: make([]*xcpb.PrivateKey, 0, 10), }, } }
[ "func", "NewSecring", "(", ")", "*", "Secring", "{", "return", "&", "Secring", "{", "data", ":", "&", "xcpb", ".", "Secring", "{", "PrivateKeys", ":", "make", "(", "[", "]", "*", "xcpb", ".", "PrivateKey", ",", "0", ",", "10", ")", ",", "}", ",", "}", "\n", "}" ]
// NewSecring initializes and a new secring
[ "NewSecring", "initializes", "and", "a", "new", "secring" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L26-L32
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
LoadSecring
func LoadSecring(file string) (*Secring, error) { pr := NewSecring() pr.File = file buf, err := ioutil.ReadFile(file) if os.IsNotExist(err) { return pr, nil } if err != nil { return nil, err } if err := proto.Unmarshal(buf, pr.data); err != nil { return nil, err } return pr, nil }
go
func LoadSecring(file string) (*Secring, error) { pr := NewSecring() pr.File = file buf, err := ioutil.ReadFile(file) if os.IsNotExist(err) { return pr, nil } if err != nil { return nil, err } if err := proto.Unmarshal(buf, pr.data); err != nil { return nil, err } return pr, nil }
[ "func", "LoadSecring", "(", "file", "string", ")", "(", "*", "Secring", ",", "error", ")", "{", "pr", ":=", "NewSecring", "(", ")", "\n", "pr", ".", "File", "=", "file", "\n\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "pr", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "buf", ",", "pr", ".", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "pr", ",", "nil", "\n", "}" ]
// LoadSecring loads an existing secring from disk. If the file is not found // an empty keyring is returned
[ "LoadSecring", "loads", "an", "existing", "secring", "from", "disk", ".", "If", "the", "file", "is", "not", "found", "an", "empty", "keyring", "is", "returned" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L36-L53
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
Contains
func (p *Secring) Contains(fp string) bool { p.Lock() defer p.Unlock() for _, pk := range p.data.PrivateKeys { if pk.PublicKey.Fingerprint == fp { return true } } return false }
go
func (p *Secring) Contains(fp string) bool { p.Lock() defer p.Unlock() for _, pk := range p.data.PrivateKeys { if pk.PublicKey.Fingerprint == fp { return true } } return false }
[ "func", "(", "p", "*", "Secring", ")", "Contains", "(", "fp", "string", ")", "bool", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "pk", ":=", "range", "p", ".", "data", ".", "PrivateKeys", "{", "if", "pk", ".", "PublicKey", ".", "Fingerprint", "==", "fp", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Contains returns true if the given key is found in the keyring
[ "Contains", "returns", "true", "if", "the", "given", "key", "is", "found", "in", "the", "keyring" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L68-L78
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
KeyIDs
func (p *Secring) KeyIDs() []string { p.Lock() defer p.Unlock() ids := make([]string, 0, len(p.data.PrivateKeys)) for _, pk := range p.data.PrivateKeys { ids = append(ids, pk.PublicKey.Fingerprint) } sort.Strings(ids) return ids }
go
func (p *Secring) KeyIDs() []string { p.Lock() defer p.Unlock() ids := make([]string, 0, len(p.data.PrivateKeys)) for _, pk := range p.data.PrivateKeys { ids = append(ids, pk.PublicKey.Fingerprint) } sort.Strings(ids) return ids }
[ "func", "(", "p", "*", "Secring", ")", "KeyIDs", "(", ")", "[", "]", "string", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "ids", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "p", ".", "data", ".", "PrivateKeys", ")", ")", "\n", "for", "_", ",", "pk", ":=", "range", "p", ".", "data", ".", "PrivateKeys", "{", "ids", "=", "append", "(", "ids", ",", "pk", ".", "PublicKey", ".", "Fingerprint", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "ids", ")", "\n", "return", "ids", "\n", "}" ]
// KeyIDs returns a list of key IDs
[ "KeyIDs", "returns", "a", "list", "of", "key", "IDs" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L81-L91
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
Export
func (p *Secring) Export(id string, withPrivate bool) ([]byte, error) { p.Lock() defer p.Unlock() xpk := p.fetch(id) if xpk == nil { return nil, fmt.Errorf("key not found") } if withPrivate { return proto.Marshal(xpk) } return proto.Marshal(xpk.PublicKey) }
go
func (p *Secring) Export(id string, withPrivate bool) ([]byte, error) { p.Lock() defer p.Unlock() xpk := p.fetch(id) if xpk == nil { return nil, fmt.Errorf("key not found") } if withPrivate { return proto.Marshal(xpk) } return proto.Marshal(xpk.PublicKey) }
[ "func", "(", "p", "*", "Secring", ")", "Export", "(", "id", "string", ",", "withPrivate", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "xpk", ":=", "p", ".", "fetch", "(", "id", ")", "\n", "if", "xpk", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "withPrivate", "{", "return", "proto", ".", "Marshal", "(", "xpk", ")", "\n", "}", "\n", "return", "proto", ".", "Marshal", "(", "xpk", ".", "PublicKey", ")", "\n", "}" ]
// Export marshals a single private key
[ "Export", "marshals", "a", "single", "private", "key" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L94-L107
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
Import
func (p *Secring) Import(buf []byte) error { pk := &xcpb.PrivateKey{} if err := proto.Unmarshal(buf, pk); err != nil { return err } p.insert(pk) return nil }
go
func (p *Secring) Import(buf []byte) error { pk := &xcpb.PrivateKey{} if err := proto.Unmarshal(buf, pk); err != nil { return err } p.insert(pk) return nil }
[ "func", "(", "p", "*", "Secring", ")", "Import", "(", "buf", "[", "]", "byte", ")", "error", "{", "pk", ":=", "&", "xcpb", ".", "PrivateKey", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "buf", ",", "pk", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "p", ".", "insert", "(", "pk", ")", "\n", "return", "nil", "\n", "}" ]
// Import unmarshals and imports a previously exported key
[ "Import", "unmarshals", "and", "imports", "a", "previously", "exported", "key" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L132-L140
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
Set
func (p *Secring) Set(pk *PrivateKey) error { if !pk.Encrypted { return fmt.Errorf("private key must be encrypted") } p.Lock() defer p.Unlock() p.insert(secKRToPB(pk)) return nil }
go
func (p *Secring) Set(pk *PrivateKey) error { if !pk.Encrypted { return fmt.Errorf("private key must be encrypted") } p.Lock() defer p.Unlock() p.insert(secKRToPB(pk)) return nil }
[ "func", "(", "p", "*", "Secring", ")", "Set", "(", "pk", "*", "PrivateKey", ")", "error", "{", "if", "!", "pk", ".", "Encrypted", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "p", ".", "insert", "(", "secKRToPB", "(", "pk", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Set inserts a single key
[ "Set", "inserts", "a", "single", "key" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L143-L153
train
gopasspw/gopass
pkg/backend/crypto/xc/keyring/secring.go
Remove
func (p *Secring) Remove(id string) error { p.Lock() defer p.Unlock() match := -1 for i, pk := range p.data.PrivateKeys { if pk.PublicKey.Fingerprint == id { match = i break } } if match < 0 || match > len(p.data.PrivateKeys) { return fmt.Errorf("not found") } p.data.PrivateKeys = append(p.data.PrivateKeys[:match], p.data.PrivateKeys[match+1:]...) return nil }
go
func (p *Secring) Remove(id string) error { p.Lock() defer p.Unlock() match := -1 for i, pk := range p.data.PrivateKeys { if pk.PublicKey.Fingerprint == id { match = i break } } if match < 0 || match > len(p.data.PrivateKeys) { return fmt.Errorf("not found") } p.data.PrivateKeys = append(p.data.PrivateKeys[:match], p.data.PrivateKeys[match+1:]...) return nil }
[ "func", "(", "p", "*", "Secring", ")", "Remove", "(", "id", "string", ")", "error", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "match", ":=", "-", "1", "\n", "for", "i", ",", "pk", ":=", "range", "p", ".", "data", ".", "PrivateKeys", "{", "if", "pk", ".", "PublicKey", ".", "Fingerprint", "==", "id", "{", "match", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "match", "<", "0", "||", "match", ">", "len", "(", "p", ".", "data", ".", "PrivateKeys", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "data", ".", "PrivateKeys", "=", "append", "(", "p", ".", "data", ".", "PrivateKeys", "[", ":", "match", "]", ",", "p", ".", "data", ".", "PrivateKeys", "[", "match", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}" ]
// Remove deletes the given key
[ "Remove", "deletes", "the", "given", "key" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/crypto/xc/keyring/secring.go#L166-L182
train
gopasspw/gopass
pkg/action/sync.go
Sync
func (s *Action) Sync(ctx context.Context, c *cli.Context) error { store := c.String("store") return s.sync(ctx, c, store) }
go
func (s *Action) Sync(ctx context.Context, c *cli.Context) error { store := c.String("store") return s.sync(ctx, c, store) }
[ "func", "(", "s", "*", "Action", ")", "Sync", "(", "ctx", "context", ".", "Context", ",", "c", "*", "cli", ".", "Context", ")", "error", "{", "store", ":=", "c", ".", "String", "(", "\"", "\"", ")", "\n", "return", "s", ".", "sync", "(", "ctx", ",", "c", ",", "store", ")", "\n", "}" ]
// Sync all stores with their remotes
[ "Sync", "all", "stores", "with", "their", "remotes" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/sync.go#L18-L21
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Open
func Open(path, gpg string) (*Git, error) { if !fsutil.IsDir(filepath.Join(path, ".git")) { return nil, fmt.Errorf("git repo does not exist") } return &Git{ path: path, }, nil }
go
func Open(path, gpg string) (*Git, error) { if !fsutil.IsDir(filepath.Join(path, ".git")) { return nil, fmt.Errorf("git repo does not exist") } return &Git{ path: path, }, nil }
[ "func", "Open", "(", "path", ",", "gpg", "string", ")", "(", "*", "Git", ",", "error", ")", "{", "if", "!", "fsutil", ".", "IsDir", "(", "filepath", ".", "Join", "(", "path", ",", "\"", "\"", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "Git", "{", "path", ":", "path", ",", "}", ",", "nil", "\n", "}" ]
// Open creates a new git cli based git backend
[ "Open", "creates", "a", "new", "git", "cli", "based", "git", "backend" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L31-L38
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Clone
func Clone(ctx context.Context, repo, path string) (*Git, error) { g := &Git{ path: filepath.Dir(path), } if err := g.Cmd(ctx, "Clone", "clone", repo, path); err != nil { return nil, err } g.path = path return g, nil }
go
func Clone(ctx context.Context, repo, path string) (*Git, error) { g := &Git{ path: filepath.Dir(path), } if err := g.Cmd(ctx, "Clone", "clone", repo, path); err != nil { return nil, err } g.path = path return g, nil }
[ "func", "Clone", "(", "ctx", "context", ".", "Context", ",", "repo", ",", "path", "string", ")", "(", "*", "Git", ",", "error", ")", "{", "g", ":=", "&", "Git", "{", "path", ":", "filepath", ".", "Dir", "(", "path", ")", ",", "}", "\n", "if", "err", ":=", "g", ".", "Cmd", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "repo", ",", "path", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "g", ".", "path", "=", "path", "\n", "return", "g", ",", "nil", "\n", "}" ]
// Clone clones an existing git repo and returns a new cli based git backend // configured for this clone repo
[ "Clone", "clones", "an", "existing", "git", "repo", "and", "returns", "a", "new", "cli", "based", "git", "backend", "configured", "for", "this", "clone", "repo" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L42-L51
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Init
func Init(ctx context.Context, path, userName, userEmail string) (*Git, error) { g := &Git{ path: path, } // the git repo may be empty (i.e. no branches, cloned from a fresh remote) // or already initialized. Only run git init if the folder is completely empty if !g.IsInitialized() { if err := g.Cmd(ctx, "Init", "init"); err != nil { return nil, errors.Errorf("failed to initialize git: %s", err) } out.Red(ctx, "git initialized at %s", g.path) } if !ctxutil.IsGitInit(ctx) { return g, nil } // initialize the local git config if err := g.InitConfig(ctx, userName, userEmail); err != nil { return g, errors.Errorf("failed to configure git: %s", err) } out.Red(ctx, "git configured at %s", g.path) // add current content of the store if err := g.Add(ctx, g.path); err != nil { return g, errors.Wrapf(err, "failed to add '%s' to git", g.path) } // commit if there is something to commit if !g.HasStagedChanges(ctx) { out.Debug(ctx, "No staged changes") return g, nil } if err := g.Commit(ctx, "Add current content of password store"); err != nil { return g, errors.Wrapf(err, "failed to commit changes to git") } return g, nil }
go
func Init(ctx context.Context, path, userName, userEmail string) (*Git, error) { g := &Git{ path: path, } // the git repo may be empty (i.e. no branches, cloned from a fresh remote) // or already initialized. Only run git init if the folder is completely empty if !g.IsInitialized() { if err := g.Cmd(ctx, "Init", "init"); err != nil { return nil, errors.Errorf("failed to initialize git: %s", err) } out.Red(ctx, "git initialized at %s", g.path) } if !ctxutil.IsGitInit(ctx) { return g, nil } // initialize the local git config if err := g.InitConfig(ctx, userName, userEmail); err != nil { return g, errors.Errorf("failed to configure git: %s", err) } out.Red(ctx, "git configured at %s", g.path) // add current content of the store if err := g.Add(ctx, g.path); err != nil { return g, errors.Wrapf(err, "failed to add '%s' to git", g.path) } // commit if there is something to commit if !g.HasStagedChanges(ctx) { out.Debug(ctx, "No staged changes") return g, nil } if err := g.Commit(ctx, "Add current content of password store"); err != nil { return g, errors.Wrapf(err, "failed to commit changes to git") } return g, nil }
[ "func", "Init", "(", "ctx", "context", ".", "Context", ",", "path", ",", "userName", ",", "userEmail", "string", ")", "(", "*", "Git", ",", "error", ")", "{", "g", ":=", "&", "Git", "{", "path", ":", "path", ",", "}", "\n", "// the git repo may be empty (i.e. no branches, cloned from a fresh remote)", "// or already initialized. Only run git init if the folder is completely empty", "if", "!", "g", ".", "IsInitialized", "(", ")", "{", "if", "err", ":=", "g", ".", "Cmd", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "out", ".", "Red", "(", "ctx", ",", "\"", "\"", ",", "g", ".", "path", ")", "\n", "}", "\n\n", "if", "!", "ctxutil", ".", "IsGitInit", "(", "ctx", ")", "{", "return", "g", ",", "nil", "\n", "}", "\n\n", "// initialize the local git config", "if", "err", ":=", "g", ".", "InitConfig", "(", "ctx", ",", "userName", ",", "userEmail", ")", ";", "err", "!=", "nil", "{", "return", "g", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "out", ".", "Red", "(", "ctx", ",", "\"", "\"", ",", "g", ".", "path", ")", "\n\n", "// add current content of the store", "if", "err", ":=", "g", ".", "Add", "(", "ctx", ",", "g", ".", "path", ")", ";", "err", "!=", "nil", "{", "return", "g", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "g", ".", "path", ")", "\n", "}", "\n\n", "// commit if there is something to commit", "if", "!", "g", ".", "HasStagedChanges", "(", "ctx", ")", "{", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ")", "\n", "return", "g", ",", "nil", "\n", "}", "\n\n", "if", "err", ":=", "g", ".", "Commit", "(", "ctx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "g", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "g", ",", "nil", "\n", "}" ]
// Init initializes this store's git repo
[ "Init", "initializes", "this", "store", "s", "git", "repo" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L54-L93
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Cmd
func (g *Git) Cmd(ctx context.Context, name string, args ...string) error { stdout, stderr, err := g.captureCmd(ctx, name, args...) if err != nil { out.Debug(ctx, "Output:\n Stdout: '%s'\n Stderr: '%s'", string(stdout), string(stderr)) return err } return nil }
go
func (g *Git) Cmd(ctx context.Context, name string, args ...string) error { stdout, stderr, err := g.captureCmd(ctx, name, args...) if err != nil { out.Debug(ctx, "Output:\n Stdout: '%s'\n Stderr: '%s'", string(stdout), string(stderr)) return err } return nil }
[ "func", "(", "g", "*", "Git", ")", "Cmd", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "args", "...", "string", ")", "error", "{", "stdout", ",", "stderr", ",", "err", ":=", "g", ".", "captureCmd", "(", "ctx", ",", "name", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "out", ".", "Debug", "(", "ctx", ",", "\"", "\\n", "\\n", "\"", ",", "string", "(", "stdout", ")", ",", "string", "(", "stderr", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Cmd runs an git command
[ "Cmd", "runs", "an", "git", "command" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L115-L123
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Version
func (g *Git) Version(ctx context.Context) semver.Version { v := semver.Version{} cmd := exec.CommandContext(ctx, "git", "version") cmdout, err := cmd.Output() if err != nil { out.Debug(ctx, "Failed to run 'git version': %s", err) return v } svStr := strings.TrimPrefix(string(cmdout), "git version ") if p := strings.Fields(svStr); len(p) > 0 { svStr = p[0] } sv, err := semver.ParseTolerant(svStr) if err != nil { out.Debug(ctx, "Failed to parse '%s' as semver: %s", svStr, err) return v } return sv }
go
func (g *Git) Version(ctx context.Context) semver.Version { v := semver.Version{} cmd := exec.CommandContext(ctx, "git", "version") cmdout, err := cmd.Output() if err != nil { out.Debug(ctx, "Failed to run 'git version': %s", err) return v } svStr := strings.TrimPrefix(string(cmdout), "git version ") if p := strings.Fields(svStr); len(p) > 0 { svStr = p[0] } sv, err := semver.ParseTolerant(svStr) if err != nil { out.Debug(ctx, "Failed to parse '%s' as semver: %s", svStr, err) return v } return sv }
[ "func", "(", "g", "*", "Git", ")", "Version", "(", "ctx", "context", ".", "Context", ")", "semver", ".", "Version", "{", "v", ":=", "semver", ".", "Version", "{", "}", "\n\n", "cmd", ":=", "exec", ".", "CommandContext", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmdout", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "return", "v", "\n", "}", "\n\n", "svStr", ":=", "strings", ".", "TrimPrefix", "(", "string", "(", "cmdout", ")", ",", "\"", "\"", ")", "\n", "if", "p", ":=", "strings", ".", "Fields", "(", "svStr", ")", ";", "len", "(", "p", ")", ">", "0", "{", "svStr", "=", "p", "[", "0", "]", "\n", "}", "\n\n", "sv", ",", "err", ":=", "semver", ".", "ParseTolerant", "(", "svStr", ")", "\n", "if", "err", "!=", "nil", "{", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "svStr", ",", "err", ")", "\n", "return", "v", "\n", "}", "\n", "return", "sv", "\n", "}" ]
// Version returns the git version as major, minor and patch level
[ "Version", "returns", "the", "git", "version", "as", "major", "minor", "and", "patch", "level" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L131-L152
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Add
func (g *Git) Add(ctx context.Context, files ...string) error { if !g.IsInitialized() { return store.ErrGitNotInit } for i := range files { files[i] = strings.TrimPrefix(files[i], g.path+"/") } args := []string{"add", "--all", "--force"} args = append(args, files...) return g.Cmd(ctx, "gitAdd", args...) }
go
func (g *Git) Add(ctx context.Context, files ...string) error { if !g.IsInitialized() { return store.ErrGitNotInit } for i := range files { files[i] = strings.TrimPrefix(files[i], g.path+"/") } args := []string{"add", "--all", "--force"} args = append(args, files...) return g.Cmd(ctx, "gitAdd", args...) }
[ "func", "(", "g", "*", "Git", ")", "Add", "(", "ctx", "context", ".", "Context", ",", "files", "...", "string", ")", "error", "{", "if", "!", "g", ".", "IsInitialized", "(", ")", "{", "return", "store", ".", "ErrGitNotInit", "\n", "}", "\n\n", "for", "i", ":=", "range", "files", "{", "files", "[", "i", "]", "=", "strings", ".", "TrimPrefix", "(", "files", "[", "i", "]", ",", "g", ".", "path", "+", "\"", "\"", ")", "\n", "}", "\n\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "args", "=", "append", "(", "args", ",", "files", "...", ")", "\n\n", "return", "g", ".", "Cmd", "(", "ctx", ",", "\"", "\"", ",", "args", "...", ")", "\n", "}" ]
// Add adds the listed files to the git index
[ "Add", "adds", "the", "listed", "files", "to", "the", "git", "index" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L160-L173
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
HasStagedChanges
func (g *Git) HasStagedChanges(ctx context.Context) bool { if err := g.Cmd(ctx, "gitDiffIndex", "diff-index", "--quiet", "HEAD"); err != nil { return true } return false }
go
func (g *Git) HasStagedChanges(ctx context.Context) bool { if err := g.Cmd(ctx, "gitDiffIndex", "diff-index", "--quiet", "HEAD"); err != nil { return true } return false }
[ "func", "(", "g", "*", "Git", ")", "HasStagedChanges", "(", "ctx", "context", ".", "Context", ")", "bool", "{", "if", "err", ":=", "g", ".", "Cmd", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasStagedChanges returns true if there are any staged changes which can be committed
[ "HasStagedChanges", "returns", "true", "if", "there", "are", "any", "staged", "changes", "which", "can", "be", "committed" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L176-L181
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Commit
func (g *Git) Commit(ctx context.Context, msg string) error { if !g.IsInitialized() { return store.ErrGitNotInit } if !g.HasStagedChanges(ctx) { return store.ErrGitNothingToCommit } return g.Cmd(ctx, "gitCommit", "commit", "-m", msg) }
go
func (g *Git) Commit(ctx context.Context, msg string) error { if !g.IsInitialized() { return store.ErrGitNotInit } if !g.HasStagedChanges(ctx) { return store.ErrGitNothingToCommit } return g.Cmd(ctx, "gitCommit", "commit", "-m", msg) }
[ "func", "(", "g", "*", "Git", ")", "Commit", "(", "ctx", "context", ".", "Context", ",", "msg", "string", ")", "error", "{", "if", "!", "g", ".", "IsInitialized", "(", ")", "{", "return", "store", ".", "ErrGitNotInit", "\n", "}", "\n\n", "if", "!", "g", ".", "HasStagedChanges", "(", "ctx", ")", "{", "return", "store", ".", "ErrGitNothingToCommit", "\n", "}", "\n\n", "return", "g", ".", "Cmd", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "msg", ")", "\n", "}" ]
// Commit creates a new git commit with the given commit message
[ "Commit", "creates", "a", "new", "git", "commit", "with", "the", "given", "commit", "message" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L184-L194
train
gopasspw/gopass
pkg/backend/rcs/git/cli/git.go
Push
func (g *Git) Push(ctx context.Context, remote, branch string) error { return g.PushPull(ctx, "push", remote, branch) }
go
func (g *Git) Push(ctx context.Context, remote, branch string) error { return g.PushPull(ctx, "push", remote, branch) }
[ "func", "(", "g", "*", "Git", ")", "Push", "(", "ctx", "context", ".", "Context", ",", "remote", ",", "branch", "string", ")", "error", "{", "return", "g", ".", "PushPull", "(", "ctx", ",", "\"", "\"", ",", "remote", ",", "branch", ")", "\n", "}" ]
// Push pushes to the git remote
[ "Push", "pushes", "to", "the", "git", "remote" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/rcs/git/cli/git.go#L256-L258
train
gopasspw/gopass
pkg/store/sub/gpg.go
exportPublicKey
func (s *Store) exportPublicKey(ctx context.Context, r string) (string, error) { filename := filepath.Join(keyDir, r) // do not overwrite existing keys if s.storage.Exists(ctx, filename) { return "", nil } pk, err := s.crypto.ExportPublicKey(ctx, r) if err != nil { return "", errors.Wrapf(err, "failed to export public key") } // ECC keys are at least 700 byte, RSA should be a lot bigger if len(pk) < 32 { return "", errors.New("exported key too small") } if err := s.storage.Set(ctx, filename, pk); err != nil { return "", errors.Wrapf(err, "failed to write exported public key to store") } return filename, nil }
go
func (s *Store) exportPublicKey(ctx context.Context, r string) (string, error) { filename := filepath.Join(keyDir, r) // do not overwrite existing keys if s.storage.Exists(ctx, filename) { return "", nil } pk, err := s.crypto.ExportPublicKey(ctx, r) if err != nil { return "", errors.Wrapf(err, "failed to export public key") } // ECC keys are at least 700 byte, RSA should be a lot bigger if len(pk) < 32 { return "", errors.New("exported key too small") } if err := s.storage.Set(ctx, filename, pk); err != nil { return "", errors.Wrapf(err, "failed to write exported public key to store") } return filename, nil }
[ "func", "(", "s", "*", "Store", ")", "exportPublicKey", "(", "ctx", "context", ".", "Context", ",", "r", "string", ")", "(", "string", ",", "error", ")", "{", "filename", ":=", "filepath", ".", "Join", "(", "keyDir", ",", "r", ")", "\n\n", "// do not overwrite existing keys", "if", "s", ".", "storage", ".", "Exists", "(", "ctx", ",", "filename", ")", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "pk", ",", "err", ":=", "s", ".", "crypto", ".", "ExportPublicKey", "(", "ctx", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// ECC keys are at least 700 byte, RSA should be a lot bigger", "if", "len", "(", "pk", ")", "<", "32", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "storage", ".", "Set", "(", "ctx", ",", "filename", ",", "pk", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "filename", ",", "nil", "\n", "}" ]
// export an ASCII armored public key
[ "export", "an", "ASCII", "armored", "public", "key" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/store/sub/gpg.go#L85-L108
train
gopasspw/gopass
pkg/store/sub/gpg.go
importPublicKey
func (s *Store) importPublicKey(ctx context.Context, r string) error { for _, kd := range []string{keyDir, oldKeyDir} { filename := filepath.Join(kd, r) if !s.storage.Exists(ctx, filename) { out.Debug(ctx, "Public Key %s not found at %s", r, filename) continue } pk, err := s.storage.Get(ctx, filename) if err != nil { return err } return s.crypto.ImportPublicKey(ctx, pk) } return fmt.Errorf("public key not found in store") }
go
func (s *Store) importPublicKey(ctx context.Context, r string) error { for _, kd := range []string{keyDir, oldKeyDir} { filename := filepath.Join(kd, r) if !s.storage.Exists(ctx, filename) { out.Debug(ctx, "Public Key %s not found at %s", r, filename) continue } pk, err := s.storage.Get(ctx, filename) if err != nil { return err } return s.crypto.ImportPublicKey(ctx, pk) } return fmt.Errorf("public key not found in store") }
[ "func", "(", "s", "*", "Store", ")", "importPublicKey", "(", "ctx", "context", ".", "Context", ",", "r", "string", ")", "error", "{", "for", "_", ",", "kd", ":=", "range", "[", "]", "string", "{", "keyDir", ",", "oldKeyDir", "}", "{", "filename", ":=", "filepath", ".", "Join", "(", "kd", ",", "r", ")", "\n", "if", "!", "s", ".", "storage", ".", "Exists", "(", "ctx", ",", "filename", ")", "{", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "r", ",", "filename", ")", "\n", "continue", "\n", "}", "\n", "pk", ",", "err", ":=", "s", ".", "storage", ".", "Get", "(", "ctx", ",", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "crypto", ".", "ImportPublicKey", "(", "ctx", ",", "pk", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// import an public key into the default keyring
[ "import", "an", "public", "key", "into", "the", "default", "keyring" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/store/sub/gpg.go#L111-L125
train
gopasspw/gopass
pkg/action/list.go
List
func (s *Action) List(ctx context.Context, c *cli.Context) error { filter := c.Args().First() flat := c.Bool("flat") stripPrefix := c.Bool("strip-prefix") limit := c.Int("limit") folders := c.Bool("folders") // we only support listing folders in flat mode currently if folders { flat = true } ctx = s.Store.WithConfig(ctx, filter) l, err := s.Store.Tree(ctx) if err != nil { return ExitError(ctx, ExitList, err, "failed to list store: %s", err) } if filter == "" { return s.listAll(ctx, l, limit, flat, folders) } return s.listFiltered(ctx, l, limit, flat, folders, stripPrefix, filter) }
go
func (s *Action) List(ctx context.Context, c *cli.Context) error { filter := c.Args().First() flat := c.Bool("flat") stripPrefix := c.Bool("strip-prefix") limit := c.Int("limit") folders := c.Bool("folders") // we only support listing folders in flat mode currently if folders { flat = true } ctx = s.Store.WithConfig(ctx, filter) l, err := s.Store.Tree(ctx) if err != nil { return ExitError(ctx, ExitList, err, "failed to list store: %s", err) } if filter == "" { return s.listAll(ctx, l, limit, flat, folders) } return s.listFiltered(ctx, l, limit, flat, folders, stripPrefix, filter) }
[ "func", "(", "s", "*", "Action", ")", "List", "(", "ctx", "context", ".", "Context", ",", "c", "*", "cli", ".", "Context", ")", "error", "{", "filter", ":=", "c", ".", "Args", "(", ")", ".", "First", "(", ")", "\n", "flat", ":=", "c", ".", "Bool", "(", "\"", "\"", ")", "\n", "stripPrefix", ":=", "c", ".", "Bool", "(", "\"", "\"", ")", "\n", "limit", ":=", "c", ".", "Int", "(", "\"", "\"", ")", "\n", "folders", ":=", "c", ".", "Bool", "(", "\"", "\"", ")", "\n", "// we only support listing folders in flat mode currently", "if", "folders", "{", "flat", "=", "true", "\n", "}", "\n\n", "ctx", "=", "s", ".", "Store", ".", "WithConfig", "(", "ctx", ",", "filter", ")", "\n\n", "l", ",", "err", ":=", "s", ".", "Store", ".", "Tree", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ExitError", "(", "ctx", ",", "ExitList", ",", "err", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "filter", "==", "\"", "\"", "{", "return", "s", ".", "listAll", "(", "ctx", ",", "l", ",", "limit", ",", "flat", ",", "folders", ")", "\n", "}", "\n", "return", "s", ".", "listFiltered", "(", "ctx", ",", "l", ",", "limit", ",", "flat", ",", "folders", ",", "stripPrefix", ",", "filter", ")", "\n", "}" ]
// List all secrets as a tree. If the filter argument is non-empty // display only those that have this prefix
[ "List", "all", "secrets", "as", "a", "tree", ".", "If", "the", "filter", "argument", "is", "non", "-", "empty", "display", "only", "those", "that", "have", "this", "prefix" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/list.go#L24-L46
train
gopasspw/gopass
pkg/action/list.go
redirectPager
func redirectPager(ctx context.Context, subtree tree.Tree) (io.Writer, *bytes.Buffer) { if ctxutil.IsNoPager(ctx) { return stdout, nil } rows, _ := termutil.GetTermsize() if rows <= 0 { return stdout, nil } if subtree == nil || subtree.Len() < rows { return stdout, nil } color.NoColor = true buf := &bytes.Buffer{} return buf, buf }
go
func redirectPager(ctx context.Context, subtree tree.Tree) (io.Writer, *bytes.Buffer) { if ctxutil.IsNoPager(ctx) { return stdout, nil } rows, _ := termutil.GetTermsize() if rows <= 0 { return stdout, nil } if subtree == nil || subtree.Len() < rows { return stdout, nil } color.NoColor = true buf := &bytes.Buffer{} return buf, buf }
[ "func", "redirectPager", "(", "ctx", "context", ".", "Context", ",", "subtree", "tree", ".", "Tree", ")", "(", "io", ".", "Writer", ",", "*", "bytes", ".", "Buffer", ")", "{", "if", "ctxutil", ".", "IsNoPager", "(", "ctx", ")", "{", "return", "stdout", ",", "nil", "\n", "}", "\n", "rows", ",", "_", ":=", "termutil", ".", "GetTermsize", "(", ")", "\n", "if", "rows", "<=", "0", "{", "return", "stdout", ",", "nil", "\n", "}", "\n", "if", "subtree", "==", "nil", "||", "subtree", ".", "Len", "(", ")", "<", "rows", "{", "return", "stdout", ",", "nil", "\n", "}", "\n", "color", ".", "NoColor", "=", "true", "\n", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "return", "buf", ",", "buf", "\n", "}" ]
// redirectPager returns a redirected io.Writer if the output would exceed // the terminal size
[ "redirectPager", "returns", "a", "redirected", "io", ".", "Writer", "if", "the", "output", "would", "exceed", "the", "terminal", "size" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/list.go#L90-L104
train
gopasspw/gopass
pkg/action/list.go
listAll
func (s *Action) listAll(ctx context.Context, l tree.Tree, limit int, flat, folders bool) error { if flat { listOver := l.List if folders { listOver = l.ListFolders } for _, e := range listOver(limit) { fmt.Fprintln(stdout, e) } return nil } // we may need to redirect stdout for the pager support so, buf := redirectPager(ctx, l) fmt.Fprintln(so, l.Format(limit)) if buf != nil { if err := s.pager(ctx, buf); err != nil { return ExitError(ctx, ExitUnknown, err, "failed to invoke pager: %s", err) } } return nil }
go
func (s *Action) listAll(ctx context.Context, l tree.Tree, limit int, flat, folders bool) error { if flat { listOver := l.List if folders { listOver = l.ListFolders } for _, e := range listOver(limit) { fmt.Fprintln(stdout, e) } return nil } // we may need to redirect stdout for the pager support so, buf := redirectPager(ctx, l) fmt.Fprintln(so, l.Format(limit)) if buf != nil { if err := s.pager(ctx, buf); err != nil { return ExitError(ctx, ExitUnknown, err, "failed to invoke pager: %s", err) } } return nil }
[ "func", "(", "s", "*", "Action", ")", "listAll", "(", "ctx", "context", ".", "Context", ",", "l", "tree", ".", "Tree", ",", "limit", "int", ",", "flat", ",", "folders", "bool", ")", "error", "{", "if", "flat", "{", "listOver", ":=", "l", ".", "List", "\n", "if", "folders", "{", "listOver", "=", "l", ".", "ListFolders", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "listOver", "(", "limit", ")", "{", "fmt", ".", "Fprintln", "(", "stdout", ",", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// we may need to redirect stdout for the pager support", "so", ",", "buf", ":=", "redirectPager", "(", "ctx", ",", "l", ")", "\n\n", "fmt", ".", "Fprintln", "(", "so", ",", "l", ".", "Format", "(", "limit", ")", ")", "\n", "if", "buf", "!=", "nil", "{", "if", "err", ":=", "s", ".", "pager", "(", "ctx", ",", "buf", ")", ";", "err", "!=", "nil", "{", "return", "ExitError", "(", "ctx", ",", "ExitUnknown", ",", "err", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// listAll will unconditionally list all entries, used if no filter is given
[ "listAll", "will", "unconditionally", "list", "all", "entries", "used", "if", "no", "filter", "is", "given" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/list.go#L107-L129
train
gopasspw/gopass
pkg/action/list.go
pager
func (s *Action) pager(ctx context.Context, buf io.Reader) error { pager := os.Getenv("PAGER") if pager == "" { fmt.Fprintln(stdout, buf) return nil } args, err := shellquote.Split(pager) if err != nil { return errors.Wrapf(err, "failed to split pager command") } cmd := exec.CommandContext(ctx, args[0], args[1:]...) cmd.Stdin = buf cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() }
go
func (s *Action) pager(ctx context.Context, buf io.Reader) error { pager := os.Getenv("PAGER") if pager == "" { fmt.Fprintln(stdout, buf) return nil } args, err := shellquote.Split(pager) if err != nil { return errors.Wrapf(err, "failed to split pager command") } cmd := exec.CommandContext(ctx, args[0], args[1:]...) cmd.Stdin = buf cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() }
[ "func", "(", "s", "*", "Action", ")", "pager", "(", "ctx", "context", ".", "Context", ",", "buf", "io", ".", "Reader", ")", "error", "{", "pager", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "pager", "==", "\"", "\"", "{", "fmt", ".", "Fprintln", "(", "stdout", ",", "buf", ")", "\n", "return", "nil", "\n", "}", "\n\n", "args", ",", "err", ":=", "shellquote", ".", "Split", "(", "pager", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "cmd", ":=", "exec", ".", "CommandContext", "(", "ctx", ",", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "...", ")", "\n", "cmd", ".", "Stdin", "=", "buf", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// pager invokes the default pager with the given content
[ "pager", "invokes", "the", "default", "pager", "with", "the", "given", "content" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/list.go#L132-L150
train
gopasspw/gopass
pkg/termutil/termutil_others.go
GetTermsize
func GetTermsize() (int, int) { ts := termSize{} ret, _, _ := syscall.Syscall( syscall.SYS_IOCTL, uintptr(syscall.Stdin), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ts)), ) if int(ret) == -1 { return -1, -1 } return int(ts.Rows), int(ts.Cols) }
go
func GetTermsize() (int, int) { ts := termSize{} ret, _, _ := syscall.Syscall( syscall.SYS_IOCTL, uintptr(syscall.Stdin), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ts)), ) if int(ret) == -1 { return -1, -1 } return int(ts.Rows), int(ts.Cols) }
[ "func", "GetTermsize", "(", ")", "(", "int", ",", "int", ")", "{", "ts", ":=", "termSize", "{", "}", "\n", "ret", ",", "_", ",", "_", ":=", "syscall", ".", "Syscall", "(", "syscall", ".", "SYS_IOCTL", ",", "uintptr", "(", "syscall", ".", "Stdin", ")", ",", "uintptr", "(", "syscall", ".", "TIOCGWINSZ", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "ts", ")", ")", ",", ")", "\n", "if", "int", "(", "ret", ")", "==", "-", "1", "{", "return", "-", "1", ",", "-", "1", "\n", "}", "\n", "return", "int", "(", "ts", ".", "Rows", ")", ",", "int", "(", "ts", ".", "Cols", ")", "\n", "}" ]
// GetTermsize returns the size of the current terminal
[ "GetTermsize", "returns", "the", "size", "of", "the", "current", "terminal" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/termutil/termutil_others.go#L18-L30
train
gopasspw/gopass
pkg/backend/strings.go
CryptoBackends
func CryptoBackends() []string { bes := make([]string, 0, len(cryptoNameToBackendMap)) for k := range cryptoNameToBackendMap { bes = append(bes, k) } sort.Strings(bes) return bes }
go
func CryptoBackends() []string { bes := make([]string, 0, len(cryptoNameToBackendMap)) for k := range cryptoNameToBackendMap { bes = append(bes, k) } sort.Strings(bes) return bes }
[ "func", "CryptoBackends", "(", ")", "[", "]", "string", "{", "bes", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cryptoNameToBackendMap", ")", ")", "\n", "for", "k", ":=", "range", "cryptoNameToBackendMap", "{", "bes", "=", "append", "(", "bes", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "bes", ")", "\n", "return", "bes", "\n", "}" ]
// CryptoBackends returns the list of registered crypto backends.
[ "CryptoBackends", "returns", "the", "list", "of", "registered", "crypto", "backends", "." ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/strings.go#L27-L34
train
gopasspw/gopass
pkg/backend/strings.go
RCSBackends
func RCSBackends() []string { bes := make([]string, 0, len(rcsNameToBackendMap)) for k := range rcsNameToBackendMap { bes = append(bes, k) } sort.Strings(bes) return bes }
go
func RCSBackends() []string { bes := make([]string, 0, len(rcsNameToBackendMap)) for k := range rcsNameToBackendMap { bes = append(bes, k) } sort.Strings(bes) return bes }
[ "func", "RCSBackends", "(", ")", "[", "]", "string", "{", "bes", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "rcsNameToBackendMap", ")", ")", "\n", "for", "k", ":=", "range", "rcsNameToBackendMap", "{", "bes", "=", "append", "(", "bes", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "bes", ")", "\n", "return", "bes", "\n", "}" ]
// RCSBackends returns the list of registered RCS backends.
[ "RCSBackends", "returns", "the", "list", "of", "registered", "RCS", "backends", "." ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/strings.go#L37-L44
train
gopasspw/gopass
pkg/backend/strings.go
StorageBackends
func StorageBackends() []string { bes := make([]string, 0, len(storageNameToBackendMap)) for k := range storageNameToBackendMap { bes = append(bes, k) } sort.Strings(bes) return bes }
go
func StorageBackends() []string { bes := make([]string, 0, len(storageNameToBackendMap)) for k := range storageNameToBackendMap { bes = append(bes, k) } sort.Strings(bes) return bes }
[ "func", "StorageBackends", "(", ")", "[", "]", "string", "{", "bes", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "storageNameToBackendMap", ")", ")", "\n", "for", "k", ":=", "range", "storageNameToBackendMap", "{", "bes", "=", "append", "(", "bes", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "bes", ")", "\n", "return", "bes", "\n", "}" ]
// StorageBackends returns the list of registered storage backends.
[ "StorageBackends", "returns", "the", "list", "of", "registered", "storage", "backends", "." ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/strings.go#L47-L54
train
gopasspw/gopass
pkg/store/root/move.go
Copy
func (r *Store) Copy(ctx context.Context, from, to string) error { return r.move(ctx, from, to, false) }
go
func (r *Store) Copy(ctx context.Context, from, to string) error { return r.move(ctx, from, to, false) }
[ "func", "(", "r", "*", "Store", ")", "Copy", "(", "ctx", "context", ".", "Context", ",", "from", ",", "to", "string", ")", "error", "{", "return", "r", ".", "move", "(", "ctx", ",", "from", ",", "to", ",", "false", ")", "\n", "}" ]
// Copy will copy one entry to another location. Multi-store copies are // supported. Each entry has to be decoded and encoded for the destination // to make sure it's encrypted for the right set of recipients.
[ "Copy", "will", "copy", "one", "entry", "to", "another", "location", ".", "Multi", "-", "store", "copies", "are", "supported", ".", "Each", "entry", "has", "to", "be", "decoded", "and", "encoded", "for", "the", "destination", "to", "make", "sure", "it", "s", "encrypted", "for", "the", "right", "set", "of", "recipients", "." ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/store/root/move.go#L19-L21
train
gopasspw/gopass
pkg/store/root/move.go
Move
func (r *Store) Move(ctx context.Context, from, to string) error { return r.move(ctx, from, to, true) }
go
func (r *Store) Move(ctx context.Context, from, to string) error { return r.move(ctx, from, to, true) }
[ "func", "(", "r", "*", "Store", ")", "Move", "(", "ctx", "context", ".", "Context", ",", "from", ",", "to", "string", ")", "error", "{", "return", "r", ".", "move", "(", "ctx", ",", "from", ",", "to", ",", "true", ")", "\n", "}" ]
// Move will move one entry from one location to another. Cross-store moves are // supported. Moving an entry will decode it from the old location, encode it // for the destination store with the right set of recipients and remove it // from the old location afterwards.
[ "Move", "will", "move", "one", "entry", "from", "one", "location", "to", "another", ".", "Cross", "-", "store", "moves", "are", "supported", ".", "Moving", "an", "entry", "will", "decode", "it", "from", "the", "old", "location", "encode", "it", "for", "the", "destination", "store", "with", "the", "right", "set", "of", "recipients", "and", "remove", "it", "from", "the", "old", "location", "afterwards", "." ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/store/root/move.go#L27-L29
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
Get
func (s *Store) Get(ctx context.Context, name string) ([]byte, error) { path := filepath.Join(s.path, filepath.Clean(name)) out.Debug(ctx, "fs.Get(%s) - %s", name, path) return ioutil.ReadFile(path) }
go
func (s *Store) Get(ctx context.Context, name string) ([]byte, error) { path := filepath.Join(s.path, filepath.Clean(name)) out.Debug(ctx, "fs.Get(%s) - %s", name, path) return ioutil.ReadFile(path) }
[ "func", "(", "s", "*", "Store", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "path", ",", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "name", ",", "path", ")", "\n", "return", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "}" ]
// Get retrieves the named content
[ "Get", "retrieves", "the", "named", "content" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L35-L39
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
Set
func (s *Store) Set(ctx context.Context, name string, value []byte) error { filename := filepath.Join(s.path, filepath.Clean(name)) filedir := filepath.Dir(filename) if !fsutil.IsDir(filedir) { if err := os.MkdirAll(filedir, 0700); err != nil { return err } } out.Debug(ctx, "fs.Set(%s) - %s", name, filepath.Join(s.path, name)) return ioutil.WriteFile(filepath.Join(s.path, name), value, 0644) }
go
func (s *Store) Set(ctx context.Context, name string, value []byte) error { filename := filepath.Join(s.path, filepath.Clean(name)) filedir := filepath.Dir(filename) if !fsutil.IsDir(filedir) { if err := os.MkdirAll(filedir, 0700); err != nil { return err } } out.Debug(ctx, "fs.Set(%s) - %s", name, filepath.Join(s.path, name)) return ioutil.WriteFile(filepath.Join(s.path, name), value, 0644) }
[ "func", "(", "s", "*", "Store", ")", "Set", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "value", "[", "]", "byte", ")", "error", "{", "filename", ":=", "filepath", ".", "Join", "(", "s", ".", "path", ",", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "filedir", ":=", "filepath", ".", "Dir", "(", "filename", ")", "\n", "if", "!", "fsutil", ".", "IsDir", "(", "filedir", ")", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "filedir", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "name", ",", "filepath", ".", "Join", "(", "s", ".", "path", ",", "name", ")", ")", "\n", "return", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "s", ".", "path", ",", "name", ")", ",", "value", ",", "0644", ")", "\n", "}" ]
// Set writes the given content
[ "Set", "writes", "the", "given", "content" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L42-L52
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
Delete
func (s *Store) Delete(ctx context.Context, name string) error { path := filepath.Join(s.path, filepath.Clean(name)) out.Debug(ctx, "fs.Delete(%s) - %s", name, path) if err := os.Remove(path); err != nil { return err } return s.removeEmptyParentDirectories(path) }
go
func (s *Store) Delete(ctx context.Context, name string) error { path := filepath.Join(s.path, filepath.Clean(name)) out.Debug(ctx, "fs.Delete(%s) - %s", name, path) if err := os.Remove(path); err != nil { return err } return s.removeEmptyParentDirectories(path) }
[ "func", "(", "s", "*", "Store", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "error", "{", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "path", ",", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "name", ",", "path", ")", "\n\n", "if", "err", ":=", "os", ".", "Remove", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "s", ".", "removeEmptyParentDirectories", "(", "path", ")", "\n", "}" ]
// Delete removes the named entity
[ "Delete", "removes", "the", "named", "entity" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L55-L64
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
removeEmptyParentDirectories
func (s *Store) removeEmptyParentDirectories(path string) error { parent := filepath.Dir(path) if relpath, err := filepath.Rel(s.path, parent); err != nil { return err } else if strings.HasPrefix(relpath, ".") { return nil } err := os.Remove(parent) switch { case err == nil: return s.removeEmptyParentDirectories(parent) case err.(*os.PathError).Err == syscall.ENOTEMPTY: // ignore when directory is non-empty return nil default: return err } }
go
func (s *Store) removeEmptyParentDirectories(path string) error { parent := filepath.Dir(path) if relpath, err := filepath.Rel(s.path, parent); err != nil { return err } else if strings.HasPrefix(relpath, ".") { return nil } err := os.Remove(parent) switch { case err == nil: return s.removeEmptyParentDirectories(parent) case err.(*os.PathError).Err == syscall.ENOTEMPTY: // ignore when directory is non-empty return nil default: return err } }
[ "func", "(", "s", "*", "Store", ")", "removeEmptyParentDirectories", "(", "path", "string", ")", "error", "{", "parent", ":=", "filepath", ".", "Dir", "(", "path", ")", "\n\n", "if", "relpath", ",", "err", ":=", "filepath", ".", "Rel", "(", "s", ".", "path", ",", "parent", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "strings", ".", "HasPrefix", "(", "relpath", ",", "\"", "\"", ")", "{", "return", "nil", "\n", "}", "\n\n", "err", ":=", "os", ".", "Remove", "(", "parent", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "return", "s", ".", "removeEmptyParentDirectories", "(", "parent", ")", "\n", "case", "err", ".", "(", "*", "os", ".", "PathError", ")", ".", "Err", "==", "syscall", ".", "ENOTEMPTY", ":", "// ignore when directory is non-empty", "return", "nil", "\n", "default", ":", "return", "err", "\n", "}", "\n", "}" ]
// Deletes all empty parent directories up to the store root
[ "Deletes", "all", "empty", "parent", "directories", "up", "to", "the", "store", "root" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L67-L86
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
Exists
func (s *Store) Exists(ctx context.Context, name string) bool { path := filepath.Join(s.path, filepath.Clean(name)) out.Debug(ctx, "fs.Exists(%s) - %s", name, path) return fsutil.IsFile(path) }
go
func (s *Store) Exists(ctx context.Context, name string) bool { path := filepath.Join(s.path, filepath.Clean(name)) out.Debug(ctx, "fs.Exists(%s) - %s", name, path) return fsutil.IsFile(path) }
[ "func", "(", "s", "*", "Store", ")", "Exists", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "bool", "{", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "path", ",", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "name", ",", "path", ")", "\n", "return", "fsutil", ".", "IsFile", "(", "path", ")", "\n", "}" ]
// Exists checks if the named entity exists
[ "Exists", "checks", "if", "the", "named", "entity", "exists" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L89-L93
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
List
func (s *Store) List(ctx context.Context, prefix string) ([]string, error) { prefix = strings.TrimPrefix(prefix, "/") out.Debug(ctx, "fs.List(%s)", prefix) files := make([]string, 0, 100) if err := filepath.Walk(s.path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() && strings.HasPrefix(info.Name(), ".") && path != s.path { return filepath.SkipDir } if info.IsDir() { return nil } if path == s.path { return nil } name := strings.TrimPrefix(path, s.path+string(filepath.Separator)) if !strings.HasPrefix(name, prefix) { return nil } files = append(files, name) return nil }); err != nil { return nil, err } sort.Strings(files) return files, nil }
go
func (s *Store) List(ctx context.Context, prefix string) ([]string, error) { prefix = strings.TrimPrefix(prefix, "/") out.Debug(ctx, "fs.List(%s)", prefix) files := make([]string, 0, 100) if err := filepath.Walk(s.path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() && strings.HasPrefix(info.Name(), ".") && path != s.path { return filepath.SkipDir } if info.IsDir() { return nil } if path == s.path { return nil } name := strings.TrimPrefix(path, s.path+string(filepath.Separator)) if !strings.HasPrefix(name, prefix) { return nil } files = append(files, name) return nil }); err != nil { return nil, err } sort.Strings(files) return files, nil }
[ "func", "(", "s", "*", "Store", ")", "List", "(", "ctx", "context", ".", "Context", ",", "prefix", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "prefix", "=", "strings", ".", "TrimPrefix", "(", "prefix", ",", "\"", "\"", ")", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "prefix", ")", "\n", "files", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "100", ")", "\n", "if", "err", ":=", "filepath", ".", "Walk", "(", "s", ".", "path", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "&&", "strings", ".", "HasPrefix", "(", "info", ".", "Name", "(", ")", ",", "\"", "\"", ")", "&&", "path", "!=", "s", ".", "path", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "nil", "\n", "}", "\n", "if", "path", "==", "s", ".", "path", "{", "return", "nil", "\n", "}", "\n", "name", ":=", "strings", ".", "TrimPrefix", "(", "path", ",", "s", ".", "path", "+", "string", "(", "filepath", ".", "Separator", ")", ")", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "name", ",", "prefix", ")", "{", "return", "nil", "\n", "}", "\n", "files", "=", "append", "(", "files", ",", "name", ")", "\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sort", ".", "Strings", "(", "files", ")", "\n", "return", "files", ",", "nil", "\n", "}" ]
// List returns a list of all entities
[ "List", "returns", "a", "list", "of", "all", "entities" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L96-L124
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
IsDir
func (s *Store) IsDir(ctx context.Context, name string) bool { path := filepath.Join(s.path, filepath.Clean(name)) isDir := fsutil.IsDir(path) out.Debug(ctx, "fs.Isdir(%s) - %s -> %t", name, path, isDir) return isDir }
go
func (s *Store) IsDir(ctx context.Context, name string) bool { path := filepath.Join(s.path, filepath.Clean(name)) isDir := fsutil.IsDir(path) out.Debug(ctx, "fs.Isdir(%s) - %s -> %t", name, path, isDir) return isDir }
[ "func", "(", "s", "*", "Store", ")", "IsDir", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "bool", "{", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "path", ",", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "isDir", ":=", "fsutil", ".", "IsDir", "(", "path", ")", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "name", ",", "path", ",", "isDir", ")", "\n", "return", "isDir", "\n", "}" ]
// IsDir returns true if the named entity is a directory
[ "IsDir", "returns", "true", "if", "the", "named", "entity", "is", "a", "directory" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L127-L132
train
gopasspw/gopass
pkg/backend/storage/fs/store.go
Prune
func (s *Store) Prune(ctx context.Context, prefix string) error { path := filepath.Join(s.path, filepath.Clean(prefix)) out.Debug(ctx, "fs.Prune(%s) - %s", prefix, path) return os.RemoveAll(path) }
go
func (s *Store) Prune(ctx context.Context, prefix string) error { path := filepath.Join(s.path, filepath.Clean(prefix)) out.Debug(ctx, "fs.Prune(%s) - %s", prefix, path) return os.RemoveAll(path) }
[ "func", "(", "s", "*", "Store", ")", "Prune", "(", "ctx", "context", ".", "Context", ",", "prefix", "string", ")", "error", "{", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "path", ",", "filepath", ".", "Clean", "(", "prefix", ")", ")", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "prefix", ",", "path", ")", "\n", "return", "os", ".", "RemoveAll", "(", "path", ")", "\n", "}" ]
// Prune removes a named directory
[ "Prune", "removes", "a", "named", "directory" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/backend/storage/fs/store.go#L135-L139
train
gopasspw/gopass
pkg/agent/agent.go
New
func New(dir string) *Agent { a := &Agent{ socket: filepath.Join(dir, ".gopass-agent.sock"), cache: &cache{ ttl: time.Hour, maxTTL: 24 * time.Hour, }, pinentry: func() (piner, error) { return pinentry.New() }, } mux := http.NewServeMux() mux.HandleFunc("/ping", a.servePing) mux.HandleFunc("/passphrase", a.servePassphrase) mux.HandleFunc("/cache/remove", a.serveRemove) mux.HandleFunc("/cache/purge", a.servePurge) a.server = &http.Server{ Handler: mux, } return a }
go
func New(dir string) *Agent { a := &Agent{ socket: filepath.Join(dir, ".gopass-agent.sock"), cache: &cache{ ttl: time.Hour, maxTTL: 24 * time.Hour, }, pinentry: func() (piner, error) { return pinentry.New() }, } mux := http.NewServeMux() mux.HandleFunc("/ping", a.servePing) mux.HandleFunc("/passphrase", a.servePassphrase) mux.HandleFunc("/cache/remove", a.serveRemove) mux.HandleFunc("/cache/purge", a.servePurge) a.server = &http.Server{ Handler: mux, } return a }
[ "func", "New", "(", "dir", "string", ")", "*", "Agent", "{", "a", ":=", "&", "Agent", "{", "socket", ":", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", ",", "cache", ":", "&", "cache", "{", "ttl", ":", "time", ".", "Hour", ",", "maxTTL", ":", "24", "*", "time", ".", "Hour", ",", "}", ",", "pinentry", ":", "func", "(", ")", "(", "piner", ",", "error", ")", "{", "return", "pinentry", ".", "New", "(", ")", "\n", "}", ",", "}", "\n", "mux", ":=", "http", ".", "NewServeMux", "(", ")", "\n", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "a", ".", "servePing", ")", "\n", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "a", ".", "servePassphrase", ")", "\n", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "a", ".", "serveRemove", ")", "\n", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "a", ".", "servePurge", ")", "\n", "a", ".", "server", "=", "&", "http", ".", "Server", "{", "Handler", ":", "mux", ",", "}", "\n", "return", "a", "\n", "}" ]
// New creates a new agent
[ "New", "creates", "a", "new", "agent" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/agent/agent.go#L38-L58
train
gopasspw/gopass
pkg/agent/agent.go
ListenAndServe
func (a *Agent) ListenAndServe(ctx context.Context) error { out.Debug(ctx, "Trying to listen on %s", a.socket) lis, err := net.Listen("unix", a.socket) if err == nil { return a.server.Serve(lis) } out.Debug(ctx, "Failed to listen on %s: %s", a.socket, err) if err := client.New(filepath.Dir(a.socket)).Ping(ctx); err == nil { return fmt.Errorf("agent already running") } if err := os.Remove(a.socket); err != nil { return errors.Wrapf(err, "failed to remove old agent socket %s: %s", a.socket, err) } out.Debug(ctx, "Trying to listen on %s after removing old socket", a.socket) lis, err = net.Listen("unix", a.socket) if err != nil { return errors.Wrapf(err, "failed to listen on %s after cleanup: %s", a.socket, err) } return a.server.Serve(lis) }
go
func (a *Agent) ListenAndServe(ctx context.Context) error { out.Debug(ctx, "Trying to listen on %s", a.socket) lis, err := net.Listen("unix", a.socket) if err == nil { return a.server.Serve(lis) } out.Debug(ctx, "Failed to listen on %s: %s", a.socket, err) if err := client.New(filepath.Dir(a.socket)).Ping(ctx); err == nil { return fmt.Errorf("agent already running") } if err := os.Remove(a.socket); err != nil { return errors.Wrapf(err, "failed to remove old agent socket %s: %s", a.socket, err) } out.Debug(ctx, "Trying to listen on %s after removing old socket", a.socket) lis, err = net.Listen("unix", a.socket) if err != nil { return errors.Wrapf(err, "failed to listen on %s after cleanup: %s", a.socket, err) } return a.server.Serve(lis) }
[ "func", "(", "a", "*", "Agent", ")", "ListenAndServe", "(", "ctx", "context", ".", "Context", ")", "error", "{", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "a", ".", "socket", ")", "\n", "lis", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "a", ".", "socket", ")", "\n", "if", "err", "==", "nil", "{", "return", "a", ".", "server", ".", "Serve", "(", "lis", ")", "\n", "}", "\n\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "a", ".", "socket", ",", "err", ")", "\n", "if", "err", ":=", "client", ".", "New", "(", "filepath", ".", "Dir", "(", "a", ".", "socket", ")", ")", ".", "Ping", "(", "ctx", ")", ";", "err", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "a", ".", "socket", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "a", ".", "socket", ",", "err", ")", "\n", "}", "\n", "out", ".", "Debug", "(", "ctx", ",", "\"", "\"", ",", "a", ".", "socket", ")", "\n", "lis", ",", "err", "=", "net", ".", "Listen", "(", "\"", "\"", ",", "a", ".", "socket", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "a", ".", "socket", ",", "err", ")", "\n", "}", "\n", "return", "a", ".", "server", ".", "Serve", "(", "lis", ")", "\n", "}" ]
// ListenAndServe starts listening and blocks
[ "ListenAndServe", "starts", "listening", "and", "blocks" ]
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/agent/agent.go#L69-L89
train
golang/oauth2
internal/token.go
lookupAuthStyle
func lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) { authStyleCache.Lock() defer authStyleCache.Unlock() style, ok = authStyleCache.m[tokenURL] return }
go
func lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) { authStyleCache.Lock() defer authStyleCache.Unlock() style, ok = authStyleCache.m[tokenURL] return }
[ "func", "lookupAuthStyle", "(", "tokenURL", "string", ")", "(", "style", "AuthStyle", ",", "ok", "bool", ")", "{", "authStyleCache", ".", "Lock", "(", ")", "\n", "defer", "authStyleCache", ".", "Unlock", "(", ")", "\n", "style", ",", "ok", "=", "authStyleCache", ".", "m", "[", "tokenURL", "]", "\n", "return", "\n", "}" ]
// lookupAuthStyle reports which auth style we last used with tokenURL // when calling RetrieveToken and whether we have ever done so.
[ "lookupAuthStyle", "reports", "which", "auth", "style", "we", "last", "used", "with", "tokenURL", "when", "calling", "RetrieveToken", "and", "whether", "we", "have", "ever", "done", "so", "." ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/internal/token.go#L134-L139
train
golang/oauth2
internal/token.go
setAuthStyle
func setAuthStyle(tokenURL string, v AuthStyle) { authStyleCache.Lock() defer authStyleCache.Unlock() if authStyleCache.m == nil { authStyleCache.m = make(map[string]AuthStyle) } authStyleCache.m[tokenURL] = v }
go
func setAuthStyle(tokenURL string, v AuthStyle) { authStyleCache.Lock() defer authStyleCache.Unlock() if authStyleCache.m == nil { authStyleCache.m = make(map[string]AuthStyle) } authStyleCache.m[tokenURL] = v }
[ "func", "setAuthStyle", "(", "tokenURL", "string", ",", "v", "AuthStyle", ")", "{", "authStyleCache", ".", "Lock", "(", ")", "\n", "defer", "authStyleCache", ".", "Unlock", "(", ")", "\n", "if", "authStyleCache", ".", "m", "==", "nil", "{", "authStyleCache", ".", "m", "=", "make", "(", "map", "[", "string", "]", "AuthStyle", ")", "\n", "}", "\n", "authStyleCache", ".", "m", "[", "tokenURL", "]", "=", "v", "\n", "}" ]
// setAuthStyle adds an entry to authStyleCache, documented above.
[ "setAuthStyle", "adds", "an", "entry", "to", "authStyleCache", "documented", "above", "." ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/internal/token.go#L142-L149
train
golang/oauth2
hipchat/hipchat.go
ServerEndpoint
func ServerEndpoint(host string) oauth2.Endpoint { return oauth2.Endpoint{ AuthURL: "https://" + host + "/users/authorize", TokenURL: "https://" + host + "/v2/oauth/token", } }
go
func ServerEndpoint(host string) oauth2.Endpoint { return oauth2.Endpoint{ AuthURL: "https://" + host + "/users/authorize", TokenURL: "https://" + host + "/v2/oauth/token", } }
[ "func", "ServerEndpoint", "(", "host", "string", ")", "oauth2", ".", "Endpoint", "{", "return", "oauth2", ".", "Endpoint", "{", "AuthURL", ":", "\"", "\"", "+", "host", "+", "\"", "\"", ",", "TokenURL", ":", "\"", "\"", "+", "host", "+", "\"", "\"", ",", "}", "\n", "}" ]
// ServerEndpoint returns a new oauth2.Endpoint for a HipChat Server instance // running on the given domain or host.
[ "ServerEndpoint", "returns", "a", "new", "oauth2", ".", "Endpoint", "for", "a", "HipChat", "Server", "instance", "running", "on", "the", "given", "domain", "or", "host", "." ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/hipchat/hipchat.go#L24-L29
train
golang/oauth2
clientcredentials/clientcredentials.go
Token
func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) { return c.TokenSource(ctx).Token() }
go
func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) { return c.TokenSource(ctx).Token() }
[ "func", "(", "c", "*", "Config", ")", "Token", "(", "ctx", "context", ".", "Context", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "return", "c", ".", "TokenSource", "(", "ctx", ")", ".", "Token", "(", ")", "\n", "}" ]
// Token uses client credentials to retrieve a token. // // The provided context optionally controls which HTTP client is used. See the oauth2.HTTPClient variable.
[ "Token", "uses", "client", "credentials", "to", "retrieve", "a", "token", ".", "The", "provided", "context", "optionally", "controls", "which", "HTTP", "client", "is", "used", ".", "See", "the", "oauth2", ".", "HTTPClient", "variable", "." ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/clientcredentials/clientcredentials.go#L55-L57
train
golang/oauth2
jws/jws.go
EncodeWithSigner
func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) { head, err := header.encode() if err != nil { return "", err } cs, err := c.encode() if err != nil { return "", err } ss := fmt.Sprintf("%s.%s", head, cs) sig, err := sg([]byte(ss)) if err != nil { return "", err } return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil }
go
func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) { head, err := header.encode() if err != nil { return "", err } cs, err := c.encode() if err != nil { return "", err } ss := fmt.Sprintf("%s.%s", head, cs) sig, err := sg([]byte(ss)) if err != nil { return "", err } return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil }
[ "func", "EncodeWithSigner", "(", "header", "*", "Header", ",", "c", "*", "ClaimSet", ",", "sg", "Signer", ")", "(", "string", ",", "error", ")", "{", "head", ",", "err", ":=", "header", ".", "encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "cs", ",", "err", ":=", "c", ".", "encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "ss", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "head", ",", "cs", ")", "\n", "sig", ",", "err", ":=", "sg", "(", "[", "]", "byte", "(", "ss", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ss", ",", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "sig", ")", ")", ",", "nil", "\n", "}" ]
// EncodeWithSigner encodes a header and claim set with the provided signer.
[ "EncodeWithSigner", "encodes", "a", "header", "and", "claim", "set", "with", "the", "provided", "signer", "." ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/jws/jws.go#L137-L152
train
golang/oauth2
jws/jws.go
Verify
func Verify(token string, key *rsa.PublicKey) error { parts := strings.Split(token, ".") if len(parts) != 3 { return errors.New("jws: invalid token received, token must have 3 parts") } signedContent := parts[0] + "." + parts[1] signatureString, err := base64.RawURLEncoding.DecodeString(parts[2]) if err != nil { return err } h := sha256.New() h.Write([]byte(signedContent)) return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString)) }
go
func Verify(token string, key *rsa.PublicKey) error { parts := strings.Split(token, ".") if len(parts) != 3 { return errors.New("jws: invalid token received, token must have 3 parts") } signedContent := parts[0] + "." + parts[1] signatureString, err := base64.RawURLEncoding.DecodeString(parts[2]) if err != nil { return err } h := sha256.New() h.Write([]byte(signedContent)) return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString)) }
[ "func", "Verify", "(", "token", "string", ",", "key", "*", "rsa", ".", "PublicKey", ")", "error", "{", "parts", ":=", "strings", ".", "Split", "(", "token", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "!=", "3", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "signedContent", ":=", "parts", "[", "0", "]", "+", "\"", "\"", "+", "parts", "[", "1", "]", "\n", "signatureString", ",", "err", ":=", "base64", ".", "RawURLEncoding", ".", "DecodeString", "(", "parts", "[", "2", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "h", ":=", "sha256", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "signedContent", ")", ")", "\n", "return", "rsa", ".", "VerifyPKCS1v15", "(", "key", ",", "crypto", ".", "SHA256", ",", "h", ".", "Sum", "(", "nil", ")", ",", "[", "]", "byte", "(", "signatureString", ")", ")", "\n", "}" ]
// Verify tests whether the provided JWT token's signature was produced by the private key // associated with the supplied public key.
[ "Verify", "tests", "whether", "the", "provided", "JWT", "token", "s", "signature", "was", "produced", "by", "the", "private", "key", "associated", "with", "the", "supplied", "public", "key", "." ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/jws/jws.go#L167-L182
train
golang/oauth2
jira/jira.go
sign
func sign(key string, claims *ClaimSet) (string, error) { b, err := json.Marshal(defaultHeader) if err != nil { return "", err } header := base64.RawURLEncoding.EncodeToString(b) jsonClaims, err := json.Marshal(claims) if err != nil { return "", err } encodedClaims := strings.TrimRight(base64.URLEncoding.EncodeToString(jsonClaims), "=") ss := fmt.Sprintf("%s.%s", header, encodedClaims) mac := hmac.New(sha256.New, []byte(key)) mac.Write([]byte(ss)) signature := mac.Sum(nil) return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(signature)), nil }
go
func sign(key string, claims *ClaimSet) (string, error) { b, err := json.Marshal(defaultHeader) if err != nil { return "", err } header := base64.RawURLEncoding.EncodeToString(b) jsonClaims, err := json.Marshal(claims) if err != nil { return "", err } encodedClaims := strings.TrimRight(base64.URLEncoding.EncodeToString(jsonClaims), "=") ss := fmt.Sprintf("%s.%s", header, encodedClaims) mac := hmac.New(sha256.New, []byte(key)) mac.Write([]byte(ss)) signature := mac.Sum(nil) return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(signature)), nil }
[ "func", "sign", "(", "key", "string", ",", "claims", "*", "ClaimSet", ")", "(", "string", ",", "error", ")", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "defaultHeader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "header", ":=", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "b", ")", "\n\n", "jsonClaims", ",", "err", ":=", "json", ".", "Marshal", "(", "claims", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "encodedClaims", ":=", "strings", ".", "TrimRight", "(", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "jsonClaims", ")", ",", "\"", "\"", ")", "\n\n", "ss", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "header", ",", "encodedClaims", ")", "\n\n", "mac", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "[", "]", "byte", "(", "key", ")", ")", "\n", "mac", ".", "Write", "(", "[", "]", "byte", "(", "ss", ")", ")", "\n", "signature", ":=", "mac", ".", "Sum", "(", "nil", ")", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ss", ",", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "signature", ")", ")", ",", "nil", "\n", "}" ]
// Sign the claim set with the shared secret // Result to be sent as assertion
[ "Sign", "the", "claim", "set", "with", "the", "shared", "secret", "Result", "to", "be", "sent", "as", "assertion" ]
9f3314589c9a9136388751d9adae6b0ed400978a
https://github.com/golang/oauth2/blob/9f3314589c9a9136388751d9adae6b0ed400978a/jira/jira.go#L147-L167
train
facebookarchive/grace
gracenet/net.go
activeListeners
func (n *Net) activeListeners() ([]net.Listener, error) { n.mutex.Lock() defer n.mutex.Unlock() ls := make([]net.Listener, len(n.active)) copy(ls, n.active) return ls, nil }
go
func (n *Net) activeListeners() ([]net.Listener, error) { n.mutex.Lock() defer n.mutex.Unlock() ls := make([]net.Listener, len(n.active)) copy(ls, n.active) return ls, nil }
[ "func", "(", "n", "*", "Net", ")", "activeListeners", "(", ")", "(", "[", "]", "net", ".", "Listener", ",", "error", ")", "{", "n", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "n", ".", "mutex", ".", "Unlock", "(", ")", "\n", "ls", ":=", "make", "(", "[", "]", "net", ".", "Listener", ",", "len", "(", "n", ".", "active", ")", ")", "\n", "copy", "(", "ls", ",", "n", ".", "active", ")", "\n", "return", "ls", ",", "nil", "\n", "}" ]
// activeListeners returns a snapshot copy of the active listeners.
[ "activeListeners", "returns", "a", "snapshot", "copy", "of", "the", "active", "listeners", "." ]
75cf19382434e82df4dd84953f566b8ad23d6e9e
https://github.com/facebookarchive/grace/blob/75cf19382434e82df4dd84953f566b8ad23d6e9e/gracenet/net.go#L172-L178
train
facebookarchive/grace
gracenet/net.go
StartProcess
func (n *Net) StartProcess() (int, error) { listeners, err := n.activeListeners() if err != nil { return 0, err } // Extract the fds from the listeners. files := make([]*os.File, len(listeners)) for i, l := range listeners { files[i], err = l.(filer).File() if err != nil { return 0, err } defer files[i].Close() } // Use the original binary location. This works with symlinks such that if // the file it points to has been changed we will use the updated symlink. argv0, err := exec.LookPath(os.Args[0]) if err != nil { return 0, err } // Pass on the environment and replace the old count key with the new one. var env []string for _, v := range os.Environ() { if !strings.HasPrefix(v, envCountKeyPrefix) { env = append(env, v) } } env = append(env, fmt.Sprintf("%s%d", envCountKeyPrefix, len(listeners))) allFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr}, files...) process, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{ Dir: originalWD, Env: env, Files: allFiles, }) if err != nil { return 0, err } return process.Pid, nil }
go
func (n *Net) StartProcess() (int, error) { listeners, err := n.activeListeners() if err != nil { return 0, err } // Extract the fds from the listeners. files := make([]*os.File, len(listeners)) for i, l := range listeners { files[i], err = l.(filer).File() if err != nil { return 0, err } defer files[i].Close() } // Use the original binary location. This works with symlinks such that if // the file it points to has been changed we will use the updated symlink. argv0, err := exec.LookPath(os.Args[0]) if err != nil { return 0, err } // Pass on the environment and replace the old count key with the new one. var env []string for _, v := range os.Environ() { if !strings.HasPrefix(v, envCountKeyPrefix) { env = append(env, v) } } env = append(env, fmt.Sprintf("%s%d", envCountKeyPrefix, len(listeners))) allFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr}, files...) process, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{ Dir: originalWD, Env: env, Files: allFiles, }) if err != nil { return 0, err } return process.Pid, nil }
[ "func", "(", "n", "*", "Net", ")", "StartProcess", "(", ")", "(", "int", ",", "error", ")", "{", "listeners", ",", "err", ":=", "n", ".", "activeListeners", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Extract the fds from the listeners.", "files", ":=", "make", "(", "[", "]", "*", "os", ".", "File", ",", "len", "(", "listeners", ")", ")", "\n", "for", "i", ",", "l", ":=", "range", "listeners", "{", "files", "[", "i", "]", ",", "err", "=", "l", ".", "(", "filer", ")", ".", "File", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "files", "[", "i", "]", ".", "Close", "(", ")", "\n", "}", "\n\n", "// Use the original binary location. This works with symlinks such that if", "// the file it points to has been changed we will use the updated symlink.", "argv0", ",", "err", ":=", "exec", ".", "LookPath", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Pass on the environment and replace the old count key with the new one.", "var", "env", "[", "]", "string", "\n", "for", "_", ",", "v", ":=", "range", "os", ".", "Environ", "(", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "v", ",", "envCountKeyPrefix", ")", "{", "env", "=", "append", "(", "env", ",", "v", ")", "\n", "}", "\n", "}", "\n", "env", "=", "append", "(", "env", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "envCountKeyPrefix", ",", "len", "(", "listeners", ")", ")", ")", "\n\n", "allFiles", ":=", "append", "(", "[", "]", "*", "os", ".", "File", "{", "os", ".", "Stdin", ",", "os", ".", "Stdout", ",", "os", ".", "Stderr", "}", ",", "files", "...", ")", "\n", "process", ",", "err", ":=", "os", ".", "StartProcess", "(", "argv0", ",", "os", ".", "Args", ",", "&", "os", ".", "ProcAttr", "{", "Dir", ":", "originalWD", ",", "Env", ":", "env", ",", "Files", ":", "allFiles", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "process", ".", "Pid", ",", "nil", "\n", "}" ]
// StartProcess starts a new process passing it the active listeners. It // doesn't fork, but starts a new process using the same environment and // arguments as when it was originally started. This allows for a newly // deployed binary to be started. It returns the pid of the newly started // process when successful.
[ "StartProcess", "starts", "a", "new", "process", "passing", "it", "the", "active", "listeners", ".", "It", "doesn", "t", "fork", "but", "starts", "a", "new", "process", "using", "the", "same", "environment", "and", "arguments", "as", "when", "it", "was", "originally", "started", ".", "This", "allows", "for", "a", "newly", "deployed", "binary", "to", "be", "started", ".", "It", "returns", "the", "pid", "of", "the", "newly", "started", "process", "when", "successful", "." ]
75cf19382434e82df4dd84953f566b8ad23d6e9e
https://github.com/facebookarchive/grace/blob/75cf19382434e82df4dd84953f566b8ad23d6e9e/gracenet/net.go#L206-L248
train
facebookarchive/grace
gracehttp/http.go
ServeWithOptions
func ServeWithOptions(servers []*http.Server, options ...option) error { a := newApp(servers) for _, opt := range options { opt(a) } return a.run() }
go
func ServeWithOptions(servers []*http.Server, options ...option) error { a := newApp(servers) for _, opt := range options { opt(a) } return a.run() }
[ "func", "ServeWithOptions", "(", "servers", "[", "]", "*", "http", ".", "Server", ",", "options", "...", "option", ")", "error", "{", "a", ":=", "newApp", "(", "servers", ")", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "a", ")", "\n", "}", "\n", "return", "a", ".", "run", "(", ")", "\n", "}" ]
// ServeWithOptions does the same as Serve, but takes a set of options to // configure the app struct.
[ "ServeWithOptions", "does", "the", "same", "as", "Serve", "but", "takes", "a", "set", "of", "options", "to", "configure", "the", "app", "struct", "." ]
75cf19382434e82df4dd84953f566b8ad23d6e9e
https://github.com/facebookarchive/grace/blob/75cf19382434e82df4dd84953f566b8ad23d6e9e/gracehttp/http.go#L181-L187
train
facebookarchive/grace
gracehttp/http.go
pprintAddr
func pprintAddr(listeners []net.Listener) []byte { var out bytes.Buffer for i, l := range listeners { if i != 0 { fmt.Fprint(&out, ", ") } fmt.Fprint(&out, l.Addr()) } return out.Bytes() }
go
func pprintAddr(listeners []net.Listener) []byte { var out bytes.Buffer for i, l := range listeners { if i != 0 { fmt.Fprint(&out, ", ") } fmt.Fprint(&out, l.Addr()) } return out.Bytes() }
[ "func", "pprintAddr", "(", "listeners", "[", "]", "net", ".", "Listener", ")", "[", "]", "byte", "{", "var", "out", "bytes", ".", "Buffer", "\n", "for", "i", ",", "l", ":=", "range", "listeners", "{", "if", "i", "!=", "0", "{", "fmt", ".", "Fprint", "(", "&", "out", ",", "\"", "\"", ")", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "&", "out", ",", "l", ".", "Addr", "(", ")", ")", "\n", "}", "\n", "return", "out", ".", "Bytes", "(", ")", "\n", "}" ]
// Used for pretty printing addresses.
[ "Used", "for", "pretty", "printing", "addresses", "." ]
75cf19382434e82df4dd84953f566b8ad23d6e9e
https://github.com/facebookarchive/grace/blob/75cf19382434e82df4dd84953f566b8ad23d6e9e/gracehttp/http.go#L206-L215
train
google/btree
btree.go
freeNode
func (f *FreeList) freeNode(n *node) (out bool) { f.mu.Lock() if len(f.freelist) < cap(f.freelist) { f.freelist = append(f.freelist, n) out = true } f.mu.Unlock() return }
go
func (f *FreeList) freeNode(n *node) (out bool) { f.mu.Lock() if len(f.freelist) < cap(f.freelist) { f.freelist = append(f.freelist, n) out = true } f.mu.Unlock() return }
[ "func", "(", "f", "*", "FreeList", ")", "freeNode", "(", "n", "*", "node", ")", "(", "out", "bool", ")", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "len", "(", "f", ".", "freelist", ")", "<", "cap", "(", "f", ".", "freelist", ")", "{", "f", ".", "freelist", "=", "append", "(", "f", ".", "freelist", ",", "n", ")", "\n", "out", "=", "true", "\n", "}", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// freeNode adds the given node to the list, returning true if it was added // and false if it was discarded.
[ "freeNode", "adds", "the", "given", "node", "to", "the", "list", "returning", "true", "if", "it", "was", "added", "and", "false", "if", "it", "was", "discarded", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L108-L116
train
google/btree
btree.go
NewWithFreeList
func NewWithFreeList(degree int, f *FreeList) *BTree { if degree <= 1 { panic("bad degree") } return &BTree{ degree: degree, cow: &copyOnWriteContext{freelist: f}, } }
go
func NewWithFreeList(degree int, f *FreeList) *BTree { if degree <= 1 { panic("bad degree") } return &BTree{ degree: degree, cow: &copyOnWriteContext{freelist: f}, } }
[ "func", "NewWithFreeList", "(", "degree", "int", ",", "f", "*", "FreeList", ")", "*", "BTree", "{", "if", "degree", "<=", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "BTree", "{", "degree", ":", "degree", ",", "cow", ":", "&", "copyOnWriteContext", "{", "freelist", ":", "f", "}", ",", "}", "\n", "}" ]
// NewWithFreeList creates a new B-Tree that uses the given node free list.
[ "NewWithFreeList", "creates", "a", "new", "B", "-", "Tree", "that", "uses", "the", "given", "node", "free", "list", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L132-L140
train
google/btree
btree.go
truncate
func (s *items) truncate(index int) { var toClear items *s, toClear = (*s)[:index], (*s)[index:] for len(toClear) > 0 { toClear = toClear[copy(toClear, nilItems):] } }
go
func (s *items) truncate(index int) { var toClear items *s, toClear = (*s)[:index], (*s)[index:] for len(toClear) > 0 { toClear = toClear[copy(toClear, nilItems):] } }
[ "func", "(", "s", "*", "items", ")", "truncate", "(", "index", "int", ")", "{", "var", "toClear", "items", "\n", "*", "s", ",", "toClear", "=", "(", "*", "s", ")", "[", ":", "index", "]", ",", "(", "*", "s", ")", "[", "index", ":", "]", "\n", "for", "len", "(", "toClear", ")", ">", "0", "{", "toClear", "=", "toClear", "[", "copy", "(", "toClear", ",", "nilItems", ")", ":", "]", "\n", "}", "\n", "}" ]
// truncate truncates this instance at index so that it contains only the // first index items. index must be less than or equal to length.
[ "truncate", "truncates", "this", "instance", "at", "index", "so", "that", "it", "contains", "only", "the", "first", "index", "items", ".", "index", "must", "be", "less", "than", "or", "equal", "to", "length", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L176-L182
train
google/btree
btree.go
find
func (s items) find(item Item) (index int, found bool) { i := sort.Search(len(s), func(i int) bool { return item.Less(s[i]) }) if i > 0 && !s[i-1].Less(item) { return i - 1, true } return i, false }
go
func (s items) find(item Item) (index int, found bool) { i := sort.Search(len(s), func(i int) bool { return item.Less(s[i]) }) if i > 0 && !s[i-1].Less(item) { return i - 1, true } return i, false }
[ "func", "(", "s", "items", ")", "find", "(", "item", "Item", ")", "(", "index", "int", ",", "found", "bool", ")", "{", "i", ":=", "sort", ".", "Search", "(", "len", "(", "s", ")", ",", "func", "(", "i", "int", ")", "bool", "{", "return", "item", ".", "Less", "(", "s", "[", "i", "]", ")", "\n", "}", ")", "\n", "if", "i", ">", "0", "&&", "!", "s", "[", "i", "-", "1", "]", ".", "Less", "(", "item", ")", "{", "return", "i", "-", "1", ",", "true", "\n", "}", "\n", "return", "i", ",", "false", "\n", "}" ]
// find returns the index where the given item should be inserted into this // list. 'found' is true if the item already exists in the list at the given // index.
[ "find", "returns", "the", "index", "where", "the", "given", "item", "should", "be", "inserted", "into", "this", "list", ".", "found", "is", "true", "if", "the", "item", "already", "exists", "in", "the", "list", "at", "the", "given", "index", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L187-L195
train
google/btree
btree.go
truncate
func (s *children) truncate(index int) { var toClear children *s, toClear = (*s)[:index], (*s)[index:] for len(toClear) > 0 { toClear = toClear[copy(toClear, nilChildren):] } }
go
func (s *children) truncate(index int) { var toClear children *s, toClear = (*s)[:index], (*s)[index:] for len(toClear) > 0 { toClear = toClear[copy(toClear, nilChildren):] } }
[ "func", "(", "s", "*", "children", ")", "truncate", "(", "index", "int", ")", "{", "var", "toClear", "children", "\n", "*", "s", ",", "toClear", "=", "(", "*", "s", ")", "[", ":", "index", "]", ",", "(", "*", "s", ")", "[", "index", ":", "]", "\n", "for", "len", "(", "toClear", ")", ">", "0", "{", "toClear", "=", "toClear", "[", "copy", "(", "toClear", ",", "nilChildren", ")", ":", "]", "\n", "}", "\n", "}" ]
// truncate truncates this instance at index so that it contains only the // first index children. index must be less than or equal to length.
[ "truncate", "truncates", "this", "instance", "at", "index", "so", "that", "it", "contains", "only", "the", "first", "index", "children", ".", "index", "must", "be", "less", "than", "or", "equal", "to", "length", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L231-L237
train
google/btree
btree.go
maybeSplitChild
func (n *node) maybeSplitChild(i, maxItems int) bool { if len(n.children[i].items) < maxItems { return false } first := n.mutableChild(i) item, second := first.split(maxItems / 2) n.items.insertAt(i, item) n.children.insertAt(i+1, second) return true }
go
func (n *node) maybeSplitChild(i, maxItems int) bool { if len(n.children[i].items) < maxItems { return false } first := n.mutableChild(i) item, second := first.split(maxItems / 2) n.items.insertAt(i, item) n.children.insertAt(i+1, second) return true }
[ "func", "(", "n", "*", "node", ")", "maybeSplitChild", "(", "i", ",", "maxItems", "int", ")", "bool", "{", "if", "len", "(", "n", ".", "children", "[", "i", "]", ".", "items", ")", "<", "maxItems", "{", "return", "false", "\n", "}", "\n", "first", ":=", "n", ".", "mutableChild", "(", "i", ")", "\n", "item", ",", "second", ":=", "first", ".", "split", "(", "maxItems", "/", "2", ")", "\n", "n", ".", "items", ".", "insertAt", "(", "i", ",", "item", ")", "\n", "n", ".", "children", ".", "insertAt", "(", "i", "+", "1", ",", "second", ")", "\n", "return", "true", "\n", "}" ]
// maybeSplitChild checks if a child should be split, and if so splits it. // Returns whether or not a split occurred.
[ "maybeSplitChild", "checks", "if", "a", "child", "should", "be", "split", "and", "if", "so", "splits", "it", ".", "Returns", "whether", "or", "not", "a", "split", "occurred", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L294-L303
train
google/btree
btree.go
get
func (n *node) get(key Item) Item { i, found := n.items.find(key) if found { return n.items[i] } else if len(n.children) > 0 { return n.children[i].get(key) } return nil }
go
func (n *node) get(key Item) Item { i, found := n.items.find(key) if found { return n.items[i] } else if len(n.children) > 0 { return n.children[i].get(key) } return nil }
[ "func", "(", "n", "*", "node", ")", "get", "(", "key", "Item", ")", "Item", "{", "i", ",", "found", ":=", "n", ".", "items", ".", "find", "(", "key", ")", "\n", "if", "found", "{", "return", "n", ".", "items", "[", "i", "]", "\n", "}", "else", "if", "len", "(", "n", ".", "children", ")", ">", "0", "{", "return", "n", ".", "children", "[", "i", "]", ".", "get", "(", "key", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// get finds the given key in the subtree and returns it.
[ "get", "finds", "the", "given", "key", "in", "the", "subtree", "and", "returns", "it", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L336-L344
train
google/btree
btree.go
min
func min(n *node) Item { if n == nil { return nil } for len(n.children) > 0 { n = n.children[0] } if len(n.items) == 0 { return nil } return n.items[0] }
go
func min(n *node) Item { if n == nil { return nil } for len(n.children) > 0 { n = n.children[0] } if len(n.items) == 0 { return nil } return n.items[0] }
[ "func", "min", "(", "n", "*", "node", ")", "Item", "{", "if", "n", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "len", "(", "n", ".", "children", ")", ">", "0", "{", "n", "=", "n", ".", "children", "[", "0", "]", "\n", "}", "\n", "if", "len", "(", "n", ".", "items", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "n", ".", "items", "[", "0", "]", "\n", "}" ]
// min returns the first item in the subtree.
[ "min", "returns", "the", "first", "item", "in", "the", "subtree", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L347-L358
train
google/btree
btree.go
max
func max(n *node) Item { if n == nil { return nil } for len(n.children) > 0 { n = n.children[len(n.children)-1] } if len(n.items) == 0 { return nil } return n.items[len(n.items)-1] }
go
func max(n *node) Item { if n == nil { return nil } for len(n.children) > 0 { n = n.children[len(n.children)-1] } if len(n.items) == 0 { return nil } return n.items[len(n.items)-1] }
[ "func", "max", "(", "n", "*", "node", ")", "Item", "{", "if", "n", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "len", "(", "n", ".", "children", ")", ">", "0", "{", "n", "=", "n", ".", "children", "[", "len", "(", "n", ".", "children", ")", "-", "1", "]", "\n", "}", "\n", "if", "len", "(", "n", ".", "items", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "n", ".", "items", "[", "len", "(", "n", ".", "items", ")", "-", "1", "]", "\n", "}" ]
// max returns the last item in the subtree.
[ "max", "returns", "the", "last", "item", "in", "the", "subtree", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L361-L372
train
google/btree
btree.go
remove
func (n *node) remove(item Item, minItems int, typ toRemove) Item { var i int var found bool switch typ { case removeMax: if len(n.children) == 0 { return n.items.pop() } i = len(n.items) case removeMin: if len(n.children) == 0 { return n.items.removeAt(0) } i = 0 case removeItem: i, found = n.items.find(item) if len(n.children) == 0 { if found { return n.items.removeAt(i) } return nil } default: panic("invalid type") } // If we get to here, we have children. if len(n.children[i].items) <= minItems { return n.growChildAndRemove(i, item, minItems, typ) } child := n.mutableChild(i) // Either we had enough items to begin with, or we've done some // merging/stealing, because we've got enough now and we're ready to return // stuff. if found { // The item exists at index 'i', and the child we've selected can give us a // predecessor, since if we've gotten here it's got > minItems items in it. out := n.items[i] // We use our special-case 'remove' call with typ=maxItem to pull the // predecessor of item i (the rightmost leaf of our immediate left child) // and set it into where we pulled the item from. n.items[i] = child.remove(nil, minItems, removeMax) return out } // Final recursive call. Once we're here, we know that the item isn't in this // node and that the child is big enough to remove from. return child.remove(item, minItems, typ) }
go
func (n *node) remove(item Item, minItems int, typ toRemove) Item { var i int var found bool switch typ { case removeMax: if len(n.children) == 0 { return n.items.pop() } i = len(n.items) case removeMin: if len(n.children) == 0 { return n.items.removeAt(0) } i = 0 case removeItem: i, found = n.items.find(item) if len(n.children) == 0 { if found { return n.items.removeAt(i) } return nil } default: panic("invalid type") } // If we get to here, we have children. if len(n.children[i].items) <= minItems { return n.growChildAndRemove(i, item, minItems, typ) } child := n.mutableChild(i) // Either we had enough items to begin with, or we've done some // merging/stealing, because we've got enough now and we're ready to return // stuff. if found { // The item exists at index 'i', and the child we've selected can give us a // predecessor, since if we've gotten here it's got > minItems items in it. out := n.items[i] // We use our special-case 'remove' call with typ=maxItem to pull the // predecessor of item i (the rightmost leaf of our immediate left child) // and set it into where we pulled the item from. n.items[i] = child.remove(nil, minItems, removeMax) return out } // Final recursive call. Once we're here, we know that the item isn't in this // node and that the child is big enough to remove from. return child.remove(item, minItems, typ) }
[ "func", "(", "n", "*", "node", ")", "remove", "(", "item", "Item", ",", "minItems", "int", ",", "typ", "toRemove", ")", "Item", "{", "var", "i", "int", "\n", "var", "found", "bool", "\n", "switch", "typ", "{", "case", "removeMax", ":", "if", "len", "(", "n", ".", "children", ")", "==", "0", "{", "return", "n", ".", "items", ".", "pop", "(", ")", "\n", "}", "\n", "i", "=", "len", "(", "n", ".", "items", ")", "\n", "case", "removeMin", ":", "if", "len", "(", "n", ".", "children", ")", "==", "0", "{", "return", "n", ".", "items", ".", "removeAt", "(", "0", ")", "\n", "}", "\n", "i", "=", "0", "\n", "case", "removeItem", ":", "i", ",", "found", "=", "n", ".", "items", ".", "find", "(", "item", ")", "\n", "if", "len", "(", "n", ".", "children", ")", "==", "0", "{", "if", "found", "{", "return", "n", ".", "items", ".", "removeAt", "(", "i", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// If we get to here, we have children.", "if", "len", "(", "n", ".", "children", "[", "i", "]", ".", "items", ")", "<=", "minItems", "{", "return", "n", ".", "growChildAndRemove", "(", "i", ",", "item", ",", "minItems", ",", "typ", ")", "\n", "}", "\n", "child", ":=", "n", ".", "mutableChild", "(", "i", ")", "\n", "// Either we had enough items to begin with, or we've done some", "// merging/stealing, because we've got enough now and we're ready to return", "// stuff.", "if", "found", "{", "// The item exists at index 'i', and the child we've selected can give us a", "// predecessor, since if we've gotten here it's got > minItems items in it.", "out", ":=", "n", ".", "items", "[", "i", "]", "\n", "// We use our special-case 'remove' call with typ=maxItem to pull the", "// predecessor of item i (the rightmost leaf of our immediate left child)", "// and set it into where we pulled the item from.", "n", ".", "items", "[", "i", "]", "=", "child", ".", "remove", "(", "nil", ",", "minItems", ",", "removeMax", ")", "\n", "return", "out", "\n", "}", "\n", "// Final recursive call. Once we're here, we know that the item isn't in this", "// node and that the child is big enough to remove from.", "return", "child", ".", "remove", "(", "item", ",", "minItems", ",", "typ", ")", "\n", "}" ]
// remove removes an item from the subtree rooted at this node.
[ "remove", "removes", "an", "item", "from", "the", "subtree", "rooted", "at", "this", "node", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L384-L430
train
google/btree
btree.go
Delete
func (t *BTree) Delete(item Item) Item { return t.deleteItem(item, removeItem) }
go
func (t *BTree) Delete(item Item) Item { return t.deleteItem(item, removeItem) }
[ "func", "(", "t", "*", "BTree", ")", "Delete", "(", "item", "Item", ")", "Item", "{", "return", "t", ".", "deleteItem", "(", "item", ",", "removeItem", ")", "\n", "}" ]
// Delete removes an item equal to the passed in item from the tree, returning // it. If no such item exists, returns nil.
[ "Delete", "removes", "an", "item", "equal", "to", "the", "passed", "in", "item", "from", "the", "tree", "returning", "it", ".", "If", "no", "such", "item", "exists", "returns", "nil", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L711-L713
train
google/btree
btree.go
AscendRange
func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator) }
go
func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator) }
[ "func", "(", "t", "*", "BTree", ")", "AscendRange", "(", "greaterOrEqual", ",", "lessThan", "Item", ",", "iterator", "ItemIterator", ")", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "\n", "}", "\n", "t", ".", "root", ".", "iterate", "(", "ascend", ",", "greaterOrEqual", ",", "lessThan", ",", "true", ",", "false", ",", "iterator", ")", "\n", "}" ]
// AscendRange calls the iterator for every value in the tree within the range // [greaterOrEqual, lessThan), until iterator returns false.
[ "AscendRange", "calls", "the", "iterator", "for", "every", "value", "in", "the", "tree", "within", "the", "range", "[", "greaterOrEqual", "lessThan", ")", "until", "iterator", "returns", "false", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L746-L751
train
google/btree
btree.go
AscendLessThan
func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, nil, pivot, false, false, iterator) }
go
func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, nil, pivot, false, false, iterator) }
[ "func", "(", "t", "*", "BTree", ")", "AscendLessThan", "(", "pivot", "Item", ",", "iterator", "ItemIterator", ")", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "\n", "}", "\n", "t", ".", "root", ".", "iterate", "(", "ascend", ",", "nil", ",", "pivot", ",", "false", ",", "false", ",", "iterator", ")", "\n", "}" ]
// AscendLessThan calls the iterator for every value in the tree within the range // [first, pivot), until iterator returns false.
[ "AscendLessThan", "calls", "the", "iterator", "for", "every", "value", "in", "the", "tree", "within", "the", "range", "[", "first", "pivot", ")", "until", "iterator", "returns", "false", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L755-L760
train
google/btree
btree.go
DescendRange
func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator) }
go
func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator) }
[ "func", "(", "t", "*", "BTree", ")", "DescendRange", "(", "lessOrEqual", ",", "greaterThan", "Item", ",", "iterator", "ItemIterator", ")", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "\n", "}", "\n", "t", ".", "root", ".", "iterate", "(", "descend", ",", "lessOrEqual", ",", "greaterThan", ",", "true", ",", "false", ",", "iterator", ")", "\n", "}" ]
// DescendRange calls the iterator for every value in the tree within the range // [lessOrEqual, greaterThan), until iterator returns false.
[ "DescendRange", "calls", "the", "iterator", "for", "every", "value", "in", "the", "tree", "within", "the", "range", "[", "lessOrEqual", "greaterThan", ")", "until", "iterator", "returns", "false", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L782-L787
train
google/btree
btree.go
DescendGreaterThan
func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, nil, pivot, false, false, iterator) }
go
func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, nil, pivot, false, false, iterator) }
[ "func", "(", "t", "*", "BTree", ")", "DescendGreaterThan", "(", "pivot", "Item", ",", "iterator", "ItemIterator", ")", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "\n", "}", "\n", "t", ".", "root", ".", "iterate", "(", "descend", ",", "nil", ",", "pivot", ",", "false", ",", "false", ",", "iterator", ")", "\n", "}" ]
// DescendGreaterThan calls the iterator for every value in the tree within // the range (pivot, last], until iterator returns false.
[ "DescendGreaterThan", "calls", "the", "iterator", "for", "every", "value", "in", "the", "tree", "within", "the", "range", "(", "pivot", "last", "]", "until", "iterator", "returns", "false", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L800-L805
train
google/btree
btree.go
Get
func (t *BTree) Get(key Item) Item { if t.root == nil { return nil } return t.root.get(key) }
go
func (t *BTree) Get(key Item) Item { if t.root == nil { return nil } return t.root.get(key) }
[ "func", "(", "t", "*", "BTree", ")", "Get", "(", "key", "Item", ")", "Item", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "t", ".", "root", ".", "get", "(", "key", ")", "\n", "}" ]
// Get looks for the key item in the tree, returning it. It returns nil if // unable to find that item.
[ "Get", "looks", "for", "the", "key", "item", "in", "the", "tree", "returning", "it", ".", "It", "returns", "nil", "if", "unable", "to", "find", "that", "item", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L818-L823
train
google/btree
btree.go
Has
func (t *BTree) Has(key Item) bool { return t.Get(key) != nil }
go
func (t *BTree) Has(key Item) bool { return t.Get(key) != nil }
[ "func", "(", "t", "*", "BTree", ")", "Has", "(", "key", "Item", ")", "bool", "{", "return", "t", ".", "Get", "(", "key", ")", "!=", "nil", "\n", "}" ]
// Has returns true if the given key is in the tree.
[ "Has", "returns", "true", "if", "the", "given", "key", "is", "in", "the", "tree", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L836-L838
train
google/btree
btree.go
reset
func (n *node) reset(c *copyOnWriteContext) bool { for _, child := range n.children { if !child.reset(c) { return false } } return c.freeNode(n) != ftFreelistFull }
go
func (n *node) reset(c *copyOnWriteContext) bool { for _, child := range n.children { if !child.reset(c) { return false } } return c.freeNode(n) != ftFreelistFull }
[ "func", "(", "n", "*", "node", ")", "reset", "(", "c", "*", "copyOnWriteContext", ")", "bool", "{", "for", "_", ",", "child", ":=", "range", "n", ".", "children", "{", "if", "!", "child", ".", "reset", "(", "c", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "c", ".", "freeNode", "(", "n", ")", "!=", "ftFreelistFull", "\n", "}" ]
// reset returns a subtree to the freelist. It breaks out immediately if the // freelist is full, since the only benefit of iterating is to fill that // freelist up. Returns true if parent reset call should continue.
[ "reset", "returns", "a", "subtree", "to", "the", "freelist", ".", "It", "breaks", "out", "immediately", "if", "the", "freelist", "is", "full", "since", "the", "only", "benefit", "of", "iterating", "is", "to", "fill", "that", "freelist", "up", ".", "Returns", "true", "if", "parent", "reset", "call", "should", "continue", "." ]
20236160a414454a9c64b6c8829381c6f4bddcaa
https://github.com/google/btree/blob/20236160a414454a9c64b6c8829381c6f4bddcaa/btree.go#L875-L882
train
kshvakov/clickhouse
lib/column/ip.go
Scan
func (ip *IP) Scan(value interface{}) (err error) { switch v := value.(type) { case []byte: if len(v) == 4 || len(v) == 16 { *ip = IP(v) } else { err = errInvalidScanValue } case string: if len(v) == 4 || len(v) == 16 { *ip = IP([]byte(v)) } else { err = errInvalidScanValue } default: err = errInvalidScanType } return }
go
func (ip *IP) Scan(value interface{}) (err error) { switch v := value.(type) { case []byte: if len(v) == 4 || len(v) == 16 { *ip = IP(v) } else { err = errInvalidScanValue } case string: if len(v) == 4 || len(v) == 16 { *ip = IP([]byte(v)) } else { err = errInvalidScanValue } default: err = errInvalidScanType } return }
[ "func", "(", "ip", "*", "IP", ")", "Scan", "(", "value", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "switch", "v", ":=", "value", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "if", "len", "(", "v", ")", "==", "4", "||", "len", "(", "v", ")", "==", "16", "{", "*", "ip", "=", "IP", "(", "v", ")", "\n", "}", "else", "{", "err", "=", "errInvalidScanValue", "\n", "}", "\n", "case", "string", ":", "if", "len", "(", "v", ")", "==", "4", "||", "len", "(", "v", ")", "==", "16", "{", "*", "ip", "=", "IP", "(", "[", "]", "byte", "(", "v", ")", ")", "\n", "}", "else", "{", "err", "=", "errInvalidScanValue", "\n", "}", "\n", "default", ":", "err", "=", "errInvalidScanType", "\n", "}", "\n", "return", "\n", "}" ]
// Scan implements the driver.Valuer interface, json field interface
[ "Scan", "implements", "the", "driver", ".", "Valuer", "interface", "json", "field", "interface" ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/lib/column/ip.go#L50-L68
train
kshvakov/clickhouse
lib/cityhash102/cityhash.go
hashLen17to32
func hashLen17to32(s []byte, length uint32) uint64 { var a = fetch64(s) * k1 var b = fetch64(s[8:]) var c = fetch64(s[length-8:]) * k2 var d = fetch64(s[length-16:]) * k0 return hashLen16(rotate64(a-b, 43)+rotate64(c, 30)+d, a+rotate64(b^k3, 20)-c+uint64(length)) }
go
func hashLen17to32(s []byte, length uint32) uint64 { var a = fetch64(s) * k1 var b = fetch64(s[8:]) var c = fetch64(s[length-8:]) * k2 var d = fetch64(s[length-16:]) * k0 return hashLen16(rotate64(a-b, 43)+rotate64(c, 30)+d, a+rotate64(b^k3, 20)-c+uint64(length)) }
[ "func", "hashLen17to32", "(", "s", "[", "]", "byte", ",", "length", "uint32", ")", "uint64", "{", "var", "a", "=", "fetch64", "(", "s", ")", "*", "k1", "\n", "var", "b", "=", "fetch64", "(", "s", "[", "8", ":", "]", ")", "\n", "var", "c", "=", "fetch64", "(", "s", "[", "length", "-", "8", ":", "]", ")", "*", "k2", "\n", "var", "d", "=", "fetch64", "(", "s", "[", "length", "-", "16", ":", "]", ")", "*", "k0", "\n\n", "return", "hashLen16", "(", "rotate64", "(", "a", "-", "b", ",", "43", ")", "+", "rotate64", "(", "c", ",", "30", ")", "+", "d", ",", "a", "+", "rotate64", "(", "b", "^", "k3", ",", "20", ")", "-", "c", "+", "uint64", "(", "length", ")", ")", "\n", "}" ]
// This probably works well for 16-byte strings as well, but it may be overkill
[ "This", "probably", "works", "well", "for", "16", "-", "byte", "strings", "as", "well", "but", "it", "may", "be", "overkill" ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/lib/cityhash102/cityhash.go#L151-L159
train
kshvakov/clickhouse
lib/binary/compress_writer.go
NewCompressWriter
func NewCompressWriter(w io.Writer) *compressWriter { p := &compressWriter{writer: w} p.data = make([]byte, BlockMaxSize, BlockMaxSize) zlen := lz4.CompressBound(BlockMaxSize) + HeaderSize p.zdata = make([]byte, zlen, zlen) return p }
go
func NewCompressWriter(w io.Writer) *compressWriter { p := &compressWriter{writer: w} p.data = make([]byte, BlockMaxSize, BlockMaxSize) zlen := lz4.CompressBound(BlockMaxSize) + HeaderSize p.zdata = make([]byte, zlen, zlen) return p }
[ "func", "NewCompressWriter", "(", "w", "io", ".", "Writer", ")", "*", "compressWriter", "{", "p", ":=", "&", "compressWriter", "{", "writer", ":", "w", "}", "\n", "p", ".", "data", "=", "make", "(", "[", "]", "byte", ",", "BlockMaxSize", ",", "BlockMaxSize", ")", "\n\n", "zlen", ":=", "lz4", ".", "CompressBound", "(", "BlockMaxSize", ")", "+", "HeaderSize", "\n", "p", ".", "zdata", "=", "make", "(", "[", "]", "byte", ",", "zlen", ",", "zlen", ")", "\n", "return", "p", "\n", "}" ]
// NewCompressWriter wrap the io.Writer
[ "NewCompressWriter", "wrap", "the", "io", ".", "Writer" ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/lib/binary/compress_writer.go#L24-L31
train
kshvakov/clickhouse
lib/column/uuid.go
xtob
func xtob(x1, x2 byte) (byte, bool) { b1 := xvalues[x1] b2 := xvalues[x2] return (b1 << 4) | b2, b1 != 255 && b2 != 255 }
go
func xtob(x1, x2 byte) (byte, bool) { b1 := xvalues[x1] b2 := xvalues[x2] return (b1 << 4) | b2, b1 != 255 && b2 != 255 }
[ "func", "xtob", "(", "x1", ",", "x2", "byte", ")", "(", "byte", ",", "bool", ")", "{", "b1", ":=", "xvalues", "[", "x1", "]", "\n", "b2", ":=", "xvalues", "[", "x2", "]", "\n", "return", "(", "b1", "<<", "4", ")", "|", "b2", ",", "b1", "!=", "255", "&&", "b2", "!=", "255", "\n", "}" ]
// xtob converts hex characters x1 and x2 into a byte.
[ "xtob", "converts", "hex", "characters", "x1", "and", "x2", "into", "a", "byte", "." ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/lib/column/uuid.go#L126-L130
train
kshvakov/clickhouse
word_matcher.go
newMatcher
func newMatcher(needle string) *wordMatcher { return &wordMatcher{word: []rune(strings.ToUpper(needle)), position: 0} }
go
func newMatcher(needle string) *wordMatcher { return &wordMatcher{word: []rune(strings.ToUpper(needle)), position: 0} }
[ "func", "newMatcher", "(", "needle", "string", ")", "*", "wordMatcher", "{", "return", "&", "wordMatcher", "{", "word", ":", "[", "]", "rune", "(", "strings", ".", "ToUpper", "(", "needle", ")", ")", ",", "position", ":", "0", "}", "\n", "}" ]
// newMatcher returns matcher for word needle
[ "newMatcher", "returns", "matcher", "for", "word", "needle" ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/word_matcher.go#L15-L18
train
kshvakov/clickhouse
lib/binary/compress_reader.go
NewCompressReader
func NewCompressReader(r io.Reader) *compressReader { p := &compressReader{ reader: r, header: make([]byte, HeaderSize), } p.data = make([]byte, BlockMaxSize, BlockMaxSize) zlen := lz4.CompressBound(BlockMaxSize) + HeaderSize p.zdata = make([]byte, zlen, zlen) p.pos = len(p.data) return p }
go
func NewCompressReader(r io.Reader) *compressReader { p := &compressReader{ reader: r, header: make([]byte, HeaderSize), } p.data = make([]byte, BlockMaxSize, BlockMaxSize) zlen := lz4.CompressBound(BlockMaxSize) + HeaderSize p.zdata = make([]byte, zlen, zlen) p.pos = len(p.data) return p }
[ "func", "NewCompressReader", "(", "r", "io", ".", "Reader", ")", "*", "compressReader", "{", "p", ":=", "&", "compressReader", "{", "reader", ":", "r", ",", "header", ":", "make", "(", "[", "]", "byte", ",", "HeaderSize", ")", ",", "}", "\n", "p", ".", "data", "=", "make", "(", "[", "]", "byte", ",", "BlockMaxSize", ",", "BlockMaxSize", ")", "\n\n", "zlen", ":=", "lz4", ".", "CompressBound", "(", "BlockMaxSize", ")", "+", "HeaderSize", "\n", "p", ".", "zdata", "=", "make", "(", "[", "]", "byte", ",", "zlen", ",", "zlen", ")", "\n\n", "p", ".", "pos", "=", "len", "(", "p", ".", "data", ")", "\n", "return", "p", "\n", "}" ]
// NewCompressReader wrap the io.Reader
[ "NewCompressReader", "wrap", "the", "io", ".", "Reader" ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/lib/binary/compress_reader.go#L26-L38
train
kshvakov/clickhouse
tls_config.go
RegisterTLSConfig
func RegisterTLSConfig(key string, config *tls.Config) error { tlsConfigLock.Lock() if tlsConfigRegistry == nil { tlsConfigRegistry = make(map[string]*tls.Config) } tlsConfigRegistry[key] = config tlsConfigLock.Unlock() return nil }
go
func RegisterTLSConfig(key string, config *tls.Config) error { tlsConfigLock.Lock() if tlsConfigRegistry == nil { tlsConfigRegistry = make(map[string]*tls.Config) } tlsConfigRegistry[key] = config tlsConfigLock.Unlock() return nil }
[ "func", "RegisterTLSConfig", "(", "key", "string", ",", "config", "*", "tls", ".", "Config", ")", "error", "{", "tlsConfigLock", ".", "Lock", "(", ")", "\n", "if", "tlsConfigRegistry", "==", "nil", "{", "tlsConfigRegistry", "=", "make", "(", "map", "[", "string", "]", "*", "tls", ".", "Config", ")", "\n", "}", "\n\n", "tlsConfigRegistry", "[", "key", "]", "=", "config", "\n", "tlsConfigLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// RegisterTLSConfig registers a custom tls.Config to be used with sql.Open.
[ "RegisterTLSConfig", "registers", "a", "custom", "tls", ".", "Config", "to", "be", "used", "with", "sql", ".", "Open", "." ]
04847609e9ba2f114bdd435bc78e6c816a4ef5c1
https://github.com/kshvakov/clickhouse/blob/04847609e9ba2f114bdd435bc78e6c816a4ef5c1/tls_config.go#L17-L26
train
takama/daemon
examples/myservice.go
acceptConnection
func acceptConnection(listener net.Listener, listen chan<- net.Conn) { for { conn, err := listener.Accept() if err != nil { continue } listen <- conn } }
go
func acceptConnection(listener net.Listener, listen chan<- net.Conn) { for { conn, err := listener.Accept() if err != nil { continue } listen <- conn } }
[ "func", "acceptConnection", "(", "listener", "net", ".", "Listener", ",", "listen", "chan", "<-", "net", ".", "Conn", ")", "{", "for", "{", "conn", ",", "err", ":=", "listener", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "listen", "<-", "conn", "\n", "}", "\n", "}" ]
// Accept a client connection and collect it in a channel
[ "Accept", "a", "client", "connection", "and", "collect", "it", "in", "a", "channel" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/examples/myservice.go#L96-L104
train
takama/daemon
daemon_freebsd.go
isEnabled
func (bsd *bsdRecord) isEnabled() (bool, error) { rcConf, err := os.Open("/etc/rc.conf") if err != nil { fmt.Println("Error opening file:", err) return false, err } defer rcConf.Close() rcData, _ := ioutil.ReadAll(rcConf) r, _ := regexp.Compile(`.*` + bsd.name + `_enable="YES".*`) v := string(r.Find(rcData)) var chrFound, sharpFound bool for _, c := range v { if c == '#' && !chrFound { sharpFound = true break } else if !sharpFound && c != ' ' { chrFound = true break } } return chrFound, nil }
go
func (bsd *bsdRecord) isEnabled() (bool, error) { rcConf, err := os.Open("/etc/rc.conf") if err != nil { fmt.Println("Error opening file:", err) return false, err } defer rcConf.Close() rcData, _ := ioutil.ReadAll(rcConf) r, _ := regexp.Compile(`.*` + bsd.name + `_enable="YES".*`) v := string(r.Find(rcData)) var chrFound, sharpFound bool for _, c := range v { if c == '#' && !chrFound { sharpFound = true break } else if !sharpFound && c != ' ' { chrFound = true break } } return chrFound, nil }
[ "func", "(", "bsd", "*", "bsdRecord", ")", "isEnabled", "(", ")", "(", "bool", ",", "error", ")", "{", "rcConf", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", ",", "err", "\n", "}", "\n", "defer", "rcConf", ".", "Close", "(", ")", "\n", "rcData", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "rcConf", ")", "\n", "r", ",", "_", ":=", "regexp", ".", "Compile", "(", "`.*`", "+", "bsd", ".", "name", "+", "`_enable=\"YES\".*`", ")", "\n", "v", ":=", "string", "(", "r", ".", "Find", "(", "rcData", ")", ")", "\n", "var", "chrFound", ",", "sharpFound", "bool", "\n", "for", "_", ",", "c", ":=", "range", "v", "{", "if", "c", "==", "'#'", "&&", "!", "chrFound", "{", "sharpFound", "=", "true", "\n", "break", "\n", "}", "else", "if", "!", "sharpFound", "&&", "c", "!=", "' '", "{", "chrFound", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "chrFound", ",", "nil", "\n", "}" ]
// Is a service is enabled
[ "Is", "a", "service", "is", "enabled" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/daemon_freebsd.go#L37-L58
train
takama/daemon
daemon_darwin.go
checkRunning
func (darwin *darwinRecord) checkRunning() (string, bool) { output, err := exec.Command("launchctl", "list", darwin.name).Output() if err == nil { if matched, err := regexp.MatchString(darwin.name, string(output)); err == nil && matched { reg := regexp.MustCompile("PID\" = ([0-9]+);") data := reg.FindStringSubmatch(string(output)) if len(data) > 1 { return "Service (pid " + data[1] + ") is running...", true } return "Service is running...", true } } return "Service is stopped", false }
go
func (darwin *darwinRecord) checkRunning() (string, bool) { output, err := exec.Command("launchctl", "list", darwin.name).Output() if err == nil { if matched, err := regexp.MatchString(darwin.name, string(output)); err == nil && matched { reg := regexp.MustCompile("PID\" = ([0-9]+);") data := reg.FindStringSubmatch(string(output)) if len(data) > 1 { return "Service (pid " + data[1] + ") is running...", true } return "Service is running...", true } } return "Service is stopped", false }
[ "func", "(", "darwin", "*", "darwinRecord", ")", "checkRunning", "(", ")", "(", "string", ",", "bool", ")", "{", "output", ",", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "darwin", ".", "name", ")", ".", "Output", "(", ")", "\n", "if", "err", "==", "nil", "{", "if", "matched", ",", "err", ":=", "regexp", ".", "MatchString", "(", "darwin", ".", "name", ",", "string", "(", "output", ")", ")", ";", "err", "==", "nil", "&&", "matched", "{", "reg", ":=", "regexp", ".", "MustCompile", "(", "\"", "\\\"", "\"", ")", "\n", "data", ":=", "reg", ".", "FindStringSubmatch", "(", "string", "(", "output", ")", ")", "\n", "if", "len", "(", "data", ")", ">", "1", "{", "return", "\"", "\"", "+", "data", "[", "1", "]", "+", "\"", "\"", ",", "true", "\n", "}", "\n", "return", "\"", "\"", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "false", "\n", "}" ]
// Check service is running
[ "Check", "service", "is", "running" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/daemon_darwin.go#L49-L63
train
takama/daemon
daemon_windows.go
execPath
func execPath() (string, error) { var n uint32 b := make([]uint16, syscall.MAX_PATH) size := uint32(len(b)) r0, _, e1 := syscall.MustLoadDLL( "kernel32.dll", ).MustFindProc( "GetModuleFileNameW", ).Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size)) n = uint32(r0) if n == 0 { return "", e1 } return string(utf16.Decode(b[0:n])), nil }
go
func execPath() (string, error) { var n uint32 b := make([]uint16, syscall.MAX_PATH) size := uint32(len(b)) r0, _, e1 := syscall.MustLoadDLL( "kernel32.dll", ).MustFindProc( "GetModuleFileNameW", ).Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size)) n = uint32(r0) if n == 0 { return "", e1 } return string(utf16.Decode(b[0:n])), nil }
[ "func", "execPath", "(", ")", "(", "string", ",", "error", ")", "{", "var", "n", "uint32", "\n", "b", ":=", "make", "(", "[", "]", "uint16", ",", "syscall", ".", "MAX_PATH", ")", "\n", "size", ":=", "uint32", "(", "len", "(", "b", ")", ")", "\n\n", "r0", ",", "_", ",", "e1", ":=", "syscall", ".", "MustLoadDLL", "(", "\"", "\"", ",", ")", ".", "MustFindProc", "(", "\"", "\"", ",", ")", ".", "Call", "(", "0", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "b", "[", "0", "]", ")", ")", ",", "uintptr", "(", "size", ")", ")", "\n", "n", "=", "uint32", "(", "r0", ")", "\n", "if", "n", "==", "0", "{", "return", "\"", "\"", ",", "e1", "\n", "}", "\n", "return", "string", "(", "utf16", ".", "Decode", "(", "b", "[", "0", ":", "n", "]", ")", ")", ",", "nil", "\n", "}" ]
// Get executable path
[ "Get", "executable", "path" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/daemon_windows.go#L202-L217
train
takama/daemon
daemon_windows.go
getWindowsError
func getWindowsError(inputError error) error { if exiterr, ok := inputError.(*exec.ExitError); ok { if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { if sysErr, ok := WinErrCode[status.ExitStatus()]; ok { return errors.New(fmt.Sprintf("\n %s: %s \n %s", sysErr.Title, sysErr.Description, sysErr.Action)) } } } return inputError }
go
func getWindowsError(inputError error) error { if exiterr, ok := inputError.(*exec.ExitError); ok { if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { if sysErr, ok := WinErrCode[status.ExitStatus()]; ok { return errors.New(fmt.Sprintf("\n %s: %s \n %s", sysErr.Title, sysErr.Description, sysErr.Action)) } } } return inputError }
[ "func", "getWindowsError", "(", "inputError", "error", ")", "error", "{", "if", "exiterr", ",", "ok", ":=", "inputError", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "{", "if", "status", ",", "ok", ":=", "exiterr", ".", "Sys", "(", ")", ".", "(", "syscall", ".", "WaitStatus", ")", ";", "ok", "{", "if", "sysErr", ",", "ok", ":=", "WinErrCode", "[", "status", ".", "ExitStatus", "(", ")", "]", ";", "ok", "{", "return", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "sysErr", ".", "Title", ",", "sysErr", ".", "Description", ",", "sysErr", ".", "Action", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "inputError", "\n", "}" ]
// Get windows error
[ "Get", "windows", "error" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/daemon_windows.go#L220-L230
train
takama/daemon
daemon_windows.go
getWindowsServiceStateFromUint32
func getWindowsServiceStateFromUint32(state svc.State) string { switch state { case svc.Stopped: return "SERVICE_STOPPED" case svc.StartPending: return "SERVICE_START_PENDING" case svc.StopPending: return "SERVICE_STOP_PENDING" case svc.Running: return "SERVICE_RUNNING" case svc.ContinuePending: return "SERVICE_CONTINUE_PENDING" case svc.PausePending: return "SERVICE_PAUSE_PENDING" case svc.Paused: return "SERVICE_PAUSED" } return "SERVICE_UNKNOWN" }
go
func getWindowsServiceStateFromUint32(state svc.State) string { switch state { case svc.Stopped: return "SERVICE_STOPPED" case svc.StartPending: return "SERVICE_START_PENDING" case svc.StopPending: return "SERVICE_STOP_PENDING" case svc.Running: return "SERVICE_RUNNING" case svc.ContinuePending: return "SERVICE_CONTINUE_PENDING" case svc.PausePending: return "SERVICE_PAUSE_PENDING" case svc.Paused: return "SERVICE_PAUSED" } return "SERVICE_UNKNOWN" }
[ "func", "getWindowsServiceStateFromUint32", "(", "state", "svc", ".", "State", ")", "string", "{", "switch", "state", "{", "case", "svc", ".", "Stopped", ":", "return", "\"", "\"", "\n", "case", "svc", ".", "StartPending", ":", "return", "\"", "\"", "\n", "case", "svc", ".", "StopPending", ":", "return", "\"", "\"", "\n", "case", "svc", ".", "Running", ":", "return", "\"", "\"", "\n", "case", "svc", ".", "ContinuePending", ":", "return", "\"", "\"", "\n", "case", "svc", ".", "PausePending", ":", "return", "\"", "\"", "\n", "case", "svc", ".", "Paused", ":", "return", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Get windows service state
[ "Get", "windows", "service", "state" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/daemon_windows.go#L233-L251
train
takama/daemon
helper.go
executablePath
func executablePath(name string) (string, error) { if path, err := exec.LookPath(name); err == nil { if _, err := os.Stat(path); err == nil { return path, nil } } return os.Executable() }
go
func executablePath(name string) (string, error) { if path, err := exec.LookPath(name); err == nil { if _, err := os.Stat(path); err == nil { return path, nil } } return os.Executable() }
[ "func", "executablePath", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "if", "path", ",", "err", ":=", "exec", ".", "LookPath", "(", "name", ")", ";", "err", "==", "nil", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "==", "nil", "{", "return", "path", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "os", ".", "Executable", "(", ")", "\n", "}" ]
// Lookup path for executable file
[ "Lookup", "path", "for", "executable", "file" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/helper.go#L49-L56
train
takama/daemon
helper.go
checkPrivileges
func checkPrivileges() (bool, error) { if output, err := exec.Command("id", "-g").Output(); err == nil { if gid, parseErr := strconv.ParseUint(strings.TrimSpace(string(output)), 10, 32); parseErr == nil { if gid == 0 { return true, nil } return false, ErrRootPrivileges } } return false, ErrUnsupportedSystem }
go
func checkPrivileges() (bool, error) { if output, err := exec.Command("id", "-g").Output(); err == nil { if gid, parseErr := strconv.ParseUint(strings.TrimSpace(string(output)), 10, 32); parseErr == nil { if gid == 0 { return true, nil } return false, ErrRootPrivileges } } return false, ErrUnsupportedSystem }
[ "func", "checkPrivileges", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "output", ",", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Output", "(", ")", ";", "err", "==", "nil", "{", "if", "gid", ",", "parseErr", ":=", "strconv", ".", "ParseUint", "(", "strings", ".", "TrimSpace", "(", "string", "(", "output", ")", ")", ",", "10", ",", "32", ")", ";", "parseErr", "==", "nil", "{", "if", "gid", "==", "0", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "ErrRootPrivileges", "\n", "}", "\n", "}", "\n", "return", "false", ",", "ErrUnsupportedSystem", "\n", "}" ]
// Check root rights to use system service
[ "Check", "root", "rights", "to", "use", "system", "service" ]
aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e
https://github.com/takama/daemon/blob/aa76b0035d1239b7bb3ae1bd84cd88ef2e0a1f1e/helper.go#L59-L70
train
docker/docker-credential-helpers
client/command.go
NewShellProgramFuncWithEnv
func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc { return func(args ...string) Program { return &Shell{cmd: createProgramCmdRedirectErr(name, args, env)} } }
go
func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc { return func(args ...string) Program { return &Shell{cmd: createProgramCmdRedirectErr(name, args, env)} } }
[ "func", "NewShellProgramFuncWithEnv", "(", "name", "string", ",", "env", "*", "map", "[", "string", "]", "string", ")", "ProgramFunc", "{", "return", "func", "(", "args", "...", "string", ")", "Program", "{", "return", "&", "Shell", "{", "cmd", ":", "createProgramCmdRedirectErr", "(", "name", ",", "args", ",", "env", ")", "}", "\n", "}", "\n", "}" ]
// NewShellProgramFuncWithEnv creates programs that are executed in a Shell with environment variables
[ "NewShellProgramFuncWithEnv", "creates", "programs", "that", "are", "executed", "in", "a", "Shell", "with", "environment", "variables" ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/command.go#L25-L29
train
docker/docker-credential-helpers
client/command.go
Input
func (s *Shell) Input(in io.Reader) { s.cmd.Stdin = in }
go
func (s *Shell) Input(in io.Reader) { s.cmd.Stdin = in }
[ "func", "(", "s", "*", "Shell", ")", "Input", "(", "in", "io", ".", "Reader", ")", "{", "s", ".", "cmd", ".", "Stdin", "=", "in", "\n", "}" ]
// Input sets the input to send to a remote credentials helper.
[ "Input", "sets", "the", "input", "to", "send", "to", "a", "remote", "credentials", "helper", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/command.go#L54-L56
train
docker/docker-credential-helpers
client/client.go
isValidCredsMessage
func isValidCredsMessage(msg string) error { if credentials.IsCredentialsMissingServerURLMessage(msg) { return credentials.NewErrCredentialsMissingServerURL() } if credentials.IsCredentialsMissingUsernameMessage(msg) { return credentials.NewErrCredentialsMissingUsername() } return nil }
go
func isValidCredsMessage(msg string) error { if credentials.IsCredentialsMissingServerURLMessage(msg) { return credentials.NewErrCredentialsMissingServerURL() } if credentials.IsCredentialsMissingUsernameMessage(msg) { return credentials.NewErrCredentialsMissingUsername() } return nil }
[ "func", "isValidCredsMessage", "(", "msg", "string", ")", "error", "{", "if", "credentials", ".", "IsCredentialsMissingServerURLMessage", "(", "msg", ")", "{", "return", "credentials", ".", "NewErrCredentialsMissingServerURL", "(", ")", "\n", "}", "\n\n", "if", "credentials", ".", "IsCredentialsMissingUsernameMessage", "(", "msg", ")", "{", "return", "credentials", ".", "NewErrCredentialsMissingUsername", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// isValidCredsMessage checks if 'msg' contains invalid credentials error message. // It returns whether the logs are free of invalid credentials errors and the error if it isn't. // error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername.
[ "isValidCredsMessage", "checks", "if", "msg", "contains", "invalid", "credentials", "error", "message", ".", "It", "returns", "whether", "the", "logs", "are", "free", "of", "invalid", "credentials", "errors", "and", "the", "error", "if", "it", "isn", "t", ".", "error", "values", "can", "be", "errCredentialsMissingServerURL", "or", "errCredentialsMissingUsername", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/client.go#L15-L25
train
docker/docker-credential-helpers
client/client.go
Store
func Store(program ProgramFunc, creds *credentials.Credentials) error { cmd := program("store") buffer := new(bytes.Buffer) if err := json.NewEncoder(buffer).Encode(creds); err != nil { return err } cmd.Input(buffer) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t) } return nil }
go
func Store(program ProgramFunc, creds *credentials.Credentials) error { cmd := program("store") buffer := new(bytes.Buffer) if err := json.NewEncoder(buffer).Encode(creds); err != nil { return err } cmd.Input(buffer) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t) } return nil }
[ "func", "Store", "(", "program", "ProgramFunc", ",", "creds", "*", "credentials", ".", "Credentials", ")", "error", "{", "cmd", ":=", "program", "(", "\"", "\"", ")", "\n\n", "buffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "buffer", ")", ".", "Encode", "(", "creds", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cmd", ".", "Input", "(", "buffer", ")", "\n\n", "out", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ":=", "strings", ".", "TrimSpace", "(", "string", "(", "out", ")", ")", "\n\n", "if", "isValidErr", ":=", "isValidCredsMessage", "(", "t", ")", ";", "isValidErr", "!=", "nil", "{", "err", "=", "isValidErr", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "t", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Store uses an external program to save credentials.
[ "Store", "uses", "an", "external", "program", "to", "save", "credentials", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/client.go#L28-L49
train
docker/docker-credential-helpers
client/client.go
Get
func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) { cmd := program("get") cmd.Input(strings.NewReader(serverURL)) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if credentials.IsErrCredentialsNotFoundMessage(t) { return nil, credentials.NewErrCredentialsNotFound() } if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t) } resp := &credentials.Credentials{ ServerURL: serverURL, } if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil { return nil, err } return resp, nil }
go
func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) { cmd := program("get") cmd.Input(strings.NewReader(serverURL)) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if credentials.IsErrCredentialsNotFoundMessage(t) { return nil, credentials.NewErrCredentialsNotFound() } if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t) } resp := &credentials.Credentials{ ServerURL: serverURL, } if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil { return nil, err } return resp, nil }
[ "func", "Get", "(", "program", "ProgramFunc", ",", "serverURL", "string", ")", "(", "*", "credentials", ".", "Credentials", ",", "error", ")", "{", "cmd", ":=", "program", "(", "\"", "\"", ")", "\n", "cmd", ".", "Input", "(", "strings", ".", "NewReader", "(", "serverURL", ")", ")", "\n\n", "out", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ":=", "strings", ".", "TrimSpace", "(", "string", "(", "out", ")", ")", "\n\n", "if", "credentials", ".", "IsErrCredentialsNotFoundMessage", "(", "t", ")", "{", "return", "nil", ",", "credentials", ".", "NewErrCredentialsNotFound", "(", ")", "\n", "}", "\n\n", "if", "isValidErr", ":=", "isValidCredsMessage", "(", "t", ")", ";", "isValidErr", "!=", "nil", "{", "err", "=", "isValidErr", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "t", ")", "\n", "}", "\n\n", "resp", ":=", "&", "credentials", ".", "Credentials", "{", "ServerURL", ":", "serverURL", ",", "}", "\n\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "out", ")", ")", ".", "Decode", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}" ]
// Get executes an external program to get the credentials from a native store.
[ "Get", "executes", "an", "external", "program", "to", "get", "the", "credentials", "from", "a", "native", "store", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/client.go#L52-L80
train
docker/docker-credential-helpers
client/client.go
Erase
func Erase(program ProgramFunc, serverURL string) error { cmd := program("erase") cmd.Input(strings.NewReader(serverURL)) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t) } return nil }
go
func Erase(program ProgramFunc, serverURL string) error { cmd := program("erase") cmd.Input(strings.NewReader(serverURL)) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t) } return nil }
[ "func", "Erase", "(", "program", "ProgramFunc", ",", "serverURL", "string", ")", "error", "{", "cmd", ":=", "program", "(", "\"", "\"", ")", "\n", "cmd", ".", "Input", "(", "strings", ".", "NewReader", "(", "serverURL", ")", ")", "\n", "out", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ":=", "strings", ".", "TrimSpace", "(", "string", "(", "out", ")", ")", "\n\n", "if", "isValidErr", ":=", "isValidCredsMessage", "(", "t", ")", ";", "isValidErr", "!=", "nil", "{", "err", "=", "isValidErr", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "t", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Erase executes a program to remove the server credentials from the native store.
[ "Erase", "executes", "a", "program", "to", "remove", "the", "server", "credentials", "from", "the", "native", "store", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/client.go#L83-L98
train
docker/docker-credential-helpers
client/client.go
List
func List(program ProgramFunc) (map[string]string, error) { cmd := program("list") cmd.Input(strings.NewReader("unused")) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t) } var resp map[string]string if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil { return nil, err } return resp, nil }
go
func List(program ProgramFunc) (map[string]string, error) { cmd := program("list") cmd.Input(strings.NewReader("unused")) out, err := cmd.Output() if err != nil { t := strings.TrimSpace(string(out)) if isValidErr := isValidCredsMessage(t); isValidErr != nil { err = isValidErr } return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t) } var resp map[string]string if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil { return nil, err } return resp, nil }
[ "func", "List", "(", "program", "ProgramFunc", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "cmd", ":=", "program", "(", "\"", "\"", ")", "\n", "cmd", ".", "Input", "(", "strings", ".", "NewReader", "(", "\"", "\"", ")", ")", "\n", "out", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ":=", "strings", ".", "TrimSpace", "(", "string", "(", "out", ")", ")", "\n\n", "if", "isValidErr", ":=", "isValidCredsMessage", "(", "t", ")", ";", "isValidErr", "!=", "nil", "{", "err", "=", "isValidErr", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "t", ")", "\n", "}", "\n\n", "var", "resp", "map", "[", "string", "]", "string", "\n", "if", "err", "=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "out", ")", ")", ".", "Decode", "(", "&", "resp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}" ]
// List executes a program to list server credentials in the native store.
[ "List", "executes", "a", "program", "to", "list", "server", "credentials", "in", "the", "native", "store", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/client/client.go#L101-L121
train
docker/docker-credential-helpers
osxkeychain/osxkeychain_darwin.go
Delete
func (h Osxkeychain) Delete(serverURL string) error { s, err := splitServer(serverURL) if err != nil { return err } defer freeServer(s) errMsg := C.keychain_delete(s) if errMsg != nil { defer C.free(unsafe.Pointer(errMsg)) return errors.New(C.GoString(errMsg)) } return nil }
go
func (h Osxkeychain) Delete(serverURL string) error { s, err := splitServer(serverURL) if err != nil { return err } defer freeServer(s) errMsg := C.keychain_delete(s) if errMsg != nil { defer C.free(unsafe.Pointer(errMsg)) return errors.New(C.GoString(errMsg)) } return nil }
[ "func", "(", "h", "Osxkeychain", ")", "Delete", "(", "serverURL", "string", ")", "error", "{", "s", ",", "err", ":=", "splitServer", "(", "serverURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "freeServer", "(", "s", ")", "\n\n", "errMsg", ":=", "C", ".", "keychain_delete", "(", "s", ")", "\n", "if", "errMsg", "!=", "nil", "{", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "errMsg", ")", ")", "\n", "return", "errors", ".", "New", "(", "C", ".", "GoString", "(", "errMsg", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Delete removes credentials from the keychain.
[ "Delete", "removes", "credentials", "from", "the", "keychain", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/osxkeychain/osxkeychain_darwin.go#L54-L68
train
docker/docker-credential-helpers
osxkeychain/osxkeychain_darwin.go
List
func (h Osxkeychain) List() (map[string]string, error) { credsLabelC := C.CString(credentials.CredsLabel) defer C.free(unsafe.Pointer(credsLabelC)) var pathsC **C.char defer C.free(unsafe.Pointer(pathsC)) var acctsC **C.char defer C.free(unsafe.Pointer(acctsC)) var listLenC C.uint errMsg := C.keychain_list(credsLabelC, &pathsC, &acctsC, &listLenC) if errMsg != nil { defer C.free(unsafe.Pointer(errMsg)) goMsg := C.GoString(errMsg) if goMsg == errCredentialsNotFound { return make(map[string]string), nil } return nil, errors.New(goMsg) } defer C.freeListData(&pathsC, listLenC) defer C.freeListData(&acctsC, listLenC) var listLen int listLen = int(listLenC) pathTmp := (*[1 << 30]*C.char)(unsafe.Pointer(pathsC))[:listLen:listLen] acctTmp := (*[1 << 30]*C.char)(unsafe.Pointer(acctsC))[:listLen:listLen] //taking the array of c strings into go while ignoring all the stuff irrelevant to credentials-helper resp := make(map[string]string) for i := 0; i < listLen; i++ { if C.GoString(pathTmp[i]) == "0" { continue } resp[C.GoString(pathTmp[i])] = C.GoString(acctTmp[i]) } return resp, nil }
go
func (h Osxkeychain) List() (map[string]string, error) { credsLabelC := C.CString(credentials.CredsLabel) defer C.free(unsafe.Pointer(credsLabelC)) var pathsC **C.char defer C.free(unsafe.Pointer(pathsC)) var acctsC **C.char defer C.free(unsafe.Pointer(acctsC)) var listLenC C.uint errMsg := C.keychain_list(credsLabelC, &pathsC, &acctsC, &listLenC) if errMsg != nil { defer C.free(unsafe.Pointer(errMsg)) goMsg := C.GoString(errMsg) if goMsg == errCredentialsNotFound { return make(map[string]string), nil } return nil, errors.New(goMsg) } defer C.freeListData(&pathsC, listLenC) defer C.freeListData(&acctsC, listLenC) var listLen int listLen = int(listLenC) pathTmp := (*[1 << 30]*C.char)(unsafe.Pointer(pathsC))[:listLen:listLen] acctTmp := (*[1 << 30]*C.char)(unsafe.Pointer(acctsC))[:listLen:listLen] //taking the array of c strings into go while ignoring all the stuff irrelevant to credentials-helper resp := make(map[string]string) for i := 0; i < listLen; i++ { if C.GoString(pathTmp[i]) == "0" { continue } resp[C.GoString(pathTmp[i])] = C.GoString(acctTmp[i]) } return resp, nil }
[ "func", "(", "h", "Osxkeychain", ")", "List", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "credsLabelC", ":=", "C", ".", "CString", "(", "credentials", ".", "CredsLabel", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "credsLabelC", ")", ")", "\n\n", "var", "pathsC", "*", "*", "C", ".", "char", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "pathsC", ")", ")", "\n", "var", "acctsC", "*", "*", "C", ".", "char", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "acctsC", ")", ")", "\n", "var", "listLenC", "C", ".", "uint", "\n", "errMsg", ":=", "C", ".", "keychain_list", "(", "credsLabelC", ",", "&", "pathsC", ",", "&", "acctsC", ",", "&", "listLenC", ")", "\n", "if", "errMsg", "!=", "nil", "{", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "errMsg", ")", ")", "\n", "goMsg", ":=", "C", ".", "GoString", "(", "errMsg", ")", "\n", "if", "goMsg", "==", "errCredentialsNotFound", "{", "return", "make", "(", "map", "[", "string", "]", "string", ")", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "errors", ".", "New", "(", "goMsg", ")", "\n", "}", "\n\n", "defer", "C", ".", "freeListData", "(", "&", "pathsC", ",", "listLenC", ")", "\n", "defer", "C", ".", "freeListData", "(", "&", "acctsC", ",", "listLenC", ")", "\n\n", "var", "listLen", "int", "\n", "listLen", "=", "int", "(", "listLenC", ")", "\n", "pathTmp", ":=", "(", "*", "[", "1", "<<", "30", "]", "*", "C", ".", "char", ")", "(", "unsafe", ".", "Pointer", "(", "pathsC", ")", ")", "[", ":", "listLen", ":", "listLen", "]", "\n", "acctTmp", ":=", "(", "*", "[", "1", "<<", "30", "]", "*", "C", ".", "char", ")", "(", "unsafe", ".", "Pointer", "(", "acctsC", ")", ")", "[", ":", "listLen", ":", "listLen", "]", "\n", "//taking the array of c strings into go while ignoring all the stuff irrelevant to credentials-helper", "resp", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "listLen", ";", "i", "++", "{", "if", "C", ".", "GoString", "(", "pathTmp", "[", "i", "]", ")", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "resp", "[", "C", ".", "GoString", "(", "pathTmp", "[", "i", "]", ")", "]", "=", "C", ".", "GoString", "(", "acctTmp", "[", "i", "]", ")", "\n", "}", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// List returns the stored URLs and corresponding usernames.
[ "List", "returns", "the", "stored", "URLs", "and", "corresponding", "usernames", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/osxkeychain/osxkeychain_darwin.go#L102-L138
train
docker/docker-credential-helpers
credentials/credentials.go
isValid
func (c *Credentials) isValid() (bool, error) { if len(c.ServerURL) == 0 { return false, NewErrCredentialsMissingServerURL() } if len(c.Username) == 0 { return false, NewErrCredentialsMissingUsername() } return true, nil }
go
func (c *Credentials) isValid() (bool, error) { if len(c.ServerURL) == 0 { return false, NewErrCredentialsMissingServerURL() } if len(c.Username) == 0 { return false, NewErrCredentialsMissingUsername() } return true, nil }
[ "func", "(", "c", "*", "Credentials", ")", "isValid", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "len", "(", "c", ".", "ServerURL", ")", "==", "0", "{", "return", "false", ",", "NewErrCredentialsMissingServerURL", "(", ")", "\n", "}", "\n\n", "if", "len", "(", "c", ".", "Username", ")", "==", "0", "{", "return", "false", ",", "NewErrCredentialsMissingUsername", "(", ")", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// isValid checks the integrity of Credentials object such that no credentials lack // a server URL or a username. // It returns whether the credentials are valid and the error if it isn't. // error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername
[ "isValid", "checks", "the", "integrity", "of", "Credentials", "object", "such", "that", "no", "credentials", "lack", "a", "server", "URL", "or", "a", "username", ".", "It", "returns", "whether", "the", "credentials", "are", "valid", "and", "the", "error", "if", "it", "isn", "t", ".", "error", "values", "can", "be", "errCredentialsMissingServerURL", "or", "errCredentialsMissingUsername" ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L24-L34
train
docker/docker-credential-helpers
credentials/credentials.go
HandleCommand
func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error { switch key { case "store": return Store(helper, in) case "get": return Get(helper, in, out) case "erase": return Erase(helper, in) case "list": return List(helper, out) case "version": return PrintVersion(out) } return fmt.Errorf("Unknown credential action `%s`", key) }
go
func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error { switch key { case "store": return Store(helper, in) case "get": return Get(helper, in, out) case "erase": return Erase(helper, in) case "list": return List(helper, out) case "version": return PrintVersion(out) } return fmt.Errorf("Unknown credential action `%s`", key) }
[ "func", "HandleCommand", "(", "helper", "Helper", ",", "key", "string", ",", "in", "io", ".", "Reader", ",", "out", "io", ".", "Writer", ")", "error", "{", "switch", "key", "{", "case", "\"", "\"", ":", "return", "Store", "(", "helper", ",", "in", ")", "\n", "case", "\"", "\"", ":", "return", "Get", "(", "helper", ",", "in", ",", "out", ")", "\n", "case", "\"", "\"", ":", "return", "Erase", "(", "helper", ",", "in", ")", "\n", "case", "\"", "\"", ":", "return", "List", "(", "helper", ",", "out", ")", "\n", "case", "\"", "\"", ":", "return", "PrintVersion", "(", "out", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}" ]
// HandleCommand uses a helper and a key to run a credential action.
[ "HandleCommand", "uses", "a", "helper", "and", "a", "key", "to", "run", "a", "credential", "action", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L68-L82
train
docker/docker-credential-helpers
credentials/credentials.go
Store
func Store(helper Helper, reader io.Reader) error { scanner := bufio.NewScanner(reader) buffer := new(bytes.Buffer) for scanner.Scan() { buffer.Write(scanner.Bytes()) } if err := scanner.Err(); err != nil && err != io.EOF { return err } var creds Credentials if err := json.NewDecoder(buffer).Decode(&creds); err != nil { return err } if ok, err := creds.isValid(); !ok { return err } return helper.Add(&creds) }
go
func Store(helper Helper, reader io.Reader) error { scanner := bufio.NewScanner(reader) buffer := new(bytes.Buffer) for scanner.Scan() { buffer.Write(scanner.Bytes()) } if err := scanner.Err(); err != nil && err != io.EOF { return err } var creds Credentials if err := json.NewDecoder(buffer).Decode(&creds); err != nil { return err } if ok, err := creds.isValid(); !ok { return err } return helper.Add(&creds) }
[ "func", "Store", "(", "helper", "Helper", ",", "reader", "io", ".", "Reader", ")", "error", "{", "scanner", ":=", "bufio", ".", "NewScanner", "(", "reader", ")", "\n\n", "buffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "buffer", ".", "Write", "(", "scanner", ".", "Bytes", "(", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n\n", "var", "creds", "Credentials", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "buffer", ")", ".", "Decode", "(", "&", "creds", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "ok", ",", "err", ":=", "creds", ".", "isValid", "(", ")", ";", "!", "ok", "{", "return", "err", "\n", "}", "\n\n", "return", "helper", ".", "Add", "(", "&", "creds", ")", "\n", "}" ]
// Store uses a helper and an input reader to save credentials. // The reader must contain the JSON serialization of a Credentials struct.
[ "Store", "uses", "a", "helper", "and", "an", "input", "reader", "to", "save", "credentials", ".", "The", "reader", "must", "contain", "the", "JSON", "serialization", "of", "a", "Credentials", "struct", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L86-L108
train
docker/docker-credential-helpers
credentials/credentials.go
Get
func Get(helper Helper, reader io.Reader, writer io.Writer) error { scanner := bufio.NewScanner(reader) buffer := new(bytes.Buffer) for scanner.Scan() { buffer.Write(scanner.Bytes()) } if err := scanner.Err(); err != nil && err != io.EOF { return err } serverURL := strings.TrimSpace(buffer.String()) if len(serverURL) == 0 { return NewErrCredentialsMissingServerURL() } username, secret, err := helper.Get(serverURL) if err != nil { return err } resp := Credentials{ ServerURL: serverURL, Username: username, Secret: secret, } buffer.Reset() if err := json.NewEncoder(buffer).Encode(resp); err != nil { return err } fmt.Fprint(writer, buffer.String()) return nil }
go
func Get(helper Helper, reader io.Reader, writer io.Writer) error { scanner := bufio.NewScanner(reader) buffer := new(bytes.Buffer) for scanner.Scan() { buffer.Write(scanner.Bytes()) } if err := scanner.Err(); err != nil && err != io.EOF { return err } serverURL := strings.TrimSpace(buffer.String()) if len(serverURL) == 0 { return NewErrCredentialsMissingServerURL() } username, secret, err := helper.Get(serverURL) if err != nil { return err } resp := Credentials{ ServerURL: serverURL, Username: username, Secret: secret, } buffer.Reset() if err := json.NewEncoder(buffer).Encode(resp); err != nil { return err } fmt.Fprint(writer, buffer.String()) return nil }
[ "func", "Get", "(", "helper", "Helper", ",", "reader", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ")", "error", "{", "scanner", ":=", "bufio", ".", "NewScanner", "(", "reader", ")", "\n\n", "buffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "buffer", ".", "Write", "(", "scanner", ".", "Bytes", "(", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n\n", "serverURL", ":=", "strings", ".", "TrimSpace", "(", "buffer", ".", "String", "(", ")", ")", "\n", "if", "len", "(", "serverURL", ")", "==", "0", "{", "return", "NewErrCredentialsMissingServerURL", "(", ")", "\n", "}", "\n\n", "username", ",", "secret", ",", "err", ":=", "helper", ".", "Get", "(", "serverURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "resp", ":=", "Credentials", "{", "ServerURL", ":", "serverURL", ",", "Username", ":", "username", ",", "Secret", ":", "secret", ",", "}", "\n\n", "buffer", ".", "Reset", "(", ")", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "buffer", ")", ".", "Encode", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Fprint", "(", "writer", ",", "buffer", ".", "String", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Get retrieves the credentials for a given server url. // The reader must contain the server URL to search. // The writer is used to write the JSON serialization of the credentials.
[ "Get", "retrieves", "the", "credentials", "for", "a", "given", "server", "url", ".", "The", "reader", "must", "contain", "the", "server", "URL", "to", "search", ".", "The", "writer", "is", "used", "to", "write", "the", "JSON", "serialization", "of", "the", "credentials", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L113-L148
train