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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
apcera/libretto
virtualmachine/gcp/util.go
stop
func (svc *googleService) stop() error { _, err := svc.getInstance() if err != nil { if !strings.Contains(err.Error(), "no instance found") { return err } return fmt.Errorf("no instance found, %v", err) } op, err := svc.service.Instances.Stop(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do() if err != nil { return err } return svc.waitForOperationReady(op.Name) }
go
func (svc *googleService) stop() error { _, err := svc.getInstance() if err != nil { if !strings.Contains(err.Error(), "no instance found") { return err } return fmt.Errorf("no instance found, %v", err) } op, err := svc.service.Instances.Stop(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do() if err != nil { return err } return svc.waitForOperationReady(op.Name) }
[ "func", "(", "svc", "*", "googleService", ")", "stop", "(", ")", "error", "{", "_", ",", "err", ":=", "svc", ".", "getInstance", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "op", ",", "err", ":=", "svc", ".", "service", ".", "Instances", ".", "Stop", "(", "svc", ".", "vm", ".", "Project", ",", "svc", ".", "vm", ".", "Zone", ",", "svc", ".", "vm", ".", "Name", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "svc", ".", "waitForOperationReady", "(", "op", ".", "Name", ")", "\n", "}" ]
// stop halts a GCE instance.
[ "stop", "halts", "a", "GCE", "instance", "." ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/gcp/util.go#L356-L371
train
apcera/libretto
virtualmachine/gcp/util.go
delete
func (svc *googleService) delete() error { op, err := svc.service.Instances.Delete(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do() if err != nil { return err } return svc.waitForOperationReady(op.Name) }
go
func (svc *googleService) delete() error { op, err := svc.service.Instances.Delete(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do() if err != nil { return err } return svc.waitForOperationReady(op.Name) }
[ "func", "(", "svc", "*", "googleService", ")", "delete", "(", ")", "error", "{", "op", ",", "err", ":=", "svc", ".", "service", ".", "Instances", ".", "Delete", "(", "svc", ".", "vm", ".", "Project", ",", "svc", ".", "vm", ".", "Zone", ",", "svc", ".", "vm", ".", "Name", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "svc", ".", "waitForOperationReady", "(", "op", ".", "Name", ")", "\n", "}" ]
// deletes the GCE instance.
[ "deletes", "the", "GCE", "instance", "." ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/gcp/util.go#L374-L381
train
apcera/libretto
virtualmachine/vmrun/vm.go
Run
func (f vmrunRunner) Run(args ...string) (string, string, error) { var vmrunPath string // If vmrun is not found in the system path, fall back to the // hard coded path (VMRunPath). path, err := exec.LookPath("vmrun") if err == nil { vmrunPath = path } else { vmrunPath = VMRunPath } if vmrunPath == "" { return "", "", ErrVmrunNotFound } cmd := exec.Command(vmrunPath, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &stdout, &stderr err = cmd.Start() timer := time.AfterFunc(vmrunTimeout, func() { cmd.Process.Kill() err = ErrVmrunTimeout }) e := cmd.Wait() timer.Stop() if err != nil || e != nil { err = lvm.WrapErrors(err, e) } return stdout.String(), stderr.String(), err }
go
func (f vmrunRunner) Run(args ...string) (string, string, error) { var vmrunPath string // If vmrun is not found in the system path, fall back to the // hard coded path (VMRunPath). path, err := exec.LookPath("vmrun") if err == nil { vmrunPath = path } else { vmrunPath = VMRunPath } if vmrunPath == "" { return "", "", ErrVmrunNotFound } cmd := exec.Command(vmrunPath, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &stdout, &stderr err = cmd.Start() timer := time.AfterFunc(vmrunTimeout, func() { cmd.Process.Kill() err = ErrVmrunTimeout }) e := cmd.Wait() timer.Stop() if err != nil || e != nil { err = lvm.WrapErrors(err, e) } return stdout.String(), stderr.String(), err }
[ "func", "(", "f", "vmrunRunner", ")", "Run", "(", "args", "...", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "var", "vmrunPath", "string", "\n\n", "// If vmrun is not found in the system path, fall back to the", "// hard coded path (VMRunPath).", "path", ",", "err", ":=", "exec", ".", "LookPath", "(", "\"", "\"", ")", "\n", "if", "err", "==", "nil", "{", "vmrunPath", "=", "path", "\n", "}", "else", "{", "vmrunPath", "=", "VMRunPath", "\n", "}", "\n\n", "if", "vmrunPath", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "ErrVmrunNotFound", "\n", "}", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "vmrunPath", ",", "args", "...", ")", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n\n", "var", "stdout", "bytes", ".", "Buffer", "\n", "var", "stderr", "bytes", ".", "Buffer", "\n\n", "cmd", ".", "Stdout", ",", "cmd", ".", "Stderr", "=", "&", "stdout", ",", "&", "stderr", "\n\n", "err", "=", "cmd", ".", "Start", "(", ")", "\n", "timer", ":=", "time", ".", "AfterFunc", "(", "vmrunTimeout", ",", "func", "(", ")", "{", "cmd", ".", "Process", ".", "Kill", "(", ")", "\n", "err", "=", "ErrVmrunTimeout", "\n", "}", ")", "\n", "e", ":=", "cmd", ".", "Wait", "(", ")", "\n", "timer", ".", "Stop", "(", ")", "\n\n", "if", "err", "!=", "nil", "||", "e", "!=", "nil", "{", "err", "=", "lvm", ".", "WrapErrors", "(", "err", ",", "e", ")", "\n", "}", "\n", "return", "stdout", ".", "String", "(", ")", ",", "stderr", ".", "String", "(", ")", ",", "err", "\n", "}" ]
// Run runs a vmrun command.
[ "Run", "runs", "a", "vmrun", "command", "." ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/vmrun/vm.go#L80-L117
train
apcera/libretto
virtualmachine/exoscale/vm.go
GetName
func (vm *VM) GetName() string { if err := vm.updateInfo(); err != nil { return "" } return vm.Name }
go
func (vm *VM) GetName() string { if err := vm.updateInfo(); err != nil { return "" } return vm.Name }
[ "func", "(", "vm", "*", "VM", ")", "GetName", "(", ")", "string", "{", "if", "err", ":=", "vm", ".", "updateInfo", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "vm", ".", "Name", "\n", "}" ]
// GetName returns the name of the virtual machine // If an error occurs, an empty string is returned
[ "GetName", "returns", "the", "name", "of", "the", "virtual", "machine", "If", "an", "error", "occurs", "an", "empty", "string", "is", "returned" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L95-L102
train
apcera/libretto
virtualmachine/exoscale/vm.go
GetIPs
func (vm *VM) GetIPs() ([]net.IP, error) { if err := vm.updateInfo(); err != nil { return nil, err } return vm.ips, nil }
go
func (vm *VM) GetIPs() ([]net.IP, error) { if err := vm.updateInfo(); err != nil { return nil, err } return vm.ips, nil }
[ "func", "(", "vm", "*", "VM", ")", "GetIPs", "(", ")", "(", "[", "]", "net", ".", "IP", ",", "error", ")", "{", "if", "err", ":=", "vm", ".", "updateInfo", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "vm", ".", "ips", ",", "nil", "\n", "}" ]
// GetIPs returns the list of ip addresses associated with the VM
[ "GetIPs", "returns", "the", "list", "of", "ip", "addresses", "associated", "with", "the", "VM" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L160-L167
train
apcera/libretto
virtualmachine/exoscale/vm.go
Destroy
func (vm *VM) Destroy() error { if vm.ID == "" { return fmt.Errorf("Need an ID to destroy the virtual machine") } params := url.Values{} params.Set("id", vm.ID) client := vm.getExoClient() resp, err := client.Request("destroyVirtualMachine", params) if err != nil { return fmt.Errorf("Destroying virtual machine %q: %s", vm.ID, err) } destroy := &egoscale.DestroyVirtualMachineResponse{} if err := json.Unmarshal(resp, destroy); err != nil { return fmt.Errorf("Destroying virtual machine %q: %s", vm.ID, err) } vm.JobID = destroy.JobID return nil }
go
func (vm *VM) Destroy() error { if vm.ID == "" { return fmt.Errorf("Need an ID to destroy the virtual machine") } params := url.Values{} params.Set("id", vm.ID) client := vm.getExoClient() resp, err := client.Request("destroyVirtualMachine", params) if err != nil { return fmt.Errorf("Destroying virtual machine %q: %s", vm.ID, err) } destroy := &egoscale.DestroyVirtualMachineResponse{} if err := json.Unmarshal(resp, destroy); err != nil { return fmt.Errorf("Destroying virtual machine %q: %s", vm.ID, err) } vm.JobID = destroy.JobID return nil }
[ "func", "(", "vm", "*", "VM", ")", "Destroy", "(", ")", "error", "{", "if", "vm", ".", "ID", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "params", ":=", "url", ".", "Values", "{", "}", "\n", "params", ".", "Set", "(", "\"", "\"", ",", "vm", ".", "ID", ")", "\n\n", "client", ":=", "vm", ".", "getExoClient", "(", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Request", "(", "\"", "\"", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vm", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "destroy", ":=", "&", "egoscale", ".", "DestroyVirtualMachineResponse", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ",", "destroy", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vm", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "vm", ".", "JobID", "=", "destroy", ".", "JobID", "\n\n", "return", "nil", "\n", "}" ]
// Destroy removes virtual machine and all storage associated
[ "Destroy", "removes", "virtual", "machine", "and", "all", "storage", "associated" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L170-L193
train
apcera/libretto
virtualmachine/exoscale/vm.go
GetState
func (vm *VM) GetState() (string, error) { if vm.ID == "" { return "", fmt.Errorf("Need an ID to get virtual machine state") } if err := vm.updateInfo(); err != nil { return "", err } return vm.state, nil }
go
func (vm *VM) GetState() (string, error) { if vm.ID == "" { return "", fmt.Errorf("Need an ID to get virtual machine state") } if err := vm.updateInfo(); err != nil { return "", err } return vm.state, nil }
[ "func", "(", "vm", "*", "VM", ")", "GetState", "(", ")", "(", "string", ",", "error", ")", "{", "if", "vm", ".", "ID", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "vm", ".", "updateInfo", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "vm", ".", "state", ",", "nil", "\n", "}" ]
// GetState returns virtual machine state
[ "GetState", "returns", "virtual", "machine", "state" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L196-L207
train
apcera/libretto
virtualmachine/exoscale/vm.go
Halt
func (vm *VM) Halt() error { if vm.ID == "" { return fmt.Errorf("Need an ID to stop the virtual machine") } params := url.Values{} params.Set("id", vm.ID) client := vm.getExoClient() resp, err := client.Request("stopVirtualMachine", params) if err != nil { return fmt.Errorf("Stopping virtual machine %q: %s", vm.ID, err) } stop := &egoscale.StopVirtualMachineResponse{} if err := json.Unmarshal(resp, stop); err != nil { return fmt.Errorf("Stopping virtual machine %q: %s", vm.ID, err) } vm.JobID = stop.JobID return nil }
go
func (vm *VM) Halt() error { if vm.ID == "" { return fmt.Errorf("Need an ID to stop the virtual machine") } params := url.Values{} params.Set("id", vm.ID) client := vm.getExoClient() resp, err := client.Request("stopVirtualMachine", params) if err != nil { return fmt.Errorf("Stopping virtual machine %q: %s", vm.ID, err) } stop := &egoscale.StopVirtualMachineResponse{} if err := json.Unmarshal(resp, stop); err != nil { return fmt.Errorf("Stopping virtual machine %q: %s", vm.ID, err) } vm.JobID = stop.JobID return nil }
[ "func", "(", "vm", "*", "VM", ")", "Halt", "(", ")", "error", "{", "if", "vm", ".", "ID", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "params", ":=", "url", ".", "Values", "{", "}", "\n", "params", ".", "Set", "(", "\"", "\"", ",", "vm", ".", "ID", ")", "\n\n", "client", ":=", "vm", ".", "getExoClient", "(", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Request", "(", "\"", "\"", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vm", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "stop", ":=", "&", "egoscale", ".", "StopVirtualMachineResponse", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ",", "stop", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vm", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "vm", ".", "JobID", "=", "stop", ".", "JobID", "\n\n", "return", "nil", "\n\n", "}" ]
// Halt stop a virtual machine
[ "Halt", "stop", "a", "virtual", "machine" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L220-L244
train
apcera/libretto
virtualmachine/exoscale/vm.go
Start
func (vm *VM) Start() error { if vm.ID == "" { return fmt.Errorf("Need an ID to start the virtual machine") } params := url.Values{} params.Set("id", vm.ID) client := vm.getExoClient() resp, err := client.Request("startVirtualMachine", params) if err != nil { return fmt.Errorf("Starting virtual machine %q: %s", vm.ID, err) } start := &egoscale.StartVirtualMachineResponse{} if err := json.Unmarshal(resp, start); err != nil { return fmt.Errorf("Starting virtual machine %q: %s", vm.ID, err) } vm.JobID = start.JobID return nil }
go
func (vm *VM) Start() error { if vm.ID == "" { return fmt.Errorf("Need an ID to start the virtual machine") } params := url.Values{} params.Set("id", vm.ID) client := vm.getExoClient() resp, err := client.Request("startVirtualMachine", params) if err != nil { return fmt.Errorf("Starting virtual machine %q: %s", vm.ID, err) } start := &egoscale.StartVirtualMachineResponse{} if err := json.Unmarshal(resp, start); err != nil { return fmt.Errorf("Starting virtual machine %q: %s", vm.ID, err) } vm.JobID = start.JobID return nil }
[ "func", "(", "vm", "*", "VM", ")", "Start", "(", ")", "error", "{", "if", "vm", ".", "ID", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "params", ":=", "url", ".", "Values", "{", "}", "\n", "params", ".", "Set", "(", "\"", "\"", ",", "vm", ".", "ID", ")", "\n\n", "client", ":=", "vm", ".", "getExoClient", "(", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Request", "(", "\"", "\"", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vm", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "start", ":=", "&", "egoscale", ".", "StartVirtualMachineResponse", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ",", "start", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vm", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "vm", ".", "JobID", "=", "start", ".", "JobID", "\n\n", "return", "nil", "\n", "}" ]
// Start starts virtual machine
[ "Start", "starts", "virtual", "machine" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L247-L270
train
apcera/libretto
virtualmachine/exoscale/vm.go
GetSSH
func (vm *VM) GetSSH(options ssh.Options) (ssh.Client, error) { ips, err := util.GetVMIPs(vm, options) if err != nil { return nil, err } client := &ssh.SSHClient{ Creds: &vm.SSHCreds, IP: ips[0], // public IP Options: options, Port: 22, } if err := client.WaitForSSH(SSHTimeout); err != nil { return nil, err } return client, nil }
go
func (vm *VM) GetSSH(options ssh.Options) (ssh.Client, error) { ips, err := util.GetVMIPs(vm, options) if err != nil { return nil, err } client := &ssh.SSHClient{ Creds: &vm.SSHCreds, IP: ips[0], // public IP Options: options, Port: 22, } if err := client.WaitForSSH(SSHTimeout); err != nil { return nil, err } return client, nil }
[ "func", "(", "vm", "*", "VM", ")", "GetSSH", "(", "options", "ssh", ".", "Options", ")", "(", "ssh", ".", "Client", ",", "error", ")", "{", "ips", ",", "err", ":=", "util", ".", "GetVMIPs", "(", "vm", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "client", ":=", "&", "ssh", ".", "SSHClient", "{", "Creds", ":", "&", "vm", ".", "SSHCreds", ",", "IP", ":", "ips", "[", "0", "]", ",", "// public IP", "Options", ":", "options", ",", "Port", ":", "22", ",", "}", "\n", "if", "err", ":=", "client", ".", "WaitForSSH", "(", "SSHTimeout", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "client", ",", "nil", "\n\n", "}" ]
// GetSSH returns SSH keys to access the virtual machine
[ "GetSSH", "returns", "SSH", "keys", "to", "access", "the", "virtual", "machine" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/virtualmachine/exoscale/vm.go#L273-L292
train
apcera/libretto
ssh/mock_ssh.go
Connect
func (c *MockSSHClient) Connect() error { if c.MockConnect != nil { return c.MockConnect() } return ErrNotImplemented }
go
func (c *MockSSHClient) Connect() error { if c.MockConnect != nil { return c.MockConnect() } return ErrNotImplemented }
[ "func", "(", "c", "*", "MockSSHClient", ")", "Connect", "(", ")", "error", "{", "if", "c", ".", "MockConnect", "!=", "nil", "{", "return", "c", ".", "MockConnect", "(", ")", "\n", "}", "\n", "return", "ErrNotImplemented", "\n", "}" ]
// Connect calls the mocked connect.
[ "Connect", "calls", "the", "mocked", "connect", "." ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L27-L32
train
apcera/libretto
ssh/mock_ssh.go
Download
func (c *MockSSHClient) Download(src io.WriteCloser, dst string) error { if c.MockDownload != nil { return c.MockDownload(src, dst) } return ErrNotImplemented }
go
func (c *MockSSHClient) Download(src io.WriteCloser, dst string) error { if c.MockDownload != nil { return c.MockDownload(src, dst) } return ErrNotImplemented }
[ "func", "(", "c", "*", "MockSSHClient", ")", "Download", "(", "src", "io", ".", "WriteCloser", ",", "dst", "string", ")", "error", "{", "if", "c", ".", "MockDownload", "!=", "nil", "{", "return", "c", ".", "MockDownload", "(", "src", ",", "dst", ")", "\n", "}", "\n", "return", "ErrNotImplemented", "\n", "}" ]
// Download calls the mocked download.
[ "Download", "calls", "the", "mocked", "download", "." ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L42-L47
train
apcera/libretto
ssh/mock_ssh.go
Run
func (c *MockSSHClient) Run(command string, stdout io.Writer, stderr io.Writer) error { if c.MockRun != nil { return c.MockRun(command, stdout, stderr) } return ErrNotImplemented }
go
func (c *MockSSHClient) Run(command string, stdout io.Writer, stderr io.Writer) error { if c.MockRun != nil { return c.MockRun(command, stdout, stderr) } return ErrNotImplemented }
[ "func", "(", "c", "*", "MockSSHClient", ")", "Run", "(", "command", "string", ",", "stdout", "io", ".", "Writer", ",", "stderr", "io", ".", "Writer", ")", "error", "{", "if", "c", ".", "MockRun", "!=", "nil", "{", "return", "c", ".", "MockRun", "(", "command", ",", "stdout", ",", "stderr", ")", "\n", "}", "\n", "return", "ErrNotImplemented", "\n", "}" ]
// Run calls the mocked run
[ "Run", "calls", "the", "mocked", "run" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L50-L55
train
apcera/libretto
ssh/mock_ssh.go
Upload
func (c *MockSSHClient) Upload(src io.Reader, dst string, size int, mode uint32) error { if c.MockUpload != nil { return c.MockUpload(src, dst, size, mode) } return ErrNotImplemented }
go
func (c *MockSSHClient) Upload(src io.Reader, dst string, size int, mode uint32) error { if c.MockUpload != nil { return c.MockUpload(src, dst, size, mode) } return ErrNotImplemented }
[ "func", "(", "c", "*", "MockSSHClient", ")", "Upload", "(", "src", "io", ".", "Reader", ",", "dst", "string", ",", "size", "int", ",", "mode", "uint32", ")", "error", "{", "if", "c", ".", "MockUpload", "!=", "nil", "{", "return", "c", ".", "MockUpload", "(", "src", ",", "dst", ",", "size", ",", "mode", ")", "\n", "}", "\n", "return", "ErrNotImplemented", "\n", "}" ]
// Upload calls the mocked upload
[ "Upload", "calls", "the", "mocked", "upload" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L58-L63
train
apcera/libretto
ssh/mock_ssh.go
Validate
func (c *MockSSHClient) Validate() error { if c.MockValidate != nil { return c.MockValidate() } return ErrNotImplemented }
go
func (c *MockSSHClient) Validate() error { if c.MockValidate != nil { return c.MockValidate() } return ErrNotImplemented }
[ "func", "(", "c", "*", "MockSSHClient", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "MockValidate", "!=", "nil", "{", "return", "c", ".", "MockValidate", "(", ")", "\n", "}", "\n", "return", "ErrNotImplemented", "\n", "}" ]
// Validate calls the mocked validate.
[ "Validate", "calls", "the", "mocked", "validate", "." ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L66-L71
train
apcera/libretto
ssh/mock_ssh.go
WaitForSSH
func (c *MockSSHClient) WaitForSSH(maxWait time.Duration) error { if c.MockWaitForSSH != nil { return c.MockWaitForSSH(maxWait) } return ErrNotImplemented }
go
func (c *MockSSHClient) WaitForSSH(maxWait time.Duration) error { if c.MockWaitForSSH != nil { return c.MockWaitForSSH(maxWait) } return ErrNotImplemented }
[ "func", "(", "c", "*", "MockSSHClient", ")", "WaitForSSH", "(", "maxWait", "time", ".", "Duration", ")", "error", "{", "if", "c", ".", "MockWaitForSSH", "!=", "nil", "{", "return", "c", ".", "MockWaitForSSH", "(", "maxWait", ")", "\n", "}", "\n", "return", "ErrNotImplemented", "\n", "}" ]
// WaitForSSH calls the mocked WaitForSSH
[ "WaitForSSH", "calls", "the", "mocked", "WaitForSSH" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L74-L79
train
apcera/libretto
ssh/mock_ssh.go
SetSSHPrivateKey
func (c *MockSSHClient) SetSSHPrivateKey(s string) { if c.MockSetSSHPrivateKey != nil { c.MockSetSSHPrivateKey(s) } }
go
func (c *MockSSHClient) SetSSHPrivateKey(s string) { if c.MockSetSSHPrivateKey != nil { c.MockSetSSHPrivateKey(s) } }
[ "func", "(", "c", "*", "MockSSHClient", ")", "SetSSHPrivateKey", "(", "s", "string", ")", "{", "if", "c", ".", "MockSetSSHPrivateKey", "!=", "nil", "{", "c", ".", "MockSetSSHPrivateKey", "(", "s", ")", "\n", "}", "\n", "}" ]
// SetSSHPrivateKey calls the mocked SetSSHPrivateKey
[ "SetSSHPrivateKey", "calls", "the", "mocked", "SetSSHPrivateKey" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L82-L86
train
apcera/libretto
ssh/mock_ssh.go
SetSSHPassword
func (c *MockSSHClient) SetSSHPassword(s string) { if c.MockSetSSHPassword != nil { c.MockSetSSHPassword(s) } }
go
func (c *MockSSHClient) SetSSHPassword(s string) { if c.MockSetSSHPassword != nil { c.MockSetSSHPassword(s) } }
[ "func", "(", "c", "*", "MockSSHClient", ")", "SetSSHPassword", "(", "s", "string", ")", "{", "if", "c", ".", "MockSetSSHPassword", "!=", "nil", "{", "c", ".", "MockSetSSHPassword", "(", "s", ")", "\n", "}", "\n", "}" ]
// SetSSHPassword calls the mocked SetSSHPassword
[ "SetSSHPassword", "calls", "the", "mocked", "SetSSHPassword" ]
3178799fbb1e39c74b02e3ecf46330b3ef0ed486
https://github.com/apcera/libretto/blob/3178799fbb1e39c74b02e3ecf46330b3ef0ed486/ssh/mock_ssh.go#L97-L101
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/definition.go
InitializeFields
func (s *Definitions) InitializeFields(d *Definition) { for fieldName, property := range d.schema.Properties { des := strings.Replace(property.Description, "\n", " ", -1) f := &Field{ Name: fieldName, Type: GetTypeName(property), Description: EscapeAsterisks(des), } if len(property.Extensions) > 0 { if ps, ok := property.Extensions.GetString(patchStrategyKey); ok { f.PatchStrategy = ps } if pmk, ok := property.Extensions.GetString(patchMergeKeyKey); ok { f.PatchMergeKey = pmk } } if fd, ok := s.GetForSchema(property); ok { f.Definition = fd } d.Fields = append(d.Fields, f) } }
go
func (s *Definitions) InitializeFields(d *Definition) { for fieldName, property := range d.schema.Properties { des := strings.Replace(property.Description, "\n", " ", -1) f := &Field{ Name: fieldName, Type: GetTypeName(property), Description: EscapeAsterisks(des), } if len(property.Extensions) > 0 { if ps, ok := property.Extensions.GetString(patchStrategyKey); ok { f.PatchStrategy = ps } if pmk, ok := property.Extensions.GetString(patchMergeKeyKey); ok { f.PatchMergeKey = pmk } } if fd, ok := s.GetForSchema(property); ok { f.Definition = fd } d.Fields = append(d.Fields, f) } }
[ "func", "(", "s", "*", "Definitions", ")", "InitializeFields", "(", "d", "*", "Definition", ")", "{", "for", "fieldName", ",", "property", ":=", "range", "d", ".", "schema", ".", "Properties", "{", "des", ":=", "strings", ".", "Replace", "(", "property", ".", "Description", ",", "\"", "\\n", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "f", ":=", "&", "Field", "{", "Name", ":", "fieldName", ",", "Type", ":", "GetTypeName", "(", "property", ")", ",", "Description", ":", "EscapeAsterisks", "(", "des", ")", ",", "}", "\n", "if", "len", "(", "property", ".", "Extensions", ")", ">", "0", "{", "if", "ps", ",", "ok", ":=", "property", ".", "Extensions", ".", "GetString", "(", "patchStrategyKey", ")", ";", "ok", "{", "f", ".", "PatchStrategy", "=", "ps", "\n", "}", "\n", "if", "pmk", ",", "ok", ":=", "property", ".", "Extensions", ".", "GetString", "(", "patchMergeKeyKey", ")", ";", "ok", "{", "f", ".", "PatchMergeKey", "=", "pmk", "\n", "}", "\n", "}", "\n\n", "if", "fd", ",", "ok", ":=", "s", ".", "GetForSchema", "(", "property", ")", ";", "ok", "{", "f", ".", "Definition", "=", "fd", "\n", "}", "\n", "d", ".", "Fields", "=", "append", "(", "d", ".", "Fields", ",", "f", ")", "\n", "}", "\n", "}" ]
// Initializes the fields for a definition
[ "Initializes", "the", "fields", "for", "a", "definition" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/definition.go#L163-L185
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/util.go
GetDefinitionVersionKind
func GetDefinitionVersionKind(s spec.Schema) (string, string, string) { // Get the reference for complex types if IsDefinition(s) { s := fmt.Sprintf("%s", s.SchemaProps.Ref.GetPointer()) s = strings.Replace(s, "/definitions/", "", -1) name := strings.Split(s, ".") var group, version, kind string if name[len(name)-3] == "api" { // e.g. "io.k8s.apimachinery.pkg.api.resource.Quantity" group = "core" version = name[len(name)-2] kind = name[len(name)-1] } else if name[len(name)-4] == "api" { // e.g. "io.k8s.api.core.v1.Pod" group = name[len(name)-3] version = name[len(name)-2] kind = name[len(name)-1] } else if name[len(name)-4] == "apis" { // e.g. "io.k8s.apimachinery.pkg.apis.meta.v1.Status" group = name[len(name)-3] version = name[len(name)-2] kind = name[len(name)-1] } else if name[len(name)-3] == "util" || name[len(name)-3] == "pkg" { // e.g. io.k8s.apimachinery.pkg.util.intstr.IntOrString // e.g. io.k8s.apimachinery.pkg.runtime.RawExtension return "", "", "" } else { panic(errors.New(fmt.Sprintf("Could not locate group for %s", name))) } return group, version, kind } // Recurse if type is array if IsArray(s) { return GetDefinitionVersionKind(*s.Items.Schema) } return "", "", "" }
go
func GetDefinitionVersionKind(s spec.Schema) (string, string, string) { // Get the reference for complex types if IsDefinition(s) { s := fmt.Sprintf("%s", s.SchemaProps.Ref.GetPointer()) s = strings.Replace(s, "/definitions/", "", -1) name := strings.Split(s, ".") var group, version, kind string if name[len(name)-3] == "api" { // e.g. "io.k8s.apimachinery.pkg.api.resource.Quantity" group = "core" version = name[len(name)-2] kind = name[len(name)-1] } else if name[len(name)-4] == "api" { // e.g. "io.k8s.api.core.v1.Pod" group = name[len(name)-3] version = name[len(name)-2] kind = name[len(name)-1] } else if name[len(name)-4] == "apis" { // e.g. "io.k8s.apimachinery.pkg.apis.meta.v1.Status" group = name[len(name)-3] version = name[len(name)-2] kind = name[len(name)-1] } else if name[len(name)-3] == "util" || name[len(name)-3] == "pkg" { // e.g. io.k8s.apimachinery.pkg.util.intstr.IntOrString // e.g. io.k8s.apimachinery.pkg.runtime.RawExtension return "", "", "" } else { panic(errors.New(fmt.Sprintf("Could not locate group for %s", name))) } return group, version, kind } // Recurse if type is array if IsArray(s) { return GetDefinitionVersionKind(*s.Items.Schema) } return "", "", "" }
[ "func", "GetDefinitionVersionKind", "(", "s", "spec", ".", "Schema", ")", "(", "string", ",", "string", ",", "string", ")", "{", "// Get the reference for complex types", "if", "IsDefinition", "(", "s", ")", "{", "s", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "SchemaProps", ".", "Ref", ".", "GetPointer", "(", ")", ")", "\n", "s", "=", "strings", ".", "Replace", "(", "s", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "name", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n\n", "var", "group", ",", "version", ",", "kind", "string", "\n", "if", "name", "[", "len", "(", "name", ")", "-", "3", "]", "==", "\"", "\"", "{", "// e.g. \"io.k8s.apimachinery.pkg.api.resource.Quantity\"", "group", "=", "\"", "\"", "\n", "version", "=", "name", "[", "len", "(", "name", ")", "-", "2", "]", "\n", "kind", "=", "name", "[", "len", "(", "name", ")", "-", "1", "]", "\n", "}", "else", "if", "name", "[", "len", "(", "name", ")", "-", "4", "]", "==", "\"", "\"", "{", "// e.g. \"io.k8s.api.core.v1.Pod\"", "group", "=", "name", "[", "len", "(", "name", ")", "-", "3", "]", "\n", "version", "=", "name", "[", "len", "(", "name", ")", "-", "2", "]", "\n", "kind", "=", "name", "[", "len", "(", "name", ")", "-", "1", "]", "\n", "}", "else", "if", "name", "[", "len", "(", "name", ")", "-", "4", "]", "==", "\"", "\"", "{", "// e.g. \"io.k8s.apimachinery.pkg.apis.meta.v1.Status\"", "group", "=", "name", "[", "len", "(", "name", ")", "-", "3", "]", "\n", "version", "=", "name", "[", "len", "(", "name", ")", "-", "2", "]", "\n", "kind", "=", "name", "[", "len", "(", "name", ")", "-", "1", "]", "\n", "}", "else", "if", "name", "[", "len", "(", "name", ")", "-", "3", "]", "==", "\"", "\"", "||", "name", "[", "len", "(", "name", ")", "-", "3", "]", "==", "\"", "\"", "{", "// e.g. io.k8s.apimachinery.pkg.util.intstr.IntOrString", "// e.g. io.k8s.apimachinery.pkg.runtime.RawExtension", "return", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "\n", "}", "else", "{", "panic", "(", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", ")", "\n", "}", "\n", "return", "group", ",", "version", ",", "kind", "\n", "}", "\n", "// Recurse if type is array", "if", "IsArray", "(", "s", ")", "{", "return", "GetDefinitionVersionKind", "(", "*", "s", ".", "Items", ".", "Schema", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "\n", "}" ]
// GetDefinitionVersionKind returns the api version and kind for the spec. This is the primary key of a Definition.
[ "GetDefinitionVersionKind", "returns", "the", "api", "version", "and", "kind", "for", "the", "spec", ".", "This", "is", "the", "primary", "key", "of", "a", "Definition", "." ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/util.go#L39-L76
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/util.go
GetTypeName
func GetTypeName(s spec.Schema) string { // Get the reference for complex types if IsDefinition(s) { _, _, name := GetDefinitionVersionKind(s) return name } // Recurse if type is array if IsArray(s) { return fmt.Sprintf("%s array", GetTypeName(*s.Items.Schema)) } // Get the value for primitive types if len(s.Type) > 0 { return fmt.Sprintf("%s", s.Type[0]) } panic(fmt.Errorf("No type found for object %v", s)) }
go
func GetTypeName(s spec.Schema) string { // Get the reference for complex types if IsDefinition(s) { _, _, name := GetDefinitionVersionKind(s) return name } // Recurse if type is array if IsArray(s) { return fmt.Sprintf("%s array", GetTypeName(*s.Items.Schema)) } // Get the value for primitive types if len(s.Type) > 0 { return fmt.Sprintf("%s", s.Type[0]) } panic(fmt.Errorf("No type found for object %v", s)) }
[ "func", "GetTypeName", "(", "s", "spec", ".", "Schema", ")", "string", "{", "// Get the reference for complex types", "if", "IsDefinition", "(", "s", ")", "{", "_", ",", "_", ",", "name", ":=", "GetDefinitionVersionKind", "(", "s", ")", "\n", "return", "name", "\n", "}", "\n", "// Recurse if type is array", "if", "IsArray", "(", "s", ")", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "GetTypeName", "(", "*", "s", ".", "Items", ".", "Schema", ")", ")", "\n", "}", "\n", "// Get the value for primitive types", "if", "len", "(", "s", ".", "Type", ")", ">", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "Type", "[", "0", "]", ")", "\n", "}", "\n", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", ")", "\n", "}" ]
// GetTypeName returns the display name of a Schema. This is the api kind for definitions and the type for // primitive types. Arrays of objects have "array" appended.
[ "GetTypeName", "returns", "the", "display", "name", "of", "a", "Schema", ".", "This", "is", "the", "api", "kind", "for", "definitions", "and", "the", "type", "for", "primitive", "types", ".", "Arrays", "of", "objects", "have", "array", "appended", "." ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/util.go#L80-L95
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/util.go
IsArray
func IsArray(s spec.Schema) bool { return len(s.Type) > 0 && s.Type[0] == "array" }
go
func IsArray(s spec.Schema) bool { return len(s.Type) > 0 && s.Type[0] == "array" }
[ "func", "IsArray", "(", "s", "spec", ".", "Schema", ")", "bool", "{", "return", "len", "(", "s", ".", "Type", ")", ">", "0", "&&", "s", ".", "Type", "[", "0", "]", "==", "\"", "\"", "\n", "}" ]
// IsArray returns true if the type is an array type.
[ "IsArray", "returns", "true", "if", "the", "type", "is", "an", "array", "type", "." ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/util.go#L98-L100
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/util.go
IsDefinition
func IsDefinition(s spec.Schema) bool { return len(s.SchemaProps.Ref.GetPointer().String()) > 0 }
go
func IsDefinition(s spec.Schema) bool { return len(s.SchemaProps.Ref.GetPointer().String()) > 0 }
[ "func", "IsDefinition", "(", "s", "spec", ".", "Schema", ")", "bool", "{", "return", "len", "(", "s", ".", "SchemaProps", ".", "Ref", ".", "GetPointer", "(", ")", ".", "String", "(", ")", ")", ">", "0", "\n", "}" ]
// IsDefinition returns true if Schema is a complex type that should have a Definition.
[ "IsDefinition", "returns", "true", "if", "Schema", "is", "a", "complex", "type", "that", "should", "have", "a", "Definition", "." ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/util.go#L103-L105
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/config.go
initOperations
func (c *Config) initOperations(specs []*loads.Document) { ops := Operations{} c.GroupMap = map[string]string{} VisitOperations(specs, func(op Operation) { ops[op.ID] = &op // Build a map of the group names to the group name appearing in operation ids // This is necessary because the group will appear without the domain // in the resource, but with the domain in the operationID, and we // will be unable to match the operationID to the resource because they // don't agree on the name of the group. // TODO: Fix this by getting the group-version-kind in the resource if *MungeGroups { if v, ok := op.op.Extensions[typeKey]; ok { gvk := v.(map[string]interface{}) group, ok := gvk["group"].(string) if !ok { log.Fatalf("group not type string %v", v) } groupId := "" for _, s := range strings.Split(group, ".") { groupId = groupId + strings.Title(s) } c.GroupMap[strings.Title(strings.Split(group, ".")[0])] = groupId } } }) c.Operations = ops c.mapOperationsToDefinitions() c.initOperationsFromTags(specs) VisitOperations(specs, func(target Operation) { if op, ok := c.Operations[target.ID]; !ok || op.Definition == nil { op.VerifyBlackListed() } }) c.initOperationParameters() // Clear the operations. We still have to calculate the operations because that is how we determine // the API Group for each definition. if !*BuildOps { c.Operations = Operations{} c.OperationCategories = []OperationCategory{} for _, d := range c.Definitions.All { d.OperationCategories = []*OperationCategory{} } } }
go
func (c *Config) initOperations(specs []*loads.Document) { ops := Operations{} c.GroupMap = map[string]string{} VisitOperations(specs, func(op Operation) { ops[op.ID] = &op // Build a map of the group names to the group name appearing in operation ids // This is necessary because the group will appear without the domain // in the resource, but with the domain in the operationID, and we // will be unable to match the operationID to the resource because they // don't agree on the name of the group. // TODO: Fix this by getting the group-version-kind in the resource if *MungeGroups { if v, ok := op.op.Extensions[typeKey]; ok { gvk := v.(map[string]interface{}) group, ok := gvk["group"].(string) if !ok { log.Fatalf("group not type string %v", v) } groupId := "" for _, s := range strings.Split(group, ".") { groupId = groupId + strings.Title(s) } c.GroupMap[strings.Title(strings.Split(group, ".")[0])] = groupId } } }) c.Operations = ops c.mapOperationsToDefinitions() c.initOperationsFromTags(specs) VisitOperations(specs, func(target Operation) { if op, ok := c.Operations[target.ID]; !ok || op.Definition == nil { op.VerifyBlackListed() } }) c.initOperationParameters() // Clear the operations. We still have to calculate the operations because that is how we determine // the API Group for each definition. if !*BuildOps { c.Operations = Operations{} c.OperationCategories = []OperationCategory{} for _, d := range c.Definitions.All { d.OperationCategories = []*OperationCategory{} } } }
[ "func", "(", "c", "*", "Config", ")", "initOperations", "(", "specs", "[", "]", "*", "loads", ".", "Document", ")", "{", "ops", ":=", "Operations", "{", "}", "\n\n", "c", ".", "GroupMap", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "VisitOperations", "(", "specs", ",", "func", "(", "op", "Operation", ")", "{", "ops", "[", "op", ".", "ID", "]", "=", "&", "op", "\n\n", "// Build a map of the group names to the group name appearing in operation ids", "// This is necessary because the group will appear without the domain", "// in the resource, but with the domain in the operationID, and we", "// will be unable to match the operationID to the resource because they", "// don't agree on the name of the group.", "// TODO: Fix this by getting the group-version-kind in the resource", "if", "*", "MungeGroups", "{", "if", "v", ",", "ok", ":=", "op", ".", "op", ".", "Extensions", "[", "typeKey", "]", ";", "ok", "{", "gvk", ":=", "v", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "group", ",", "ok", ":=", "gvk", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "groupId", ":=", "\"", "\"", "\n", "for", "_", ",", "s", ":=", "range", "strings", ".", "Split", "(", "group", ",", "\"", "\"", ")", "{", "groupId", "=", "groupId", "+", "strings", ".", "Title", "(", "s", ")", "\n", "}", "\n", "c", ".", "GroupMap", "[", "strings", ".", "Title", "(", "strings", ".", "Split", "(", "group", ",", "\"", "\"", ")", "[", "0", "]", ")", "]", "=", "groupId", "\n", "}", "\n", "}", "\n", "}", ")", "\n\n", "c", ".", "Operations", "=", "ops", "\n", "c", ".", "mapOperationsToDefinitions", "(", ")", "\n", "c", ".", "initOperationsFromTags", "(", "specs", ")", "\n\n", "VisitOperations", "(", "specs", ",", "func", "(", "target", "Operation", ")", "{", "if", "op", ",", "ok", ":=", "c", ".", "Operations", "[", "target", ".", "ID", "]", ";", "!", "ok", "||", "op", ".", "Definition", "==", "nil", "{", "op", ".", "VerifyBlackListed", "(", ")", "\n", "}", "\n", "}", ")", "\n", "c", ".", "initOperationParameters", "(", ")", "\n\n", "// Clear the operations. We still have to calculate the operations because that is how we determine", "// the API Group for each definition.", "if", "!", "*", "BuildOps", "{", "c", ".", "Operations", "=", "Operations", "{", "}", "\n", "c", ".", "OperationCategories", "=", "[", "]", "OperationCategory", "{", "}", "\n", "for", "_", ",", "d", ":=", "range", "c", ".", "Definitions", ".", "All", "{", "d", ".", "OperationCategories", "=", "[", "]", "*", "OperationCategory", "{", "}", "\n", "}", "\n", "}", "\n", "}" ]
// initOperations returns all Operations found in the Documents
[ "initOperations", "returns", "all", "Operations", "found", "in", "the", "Documents" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/config.go#L195-L244
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/config.go
CleanUp
func (c *Config) CleanUp() { for _, d := range c.Definitions.All { sort.Sort(d.AppearsIn) sort.Sort(d.Fields) dedup := SortDefinitionsByName{} var last *Definition for _, i := range d.AppearsIn { if last != nil && i.Name == last.Name && i.Group.String() == last.Group.String() && i.Version.String() == last.Version.String() { continue } last = i dedup = append(dedup, i) } d.AppearsIn = dedup } }
go
func (c *Config) CleanUp() { for _, d := range c.Definitions.All { sort.Sort(d.AppearsIn) sort.Sort(d.Fields) dedup := SortDefinitionsByName{} var last *Definition for _, i := range d.AppearsIn { if last != nil && i.Name == last.Name && i.Group.String() == last.Group.String() && i.Version.String() == last.Version.String() { continue } last = i dedup = append(dedup, i) } d.AppearsIn = dedup } }
[ "func", "(", "c", "*", "Config", ")", "CleanUp", "(", ")", "{", "for", "_", ",", "d", ":=", "range", "c", ".", "Definitions", ".", "All", "{", "sort", ".", "Sort", "(", "d", ".", "AppearsIn", ")", "\n", "sort", ".", "Sort", "(", "d", ".", "Fields", ")", "\n", "dedup", ":=", "SortDefinitionsByName", "{", "}", "\n", "var", "last", "*", "Definition", "\n", "for", "_", ",", "i", ":=", "range", "d", ".", "AppearsIn", "{", "if", "last", "!=", "nil", "&&", "i", ".", "Name", "==", "last", ".", "Name", "&&", "i", ".", "Group", ".", "String", "(", ")", "==", "last", ".", "Group", ".", "String", "(", ")", "&&", "i", ".", "Version", ".", "String", "(", ")", "==", "last", ".", "Version", ".", "String", "(", ")", "{", "continue", "\n", "}", "\n", "last", "=", "i", "\n", "dedup", "=", "append", "(", "dedup", ",", "i", ")", "\n", "}", "\n", "d", ".", "AppearsIn", "=", "dedup", "\n", "}", "\n", "}" ]
// CleanUp sorts and dedups fields
[ "CleanUp", "sorts", "and", "dedups", "fields" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/config.go#L247-L265
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/config.go
LoadConfigFromYAML
func LoadConfigFromYAML() *Config { f := filepath.Join(*ConfigDir, "config.yaml") config := &Config{} contents, err := ioutil.ReadFile(f) if err != nil { if !*UseTags { fmt.Printf("Failed to read yaml file %s: %v", f, err) os.Exit(2) } } else { err = yaml.Unmarshal(contents, config) if err != nil { fmt.Println(err) os.Exit(1) } } writeCategory := OperationCategory{ Name: "Write Operations", OperationTypes: []OperationType{ { Name: "Create", Match: "create${group}${version}(Namespaced)?${resource}", }, { Name: "Create Eviction", Match: "create${group}${version}(Namespaced)?${resource}Eviction", }, { Name: "Patch", Match: "patch${group}${version}(Namespaced)?${resource}", }, { Name: "Replace", Match: "replace${group}${version}(Namespaced)?${resource}", }, { Name: "Delete", Match: "delete${group}${version}(Namespaced)?${resource}", }, { Name: "Delete Collection", Match: "delete${group}${version}Collection(Namespaced)?${resource}", }, }, } readCategory := OperationCategory{ Name: "Read Operations", OperationTypes: []OperationType{ { Name: "Read", Match: "read${group}${version}(Namespaced)?${resource}", }, { Name: "List", Match: "list${group}${version}(Namespaced)?${resource}", }, { Name: "List All Namespaces", Match: "list${group}${version}(Namespaced)?${resource}ForAllNamespaces", }, { Name: "Watch", Match: "watch${group}${version}(Namespaced)?${resource}", }, { Name: "Watch List", Match: "watch${group}${version}(Namespaced)?${resource}List", }, { Name: "Watch List All Namespaces", Match: "watch${group}${version}(Namespaced)?${resource}ListForAllNamespaces", }, }, } statusCategory := OperationCategory{ Name: "Status Operations", OperationTypes: []OperationType{ { Name: "Patch Status", Match: "patch${group}${version}(Namespaced)?${resource}Status", }, { Name: "Read Status", Match: "read${group}${version}(Namespaced)?${resource}Status", }, { Name: "Replace Status", Match: "replace${group}${version}(Namespaced)?${resource}Status", }, }, } config.OperationCategories = append([]OperationCategory{writeCategory, readCategory, statusCategory}, config.OperationCategories...) return config }
go
func LoadConfigFromYAML() *Config { f := filepath.Join(*ConfigDir, "config.yaml") config := &Config{} contents, err := ioutil.ReadFile(f) if err != nil { if !*UseTags { fmt.Printf("Failed to read yaml file %s: %v", f, err) os.Exit(2) } } else { err = yaml.Unmarshal(contents, config) if err != nil { fmt.Println(err) os.Exit(1) } } writeCategory := OperationCategory{ Name: "Write Operations", OperationTypes: []OperationType{ { Name: "Create", Match: "create${group}${version}(Namespaced)?${resource}", }, { Name: "Create Eviction", Match: "create${group}${version}(Namespaced)?${resource}Eviction", }, { Name: "Patch", Match: "patch${group}${version}(Namespaced)?${resource}", }, { Name: "Replace", Match: "replace${group}${version}(Namespaced)?${resource}", }, { Name: "Delete", Match: "delete${group}${version}(Namespaced)?${resource}", }, { Name: "Delete Collection", Match: "delete${group}${version}Collection(Namespaced)?${resource}", }, }, } readCategory := OperationCategory{ Name: "Read Operations", OperationTypes: []OperationType{ { Name: "Read", Match: "read${group}${version}(Namespaced)?${resource}", }, { Name: "List", Match: "list${group}${version}(Namespaced)?${resource}", }, { Name: "List All Namespaces", Match: "list${group}${version}(Namespaced)?${resource}ForAllNamespaces", }, { Name: "Watch", Match: "watch${group}${version}(Namespaced)?${resource}", }, { Name: "Watch List", Match: "watch${group}${version}(Namespaced)?${resource}List", }, { Name: "Watch List All Namespaces", Match: "watch${group}${version}(Namespaced)?${resource}ListForAllNamespaces", }, }, } statusCategory := OperationCategory{ Name: "Status Operations", OperationTypes: []OperationType{ { Name: "Patch Status", Match: "patch${group}${version}(Namespaced)?${resource}Status", }, { Name: "Read Status", Match: "read${group}${version}(Namespaced)?${resource}Status", }, { Name: "Replace Status", Match: "replace${group}${version}(Namespaced)?${resource}Status", }, }, } config.OperationCategories = append([]OperationCategory{writeCategory, readCategory, statusCategory}, config.OperationCategories...) return config }
[ "func", "LoadConfigFromYAML", "(", ")", "*", "Config", "{", "f", ":=", "filepath", ".", "Join", "(", "*", "ConfigDir", ",", "\"", "\"", ")", "\n\n", "config", ":=", "&", "Config", "{", "}", "\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "*", "UseTags", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "f", ",", "err", ")", "\n", "os", ".", "Exit", "(", "2", ")", "\n", "}", "\n", "}", "else", "{", "err", "=", "yaml", ".", "Unmarshal", "(", "contents", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", "\n\n", "writeCategory", ":=", "OperationCategory", "{", "Name", ":", "\"", "\"", ",", "OperationTypes", ":", "[", "]", "OperationType", "{", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "}", ",", "}", "\n\n", "readCategory", ":=", "OperationCategory", "{", "Name", ":", "\"", "\"", ",", "OperationTypes", ":", "[", "]", "OperationType", "{", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "}", ",", "}", "\n\n", "statusCategory", ":=", "OperationCategory", "{", "Name", ":", "\"", "\"", ",", "OperationTypes", ":", "[", "]", "OperationType", "{", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Match", ":", "\"", "\"", ",", "}", ",", "}", ",", "}", "\n\n", "config", ".", "OperationCategories", "=", "append", "(", "[", "]", "OperationCategory", "{", "writeCategory", ",", "readCategory", ",", "statusCategory", "}", ",", "config", ".", "OperationCategories", "...", ")", "\n\n", "return", "config", "\n", "}" ]
// LoadConfigFromYAML reads the config yaml file into a struct
[ "LoadConfigFromYAML", "reads", "the", "config", "yaml", "file", "into", "a", "struct" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/config.go#L268-L367
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/config.go
mapOperationsToDefinitions
func (c *Config) mapOperationsToDefinitions() { for _, d := range c.Definitions.All { if d.IsInlined { continue } for i := range c.OperationCategories { oc := c.OperationCategories[i] for j := range oc.OperationTypes { ot := oc.OperationTypes[j] operationId := c.getOperationId(ot.Match, d.GetOperationGroupName(), d.Version, d.Name) c.setOperation(operationId, "Namespaced", &ot, &oc, d) c.setOperation(operationId, "", &ot, &oc, d) } if len(oc.Operations) > 0 { d.OperationCategories = append(d.OperationCategories, &oc) } } } }
go
func (c *Config) mapOperationsToDefinitions() { for _, d := range c.Definitions.All { if d.IsInlined { continue } for i := range c.OperationCategories { oc := c.OperationCategories[i] for j := range oc.OperationTypes { ot := oc.OperationTypes[j] operationId := c.getOperationId(ot.Match, d.GetOperationGroupName(), d.Version, d.Name) c.setOperation(operationId, "Namespaced", &ot, &oc, d) c.setOperation(operationId, "", &ot, &oc, d) } if len(oc.Operations) > 0 { d.OperationCategories = append(d.OperationCategories, &oc) } } } }
[ "func", "(", "c", "*", "Config", ")", "mapOperationsToDefinitions", "(", ")", "{", "for", "_", ",", "d", ":=", "range", "c", ".", "Definitions", ".", "All", "{", "if", "d", ".", "IsInlined", "{", "continue", "\n", "}", "\n\n", "for", "i", ":=", "range", "c", ".", "OperationCategories", "{", "oc", ":=", "c", ".", "OperationCategories", "[", "i", "]", "\n", "for", "j", ":=", "range", "oc", ".", "OperationTypes", "{", "ot", ":=", "oc", ".", "OperationTypes", "[", "j", "]", "\n", "operationId", ":=", "c", ".", "getOperationId", "(", "ot", ".", "Match", ",", "d", ".", "GetOperationGroupName", "(", ")", ",", "d", ".", "Version", ",", "d", ".", "Name", ")", "\n", "c", ".", "setOperation", "(", "operationId", ",", "\"", "\"", ",", "&", "ot", ",", "&", "oc", ",", "d", ")", "\n", "c", ".", "setOperation", "(", "operationId", ",", "\"", "\"", ",", "&", "ot", ",", "&", "oc", ",", "d", ")", "\n", "}", "\n\n", "if", "len", "(", "oc", ".", "Operations", ")", ">", "0", "{", "d", ".", "OperationCategories", "=", "append", "(", "d", ".", "OperationCategories", ",", "&", "oc", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// mapOperationsToDefinitions adds operations to the definitions they operate
[ "mapOperationsToDefinitions", "adds", "operations", "to", "the", "definitions", "they", "operate" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/config.go#L471-L491
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/config.go
visitResourcesInToc
func (c *Config) visitResourcesInToc() { missing := false for _, cat := range c.ResourceCategories { for _, r := range cat.Resources { if d, ok := c.Definitions.GetByVersionKind(r.Group, r.Version, r.Name); ok { d.InToc = true // Mark as in Toc d.initExample(c) r.Definition = d } else { fmt.Printf("Could not find definition for resource in TOC: %s %s %s.\n", r.Group, r.Version, r.Name) missing = true } } } if missing { fmt.Printf("All known definitions: %v\n", c.Definitions.All) } }
go
func (c *Config) visitResourcesInToc() { missing := false for _, cat := range c.ResourceCategories { for _, r := range cat.Resources { if d, ok := c.Definitions.GetByVersionKind(r.Group, r.Version, r.Name); ok { d.InToc = true // Mark as in Toc d.initExample(c) r.Definition = d } else { fmt.Printf("Could not find definition for resource in TOC: %s %s %s.\n", r.Group, r.Version, r.Name) missing = true } } } if missing { fmt.Printf("All known definitions: %v\n", c.Definitions.All) } }
[ "func", "(", "c", "*", "Config", ")", "visitResourcesInToc", "(", ")", "{", "missing", ":=", "false", "\n", "for", "_", ",", "cat", ":=", "range", "c", ".", "ResourceCategories", "{", "for", "_", ",", "r", ":=", "range", "cat", ".", "Resources", "{", "if", "d", ",", "ok", ":=", "c", ".", "Definitions", ".", "GetByVersionKind", "(", "r", ".", "Group", ",", "r", ".", "Version", ",", "r", ".", "Name", ")", ";", "ok", "{", "d", ".", "InToc", "=", "true", "// Mark as in Toc", "\n", "d", ".", "initExample", "(", "c", ")", "\n", "r", ".", "Definition", "=", "d", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "r", ".", "Group", ",", "r", ".", "Version", ",", "r", ".", "Name", ")", "\n", "missing", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "missing", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "c", ".", "Definitions", ".", "All", ")", "\n", "}", "\n", "}" ]
// For each resource in the ToC, look up its definition and visit it.
[ "For", "each", "resource", "in", "the", "ToC", "look", "up", "its", "definition", "and", "visit", "it", "." ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/config.go#L524-L541
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
GetOperationId
func (ot OperationType) GetOperationId(d string) string { return strings.Replace(ot.Match, "${resource}", d, -1) }
go
func (ot OperationType) GetOperationId(d string) string { return strings.Replace(ot.Match, "${resource}", d, -1) }
[ "func", "(", "ot", "OperationType", ")", "GetOperationId", "(", "d", "string", ")", "string", "{", "return", "strings", ".", "Replace", "(", "ot", ".", "Match", ",", "\"", "\"", ",", "d", ",", "-", "1", ")", "\n", "}" ]
// GetOperationId returns the ID of the operation for the given definition
[ "GetOperationId", "returns", "the", "ID", "of", "the", "operation", "for", "the", "given", "definition" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L35-L37
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
VisitOperations
func VisitOperations(specs []*loads.Document, fn func(operation Operation)) { for _, d := range specs { for path, item := range d.Spec().Paths.Paths { for method, operation := range getOperationsForItem(item) { if operation != nil && !IsBlacklistedOperation(operation) { fn(Operation{ item: item, op: operation, Path: path, HttpMethod: method, ID: operation.ID, }) } } } } }
go
func VisitOperations(specs []*loads.Document, fn func(operation Operation)) { for _, d := range specs { for path, item := range d.Spec().Paths.Paths { for method, operation := range getOperationsForItem(item) { if operation != nil && !IsBlacklistedOperation(operation) { fn(Operation{ item: item, op: operation, Path: path, HttpMethod: method, ID: operation.ID, }) } } } } }
[ "func", "VisitOperations", "(", "specs", "[", "]", "*", "loads", ".", "Document", ",", "fn", "func", "(", "operation", "Operation", ")", ")", "{", "for", "_", ",", "d", ":=", "range", "specs", "{", "for", "path", ",", "item", ":=", "range", "d", ".", "Spec", "(", ")", ".", "Paths", ".", "Paths", "{", "for", "method", ",", "operation", ":=", "range", "getOperationsForItem", "(", "item", ")", "{", "if", "operation", "!=", "nil", "&&", "!", "IsBlacklistedOperation", "(", "operation", ")", "{", "fn", "(", "Operation", "{", "item", ":", "item", ",", "op", ":", "operation", ",", "Path", ":", "path", ",", "HttpMethod", ":", "method", ",", "ID", ":", "operation", ".", "ID", ",", "}", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// VisitOperations calls fn once for each operation found in the collection of Documents // VisitOperations calls fn once for each operation found in the collection of Documents
[ "VisitOperations", "calls", "fn", "once", "for", "each", "operation", "found", "in", "the", "collection", "of", "Documents", "VisitOperations", "calls", "fn", "once", "for", "each", "operation", "found", "in", "the", "collection", "of", "Documents" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L81-L97
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
getOperationsForItem
func getOperationsForItem(pathItem spec.PathItem) map[string]*spec.Operation { return map[string]*spec.Operation{ "GET": pathItem.Get, "DELETE": pathItem.Delete, "PATCH": pathItem.Patch, "PUT": pathItem.Put, "POST": pathItem.Post, "HEAD": pathItem.Head, } }
go
func getOperationsForItem(pathItem spec.PathItem) map[string]*spec.Operation { return map[string]*spec.Operation{ "GET": pathItem.Get, "DELETE": pathItem.Delete, "PATCH": pathItem.Patch, "PUT": pathItem.Put, "POST": pathItem.Post, "HEAD": pathItem.Head, } }
[ "func", "getOperationsForItem", "(", "pathItem", "spec", ".", "PathItem", ")", "map", "[", "string", "]", "*", "spec", ".", "Operation", "{", "return", "map", "[", "string", "]", "*", "spec", ".", "Operation", "{", "\"", "\"", ":", "pathItem", ".", "Get", ",", "\"", "\"", ":", "pathItem", ".", "Delete", ",", "\"", "\"", ":", "pathItem", ".", "Patch", ",", "\"", "\"", ":", "pathItem", ".", "Put", ",", "\"", "\"", ":", "pathItem", ".", "Post", ",", "\"", "\"", ":", "pathItem", ".", "Head", ",", "}", "\n", "}" ]
// Get all operations from the pathitem so we cacn iterate over them
[ "Get", "all", "operations", "from", "the", "pathitem", "so", "we", "cacn", "iterate", "over", "them" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L108-L117
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
initExample
func (o *Operation) initExample(config *Config) { path := o.Type.Name + ".yaml" path = filepath.Join(*ConfigDir, config.ExampleLocation, o.Definition.Name, path) path = strings.Replace(path, " ", "_", -1) path = strings.ToLower(path) content, err := ioutil.ReadFile(path) if err != nil { return } err = yaml.Unmarshal(content, &o.ExampleConfig) if err != nil { panic(fmt.Sprintf("Could not Unmarshal ExampleConfig yaml: %s\n", content)) } }
go
func (o *Operation) initExample(config *Config) { path := o.Type.Name + ".yaml" path = filepath.Join(*ConfigDir, config.ExampleLocation, o.Definition.Name, path) path = strings.Replace(path, " ", "_", -1) path = strings.ToLower(path) content, err := ioutil.ReadFile(path) if err != nil { return } err = yaml.Unmarshal(content, &o.ExampleConfig) if err != nil { panic(fmt.Sprintf("Could not Unmarshal ExampleConfig yaml: %s\n", content)) } }
[ "func", "(", "o", "*", "Operation", ")", "initExample", "(", "config", "*", "Config", ")", "{", "path", ":=", "o", ".", "Type", ".", "Name", "+", "\"", "\"", "\n", "path", "=", "filepath", ".", "Join", "(", "*", "ConfigDir", ",", "config", ".", "ExampleLocation", ",", "o", ".", "Definition", ".", "Name", ",", "path", ")", "\n", "path", "=", "strings", ".", "Replace", "(", "path", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "path", "=", "strings", ".", "ToLower", "(", "path", ")", "\n", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "yaml", ".", "Unmarshal", "(", "content", ",", "&", "o", ".", "ExampleConfig", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "content", ")", ")", "\n", "}", "\n", "}" ]
// initExample reads the example config for an operation
[ "initExample", "reads", "the", "example", "config", "for", "an", "operation" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L174-L187
train
kubernetes-incubator/reference-docs
gen-kubectldocs/generators/read_cmd.go
NewOptions
func NewOptions(flags *pflag.FlagSet) Options { result := Options{} flags.VisitAll(func(flag *pflag.Flag) { opt := &Option{ Name: flag.Name, Shorthand: flag.Shorthand, DefaultValue: flag.DefValue, Usage: flag.Usage, } result = append(result, opt) }) return result }
go
func NewOptions(flags *pflag.FlagSet) Options { result := Options{} flags.VisitAll(func(flag *pflag.Flag) { opt := &Option{ Name: flag.Name, Shorthand: flag.Shorthand, DefaultValue: flag.DefValue, Usage: flag.Usage, } result = append(result, opt) }) return result }
[ "func", "NewOptions", "(", "flags", "*", "pflag", ".", "FlagSet", ")", "Options", "{", "result", ":=", "Options", "{", "}", "\n", "flags", ".", "VisitAll", "(", "func", "(", "flag", "*", "pflag", ".", "Flag", ")", "{", "opt", ":=", "&", "Option", "{", "Name", ":", "flag", ".", "Name", ",", "Shorthand", ":", "flag", ".", "Shorthand", ",", "DefaultValue", ":", "flag", ".", "DefValue", ",", "Usage", ":", "flag", ".", "Usage", ",", "}", "\n", "result", "=", "append", "(", "result", ",", "opt", ")", "\n", "}", ")", "\n", "return", "result", "\n", "}" ]
// Parse the Options
[ "Parse", "the", "Options" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-kubectldocs/generators/read_cmd.go#L66-L78
train
kubernetes-incubator/reference-docs
gen-kubectldocs/generators/read_cmd.go
NewSubCommands
func NewSubCommands(c *cobra.Command, path string) Commands { subCommands := Commands{NewCommand(c, path+c.Name())} for _, subCommand := range c.Commands() { subCommands = append(subCommands, NewSubCommands(subCommand, path+c.Name()+" ")...) } return subCommands }
go
func NewSubCommands(c *cobra.Command, path string) Commands { subCommands := Commands{NewCommand(c, path+c.Name())} for _, subCommand := range c.Commands() { subCommands = append(subCommands, NewSubCommands(subCommand, path+c.Name()+" ")...) } return subCommands }
[ "func", "NewSubCommands", "(", "c", "*", "cobra", ".", "Command", ",", "path", "string", ")", "Commands", "{", "subCommands", ":=", "Commands", "{", "NewCommand", "(", "c", ",", "path", "+", "c", ".", "Name", "(", ")", ")", "}", "\n", "for", "_", ",", "subCommand", ":=", "range", "c", ".", "Commands", "(", ")", "{", "subCommands", "=", "append", "(", "subCommands", ",", "NewSubCommands", "(", "subCommand", ",", "path", "+", "c", ".", "Name", "(", ")", "+", "\"", "\"", ")", "...", ")", "\n", "}", "\n", "return", "subCommands", "\n", "}" ]
// Parse the Commands
[ "Parse", "the", "Commands" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-kubectldocs/generators/read_cmd.go#L81-L87
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/open_api.go
LoadOpenApiSpec
func LoadOpenApiSpec() []*loads.Document { dir := filepath.Join(*ConfigDir, "openapi-spec/") docs := []*loads.Document{} err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { ext := filepath.Ext(path) if ext != ".json" { return nil } var d *loads.Document d, err = loads.JSONSpec(path) if err != nil { return fmt.Errorf("Could not load json file %s as api-spec: %v\n", path, err) } docs = append(docs, d) return nil }) if err != nil { os.Stderr.WriteString(fmt.Sprintf("%v", err)) os.Exit(1) } return docs }
go
func LoadOpenApiSpec() []*loads.Document { dir := filepath.Join(*ConfigDir, "openapi-spec/") docs := []*loads.Document{} err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { ext := filepath.Ext(path) if ext != ".json" { return nil } var d *loads.Document d, err = loads.JSONSpec(path) if err != nil { return fmt.Errorf("Could not load json file %s as api-spec: %v\n", path, err) } docs = append(docs, d) return nil }) if err != nil { os.Stderr.WriteString(fmt.Sprintf("%v", err)) os.Exit(1) } return docs }
[ "func", "LoadOpenApiSpec", "(", ")", "[", "]", "*", "loads", ".", "Document", "{", "dir", ":=", "filepath", ".", "Join", "(", "*", "ConfigDir", ",", "\"", "\"", ")", "\n", "docs", ":=", "[", "]", "*", "loads", ".", "Document", "{", "}", "\n", "err", ":=", "filepath", ".", "Walk", "(", "dir", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "ext", ":=", "filepath", ".", "Ext", "(", "path", ")", "\n", "if", "ext", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "var", "d", "*", "loads", ".", "Document", "\n", "d", ",", "err", "=", "loads", ".", "JSONSpec", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "docs", "=", "append", "(", "docs", ",", "d", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Stderr", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "return", "docs", "\n", "}" ]
// Loads all of the open-api documents
[ "Loads", "all", "of", "the", "open", "-", "api", "documents" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/open_api.go#L37-L58
train
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/open_api.go
buildGroupMap
func buildGroupMap(specs []*loads.Document) map[string]string { mapping := map[string]string{} mapping["apiregistration"] = "apiregistration.k8s.io" mapping["apiextensions"] = "apiextensions.k8s.io" mapping["certificates"] = "certificates.k8s.io" mapping["meta"] = "meta" mapping["core"] = "core" mapping["extensions"] = "extensions" for _, spec := range specs { for name, spec := range spec.Spec().Definitions { group, _, _ := GuessGVK(name) if _, found := mapping[group]; found { continue } // special groups where group name from extension is empty! if group == "meta" || group == "core" { continue } // full group not exposed as x-kubernetes- openapi extensions // from kube-aggregator project or apiextensions-apiserver project if group == "apiregistration" || group == "apiextensions" { continue } if extension, found := spec.Extensions[typeKey]; found { gvks, ok := extension.([]interface{}) if ok { for _, item := range gvks { gvk, ok := item.(map[string]interface{}) if ok { mapping[group] = gvk["group"].(string) break } } } } } } return mapping }
go
func buildGroupMap(specs []*loads.Document) map[string]string { mapping := map[string]string{} mapping["apiregistration"] = "apiregistration.k8s.io" mapping["apiextensions"] = "apiextensions.k8s.io" mapping["certificates"] = "certificates.k8s.io" mapping["meta"] = "meta" mapping["core"] = "core" mapping["extensions"] = "extensions" for _, spec := range specs { for name, spec := range spec.Spec().Definitions { group, _, _ := GuessGVK(name) if _, found := mapping[group]; found { continue } // special groups where group name from extension is empty! if group == "meta" || group == "core" { continue } // full group not exposed as x-kubernetes- openapi extensions // from kube-aggregator project or apiextensions-apiserver project if group == "apiregistration" || group == "apiextensions" { continue } if extension, found := spec.Extensions[typeKey]; found { gvks, ok := extension.([]interface{}) if ok { for _, item := range gvks { gvk, ok := item.(map[string]interface{}) if ok { mapping[group] = gvk["group"].(string) break } } } } } } return mapping }
[ "func", "buildGroupMap", "(", "specs", "[", "]", "*", "loads", ".", "Document", ")", "map", "[", "string", "]", "string", "{", "mapping", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n\n", "for", "_", ",", "spec", ":=", "range", "specs", "{", "for", "name", ",", "spec", ":=", "range", "spec", ".", "Spec", "(", ")", ".", "Definitions", "{", "group", ",", "_", ",", "_", ":=", "GuessGVK", "(", "name", ")", "\n", "if", "_", ",", "found", ":=", "mapping", "[", "group", "]", ";", "found", "{", "continue", "\n", "}", "\n", "// special groups where group name from extension is empty!", "if", "group", "==", "\"", "\"", "||", "group", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "// full group not exposed as x-kubernetes- openapi extensions", "// from kube-aggregator project or apiextensions-apiserver project", "if", "group", "==", "\"", "\"", "||", "group", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "if", "extension", ",", "found", ":=", "spec", ".", "Extensions", "[", "typeKey", "]", ";", "found", "{", "gvks", ",", "ok", ":=", "extension", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "ok", "{", "for", "_", ",", "item", ":=", "range", "gvks", "{", "gvk", ",", "ok", ":=", "item", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "ok", "{", "mapping", "[", "group", "]", "=", "gvk", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "mapping", "\n", "}" ]
// return the map from short group name to full group name
[ "return", "the", "map", "from", "short", "group", "name", "to", "full", "group", "name" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/open_api.go#L61-L102
train
docker/go-connections
tlsconfig/certpool_go17.go
SystemCertPool
func SystemCertPool() (*x509.CertPool, error) { certpool, err := x509.SystemCertPool() if err != nil && runtime.GOOS == "windows" { return x509.NewCertPool(), nil } return certpool, err }
go
func SystemCertPool() (*x509.CertPool, error) { certpool, err := x509.SystemCertPool() if err != nil && runtime.GOOS == "windows" { return x509.NewCertPool(), nil } return certpool, err }
[ "func", "SystemCertPool", "(", ")", "(", "*", "x509", ".", "CertPool", ",", "error", ")", "{", "certpool", ",", "err", ":=", "x509", ".", "SystemCertPool", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "return", "x509", ".", "NewCertPool", "(", ")", ",", "nil", "\n", "}", "\n", "return", "certpool", ",", "err", "\n", "}" ]
// SystemCertPool returns a copy of the system cert pool, // returns an error if failed to load or empty pool on windows.
[ "SystemCertPool", "returns", "a", "copy", "of", "the", "system", "cert", "pool", "returns", "an", "error", "if", "failed", "to", "load", "or", "empty", "pool", "on", "windows", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/certpool_go17.go#L12-L18
train
docker/go-connections
sockets/sockets_unix.go
DialPipe
func DialPipe(_ string, _ time.Duration) (net.Conn, error) { return nil, syscall.EAFNOSUPPORT }
go
func DialPipe(_ string, _ time.Duration) (net.Conn, error) { return nil, syscall.EAFNOSUPPORT }
[ "func", "DialPipe", "(", "_", "string", ",", "_", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "nil", ",", "syscall", ".", "EAFNOSUPPORT", "\n", "}" ]
// DialPipe connects to a Windows named pipe. // This is not supported on other OSes.
[ "DialPipe", "connects", "to", "a", "Windows", "named", "pipe", ".", "This", "is", "not", "supported", "on", "other", "OSes", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/sockets_unix.go#L36-L38
train
docker/go-connections
proxy/udp_proxy.go
Run
func (proxy *UDPProxy) Run() { readBuf := make([]byte, UDPBufSize) for { read, from, err := proxy.listener.ReadFromUDP(readBuf) if err != nil { // NOTE: Apparently ReadFrom doesn't return // ECONNREFUSED like Read do (see comment in // UDPProxy.replyLoop) if !isClosedError(err) { proxy.Logger.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) } break } fromKey := newConnTrackKey(from) proxy.connTrackLock.Lock() proxyConn, hit := proxy.connTrackTable[*fromKey] if !hit { proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) proxy.connTrackLock.Unlock() continue } proxy.connTrackTable[*fromKey] = proxyConn go proxy.replyLoop(proxyConn, from, fromKey) } proxy.connTrackLock.Unlock() for i := 0; i != read; { written, err := proxyConn.Write(readBuf[i:read]) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) break } i += written } } }
go
func (proxy *UDPProxy) Run() { readBuf := make([]byte, UDPBufSize) for { read, from, err := proxy.listener.ReadFromUDP(readBuf) if err != nil { // NOTE: Apparently ReadFrom doesn't return // ECONNREFUSED like Read do (see comment in // UDPProxy.replyLoop) if !isClosedError(err) { proxy.Logger.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) } break } fromKey := newConnTrackKey(from) proxy.connTrackLock.Lock() proxyConn, hit := proxy.connTrackTable[*fromKey] if !hit { proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) proxy.connTrackLock.Unlock() continue } proxy.connTrackTable[*fromKey] = proxyConn go proxy.replyLoop(proxyConn, from, fromKey) } proxy.connTrackLock.Unlock() for i := 0; i != read; { written, err := proxyConn.Write(readBuf[i:read]) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) break } i += written } } }
[ "func", "(", "proxy", "*", "UDPProxy", ")", "Run", "(", ")", "{", "readBuf", ":=", "make", "(", "[", "]", "byte", ",", "UDPBufSize", ")", "\n", "for", "{", "read", ",", "from", ",", "err", ":=", "proxy", ".", "listener", ".", "ReadFromUDP", "(", "readBuf", ")", "\n", "if", "err", "!=", "nil", "{", "// NOTE: Apparently ReadFrom doesn't return", "// ECONNREFUSED like Read do (see comment in", "// UDPProxy.replyLoop)", "if", "!", "isClosedError", "(", "err", ")", "{", "proxy", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "proxy", ".", "frontendAddr", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n\n", "fromKey", ":=", "newConnTrackKey", "(", "from", ")", "\n", "proxy", ".", "connTrackLock", ".", "Lock", "(", ")", "\n", "proxyConn", ",", "hit", ":=", "proxy", ".", "connTrackTable", "[", "*", "fromKey", "]", "\n", "if", "!", "hit", "{", "proxyConn", ",", "err", "=", "net", ".", "DialUDP", "(", "\"", "\"", ",", "nil", ",", "proxy", ".", "backendAddr", ")", "\n", "if", "err", "!=", "nil", "{", "proxy", ".", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "proxy", ".", "connTrackLock", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "\n", "proxy", ".", "connTrackTable", "[", "*", "fromKey", "]", "=", "proxyConn", "\n", "go", "proxy", ".", "replyLoop", "(", "proxyConn", ",", "from", ",", "fromKey", ")", "\n", "}", "\n", "proxy", ".", "connTrackLock", ".", "Unlock", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "!=", "read", ";", "{", "written", ",", "err", ":=", "proxyConn", ".", "Write", "(", "readBuf", "[", "i", ":", "read", "]", ")", "\n", "if", "err", "!=", "nil", "{", "proxy", ".", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "break", "\n", "}", "\n", "i", "+=", "written", "\n", "}", "\n", "}", "\n", "}" ]
// Run starts forwarding the traffic using UDP.
[ "Run", "starts", "forwarding", "the", "traffic", "using", "UDP", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/proxy/udp_proxy.go#L113-L150
train
docker/go-connections
nat/nat.go
NewPort
func NewPort(proto, port string) (Port, error) { // Check for parsing issues on "port" now so we can avoid having // to check it later on. portStartInt, portEndInt, err := ParsePortRangeToInt(port) if err != nil { return "", err } if portStartInt == portEndInt { return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil } return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil }
go
func NewPort(proto, port string) (Port, error) { // Check for parsing issues on "port" now so we can avoid having // to check it later on. portStartInt, portEndInt, err := ParsePortRangeToInt(port) if err != nil { return "", err } if portStartInt == portEndInt { return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil } return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil }
[ "func", "NewPort", "(", "proto", ",", "port", "string", ")", "(", "Port", ",", "error", ")", "{", "// Check for parsing issues on \"port\" now so we can avoid having", "// to check it later on.", "portStartInt", ",", "portEndInt", ",", "err", ":=", "ParsePortRangeToInt", "(", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "portStartInt", "==", "portEndInt", "{", "return", "Port", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "portStartInt", ",", "proto", ")", ")", ",", "nil", "\n", "}", "\n", "return", "Port", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "portStartInt", ",", "portEndInt", ",", "proto", ")", ")", ",", "nil", "\n", "}" ]
// NewPort creates a new instance of a Port given a protocol and port number or port range
[ "NewPort", "creates", "a", "new", "instance", "of", "a", "Port", "given", "a", "protocol", "and", "port", "number", "or", "port", "range" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L34-L47
train
docker/go-connections
nat/nat.go
ParsePort
func ParsePort(rawPort string) (int, error) { if len(rawPort) == 0 { return 0, nil } port, err := strconv.ParseUint(rawPort, 10, 16) if err != nil { return 0, err } return int(port), nil }
go
func ParsePort(rawPort string) (int, error) { if len(rawPort) == 0 { return 0, nil } port, err := strconv.ParseUint(rawPort, 10, 16) if err != nil { return 0, err } return int(port), nil }
[ "func", "ParsePort", "(", "rawPort", "string", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "rawPort", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "port", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "rawPort", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "int", "(", "port", ")", ",", "nil", "\n", "}" ]
// ParsePort parses the port number string and returns an int
[ "ParsePort", "parses", "the", "port", "number", "string", "and", "returns", "an", "int" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L50-L59
train
docker/go-connections
nat/nat.go
Proto
func (p Port) Proto() string { proto, _ := SplitProtoPort(string(p)) return proto }
go
func (p Port) Proto() string { proto, _ := SplitProtoPort(string(p)) return proto }
[ "func", "(", "p", "Port", ")", "Proto", "(", ")", "string", "{", "proto", ",", "_", ":=", "SplitProtoPort", "(", "string", "(", "p", ")", ")", "\n", "return", "proto", "\n", "}" ]
// Proto returns the protocol of a Port
[ "Proto", "returns", "the", "protocol", "of", "a", "Port" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L74-L77
train
docker/go-connections
nat/nat.go
Port
func (p Port) Port() string { _, port := SplitProtoPort(string(p)) return port }
go
func (p Port) Port() string { _, port := SplitProtoPort(string(p)) return port }
[ "func", "(", "p", "Port", ")", "Port", "(", ")", "string", "{", "_", ",", "port", ":=", "SplitProtoPort", "(", "string", "(", "p", ")", ")", "\n", "return", "port", "\n", "}" ]
// Port returns the port number of a Port
[ "Port", "returns", "the", "port", "number", "of", "a", "Port" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L80-L83
train
docker/go-connections
nat/nat.go
Int
func (p Port) Int() int { portStr := p.Port() // We don't need to check for an error because we're going to // assume that any error would have been found, and reported, in NewPort() port, _ := ParsePort(portStr) return port }
go
func (p Port) Int() int { portStr := p.Port() // We don't need to check for an error because we're going to // assume that any error would have been found, and reported, in NewPort() port, _ := ParsePort(portStr) return port }
[ "func", "(", "p", "Port", ")", "Int", "(", ")", "int", "{", "portStr", ":=", "p", ".", "Port", "(", ")", "\n", "// We don't need to check for an error because we're going to", "// assume that any error would have been found, and reported, in NewPort()", "port", ",", "_", ":=", "ParsePort", "(", "portStr", ")", "\n", "return", "port", "\n", "}" ]
// Int returns the port number of a Port as an int
[ "Int", "returns", "the", "port", "number", "of", "a", "Port", "as", "an", "int" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L86-L92
train
docker/go-connections
nat/nat.go
ParsePortSpec
func ParsePortSpec(rawPort string) ([]PortMapping, error) { var proto string rawIP, hostPort, containerPort := splitParts(rawPort) proto, containerPort = SplitProtoPort(containerPort) // Strip [] from IPV6 addresses ip, _, err := net.SplitHostPort(rawIP + ":") if err != nil { return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) } if ip != "" && net.ParseIP(ip) == nil { return nil, fmt.Errorf("Invalid ip address: %s", ip) } if containerPort == "" { return nil, fmt.Errorf("No port specified: %s<empty>", rawPort) } startPort, endPort, err := ParsePortRange(containerPort) if err != nil { return nil, fmt.Errorf("Invalid containerPort: %s", containerPort) } var startHostPort, endHostPort uint64 = 0, 0 if len(hostPort) > 0 { startHostPort, endHostPort, err = ParsePortRange(hostPort) if err != nil { return nil, fmt.Errorf("Invalid hostPort: %s", hostPort) } } if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { // Allow host port range iff containerPort is not a range. // In this case, use the host port range as the dynamic // host port range to allocate into. if endPort != startPort { return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) } } if !validateProto(strings.ToLower(proto)) { return nil, fmt.Errorf("Invalid proto: %s", proto) } ports := []PortMapping{} for i := uint64(0); i <= (endPort - startPort); i++ { containerPort = strconv.FormatUint(startPort+i, 10) if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } // Set hostPort to a range only if there is a single container port // and a dynamic host port. if startPort == endPort && startHostPort != endHostPort { hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) } port, err := NewPort(strings.ToLower(proto), containerPort) if err != nil { return nil, err } binding := PortBinding{ HostIP: ip, HostPort: hostPort, } ports = append(ports, PortMapping{Port: port, Binding: binding}) } return ports, nil }
go
func ParsePortSpec(rawPort string) ([]PortMapping, error) { var proto string rawIP, hostPort, containerPort := splitParts(rawPort) proto, containerPort = SplitProtoPort(containerPort) // Strip [] from IPV6 addresses ip, _, err := net.SplitHostPort(rawIP + ":") if err != nil { return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) } if ip != "" && net.ParseIP(ip) == nil { return nil, fmt.Errorf("Invalid ip address: %s", ip) } if containerPort == "" { return nil, fmt.Errorf("No port specified: %s<empty>", rawPort) } startPort, endPort, err := ParsePortRange(containerPort) if err != nil { return nil, fmt.Errorf("Invalid containerPort: %s", containerPort) } var startHostPort, endHostPort uint64 = 0, 0 if len(hostPort) > 0 { startHostPort, endHostPort, err = ParsePortRange(hostPort) if err != nil { return nil, fmt.Errorf("Invalid hostPort: %s", hostPort) } } if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { // Allow host port range iff containerPort is not a range. // In this case, use the host port range as the dynamic // host port range to allocate into. if endPort != startPort { return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) } } if !validateProto(strings.ToLower(proto)) { return nil, fmt.Errorf("Invalid proto: %s", proto) } ports := []PortMapping{} for i := uint64(0); i <= (endPort - startPort); i++ { containerPort = strconv.FormatUint(startPort+i, 10) if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } // Set hostPort to a range only if there is a single container port // and a dynamic host port. if startPort == endPort && startHostPort != endHostPort { hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) } port, err := NewPort(strings.ToLower(proto), containerPort) if err != nil { return nil, err } binding := PortBinding{ HostIP: ip, HostPort: hostPort, } ports = append(ports, PortMapping{Port: port, Binding: binding}) } return ports, nil }
[ "func", "ParsePortSpec", "(", "rawPort", "string", ")", "(", "[", "]", "PortMapping", ",", "error", ")", "{", "var", "proto", "string", "\n", "rawIP", ",", "hostPort", ",", "containerPort", ":=", "splitParts", "(", "rawPort", ")", "\n", "proto", ",", "containerPort", "=", "SplitProtoPort", "(", "containerPort", ")", "\n\n", "// Strip [] from IPV6 addresses", "ip", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "rawIP", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawIP", ",", "err", ")", "\n", "}", "\n", "if", "ip", "!=", "\"", "\"", "&&", "net", ".", "ParseIP", "(", "ip", ")", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ip", ")", "\n", "}", "\n", "if", "containerPort", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawPort", ")", "\n", "}", "\n\n", "startPort", ",", "endPort", ",", "err", ":=", "ParsePortRange", "(", "containerPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "containerPort", ")", "\n", "}", "\n\n", "var", "startHostPort", ",", "endHostPort", "uint64", "=", "0", ",", "0", "\n", "if", "len", "(", "hostPort", ")", ">", "0", "{", "startHostPort", ",", "endHostPort", ",", "err", "=", "ParsePortRange", "(", "hostPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hostPort", ")", "\n", "}", "\n", "}", "\n\n", "if", "hostPort", "!=", "\"", "\"", "&&", "(", "endPort", "-", "startPort", ")", "!=", "(", "endHostPort", "-", "startHostPort", ")", "{", "// Allow host port range iff containerPort is not a range.", "// In this case, use the host port range as the dynamic", "// host port range to allocate into.", "if", "endPort", "!=", "startPort", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "containerPort", ",", "hostPort", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "validateProto", "(", "strings", ".", "ToLower", "(", "proto", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "proto", ")", "\n", "}", "\n\n", "ports", ":=", "[", "]", "PortMapping", "{", "}", "\n", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<=", "(", "endPort", "-", "startPort", ")", ";", "i", "++", "{", "containerPort", "=", "strconv", ".", "FormatUint", "(", "startPort", "+", "i", ",", "10", ")", "\n", "if", "len", "(", "hostPort", ")", ">", "0", "{", "hostPort", "=", "strconv", ".", "FormatUint", "(", "startHostPort", "+", "i", ",", "10", ")", "\n", "}", "\n", "// Set hostPort to a range only if there is a single container port", "// and a dynamic host port.", "if", "startPort", "==", "endPort", "&&", "startHostPort", "!=", "endHostPort", "{", "hostPort", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hostPort", ",", "strconv", ".", "FormatUint", "(", "endHostPort", ",", "10", ")", ")", "\n", "}", "\n", "port", ",", "err", ":=", "NewPort", "(", "strings", ".", "ToLower", "(", "proto", ")", ",", "containerPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "binding", ":=", "PortBinding", "{", "HostIP", ":", "ip", ",", "HostPort", ":", "hostPort", ",", "}", "\n", "ports", "=", "append", "(", "ports", ",", "PortMapping", "{", "Port", ":", "port", ",", "Binding", ":", "binding", "}", ")", "\n", "}", "\n", "return", "ports", ",", "nil", "\n", "}" ]
// ParsePortSpec parses a port specification string into a slice of PortMappings
[ "ParsePortSpec", "parses", "a", "port", "specification", "string", "into", "a", "slice", "of", "PortMappings" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L176-L242
train
docker/go-connections
tlsconfig/config.go
ServerDefault
func ServerDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Avoid fallback by default to SSL protocols < TLS1.2 MinVersion: tls.VersionTLS12, PreferServerCipherSuites: true, CipherSuites: DefaultServerAcceptedCiphers, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
go
func ServerDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Avoid fallback by default to SSL protocols < TLS1.2 MinVersion: tls.VersionTLS12, PreferServerCipherSuites: true, CipherSuites: DefaultServerAcceptedCiphers, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
[ "func", "ServerDefault", "(", "ops", "...", "func", "(", "*", "tls", ".", "Config", ")", ")", "*", "tls", ".", "Config", "{", "tlsconfig", ":=", "&", "tls", ".", "Config", "{", "// Avoid fallback by default to SSL protocols < TLS1.2", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "PreferServerCipherSuites", ":", "true", ",", "CipherSuites", ":", "DefaultServerAcceptedCiphers", ",", "}", "\n\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "op", "(", "tlsconfig", ")", "\n", "}", "\n\n", "return", "tlsconfig", "\n", "}" ]
// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
[ "ServerDefault", "returns", "a", "secure", "-", "enough", "TLS", "configuration", "for", "the", "server", "TLS", "configuration", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L66-L79
train
docker/go-connections
tlsconfig/config.go
ClientDefault
func ClientDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Prefer TLS1.2 as the client minimum MinVersion: tls.VersionTLS12, CipherSuites: clientCipherSuites, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
go
func ClientDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Prefer TLS1.2 as the client minimum MinVersion: tls.VersionTLS12, CipherSuites: clientCipherSuites, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
[ "func", "ClientDefault", "(", "ops", "...", "func", "(", "*", "tls", ".", "Config", ")", ")", "*", "tls", ".", "Config", "{", "tlsconfig", ":=", "&", "tls", ".", "Config", "{", "// Prefer TLS1.2 as the client minimum", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "CipherSuites", ":", "clientCipherSuites", ",", "}", "\n\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "op", "(", "tlsconfig", ")", "\n", "}", "\n\n", "return", "tlsconfig", "\n", "}" ]
// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration.
[ "ClientDefault", "returns", "a", "secure", "-", "enough", "TLS", "configuration", "for", "the", "client", "TLS", "configuration", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L82-L94
train
docker/go-connections
tlsconfig/config.go
certPool
func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { // If we should verify the server, we need to load a trusted ca var ( certPool *x509.CertPool err error ) if exclusivePool { certPool = x509.NewCertPool() } else { certPool, err = SystemCertPool() if err != nil { return nil, fmt.Errorf("failed to read system certificates: %v", err) } } pem, err := ioutil.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) } if !certPool.AppendCertsFromPEM(pem) { return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) } return certPool, nil }
go
func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { // If we should verify the server, we need to load a trusted ca var ( certPool *x509.CertPool err error ) if exclusivePool { certPool = x509.NewCertPool() } else { certPool, err = SystemCertPool() if err != nil { return nil, fmt.Errorf("failed to read system certificates: %v", err) } } pem, err := ioutil.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) } if !certPool.AppendCertsFromPEM(pem) { return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) } return certPool, nil }
[ "func", "certPool", "(", "caFile", "string", ",", "exclusivePool", "bool", ")", "(", "*", "x509", ".", "CertPool", ",", "error", ")", "{", "// If we should verify the server, we need to load a trusted ca", "var", "(", "certPool", "*", "x509", ".", "CertPool", "\n", "err", "error", "\n", ")", "\n", "if", "exclusivePool", "{", "certPool", "=", "x509", ".", "NewCertPool", "(", ")", "\n", "}", "else", "{", "certPool", ",", "err", "=", "SystemCertPool", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "pem", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "caFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caFile", ",", "err", ")", "\n", "}", "\n", "if", "!", "certPool", ".", "AppendCertsFromPEM", "(", "pem", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caFile", ")", "\n", "}", "\n", "return", "certPool", ",", "nil", "\n", "}" ]
// certPool returns an X.509 certificate pool from `caFile`, the certificate file.
[ "certPool", "returns", "an", "X", ".", "509", "certificate", "pool", "from", "caFile", "the", "certificate", "file", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L97-L119
train
docker/go-connections
tlsconfig/config.go
adjustMinVersion
func adjustMinVersion(options Options, config *tls.Config) error { if options.MinVersion > 0 { if !isValidMinVersion(options.MinVersion) { return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion) } if options.MinVersion < config.MinVersion { return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) } config.MinVersion = options.MinVersion } return nil }
go
func adjustMinVersion(options Options, config *tls.Config) error { if options.MinVersion > 0 { if !isValidMinVersion(options.MinVersion) { return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion) } if options.MinVersion < config.MinVersion { return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) } config.MinVersion = options.MinVersion } return nil }
[ "func", "adjustMinVersion", "(", "options", "Options", ",", "config", "*", "tls", ".", "Config", ")", "error", "{", "if", "options", ".", "MinVersion", ">", "0", "{", "if", "!", "isValidMinVersion", "(", "options", ".", "MinVersion", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "MinVersion", ")", "\n", "}", "\n", "if", "options", ".", "MinVersion", "<", "config", ".", "MinVersion", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "MinVersion", ")", "\n", "}", "\n", "config", ".", "MinVersion", "=", "options", ".", "MinVersion", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// adjustMinVersion sets the MinVersion on `config`, the input configuration. // It assumes the current MinVersion on the `config` is the lowest allowed.
[ "adjustMinVersion", "sets", "the", "MinVersion", "on", "config", "the", "input", "configuration", ".", "It", "assumes", "the", "current", "MinVersion", "on", "the", "config", "is", "the", "lowest", "allowed", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L129-L141
train
docker/go-connections
tlsconfig/config.go
getPrivateKey
func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { // this section makes some small changes to code from notary/tuf/utils/x509.go pemBlock, _ := pem.Decode(keyBytes) if pemBlock == nil { return nil, fmt.Errorf("no valid private key found") } var err error if x509.IsEncryptedPEMBlock(pemBlock) { keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) if err != nil { return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") } keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) } return keyBytes, nil }
go
func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { // this section makes some small changes to code from notary/tuf/utils/x509.go pemBlock, _ := pem.Decode(keyBytes) if pemBlock == nil { return nil, fmt.Errorf("no valid private key found") } var err error if x509.IsEncryptedPEMBlock(pemBlock) { keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) if err != nil { return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") } keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) } return keyBytes, nil }
[ "func", "getPrivateKey", "(", "keyBytes", "[", "]", "byte", ",", "passphrase", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// this section makes some small changes to code from notary/tuf/utils/x509.go", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "keyBytes", ")", "\n", "if", "pemBlock", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "if", "x509", ".", "IsEncryptedPEMBlock", "(", "pemBlock", ")", "{", "keyBytes", ",", "err", "=", "x509", ".", "DecryptPEMBlock", "(", "pemBlock", ",", "[", "]", "byte", "(", "passphrase", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "keyBytes", "=", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "pemBlock", ".", "Type", ",", "Bytes", ":", "keyBytes", "}", ")", "\n", "}", "\n\n", "return", "keyBytes", ",", "nil", "\n", "}" ]
// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format. // If the private key is encrypted, 'passphrase' is used to decrypted the // private key.
[ "getPrivateKey", "returns", "the", "private", "key", "in", "keyBytes", "in", "PEM", "-", "encoded", "format", ".", "If", "the", "private", "key", "is", "encrypted", "passphrase", "is", "used", "to", "decrypted", "the", "private", "key", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L152-L169
train
docker/go-connections
tlsconfig/config.go
getCert
func getCert(options Options) ([]tls.Certificate, error) { if options.CertFile == "" && options.KeyFile == "" { return nil, nil } errMessage := "Could not load X509 key pair" cert, err := ioutil.ReadFile(options.CertFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err := ioutil.ReadFile(options.KeyFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) if err != nil { return nil, errors.Wrap(err, errMessage) } tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) if err != nil { return nil, errors.Wrap(err, errMessage) } return []tls.Certificate{tlsCert}, nil }
go
func getCert(options Options) ([]tls.Certificate, error) { if options.CertFile == "" && options.KeyFile == "" { return nil, nil } errMessage := "Could not load X509 key pair" cert, err := ioutil.ReadFile(options.CertFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err := ioutil.ReadFile(options.KeyFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) if err != nil { return nil, errors.Wrap(err, errMessage) } tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) if err != nil { return nil, errors.Wrap(err, errMessage) } return []tls.Certificate{tlsCert}, nil }
[ "func", "getCert", "(", "options", "Options", ")", "(", "[", "]", "tls", ".", "Certificate", ",", "error", ")", "{", "if", "options", ".", "CertFile", "==", "\"", "\"", "&&", "options", ".", "KeyFile", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "errMessage", ":=", "\"", "\"", "\n\n", "cert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "options", ".", "CertFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "prKeyBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "options", ".", "KeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "prKeyBytes", ",", "err", "=", "getPrivateKey", "(", "prKeyBytes", ",", "options", ".", "Passphrase", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "tlsCert", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "cert", ",", "prKeyBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "return", "[", "]", "tls", ".", "Certificate", "{", "tlsCert", "}", ",", "nil", "\n", "}" ]
// getCert returns a Certificate from the CertFile and KeyFile in 'options', // if the key is encrypted, the Passphrase in 'options' will be used to // decrypt it.
[ "getCert", "returns", "a", "Certificate", "from", "the", "CertFile", "and", "KeyFile", "in", "options", "if", "the", "key", "is", "encrypted", "the", "Passphrase", "in", "options", "will", "be", "used", "to", "decrypt", "it", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L174-L202
train
docker/go-connections
tlsconfig/config.go
Client
func Client(options Options) (*tls.Config, error) { tlsConfig := ClientDefault() tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify if !options.InsecureSkipVerify && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.RootCAs = CAs } tlsCerts, err := getCert(options) if err != nil { return nil, err } tlsConfig.Certificates = tlsCerts if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
go
func Client(options Options) (*tls.Config, error) { tlsConfig := ClientDefault() tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify if !options.InsecureSkipVerify && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.RootCAs = CAs } tlsCerts, err := getCert(options) if err != nil { return nil, err } tlsConfig.Certificates = tlsCerts if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
[ "func", "Client", "(", "options", "Options", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "tlsConfig", ":=", "ClientDefault", "(", ")", "\n", "tlsConfig", ".", "InsecureSkipVerify", "=", "options", ".", "InsecureSkipVerify", "\n", "if", "!", "options", ".", "InsecureSkipVerify", "&&", "options", ".", "CAFile", "!=", "\"", "\"", "{", "CAs", ",", "err", ":=", "certPool", "(", "options", ".", "CAFile", ",", "options", ".", "ExclusiveRootPools", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tlsConfig", ".", "RootCAs", "=", "CAs", "\n", "}", "\n\n", "tlsCerts", ",", "err", ":=", "getCert", "(", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "tlsCerts", "\n\n", "if", "err", ":=", "adjustMinVersion", "(", "options", ",", "tlsConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// Client returns a TLS configuration meant to be used by a client.
[ "Client", "returns", "a", "TLS", "configuration", "meant", "to", "be", "used", "by", "a", "client", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L205-L227
train
docker/go-connections
tlsconfig/config.go
Server
func Server(options Options) (*tls.Config, error) { tlsConfig := ServerDefault() tlsConfig.ClientAuth = options.ClientAuth tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) } return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.ClientCAs = CAs } if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
go
func Server(options Options) (*tls.Config, error) { tlsConfig := ServerDefault() tlsConfig.ClientAuth = options.ClientAuth tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) } return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.ClientCAs = CAs } if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
[ "func", "Server", "(", "options", "Options", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "tlsConfig", ":=", "ServerDefault", "(", ")", "\n", "tlsConfig", ".", "ClientAuth", "=", "options", ".", "ClientAuth", "\n", "tlsCert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "options", ".", "CertFile", ",", "options", ".", "KeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "CertFile", ",", "options", ".", "KeyFile", ",", "err", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "CertFile", ",", "options", ".", "KeyFile", ",", "err", ")", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "tlsCert", "}", "\n", "if", "options", ".", "ClientAuth", ">=", "tls", ".", "VerifyClientCertIfGiven", "&&", "options", ".", "CAFile", "!=", "\"", "\"", "{", "CAs", ",", "err", ":=", "certPool", "(", "options", ".", "CAFile", ",", "options", ".", "ExclusiveRootPools", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tlsConfig", ".", "ClientCAs", "=", "CAs", "\n", "}", "\n\n", "if", "err", ":=", "adjustMinVersion", "(", "options", ",", "tlsConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// Server returns a TLS configuration meant to be used by a server.
[ "Server", "returns", "a", "TLS", "configuration", "meant", "to", "be", "used", "by", "a", "server", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L230-L254
train
docker/go-connections
sockets/unix_socket.go
WithChown
func WithChown(uid, gid int) SockOption { return func(path string) error { if err := os.Chown(path, uid, gid); err != nil { return err } return nil } }
go
func WithChown(uid, gid int) SockOption { return func(path string) error { if err := os.Chown(path, uid, gid); err != nil { return err } return nil } }
[ "func", "WithChown", "(", "uid", ",", "gid", "int", ")", "SockOption", "{", "return", "func", "(", "path", "string", ")", "error", "{", "if", "err", ":=", "os", ".", "Chown", "(", "path", ",", "uid", ",", "gid", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithChown modifies the socket file's uid and gid
[ "WithChown", "modifies", "the", "socket", "file", "s", "uid", "and", "gid" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L61-L68
train
docker/go-connections
sockets/unix_socket.go
WithChmod
func WithChmod(mask os.FileMode) SockOption { return func(path string) error { if err := os.Chmod(path, mask); err != nil { return err } return nil } }
go
func WithChmod(mask os.FileMode) SockOption { return func(path string) error { if err := os.Chmod(path, mask); err != nil { return err } return nil } }
[ "func", "WithChmod", "(", "mask", "os", ".", "FileMode", ")", "SockOption", "{", "return", "func", "(", "path", "string", ")", "error", "{", "if", "err", ":=", "os", ".", "Chmod", "(", "path", ",", "mask", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithChmod modifies socket file's access mode
[ "WithChmod", "modifies", "socket", "file", "s", "access", "mode" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L71-L78
train
docker/go-connections
sockets/unix_socket.go
NewUnixSocketWithOpts
func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } mask := syscall.Umask(0777) defer syscall.Umask(mask) l, err := net.Listen("unix", path) if err != nil { return nil, err } for _, op := range opts { if err := op(path); err != nil { l.Close() return nil, err } } return l, nil }
go
func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } mask := syscall.Umask(0777) defer syscall.Umask(mask) l, err := net.Listen("unix", path) if err != nil { return nil, err } for _, op := range opts { if err := op(path); err != nil { l.Close() return nil, err } } return l, nil }
[ "func", "NewUnixSocketWithOpts", "(", "path", "string", ",", "opts", "...", "SockOption", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "if", "err", ":=", "syscall", ".", "Unlink", "(", "path", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "mask", ":=", "syscall", ".", "Umask", "(", "0777", ")", "\n", "defer", "syscall", ".", "Umask", "(", "mask", ")", "\n\n", "l", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "op", ":=", "range", "opts", "{", "if", "err", ":=", "op", "(", "path", ")", ";", "err", "!=", "nil", "{", "l", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "l", ",", "nil", "\n", "}" ]
// NewUnixSocketWithOpts creates a unix socket with the specified options
[ "NewUnixSocketWithOpts", "creates", "a", "unix", "socket", "with", "the", "specified", "options" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L81-L101
train
docker/go-connections
sockets/unix_socket.go
NewUnixSocket
func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0660)) }
go
func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0660)) }
[ "func", "NewUnixSocket", "(", "path", "string", ",", "gid", "int", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "return", "NewUnixSocketWithOpts", "(", "path", ",", "WithChown", "(", "0", ",", "gid", ")", ",", "WithChmod", "(", "0660", ")", ")", "\n", "}" ]
// NewUnixSocket creates a unix socket with the specified path and group.
[ "NewUnixSocket", "creates", "a", "unix", "socket", "with", "the", "specified", "path", "and", "group", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L104-L106
train
docker/go-connections
sockets/sockets_windows.go
DialPipe
func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { return winio.DialPipe(addr, &timeout) }
go
func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { return winio.DialPipe(addr, &timeout) }
[ "func", "DialPipe", "(", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "winio", ".", "DialPipe", "(", "addr", ",", "&", "timeout", ")", "\n", "}" ]
// DialPipe connects to a Windows named pipe.
[ "DialPipe", "connects", "to", "a", "Windows", "named", "pipe", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/sockets_windows.go#L33-L35
train
ipfs/go-dnslink
dnslink/main.go
printLink
func printLink(domain string) error { link, err := dnslink.Resolve(domain) if err != nil { return err } fmt.Println(link) return nil }
go
func printLink(domain string) error { link, err := dnslink.Resolve(domain) if err != nil { return err } fmt.Println(link) return nil }
[ "func", "printLink", "(", "domain", "string", ")", "error", "{", "link", ",", "err", ":=", "dnslink", ".", "Resolve", "(", "domain", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fmt", ".", "Println", "(", "link", ")", "\n", "return", "nil", "\n", "}" ]
// print a single link
[ "print", "a", "single", "link" ]
47ab53fda3fac2f043084406e6da47232efa91d1
https://github.com/ipfs/go-dnslink/blob/47ab53fda3fac2f043084406e6da47232efa91d1/dnslink/main.go#L57-L64
train
ipfs/go-dnslink
dnslink/main.go
printLinks
func printLinks(domains []string) error { for _, domain := range domains { fmt.Print(domain, ": ") result, err := dnslink.Resolve(domain) if result != "" { fmt.Print(result) } if err != nil { fmt.Print("error: ", err) } fmt.Println() } return nil }
go
func printLinks(domains []string) error { for _, domain := range domains { fmt.Print(domain, ": ") result, err := dnslink.Resolve(domain) if result != "" { fmt.Print(result) } if err != nil { fmt.Print("error: ", err) } fmt.Println() } return nil }
[ "func", "printLinks", "(", "domains", "[", "]", "string", ")", "error", "{", "for", "_", ",", "domain", ":=", "range", "domains", "{", "fmt", ".", "Print", "(", "domain", ",", "\"", "\"", ")", "\n\n", "result", ",", "err", ":=", "dnslink", ".", "Resolve", "(", "domain", ")", "\n", "if", "result", "!=", "\"", "\"", "{", "fmt", ".", "Print", "(", "result", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// print multiple links. // errors printed as output, and do not fail the entire process.
[ "print", "multiple", "links", ".", "errors", "printed", "as", "output", "and", "do", "not", "fail", "the", "entire", "process", "." ]
47ab53fda3fac2f043084406e6da47232efa91d1
https://github.com/ipfs/go-dnslink/blob/47ab53fda3fac2f043084406e6da47232efa91d1/dnslink/main.go#L68-L82
train
ipfs/go-dnslink
dnslink.go
Resolve
func (r *Resolver) Resolve(domain string) (string, error) { return r.ResolveN(domain, DefaultDepthLimit) }
go
func (r *Resolver) Resolve(domain string) (string, error) { return r.ResolveN(domain, DefaultDepthLimit) }
[ "func", "(", "r", "*", "Resolver", ")", "Resolve", "(", "domain", "string", ")", "(", "string", ",", "error", ")", "{", "return", "r", ".", "ResolveN", "(", "domain", ",", "DefaultDepthLimit", ")", "\n", "}" ]
// Resolve resolves the dnslink at a particular domain. It will recursively // keep resolving until reaching the defaultDepth of Resolver. If the depth // is reached, Resolve will return the last value retrieved, and ErrResolveLimit. // If TXT records are found but are not valid dnslink records, Resolve will // return ErrInvalidDnslink. Resolve will check every TXT record returned. // If resolution fails otherwise, Resolve will return ErrResolveFailed
[ "Resolve", "resolves", "the", "dnslink", "at", "a", "particular", "domain", ".", "It", "will", "recursively", "keep", "resolving", "until", "reaching", "the", "defaultDepth", "of", "Resolver", ".", "If", "the", "depth", "is", "reached", "Resolve", "will", "return", "the", "last", "value", "retrieved", "and", "ErrResolveLimit", ".", "If", "TXT", "records", "are", "found", "but", "are", "not", "valid", "dnslink", "records", "Resolve", "will", "return", "ErrInvalidDnslink", ".", "Resolve", "will", "check", "every", "TXT", "record", "returned", ".", "If", "resolution", "fails", "otherwise", "Resolve", "will", "return", "ErrResolveFailed" ]
47ab53fda3fac2f043084406e6da47232efa91d1
https://github.com/ipfs/go-dnslink/blob/47ab53fda3fac2f043084406e6da47232efa91d1/dnslink.go#L142-L144
train
Joker/jade
template.go
ParseFile
func ParseFile(filename string) (string, error) { bs, err := ioutil.ReadFile(filename) if err != nil { return "", err } return Parse(filepath.Base(filename), bs) }
go
func ParseFile(filename string) (string, error) { bs, err := ioutil.ReadFile(filename) if err != nil { return "", err } return Parse(filepath.Base(filename), bs) }
[ "func", "ParseFile", "(", "filename", "string", ")", "(", "string", ",", "error", ")", "{", "bs", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "Parse", "(", "filepath", ".", "Base", "(", "filename", ")", ",", "bs", ")", "\n", "}" ]
// ParseFile parse the jade template file in given filename
[ "ParseFile", "parse", "the", "jade", "template", "file", "in", "given", "filename" ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/template.go#L48-L54
train
Joker/jade
jade_node.go
filterString
func filterString(in string) string { var ( rs = []rune(in) flag, prev rune psn int ) for k, r := range rs { // fmt.Println(string(r), " ", r) switch r { case '"': if flag == '\'' && prev != '\\' { rs[k] = 0 // bookmark for replace } if flag == 0 { flag = '"' psn = k } else if r == flag && prev != '\\' { flag = 0 } case '\'': if flag == 0 { flag = '\'' psn = k } else if r == flag && prev != '\\' { // if k-(psn+1) != 1 { rs[psn] = '"' rs[k] = '"' // } flag = 0 } case '`': if flag == 0 { flag = '`' psn = k } else if r == flag { flag = 0 } } prev = r } filterPlus(rs) filterJsEsc(rs) out := strings.Replace(string(rs), string(rune(0)), `\"`, -1) out = strings.Replace(out, string(rune(1)), ``, -1) out = strings.Replace(out, string([]rune{2, 2}), "`+", -1) out = strings.Replace(out, string(rune(3)), "+`", -1) return out }
go
func filterString(in string) string { var ( rs = []rune(in) flag, prev rune psn int ) for k, r := range rs { // fmt.Println(string(r), " ", r) switch r { case '"': if flag == '\'' && prev != '\\' { rs[k] = 0 // bookmark for replace } if flag == 0 { flag = '"' psn = k } else if r == flag && prev != '\\' { flag = 0 } case '\'': if flag == 0 { flag = '\'' psn = k } else if r == flag && prev != '\\' { // if k-(psn+1) != 1 { rs[psn] = '"' rs[k] = '"' // } flag = 0 } case '`': if flag == 0 { flag = '`' psn = k } else if r == flag { flag = 0 } } prev = r } filterPlus(rs) filterJsEsc(rs) out := strings.Replace(string(rs), string(rune(0)), `\"`, -1) out = strings.Replace(out, string(rune(1)), ``, -1) out = strings.Replace(out, string([]rune{2, 2}), "`+", -1) out = strings.Replace(out, string(rune(3)), "+`", -1) return out }
[ "func", "filterString", "(", "in", "string", ")", "string", "{", "var", "(", "rs", "=", "[", "]", "rune", "(", "in", ")", "\n", "flag", ",", "prev", "rune", "\n", "psn", "int", "\n", ")", "\n", "for", "k", ",", "r", ":=", "range", "rs", "{", "// fmt.Println(string(r), \" \", r)", "switch", "r", "{", "case", "'\"'", ":", "if", "flag", "==", "'\\''", "&&", "prev", "!=", "'\\\\'", "{", "rs", "[", "k", "]", "=", "0", "// bookmark for replace", "\n", "}", "\n", "if", "flag", "==", "0", "{", "flag", "=", "'\"'", "\n", "psn", "=", "k", "\n", "}", "else", "if", "r", "==", "flag", "&&", "prev", "!=", "'\\\\'", "{", "flag", "=", "0", "\n", "}", "\n", "case", "'\\''", ":", "if", "flag", "==", "0", "{", "flag", "=", "'\\''", "\n", "psn", "=", "k", "\n", "}", "else", "if", "r", "==", "flag", "&&", "prev", "!=", "'\\\\'", "{", "// if k-(psn+1) != 1 {", "rs", "[", "psn", "]", "=", "'\"'", "\n", "rs", "[", "k", "]", "=", "'\"'", "\n", "// }", "flag", "=", "0", "\n", "}", "\n", "case", "'`'", ":", "if", "flag", "==", "0", "{", "flag", "=", "'`'", "\n", "psn", "=", "k", "\n", "}", "else", "if", "r", "==", "flag", "{", "flag", "=", "0", "\n", "}", "\n", "}", "\n", "prev", "=", "r", "\n", "}", "\n", "filterPlus", "(", "rs", ")", "\n", "filterJsEsc", "(", "rs", ")", "\n", "out", ":=", "strings", ".", "Replace", "(", "string", "(", "rs", ")", ",", "string", "(", "rune", "(", "0", ")", ")", ",", "`\\\"`", ",", "-", "1", ")", "\n", "out", "=", "strings", ".", "Replace", "(", "out", ",", "string", "(", "rune", "(", "1", ")", ")", ",", "``", ",", "-", "1", ")", "\n", "out", "=", "strings", ".", "Replace", "(", "out", ",", "string", "(", "[", "]", "rune", "{", "2", ",", "2", "}", ")", ",", "\"", "\"", ",", "-", "1", ")", "\n", "out", "=", "strings", ".", "Replace", "(", "out", ",", "string", "(", "rune", "(", "3", ")", ")", ",", "\"", "\"", ",", "-", "1", ")", "\n", "return", "out", "\n", "}" ]
// `"aaa'a" + 'b\"bb"b' + 'c'` >>> `"aaa'a" + "b\"bb\"b" + "c"`
[ "aaa", "a", "+", "b", "\\", "bb", "b", "+", "c", ">>>", "aaa", "a", "+", "b", "\\", "bb", "\\", "b", "+", "c" ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/jade_node.go#L65-L112
train
Joker/jade
jade_node.go
filterPlus
func filterPlus(rs []rune) { var ( flag, prev rune psn int ) for k, r := range rs { switch r { case '"': if flag == 0 { flag = '"' if psn > 0 { for i := psn; i < k+1; i++ { // fmt.Println(string(rs[i]), rs[i]) rs[i] = 1 } } } else if r == flag && prev != '\\' { psn = k flag = 0 } case '`': if flag == 0 { flag = '`' } else if r == flag { flag = 0 } case ' ', '+': default: psn = 0 } prev = r } }
go
func filterPlus(rs []rune) { var ( flag, prev rune psn int ) for k, r := range rs { switch r { case '"': if flag == 0 { flag = '"' if psn > 0 { for i := psn; i < k+1; i++ { // fmt.Println(string(rs[i]), rs[i]) rs[i] = 1 } } } else if r == flag && prev != '\\' { psn = k flag = 0 } case '`': if flag == 0 { flag = '`' } else if r == flag { flag = 0 } case ' ', '+': default: psn = 0 } prev = r } }
[ "func", "filterPlus", "(", "rs", "[", "]", "rune", ")", "{", "var", "(", "flag", ",", "prev", "rune", "\n", "psn", "int", "\n", ")", "\n", "for", "k", ",", "r", ":=", "range", "rs", "{", "switch", "r", "{", "case", "'\"'", ":", "if", "flag", "==", "0", "{", "flag", "=", "'\"'", "\n", "if", "psn", ">", "0", "{", "for", "i", ":=", "psn", ";", "i", "<", "k", "+", "1", ";", "i", "++", "{", "// fmt.Println(string(rs[i]), rs[i])", "rs", "[", "i", "]", "=", "1", "\n", "}", "\n", "}", "\n", "}", "else", "if", "r", "==", "flag", "&&", "prev", "!=", "'\\\\'", "{", "psn", "=", "k", "\n", "flag", "=", "0", "\n", "}", "\n", "case", "'`'", ":", "if", "flag", "==", "0", "{", "flag", "=", "'`'", "\n", "}", "else", "if", "r", "==", "flag", "{", "flag", "=", "0", "\n", "}", "\n", "case", "' '", ",", "'+'", ":", "default", ":", "psn", "=", "0", "\n", "}", "\n", "prev", "=", "r", "\n", "}", "\n", "}" ]
// "aaa" + "bbb" >>> "aaabbb"
[ "aaa", "+", "bbb", ">>>", "aaabbb" ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/jade_node.go#L115-L147
train
Joker/jade
parse.go
Copy
func (t *Tree) Copy() *Tree { if t == nil { return nil } return &Tree{ Name: t.Name, Root: t.Root.CopyList(), text: t.text, } }
go
func (t *Tree) Copy() *Tree { if t == nil { return nil } return &Tree{ Name: t.Name, Root: t.Root.CopyList(), text: t.text, } }
[ "func", "(", "t", "*", "Tree", ")", "Copy", "(", ")", "*", "Tree", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "Tree", "{", "Name", ":", "t", ".", "Name", ",", "Root", ":", "t", ".", "Root", ".", "CopyList", "(", ")", ",", "text", ":", "t", ".", "text", ",", "}", "\n", "}" ]
// Copy returns a copy of the Tree. Any parsing state is discarded.
[ "Copy", "returns", "a", "copy", "of", "the", "Tree", ".", "Any", "parsing", "state", "is", "discarded", "." ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/parse.go#L28-L37
train
Joker/jade
parse.go
New
func New(name string) *Tree { return &Tree{ Name: name, mixin: map[string]*MixinNode{}, block: map[string]*ListNode{}, } }
go
func New(name string) *Tree { return &Tree{ Name: name, mixin: map[string]*MixinNode{}, block: map[string]*ListNode{}, } }
[ "func", "New", "(", "name", "string", ")", "*", "Tree", "{", "return", "&", "Tree", "{", "Name", ":", "name", ",", "mixin", ":", "map", "[", "string", "]", "*", "MixinNode", "{", "}", ",", "block", ":", "map", "[", "string", "]", "*", "ListNode", "{", "}", ",", "}", "\n", "}" ]
// New allocates a new parse tree with the given name.
[ "New", "allocates", "a", "new", "parse", "tree", "with", "the", "given", "name", "." ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/parse.go#L139-L145
train
Joker/jade
lex.go
backup
func (l *lexer) backup() { l.pos -= l.width // Correct newline count. if l.width == 1 && l.input[l.pos] == '\n' { l.line-- } }
go
func (l *lexer) backup() { l.pos -= l.width // Correct newline count. if l.width == 1 && l.input[l.pos] == '\n' { l.line-- } }
[ "func", "(", "l", "*", "lexer", ")", "backup", "(", ")", "{", "l", ".", "pos", "-=", "l", ".", "width", "\n", "// Correct newline count.", "if", "l", ".", "width", "==", "1", "&&", "l", ".", "input", "[", "l", ".", "pos", "]", "==", "'\\n'", "{", "l", ".", "line", "--", "\n", "}", "\n", "}" ]
// backup steps back one rune. Can only be called once per call of next.
[ "backup", "steps", "back", "one", "rune", ".", "Can", "only", "be", "called", "once", "per", "call", "of", "next", "." ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/lex.go#L83-L89
train
couchbase/go-couchbase
conn_pool.go
Discard
func (cp *connectionPool) Discard(c *memcached.Client) { <-cp.createsem c.Close() }
go
func (cp *connectionPool) Discard(c *memcached.Client) { <-cp.createsem c.Close() }
[ "func", "(", "cp", "*", "connectionPool", ")", "Discard", "(", "c", "*", "memcached", ".", "Client", ")", "{", "<-", "cp", ".", "createsem", "\n", "c", ".", "Close", "(", ")", "\n", "}" ]
// give the ability to discard a connection from a pool // useful for ditching connections to the wrong node after a rebalance
[ "give", "the", "ability", "to", "discard", "a", "connection", "from", "a", "pool", "useful", "for", "ditching", "connections", "to", "the", "wrong", "node", "after", "a", "rebalance" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/conn_pool.go#L292-L295
train
couchbase/go-couchbase
conn_pool.go
connCloser
func (cp *connectionPool) connCloser() { var connCount uint64 t := time.NewTimer(ConnCloserInterval) defer t.Stop() for { connCount = cp.connCount // we don't exist anymore! bail out! select { case <-cp.bailOut: return case <-t.C: } t.Reset(ConnCloserInterval) // no overflow connections open or sustained requests for connections // nothing to do until the next cycle if len(cp.connections) <= cp.poolSize || ConnCloserInterval/ConnPoolAvailWaitTime < time.Duration(cp.connCount-connCount) { continue } // close overflow connections now that they are not needed for c := range cp.connections { select { case <-cp.bailOut: return default: } // bail out if close did not work out if !cp.connCleanup(c) { return } if len(cp.connections) <= cp.poolSize { break } } } }
go
func (cp *connectionPool) connCloser() { var connCount uint64 t := time.NewTimer(ConnCloserInterval) defer t.Stop() for { connCount = cp.connCount // we don't exist anymore! bail out! select { case <-cp.bailOut: return case <-t.C: } t.Reset(ConnCloserInterval) // no overflow connections open or sustained requests for connections // nothing to do until the next cycle if len(cp.connections) <= cp.poolSize || ConnCloserInterval/ConnPoolAvailWaitTime < time.Duration(cp.connCount-connCount) { continue } // close overflow connections now that they are not needed for c := range cp.connections { select { case <-cp.bailOut: return default: } // bail out if close did not work out if !cp.connCleanup(c) { return } if len(cp.connections) <= cp.poolSize { break } } } }
[ "func", "(", "cp", "*", "connectionPool", ")", "connCloser", "(", ")", "{", "var", "connCount", "uint64", "\n\n", "t", ":=", "time", ".", "NewTimer", "(", "ConnCloserInterval", ")", "\n", "defer", "t", ".", "Stop", "(", ")", "\n\n", "for", "{", "connCount", "=", "cp", ".", "connCount", "\n\n", "// we don't exist anymore! bail out!", "select", "{", "case", "<-", "cp", ".", "bailOut", ":", "return", "\n", "case", "<-", "t", ".", "C", ":", "}", "\n", "t", ".", "Reset", "(", "ConnCloserInterval", ")", "\n\n", "// no overflow connections open or sustained requests for connections", "// nothing to do until the next cycle", "if", "len", "(", "cp", ".", "connections", ")", "<=", "cp", ".", "poolSize", "||", "ConnCloserInterval", "/", "ConnPoolAvailWaitTime", "<", "time", ".", "Duration", "(", "cp", ".", "connCount", "-", "connCount", ")", "{", "continue", "\n", "}", "\n\n", "// close overflow connections now that they are not needed", "for", "c", ":=", "range", "cp", ".", "connections", "{", "select", "{", "case", "<-", "cp", ".", "bailOut", ":", "return", "\n", "default", ":", "}", "\n\n", "// bail out if close did not work out", "if", "!", "cp", ".", "connCleanup", "(", "c", ")", "{", "return", "\n", "}", "\n", "if", "len", "(", "cp", ".", "connections", ")", "<=", "cp", ".", "poolSize", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// asynchronous connection closer
[ "asynchronous", "connection", "closer" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/conn_pool.go#L298-L339
train
couchbase/go-couchbase
conn_pool.go
connCleanup
func (cp *connectionPool) connCleanup(c *memcached.Client) (rv bool) { // just in case we are closing a connection after // bailOut has been sent but we haven't yet read it defer func() { if recover() != nil { rv = false } }() rv = true c.Close() <-cp.createsem return }
go
func (cp *connectionPool) connCleanup(c *memcached.Client) (rv bool) { // just in case we are closing a connection after // bailOut has been sent but we haven't yet read it defer func() { if recover() != nil { rv = false } }() rv = true c.Close() <-cp.createsem return }
[ "func", "(", "cp", "*", "connectionPool", ")", "connCleanup", "(", "c", "*", "memcached", ".", "Client", ")", "(", "rv", "bool", ")", "{", "// just in case we are closing a connection after", "// bailOut has been sent but we haven't yet read it", "defer", "func", "(", ")", "{", "if", "recover", "(", ")", "!=", "nil", "{", "rv", "=", "false", "\n", "}", "\n", "}", "(", ")", "\n", "rv", "=", "true", "\n\n", "c", ".", "Close", "(", ")", "\n", "<-", "cp", ".", "createsem", "\n", "return", "\n", "}" ]
// close connection with recovery on error
[ "close", "connection", "with", "recovery", "on", "error" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/conn_pool.go#L342-L356
train
couchbase/go-couchbase
trace/trace.go
ConsolidateByTitle
func ConsolidateByTitle(next *Msg, prev *Msg) *Msg { if prev == nil || prev.Title != next.Title { return next } prev.Repeats++ return nil }
go
func ConsolidateByTitle(next *Msg, prev *Msg) *Msg { if prev == nil || prev.Title != next.Title { return next } prev.Repeats++ return nil }
[ "func", "ConsolidateByTitle", "(", "next", "*", "Msg", ",", "prev", "*", "Msg", ")", "*", "Msg", "{", "if", "prev", "==", "nil", "||", "prev", ".", "Title", "!=", "next", ".", "Title", "{", "return", "next", "\n", "}", "\n\n", "prev", ".", "Repeats", "++", "\n", "return", "nil", "\n", "}" ]
// ConsolidateByTitle implements the MsgConsolidateFunc signature // by consolidating trace message when their titles are the same.
[ "ConsolidateByTitle", "implements", "the", "MsgConsolidateFunc", "signature", "by", "consolidating", "trace", "message", "when", "their", "titles", "are", "the", "same", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L57-L64
train
couchbase/go-couchbase
trace/trace.go
NewRingBuffer
func NewRingBuffer( capacity int, consolidateFunc MsgConsolidateFunc) *RingBuffer { return &RingBuffer{ consolidateFunc: consolidateFunc, next: 0, msgs: make([]Msg, capacity), } }
go
func NewRingBuffer( capacity int, consolidateFunc MsgConsolidateFunc) *RingBuffer { return &RingBuffer{ consolidateFunc: consolidateFunc, next: 0, msgs: make([]Msg, capacity), } }
[ "func", "NewRingBuffer", "(", "capacity", "int", ",", "consolidateFunc", "MsgConsolidateFunc", ")", "*", "RingBuffer", "{", "return", "&", "RingBuffer", "{", "consolidateFunc", ":", "consolidateFunc", ",", "next", ":", "0", ",", "msgs", ":", "make", "(", "[", "]", "Msg", ",", "capacity", ")", ",", "}", "\n", "}" ]
// NewRingBuffer returns a RingBuffer initialized with the // given capacity and optional consolidateFunc.
[ "NewRingBuffer", "returns", "a", "RingBuffer", "initialized", "with", "the", "given", "capacity", "and", "optional", "consolidateFunc", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L68-L76
train
couchbase/go-couchbase
trace/trace.go
Add
func (trb *RingBuffer) Add(title string, body []byte) { if len(trb.msgs) <= 0 { return } msg := &Msg{ Title: title, Body: body, Repeats: 1, } trb.m.Lock() if trb.consolidateFunc != nil { msg = trb.consolidateFunc(msg, trb.lastUNLOCKED()) if msg == nil { trb.m.Unlock() return } } trb.msgs[trb.next] = *msg trb.next++ if trb.next >= len(trb.msgs) { trb.next = 0 } trb.m.Unlock() }
go
func (trb *RingBuffer) Add(title string, body []byte) { if len(trb.msgs) <= 0 { return } msg := &Msg{ Title: title, Body: body, Repeats: 1, } trb.m.Lock() if trb.consolidateFunc != nil { msg = trb.consolidateFunc(msg, trb.lastUNLOCKED()) if msg == nil { trb.m.Unlock() return } } trb.msgs[trb.next] = *msg trb.next++ if trb.next >= len(trb.msgs) { trb.next = 0 } trb.m.Unlock() }
[ "func", "(", "trb", "*", "RingBuffer", ")", "Add", "(", "title", "string", ",", "body", "[", "]", "byte", ")", "{", "if", "len", "(", "trb", ".", "msgs", ")", "<=", "0", "{", "return", "\n", "}", "\n\n", "msg", ":=", "&", "Msg", "{", "Title", ":", "title", ",", "Body", ":", "body", ",", "Repeats", ":", "1", ",", "}", "\n\n", "trb", ".", "m", ".", "Lock", "(", ")", "\n\n", "if", "trb", ".", "consolidateFunc", "!=", "nil", "{", "msg", "=", "trb", ".", "consolidateFunc", "(", "msg", ",", "trb", ".", "lastUNLOCKED", "(", ")", ")", "\n", "if", "msg", "==", "nil", "{", "trb", ".", "m", ".", "Unlock", "(", ")", "\n\n", "return", "\n", "}", "\n", "}", "\n\n", "trb", ".", "msgs", "[", "trb", ".", "next", "]", "=", "*", "msg", "\n\n", "trb", ".", "next", "++", "\n", "if", "trb", ".", "next", ">=", "len", "(", "trb", ".", "msgs", ")", "{", "trb", ".", "next", "=", "0", "\n", "}", "\n\n", "trb", ".", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// Add appens a trace message to the ring buffer, consolidating trace // messages based on the optional consolidation function.
[ "Add", "appens", "a", "trace", "message", "to", "the", "ring", "buffer", "consolidating", "trace", "messages", "based", "on", "the", "optional", "consolidation", "function", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L80-L110
train
couchbase/go-couchbase
trace/trace.go
Last
func (trb *RingBuffer) Last() *Msg { trb.m.Lock() last := trb.lastUNLOCKED() trb.m.Unlock() return last }
go
func (trb *RingBuffer) Last() *Msg { trb.m.Lock() last := trb.lastUNLOCKED() trb.m.Unlock() return last }
[ "func", "(", "trb", "*", "RingBuffer", ")", "Last", "(", ")", "*", "Msg", "{", "trb", ".", "m", ".", "Lock", "(", ")", "\n", "last", ":=", "trb", ".", "lastUNLOCKED", "(", ")", "\n", "trb", ".", "m", ".", "Unlock", "(", ")", "\n", "return", "last", "\n", "}" ]
// Last returns the last trace in the ring buffer.
[ "Last", "returns", "the", "last", "trace", "in", "the", "ring", "buffer", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L118-L123
train
couchbase/go-couchbase
trace/trace.go
Msgs
func (trb *RingBuffer) Msgs() []Msg { rv := make([]Msg, 0, len(trb.msgs)) trb.m.Lock() i := trb.next for { if trb.msgs[i].Title != "" { rv = append(rv, trb.msgs[i]) } i++ if i >= len(trb.msgs) { i = 0 } if i == trb.next { // We've returned to the beginning. break } } trb.m.Unlock() return rv }
go
func (trb *RingBuffer) Msgs() []Msg { rv := make([]Msg, 0, len(trb.msgs)) trb.m.Lock() i := trb.next for { if trb.msgs[i].Title != "" { rv = append(rv, trb.msgs[i]) } i++ if i >= len(trb.msgs) { i = 0 } if i == trb.next { // We've returned to the beginning. break } } trb.m.Unlock() return rv }
[ "func", "(", "trb", "*", "RingBuffer", ")", "Msgs", "(", ")", "[", "]", "Msg", "{", "rv", ":=", "make", "(", "[", "]", "Msg", ",", "0", ",", "len", "(", "trb", ".", "msgs", ")", ")", "\n\n", "trb", ".", "m", ".", "Lock", "(", ")", "\n\n", "i", ":=", "trb", ".", "next", "\n", "for", "{", "if", "trb", ".", "msgs", "[", "i", "]", ".", "Title", "!=", "\"", "\"", "{", "rv", "=", "append", "(", "rv", ",", "trb", ".", "msgs", "[", "i", "]", ")", "\n", "}", "\n\n", "i", "++", "\n", "if", "i", ">=", "len", "(", "trb", ".", "msgs", ")", "{", "i", "=", "0", "\n", "}", "\n\n", "if", "i", "==", "trb", ".", "next", "{", "// We've returned to the beginning.", "break", "\n", "}", "\n", "}", "\n\n", "trb", ".", "m", ".", "Unlock", "(", ")", "\n\n", "return", "rv", "\n", "}" ]
// Msgs returns a copy of all the trace messages, as an array with the // oldest trace message first.
[ "Msgs", "returns", "a", "copy", "of", "all", "the", "trace", "messages", "as", "an", "array", "with", "the", "oldest", "trace", "message", "first", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L138-L162
train
couchbase/go-couchbase
perf/generate-json.go
generateRandomDocument
func generateRandomDocument() ([]byte, error) { c := &contacts{} c.Name = randomdata.FullName(randomdata.RandomGender) c.Email = randomdata.Email() c.Age = randomdata.Number(20, 50) c.Address = randomdata.Address() c.City = randomdata.City() c.State = randomdata.State(randomdata.Large) c.Country = randomdata.Country(randomdata.FullCountry) return json.Marshal(c) }
go
func generateRandomDocument() ([]byte, error) { c := &contacts{} c.Name = randomdata.FullName(randomdata.RandomGender) c.Email = randomdata.Email() c.Age = randomdata.Number(20, 50) c.Address = randomdata.Address() c.City = randomdata.City() c.State = randomdata.State(randomdata.Large) c.Country = randomdata.Country(randomdata.FullCountry) return json.Marshal(c) }
[ "func", "generateRandomDocument", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "c", ":=", "&", "contacts", "{", "}", "\n", "c", ".", "Name", "=", "randomdata", ".", "FullName", "(", "randomdata", ".", "RandomGender", ")", "\n", "c", ".", "Email", "=", "randomdata", ".", "Email", "(", ")", "\n", "c", ".", "Age", "=", "randomdata", ".", "Number", "(", "20", ",", "50", ")", "\n", "c", ".", "Address", "=", "randomdata", ".", "Address", "(", ")", "\n", "c", ".", "City", "=", "randomdata", ".", "City", "(", ")", "\n", "c", ".", "State", "=", "randomdata", ".", "State", "(", "randomdata", ".", "Large", ")", "\n", "c", ".", "Country", "=", "randomdata", ".", "Country", "(", "randomdata", ".", "FullCountry", ")", "\n\n", "return", "json", ".", "Marshal", "(", "c", ")", "\n", "}" ]
// return a json marshalled document
[ "return", "a", "json", "marshalled", "document" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/perf/generate-json.go#L19-L30
train
couchbase/go-couchbase
platform/platform_windows.go
HideConsole
func HideConsole(hide bool) { var k32 = syscall.NewLazyDLL("kernel32.dll") var cw = k32.NewProc("GetConsoleWindow") var u32 = syscall.NewLazyDLL("user32.dll") var sw = u32.NewProc("ShowWindow") hwnd, _, _ := cw.Call() if hwnd == 0 { return } if hide { var SW_HIDE uintptr = 0 sw.Call(hwnd, SW_HIDE) } else { var SW_RESTORE uintptr = 9 sw.Call(hwnd, SW_RESTORE) } }
go
func HideConsole(hide bool) { var k32 = syscall.NewLazyDLL("kernel32.dll") var cw = k32.NewProc("GetConsoleWindow") var u32 = syscall.NewLazyDLL("user32.dll") var sw = u32.NewProc("ShowWindow") hwnd, _, _ := cw.Call() if hwnd == 0 { return } if hide { var SW_HIDE uintptr = 0 sw.Call(hwnd, SW_HIDE) } else { var SW_RESTORE uintptr = 9 sw.Call(hwnd, SW_RESTORE) } }
[ "func", "HideConsole", "(", "hide", "bool", ")", "{", "var", "k32", "=", "syscall", ".", "NewLazyDLL", "(", "\"", "\"", ")", "\n", "var", "cw", "=", "k32", ".", "NewProc", "(", "\"", "\"", ")", "\n", "var", "u32", "=", "syscall", ".", "NewLazyDLL", "(", "\"", "\"", ")", "\n", "var", "sw", "=", "u32", ".", "NewProc", "(", "\"", "\"", ")", "\n", "hwnd", ",", "_", ",", "_", ":=", "cw", ".", "Call", "(", ")", "\n", "if", "hwnd", "==", "0", "{", "return", "\n", "}", "\n", "if", "hide", "{", "var", "SW_HIDE", "uintptr", "=", "0", "\n", "sw", ".", "Call", "(", "hwnd", ",", "SW_HIDE", ")", "\n", "}", "else", "{", "var", "SW_RESTORE", "uintptr", "=", "9", "\n", "sw", ".", "Call", "(", "hwnd", ",", "SW_RESTORE", ")", "\n", "}", "\n", "}" ]
// Hide console on windows without removing it unlike -H windowsgui.
[ "Hide", "console", "on", "windows", "without", "removing", "it", "unlike", "-", "H", "windowsgui", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/platform/platform_windows.go#L20-L36
train
couchbase/go-couchbase
ddocs.go
GetDDocs
func (b *Bucket) GetDDocs() (DDocsResult, error) { var ddocsResult DDocsResult b.RLock() pool := b.pool uri := b.DDocs.URI b.RUnlock() // MB-23555 ephemeral buckets have no ddocs if uri == "" { return DDocsResult{}, nil } err := pool.client.parseURLResponse(uri, &ddocsResult) if err != nil { return DDocsResult{}, err } return ddocsResult, nil }
go
func (b *Bucket) GetDDocs() (DDocsResult, error) { var ddocsResult DDocsResult b.RLock() pool := b.pool uri := b.DDocs.URI b.RUnlock() // MB-23555 ephemeral buckets have no ddocs if uri == "" { return DDocsResult{}, nil } err := pool.client.parseURLResponse(uri, &ddocsResult) if err != nil { return DDocsResult{}, err } return ddocsResult, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetDDocs", "(", ")", "(", "DDocsResult", ",", "error", ")", "{", "var", "ddocsResult", "DDocsResult", "\n", "b", ".", "RLock", "(", ")", "\n", "pool", ":=", "b", ".", "pool", "\n", "uri", ":=", "b", ".", "DDocs", ".", "URI", "\n", "b", ".", "RUnlock", "(", ")", "\n\n", "// MB-23555 ephemeral buckets have no ddocs", "if", "uri", "==", "\"", "\"", "{", "return", "DDocsResult", "{", "}", ",", "nil", "\n", "}", "\n\n", "err", ":=", "pool", ".", "client", ".", "parseURLResponse", "(", "uri", ",", "&", "ddocsResult", ")", "\n", "if", "err", "!=", "nil", "{", "return", "DDocsResult", "{", "}", ",", "err", "\n", "}", "\n", "return", "ddocsResult", ",", "nil", "\n", "}" ]
// GetDDocs lists all design documents
[ "GetDDocs", "lists", "all", "design", "documents" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/ddocs.go#L36-L53
train
couchbase/go-couchbase
ddocs.go
PutDDoc
func (b *Bucket) PutDDoc(docname string, value interface{}) error { var Err error maxRetries, err := b.getMaxRetries() if err != nil { return err } lastNode := START_NODE_ID for retryCount := 0; retryCount < maxRetries; retryCount++ { Err = nil ddocU, selectedNode, err := b.ddocURLNext(lastNode, docname) if err != nil { return err } lastNode = selectedNode logging.Infof(" Trying with selected node %d", selectedNode) j, err := json.Marshal(value) if err != nil { return err } req, err := http.NewRequest("PUT", ddocU, bytes.NewReader(j)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") err = maybeAddAuth(req, b.authHandler(false /* bucket not yet locked */)) if err != nil { return err } res, err := doHTTPRequest(req) if err != nil { return err } if res.StatusCode != 201 { body, _ := ioutil.ReadAll(res.Body) Err = fmt.Errorf("error installing view: %v / %s", res.Status, body) logging.Errorf(" Error in PutDDOC %v. Retrying...", Err) res.Body.Close() b.Refresh() continue } res.Body.Close() break } return Err }
go
func (b *Bucket) PutDDoc(docname string, value interface{}) error { var Err error maxRetries, err := b.getMaxRetries() if err != nil { return err } lastNode := START_NODE_ID for retryCount := 0; retryCount < maxRetries; retryCount++ { Err = nil ddocU, selectedNode, err := b.ddocURLNext(lastNode, docname) if err != nil { return err } lastNode = selectedNode logging.Infof(" Trying with selected node %d", selectedNode) j, err := json.Marshal(value) if err != nil { return err } req, err := http.NewRequest("PUT", ddocU, bytes.NewReader(j)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") err = maybeAddAuth(req, b.authHandler(false /* bucket not yet locked */)) if err != nil { return err } res, err := doHTTPRequest(req) if err != nil { return err } if res.StatusCode != 201 { body, _ := ioutil.ReadAll(res.Body) Err = fmt.Errorf("error installing view: %v / %s", res.Status, body) logging.Errorf(" Error in PutDDOC %v. Retrying...", Err) res.Body.Close() b.Refresh() continue } res.Body.Close() break } return Err }
[ "func", "(", "b", "*", "Bucket", ")", "PutDDoc", "(", "docname", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "var", "Err", "error", "\n\n", "maxRetries", ",", "err", ":=", "b", ".", "getMaxRetries", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lastNode", ":=", "START_NODE_ID", "\n\n", "for", "retryCount", ":=", "0", ";", "retryCount", "<", "maxRetries", ";", "retryCount", "++", "{", "Err", "=", "nil", "\n\n", "ddocU", ",", "selectedNode", ",", "err", ":=", "b", ".", "ddocURLNext", "(", "lastNode", ",", "docname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lastNode", "=", "selectedNode", "\n\n", "logging", ".", "Infof", "(", "\"", "\"", ",", "selectedNode", ")", "\n", "j", ",", "err", ":=", "json", ".", "Marshal", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "ddocU", ",", "bytes", ".", "NewReader", "(", "j", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "err", "=", "maybeAddAuth", "(", "req", ",", "b", ".", "authHandler", "(", "false", "/* bucket not yet locked */", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "doHTTPRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "res", ".", "StatusCode", "!=", "201", "{", "body", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "Err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Status", ",", "body", ")", "\n", "logging", ".", "Errorf", "(", "\"", "\"", ",", "Err", ")", "\n", "res", ".", "Body", ".", "Close", "(", ")", "\n", "b", ".", "Refresh", "(", ")", "\n", "continue", "\n", "}", "\n\n", "res", ".", "Body", ".", "Close", "(", ")", "\n", "break", "\n", "}", "\n\n", "return", "Err", "\n", "}" ]
// PutDDoc installs a design document.
[ "PutDDoc", "installs", "a", "design", "document", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/ddocs.go#L121-L179
train
couchbase/go-couchbase
util.go
CleanupHost
func CleanupHost(h, commonSuffix string) string { if strings.HasSuffix(h, commonSuffix) { return h[:len(h)-len(commonSuffix)] } return h }
go
func CleanupHost(h, commonSuffix string) string { if strings.HasSuffix(h, commonSuffix) { return h[:len(h)-len(commonSuffix)] } return h }
[ "func", "CleanupHost", "(", "h", ",", "commonSuffix", "string", ")", "string", "{", "if", "strings", ".", "HasSuffix", "(", "h", ",", "commonSuffix", ")", "{", "return", "h", "[", ":", "len", "(", "h", ")", "-", "len", "(", "commonSuffix", ")", "]", "\n", "}", "\n", "return", "h", "\n", "}" ]
// CleanupHost returns the hostname with the given suffix removed.
[ "CleanupHost", "returns", "the", "hostname", "with", "the", "given", "suffix", "removed", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/util.go#L10-L15
train
couchbase/go-couchbase
util.go
FindCommonSuffix
func FindCommonSuffix(input []string) string { rv := "" if len(input) < 2 { return "" } from := input for i := len(input[0]); i > 0; i-- { common := true suffix := input[0][i:] for _, s := range from { if !strings.HasSuffix(s, suffix) { common = false break } } if common { rv = suffix } } return rv }
go
func FindCommonSuffix(input []string) string { rv := "" if len(input) < 2 { return "" } from := input for i := len(input[0]); i > 0; i-- { common := true suffix := input[0][i:] for _, s := range from { if !strings.HasSuffix(s, suffix) { common = false break } } if common { rv = suffix } } return rv }
[ "func", "FindCommonSuffix", "(", "input", "[", "]", "string", ")", "string", "{", "rv", ":=", "\"", "\"", "\n", "if", "len", "(", "input", ")", "<", "2", "{", "return", "\"", "\"", "\n", "}", "\n", "from", ":=", "input", "\n", "for", "i", ":=", "len", "(", "input", "[", "0", "]", ")", ";", "i", ">", "0", ";", "i", "--", "{", "common", ":=", "true", "\n", "suffix", ":=", "input", "[", "0", "]", "[", "i", ":", "]", "\n", "for", "_", ",", "s", ":=", "range", "from", "{", "if", "!", "strings", ".", "HasSuffix", "(", "s", ",", "suffix", ")", "{", "common", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "common", "{", "rv", "=", "suffix", "\n", "}", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// FindCommonSuffix returns the longest common suffix from the given // strings.
[ "FindCommonSuffix", "returns", "the", "longest", "common", "suffix", "from", "the", "given", "strings", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/util.go#L19-L39
train
couchbase/go-couchbase
util.go
ParseURL
func ParseURL(urlStr string) (result *url.URL, err error) { result, err = url.Parse(urlStr) if result != nil && result.Scheme == "" { result = nil err = fmt.Errorf("invalid URL <%s>", urlStr) } return }
go
func ParseURL(urlStr string) (result *url.URL, err error) { result, err = url.Parse(urlStr) if result != nil && result.Scheme == "" { result = nil err = fmt.Errorf("invalid URL <%s>", urlStr) } return }
[ "func", "ParseURL", "(", "urlStr", "string", ")", "(", "result", "*", "url", ".", "URL", ",", "err", "error", ")", "{", "result", ",", "err", "=", "url", ".", "Parse", "(", "urlStr", ")", "\n", "if", "result", "!=", "nil", "&&", "result", ".", "Scheme", "==", "\"", "\"", "{", "result", "=", "nil", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "urlStr", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ParseURL is a wrapper around url.Parse with some sanity-checking
[ "ParseURL", "is", "a", "wrapper", "around", "url", ".", "Parse", "with", "some", "sanity", "-", "checking" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/util.go#L42-L49
train
couchbase/go-couchbase
vbmap.go
VBHash
func (b *Bucket) VBHash(key string) uint32 { crc := uint32(0xffffffff) for x := 0; x < len(key); x++ { crc = (crc >> 8) ^ crc32tab[(uint64(crc)^uint64(key[x]))&0xff] } vbm := b.VBServerMap() return ((^crc) >> 16) & 0x7fff & (uint32(len(vbm.VBucketMap)) - 1) }
go
func (b *Bucket) VBHash(key string) uint32 { crc := uint32(0xffffffff) for x := 0; x < len(key); x++ { crc = (crc >> 8) ^ crc32tab[(uint64(crc)^uint64(key[x]))&0xff] } vbm := b.VBServerMap() return ((^crc) >> 16) & 0x7fff & (uint32(len(vbm.VBucketMap)) - 1) }
[ "func", "(", "b", "*", "Bucket", ")", "VBHash", "(", "key", "string", ")", "uint32", "{", "crc", ":=", "uint32", "(", "0xffffffff", ")", "\n", "for", "x", ":=", "0", ";", "x", "<", "len", "(", "key", ")", ";", "x", "++", "{", "crc", "=", "(", "crc", ">>", "8", ")", "^", "crc32tab", "[", "(", "uint64", "(", "crc", ")", "^", "uint64", "(", "key", "[", "x", "]", ")", ")", "&", "0xff", "]", "\n", "}", "\n", "vbm", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "return", "(", "(", "^", "crc", ")", ">>", "16", ")", "&", "0x7fff", "&", "(", "uint32", "(", "len", "(", "vbm", ".", "VBucketMap", ")", ")", "-", "1", ")", "\n", "}" ]
// VBHash finds the vbucket for the given key.
[ "VBHash", "finds", "the", "vbucket", "for", "the", "given", "key", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/vbmap.go#L70-L77
train
couchbase/go-couchbase
pools.go
SetConnectionPoolParams
func SetConnectionPoolParams(size, overflow int) { if size > 0 { PoolSize = size } if overflow > 0 { PoolOverflow = overflow } }
go
func SetConnectionPoolParams(size, overflow int) { if size > 0 { PoolSize = size } if overflow > 0 { PoolOverflow = overflow } }
[ "func", "SetConnectionPoolParams", "(", "size", ",", "overflow", "int", ")", "{", "if", "size", ">", "0", "{", "PoolSize", "=", "size", "\n", "}", "\n\n", "if", "overflow", ">", "0", "{", "PoolOverflow", "=", "overflow", "\n", "}", "\n", "}" ]
// Allow applications to speciify the Poolsize and Overflow
[ "Allow", "applications", "to", "speciify", "the", "Poolsize", "and", "Overflow" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L87-L96
train
couchbase/go-couchbase
pools.go
SetTcpKeepalive
func SetTcpKeepalive(enabled bool, interval int) { TCPKeepalive = enabled if interval > 0 { TCPKeepaliveInterval = interval } }
go
func SetTcpKeepalive(enabled bool, interval int) { TCPKeepalive = enabled if interval > 0 { TCPKeepaliveInterval = interval } }
[ "func", "SetTcpKeepalive", "(", "enabled", "bool", ",", "interval", "int", ")", "{", "TCPKeepalive", "=", "enabled", "\n\n", "if", "interval", ">", "0", "{", "TCPKeepaliveInterval", "=", "interval", "\n", "}", "\n", "}" ]
// Allow TCP keepalive parameters to be set by the application
[ "Allow", "TCP", "keepalive", "parameters", "to", "be", "set", "by", "the", "application" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L109-L116
train
couchbase/go-couchbase
pools.go
VBServerMap
func (b *Bucket) VBServerMap() *VBucketServerMap { b.RLock() defer b.RUnlock() ret := (*VBucketServerMap)(b.vBucketServerMap) return ret }
go
func (b *Bucket) VBServerMap() *VBucketServerMap { b.RLock() defer b.RUnlock() ret := (*VBucketServerMap)(b.vBucketServerMap) return ret }
[ "func", "(", "b", "*", "Bucket", ")", "VBServerMap", "(", ")", "*", "VBucketServerMap", "{", "b", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "RUnlock", "(", ")", "\n", "ret", ":=", "(", "*", "VBucketServerMap", ")", "(", "b", ".", "vBucketServerMap", ")", "\n", "return", "ret", "\n", "}" ]
// VBServerMap returns the current VBucketServerMap.
[ "VBServerMap", "returns", "the", "current", "VBucketServerMap", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L288-L293
train
couchbase/go-couchbase
pools.go
checkVBmap
func (b *Bucket) checkVBmap(node string) bool { vbmap := b.VBServerMap() servers := vbmap.ServerList for _, idxs := range vbmap.VBucketMap { if len(idxs) == 0 { return true } else if idxs[0] < 0 || idxs[0] >= len(servers) { return true } if servers[idxs[0]] == node { return false } } return true }
go
func (b *Bucket) checkVBmap(node string) bool { vbmap := b.VBServerMap() servers := vbmap.ServerList for _, idxs := range vbmap.VBucketMap { if len(idxs) == 0 { return true } else if idxs[0] < 0 || idxs[0] >= len(servers) { return true } if servers[idxs[0]] == node { return false } } return true }
[ "func", "(", "b", "*", "Bucket", ")", "checkVBmap", "(", "node", "string", ")", "bool", "{", "vbmap", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "servers", ":=", "vbmap", ".", "ServerList", "\n\n", "for", "_", ",", "idxs", ":=", "range", "vbmap", ".", "VBucketMap", "{", "if", "len", "(", "idxs", ")", "==", "0", "{", "return", "true", "\n", "}", "else", "if", "idxs", "[", "0", "]", "<", "0", "||", "idxs", "[", "0", "]", ">=", "len", "(", "servers", ")", "{", "return", "true", "\n", "}", "\n", "if", "servers", "[", "idxs", "[", "0", "]", "]", "==", "node", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// true if node is not on the bucket VBmap
[ "true", "if", "node", "is", "not", "on", "the", "bucket", "VBmap" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L321-L336
train
couchbase/go-couchbase
pools.go
Nodes
func (b *Bucket) Nodes() []Node { b.RLock() defer b.RUnlock() ret := *(*[]Node)(b.nodeList) return ret }
go
func (b *Bucket) Nodes() []Node { b.RLock() defer b.RUnlock() ret := *(*[]Node)(b.nodeList) return ret }
[ "func", "(", "b", "*", "Bucket", ")", "Nodes", "(", ")", "[", "]", "Node", "{", "b", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "RUnlock", "(", ")", "\n", "ret", ":=", "*", "(", "*", "[", "]", "Node", ")", "(", "b", ".", "nodeList", ")", "\n", "return", "ret", "\n", "}" ]
// Nodes returns the current list of nodes servicing this bucket.
[ "Nodes", "returns", "the", "current", "list", "of", "nodes", "servicing", "this", "bucket", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L346-L351
train
couchbase/go-couchbase
pools.go
HealthyNodes
func (b *Bucket) HealthyNodes() []Node { nodes := []Node{} for _, n := range b.Nodes() { if n.Status == "healthy" && n.CouchAPIBase != "" { nodes = append(nodes, n) } if n.Status != "healthy" { // log non-healthy node logging.Infof("Non-healthy node; node details:") logging.Infof("Hostname=%v, Status=%v, CouchAPIBase=%v, ThisNode=%v", n.Hostname, n.Status, n.CouchAPIBase, n.ThisNode) } } return nodes }
go
func (b *Bucket) HealthyNodes() []Node { nodes := []Node{} for _, n := range b.Nodes() { if n.Status == "healthy" && n.CouchAPIBase != "" { nodes = append(nodes, n) } if n.Status != "healthy" { // log non-healthy node logging.Infof("Non-healthy node; node details:") logging.Infof("Hostname=%v, Status=%v, CouchAPIBase=%v, ThisNode=%v", n.Hostname, n.Status, n.CouchAPIBase, n.ThisNode) } } return nodes }
[ "func", "(", "b", "*", "Bucket", ")", "HealthyNodes", "(", ")", "[", "]", "Node", "{", "nodes", ":=", "[", "]", "Node", "{", "}", "\n\n", "for", "_", ",", "n", ":=", "range", "b", ".", "Nodes", "(", ")", "{", "if", "n", ".", "Status", "==", "\"", "\"", "&&", "n", ".", "CouchAPIBase", "!=", "\"", "\"", "{", "nodes", "=", "append", "(", "nodes", ",", "n", ")", "\n", "}", "\n", "if", "n", ".", "Status", "!=", "\"", "\"", "{", "// log non-healthy node", "logging", ".", "Infof", "(", "\"", "\"", ")", "\n", "logging", ".", "Infof", "(", "\"", "\"", ",", "n", ".", "Hostname", ",", "n", ".", "Status", ",", "n", ".", "CouchAPIBase", ",", "n", ".", "ThisNode", ")", "\n", "}", "\n", "}", "\n\n", "return", "nodes", "\n", "}" ]
// return the list of healthy nodes
[ "return", "the", "list", "of", "healthy", "nodes" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L354-L368
train
couchbase/go-couchbase
pools.go
getConnectionToVBucket
func (b *Bucket) getConnectionToVBucket(vb uint32) (*memcached.Client, *connectionPool, error) { for { vbm := b.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return nil, nil, fmt.Errorf("go-couchbase: vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } masterId := vbm.VBucketMap[vb][0] if masterId < 0 { return nil, nil, fmt.Errorf("go-couchbase: No master for vbucket %d", vb) } pool := b.getConnPool(masterId) conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
go
func (b *Bucket) getConnectionToVBucket(vb uint32) (*memcached.Client, *connectionPool, error) { for { vbm := b.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return nil, nil, fmt.Errorf("go-couchbase: vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } masterId := vbm.VBucketMap[vb][0] if masterId < 0 { return nil, nil, fmt.Errorf("go-couchbase: No master for vbucket %d", vb) } pool := b.getConnPool(masterId) conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
[ "func", "(", "b", "*", "Bucket", ")", "getConnectionToVBucket", "(", "vb", "uint32", ")", "(", "*", "memcached", ".", "Client", ",", "*", "connectionPool", ",", "error", ")", "{", "for", "{", "vbm", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "if", "len", "(", "vbm", ".", "VBucketMap", ")", "<", "int", "(", "vb", ")", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ",", "vbm", ".", "VBucketMap", ")", "\n", "}", "\n", "masterId", ":=", "vbm", ".", "VBucketMap", "[", "vb", "]", "[", "0", "]", "\n", "if", "masterId", "<", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n", "pool", ":=", "b", ".", "getConnPool", "(", "masterId", ")", "\n", "conn", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "errClosedPool", "{", "return", "conn", ",", "pool", ",", "err", "\n", "}", "\n", "// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...", "}", "\n", "}" ]
// Given a vbucket number, returns a memcached connection to it. // The connection must be returned to its pool after use.
[ "Given", "a", "vbucket", "number", "returns", "a", "memcached", "connection", "to", "it", ".", "The", "connection", "must", "be", "returned", "to", "its", "pool", "after", "use", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L425-L443
train
couchbase/go-couchbase
pools.go
getRandomConnection
func (b *Bucket) getRandomConnection() (*memcached.Client, *connectionPool, error) { for { var currentPool = 0 pools := b.getConnPools(false /* not already locked */) if len(pools) == 0 { return nil, nil, fmt.Errorf("No connection pool found") } else if len(pools) > 1 { // choose a random connection currentPool = rand.Intn(len(pools)) } // if only one pool, currentPool defaults to 0, i.e., the only pool // get the pool pool := pools[currentPool] conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
go
func (b *Bucket) getRandomConnection() (*memcached.Client, *connectionPool, error) { for { var currentPool = 0 pools := b.getConnPools(false /* not already locked */) if len(pools) == 0 { return nil, nil, fmt.Errorf("No connection pool found") } else if len(pools) > 1 { // choose a random connection currentPool = rand.Intn(len(pools)) } // if only one pool, currentPool defaults to 0, i.e., the only pool // get the pool pool := pools[currentPool] conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
[ "func", "(", "b", "*", "Bucket", ")", "getRandomConnection", "(", ")", "(", "*", "memcached", ".", "Client", ",", "*", "connectionPool", ",", "error", ")", "{", "for", "{", "var", "currentPool", "=", "0", "\n", "pools", ":=", "b", ".", "getConnPools", "(", "false", "/* not already locked */", ")", "\n", "if", "len", "(", "pools", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "if", "len", "(", "pools", ")", ">", "1", "{", "// choose a random connection", "currentPool", "=", "rand", ".", "Intn", "(", "len", "(", "pools", ")", ")", "\n", "}", "// if only one pool, currentPool defaults to 0, i.e., the only pool", "\n\n", "// get the pool", "pool", ":=", "pools", "[", "currentPool", "]", "\n", "conn", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "errClosedPool", "{", "return", "conn", ",", "pool", ",", "err", "\n", "}", "\n\n", "// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...", "}", "\n", "}" ]
// To get random documents, we need to cover all the nodes, so select // a connection at random.
[ "To", "get", "random", "documents", "we", "need", "to", "cover", "all", "the", "nodes", "so", "select", "a", "connection", "at", "random", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L448-L467
train
couchbase/go-couchbase
pools.go
ConnectWithAuth
func ConnectWithAuth(baseU string, ah AuthHandler) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = ah return c, c.parseURLResponse("/pools", &c.Info) }
go
func ConnectWithAuth(baseU string, ah AuthHandler) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = ah return c, c.parseURLResponse("/pools", &c.Info) }
[ "func", "ConnectWithAuth", "(", "baseU", "string", ",", "ah", "AuthHandler", ")", "(", "c", "Client", ",", "err", "error", ")", "{", "c", ".", "BaseURL", ",", "err", "=", "ParseURL", "(", "baseU", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "c", ".", "ah", "=", "ah", "\n\n", "return", "c", ",", "c", ".", "parseURLResponse", "(", "\"", "\"", ",", "&", "c", ".", "Info", ")", "\n", "}" ]
// ConnectWithAuth connects to a couchbase cluster with the given // authentication handler.
[ "ConnectWithAuth", "connects", "to", "a", "couchbase", "cluster", "with", "the", "given", "authentication", "handler", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L938-L946
train
couchbase/go-couchbase
pools.go
ConnectWithAuthCreds
func ConnectWithAuthCreds(baseU, username, password string) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = newBucketAuth(username, password, "") return c, c.parseURLResponse("/pools", &c.Info) }
go
func ConnectWithAuthCreds(baseU, username, password string) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = newBucketAuth(username, password, "") return c, c.parseURLResponse("/pools", &c.Info) }
[ "func", "ConnectWithAuthCreds", "(", "baseU", ",", "username", ",", "password", "string", ")", "(", "c", "Client", ",", "err", "error", ")", "{", "c", ".", "BaseURL", ",", "err", "=", "ParseURL", "(", "baseU", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "c", ".", "ah", "=", "newBucketAuth", "(", "username", ",", "password", ",", "\"", "\"", ")", "\n", "return", "c", ",", "c", ".", "parseURLResponse", "(", "\"", "\"", ",", "&", "c", ".", "Info", ")", "\n", "}" ]
// ConnectWithAuthCreds connects to a couchbase cluster with the give // authorization creds returned by cb_auth
[ "ConnectWithAuthCreds", "connects", "to", "a", "couchbase", "cluster", "with", "the", "give", "authorization", "creds", "returned", "by", "cb_auth" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L969-L977
train
couchbase/go-couchbase
pools.go
GetBucketList
func GetBucketList(baseU string) (bInfo []BucketInfo, err error) { c := &Client{} c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = basicAuthFromURL(baseU) var buckets []Bucket err = c.parseURLResponse("/pools/default/buckets", &buckets) if err != nil { return } bInfo = make([]BucketInfo, 0) for _, bucket := range buckets { bucketInfo := BucketInfo{Name: bucket.Name, Password: bucket.Password} bInfo = append(bInfo, bucketInfo) } return bInfo, err }
go
func GetBucketList(baseU string) (bInfo []BucketInfo, err error) { c := &Client{} c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = basicAuthFromURL(baseU) var buckets []Bucket err = c.parseURLResponse("/pools/default/buckets", &buckets) if err != nil { return } bInfo = make([]BucketInfo, 0) for _, bucket := range buckets { bucketInfo := BucketInfo{Name: bucket.Name, Password: bucket.Password} bInfo = append(bInfo, bucketInfo) } return bInfo, err }
[ "func", "GetBucketList", "(", "baseU", "string", ")", "(", "bInfo", "[", "]", "BucketInfo", ",", "err", "error", ")", "{", "c", ":=", "&", "Client", "{", "}", "\n", "c", ".", "BaseURL", ",", "err", "=", "ParseURL", "(", "baseU", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "c", ".", "ah", "=", "basicAuthFromURL", "(", "baseU", ")", "\n\n", "var", "buckets", "[", "]", "Bucket", "\n", "err", "=", "c", ".", "parseURLResponse", "(", "\"", "\"", ",", "&", "buckets", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "bInfo", "=", "make", "(", "[", "]", "BucketInfo", ",", "0", ")", "\n", "for", "_", ",", "bucket", ":=", "range", "buckets", "{", "bucketInfo", ":=", "BucketInfo", "{", "Name", ":", "bucket", ".", "Name", ",", "Password", ":", "bucket", ".", "Password", "}", "\n", "bInfo", "=", "append", "(", "bInfo", ",", "bucketInfo", ")", "\n", "}", "\n", "return", "bInfo", ",", "err", "\n", "}" ]
//Get SASL buckets
[ "Get", "SASL", "buckets" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L991-L1011
train
couchbase/go-couchbase
pools.go
GetCollectionsManifest
func (b *Bucket) GetCollectionsManifest() (*Manifest, error) { // Collections not used? if !EnableCollections { return nil, fmt.Errorf("Collections not enabled.") } b.RLock() pools := b.getConnPools(true /* already locked */) pool := pools[0] // Any pool will do, so use the first one. b.RUnlock() client, err := pool.Get() if err != nil { return nil, fmt.Errorf("Unable to get connection to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } // We need to select the bucket before GetCollectionsManifest() // will work. This is sometimes done at startup (see defaultMkConn()) // but not always, depending on the auth type. // Doing this is safe because we collect the the connections // by bucket, so the bucket being selected will never change. _, err = client.SelectBucket(b.Name) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to select bucket %s: %v. No collections access to bucket %s.", err, b.Name, b.Name) } res, err := client.GetCollectionsManifest() if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } mani, err := parseCollectionsManifest(res) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to parse collections manifest: %v. No collections access to bucket %s.", err, b.Name) } pool.Return(client) return mani, nil }
go
func (b *Bucket) GetCollectionsManifest() (*Manifest, error) { // Collections not used? if !EnableCollections { return nil, fmt.Errorf("Collections not enabled.") } b.RLock() pools := b.getConnPools(true /* already locked */) pool := pools[0] // Any pool will do, so use the first one. b.RUnlock() client, err := pool.Get() if err != nil { return nil, fmt.Errorf("Unable to get connection to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } // We need to select the bucket before GetCollectionsManifest() // will work. This is sometimes done at startup (see defaultMkConn()) // but not always, depending on the auth type. // Doing this is safe because we collect the the connections // by bucket, so the bucket being selected will never change. _, err = client.SelectBucket(b.Name) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to select bucket %s: %v. No collections access to bucket %s.", err, b.Name, b.Name) } res, err := client.GetCollectionsManifest() if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } mani, err := parseCollectionsManifest(res) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to parse collections manifest: %v. No collections access to bucket %s.", err, b.Name) } pool.Return(client) return mani, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetCollectionsManifest", "(", ")", "(", "*", "Manifest", ",", "error", ")", "{", "// Collections not used?", "if", "!", "EnableCollections", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "b", ".", "RLock", "(", ")", "\n", "pools", ":=", "b", ".", "getConnPools", "(", "true", "/* already locked */", ")", "\n", "pool", ":=", "pools", "[", "0", "]", "// Any pool will do, so use the first one.", "\n", "b", ".", "RUnlock", "(", ")", "\n", "client", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ")", "\n", "}", "\n\n", "// We need to select the bucket before GetCollectionsManifest()", "// will work. This is sometimes done at startup (see defaultMkConn())", "// but not always, depending on the auth type.", "// Doing this is safe because we collect the the connections", "// by bucket, so the bucket being selected will never change.", "_", ",", "err", "=", "client", ".", "SelectBucket", "(", "b", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "pool", ".", "Return", "(", "client", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ",", "b", ".", "Name", ")", "\n", "}", "\n\n", "res", ",", "err", ":=", "client", ".", "GetCollectionsManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "pool", ".", "Return", "(", "client", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ")", "\n", "}", "\n", "mani", ",", "err", ":=", "parseCollectionsManifest", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "pool", ".", "Return", "(", "client", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ")", "\n", "}", "\n\n", "pool", ".", "Return", "(", "client", ")", "\n", "return", "mani", ",", "nil", "\n", "}" ]
// This function assumes the bucket is locked.
[ "This", "function", "assumes", "the", "bucket", "is", "locked", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1152-L1191
train
couchbase/go-couchbase
pools.go
Close
func (b *Bucket) Close() { b.Lock() defer b.Unlock() if b.connPools != nil { for _, c := range b.getConnPools(true /* already locked */) { if c != nil { c.Close() } } b.connPools = nil } }
go
func (b *Bucket) Close() { b.Lock() defer b.Unlock() if b.connPools != nil { for _, c := range b.getConnPools(true /* already locked */) { if c != nil { c.Close() } } b.connPools = nil } }
[ "func", "(", "b", "*", "Bucket", ")", "Close", "(", ")", "{", "b", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "Unlock", "(", ")", "\n", "if", "b", ".", "connPools", "!=", "nil", "{", "for", "_", ",", "c", ":=", "range", "b", ".", "getConnPools", "(", "true", "/* already locked */", ")", "{", "if", "c", "!=", "nil", "{", "c", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "b", ".", "connPools", "=", "nil", "\n", "}", "\n", "}" ]
// Close marks this bucket as no longer needed, closing connections it // may have open.
[ "Close", "marks", "this", "bucket", "as", "no", "longer", "needed", "closing", "connections", "it", "may", "have", "open", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1362-L1373
train
couchbase/go-couchbase
pools.go
GetPool
func (b *Bucket) GetPool() *Pool { b.RLock() defer b.RUnlock() ret := b.pool return ret }
go
func (b *Bucket) GetPool() *Pool { b.RLock() defer b.RUnlock() ret := b.pool return ret }
[ "func", "(", "b", "*", "Bucket", ")", "GetPool", "(", ")", "*", "Pool", "{", "b", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "RUnlock", "(", ")", "\n", "ret", ":=", "b", ".", "pool", "\n", "return", "ret", "\n", "}" ]
// GetPool gets the pool to which this bucket belongs.
[ "GetPool", "gets", "the", "pool", "to", "which", "this", "bucket", "belongs", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1414-L1419
train
couchbase/go-couchbase
pools.go
Close
func (p *Pool) Close() { // fine to loop through the buckets unlocked // locking happens at the bucket level for b, _ := range p.BucketMap { // MB-33208 defer closing connection pools until the bucket is no longer used bucket := p.BucketMap[b] bucket.Lock() bucket.closed = true bucket.Unlock() } }
go
func (p *Pool) Close() { // fine to loop through the buckets unlocked // locking happens at the bucket level for b, _ := range p.BucketMap { // MB-33208 defer closing connection pools until the bucket is no longer used bucket := p.BucketMap[b] bucket.Lock() bucket.closed = true bucket.Unlock() } }
[ "func", "(", "p", "*", "Pool", ")", "Close", "(", ")", "{", "// fine to loop through the buckets unlocked", "// locking happens at the bucket level", "for", "b", ",", "_", ":=", "range", "p", ".", "BucketMap", "{", "// MB-33208 defer closing connection pools until the bucket is no longer used", "bucket", ":=", "p", ".", "BucketMap", "[", "b", "]", "\n", "bucket", ".", "Lock", "(", ")", "\n", "bucket", ".", "closed", "=", "true", "\n", "bucket", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// Release bucket connections when the pool is no longer in use
[ "Release", "bucket", "connections", "when", "the", "pool", "is", "no", "longer", "in", "use" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1427-L1438
train
couchbase/go-couchbase
pools.go
GetBucket
func GetBucket(endpoint, poolname, bucketname string) (*Bucket, error) { var err error client, err := Connect(endpoint) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
go
func GetBucket(endpoint, poolname, bucketname string) (*Bucket, error) { var err error client, err := Connect(endpoint) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
[ "func", "GetBucket", "(", "endpoint", ",", "poolname", ",", "bucketname", "string", ")", "(", "*", "Bucket", ",", "error", ")", "{", "var", "err", "error", "\n", "client", ",", "err", ":=", "Connect", "(", "endpoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pool", ",", "err", ":=", "client", ".", "GetPool", "(", "poolname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "pool", ".", "GetBucket", "(", "bucketname", ")", "\n", "}" ]
// GetBucket is a convenience function for getting a named bucket from // a URL
[ "GetBucket", "is", "a", "convenience", "function", "for", "getting", "a", "named", "bucket", "from", "a", "URL" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1442-L1455
train
couchbase/go-couchbase
pools.go
ConnectWithAuthAndGetBucket
func ConnectWithAuthAndGetBucket(endpoint, poolname, bucketname string, ah AuthHandler) (*Bucket, error) { client, err := ConnectWithAuth(endpoint, ah) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
go
func ConnectWithAuthAndGetBucket(endpoint, poolname, bucketname string, ah AuthHandler) (*Bucket, error) { client, err := ConnectWithAuth(endpoint, ah) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
[ "func", "ConnectWithAuthAndGetBucket", "(", "endpoint", ",", "poolname", ",", "bucketname", "string", ",", "ah", "AuthHandler", ")", "(", "*", "Bucket", ",", "error", ")", "{", "client", ",", "err", ":=", "ConnectWithAuth", "(", "endpoint", ",", "ah", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pool", ",", "err", ":=", "client", ".", "GetPool", "(", "poolname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "pool", ".", "GetBucket", "(", "bucketname", ")", "\n", "}" ]
// ConnectWithAuthAndGetBucket is a convenience function for // getting a named bucket from a given URL and an auth callback
[ "ConnectWithAuthAndGetBucket", "is", "a", "convenience", "function", "for", "getting", "a", "named", "bucket", "from", "a", "given", "URL", "and", "an", "auth", "callback" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1459-L1472
train