repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | SetAfterConnectHandler | func (c *Client) SetAfterConnectHandler(h handler) {
c.Lock()
defer c.Unlock()
c.afterConnect = h
} | go | func (c *Client) SetAfterConnectHandler(h handler) {
c.Lock()
defer c.Unlock()
c.afterConnect = h
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetAfterConnectHandler",
"(",
"h",
"handler",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"afterConnect",
"=",
"h",
"\n",
"}"
] | // SetAfterConnectHandler registers a handler that is called
// after the client connects to the event server. This allows for
// custom code to be executed for a particular
// event client implementation. | [
"SetAfterConnectHandler",
"registers",
"a",
"handler",
"that",
"is",
"called",
"after",
"the",
"client",
"connects",
"to",
"the",
"event",
"server",
".",
"This",
"allows",
"for",
"custom",
"code",
"to",
"be",
"executed",
"for",
"a",
"particular",
"event",
"client",
"implementation",
"."
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L70-L74 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | SetBeforeReconnectHandler | func (c *Client) SetBeforeReconnectHandler(h handler) {
c.Lock()
defer c.Unlock()
c.beforeReconnect = h
} | go | func (c *Client) SetBeforeReconnectHandler(h handler) {
c.Lock()
defer c.Unlock()
c.beforeReconnect = h
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetBeforeReconnectHandler",
"(",
"h",
"handler",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"beforeReconnect",
"=",
"h",
"\n",
"}"
] | // SetBeforeReconnectHandler registers a handler that will be called
// before retrying to reconnect to the event server. This allows for
// custom code to be executed for a particular event client implementation. | [
"SetBeforeReconnectHandler",
"registers",
"a",
"handler",
"that",
"will",
"be",
"called",
"before",
"retrying",
"to",
"reconnect",
"to",
"the",
"event",
"server",
".",
"This",
"allows",
"for",
"custom",
"code",
"to",
"be",
"executed",
"for",
"a",
"particular",
"event",
"client",
"implementation",
"."
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L85-L89 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | Connect | func (c *Client) Connect() error {
if c.maxConnAttempts == 1 {
return c.connect()
}
return c.connectWithRetry(c.maxConnAttempts, c.timeBetweenConnAttempts)
} | go | func (c *Client) Connect() error {
if c.maxConnAttempts == 1 {
return c.connect()
}
return c.connectWithRetry(c.maxConnAttempts, c.timeBetweenConnAttempts)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Connect",
"(",
")",
"error",
"{",
"if",
"c",
".",
"maxConnAttempts",
"==",
"1",
"{",
"return",
"c",
".",
"connect",
"(",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"connectWithRetry",
"(",
"c",
".",
"maxConnAttempts",
",",
"c",
".",
"timeBetweenConnAttempts",
")",
"\n",
"}"
] | // Connect connects to the peer and registers for events on a particular channel. | [
"Connect",
"connects",
"to",
"the",
"peer",
"and",
"registers",
"for",
"events",
"on",
"a",
"particular",
"channel",
"."
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L98-L103 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | CloseIfIdle | func (c *Client) CloseIfIdle() bool {
logger.Debug("Attempting to close event client...")
// Check if there are any outstanding registrations
regInfoCh := make(chan *esdispatcher.RegistrationInfo)
err := c.Submit(esdispatcher.NewRegistrationInfoEvent(regInfoCh))
if err != nil {
logger.Debugf("Submit failed %s", err)
return false
}
regInfo := <-regInfoCh
logger.Debugf("Outstanding registrations: %d", regInfo.TotalRegistrations)
if regInfo.TotalRegistrations > 0 {
logger.Debugf("Cannot stop client since there are %d outstanding registrations", regInfo.TotalRegistrations)
return false
}
c.Close()
return true
} | go | func (c *Client) CloseIfIdle() bool {
logger.Debug("Attempting to close event client...")
// Check if there are any outstanding registrations
regInfoCh := make(chan *esdispatcher.RegistrationInfo)
err := c.Submit(esdispatcher.NewRegistrationInfoEvent(regInfoCh))
if err != nil {
logger.Debugf("Submit failed %s", err)
return false
}
regInfo := <-regInfoCh
logger.Debugf("Outstanding registrations: %d", regInfo.TotalRegistrations)
if regInfo.TotalRegistrations > 0 {
logger.Debugf("Cannot stop client since there are %d outstanding registrations", regInfo.TotalRegistrations)
return false
}
c.Close()
return true
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CloseIfIdle",
"(",
")",
"bool",
"{",
"logger",
".",
"Debug",
"(",
"\"Attempting to close event client...\"",
")",
"\n",
"regInfoCh",
":=",
"make",
"(",
"chan",
"*",
"esdispatcher",
".",
"RegistrationInfo",
")",
"\n",
"err",
":=",
"c",
".",
"Submit",
"(",
"esdispatcher",
".",
"NewRegistrationInfoEvent",
"(",
"regInfoCh",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"Submit failed %s\"",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"regInfo",
":=",
"<-",
"regInfoCh",
"\n",
"logger",
".",
"Debugf",
"(",
"\"Outstanding registrations: %d\"",
",",
"regInfo",
".",
"TotalRegistrations",
")",
"\n",
"if",
"regInfo",
".",
"TotalRegistrations",
">",
"0",
"{",
"logger",
".",
"Debugf",
"(",
"\"Cannot stop client since there are %d outstanding registrations\"",
",",
"regInfo",
".",
"TotalRegistrations",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"c",
".",
"Close",
"(",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // CloseIfIdle closes the connection to the event server only if there are no outstanding
// registrations.
// Returns true if the client was closed. In this case the client may no longer be used.
// A return value of false indicates that the client could not be closed since
// there was at least one registration. | [
"CloseIfIdle",
"closes",
"the",
"connection",
"to",
"the",
"event",
"server",
"only",
"if",
"there",
"are",
"no",
"outstanding",
"registrations",
".",
"Returns",
"true",
"if",
"the",
"client",
"was",
"closed",
".",
"In",
"this",
"case",
"the",
"client",
"may",
"no",
"longer",
"be",
"used",
".",
"A",
"return",
"value",
"of",
"false",
"indicates",
"that",
"the",
"client",
"could",
"not",
"be",
"closed",
"since",
"there",
"was",
"at",
"least",
"one",
"registration",
"."
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L110-L132 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | TransferRegistrations | func (c *Client) TransferRegistrations(close bool) (fab.EventSnapshot, error) {
if !close {
return c.Transfer()
}
var snapshot fab.EventSnapshot
var err error
c.close(func() {
logger.Debug("Stopping dispatcher and taking snapshot of all registrations...")
snapshot, err = c.StopAndTransfer()
if err != nil {
logger.Errorf("An error occurred while stopping dispatcher and taking snapshot: %s", err)
}
})
return snapshot, err
} | go | func (c *Client) TransferRegistrations(close bool) (fab.EventSnapshot, error) {
if !close {
return c.Transfer()
}
var snapshot fab.EventSnapshot
var err error
c.close(func() {
logger.Debug("Stopping dispatcher and taking snapshot of all registrations...")
snapshot, err = c.StopAndTransfer()
if err != nil {
logger.Errorf("An error occurred while stopping dispatcher and taking snapshot: %s", err)
}
})
return snapshot, err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"TransferRegistrations",
"(",
"close",
"bool",
")",
"(",
"fab",
".",
"EventSnapshot",
",",
"error",
")",
"{",
"if",
"!",
"close",
"{",
"return",
"c",
".",
"Transfer",
"(",
")",
"\n",
"}",
"\n",
"var",
"snapshot",
"fab",
".",
"EventSnapshot",
"\n",
"var",
"err",
"error",
"\n",
"c",
".",
"close",
"(",
"func",
"(",
")",
"{",
"logger",
".",
"Debug",
"(",
"\"Stopping dispatcher and taking snapshot of all registrations...\"",
")",
"\n",
"snapshot",
",",
"err",
"=",
"c",
".",
"StopAndTransfer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"An error occurred while stopping dispatcher and taking snapshot: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"snapshot",
",",
"err",
"\n",
"}"
] | // TransferRegistrations transfers all registrations into an EventSnapshot.
// The registrations are not closed and may susequently be transferred to a
// new event client.
// - close - if true then the client will also be closed | [
"TransferRegistrations",
"transfers",
"all",
"registrations",
"into",
"an",
"EventSnapshot",
".",
"The",
"registrations",
"are",
"not",
"closed",
"and",
"may",
"susequently",
"be",
"transferred",
"to",
"a",
"new",
"event",
"client",
".",
"-",
"close",
"-",
"if",
"true",
"then",
"the",
"client",
"will",
"also",
"be",
"closed"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L146-L162 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | registerConnectionEvent | func (c *Client) registerConnectionEvent() (fab.Registration, chan *dispatcher.ConnectionEvent, error) {
if c.Stopped() {
return nil, nil, errors.New("event client is closed")
}
eventch := make(chan *dispatcher.ConnectionEvent, c.eventConsumerBufferSize)
errch := make(chan error)
regch := make(chan fab.Registration)
err1 := c.Submit(dispatcher.NewRegisterConnectionEvent(eventch, regch, errch))
if err1 != nil {
return nil, nil, err1
}
select {
case reg := <-regch:
return reg, eventch, nil
case err := <-errch:
return nil, nil, err
}
} | go | func (c *Client) registerConnectionEvent() (fab.Registration, chan *dispatcher.ConnectionEvent, error) {
if c.Stopped() {
return nil, nil, errors.New("event client is closed")
}
eventch := make(chan *dispatcher.ConnectionEvent, c.eventConsumerBufferSize)
errch := make(chan error)
regch := make(chan fab.Registration)
err1 := c.Submit(dispatcher.NewRegisterConnectionEvent(eventch, regch, errch))
if err1 != nil {
return nil, nil, err1
}
select {
case reg := <-regch:
return reg, eventch, nil
case err := <-errch:
return nil, nil, err
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"registerConnectionEvent",
"(",
")",
"(",
"fab",
".",
"Registration",
",",
"chan",
"*",
"dispatcher",
".",
"ConnectionEvent",
",",
"error",
")",
"{",
"if",
"c",
".",
"Stopped",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"event client is closed\"",
")",
"\n",
"}",
"\n",
"eventch",
":=",
"make",
"(",
"chan",
"*",
"dispatcher",
".",
"ConnectionEvent",
",",
"c",
".",
"eventConsumerBufferSize",
")",
"\n",
"errch",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"regch",
":=",
"make",
"(",
"chan",
"fab",
".",
"Registration",
")",
"\n",
"err1",
":=",
"c",
".",
"Submit",
"(",
"dispatcher",
".",
"NewRegisterConnectionEvent",
"(",
"eventch",
",",
"regch",
",",
"errch",
")",
")",
"\n",
"if",
"err1",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err1",
"\n",
"}",
"\n",
"select",
"{",
"case",
"reg",
":=",
"<-",
"regch",
":",
"return",
"reg",
",",
"eventch",
",",
"nil",
"\n",
"case",
"err",
":=",
"<-",
"errch",
":",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // registerConnectionEvent registers a connection event. The returned
// ConnectionEvent channel will be called whenever the client clients or disconnects
// from the event server | [
"registerConnectionEvent",
"registers",
"a",
"connection",
"event",
".",
"The",
"returned",
"ConnectionEvent",
"channel",
"will",
"be",
"called",
"whenever",
"the",
"client",
"clients",
"or",
"disconnects",
"from",
"the",
"event",
"server"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L319-L337 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/client.go | setConnectionState | func (c *Client) setConnectionState(currentState, newState ConnectionState) bool {
return atomic.CompareAndSwapInt32(&c.connectionState, int32(currentState), int32(newState))
} | go | func (c *Client) setConnectionState(currentState, newState ConnectionState) bool {
return atomic.CompareAndSwapInt32(&c.connectionState, int32(currentState), int32(newState))
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"setConnectionState",
"(",
"currentState",
",",
"newState",
"ConnectionState",
")",
"bool",
"{",
"return",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"c",
".",
"connectionState",
",",
"int32",
"(",
"currentState",
")",
",",
"int32",
"(",
"newState",
")",
")",
"\n",
"}"
] | // setConnectionState sets the connection state only if the given currentState
// matches the actual state. True is returned if the connection state was successfully set. | [
"setConnectionState",
"sets",
"the",
"connection",
"state",
"only",
"if",
"the",
"given",
"currentState",
"matches",
"the",
"actual",
"state",
".",
"True",
"is",
"returned",
"if",
"the",
"connection",
"state",
"was",
"successfully",
"set",
"."
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/client.go#L356-L358 | train |
hyperledger/fabric-sdk-go | pkg/client/channel/invoke/txnhandler.go | Handle | func (e *EndorsementHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
if len(requestContext.Opts.Targets) == 0 {
requestContext.Error = status.New(status.ClientStatus, status.NoPeersFound.ToInt32(), "targets were not provided", nil)
return
}
// Endorse Tx
var TxnHeaderOpts []fab.TxnHeaderOpt
if e.headerOptsProvider != nil {
TxnHeaderOpts = e.headerOptsProvider()
}
transactionProposalResponses, proposal, err := createAndSendTransactionProposal(
clientContext.Transactor,
&requestContext.Request,
peer.PeersToTxnProcessors(requestContext.Opts.Targets),
TxnHeaderOpts...,
)
requestContext.Response.Proposal = proposal
requestContext.Response.TransactionID = proposal.TxnID // TODO: still needed?
if err != nil {
requestContext.Error = err
return
}
requestContext.Response.Responses = transactionProposalResponses
if len(transactionProposalResponses) > 0 {
requestContext.Response.Payload = transactionProposalResponses[0].ProposalResponse.GetResponse().Payload
requestContext.Response.ChaincodeStatus = transactionProposalResponses[0].ChaincodeStatus
}
//Delegate to next step if any
if e.next != nil {
e.next.Handle(requestContext, clientContext)
}
} | go | func (e *EndorsementHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
if len(requestContext.Opts.Targets) == 0 {
requestContext.Error = status.New(status.ClientStatus, status.NoPeersFound.ToInt32(), "targets were not provided", nil)
return
}
// Endorse Tx
var TxnHeaderOpts []fab.TxnHeaderOpt
if e.headerOptsProvider != nil {
TxnHeaderOpts = e.headerOptsProvider()
}
transactionProposalResponses, proposal, err := createAndSendTransactionProposal(
clientContext.Transactor,
&requestContext.Request,
peer.PeersToTxnProcessors(requestContext.Opts.Targets),
TxnHeaderOpts...,
)
requestContext.Response.Proposal = proposal
requestContext.Response.TransactionID = proposal.TxnID // TODO: still needed?
if err != nil {
requestContext.Error = err
return
}
requestContext.Response.Responses = transactionProposalResponses
if len(transactionProposalResponses) > 0 {
requestContext.Response.Payload = transactionProposalResponses[0].ProposalResponse.GetResponse().Payload
requestContext.Response.ChaincodeStatus = transactionProposalResponses[0].ChaincodeStatus
}
//Delegate to next step if any
if e.next != nil {
e.next.Handle(requestContext, clientContext)
}
} | [
"func",
"(",
"e",
"*",
"EndorsementHandler",
")",
"Handle",
"(",
"requestContext",
"*",
"RequestContext",
",",
"clientContext",
"*",
"ClientContext",
")",
"{",
"if",
"len",
"(",
"requestContext",
".",
"Opts",
".",
"Targets",
")",
"==",
"0",
"{",
"requestContext",
".",
"Error",
"=",
"status",
".",
"New",
"(",
"status",
".",
"ClientStatus",
",",
"status",
".",
"NoPeersFound",
".",
"ToInt32",
"(",
")",
",",
"\"targets were not provided\"",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"TxnHeaderOpts",
"[",
"]",
"fab",
".",
"TxnHeaderOpt",
"\n",
"if",
"e",
".",
"headerOptsProvider",
"!=",
"nil",
"{",
"TxnHeaderOpts",
"=",
"e",
".",
"headerOptsProvider",
"(",
")",
"\n",
"}",
"\n",
"transactionProposalResponses",
",",
"proposal",
",",
"err",
":=",
"createAndSendTransactionProposal",
"(",
"clientContext",
".",
"Transactor",
",",
"&",
"requestContext",
".",
"Request",
",",
"peer",
".",
"PeersToTxnProcessors",
"(",
"requestContext",
".",
"Opts",
".",
"Targets",
")",
",",
"TxnHeaderOpts",
"...",
",",
")",
"\n",
"requestContext",
".",
"Response",
".",
"Proposal",
"=",
"proposal",
"\n",
"requestContext",
".",
"Response",
".",
"TransactionID",
"=",
"proposal",
".",
"TxnID",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"requestContext",
".",
"Error",
"=",
"err",
"\n",
"return",
"\n",
"}",
"\n",
"requestContext",
".",
"Response",
".",
"Responses",
"=",
"transactionProposalResponses",
"\n",
"if",
"len",
"(",
"transactionProposalResponses",
")",
">",
"0",
"{",
"requestContext",
".",
"Response",
".",
"Payload",
"=",
"transactionProposalResponses",
"[",
"0",
"]",
".",
"ProposalResponse",
".",
"GetResponse",
"(",
")",
".",
"Payload",
"\n",
"requestContext",
".",
"Response",
".",
"ChaincodeStatus",
"=",
"transactionProposalResponses",
"[",
"0",
"]",
".",
"ChaincodeStatus",
"\n",
"}",
"\n",
"if",
"e",
".",
"next",
"!=",
"nil",
"{",
"e",
".",
"next",
".",
"Handle",
"(",
"requestContext",
",",
"clientContext",
")",
"\n",
"}",
"\n",
"}"
] | //Handle for endorsing transactions | [
"Handle",
"for",
"endorsing",
"transactions"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/client/channel/invoke/txnhandler.go#L35-L73 | train |
hyperledger/fabric-sdk-go | pkg/client/channel/invoke/txnhandler.go | Handle | func (h *ProposalProcessorHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
//Get proposal processor, if not supplied then use selection service to get available peers as endorser
if len(requestContext.Opts.Targets) == 0 {
var selectionOpts []options.Opt
if requestContext.SelectionFilter != nil {
selectionOpts = append(selectionOpts, selectopts.WithPeerFilter(requestContext.SelectionFilter))
}
if requestContext.PeerSorter != nil {
selectionOpts = append(selectionOpts, selectopts.WithPeerSorter(requestContext.PeerSorter))
}
endorsers, err := clientContext.Selection.GetEndorsersForChaincode(newInvocationChain(requestContext), selectionOpts...)
if err != nil {
requestContext.Error = errors.WithMessage(err, "Failed to get endorsing peers")
return
}
requestContext.Opts.Targets = endorsers
}
//Delegate to next step if any
if h.next != nil {
h.next.Handle(requestContext, clientContext)
}
} | go | func (h *ProposalProcessorHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
//Get proposal processor, if not supplied then use selection service to get available peers as endorser
if len(requestContext.Opts.Targets) == 0 {
var selectionOpts []options.Opt
if requestContext.SelectionFilter != nil {
selectionOpts = append(selectionOpts, selectopts.WithPeerFilter(requestContext.SelectionFilter))
}
if requestContext.PeerSorter != nil {
selectionOpts = append(selectionOpts, selectopts.WithPeerSorter(requestContext.PeerSorter))
}
endorsers, err := clientContext.Selection.GetEndorsersForChaincode(newInvocationChain(requestContext), selectionOpts...)
if err != nil {
requestContext.Error = errors.WithMessage(err, "Failed to get endorsing peers")
return
}
requestContext.Opts.Targets = endorsers
}
//Delegate to next step if any
if h.next != nil {
h.next.Handle(requestContext, clientContext)
}
} | [
"func",
"(",
"h",
"*",
"ProposalProcessorHandler",
")",
"Handle",
"(",
"requestContext",
"*",
"RequestContext",
",",
"clientContext",
"*",
"ClientContext",
")",
"{",
"if",
"len",
"(",
"requestContext",
".",
"Opts",
".",
"Targets",
")",
"==",
"0",
"{",
"var",
"selectionOpts",
"[",
"]",
"options",
".",
"Opt",
"\n",
"if",
"requestContext",
".",
"SelectionFilter",
"!=",
"nil",
"{",
"selectionOpts",
"=",
"append",
"(",
"selectionOpts",
",",
"selectopts",
".",
"WithPeerFilter",
"(",
"requestContext",
".",
"SelectionFilter",
")",
")",
"\n",
"}",
"\n",
"if",
"requestContext",
".",
"PeerSorter",
"!=",
"nil",
"{",
"selectionOpts",
"=",
"append",
"(",
"selectionOpts",
",",
"selectopts",
".",
"WithPeerSorter",
"(",
"requestContext",
".",
"PeerSorter",
")",
")",
"\n",
"}",
"\n",
"endorsers",
",",
"err",
":=",
"clientContext",
".",
"Selection",
".",
"GetEndorsersForChaincode",
"(",
"newInvocationChain",
"(",
"requestContext",
")",
",",
"selectionOpts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"requestContext",
".",
"Error",
"=",
"errors",
".",
"WithMessage",
"(",
"err",
",",
"\"Failed to get endorsing peers\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"requestContext",
".",
"Opts",
".",
"Targets",
"=",
"endorsers",
"\n",
"}",
"\n",
"if",
"h",
".",
"next",
"!=",
"nil",
"{",
"h",
".",
"next",
".",
"Handle",
"(",
"requestContext",
",",
"clientContext",
")",
"\n",
"}",
"\n",
"}"
] | //Handle selects proposal processors | [
"Handle",
"selects",
"proposal",
"processors"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/client/channel/invoke/txnhandler.go#L81-L104 | train |
hyperledger/fabric-sdk-go | pkg/client/channel/invoke/txnhandler.go | Handle | func (f *EndorsementValidationHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
//Filter tx proposal responses
err := f.validate(requestContext.Response.Responses)
if err != nil {
requestContext.Error = errors.WithMessage(err, "endorsement validation failed")
return
}
//Delegate to next step if any
if f.next != nil {
f.next.Handle(requestContext, clientContext)
}
} | go | func (f *EndorsementValidationHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
//Filter tx proposal responses
err := f.validate(requestContext.Response.Responses)
if err != nil {
requestContext.Error = errors.WithMessage(err, "endorsement validation failed")
return
}
//Delegate to next step if any
if f.next != nil {
f.next.Handle(requestContext, clientContext)
}
} | [
"func",
"(",
"f",
"*",
"EndorsementValidationHandler",
")",
"Handle",
"(",
"requestContext",
"*",
"RequestContext",
",",
"clientContext",
"*",
"ClientContext",
")",
"{",
"err",
":=",
"f",
".",
"validate",
"(",
"requestContext",
".",
"Response",
".",
"Responses",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"requestContext",
".",
"Error",
"=",
"errors",
".",
"WithMessage",
"(",
"err",
",",
"\"endorsement validation failed\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"f",
".",
"next",
"!=",
"nil",
"{",
"f",
".",
"next",
".",
"Handle",
"(",
"requestContext",
",",
"clientContext",
")",
"\n",
"}",
"\n",
"}"
] | //Handle for Filtering proposal response | [
"Handle",
"for",
"Filtering",
"proposal",
"response"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/client/channel/invoke/txnhandler.go#L124-L137 | train |
hyperledger/fabric-sdk-go | pkg/client/channel/invoke/txnhandler.go | Handle | func (c *CommitTxHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
txnID := requestContext.Response.TransactionID
//Register Tx event
reg, statusNotifier, err := clientContext.EventService.RegisterTxStatusEvent(string(txnID)) // TODO: Change func to use TransactionID instead of string
if err != nil {
requestContext.Error = errors.Wrap(err, "error registering for TxStatus event")
return
}
defer clientContext.EventService.Unregister(reg)
_, err = createAndSendTransaction(clientContext.Transactor, requestContext.Response.Proposal, requestContext.Response.Responses)
if err != nil {
requestContext.Error = errors.Wrap(err, "CreateAndSendTransaction failed")
return
}
select {
case txStatus := <-statusNotifier:
requestContext.Response.TxValidationCode = txStatus.TxValidationCode
if txStatus.TxValidationCode != pb.TxValidationCode_VALID {
requestContext.Error = status.New(status.EventServerStatus, int32(txStatus.TxValidationCode),
"received invalid transaction", nil)
return
}
case <-requestContext.Ctx.Done():
requestContext.Error = status.New(status.ClientStatus, status.Timeout.ToInt32(),
"Execute didn't receive block event", nil)
return
}
//Delegate to next step if any
if c.next != nil {
c.next.Handle(requestContext, clientContext)
}
} | go | func (c *CommitTxHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
txnID := requestContext.Response.TransactionID
//Register Tx event
reg, statusNotifier, err := clientContext.EventService.RegisterTxStatusEvent(string(txnID)) // TODO: Change func to use TransactionID instead of string
if err != nil {
requestContext.Error = errors.Wrap(err, "error registering for TxStatus event")
return
}
defer clientContext.EventService.Unregister(reg)
_, err = createAndSendTransaction(clientContext.Transactor, requestContext.Response.Proposal, requestContext.Response.Responses)
if err != nil {
requestContext.Error = errors.Wrap(err, "CreateAndSendTransaction failed")
return
}
select {
case txStatus := <-statusNotifier:
requestContext.Response.TxValidationCode = txStatus.TxValidationCode
if txStatus.TxValidationCode != pb.TxValidationCode_VALID {
requestContext.Error = status.New(status.EventServerStatus, int32(txStatus.TxValidationCode),
"received invalid transaction", nil)
return
}
case <-requestContext.Ctx.Done():
requestContext.Error = status.New(status.ClientStatus, status.Timeout.ToInt32(),
"Execute didn't receive block event", nil)
return
}
//Delegate to next step if any
if c.next != nil {
c.next.Handle(requestContext, clientContext)
}
} | [
"func",
"(",
"c",
"*",
"CommitTxHandler",
")",
"Handle",
"(",
"requestContext",
"*",
"RequestContext",
",",
"clientContext",
"*",
"ClientContext",
")",
"{",
"txnID",
":=",
"requestContext",
".",
"Response",
".",
"TransactionID",
"\n",
"reg",
",",
"statusNotifier",
",",
"err",
":=",
"clientContext",
".",
"EventService",
".",
"RegisterTxStatusEvent",
"(",
"string",
"(",
"txnID",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"requestContext",
".",
"Error",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"error registering for TxStatus event\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"clientContext",
".",
"EventService",
".",
"Unregister",
"(",
"reg",
")",
"\n",
"_",
",",
"err",
"=",
"createAndSendTransaction",
"(",
"clientContext",
".",
"Transactor",
",",
"requestContext",
".",
"Response",
".",
"Proposal",
",",
"requestContext",
".",
"Response",
".",
"Responses",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"requestContext",
".",
"Error",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"CreateAndSendTransaction failed\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"select",
"{",
"case",
"txStatus",
":=",
"<-",
"statusNotifier",
":",
"requestContext",
".",
"Response",
".",
"TxValidationCode",
"=",
"txStatus",
".",
"TxValidationCode",
"\n",
"if",
"txStatus",
".",
"TxValidationCode",
"!=",
"pb",
".",
"TxValidationCode_VALID",
"{",
"requestContext",
".",
"Error",
"=",
"status",
".",
"New",
"(",
"status",
".",
"EventServerStatus",
",",
"int32",
"(",
"txStatus",
".",
"TxValidationCode",
")",
",",
"\"received invalid transaction\"",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"case",
"<-",
"requestContext",
".",
"Ctx",
".",
"Done",
"(",
")",
":",
"requestContext",
".",
"Error",
"=",
"status",
".",
"New",
"(",
"status",
".",
"ClientStatus",
",",
"status",
".",
"Timeout",
".",
"ToInt32",
"(",
")",
",",
"\"Execute didn't receive block event\"",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"c",
".",
"next",
"!=",
"nil",
"{",
"c",
".",
"next",
".",
"Handle",
"(",
"requestContext",
",",
"clientContext",
")",
"\n",
"}",
"\n",
"}"
] | //Handle handles commit tx | [
"Handle",
"handles",
"commit",
"tx"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/client/channel/invoke/txnhandler.go#L167-L203 | train |
hyperledger/fabric-sdk-go | pkg/client/channel/invoke/txnhandler.go | NewEndorsementHandlerWithOpts | func NewEndorsementHandlerWithOpts(next Handler, provider TxnHeaderOptsProvider) *EndorsementHandler {
return &EndorsementHandler{next: next, headerOptsProvider: provider}
} | go | func NewEndorsementHandlerWithOpts(next Handler, provider TxnHeaderOptsProvider) *EndorsementHandler {
return &EndorsementHandler{next: next, headerOptsProvider: provider}
} | [
"func",
"NewEndorsementHandlerWithOpts",
"(",
"next",
"Handler",
",",
"provider",
"TxnHeaderOptsProvider",
")",
"*",
"EndorsementHandler",
"{",
"return",
"&",
"EndorsementHandler",
"{",
"next",
":",
"next",
",",
"headerOptsProvider",
":",
"provider",
"}",
"\n",
"}"
] | //NewEndorsementHandlerWithOpts returns a handler that endorses a transaction proposal | [
"NewEndorsementHandlerWithOpts",
"returns",
"a",
"handler",
"that",
"endorses",
"a",
"transaction",
"proposal"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/client/channel/invoke/txnhandler.go#L236-L238 | train |
hyperledger/fabric-sdk-go | pkg/fab/events/client/lbp/roundrobin.go | Choose | func (lbp *RoundRobin) Choose(peers []fab.Peer) (fab.Peer, error) {
if len(peers) == 0 {
logger.Warn("No peers to choose from!")
return nil, nil
}
return peers[lbp.counter.Next(len(peers))], nil
} | go | func (lbp *RoundRobin) Choose(peers []fab.Peer) (fab.Peer, error) {
if len(peers) == 0 {
logger.Warn("No peers to choose from!")
return nil, nil
}
return peers[lbp.counter.Next(len(peers))], nil
} | [
"func",
"(",
"lbp",
"*",
"RoundRobin",
")",
"Choose",
"(",
"peers",
"[",
"]",
"fab",
".",
"Peer",
")",
"(",
"fab",
".",
"Peer",
",",
"error",
")",
"{",
"if",
"len",
"(",
"peers",
")",
"==",
"0",
"{",
"logger",
".",
"Warn",
"(",
"\"No peers to choose from!\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"peers",
"[",
"lbp",
".",
"counter",
".",
"Next",
"(",
"len",
"(",
"peers",
")",
")",
"]",
",",
"nil",
"\n",
"}"
] | // Choose chooses from the list of peers in round-robin fashion | [
"Choose",
"chooses",
"from",
"the",
"list",
"of",
"peers",
"in",
"round",
"-",
"robin",
"fashion"
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/events/client/lbp/roundrobin.go#L28-L34 | train |
hyperledger/fabric-sdk-go | pkg/fab/signingmgr/signingmgr.go | New | func New(cryptoProvider core.CryptoSuite) (*SigningManager, error) {
return &SigningManager{cryptoProvider: cryptoProvider, hashOpts: cryptosuite.GetSHAOpts()}, nil
} | go | func New(cryptoProvider core.CryptoSuite) (*SigningManager, error) {
return &SigningManager{cryptoProvider: cryptoProvider, hashOpts: cryptosuite.GetSHAOpts()}, nil
} | [
"func",
"New",
"(",
"cryptoProvider",
"core",
".",
"CryptoSuite",
")",
"(",
"*",
"SigningManager",
",",
"error",
")",
"{",
"return",
"&",
"SigningManager",
"{",
"cryptoProvider",
":",
"cryptoProvider",
",",
"hashOpts",
":",
"cryptosuite",
".",
"GetSHAOpts",
"(",
")",
"}",
",",
"nil",
"\n",
"}"
] | // New Constructor for a signing manager.
// @param {BCCSP} cryptoProvider - crypto provider
// @param {Config} config - configuration provider
// @returns {SigningManager} new signing manager | [
"New",
"Constructor",
"for",
"a",
"signing",
"manager",
"."
] | 48bb0d199e2cee03ad3af0a413bdfc064fc69bfe | https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/signingmgr/signingmgr.go#L27-L29 | train |
gobuffalo/packr | box.go | NewBox | func NewBox(path string) Box {
var cd string
if !filepath.IsAbs(path) {
_, filename, _, _ := runtime.Caller(1)
cd = filepath.Dir(filename)
}
// this little hack courtesy of the `-cover` flag!!
cov := filepath.Join("_test", "_obj_test")
cd = strings.Replace(cd, string(filepath.Separator)+cov, "", 1)
if !filepath.IsAbs(cd) && cd != "" {
cd = filepath.Join(GoPath(), "src", cd)
}
return Box{
Path: path,
callingDir: cd,
data: map[string][]byte{},
}
} | go | func NewBox(path string) Box {
var cd string
if !filepath.IsAbs(path) {
_, filename, _, _ := runtime.Caller(1)
cd = filepath.Dir(filename)
}
// this little hack courtesy of the `-cover` flag!!
cov := filepath.Join("_test", "_obj_test")
cd = strings.Replace(cd, string(filepath.Separator)+cov, "", 1)
if !filepath.IsAbs(cd) && cd != "" {
cd = filepath.Join(GoPath(), "src", cd)
}
return Box{
Path: path,
callingDir: cd,
data: map[string][]byte{},
}
} | [
"func",
"NewBox",
"(",
"path",
"string",
")",
"Box",
"{",
"var",
"cd",
"string",
"\n",
"if",
"!",
"filepath",
".",
"IsAbs",
"(",
"path",
")",
"{",
"_",
",",
"filename",
",",
"_",
",",
"_",
":=",
"runtime",
".",
"Caller",
"(",
"1",
")",
"\n",
"cd",
"=",
"filepath",
".",
"Dir",
"(",
"filename",
")",
"\n",
"}",
"\n",
"cov",
":=",
"filepath",
".",
"Join",
"(",
"\"_test\"",
",",
"\"_obj_test\"",
")",
"\n",
"cd",
"=",
"strings",
".",
"Replace",
"(",
"cd",
",",
"string",
"(",
"filepath",
".",
"Separator",
")",
"+",
"cov",
",",
"\"\"",
",",
"1",
")",
"\n",
"if",
"!",
"filepath",
".",
"IsAbs",
"(",
"cd",
")",
"&&",
"cd",
"!=",
"\"\"",
"{",
"cd",
"=",
"filepath",
".",
"Join",
"(",
"GoPath",
"(",
")",
",",
"\"src\"",
",",
"cd",
")",
"\n",
"}",
"\n",
"return",
"Box",
"{",
"Path",
":",
"path",
",",
"callingDir",
":",
"cd",
",",
"data",
":",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
"{",
"}",
",",
"}",
"\n",
"}"
] | // NewBox returns a Box that can be used to
// retrieve files from either disk or the embedded
// binary. | [
"NewBox",
"returns",
"a",
"Box",
"that",
"can",
"be",
"used",
"to",
"retrieve",
"files",
"from",
"either",
"disk",
"or",
"the",
"embedded",
"binary",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/box.go#L35-L54 | train |
gobuffalo/packr | v2/jam/parser/box.go | String | func (b Box) String() string {
x, _ := json.Marshal(b)
return string(x)
} | go | func (b Box) String() string {
x, _ := json.Marshal(b)
return string(x)
} | [
"func",
"(",
"b",
"Box",
")",
"String",
"(",
")",
"string",
"{",
"x",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"b",
")",
"\n",
"return",
"string",
"(",
"x",
")",
"\n",
"}"
] | // String - json returned | [
"String",
"-",
"json",
"returned"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/parser/box.go#L22-L25 | train |
gobuffalo/packr | v2/jam/parser/box.go | NewBox | func NewBox(name string, path string) *Box {
if len(name) == 0 {
name = path
}
name = strings.Replace(name, "\"", "", -1)
pwd, _ := os.Getwd()
box := &Box{
Name: name,
Path: path,
PWD: pwd,
}
return box
} | go | func NewBox(name string, path string) *Box {
if len(name) == 0 {
name = path
}
name = strings.Replace(name, "\"", "", -1)
pwd, _ := os.Getwd()
box := &Box{
Name: name,
Path: path,
PWD: pwd,
}
return box
} | [
"func",
"NewBox",
"(",
"name",
"string",
",",
"path",
"string",
")",
"*",
"Box",
"{",
"if",
"len",
"(",
"name",
")",
"==",
"0",
"{",
"name",
"=",
"path",
"\n",
"}",
"\n",
"name",
"=",
"strings",
".",
"Replace",
"(",
"name",
",",
"\"\\\"\"",
",",
"\\\"",
",",
"\"\"",
")",
"\n",
"-",
"1",
"\n",
"pwd",
",",
"_",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"box",
":=",
"&",
"Box",
"{",
"Name",
":",
"name",
",",
"Path",
":",
"path",
",",
"PWD",
":",
"pwd",
",",
"}",
"\n",
"}"
] | // NewBox stub from the name and the path provided | [
"NewBox",
"stub",
"from",
"the",
"name",
"and",
"the",
"path",
"provided"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/parser/box.go#L28-L40 | train |
gobuffalo/packr | v2/jam/pack.go | Pack | func Pack(opts PackOptions) error {
pwd, err := os.Getwd()
if err != nil {
return err
}
opts.Roots = append(opts.Roots, pwd)
if err := Clean(opts.Roots...); err != nil {
return err
}
p, err := parser.NewFromRoots(opts.Roots, &parser.RootsOptions{
IgnoreImports: opts.IgnoreImports,
})
if err != nil {
return err
}
boxes, err := p.Run()
if err != nil {
return err
}
// reduce boxes - remove ones we don't want
// MB: current assumption is we want all these
// boxes, just adding a comment suggesting they're
// might be a reason to exclude some
plog.Logger.Debugf("found %d boxes", len(boxes))
if len(opts.StoreCmd) != 0 {
return ShellPack(opts, boxes)
}
var st store.Store = store.NewDisk("", "")
if opts.Legacy {
st = store.NewLegacy()
}
for _, b := range boxes {
if b.Name == store.DISK_GLOBAL_KEY {
continue
}
if err := st.Pack(b); err != nil {
return err
}
}
if cl, ok := st.(io.Closer); ok {
return cl.Close()
}
return nil
} | go | func Pack(opts PackOptions) error {
pwd, err := os.Getwd()
if err != nil {
return err
}
opts.Roots = append(opts.Roots, pwd)
if err := Clean(opts.Roots...); err != nil {
return err
}
p, err := parser.NewFromRoots(opts.Roots, &parser.RootsOptions{
IgnoreImports: opts.IgnoreImports,
})
if err != nil {
return err
}
boxes, err := p.Run()
if err != nil {
return err
}
// reduce boxes - remove ones we don't want
// MB: current assumption is we want all these
// boxes, just adding a comment suggesting they're
// might be a reason to exclude some
plog.Logger.Debugf("found %d boxes", len(boxes))
if len(opts.StoreCmd) != 0 {
return ShellPack(opts, boxes)
}
var st store.Store = store.NewDisk("", "")
if opts.Legacy {
st = store.NewLegacy()
}
for _, b := range boxes {
if b.Name == store.DISK_GLOBAL_KEY {
continue
}
if err := st.Pack(b); err != nil {
return err
}
}
if cl, ok := st.(io.Closer); ok {
return cl.Close()
}
return nil
} | [
"func",
"Pack",
"(",
"opts",
"PackOptions",
")",
"error",
"{",
"pwd",
",",
"err",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"opts",
".",
"Roots",
"=",
"append",
"(",
"opts",
".",
"Roots",
",",
"pwd",
")",
"\n",
"if",
"err",
":=",
"Clean",
"(",
"opts",
".",
"Roots",
"...",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"parser",
".",
"NewFromRoots",
"(",
"opts",
".",
"Roots",
",",
"&",
"parser",
".",
"RootsOptions",
"{",
"IgnoreImports",
":",
"opts",
".",
"IgnoreImports",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"boxes",
",",
"err",
":=",
"p",
".",
"Run",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"plog",
".",
"Logger",
".",
"Debugf",
"(",
"\"found %d boxes\"",
",",
"len",
"(",
"boxes",
")",
")",
"\n",
"if",
"len",
"(",
"opts",
".",
"StoreCmd",
")",
"!=",
"0",
"{",
"return",
"ShellPack",
"(",
"opts",
",",
"boxes",
")",
"\n",
"}",
"\n",
"var",
"st",
"store",
".",
"Store",
"=",
"store",
".",
"NewDisk",
"(",
"\"\"",
",",
"\"\"",
")",
"\n",
"if",
"opts",
".",
"Legacy",
"{",
"st",
"=",
"store",
".",
"NewLegacy",
"(",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"boxes",
"{",
"if",
"b",
".",
"Name",
"==",
"store",
".",
"DISK_GLOBAL_KEY",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"st",
".",
"Pack",
"(",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cl",
",",
"ok",
":=",
"st",
".",
"(",
"io",
".",
"Closer",
")",
";",
"ok",
"{",
"return",
"cl",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Pack the roots given + PWD | [
"Pack",
"the",
"roots",
"given",
"+",
"PWD"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/pack.go#L25-L76 | train |
gobuffalo/packr | builder/builder.go | Run | func (b *Builder) Run() error {
wg := &errgroup.Group{}
root, err := filepath.EvalSymlinks(b.RootPath)
if err != nil {
return err
}
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if info == nil {
return filepath.SkipDir
}
base := strings.ToLower(filepath.Base(path))
if strings.HasPrefix(base, "_") {
return filepath.SkipDir
}
for _, f := range b.IgnoredFolders {
if strings.ToLower(f) == base {
if info.IsDir() {
return filepath.SkipDir
} else {
return nil
}
}
}
if !info.IsDir() {
wg.Go(func() error {
return b.process(path)
})
}
return nil
})
if err != nil {
return err
}
if err := wg.Wait(); err != nil {
return err
}
return b.dump()
} | go | func (b *Builder) Run() error {
wg := &errgroup.Group{}
root, err := filepath.EvalSymlinks(b.RootPath)
if err != nil {
return err
}
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if info == nil {
return filepath.SkipDir
}
base := strings.ToLower(filepath.Base(path))
if strings.HasPrefix(base, "_") {
return filepath.SkipDir
}
for _, f := range b.IgnoredFolders {
if strings.ToLower(f) == base {
if info.IsDir() {
return filepath.SkipDir
} else {
return nil
}
}
}
if !info.IsDir() {
wg.Go(func() error {
return b.process(path)
})
}
return nil
})
if err != nil {
return err
}
if err := wg.Wait(); err != nil {
return err
}
return b.dump()
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Run",
"(",
")",
"error",
"{",
"wg",
":=",
"&",
"errgroup",
".",
"Group",
"{",
"}",
"\n",
"root",
",",
"err",
":=",
"filepath",
".",
"EvalSymlinks",
"(",
"b",
".",
"RootPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"filepath",
".",
"Walk",
"(",
"root",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"info",
"==",
"nil",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n",
"base",
":=",
"strings",
".",
"ToLower",
"(",
"filepath",
".",
"Base",
"(",
"path",
")",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"base",
",",
"\"_\"",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"b",
".",
"IgnoredFolders",
"{",
"if",
"strings",
".",
"ToLower",
"(",
"f",
")",
"==",
"base",
"{",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"else",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"{",
"wg",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"return",
"b",
".",
"process",
"(",
"path",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"wg",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"b",
".",
"dump",
"(",
")",
"\n",
"}"
] | // Run the builder. | [
"Run",
"the",
"builder",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/builder/builder.go#L37-L75 | train |
gobuffalo/packr | builder/builder.go | New | func New(ctx context.Context, path string) *Builder {
return &Builder{
Context: ctx,
RootPath: path,
IgnoredBoxes: []string{},
IgnoredFolders: []string{"vendor", ".git", "node_modules", ".idea"},
pkgs: map[string]pkg{},
moot: &sync.Mutex{},
}
} | go | func New(ctx context.Context, path string) *Builder {
return &Builder{
Context: ctx,
RootPath: path,
IgnoredBoxes: []string{},
IgnoredFolders: []string{"vendor", ".git", "node_modules", ".idea"},
pkgs: map[string]pkg{},
moot: &sync.Mutex{},
}
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"*",
"Builder",
"{",
"return",
"&",
"Builder",
"{",
"Context",
":",
"ctx",
",",
"RootPath",
":",
"path",
",",
"IgnoredBoxes",
":",
"[",
"]",
"string",
"{",
"}",
",",
"IgnoredFolders",
":",
"[",
"]",
"string",
"{",
"\"vendor\"",
",",
"\".git\"",
",",
"\"node_modules\"",
",",
"\".idea\"",
"}",
",",
"pkgs",
":",
"map",
"[",
"string",
"]",
"pkg",
"{",
"}",
",",
"moot",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n",
"}"
] | // New Builder with a given context and path | [
"New",
"Builder",
"with",
"a",
"given",
"context",
"and",
"path"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/builder/builder.go#L162-L171 | train |
gobuffalo/packr | v2/jam/parser/file.go | String | func (f *File) String() string {
src, _ := ioutil.ReadAll(f)
f.Reader = bytes.NewReader(src)
return string(src)
} | go | func (f *File) String() string {
src, _ := ioutil.ReadAll(f)
f.Reader = bytes.NewReader(src)
return string(src)
} | [
"func",
"(",
"f",
"*",
"File",
")",
"String",
"(",
")",
"string",
"{",
"src",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"f",
".",
"Reader",
"=",
"bytes",
".",
"NewReader",
"(",
"src",
")",
"\n",
"return",
"string",
"(",
"src",
")",
"\n",
"}"
] | // String returns the contents of the reader | [
"String",
"returns",
"the",
"contents",
"of",
"the",
"reader"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/parser/file.go#L23-L27 | train |
gobuffalo/packr | v2/jam/parser/file.go | NewFile | func NewFile(path string, r io.Reader) *File {
if r == nil {
r = &bytes.Buffer{}
}
if seek, ok := r.(io.Seeker); ok {
seek.Seek(0, 0)
}
abs := path
if !filepath.IsAbs(path) {
abs, _ = filepath.Abs(path)
}
return &File{
Reader: r,
Path: path,
AbsPath: abs,
}
} | go | func NewFile(path string, r io.Reader) *File {
if r == nil {
r = &bytes.Buffer{}
}
if seek, ok := r.(io.Seeker); ok {
seek.Seek(0, 0)
}
abs := path
if !filepath.IsAbs(path) {
abs, _ = filepath.Abs(path)
}
return &File{
Reader: r,
Path: path,
AbsPath: abs,
}
} | [
"func",
"NewFile",
"(",
"path",
"string",
",",
"r",
"io",
".",
"Reader",
")",
"*",
"File",
"{",
"if",
"r",
"==",
"nil",
"{",
"r",
"=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"}",
"\n",
"if",
"seek",
",",
"ok",
":=",
"r",
".",
"(",
"io",
".",
"Seeker",
")",
";",
"ok",
"{",
"seek",
".",
"Seek",
"(",
"0",
",",
"0",
")",
"\n",
"}",
"\n",
"abs",
":=",
"path",
"\n",
"if",
"!",
"filepath",
".",
"IsAbs",
"(",
"path",
")",
"{",
"abs",
",",
"_",
"=",
"filepath",
".",
"Abs",
"(",
"path",
")",
"\n",
"}",
"\n",
"return",
"&",
"File",
"{",
"Reader",
":",
"r",
",",
"Path",
":",
"path",
",",
"AbsPath",
":",
"abs",
",",
"}",
"\n",
"}"
] | // NewFile takes the name of the file you want to
// write to and a reader to reader from | [
"NewFile",
"takes",
"the",
"name",
"of",
"the",
"file",
"you",
"want",
"to",
"write",
"to",
"and",
"a",
"reader",
"to",
"reader",
"from"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/parser/file.go#L38-L54 | train |
gobuffalo/packr | v2/pointer.go | Resolve | func (p Pointer) Resolve(box string, path string) (file.File, error) {
plog.Debug(p, "Resolve", "box", box, "path", path, "forward-box", p.ForwardBox, "forward-path", p.ForwardPath)
b, err := findBox(p.ForwardBox)
if err != nil {
return nil, err
}
f, err := b.Resolve(p.ForwardPath)
if err != nil {
return f, errors.WithStack(errors.Wrap(err, path))
}
plog.Debug(p, "Resolve", "box", box, "path", path, "file", f)
return file.NewFileR(path, f)
} | go | func (p Pointer) Resolve(box string, path string) (file.File, error) {
plog.Debug(p, "Resolve", "box", box, "path", path, "forward-box", p.ForwardBox, "forward-path", p.ForwardPath)
b, err := findBox(p.ForwardBox)
if err != nil {
return nil, err
}
f, err := b.Resolve(p.ForwardPath)
if err != nil {
return f, errors.WithStack(errors.Wrap(err, path))
}
plog.Debug(p, "Resolve", "box", box, "path", path, "file", f)
return file.NewFileR(path, f)
} | [
"func",
"(",
"p",
"Pointer",
")",
"Resolve",
"(",
"box",
"string",
",",
"path",
"string",
")",
"(",
"file",
".",
"File",
",",
"error",
")",
"{",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"Resolve\"",
",",
"\"box\"",
",",
"box",
",",
"\"path\"",
",",
"path",
",",
"\"forward-box\"",
",",
"p",
".",
"ForwardBox",
",",
"\"forward-path\"",
",",
"p",
".",
"ForwardPath",
")",
"\n",
"b",
",",
"err",
":=",
"findBox",
"(",
"p",
".",
"ForwardBox",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"b",
".",
"Resolve",
"(",
"p",
".",
"ForwardPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"f",
",",
"errors",
".",
"WithStack",
"(",
"errors",
".",
"Wrap",
"(",
"err",
",",
"path",
")",
")",
"\n",
"}",
"\n",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"Resolve\"",
",",
"\"box\"",
",",
"box",
",",
"\"path\"",
",",
"path",
",",
"\"file\"",
",",
"f",
")",
"\n",
"return",
"file",
".",
"NewFileR",
"(",
"path",
",",
"f",
")",
"\n",
"}"
] | // Resolve attempts to find the file in the specific box
// with the specified key | [
"Resolve",
"attempts",
"to",
"find",
"the",
"file",
"in",
"the",
"specific",
"box",
"with",
"the",
"specified",
"key"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/pointer.go#L21-L33 | train |
gobuffalo/packr | v2/jam/parser/parser.go | Run | func (p *Parser) Run() (Boxes, error) {
var boxes Boxes
for _, pros := range p.Prospects {
plog.Debug(p, "Run", "parsing", pros.Name())
v := NewVisitor(pros)
pbr, err := v.Run()
if err != nil {
return boxes, err
}
for _, b := range pbr {
plog.Debug(p, "Run", "file", pros.Name(), "box", b.Name)
boxes = append(boxes, b)
}
}
pwd, _ := os.Getwd()
sort.Slice(boxes, func(a, b int) bool {
b1 := boxes[a]
return !strings.HasPrefix(b1.AbsPath, pwd)
})
return boxes, nil
} | go | func (p *Parser) Run() (Boxes, error) {
var boxes Boxes
for _, pros := range p.Prospects {
plog.Debug(p, "Run", "parsing", pros.Name())
v := NewVisitor(pros)
pbr, err := v.Run()
if err != nil {
return boxes, err
}
for _, b := range pbr {
plog.Debug(p, "Run", "file", pros.Name(), "box", b.Name)
boxes = append(boxes, b)
}
}
pwd, _ := os.Getwd()
sort.Slice(boxes, func(a, b int) bool {
b1 := boxes[a]
return !strings.HasPrefix(b1.AbsPath, pwd)
})
return boxes, nil
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Run",
"(",
")",
"(",
"Boxes",
",",
"error",
")",
"{",
"var",
"boxes",
"Boxes",
"\n",
"for",
"_",
",",
"pros",
":=",
"range",
"p",
".",
"Prospects",
"{",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"Run\"",
",",
"\"parsing\"",
",",
"pros",
".",
"Name",
"(",
")",
")",
"\n",
"v",
":=",
"NewVisitor",
"(",
"pros",
")",
"\n",
"pbr",
",",
"err",
":=",
"v",
".",
"Run",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"boxes",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"pbr",
"{",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"Run\"",
",",
"\"file\"",
",",
"pros",
".",
"Name",
"(",
")",
",",
"\"box\"",
",",
"b",
".",
"Name",
")",
"\n",
"boxes",
"=",
"append",
"(",
"boxes",
",",
"b",
")",
"\n",
"}",
"\n",
"}",
"\n",
"pwd",
",",
"_",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"sort",
".",
"Slice",
"(",
"boxes",
",",
"func",
"(",
"a",
",",
"b",
"int",
")",
"bool",
"{",
"b1",
":=",
"boxes",
"[",
"a",
"]",
"\n",
"return",
"!",
"strings",
".",
"HasPrefix",
"(",
"b1",
".",
"AbsPath",
",",
"pwd",
")",
"\n",
"}",
")",
"\n",
"return",
"boxes",
",",
"nil",
"\n",
"}"
] | // Run the parser and run any boxes found | [
"Run",
"the",
"parser",
"and",
"run",
"any",
"boxes",
"found"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/parser/parser.go#L18-L39 | train |
gobuffalo/packr | packr.go | PackBytes | func PackBytes(box string, name string, bb []byte) {
gil.Lock()
defer gil.Unlock()
if _, ok := data[box]; !ok {
data[box] = map[string][]byte{}
}
data[box][name] = bb
} | go | func PackBytes(box string, name string, bb []byte) {
gil.Lock()
defer gil.Unlock()
if _, ok := data[box]; !ok {
data[box] = map[string][]byte{}
}
data[box][name] = bb
} | [
"func",
"PackBytes",
"(",
"box",
"string",
",",
"name",
"string",
",",
"bb",
"[",
"]",
"byte",
")",
"{",
"gil",
".",
"Lock",
"(",
")",
"\n",
"defer",
"gil",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"data",
"[",
"box",
"]",
";",
"!",
"ok",
"{",
"data",
"[",
"box",
"]",
"=",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
"{",
"}",
"\n",
"}",
"\n",
"data",
"[",
"box",
"]",
"[",
"name",
"]",
"=",
"bb",
"\n",
"}"
] | // PackBytes packs bytes for a file into a box. | [
"PackBytes",
"packs",
"bytes",
"for",
"a",
"file",
"into",
"a",
"box",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/packr.go#L16-L23 | train |
gobuffalo/packr | packr.go | PackBytesGzip | func PackBytesGzip(box string, name string, bb []byte) error {
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
_, err := w.Write(bb)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
PackBytes(box, name, buf.Bytes())
return nil
} | go | func PackBytesGzip(box string, name string, bb []byte) error {
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
_, err := w.Write(bb)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
PackBytes(box, name, buf.Bytes())
return nil
} | [
"func",
"PackBytesGzip",
"(",
"box",
"string",
",",
"name",
"string",
",",
"bb",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"w",
":=",
"gzip",
".",
"NewWriter",
"(",
"&",
"buf",
")",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"bb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"w",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"PackBytes",
"(",
"box",
",",
"name",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // PackBytesGzip packets the gzipped compressed bytes into a box. | [
"PackBytesGzip",
"packets",
"the",
"gzipped",
"compressed",
"bytes",
"into",
"a",
"box",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/packr.go#L26-L39 | train |
gobuffalo/packr | packr.go | PackJSONBytes | func PackJSONBytes(box string, name string, jbb string) error {
var bb []byte
err := json.Unmarshal([]byte(jbb), &bb)
if err != nil {
return err
}
PackBytes(box, name, bb)
return nil
} | go | func PackJSONBytes(box string, name string, jbb string) error {
var bb []byte
err := json.Unmarshal([]byte(jbb), &bb)
if err != nil {
return err
}
PackBytes(box, name, bb)
return nil
} | [
"func",
"PackJSONBytes",
"(",
"box",
"string",
",",
"name",
"string",
",",
"jbb",
"string",
")",
"error",
"{",
"var",
"bb",
"[",
"]",
"byte",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"jbb",
")",
",",
"&",
"bb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"PackBytes",
"(",
"box",
",",
"name",
",",
"bb",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // PackJSONBytes packs JSON encoded bytes for a file into a box. | [
"PackJSONBytes",
"packs",
"JSON",
"encoded",
"bytes",
"for",
"a",
"file",
"into",
"a",
"box",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/packr.go#L42-L50 | train |
gobuffalo/packr | packr.go | UnpackBytes | func UnpackBytes(box string) {
gil.Lock()
defer gil.Unlock()
delete(data, box)
} | go | func UnpackBytes(box string) {
gil.Lock()
defer gil.Unlock()
delete(data, box)
} | [
"func",
"UnpackBytes",
"(",
"box",
"string",
")",
"{",
"gil",
".",
"Lock",
"(",
")",
"\n",
"defer",
"gil",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"data",
",",
"box",
")",
"\n",
"}"
] | // UnpackBytes unpacks bytes for specific box. | [
"UnpackBytes",
"unpacks",
"bytes",
"for",
"specific",
"box",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/packr.go#L53-L57 | train |
gobuffalo/packr | v2/file/resolver/encoding/hex/hex.go | DecodeString | func DecodeString(s string) ([]byte, error) {
src := []byte(s)
// We can use the source slice itself as the destination
// because the decode loop increments by one and then the 'seen' byte is not used anymore.
n, err := Decode(src, src)
return src[:n], err
} | go | func DecodeString(s string) ([]byte, error) {
src := []byte(s)
// We can use the source slice itself as the destination
// because the decode loop increments by one and then the 'seen' byte is not used anymore.
n, err := Decode(src, src)
return src[:n], err
} | [
"func",
"DecodeString",
"(",
"s",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"src",
":=",
"[",
"]",
"byte",
"(",
"s",
")",
"\n",
"n",
",",
"err",
":=",
"Decode",
"(",
"src",
",",
"src",
")",
"\n",
"return",
"src",
"[",
":",
"n",
"]",
",",
"err",
"\n",
"}"
] | // DecodeString returns the bytes represented by the hexadecimal string s.
//
// DecodeString expects that src contains only hexadecimal
// characters and that src has even length.
// If the input is malformed, DecodeString returns
// the bytes decoded before the error. | [
"DecodeString",
"returns",
"the",
"bytes",
"represented",
"by",
"the",
"hexadecimal",
"string",
"s",
".",
"DecodeString",
"expects",
"that",
"src",
"contains",
"only",
"hexadecimal",
"characters",
"and",
"that",
"src",
"has",
"even",
"length",
".",
"If",
"the",
"input",
"is",
"malformed",
"DecodeString",
"returns",
"the",
"bytes",
"decoded",
"before",
"the",
"error",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/file/resolver/encoding/hex/hex.go#L108-L114 | train |
gobuffalo/packr | v2/file/resolver/encoding/hex/hex.go | Dump | func Dump(data []byte) string {
var buf bytes.Buffer
dumper := Dumper(&buf)
dumper.Write(data)
dumper.Close()
return buf.String()
} | go | func Dump(data []byte) string {
var buf bytes.Buffer
dumper := Dumper(&buf)
dumper.Write(data)
dumper.Close()
return buf.String()
} | [
"func",
"Dump",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"dumper",
":=",
"Dumper",
"(",
"&",
"buf",
")",
"\n",
"dumper",
".",
"Write",
"(",
"data",
")",
"\n",
"dumper",
".",
"Close",
"(",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // Dump returns a string that contains a hex dump of the given data. The format
// of the hex dump matches the output of `hexdump -C` on the command line. | [
"Dump",
"returns",
"a",
"string",
"that",
"contains",
"a",
"hex",
"dump",
"of",
"the",
"given",
"data",
".",
"The",
"format",
"of",
"the",
"hex",
"dump",
"matches",
"the",
"output",
"of",
"hexdump",
"-",
"C",
"on",
"the",
"command",
"line",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/file/resolver/encoding/hex/hex.go#L118-L124 | train |
gobuffalo/packr | v2/resolvers_map.go | Load | func (m *resolversMap) Load(key string) (resolver.Resolver, bool) {
i, ok := m.data.Load(key)
if !ok {
return nil, false
}
s, ok := i.(resolver.Resolver)
return s, ok
} | go | func (m *resolversMap) Load(key string) (resolver.Resolver, bool) {
i, ok := m.data.Load(key)
if !ok {
return nil, false
}
s, ok := i.(resolver.Resolver)
return s, ok
} | [
"func",
"(",
"m",
"*",
"resolversMap",
")",
"Load",
"(",
"key",
"string",
")",
"(",
"resolver",
".",
"Resolver",
",",
"bool",
")",
"{",
"i",
",",
"ok",
":=",
"m",
".",
"data",
".",
"Load",
"(",
"key",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"s",
",",
"ok",
":=",
"i",
".",
"(",
"resolver",
".",
"Resolver",
")",
"\n",
"return",
"s",
",",
"ok",
"\n",
"}"
] | // Load the key from the map.
// Returns resolver.Resolver or bool.
// A false return indicates either the key was not found
// or the value is not of type resolver.Resolver | [
"Load",
"the",
"key",
"from",
"the",
"map",
".",
"Returns",
"resolver",
".",
"Resolver",
"or",
"bool",
".",
"A",
"false",
"return",
"indicates",
"either",
"the",
"key",
"was",
"not",
"found",
"or",
"the",
"value",
"is",
"not",
"of",
"type",
"resolver",
".",
"Resolver"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/resolvers_map.go#L29-L36 | train |
gobuffalo/packr | v2/resolvers_map.go | Range | func (m *resolversMap) Range(f func(key string, value resolver.Resolver) bool) {
m.data.Range(func(k, v interface{}) bool {
key, ok := k.(string)
if !ok {
return false
}
value, ok := v.(resolver.Resolver)
if !ok {
return false
}
return f(key, value)
})
} | go | func (m *resolversMap) Range(f func(key string, value resolver.Resolver) bool) {
m.data.Range(func(k, v interface{}) bool {
key, ok := k.(string)
if !ok {
return false
}
value, ok := v.(resolver.Resolver)
if !ok {
return false
}
return f(key, value)
})
} | [
"func",
"(",
"m",
"*",
"resolversMap",
")",
"Range",
"(",
"f",
"func",
"(",
"key",
"string",
",",
"value",
"resolver",
".",
"Resolver",
")",
"bool",
")",
"{",
"m",
".",
"data",
".",
"Range",
"(",
"func",
"(",
"k",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"key",
",",
"ok",
":=",
"k",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"value",
",",
"ok",
":=",
"v",
".",
"(",
"resolver",
".",
"Resolver",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"f",
"(",
"key",
",",
"value",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Range over the resolver.Resolver values in the map | [
"Range",
"over",
"the",
"resolver",
".",
"Resolver",
"values",
"in",
"the",
"map"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/resolvers_map.go#L47-L59 | train |
gobuffalo/packr | v2/resolvers_map.go | Store | func (m *resolversMap) Store(key string, value resolver.Resolver) {
m.data.Store(key, value)
} | go | func (m *resolversMap) Store(key string, value resolver.Resolver) {
m.data.Store(key, value)
} | [
"func",
"(",
"m",
"*",
"resolversMap",
")",
"Store",
"(",
"key",
"string",
",",
"value",
"resolver",
".",
"Resolver",
")",
"{",
"m",
".",
"data",
".",
"Store",
"(",
"key",
",",
"value",
")",
"\n",
"}"
] | // Store a resolver.Resolver in the map | [
"Store",
"a",
"resolver",
".",
"Resolver",
"in",
"the",
"map"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/resolvers_map.go#L62-L64 | train |
gobuffalo/packr | v2/deprecated.go | PackBytes | func PackBytes(box string, name string, bb []byte) {
b := NewBox(box)
d := resolver.NewInMemory(map[string]file.File{})
f, err := file.NewFile(name, bb)
if err != nil {
panic(err)
}
if err := d.Pack(name, f); err != nil {
panic(err)
}
b.SetResolver(name, d)
} | go | func PackBytes(box string, name string, bb []byte) {
b := NewBox(box)
d := resolver.NewInMemory(map[string]file.File{})
f, err := file.NewFile(name, bb)
if err != nil {
panic(err)
}
if err := d.Pack(name, f); err != nil {
panic(err)
}
b.SetResolver(name, d)
} | [
"func",
"PackBytes",
"(",
"box",
"string",
",",
"name",
"string",
",",
"bb",
"[",
"]",
"byte",
")",
"{",
"b",
":=",
"NewBox",
"(",
"box",
")",
"\n",
"d",
":=",
"resolver",
".",
"NewInMemory",
"(",
"map",
"[",
"string",
"]",
"file",
".",
"File",
"{",
"}",
")",
"\n",
"f",
",",
"err",
":=",
"file",
".",
"NewFile",
"(",
"name",
",",
"bb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"Pack",
"(",
"name",
",",
"f",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"b",
".",
"SetResolver",
"(",
"name",
",",
"d",
")",
"\n",
"}"
] | // PackBytes packs bytes for a file into a box.
// Deprecated | [
"PackBytes",
"packs",
"bytes",
"for",
"a",
"file",
"into",
"a",
"box",
".",
"Deprecated"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/deprecated.go#L23-L34 | train |
gobuffalo/packr | v2/deprecated.go | PackBytesGzip | func PackBytesGzip(box string, name string, bb []byte) error {
// TODO: this function never did what it was supposed to do!
PackBytes(box, name, bb)
return nil
} | go | func PackBytesGzip(box string, name string, bb []byte) error {
// TODO: this function never did what it was supposed to do!
PackBytes(box, name, bb)
return nil
} | [
"func",
"PackBytesGzip",
"(",
"box",
"string",
",",
"name",
"string",
",",
"bb",
"[",
"]",
"byte",
")",
"error",
"{",
"PackBytes",
"(",
"box",
",",
"name",
",",
"bb",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // PackBytesGzip packets the gzipped compressed bytes into a box.
// Deprecated | [
"PackBytesGzip",
"packets",
"the",
"gzipped",
"compressed",
"bytes",
"into",
"a",
"box",
".",
"Deprecated"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/deprecated.go#L38-L42 | train |
gobuffalo/packr | v2/deprecated.go | String | func (b *Box) String(name string) string {
oncer.Deprecate(0, "github.com/gobuffalo/packr/v2#Box.String", "Use github.com/gobuffalo/packr/v2#Box.FindString instead.")
return string(b.Bytes(name))
} | go | func (b *Box) String(name string) string {
oncer.Deprecate(0, "github.com/gobuffalo/packr/v2#Box.String", "Use github.com/gobuffalo/packr/v2#Box.FindString instead.")
return string(b.Bytes(name))
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"String",
"(",
"name",
"string",
")",
"string",
"{",
"oncer",
".",
"Deprecate",
"(",
"0",
",",
"\"github.com/gobuffalo/packr/v2#Box.String\"",
",",
"\"Use github.com/gobuffalo/packr/v2#Box.FindString instead.\"",
")",
"\n",
"return",
"string",
"(",
"b",
".",
"Bytes",
"(",
"name",
")",
")",
"\n",
"}"
] | // String is deprecated. Use FindString instead | [
"String",
"is",
"deprecated",
".",
"Use",
"FindString",
"instead"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/deprecated.go#L70-L73 | train |
gobuffalo/packr | v2/deprecated.go | MustString | func (b *Box) MustString(name string) (string, error) {
oncer.Deprecate(0, "github.com/gobuffalo/packr/v2#Box.MustString", "Use github.com/gobuffalo/packr/v2#Box.FindString instead.")
return b.FindString(name)
} | go | func (b *Box) MustString(name string) (string, error) {
oncer.Deprecate(0, "github.com/gobuffalo/packr/v2#Box.MustString", "Use github.com/gobuffalo/packr/v2#Box.FindString instead.")
return b.FindString(name)
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"MustString",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"oncer",
".",
"Deprecate",
"(",
"0",
",",
"\"github.com/gobuffalo/packr/v2#Box.MustString\"",
",",
"\"Use github.com/gobuffalo/packr/v2#Box.FindString instead.\"",
")",
"\n",
"return",
"b",
".",
"FindString",
"(",
"name",
")",
"\n",
"}"
] | // MustString is deprecated. Use FindString instead | [
"MustString",
"is",
"deprecated",
".",
"Use",
"FindString",
"instead"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/deprecated.go#L76-L79 | train |
gobuffalo/packr | v2/dirs_map.go | Delete | func (m *dirsMap) Delete(key string) {
m.data.Delete(m.normalizeKey(key))
} | go | func (m *dirsMap) Delete(key string) {
m.data.Delete(m.normalizeKey(key))
} | [
"func",
"(",
"m",
"*",
"dirsMap",
")",
"Delete",
"(",
"key",
"string",
")",
"{",
"m",
".",
"data",
".",
"Delete",
"(",
"m",
".",
"normalizeKey",
"(",
"key",
")",
")",
"\n",
"}"
] | // Delete the key from the map | [
"Delete",
"the",
"key",
"from",
"the",
"map"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/dirs_map.go#L20-L22 | train |
gobuffalo/packr | v2/dirs_map.go | Load | func (m *dirsMap) Load(key string) (bool, bool) {
i, ok := m.data.Load(m.normalizeKey(key))
if !ok {
return false, false
}
s, ok := i.(bool)
return s, ok
} | go | func (m *dirsMap) Load(key string) (bool, bool) {
i, ok := m.data.Load(m.normalizeKey(key))
if !ok {
return false, false
}
s, ok := i.(bool)
return s, ok
} | [
"func",
"(",
"m",
"*",
"dirsMap",
")",
"Load",
"(",
"key",
"string",
")",
"(",
"bool",
",",
"bool",
")",
"{",
"i",
",",
"ok",
":=",
"m",
".",
"data",
".",
"Load",
"(",
"m",
".",
"normalizeKey",
"(",
"key",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
",",
"false",
"\n",
"}",
"\n",
"s",
",",
"ok",
":=",
"i",
".",
"(",
"bool",
")",
"\n",
"return",
"s",
",",
"ok",
"\n",
"}"
] | // Load the key from the map.
// Returns bool or bool.
// A false return indicates either the key was not found
// or the value is not of type bool | [
"Load",
"the",
"key",
"from",
"the",
"map",
".",
"Returns",
"bool",
"or",
"bool",
".",
"A",
"false",
"return",
"indicates",
"either",
"the",
"key",
"was",
"not",
"found",
"or",
"the",
"value",
"is",
"not",
"of",
"type",
"bool"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/dirs_map.go#L28-L35 | train |
gobuffalo/packr | v2/dirs_map.go | Store | func (m *dirsMap) Store(key string, value bool) {
d := m.normalizeKey(key)
m.data.Store(d, value)
m.data.Store(strings.TrimPrefix(d, "/"), value)
} | go | func (m *dirsMap) Store(key string, value bool) {
d := m.normalizeKey(key)
m.data.Store(d, value)
m.data.Store(strings.TrimPrefix(d, "/"), value)
} | [
"func",
"(",
"m",
"*",
"dirsMap",
")",
"Store",
"(",
"key",
"string",
",",
"value",
"bool",
")",
"{",
"d",
":=",
"m",
".",
"normalizeKey",
"(",
"key",
")",
"\n",
"m",
".",
"data",
".",
"Store",
"(",
"d",
",",
"value",
")",
"\n",
"m",
".",
"data",
".",
"Store",
"(",
"strings",
".",
"TrimPrefix",
"(",
"d",
",",
"\"/\"",
")",
",",
"value",
")",
"\n",
"}"
] | // Store a bool in the map | [
"Store",
"a",
"bool",
"in",
"the",
"map"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/dirs_map.go#L61-L65 | train |
gobuffalo/packr | v2/packr2/cmd/fix/runner.go | Run | func Run() error {
fmt.Printf("! This updater will attempt to update your application to packr version: %s\n", packr.Version)
if !ask("Do you wish to continue?") {
fmt.Println("~~~ cancelling update ~~~")
return nil
}
r := &Runner{
Warnings: []string{},
}
defer func() {
if len(r.Warnings) == 0 {
return
}
fmt.Println("\n\n----------------------------")
fmt.Printf("!!! (%d) Warnings Were Found !!!\n\n", len(r.Warnings))
for _, w := range r.Warnings {
fmt.Printf("[WARNING]: %s\n", w)
}
}()
for _, c := range checks {
if err := c(r); err != nil {
return err
}
}
return nil
} | go | func Run() error {
fmt.Printf("! This updater will attempt to update your application to packr version: %s\n", packr.Version)
if !ask("Do you wish to continue?") {
fmt.Println("~~~ cancelling update ~~~")
return nil
}
r := &Runner{
Warnings: []string{},
}
defer func() {
if len(r.Warnings) == 0 {
return
}
fmt.Println("\n\n----------------------------")
fmt.Printf("!!! (%d) Warnings Were Found !!!\n\n", len(r.Warnings))
for _, w := range r.Warnings {
fmt.Printf("[WARNING]: %s\n", w)
}
}()
for _, c := range checks {
if err := c(r); err != nil {
return err
}
}
return nil
} | [
"func",
"Run",
"(",
")",
"error",
"{",
"fmt",
".",
"Printf",
"(",
"\"! This updater will attempt to update your application to packr version: %s\\n\"",
",",
"\\n",
")",
"\n",
"packr",
".",
"Version",
"\n",
"if",
"!",
"ask",
"(",
"\"Do you wish to continue?\"",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"~~~ cancelling update ~~~\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"r",
":=",
"&",
"Runner",
"{",
"Warnings",
":",
"[",
"]",
"string",
"{",
"}",
",",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"len",
"(",
"r",
".",
"Warnings",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"\\n\\n----------------------------\"",
")",
"\n",
"\\n",
"\n",
"\\n",
"\n",
"}",
"fmt",
".",
"Printf",
"(",
"\"!!! (%d) Warnings Were Found !!!\\n\\n\"",
",",
"\\n",
")",
"\n",
"\\n",
"\n",
"}"
] | // Run all compatible checks | [
"Run",
"all",
"compatible",
"checks"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/packr2/cmd/fix/runner.go#L18-L47 | train |
gobuffalo/packr | v2/box.go | New | func New(name string, path string) *Box {
plog.Debug("packr", "New", "name", name, "path", path)
b, _ := findBox(name)
if b != nil {
return b
}
b = construct(name, path)
plog.Debug(b, "New", "Box", b, "ResolutionDir", b.ResolutionDir)
b, err := placeBox(b)
if err != nil {
panic(err)
}
return b
} | go | func New(name string, path string) *Box {
plog.Debug("packr", "New", "name", name, "path", path)
b, _ := findBox(name)
if b != nil {
return b
}
b = construct(name, path)
plog.Debug(b, "New", "Box", b, "ResolutionDir", b.ResolutionDir)
b, err := placeBox(b)
if err != nil {
panic(err)
}
return b
} | [
"func",
"New",
"(",
"name",
"string",
",",
"path",
"string",
")",
"*",
"Box",
"{",
"plog",
".",
"Debug",
"(",
"\"packr\"",
",",
"\"New\"",
",",
"\"name\"",
",",
"name",
",",
"\"path\"",
",",
"path",
")",
"\n",
"b",
",",
"_",
":=",
"findBox",
"(",
"name",
")",
"\n",
"if",
"b",
"!=",
"nil",
"{",
"return",
"b",
"\n",
"}",
"\n",
"b",
"=",
"construct",
"(",
"name",
",",
"path",
")",
"\n",
"plog",
".",
"Debug",
"(",
"b",
",",
"\"New\"",
",",
"\"Box\"",
",",
"b",
",",
"\"ResolutionDir\"",
",",
"b",
".",
"ResolutionDir",
")",
"\n",
"b",
",",
"err",
":=",
"placeBox",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"b",
"\n",
"}"
] | // New returns a new Box with the name of the box
// and the path of the box. | [
"New",
"returns",
"a",
"new",
"Box",
"with",
"the",
"name",
"of",
"the",
"box",
"and",
"the",
"path",
"of",
"the",
"box",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L51-L66 | train |
gobuffalo/packr | v2/box.go | SetResolver | func (b *Box) SetResolver(file string, res resolver.Resolver) {
d := filepath.Dir(file)
b.dirs.Store(d, true)
plog.Debug(b, "SetResolver", "file", file, "resolver", fmt.Sprintf("%T", res))
b.resolvers.Store(resolver.Key(file), res)
} | go | func (b *Box) SetResolver(file string, res resolver.Resolver) {
d := filepath.Dir(file)
b.dirs.Store(d, true)
plog.Debug(b, "SetResolver", "file", file, "resolver", fmt.Sprintf("%T", res))
b.resolvers.Store(resolver.Key(file), res)
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"SetResolver",
"(",
"file",
"string",
",",
"res",
"resolver",
".",
"Resolver",
")",
"{",
"d",
":=",
"filepath",
".",
"Dir",
"(",
"file",
")",
"\n",
"b",
".",
"dirs",
".",
"Store",
"(",
"d",
",",
"true",
")",
"\n",
"plog",
".",
"Debug",
"(",
"b",
",",
"\"SetResolver\"",
",",
"\"file\"",
",",
"file",
",",
"\"resolver\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%T\"",
",",
"res",
")",
")",
"\n",
"b",
".",
"resolvers",
".",
"Store",
"(",
"resolver",
".",
"Key",
"(",
"file",
")",
",",
"res",
")",
"\n",
"}"
] | // SetResolver allows for the use of a custom resolver for
// the specified file | [
"SetResolver",
"allows",
"for",
"the",
"use",
"of",
"a",
"custom",
"resolver",
"for",
"the",
"specified",
"file"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L77-L82 | train |
gobuffalo/packr | v2/box.go | AddString | func (b *Box) AddString(path string, t string) error {
return b.AddBytes(path, []byte(t))
} | go | func (b *Box) AddString(path string, t string) error {
return b.AddBytes(path, []byte(t))
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"AddString",
"(",
"path",
"string",
",",
"t",
"string",
")",
"error",
"{",
"return",
"b",
".",
"AddBytes",
"(",
"path",
",",
"[",
"]",
"byte",
"(",
"t",
")",
")",
"\n",
"}"
] | // AddString converts t to a byteslice and delegates to AddBytes to add to b.data | [
"AddString",
"converts",
"t",
"to",
"a",
"byteslice",
"and",
"delegates",
"to",
"AddBytes",
"to",
"add",
"to",
"b",
".",
"data"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L85-L87 | train |
gobuffalo/packr | v2/box.go | AddBytes | func (b *Box) AddBytes(path string, t []byte) error {
m := map[string]file.File{}
f, err := file.NewFile(path, t)
if err != nil {
return err
}
m[resolver.Key(path)] = f
res := resolver.NewInMemory(m)
b.SetResolver(path, res)
return nil
} | go | func (b *Box) AddBytes(path string, t []byte) error {
m := map[string]file.File{}
f, err := file.NewFile(path, t)
if err != nil {
return err
}
m[resolver.Key(path)] = f
res := resolver.NewInMemory(m)
b.SetResolver(path, res)
return nil
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"AddBytes",
"(",
"path",
"string",
",",
"t",
"[",
"]",
"byte",
")",
"error",
"{",
"m",
":=",
"map",
"[",
"string",
"]",
"file",
".",
"File",
"{",
"}",
"\n",
"f",
",",
"err",
":=",
"file",
".",
"NewFile",
"(",
"path",
",",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"m",
"[",
"resolver",
".",
"Key",
"(",
"path",
")",
"]",
"=",
"f",
"\n",
"res",
":=",
"resolver",
".",
"NewInMemory",
"(",
"m",
")",
"\n",
"b",
".",
"SetResolver",
"(",
"path",
",",
"res",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddBytes sets t in b.data by the given path | [
"AddBytes",
"sets",
"t",
"in",
"b",
".",
"data",
"by",
"the",
"given",
"path"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L90-L100 | train |
gobuffalo/packr | v2/box.go | FindString | func (b *Box) FindString(name string) (string, error) {
bb, err := b.Find(name)
return string(bb), err
} | go | func (b *Box) FindString(name string) (string, error) {
bb, err := b.Find(name)
return string(bb), err
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"FindString",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"bb",
",",
"err",
":=",
"b",
".",
"Find",
"(",
"name",
")",
"\n",
"return",
"string",
"(",
"bb",
")",
",",
"err",
"\n",
"}"
] | // FindString returns either the string of the requested
// file or an error if it can not be found. | [
"FindString",
"returns",
"either",
"the",
"string",
"of",
"the",
"requested",
"file",
"or",
"an",
"error",
"if",
"it",
"can",
"not",
"be",
"found",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L104-L107 | train |
gobuffalo/packr | v2/box.go | HasDir | func (b *Box) HasDir(name string) bool {
oncer.Do("packr2/box/HasDir"+b.Name, func() {
for _, f := range b.List() {
for d := filepath.Dir(f); d != "."; d = filepath.Dir(d) {
b.dirs.Store(d, true)
}
}
})
if name == "/" {
return b.Has("index.html")
}
_, ok := b.dirs.Load(name)
return ok
} | go | func (b *Box) HasDir(name string) bool {
oncer.Do("packr2/box/HasDir"+b.Name, func() {
for _, f := range b.List() {
for d := filepath.Dir(f); d != "."; d = filepath.Dir(d) {
b.dirs.Store(d, true)
}
}
})
if name == "/" {
return b.Has("index.html")
}
_, ok := b.dirs.Load(name)
return ok
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"HasDir",
"(",
"name",
"string",
")",
"bool",
"{",
"oncer",
".",
"Do",
"(",
"\"packr2/box/HasDir\"",
"+",
"b",
".",
"Name",
",",
"func",
"(",
")",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"b",
".",
"List",
"(",
")",
"{",
"for",
"d",
":=",
"filepath",
".",
"Dir",
"(",
"f",
")",
";",
"d",
"!=",
"\".\"",
";",
"d",
"=",
"filepath",
".",
"Dir",
"(",
"d",
")",
"{",
"b",
".",
"dirs",
".",
"Store",
"(",
"d",
",",
"true",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"if",
"name",
"==",
"\"/\"",
"{",
"return",
"b",
".",
"Has",
"(",
"\"index.html\"",
")",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"b",
".",
"dirs",
".",
"Load",
"(",
"name",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // HasDir returns true if the directory exists in the box | [
"HasDir",
"returns",
"true",
"if",
"the",
"directory",
"exists",
"in",
"the",
"box"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L128-L141 | train |
gobuffalo/packr | v2/box.go | Resolve | func (b *Box) Resolve(key string) (file.File, error) {
key = strings.TrimPrefix(key, "/")
var r resolver.Resolver
b.resolvers.Range(func(k string, vr resolver.Resolver) bool {
lk := strings.ToLower(resolver.Key(k))
lkey := strings.ToLower(resolver.Key(key))
if lk == lkey {
r = vr
return false
}
return true
})
if r == nil {
r = b.DefaultResolver
if r == nil {
r = resolver.DefaultResolver
if r == nil {
return nil, errors.New("resolver.DefaultResolver is nil")
}
}
}
plog.Debug(r, "Resolve", "box", b.Name, "key", key)
f, err := r.Resolve(b.Name, key)
if err != nil {
z := filepath.Join(resolver.OsPath(b.ResolutionDir), resolver.OsPath(key))
f, err = r.Resolve(b.Name, z)
if err != nil {
plog.Debug(r, "Resolve", "box", b.Name, "key", z, "err", err)
return f, err
}
b, err := ioutil.ReadAll(f)
if err != nil {
return f, err
}
f, err = file.NewFile(key, b)
if err != nil {
return f, err
}
}
plog.Debug(r, "Resolve", "box", b.Name, "key", key, "file", f.Name())
return f, nil
} | go | func (b *Box) Resolve(key string) (file.File, error) {
key = strings.TrimPrefix(key, "/")
var r resolver.Resolver
b.resolvers.Range(func(k string, vr resolver.Resolver) bool {
lk := strings.ToLower(resolver.Key(k))
lkey := strings.ToLower(resolver.Key(key))
if lk == lkey {
r = vr
return false
}
return true
})
if r == nil {
r = b.DefaultResolver
if r == nil {
r = resolver.DefaultResolver
if r == nil {
return nil, errors.New("resolver.DefaultResolver is nil")
}
}
}
plog.Debug(r, "Resolve", "box", b.Name, "key", key)
f, err := r.Resolve(b.Name, key)
if err != nil {
z := filepath.Join(resolver.OsPath(b.ResolutionDir), resolver.OsPath(key))
f, err = r.Resolve(b.Name, z)
if err != nil {
plog.Debug(r, "Resolve", "box", b.Name, "key", z, "err", err)
return f, err
}
b, err := ioutil.ReadAll(f)
if err != nil {
return f, err
}
f, err = file.NewFile(key, b)
if err != nil {
return f, err
}
}
plog.Debug(r, "Resolve", "box", b.Name, "key", key, "file", f.Name())
return f, nil
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"Resolve",
"(",
"key",
"string",
")",
"(",
"file",
".",
"File",
",",
"error",
")",
"{",
"key",
"=",
"strings",
".",
"TrimPrefix",
"(",
"key",
",",
"\"/\"",
")",
"\n",
"var",
"r",
"resolver",
".",
"Resolver",
"\n",
"b",
".",
"resolvers",
".",
"Range",
"(",
"func",
"(",
"k",
"string",
",",
"vr",
"resolver",
".",
"Resolver",
")",
"bool",
"{",
"lk",
":=",
"strings",
".",
"ToLower",
"(",
"resolver",
".",
"Key",
"(",
"k",
")",
")",
"\n",
"lkey",
":=",
"strings",
".",
"ToLower",
"(",
"resolver",
".",
"Key",
"(",
"key",
")",
")",
"\n",
"if",
"lk",
"==",
"lkey",
"{",
"r",
"=",
"vr",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"if",
"r",
"==",
"nil",
"{",
"r",
"=",
"b",
".",
"DefaultResolver",
"\n",
"if",
"r",
"==",
"nil",
"{",
"r",
"=",
"resolver",
".",
"DefaultResolver",
"\n",
"if",
"r",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"resolver.DefaultResolver is nil\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"plog",
".",
"Debug",
"(",
"r",
",",
"\"Resolve\"",
",",
"\"box\"",
",",
"b",
".",
"Name",
",",
"\"key\"",
",",
"key",
")",
"\n",
"f",
",",
"err",
":=",
"r",
".",
"Resolve",
"(",
"b",
".",
"Name",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"z",
":=",
"filepath",
".",
"Join",
"(",
"resolver",
".",
"OsPath",
"(",
"b",
".",
"ResolutionDir",
")",
",",
"resolver",
".",
"OsPath",
"(",
"key",
")",
")",
"\n",
"f",
",",
"err",
"=",
"r",
".",
"Resolve",
"(",
"b",
".",
"Name",
",",
"z",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"plog",
".",
"Debug",
"(",
"r",
",",
"\"Resolve\"",
",",
"\"box\"",
",",
"b",
".",
"Name",
",",
"\"key\"",
",",
"z",
",",
"\"err\"",
",",
"err",
")",
"\n",
"return",
"f",
",",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"f",
",",
"err",
"\n",
"}",
"\n",
"f",
",",
"err",
"=",
"file",
".",
"NewFile",
"(",
"key",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"f",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"plog",
".",
"Debug",
"(",
"r",
",",
"\"Resolve\"",
",",
"\"box\"",
",",
"b",
".",
"Name",
",",
"\"key\"",
",",
"key",
",",
"\"file\"",
",",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] | // Resolve will attempt to find the file in the box,
// returning an error if the find can not be found. | [
"Resolve",
"will",
"attempt",
"to",
"find",
"the",
"file",
"in",
"the",
"box",
"returning",
"an",
"error",
"if",
"the",
"find",
"can",
"not",
"be",
"found",
"."
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/box.go#L191-L236 | train |
gobuffalo/packr | v2/jam/parser/roots.go | NewFromRoots | func NewFromRoots(roots []string, opts *RootsOptions) (*Parser, error) {
if opts == nil {
opts = &RootsOptions{}
}
if len(roots) == 0 {
pwd, _ := os.Getwd()
roots = append(roots, pwd)
}
p := New()
plog.Debug(p, "NewFromRoots", "roots", roots, "options", opts)
callback := func(path string, de *godirwalk.Dirent) error {
if IsProspect(path, opts.Ignores...) {
if de.IsDir() {
return nil
}
roots = append(roots, path)
return nil
}
if de.IsDir() {
return filepath.SkipDir
}
return nil
}
wopts := &godirwalk.Options{
FollowSymbolicLinks: true,
Callback: callback,
}
for _, root := range roots {
plog.Debug(p, "NewFromRoots", "walking", root)
err := godirwalk.Walk(root, wopts)
if err != nil {
return p, err
}
}
dd := map[string]string{}
fd := &finder{id: time.Now()}
for _, r := range roots {
var names []string
if opts.IgnoreImports {
names, _ = fd.findAllGoFiles(r)
} else {
names, _ = fd.findAllGoFilesImports(r)
}
for _, n := range names {
if IsProspect(n) {
plog.Debug(p, "NewFromRoots", "mapping", n)
dd[n] = n
}
}
}
for path := range dd {
plog.Debug(p, "NewFromRoots", "reading file", path)
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
p.Prospects = append(p.Prospects, NewFile(path, bytes.NewReader(b)))
}
plog.Debug(p, "NewFromRoots", "found prospects", len(p.Prospects))
return p, nil
} | go | func NewFromRoots(roots []string, opts *RootsOptions) (*Parser, error) {
if opts == nil {
opts = &RootsOptions{}
}
if len(roots) == 0 {
pwd, _ := os.Getwd()
roots = append(roots, pwd)
}
p := New()
plog.Debug(p, "NewFromRoots", "roots", roots, "options", opts)
callback := func(path string, de *godirwalk.Dirent) error {
if IsProspect(path, opts.Ignores...) {
if de.IsDir() {
return nil
}
roots = append(roots, path)
return nil
}
if de.IsDir() {
return filepath.SkipDir
}
return nil
}
wopts := &godirwalk.Options{
FollowSymbolicLinks: true,
Callback: callback,
}
for _, root := range roots {
plog.Debug(p, "NewFromRoots", "walking", root)
err := godirwalk.Walk(root, wopts)
if err != nil {
return p, err
}
}
dd := map[string]string{}
fd := &finder{id: time.Now()}
for _, r := range roots {
var names []string
if opts.IgnoreImports {
names, _ = fd.findAllGoFiles(r)
} else {
names, _ = fd.findAllGoFilesImports(r)
}
for _, n := range names {
if IsProspect(n) {
plog.Debug(p, "NewFromRoots", "mapping", n)
dd[n] = n
}
}
}
for path := range dd {
plog.Debug(p, "NewFromRoots", "reading file", path)
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
p.Prospects = append(p.Prospects, NewFile(path, bytes.NewReader(b)))
}
plog.Debug(p, "NewFromRoots", "found prospects", len(p.Prospects))
return p, nil
} | [
"func",
"NewFromRoots",
"(",
"roots",
"[",
"]",
"string",
",",
"opts",
"*",
"RootsOptions",
")",
"(",
"*",
"Parser",
",",
"error",
")",
"{",
"if",
"opts",
"==",
"nil",
"{",
"opts",
"=",
"&",
"RootsOptions",
"{",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"roots",
")",
"==",
"0",
"{",
"pwd",
",",
"_",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"roots",
"=",
"append",
"(",
"roots",
",",
"pwd",
")",
"\n",
"}",
"\n",
"p",
":=",
"New",
"(",
")",
"\n",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"NewFromRoots\"",
",",
"\"roots\"",
",",
"roots",
",",
"\"options\"",
",",
"opts",
")",
"\n",
"callback",
":=",
"func",
"(",
"path",
"string",
",",
"de",
"*",
"godirwalk",
".",
"Dirent",
")",
"error",
"{",
"if",
"IsProspect",
"(",
"path",
",",
"opts",
".",
"Ignores",
"...",
")",
"{",
"if",
"de",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"roots",
"=",
"append",
"(",
"roots",
",",
"path",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"de",
".",
"IsDir",
"(",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"wopts",
":=",
"&",
"godirwalk",
".",
"Options",
"{",
"FollowSymbolicLinks",
":",
"true",
",",
"Callback",
":",
"callback",
",",
"}",
"\n",
"for",
"_",
",",
"root",
":=",
"range",
"roots",
"{",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"NewFromRoots\"",
",",
"\"walking\"",
",",
"root",
")",
"\n",
"err",
":=",
"godirwalk",
".",
"Walk",
"(",
"root",
",",
"wopts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"p",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"dd",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"fd",
":=",
"&",
"finder",
"{",
"id",
":",
"time",
".",
"Now",
"(",
")",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"roots",
"{",
"var",
"names",
"[",
"]",
"string",
"\n",
"if",
"opts",
".",
"IgnoreImports",
"{",
"names",
",",
"_",
"=",
"fd",
".",
"findAllGoFiles",
"(",
"r",
")",
"\n",
"}",
"else",
"{",
"names",
",",
"_",
"=",
"fd",
".",
"findAllGoFilesImports",
"(",
"r",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"names",
"{",
"if",
"IsProspect",
"(",
"n",
")",
"{",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"NewFromRoots\"",
",",
"\"mapping\"",
",",
"n",
")",
"\n",
"dd",
"[",
"n",
"]",
"=",
"n",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"path",
":=",
"range",
"dd",
"{",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"NewFromRoots\"",
",",
"\"reading file\"",
",",
"path",
")",
"\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"p",
".",
"Prospects",
"=",
"append",
"(",
"p",
".",
"Prospects",
",",
"NewFile",
"(",
"path",
",",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
")",
"\n",
"}",
"\n",
"plog",
".",
"Debug",
"(",
"p",
",",
"\"NewFromRoots\"",
",",
"\"found prospects\"",
",",
"len",
"(",
"p",
".",
"Prospects",
")",
")",
"\n",
"return",
"p",
",",
"nil",
"\n",
"}"
] | // NewFromRoots scans the file roots provided and returns a
// new Parser containing the prospects | [
"NewFromRoots",
"scans",
"the",
"file",
"roots",
"provided",
"and",
"returns",
"a",
"new",
"Parser",
"containing",
"the",
"prospects"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/jam/parser/roots.go#L27-L89 | train |
gobuffalo/packr | v2/file/file.go | NewFile | func NewFile(name string, b []byte) (File, error) {
return packd.NewFile(name, bytes.NewReader(b))
} | go | func NewFile(name string, b []byte) (File, error) {
return packd.NewFile(name, bytes.NewReader(b))
} | [
"func",
"NewFile",
"(",
"name",
"string",
",",
"b",
"[",
"]",
"byte",
")",
"(",
"File",
",",
"error",
")",
"{",
"return",
"packd",
".",
"NewFile",
"(",
"name",
",",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
"\n",
"}"
] | // NewFile returns a virtual File implementation | [
"NewFile",
"returns",
"a",
"virtual",
"File",
"implementation"
] | 9819ef1571983a956c49475cb0524d8a4971620f | https://github.com/gobuffalo/packr/blob/9819ef1571983a956c49475cb0524d8a4971620f/v2/file/file.go#L21-L23 | train |
koding/kite | heartbeat.go | RegisterHTTPForever | func (k *Kite) RegisterHTTPForever(kiteURL *url.URL) {
// Create the httpBackoffRegister that RegisterHTTPForever will
// use to backoff repeated register attempts.
httpRegisterBackOff := backoff.NewExponentialBackOff()
httpRegisterBackOff.InitialInterval = 30 * time.Second
httpRegisterBackOff.MaxInterval = 5 * time.Minute
httpRegisterBackOff.Multiplier = 1.7
httpRegisterBackOff.MaxElapsedTime = 0
register := func() error {
_, err := k.RegisterHTTP(kiteURL)
if err != nil {
k.Log.Error("Cannot register to Kontrol: %s Will retry after %d seconds",
err,
httpRegisterBackOff.NextBackOff()/time.Second)
return err
}
return nil
}
// this will retry register forever
err := backoff.Retry(register, httpRegisterBackOff)
if err != nil {
k.Log.Error("BackOff stopped retrying with Error '%s'", err)
}
} | go | func (k *Kite) RegisterHTTPForever(kiteURL *url.URL) {
// Create the httpBackoffRegister that RegisterHTTPForever will
// use to backoff repeated register attempts.
httpRegisterBackOff := backoff.NewExponentialBackOff()
httpRegisterBackOff.InitialInterval = 30 * time.Second
httpRegisterBackOff.MaxInterval = 5 * time.Minute
httpRegisterBackOff.Multiplier = 1.7
httpRegisterBackOff.MaxElapsedTime = 0
register := func() error {
_, err := k.RegisterHTTP(kiteURL)
if err != nil {
k.Log.Error("Cannot register to Kontrol: %s Will retry after %d seconds",
err,
httpRegisterBackOff.NextBackOff()/time.Second)
return err
}
return nil
}
// this will retry register forever
err := backoff.Retry(register, httpRegisterBackOff)
if err != nil {
k.Log.Error("BackOff stopped retrying with Error '%s'", err)
}
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"RegisterHTTPForever",
"(",
"kiteURL",
"*",
"url",
".",
"URL",
")",
"{",
"httpRegisterBackOff",
":=",
"backoff",
".",
"NewExponentialBackOff",
"(",
")",
"\n",
"httpRegisterBackOff",
".",
"InitialInterval",
"=",
"30",
"*",
"time",
".",
"Second",
"\n",
"httpRegisterBackOff",
".",
"MaxInterval",
"=",
"5",
"*",
"time",
".",
"Minute",
"\n",
"httpRegisterBackOff",
".",
"Multiplier",
"=",
"1.7",
"\n",
"httpRegisterBackOff",
".",
"MaxElapsedTime",
"=",
"0",
"\n",
"register",
":=",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"k",
".",
"RegisterHTTP",
"(",
"kiteURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"Cannot register to Kontrol: %s Will retry after %d seconds\"",
",",
"err",
",",
"httpRegisterBackOff",
".",
"NextBackOff",
"(",
")",
"/",
"time",
".",
"Second",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"backoff",
".",
"Retry",
"(",
"register",
",",
"httpRegisterBackOff",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"BackOff stopped retrying with Error '%s'\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // RegisterHTTPForever is just like RegisterHTTP however it first tries to
// register forever until a response from kontrol is received. It's useful to
// use it during app initializations. After the registration a reconnect is
// automatically handled inside the RegisterHTTP method. | [
"RegisterHTTPForever",
"is",
"just",
"like",
"RegisterHTTP",
"however",
"it",
"first",
"tries",
"to",
"register",
"forever",
"until",
"a",
"response",
"from",
"kontrol",
"is",
"received",
".",
"It",
"s",
"useful",
"to",
"use",
"it",
"during",
"app",
"initializations",
".",
"After",
"the",
"registration",
"a",
"reconnect",
"is",
"automatically",
"handled",
"inside",
"the",
"RegisterHTTP",
"method",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/heartbeat.go#L90-L116 | train |
koding/kite | heartbeat.go | handleHeartbeat | func (k *Kite) handleHeartbeat(r *Request) (interface{}, error) {
req, err := newHeartbeatReq(r)
if err != nil {
return nil, err
}
k.heartbeatC <- req
return nil, req.ping()
} | go | func (k *Kite) handleHeartbeat(r *Request) (interface{}, error) {
req, err := newHeartbeatReq(r)
if err != nil {
return nil, err
}
k.heartbeatC <- req
return nil, req.ping()
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"handleHeartbeat",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"newHeartbeatReq",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"k",
".",
"heartbeatC",
"<-",
"req",
"\n",
"return",
"nil",
",",
"req",
".",
"ping",
"(",
")",
"\n",
"}"
] | // handleHeartbeat pings the callback with the given interval seconds. | [
"handleHeartbeat",
"pings",
"the",
"callback",
"with",
"the",
"given",
"interval",
"seconds",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/heartbeat.go#L246-L255 | train |
koding/kite | dnode/callback.go | Call | func (f Function) Call(args ...interface{}) error {
if !f.IsValid() {
return errors.New("invalid function")
}
return f.Caller.Call(args...)
} | go | func (f Function) Call(args ...interface{}) error {
if !f.IsValid() {
return errors.New("invalid function")
}
return f.Caller.Call(args...)
} | [
"func",
"(",
"f",
"Function",
")",
"Call",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"!",
"f",
".",
"IsValid",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"invalid function\"",
")",
"\n",
"}",
"\n",
"return",
"f",
".",
"Caller",
".",
"Call",
"(",
"args",
"...",
")",
"\n",
"}"
] | // Call the received function. | [
"Call",
"the",
"received",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/callback.go#L18-L23 | train |
koding/kite | dnode/callback.go | ParseCallbacks | func ParseCallbacks(msg *Message, sender func(id uint64, args []interface{}) error) error {
// Parse callbacks field and create callback functions.
for methodID, path := range msg.Callbacks {
id, err := strconv.ParseUint(methodID, 10, 64)
if err != nil {
return err
}
f := func(args ...interface{}) error { return sender(id, args) }
spec := CallbackSpec{path, Function{functionReceived(f)}}
msg.Arguments.CallbackSpecs = append(msg.Arguments.CallbackSpecs, spec)
}
return nil
} | go | func ParseCallbacks(msg *Message, sender func(id uint64, args []interface{}) error) error {
// Parse callbacks field and create callback functions.
for methodID, path := range msg.Callbacks {
id, err := strconv.ParseUint(methodID, 10, 64)
if err != nil {
return err
}
f := func(args ...interface{}) error { return sender(id, args) }
spec := CallbackSpec{path, Function{functionReceived(f)}}
msg.Arguments.CallbackSpecs = append(msg.Arguments.CallbackSpecs, spec)
}
return nil
} | [
"func",
"ParseCallbacks",
"(",
"msg",
"*",
"Message",
",",
"sender",
"func",
"(",
"id",
"uint64",
",",
"args",
"[",
"]",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"for",
"methodID",
",",
"path",
":=",
"range",
"msg",
".",
"Callbacks",
"{",
"id",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"methodID",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
":=",
"func",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"sender",
"(",
"id",
",",
"args",
")",
"}",
"\n",
"spec",
":=",
"CallbackSpec",
"{",
"path",
",",
"Function",
"{",
"functionReceived",
"(",
"f",
")",
"}",
"}",
"\n",
"msg",
".",
"Arguments",
".",
"CallbackSpecs",
"=",
"append",
"(",
"msg",
".",
"Arguments",
".",
"CallbackSpecs",
",",
"spec",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // parseCallbacks parses the message's "callbacks" field and prepares
// callback functions in "arguments" field. | [
"parseCallbacks",
"parses",
"the",
"message",
"s",
"callbacks",
"field",
"and",
"prepares",
"callback",
"functions",
"in",
"arguments",
"field",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/callback.go#L78-L92 | train |
koding/kite | kontrol/node.go | Flatten | func (n *Node) Flatten() []*Node {
nodes := make([]*Node, 0)
for _, node := range n.Node.Nodes {
if node.Dir {
nodes = append(nodes, NewNode(node).Flatten()...)
continue
}
nodes = append(nodes, NewNode(node))
}
return nodes
} | go | func (n *Node) Flatten() []*Node {
nodes := make([]*Node, 0)
for _, node := range n.Node.Nodes {
if node.Dir {
nodes = append(nodes, NewNode(node).Flatten()...)
continue
}
nodes = append(nodes, NewNode(node))
}
return nodes
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"Flatten",
"(",
")",
"[",
"]",
"*",
"Node",
"{",
"nodes",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"0",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"n",
".",
"Node",
".",
"Nodes",
"{",
"if",
"node",
".",
"Dir",
"{",
"nodes",
"=",
"append",
"(",
"nodes",
",",
"NewNode",
"(",
"node",
")",
".",
"Flatten",
"(",
")",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"nodes",
"=",
"append",
"(",
"nodes",
",",
"NewNode",
"(",
"node",
")",
")",
"\n",
"}",
"\n",
"return",
"nodes",
"\n",
"}"
] | // Flatten converts the recursive etcd directory structure to a flat one that
// contains all kontrolNodes | [
"Flatten",
"converts",
"the",
"recursive",
"etcd",
"directory",
"structure",
"to",
"a",
"flat",
"one",
"that",
"contains",
"all",
"kontrolNodes"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/node.go#L33-L45 | train |
koding/kite | kontrol/node.go | Kite | func (n *Node) Kite() (*protocol.KiteWithToken, error) {
kite, err := n.KiteFromKey()
if err != nil {
return nil, err
}
val, err := n.Value()
if err != nil {
return nil, err
}
return &protocol.KiteWithToken{
Kite: *kite,
URL: val.URL,
KeyID: val.KeyID,
}, nil
} | go | func (n *Node) Kite() (*protocol.KiteWithToken, error) {
kite, err := n.KiteFromKey()
if err != nil {
return nil, err
}
val, err := n.Value()
if err != nil {
return nil, err
}
return &protocol.KiteWithToken{
Kite: *kite,
URL: val.URL,
KeyID: val.KeyID,
}, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"Kite",
"(",
")",
"(",
"*",
"protocol",
".",
"KiteWithToken",
",",
"error",
")",
"{",
"kite",
",",
"err",
":=",
"n",
".",
"KiteFromKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"val",
",",
"err",
":=",
"n",
".",
"Value",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"protocol",
".",
"KiteWithToken",
"{",
"Kite",
":",
"*",
"kite",
",",
"URL",
":",
"val",
".",
"URL",
",",
"KeyID",
":",
"val",
".",
"KeyID",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Kite returns a single kite gathered from the key and the value for the
// current node. | [
"Kite",
"returns",
"a",
"single",
"kite",
"gathered",
"from",
"the",
"key",
"and",
"the",
"value",
"for",
"the",
"current",
"node",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/node.go#L49-L65 | train |
koding/kite | kontrol/node.go | Value | func (n *Node) Value() (kontrolprotocol.RegisterValue, error) {
var rv kontrolprotocol.RegisterValue
err := json.Unmarshal([]byte(n.Node.Value), &rv)
return rv, err
} | go | func (n *Node) Value() (kontrolprotocol.RegisterValue, error) {
var rv kontrolprotocol.RegisterValue
err := json.Unmarshal([]byte(n.Node.Value), &rv)
return rv, err
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"Value",
"(",
")",
"(",
"kontrolprotocol",
".",
"RegisterValue",
",",
"error",
")",
"{",
"var",
"rv",
"kontrolprotocol",
".",
"RegisterValue",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"n",
".",
"Node",
".",
"Value",
")",
",",
"&",
"rv",
")",
"\n",
"return",
"rv",
",",
"err",
"\n",
"}"
] | // Value returns the value associated with the current node. | [
"Value",
"returns",
"the",
"value",
"associated",
"with",
"the",
"current",
"node",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/node.go#L88-L92 | train |
koding/kite | kontrol/node.go | Kites | func (n *Node) Kites() (Kites, error) {
// Get all nodes recursively.
nodes := n.Flatten()
// Convert etcd nodes to kites.
var err error
kites := make(Kites, len(nodes))
for i, n := range nodes {
kites[i], err = n.Kite()
if err != nil {
return nil, err
}
}
return kites, nil
} | go | func (n *Node) Kites() (Kites, error) {
// Get all nodes recursively.
nodes := n.Flatten()
// Convert etcd nodes to kites.
var err error
kites := make(Kites, len(nodes))
for i, n := range nodes {
kites[i], err = n.Kite()
if err != nil {
return nil, err
}
}
return kites, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"Kites",
"(",
")",
"(",
"Kites",
",",
"error",
")",
"{",
"nodes",
":=",
"n",
".",
"Flatten",
"(",
")",
"\n",
"var",
"err",
"error",
"\n",
"kites",
":=",
"make",
"(",
"Kites",
",",
"len",
"(",
"nodes",
")",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"nodes",
"{",
"kites",
"[",
"i",
"]",
",",
"err",
"=",
"n",
".",
"Kite",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"kites",
",",
"nil",
"\n",
"}"
] | // Kites returns a list of kites that are gathered by collecting recursively
// all nodes under the current node. | [
"Kites",
"returns",
"a",
"list",
"of",
"kites",
"that",
"are",
"gathered",
"by",
"collecting",
"recursively",
"all",
"nodes",
"under",
"the",
"current",
"node",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/node.go#L96-L111 | train |
koding/kite | errors.go | createError | func createError(req *Request, r interface{}) *Error {
if r == nil {
return nil
}
var kiteErr *Error
switch err := r.(type) {
case *Error:
kiteErr = err
case *dnode.ArgumentError:
kiteErr = &Error{
Type: "argumentError",
Message: err.Error(),
}
default:
kiteErr = &Error{
Type: "genericError",
Message: fmt.Sprint(r),
}
}
if kiteErr.RequestID == "" && req != nil {
kiteErr.RequestID = req.ID
}
return kiteErr
} | go | func createError(req *Request, r interface{}) *Error {
if r == nil {
return nil
}
var kiteErr *Error
switch err := r.(type) {
case *Error:
kiteErr = err
case *dnode.ArgumentError:
kiteErr = &Error{
Type: "argumentError",
Message: err.Error(),
}
default:
kiteErr = &Error{
Type: "genericError",
Message: fmt.Sprint(r),
}
}
if kiteErr.RequestID == "" && req != nil {
kiteErr.RequestID = req.ID
}
return kiteErr
} | [
"func",
"createError",
"(",
"req",
"*",
"Request",
",",
"r",
"interface",
"{",
"}",
")",
"*",
"Error",
"{",
"if",
"r",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"kiteErr",
"*",
"Error",
"\n",
"switch",
"err",
":=",
"r",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Error",
":",
"kiteErr",
"=",
"err",
"\n",
"case",
"*",
"dnode",
".",
"ArgumentError",
":",
"kiteErr",
"=",
"&",
"Error",
"{",
"Type",
":",
"\"argumentError\"",
",",
"Message",
":",
"err",
".",
"Error",
"(",
")",
",",
"}",
"\n",
"default",
":",
"kiteErr",
"=",
"&",
"Error",
"{",
"Type",
":",
"\"genericError\"",
",",
"Message",
":",
"fmt",
".",
"Sprint",
"(",
"r",
")",
",",
"}",
"\n",
"}",
"\n",
"if",
"kiteErr",
".",
"RequestID",
"==",
"\"\"",
"&&",
"req",
"!=",
"nil",
"{",
"kiteErr",
".",
"RequestID",
"=",
"req",
".",
"ID",
"\n",
"}",
"\n",
"return",
"kiteErr",
"\n",
"}"
] | // createError creates a new kite.Error for the given r variable | [
"createError",
"creates",
"a",
"new",
"kite",
".",
"Error",
"for",
"the",
"given",
"r",
"variable"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/errors.go#L41-L67 | train |
koding/kite | reverseproxy/reverseproxy.go | isWebsocket | func isWebsocket(req *http.Request) bool {
if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" ||
!strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") {
return false
}
return true
} | go | func isWebsocket(req *http.Request) bool {
if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" ||
!strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") {
return false
}
return true
} | [
"func",
"isWebsocket",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"if",
"strings",
".",
"ToLower",
"(",
"req",
".",
"Header",
".",
"Get",
"(",
"\"Upgrade\"",
")",
")",
"!=",
"\"websocket\"",
"||",
"!",
"strings",
".",
"Contains",
"(",
"strings",
".",
"ToLower",
"(",
"req",
".",
"Header",
".",
"Get",
"(",
"\"Connection\"",
")",
")",
",",
"\"upgrade\"",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // isWebsocket checks wether the incoming request is a part of websocket
// handshake | [
"isWebsocket",
"checks",
"wether",
"the",
"incoming",
"request",
"is",
"a",
"part",
"of",
"websocket",
"handshake"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/reverseproxy/reverseproxy.go#L109-L115 | train |
koding/kite | reverseproxy/reverseproxy.go | ListenAndServe | func (p *Proxy) ListenAndServe() error {
var err error
p.listener, err = net.Listen("tcp4",
net.JoinHostPort(p.Kite.Config.IP, strconv.Itoa(p.Kite.Config.Port)))
if err != nil {
return err
}
p.Kite.Log.Info("Listening on: %s", p.listener.Addr().String())
close(p.readyC)
server := http.Server{
Handler: p.mux,
}
defer close(p.closeC)
return server.Serve(p.listener)
} | go | func (p *Proxy) ListenAndServe() error {
var err error
p.listener, err = net.Listen("tcp4",
net.JoinHostPort(p.Kite.Config.IP, strconv.Itoa(p.Kite.Config.Port)))
if err != nil {
return err
}
p.Kite.Log.Info("Listening on: %s", p.listener.Addr().String())
close(p.readyC)
server := http.Server{
Handler: p.mux,
}
defer close(p.closeC)
return server.Serve(p.listener)
} | [
"func",
"(",
"p",
"*",
"Proxy",
")",
"ListenAndServe",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"p",
".",
"listener",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"\"tcp4\"",
",",
"net",
".",
"JoinHostPort",
"(",
"p",
".",
"Kite",
".",
"Config",
".",
"IP",
",",
"strconv",
".",
"Itoa",
"(",
"p",
".",
"Kite",
".",
"Config",
".",
"Port",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"Kite",
".",
"Log",
".",
"Info",
"(",
"\"Listening on: %s\"",
",",
"p",
".",
"listener",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"close",
"(",
"p",
".",
"readyC",
")",
"\n",
"server",
":=",
"http",
".",
"Server",
"{",
"Handler",
":",
"p",
".",
"mux",
",",
"}",
"\n",
"defer",
"close",
"(",
"p",
".",
"closeC",
")",
"\n",
"return",
"server",
".",
"Serve",
"(",
"p",
".",
"listener",
")",
"\n",
"}"
] | // ListenAndServe listens on the TCP network address addr and then calls Serve
// with handler to handle requests on incoming connections. | [
"ListenAndServe",
"listens",
"on",
"the",
"TCP",
"network",
"address",
"addr",
"and",
"then",
"calls",
"Serve",
"with",
"handler",
"to",
"handle",
"requests",
"on",
"incoming",
"connections",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/reverseproxy/reverseproxy.go#L195-L212 | train |
koding/kite | systeminfo/systeminfo_windows.go | diskStats | func diskStats() (*disk, error) {
var (
freeBytes uint64 = 0
totalBytes uint64 = 0
)
// windows sets return value to 0 when function fails.
ret, _, err := procGetDiskFreeSpaceExW.Call(
0,
uintptr(unsafe.Pointer(&freeBytes)),
uintptr(unsafe.Pointer(&totalBytes)),
0,
)
if ret == 0 {
return nil, err
}
// diskStats functions from other platforms return disk usage in kiB.
return &disk{
Usage: (totalBytes - freeBytes) / 1024,
Total: totalBytes / 1024,
}, nil
} | go | func diskStats() (*disk, error) {
var (
freeBytes uint64 = 0
totalBytes uint64 = 0
)
// windows sets return value to 0 when function fails.
ret, _, err := procGetDiskFreeSpaceExW.Call(
0,
uintptr(unsafe.Pointer(&freeBytes)),
uintptr(unsafe.Pointer(&totalBytes)),
0,
)
if ret == 0 {
return nil, err
}
// diskStats functions from other platforms return disk usage in kiB.
return &disk{
Usage: (totalBytes - freeBytes) / 1024,
Total: totalBytes / 1024,
}, nil
} | [
"func",
"diskStats",
"(",
")",
"(",
"*",
"disk",
",",
"error",
")",
"{",
"var",
"(",
"freeBytes",
"uint64",
"=",
"0",
"\n",
"totalBytes",
"uint64",
"=",
"0",
"\n",
")",
"\n",
"ret",
",",
"_",
",",
"err",
":=",
"procGetDiskFreeSpaceExW",
".",
"Call",
"(",
"0",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"freeBytes",
")",
")",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"totalBytes",
")",
")",
",",
"0",
",",
")",
"\n",
"if",
"ret",
"==",
"0",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"disk",
"{",
"Usage",
":",
"(",
"totalBytes",
"-",
"freeBytes",
")",
"/",
"1024",
",",
"Total",
":",
"totalBytes",
"/",
"1024",
",",
"}",
",",
"nil",
"\n",
"}"
] | // diskStats returns information about the amount of space that is available on
// a current disk volume for the user who calls this function. | [
"diskStats",
"returns",
"information",
"about",
"the",
"amount",
"of",
"space",
"that",
"is",
"available",
"on",
"a",
"current",
"disk",
"volume",
"for",
"the",
"user",
"who",
"calls",
"this",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/systeminfo/systeminfo_windows.go#L17-L39 | train |
koding/kite | systeminfo/systeminfo_windows.go | memoryStats | func memoryStats() (*memory, error) {
mstat := struct {
size uint32
_ uint32
totalPhys uint64
availPhys uint64
_ [5]uint64
}{}
// windows sets return value to 0 when function fails.
mstat.size = uint32(unsafe.Sizeof(mstat))
ret, _, err := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&mstat)))
if ret == 0 {
return nil, err
}
// memoryStats functions from other platforms return memory usage in bytes.
return &memory{
Usage: mstat.totalPhys - mstat.availPhys,
Total: mstat.totalPhys,
}, nil
} | go | func memoryStats() (*memory, error) {
mstat := struct {
size uint32
_ uint32
totalPhys uint64
availPhys uint64
_ [5]uint64
}{}
// windows sets return value to 0 when function fails.
mstat.size = uint32(unsafe.Sizeof(mstat))
ret, _, err := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&mstat)))
if ret == 0 {
return nil, err
}
// memoryStats functions from other platforms return memory usage in bytes.
return &memory{
Usage: mstat.totalPhys - mstat.availPhys,
Total: mstat.totalPhys,
}, nil
} | [
"func",
"memoryStats",
"(",
")",
"(",
"*",
"memory",
",",
"error",
")",
"{",
"mstat",
":=",
"struct",
"{",
"size",
"uint32",
"\n",
"_",
"uint32",
"\n",
"totalPhys",
"uint64",
"\n",
"availPhys",
"uint64",
"\n",
"_",
"[",
"5",
"]",
"uint64",
"\n",
"}",
"{",
"}",
"\n",
"mstat",
".",
"size",
"=",
"uint32",
"(",
"unsafe",
".",
"Sizeof",
"(",
"mstat",
")",
")",
"\n",
"ret",
",",
"_",
",",
"err",
":=",
"procGlobalMemoryStatusEx",
".",
"Call",
"(",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"mstat",
")",
")",
")",
"\n",
"if",
"ret",
"==",
"0",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"memory",
"{",
"Usage",
":",
"mstat",
".",
"totalPhys",
"-",
"mstat",
".",
"availPhys",
",",
"Total",
":",
"mstat",
".",
"totalPhys",
",",
"}",
",",
"nil",
"\n",
"}"
] | // memoryStatus retrieves information about the system's current usage of
// physical memory. | [
"memoryStatus",
"retrieves",
"information",
"about",
"the",
"system",
"s",
"current",
"usage",
"of",
"physical",
"memory",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/systeminfo/systeminfo_windows.go#L43-L65 | train |
koding/kite | protocol/webrtc.go | ParsePayload | func (w *WebRTCSignalMessage) ParsePayload() (*Payload, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.isParsed {
return w.parsedPayload, nil
}
payload := &Payload{}
if err := json.Unmarshal(w.Payload, payload); err != nil {
return nil, err
}
w.parsedPayload = payload
return payload, nil
} | go | func (w *WebRTCSignalMessage) ParsePayload() (*Payload, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.isParsed {
return w.parsedPayload, nil
}
payload := &Payload{}
if err := json.Unmarshal(w.Payload, payload); err != nil {
return nil, err
}
w.parsedPayload = payload
return payload, nil
} | [
"func",
"(",
"w",
"*",
"WebRTCSignalMessage",
")",
"ParsePayload",
"(",
")",
"(",
"*",
"Payload",
",",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"w",
".",
"isParsed",
"{",
"return",
"w",
".",
"parsedPayload",
",",
"nil",
"\n",
"}",
"\n",
"payload",
":=",
"&",
"Payload",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"w",
".",
"Payload",
",",
"payload",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"w",
".",
"parsedPayload",
"=",
"payload",
"\n",
"return",
"payload",
",",
"nil",
"\n",
"}"
] | // ParsePayload parses the payload if it is not parsed previously. This method
// can be called concurrently. | [
"ParsePayload",
"parses",
"the",
"payload",
"if",
"it",
"is",
"not",
"parsed",
"previously",
".",
"This",
"method",
"can",
"be",
"called",
"concurrently",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/protocol/webrtc.go#L50-L65 | train |
koding/kite | logger.go | getLogLevel | func getLogLevel() Level {
switch strings.ToUpper(os.Getenv("KITE_LOG_LEVEL")) {
case "DEBUG":
return DEBUG
case "WARNING":
return WARNING
case "ERROR":
return ERROR
case "FATAL":
return FATAL
default:
return INFO
}
} | go | func getLogLevel() Level {
switch strings.ToUpper(os.Getenv("KITE_LOG_LEVEL")) {
case "DEBUG":
return DEBUG
case "WARNING":
return WARNING
case "ERROR":
return ERROR
case "FATAL":
return FATAL
default:
return INFO
}
} | [
"func",
"getLogLevel",
"(",
")",
"Level",
"{",
"switch",
"strings",
".",
"ToUpper",
"(",
"os",
".",
"Getenv",
"(",
"\"KITE_LOG_LEVEL\"",
")",
")",
"{",
"case",
"\"DEBUG\"",
":",
"return",
"DEBUG",
"\n",
"case",
"\"WARNING\"",
":",
"return",
"WARNING",
"\n",
"case",
"\"ERROR\"",
":",
"return",
"ERROR",
"\n",
"case",
"\"FATAL\"",
":",
"return",
"FATAL",
"\n",
"default",
":",
"return",
"INFO",
"\n",
"}",
"\n",
"}"
] | // getLogLevel returns the logging level defined via the KITE_LOG_LEVEL
// environment. It returns Info by default if no environment variable
// is set. | [
"getLogLevel",
"returns",
"the",
"logging",
"level",
"defined",
"via",
"the",
"KITE_LOG_LEVEL",
"environment",
".",
"It",
"returns",
"Info",
"by",
"default",
"if",
"no",
"environment",
"variable",
"is",
"set",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/logger.go#L46-L59 | train |
koding/kite | logger.go | convertLevel | func convertLevel(l Level) logging.Level {
switch l {
case DEBUG:
return logging.DEBUG
case WARNING:
return logging.WARNING
case ERROR:
return logging.ERROR
case FATAL:
return logging.CRITICAL
default:
return logging.INFO
}
} | go | func convertLevel(l Level) logging.Level {
switch l {
case DEBUG:
return logging.DEBUG
case WARNING:
return logging.WARNING
case ERROR:
return logging.ERROR
case FATAL:
return logging.CRITICAL
default:
return logging.INFO
}
} | [
"func",
"convertLevel",
"(",
"l",
"Level",
")",
"logging",
".",
"Level",
"{",
"switch",
"l",
"{",
"case",
"DEBUG",
":",
"return",
"logging",
".",
"DEBUG",
"\n",
"case",
"WARNING",
":",
"return",
"logging",
".",
"WARNING",
"\n",
"case",
"ERROR",
":",
"return",
"logging",
".",
"ERROR",
"\n",
"case",
"FATAL",
":",
"return",
"logging",
".",
"CRITICAL",
"\n",
"default",
":",
"return",
"logging",
".",
"INFO",
"\n",
"}",
"\n",
"}"
] | // convertLevel converts a kite level into logging level | [
"convertLevel",
"converts",
"a",
"kite",
"level",
"into",
"logging",
"level"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/logger.go#L62-L75 | train |
koding/kite | dnode/scrub.go | fields | func (s *Scrubber) fields(rv reflect.Value, path Path, callbacks map[string]Path) {
for i := 0; i < rv.NumField(); i++ {
sf := rv.Type().Field(i)
if sf.PkgPath != "" && !sf.Anonymous { // unexported.
continue
}
// dnode uses JSON package tags for field naming so we need to
// discard their comma-separated options.
tag := sf.Tag.Get("json")
if idx := strings.Index(tag, ","); idx != -1 {
tag = tag[:idx]
}
if tag == "-" {
continue
}
// do not collect callbacks for "-" tagged fields.
if skip := sf.Tag.Get("dnode"); skip == "-" {
continue
}
var name = tag
if name == "" {
name = sf.Name
}
if sf.Anonymous {
s.collect(rv.Field(i), path, callbacks)
} else {
s.collect(rv.Field(i), append(path, name), callbacks)
}
}
} | go | func (s *Scrubber) fields(rv reflect.Value, path Path, callbacks map[string]Path) {
for i := 0; i < rv.NumField(); i++ {
sf := rv.Type().Field(i)
if sf.PkgPath != "" && !sf.Anonymous { // unexported.
continue
}
// dnode uses JSON package tags for field naming so we need to
// discard their comma-separated options.
tag := sf.Tag.Get("json")
if idx := strings.Index(tag, ","); idx != -1 {
tag = tag[:idx]
}
if tag == "-" {
continue
}
// do not collect callbacks for "-" tagged fields.
if skip := sf.Tag.Get("dnode"); skip == "-" {
continue
}
var name = tag
if name == "" {
name = sf.Name
}
if sf.Anonymous {
s.collect(rv.Field(i), path, callbacks)
} else {
s.collect(rv.Field(i), append(path, name), callbacks)
}
}
} | [
"func",
"(",
"s",
"*",
"Scrubber",
")",
"fields",
"(",
"rv",
"reflect",
".",
"Value",
",",
"path",
"Path",
",",
"callbacks",
"map",
"[",
"string",
"]",
"Path",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"rv",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"sf",
":=",
"rv",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
"\n",
"if",
"sf",
".",
"PkgPath",
"!=",
"\"\"",
"&&",
"!",
"sf",
".",
"Anonymous",
"{",
"continue",
"\n",
"}",
"\n",
"tag",
":=",
"sf",
".",
"Tag",
".",
"Get",
"(",
"\"json\"",
")",
"\n",
"if",
"idx",
":=",
"strings",
".",
"Index",
"(",
"tag",
",",
"\",\"",
")",
";",
"idx",
"!=",
"-",
"1",
"{",
"tag",
"=",
"tag",
"[",
":",
"idx",
"]",
"\n",
"}",
"\n",
"if",
"tag",
"==",
"\"-\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"skip",
":=",
"sf",
".",
"Tag",
".",
"Get",
"(",
"\"dnode\"",
")",
";",
"skip",
"==",
"\"-\"",
"{",
"continue",
"\n",
"}",
"\n",
"var",
"name",
"=",
"tag",
"\n",
"if",
"name",
"==",
"\"\"",
"{",
"name",
"=",
"sf",
".",
"Name",
"\n",
"}",
"\n",
"if",
"sf",
".",
"Anonymous",
"{",
"s",
".",
"collect",
"(",
"rv",
".",
"Field",
"(",
"i",
")",
",",
"path",
",",
"callbacks",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"collect",
"(",
"rv",
".",
"Field",
"(",
"i",
")",
",",
"append",
"(",
"path",
",",
"name",
")",
",",
"callbacks",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // fields walks over a structure and scrubs its fields. | [
"fields",
"walks",
"over",
"a",
"structure",
"and",
"scrubs",
"its",
"fields",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/scrub.go#L71-L103 | train |
koding/kite | dnode/scrub.go | methods | func (s *Scrubber) methods(rv reflect.Value, path Path, callbacks map[string]Path) {
for i := 0; i < rv.NumMethod(); i++ {
if rv.Type().Method(i).PkgPath == "" { // exported
cb, ok := rv.Method(i).Interface().(func(*Partial))
if !ok {
continue
}
name := rv.Type().Method(i).Name
name = strings.ToLower(name[0:1]) + name[1:]
s.register(cb, append(path, name), callbacks)
}
}
} | go | func (s *Scrubber) methods(rv reflect.Value, path Path, callbacks map[string]Path) {
for i := 0; i < rv.NumMethod(); i++ {
if rv.Type().Method(i).PkgPath == "" { // exported
cb, ok := rv.Method(i).Interface().(func(*Partial))
if !ok {
continue
}
name := rv.Type().Method(i).Name
name = strings.ToLower(name[0:1]) + name[1:]
s.register(cb, append(path, name), callbacks)
}
}
} | [
"func",
"(",
"s",
"*",
"Scrubber",
")",
"methods",
"(",
"rv",
"reflect",
".",
"Value",
",",
"path",
"Path",
",",
"callbacks",
"map",
"[",
"string",
"]",
"Path",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"rv",
".",
"NumMethod",
"(",
")",
";",
"i",
"++",
"{",
"if",
"rv",
".",
"Type",
"(",
")",
".",
"Method",
"(",
"i",
")",
".",
"PkgPath",
"==",
"\"\"",
"{",
"cb",
",",
"ok",
":=",
"rv",
".",
"Method",
"(",
"i",
")",
".",
"Interface",
"(",
")",
".",
"(",
"func",
"(",
"*",
"Partial",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"name",
":=",
"rv",
".",
"Type",
"(",
")",
".",
"Method",
"(",
"i",
")",
".",
"Name",
"\n",
"name",
"=",
"strings",
".",
"ToLower",
"(",
"name",
"[",
"0",
":",
"1",
"]",
")",
"+",
"name",
"[",
"1",
":",
"]",
"\n",
"s",
".",
"register",
"(",
"cb",
",",
"append",
"(",
"path",
",",
"name",
")",
",",
"callbacks",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // methods walks over a structure and scrubs its exported methods. | [
"methods",
"walks",
"over",
"a",
"structure",
"and",
"scrubs",
"its",
"exported",
"methods",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/scrub.go#L106-L119 | train |
koding/kite | kontrolclient.go | SetupKontrolClient | func (k *Kite) SetupKontrolClient() error {
if k.kontrol.Client != nil {
return nil // already prepared
}
if k.Config.KontrolURL == "" {
return errors.New("no kontrol URL given in config")
}
client := k.NewClient(k.Config.KontrolURL)
client.Kite = protocol.Kite{Name: "kontrol"} // for logging purposes
client.Auth = &Auth{
Type: "kiteKey",
Key: k.KiteKey(),
}
k.kontrol.Lock()
k.kontrol.Client = client
k.kontrol.Unlock()
k.kontrol.OnConnect(func() {
k.Log.Info("Connected to Kontrol")
k.Log.Debug("Connected to Kontrol with session %q", client.session.ID())
// try to re-register on connect
k.kontrol.Lock()
if k.kontrol.lastRegisteredURL != nil {
select {
case k.kontrol.registerChan <- k.kontrol.lastRegisteredURL:
default:
}
}
k.kontrol.Unlock()
// signal all other methods that are listening on this channel, that we
// are connected to kontrol.
k.kontrol.onceConnected.Do(func() { close(k.kontrol.readyConnected) })
})
k.kontrol.OnDisconnect(func() {
k.Log.Warning("Disconnected from Kontrol.")
})
// non blocking, is going to reconnect if the connection goes down.
if _, err := k.kontrol.DialForever(); err != nil {
return err
}
return nil
} | go | func (k *Kite) SetupKontrolClient() error {
if k.kontrol.Client != nil {
return nil // already prepared
}
if k.Config.KontrolURL == "" {
return errors.New("no kontrol URL given in config")
}
client := k.NewClient(k.Config.KontrolURL)
client.Kite = protocol.Kite{Name: "kontrol"} // for logging purposes
client.Auth = &Auth{
Type: "kiteKey",
Key: k.KiteKey(),
}
k.kontrol.Lock()
k.kontrol.Client = client
k.kontrol.Unlock()
k.kontrol.OnConnect(func() {
k.Log.Info("Connected to Kontrol")
k.Log.Debug("Connected to Kontrol with session %q", client.session.ID())
// try to re-register on connect
k.kontrol.Lock()
if k.kontrol.lastRegisteredURL != nil {
select {
case k.kontrol.registerChan <- k.kontrol.lastRegisteredURL:
default:
}
}
k.kontrol.Unlock()
// signal all other methods that are listening on this channel, that we
// are connected to kontrol.
k.kontrol.onceConnected.Do(func() { close(k.kontrol.readyConnected) })
})
k.kontrol.OnDisconnect(func() {
k.Log.Warning("Disconnected from Kontrol.")
})
// non blocking, is going to reconnect if the connection goes down.
if _, err := k.kontrol.DialForever(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"SetupKontrolClient",
"(",
")",
"error",
"{",
"if",
"k",
".",
"kontrol",
".",
"Client",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"k",
".",
"Config",
".",
"KontrolURL",
"==",
"\"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"no kontrol URL given in config\"",
")",
"\n",
"}",
"\n",
"client",
":=",
"k",
".",
"NewClient",
"(",
"k",
".",
"Config",
".",
"KontrolURL",
")",
"\n",
"client",
".",
"Kite",
"=",
"protocol",
".",
"Kite",
"{",
"Name",
":",
"\"kontrol\"",
"}",
"\n",
"client",
".",
"Auth",
"=",
"&",
"Auth",
"{",
"Type",
":",
"\"kiteKey\"",
",",
"Key",
":",
"k",
".",
"KiteKey",
"(",
")",
",",
"}",
"\n",
"k",
".",
"kontrol",
".",
"Lock",
"(",
")",
"\n",
"k",
".",
"kontrol",
".",
"Client",
"=",
"client",
"\n",
"k",
".",
"kontrol",
".",
"Unlock",
"(",
")",
"\n",
"k",
".",
"kontrol",
".",
"OnConnect",
"(",
"func",
"(",
")",
"{",
"k",
".",
"Log",
".",
"Info",
"(",
"\"Connected to Kontrol\"",
")",
"\n",
"k",
".",
"Log",
".",
"Debug",
"(",
"\"Connected to Kontrol with session %q\"",
",",
"client",
".",
"session",
".",
"ID",
"(",
")",
")",
"\n",
"k",
".",
"kontrol",
".",
"Lock",
"(",
")",
"\n",
"if",
"k",
".",
"kontrol",
".",
"lastRegisteredURL",
"!=",
"nil",
"{",
"select",
"{",
"case",
"k",
".",
"kontrol",
".",
"registerChan",
"<-",
"k",
".",
"kontrol",
".",
"lastRegisteredURL",
":",
"default",
":",
"}",
"\n",
"}",
"\n",
"k",
".",
"kontrol",
".",
"Unlock",
"(",
")",
"\n",
"k",
".",
"kontrol",
".",
"onceConnected",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"close",
"(",
"k",
".",
"kontrol",
".",
"readyConnected",
")",
"}",
")",
"\n",
"}",
")",
"\n",
"k",
".",
"kontrol",
".",
"OnDisconnect",
"(",
"func",
"(",
")",
"{",
"k",
".",
"Log",
".",
"Warning",
"(",
"\"Disconnected from Kontrol.\"",
")",
"\n",
"}",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"k",
".",
"kontrol",
".",
"DialForever",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetupKontrolClient setups and prepares a the kontrol instance. It connects
// to kontrol and reconnects again if there is any disconnections. This method
// is called internally whenever a kontrol client specific action is taking.
// However if you wish to connect earlier you may call this method. | [
"SetupKontrolClient",
"setups",
"and",
"prepares",
"a",
"the",
"kontrol",
"instance",
".",
"It",
"connects",
"to",
"kontrol",
"and",
"reconnects",
"again",
"if",
"there",
"is",
"any",
"disconnections",
".",
"This",
"method",
"is",
"called",
"internally",
"whenever",
"a",
"kontrol",
"client",
"specific",
"action",
"is",
"taking",
".",
"However",
"if",
"you",
"wish",
"to",
"connect",
"earlier",
"you",
"may",
"call",
"this",
"method",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L53-L102 | train |
koding/kite | kontrolclient.go | GetToken | func (k *Kite) GetToken(kite *protocol.Kite) (string, error) {
if err := k.SetupKontrolClient(); err != nil {
return "", err
}
<-k.kontrol.readyConnected
result, err := k.kontrol.TellWithTimeout("getToken", k.Config.Timeout, kite)
if err != nil {
return "", err
}
var tkn string
err = result.Unmarshal(&tkn)
if err != nil {
return "", err
}
return tkn, nil
} | go | func (k *Kite) GetToken(kite *protocol.Kite) (string, error) {
if err := k.SetupKontrolClient(); err != nil {
return "", err
}
<-k.kontrol.readyConnected
result, err := k.kontrol.TellWithTimeout("getToken", k.Config.Timeout, kite)
if err != nil {
return "", err
}
var tkn string
err = result.Unmarshal(&tkn)
if err != nil {
return "", err
}
return tkn, nil
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"GetToken",
"(",
"kite",
"*",
"protocol",
".",
"Kite",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"k",
".",
"SetupKontrolClient",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"<-",
"k",
".",
"kontrol",
".",
"readyConnected",
"\n",
"result",
",",
"err",
":=",
"k",
".",
"kontrol",
".",
"TellWithTimeout",
"(",
"\"getToken\"",
",",
"k",
".",
"Config",
".",
"Timeout",
",",
"kite",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"var",
"tkn",
"string",
"\n",
"err",
"=",
"result",
".",
"Unmarshal",
"(",
"&",
"tkn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"tkn",
",",
"nil",
"\n",
"}"
] | // GetToken is used to get a token for a single Kite.
//
// In case of calling GetToken multiple times, it usually
// returns the same token until it expires on Kontrol side. | [
"GetToken",
"is",
"used",
"to",
"get",
"a",
"token",
"for",
"a",
"single",
"Kite",
".",
"In",
"case",
"of",
"calling",
"GetToken",
"multiple",
"times",
"it",
"usually",
"returns",
"the",
"same",
"token",
"until",
"it",
"expires",
"on",
"Kontrol",
"side",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L187-L206 | train |
koding/kite | kontrolclient.go | GetTokenForce | func (k *Kite) GetTokenForce(kite *protocol.Kite) (string, error) {
if err := k.SetupKontrolClient(); err != nil {
return "", err
}
<-k.kontrol.readyConnected
args := &protocol.GetTokenArgs{
KontrolQuery: *kite.Query(),
Force: true,
}
result, err := k.kontrol.TellWithTimeout("getToken", k.Config.Timeout, args)
if err != nil {
return "", err
}
var tkn string
err = result.Unmarshal(&tkn)
if err != nil {
return "", err
}
return tkn, nil
} | go | func (k *Kite) GetTokenForce(kite *protocol.Kite) (string, error) {
if err := k.SetupKontrolClient(); err != nil {
return "", err
}
<-k.kontrol.readyConnected
args := &protocol.GetTokenArgs{
KontrolQuery: *kite.Query(),
Force: true,
}
result, err := k.kontrol.TellWithTimeout("getToken", k.Config.Timeout, args)
if err != nil {
return "", err
}
var tkn string
err = result.Unmarshal(&tkn)
if err != nil {
return "", err
}
return tkn, nil
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"GetTokenForce",
"(",
"kite",
"*",
"protocol",
".",
"Kite",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"k",
".",
"SetupKontrolClient",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"<-",
"k",
".",
"kontrol",
".",
"readyConnected",
"\n",
"args",
":=",
"&",
"protocol",
".",
"GetTokenArgs",
"{",
"KontrolQuery",
":",
"*",
"kite",
".",
"Query",
"(",
")",
",",
"Force",
":",
"true",
",",
"}",
"\n",
"result",
",",
"err",
":=",
"k",
".",
"kontrol",
".",
"TellWithTimeout",
"(",
"\"getToken\"",
",",
"k",
".",
"Config",
".",
"Timeout",
",",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"var",
"tkn",
"string",
"\n",
"err",
"=",
"result",
".",
"Unmarshal",
"(",
"&",
"tkn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"tkn",
",",
"nil",
"\n",
"}"
] | // GetTokenForce is used to obtain a new token for the given kite.
//
// It always returns a new token and forces a Kontrol to
// forget about any previous ones. | [
"GetTokenForce",
"is",
"used",
"to",
"obtain",
"a",
"new",
"token",
"for",
"the",
"given",
"kite",
".",
"It",
"always",
"returns",
"a",
"new",
"token",
"and",
"forces",
"a",
"Kontrol",
"to",
"forget",
"about",
"any",
"previous",
"ones",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L224-L248 | train |
koding/kite | kontrolclient.go | GetKey | func (k *Kite) GetKey() (string, error) {
if err := k.SetupKontrolClient(); err != nil {
return "", err
}
<-k.kontrol.readyConnected
result, err := k.kontrol.TellWithTimeout("getKey", k.Config.Timeout)
if err != nil {
return "", err
}
var key string
err = result.Unmarshal(&key)
if err != nil {
return "", err
}
k.configMu.Lock()
k.Config.KontrolKey = key
k.configMu.Unlock()
return key, nil
} | go | func (k *Kite) GetKey() (string, error) {
if err := k.SetupKontrolClient(); err != nil {
return "", err
}
<-k.kontrol.readyConnected
result, err := k.kontrol.TellWithTimeout("getKey", k.Config.Timeout)
if err != nil {
return "", err
}
var key string
err = result.Unmarshal(&key)
if err != nil {
return "", err
}
k.configMu.Lock()
k.Config.KontrolKey = key
k.configMu.Unlock()
return key, nil
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"GetKey",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"k",
".",
"SetupKontrolClient",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"<-",
"k",
".",
"kontrol",
".",
"readyConnected",
"\n",
"result",
",",
"err",
":=",
"k",
".",
"kontrol",
".",
"TellWithTimeout",
"(",
"\"getKey\"",
",",
"k",
".",
"Config",
".",
"Timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"var",
"key",
"string",
"\n",
"err",
"=",
"result",
".",
"Unmarshal",
"(",
"&",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"k",
".",
"configMu",
".",
"Lock",
"(",
")",
"\n",
"k",
".",
"Config",
".",
"KontrolKey",
"=",
"key",
"\n",
"k",
".",
"configMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"key",
",",
"nil",
"\n",
"}"
] | // GetKey is used to get a new public key from kontrol if the current one is
// invalidated. The key is also replaced in memory and every request is going
// to use it. This means even if kite.key contains the old key, the kite itself
// uses the new one. | [
"GetKey",
"is",
"used",
"to",
"get",
"a",
"new",
"public",
"key",
"from",
"kontrol",
"if",
"the",
"current",
"one",
"is",
"invalidated",
".",
"The",
"key",
"is",
"also",
"replaced",
"in",
"memory",
"and",
"every",
"request",
"is",
"going",
"to",
"use",
"it",
".",
"This",
"means",
"even",
"if",
"kite",
".",
"key",
"contains",
"the",
"old",
"key",
"the",
"kite",
"itself",
"uses",
"the",
"new",
"one",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L254-L277 | train |
koding/kite | kontrolclient.go | NewKeyRenewer | func (k *Kite) NewKeyRenewer(interval time.Duration) {
ticker := time.NewTicker(interval)
for range ticker.C {
_, err := k.GetKey()
if err != nil {
k.Log.Warning("Key renew failed: %s", err)
}
}
} | go | func (k *Kite) NewKeyRenewer(interval time.Duration) {
ticker := time.NewTicker(interval)
for range ticker.C {
_, err := k.GetKey()
if err != nil {
k.Log.Warning("Key renew failed: %s", err)
}
}
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"NewKeyRenewer",
"(",
"interval",
"time",
".",
"Duration",
")",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"interval",
")",
"\n",
"for",
"range",
"ticker",
".",
"C",
"{",
"_",
",",
"err",
":=",
"k",
".",
"GetKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Warning",
"(",
"\"Key renew failed: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // NewKeyRenewer renews the internal key every given interval | [
"NewKeyRenewer",
"renews",
"the",
"internal",
"key",
"every",
"given",
"interval"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L280-L288 | train |
koding/kite | kontrolclient.go | signalReady | func (k *Kite) signalReady() {
k.kontrol.onceRegistered.Do(func() { close(k.kontrol.readyRegistered) })
} | go | func (k *Kite) signalReady() {
k.kontrol.onceRegistered.Do(func() { close(k.kontrol.readyRegistered) })
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"signalReady",
"(",
")",
"{",
"k",
".",
"kontrol",
".",
"onceRegistered",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"close",
"(",
"k",
".",
"kontrol",
".",
"readyRegistered",
")",
"}",
")",
"\n",
"}"
] | // signalReady is an internal method to notify that a successful registration
// is done. | [
"signalReady",
"is",
"an",
"internal",
"method",
"to",
"notify",
"that",
"a",
"successful",
"registration",
"is",
"done",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L298-L300 | train |
koding/kite | kontrolclient.go | RegisterToTunnel | func (k *Kite) RegisterToTunnel() {
query := &protocol.KontrolQuery{
Username: k.Config.KontrolUser,
Environment: k.Config.Environment,
Name: "tunnelproxy",
}
k.RegisterToProxy(nil, query)
} | go | func (k *Kite) RegisterToTunnel() {
query := &protocol.KontrolQuery{
Username: k.Config.KontrolUser,
Environment: k.Config.Environment,
Name: "tunnelproxy",
}
k.RegisterToProxy(nil, query)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"RegisterToTunnel",
"(",
")",
"{",
"query",
":=",
"&",
"protocol",
".",
"KontrolQuery",
"{",
"Username",
":",
"k",
".",
"Config",
".",
"KontrolUser",
",",
"Environment",
":",
"k",
".",
"Config",
".",
"Environment",
",",
"Name",
":",
"\"tunnelproxy\"",
",",
"}",
"\n",
"k",
".",
"RegisterToProxy",
"(",
"nil",
",",
"query",
")",
"\n",
"}"
] | // RegisterToTunnel finds a tunnel proxy kite by asking kontrol then registers
// itself on proxy. On error, retries forever. On every successful
// registration, it sends the proxied URL to the registerChan channel. There is
// no register URL needed because the Tunnel Proxy automatically gets the IP
// from tunneling. This is a blocking function. | [
"RegisterToTunnel",
"finds",
"a",
"tunnel",
"proxy",
"kite",
"by",
"asking",
"kontrol",
"then",
"registers",
"itself",
"on",
"proxy",
".",
"On",
"error",
"retries",
"forever",
".",
"On",
"every",
"successful",
"registration",
"it",
"sends",
"the",
"proxied",
"URL",
"to",
"the",
"registerChan",
"channel",
".",
"There",
"is",
"no",
"register",
"URL",
"needed",
"because",
"the",
"Tunnel",
"Proxy",
"automatically",
"gets",
"the",
"IP",
"from",
"tunneling",
".",
"This",
"is",
"a",
"blocking",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L398-L406 | train |
koding/kite | kontrolclient.go | RegisterToProxy | func (k *Kite) RegisterToProxy(registerURL *url.URL, query *protocol.KontrolQuery) {
go k.RegisterForever(nil)
for {
var proxyKite *Client
// The proxy kite to connect can be overridden with the
// environmental variable "KITE_PROXY_URL". If it is not set
// we will ask Kontrol for available Proxy kites.
// As an authentication informain kiteKey method will be used,
// so be careful when using this feature.
kiteProxyURL := os.Getenv("KITE_PROXY_URL")
if kiteProxyURL != "" {
proxyKite = k.NewClient(kiteProxyURL)
proxyKite.Auth = &Auth{
Type: "kiteKey",
Key: k.KiteKey(),
}
} else {
kites, err := k.GetKites(query)
if err != nil {
k.Log.Error("Cannot get Proxy kites from Kontrol: %s", err.Error())
time.Sleep(proxyRetryDuration)
continue
}
// If more than one one Proxy Kite is available pick one randomly.
// It does not matter which one we connect.
proxyKite = kites[rand.Int()%len(kites)]
}
// Notify us on disconnect
disconnect := make(chan bool, 1)
proxyKite.OnDisconnect(func() {
select {
case disconnect <- true:
default:
}
})
proxyURL, err := k.registerToProxyKite(proxyKite, registerURL)
if err != nil {
time.Sleep(proxyRetryDuration)
continue
}
k.kontrol.registerChan <- proxyURL
// Block until disconnect from Proxy Kite.
<-disconnect
}
} | go | func (k *Kite) RegisterToProxy(registerURL *url.URL, query *protocol.KontrolQuery) {
go k.RegisterForever(nil)
for {
var proxyKite *Client
// The proxy kite to connect can be overridden with the
// environmental variable "KITE_PROXY_URL". If it is not set
// we will ask Kontrol for available Proxy kites.
// As an authentication informain kiteKey method will be used,
// so be careful when using this feature.
kiteProxyURL := os.Getenv("KITE_PROXY_URL")
if kiteProxyURL != "" {
proxyKite = k.NewClient(kiteProxyURL)
proxyKite.Auth = &Auth{
Type: "kiteKey",
Key: k.KiteKey(),
}
} else {
kites, err := k.GetKites(query)
if err != nil {
k.Log.Error("Cannot get Proxy kites from Kontrol: %s", err.Error())
time.Sleep(proxyRetryDuration)
continue
}
// If more than one one Proxy Kite is available pick one randomly.
// It does not matter which one we connect.
proxyKite = kites[rand.Int()%len(kites)]
}
// Notify us on disconnect
disconnect := make(chan bool, 1)
proxyKite.OnDisconnect(func() {
select {
case disconnect <- true:
default:
}
})
proxyURL, err := k.registerToProxyKite(proxyKite, registerURL)
if err != nil {
time.Sleep(proxyRetryDuration)
continue
}
k.kontrol.registerChan <- proxyURL
// Block until disconnect from Proxy Kite.
<-disconnect
}
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"RegisterToProxy",
"(",
"registerURL",
"*",
"url",
".",
"URL",
",",
"query",
"*",
"protocol",
".",
"KontrolQuery",
")",
"{",
"go",
"k",
".",
"RegisterForever",
"(",
"nil",
")",
"\n",
"for",
"{",
"var",
"proxyKite",
"*",
"Client",
"\n",
"kiteProxyURL",
":=",
"os",
".",
"Getenv",
"(",
"\"KITE_PROXY_URL\"",
")",
"\n",
"if",
"kiteProxyURL",
"!=",
"\"\"",
"{",
"proxyKite",
"=",
"k",
".",
"NewClient",
"(",
"kiteProxyURL",
")",
"\n",
"proxyKite",
".",
"Auth",
"=",
"&",
"Auth",
"{",
"Type",
":",
"\"kiteKey\"",
",",
"Key",
":",
"k",
".",
"KiteKey",
"(",
")",
",",
"}",
"\n",
"}",
"else",
"{",
"kites",
",",
"err",
":=",
"k",
".",
"GetKites",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"Cannot get Proxy kites from Kontrol: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"time",
".",
"Sleep",
"(",
"proxyRetryDuration",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"proxyKite",
"=",
"kites",
"[",
"rand",
".",
"Int",
"(",
")",
"%",
"len",
"(",
"kites",
")",
"]",
"\n",
"}",
"\n",
"disconnect",
":=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"proxyKite",
".",
"OnDisconnect",
"(",
"func",
"(",
")",
"{",
"select",
"{",
"case",
"disconnect",
"<-",
"true",
":",
"default",
":",
"}",
"\n",
"}",
")",
"\n",
"proxyURL",
",",
"err",
":=",
"k",
".",
"registerToProxyKite",
"(",
"proxyKite",
",",
"registerURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"time",
".",
"Sleep",
"(",
"proxyRetryDuration",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"k",
".",
"kontrol",
".",
"registerChan",
"<-",
"proxyURL",
"\n",
"<-",
"disconnect",
"\n",
"}",
"\n",
"}"
] | // RegisterToProxy is just like RegisterForever but registers the given URL
// to kontrol over a kite-proxy. A Kiteproxy is a reverseproxy that can be used
// for SSL termination or handling hundreds of kites behind a single. This is a
// blocking function. | [
"RegisterToProxy",
"is",
"just",
"like",
"RegisterForever",
"but",
"registers",
"the",
"given",
"URL",
"to",
"kontrol",
"over",
"a",
"kite",
"-",
"proxy",
".",
"A",
"Kiteproxy",
"is",
"a",
"reverseproxy",
"that",
"can",
"be",
"used",
"for",
"SSL",
"termination",
"or",
"handling",
"hundreds",
"of",
"kites",
"behind",
"a",
"single",
".",
"This",
"is",
"a",
"blocking",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L412-L463 | train |
koding/kite | kontrolclient.go | registerToProxyKite | func (k *Kite) registerToProxyKite(c *Client, kiteURL *url.URL) (*url.URL, error) {
err := c.Dial()
if err != nil {
k.Log.Error("Cannot connect to Proxy kite: %s", err.Error())
return nil, err
}
// Disconnect from Proxy Kite if error happens while registering.
defer func() {
if err != nil {
c.Close()
}
}()
// do not panic if we call Tell method below
if kiteURL == nil {
kiteURL = &url.URL{}
}
// this could be tunnelproxy or reverseproxy. Tunnelproxy doesn't need an
// URL however Reverseproxy needs one.
result, err := c.TellWithTimeout("register", k.Config.Timeout, kiteURL.String())
if err != nil {
k.Log.Error("Proxy register error: %s", err.Error())
return nil, err
}
proxyURL, err := result.String()
if err != nil {
k.Log.Error("Proxy register result error: %s", err.Error())
return nil, err
}
parsed, err := url.Parse(proxyURL)
if err != nil {
k.Log.Error("Cannot parse Proxy URL: %s", err.Error())
return nil, err
}
return parsed, nil
} | go | func (k *Kite) registerToProxyKite(c *Client, kiteURL *url.URL) (*url.URL, error) {
err := c.Dial()
if err != nil {
k.Log.Error("Cannot connect to Proxy kite: %s", err.Error())
return nil, err
}
// Disconnect from Proxy Kite if error happens while registering.
defer func() {
if err != nil {
c.Close()
}
}()
// do not panic if we call Tell method below
if kiteURL == nil {
kiteURL = &url.URL{}
}
// this could be tunnelproxy or reverseproxy. Tunnelproxy doesn't need an
// URL however Reverseproxy needs one.
result, err := c.TellWithTimeout("register", k.Config.Timeout, kiteURL.String())
if err != nil {
k.Log.Error("Proxy register error: %s", err.Error())
return nil, err
}
proxyURL, err := result.String()
if err != nil {
k.Log.Error("Proxy register result error: %s", err.Error())
return nil, err
}
parsed, err := url.Parse(proxyURL)
if err != nil {
k.Log.Error("Cannot parse Proxy URL: %s", err.Error())
return nil, err
}
return parsed, nil
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"registerToProxyKite",
"(",
"c",
"*",
"Client",
",",
"kiteURL",
"*",
"url",
".",
"URL",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"Dial",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"Cannot connect to Proxy kite: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"if",
"kiteURL",
"==",
"nil",
"{",
"kiteURL",
"=",
"&",
"url",
".",
"URL",
"{",
"}",
"\n",
"}",
"\n",
"result",
",",
"err",
":=",
"c",
".",
"TellWithTimeout",
"(",
"\"register\"",
",",
"k",
".",
"Config",
".",
"Timeout",
",",
"kiteURL",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"Proxy register error: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"proxyURL",
",",
"err",
":=",
"result",
".",
"String",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"Proxy register result error: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"parsed",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"proxyURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"k",
".",
"Log",
".",
"Error",
"(",
"\"Cannot parse Proxy URL: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"parsed",
",",
"nil",
"\n",
"}"
] | // registerToProxyKite dials the proxy kite and calls register method then
// returns the reverse-proxy URL. | [
"registerToProxyKite",
"dials",
"the",
"proxy",
"kite",
"and",
"calls",
"register",
"method",
"then",
"returns",
"the",
"reverse",
"-",
"proxy",
"URL",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L467-L507 | train |
koding/kite | kontrolclient.go | TellKontrolWithTimeout | func (k *Kite) TellKontrolWithTimeout(method string, timeout time.Duration, args ...interface{}) (result *dnode.Partial, err error) {
if err := k.SetupKontrolClient(); err != nil {
return nil, err
}
// Wait for readyConnect, or timeout
select {
case <-time.After(k.Config.Timeout):
return nil, &Error{
Type: "timeout",
Message: fmt.Sprintf(
"Timed out registering to kontrol for %s method after %s",
method, k.Config.Timeout,
),
}
case <-k.kontrol.readyConnected:
}
return k.kontrol.TellWithTimeout(method, timeout, args...)
} | go | func (k *Kite) TellKontrolWithTimeout(method string, timeout time.Duration, args ...interface{}) (result *dnode.Partial, err error) {
if err := k.SetupKontrolClient(); err != nil {
return nil, err
}
// Wait for readyConnect, or timeout
select {
case <-time.After(k.Config.Timeout):
return nil, &Error{
Type: "timeout",
Message: fmt.Sprintf(
"Timed out registering to kontrol for %s method after %s",
method, k.Config.Timeout,
),
}
case <-k.kontrol.readyConnected:
}
return k.kontrol.TellWithTimeout(method, timeout, args...)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"TellKontrolWithTimeout",
"(",
"method",
"string",
",",
"timeout",
"time",
".",
"Duration",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"result",
"*",
"dnode",
".",
"Partial",
",",
"err",
"error",
")",
"{",
"if",
"err",
":=",
"k",
".",
"SetupKontrolClient",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"k",
".",
"Config",
".",
"Timeout",
")",
":",
"return",
"nil",
",",
"&",
"Error",
"{",
"Type",
":",
"\"timeout\"",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"Timed out registering to kontrol for %s method after %s\"",
",",
"method",
",",
"k",
".",
"Config",
".",
"Timeout",
",",
")",
",",
"}",
"\n",
"case",
"<-",
"k",
".",
"kontrol",
".",
"readyConnected",
":",
"}",
"\n",
"return",
"k",
".",
"kontrol",
".",
"TellWithTimeout",
"(",
"method",
",",
"timeout",
",",
"args",
"...",
")",
"\n",
"}"
] | // TellKontrolWithTimeout is a lower level function for communicating directly with
// kontrol. Like GetKites and GetToken, this automatically sets up and connects to
// kontrol as needed. | [
"TellKontrolWithTimeout",
"is",
"a",
"lower",
"level",
"function",
"for",
"communicating",
"directly",
"with",
"kontrol",
".",
"Like",
"GetKites",
"and",
"GetToken",
"this",
"automatically",
"sets",
"up",
"and",
"connects",
"to",
"kontrol",
"as",
"needed",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrolclient.go#L512-L531 | train |
koding/kite | kontrol/idlock.go | Get | func (i *IdLock) Get(id string) sync.Locker {
i.locksMu.Lock()
defer i.locksMu.Unlock()
var l sync.Locker
var ok bool
l, ok = i.locks[id]
if !ok {
l = &sync.Mutex{}
i.locks[id] = l
}
return l
} | go | func (i *IdLock) Get(id string) sync.Locker {
i.locksMu.Lock()
defer i.locksMu.Unlock()
var l sync.Locker
var ok bool
l, ok = i.locks[id]
if !ok {
l = &sync.Mutex{}
i.locks[id] = l
}
return l
} | [
"func",
"(",
"i",
"*",
"IdLock",
")",
"Get",
"(",
"id",
"string",
")",
"sync",
".",
"Locker",
"{",
"i",
".",
"locksMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"i",
".",
"locksMu",
".",
"Unlock",
"(",
")",
"\n",
"var",
"l",
"sync",
".",
"Locker",
"\n",
"var",
"ok",
"bool",
"\n",
"l",
",",
"ok",
"=",
"i",
".",
"locks",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"l",
"=",
"&",
"sync",
".",
"Mutex",
"{",
"}",
"\n",
"i",
".",
"locks",
"[",
"id",
"]",
"=",
"l",
"\n",
"}",
"\n",
"return",
"l",
"\n",
"}"
] | // Get returns a lock that is bound to a specific id. | [
"Get",
"returns",
"a",
"lock",
"that",
"is",
"bound",
"to",
"a",
"specific",
"id",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/idlock.go#L19-L33 | train |
koding/kite | kitectl/command/list.go | BinPath | func (k *InstalledKite) BinPath() string {
return filepath.Join(k.Domain, k.User, k.Repo, k.Version, "bin", strings.TrimSuffix(k.Repo, ".kite"))
} | go | func (k *InstalledKite) BinPath() string {
return filepath.Join(k.Domain, k.User, k.Repo, k.Version, "bin", strings.TrimSuffix(k.Repo, ".kite"))
} | [
"func",
"(",
"k",
"*",
"InstalledKite",
")",
"BinPath",
"(",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"k",
".",
"Domain",
",",
"k",
".",
"User",
",",
"k",
".",
"Repo",
",",
"k",
".",
"Version",
",",
"\"bin\"",
",",
"strings",
".",
"TrimSuffix",
"(",
"k",
".",
"Repo",
",",
"\".kite\"",
")",
")",
"\n",
"}"
] | // BinPath returns the path of the executable binary file. | [
"BinPath",
"returns",
"the",
"path",
"of",
"the",
"executable",
"binary",
"file",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kitectl/command/list.go#L134-L136 | train |
koding/kite | sockjsclient/sockjsclient.go | Error | func (err *ErrSession) Error() string {
if err.Err == nil {
return fmt.Sprintf("%s (%s)", stateTexts[err.State], err.Type)
}
return fmt.Sprintf("%s: %s (%s)", stateTexts[err.State], err.Err, err.Type)
} | go | func (err *ErrSession) Error() string {
if err.Err == nil {
return fmt.Sprintf("%s (%s)", stateTexts[err.State], err.Type)
}
return fmt.Sprintf("%s: %s (%s)", stateTexts[err.State], err.Err, err.Type)
} | [
"func",
"(",
"err",
"*",
"ErrSession",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"err",
".",
"Err",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s (%s)\"",
",",
"stateTexts",
"[",
"err",
".",
"State",
"]",
",",
"err",
".",
"Type",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s: %s (%s)\"",
",",
"stateTexts",
"[",
"err",
".",
"State",
"]",
",",
"err",
".",
"Err",
",",
"err",
".",
"Type",
")",
"\n",
"}"
] | // Error implements the buildin error interface. | [
"Error",
"implements",
"the",
"buildin",
"error",
"interface",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/sockjsclient.go#L51-L56 | train |
koding/kite | sockjsclient/sockjsclient.go | IsSessionClosed | func IsSessionClosed(err error) bool {
switch err {
case ErrSessionClosed, sockjs.ErrSessionNotOpen, websocket.ErrCloseSent:
return true
}
if e, ok := err.(*ErrSession); ok && e.State > sockjs.SessionActive {
return true
}
_, ok := err.(*websocket.CloseError)
return ok
} | go | func IsSessionClosed(err error) bool {
switch err {
case ErrSessionClosed, sockjs.ErrSessionNotOpen, websocket.ErrCloseSent:
return true
}
if e, ok := err.(*ErrSession); ok && e.State > sockjs.SessionActive {
return true
}
_, ok := err.(*websocket.CloseError)
return ok
} | [
"func",
"IsSessionClosed",
"(",
"err",
"error",
")",
"bool",
"{",
"switch",
"err",
"{",
"case",
"ErrSessionClosed",
",",
"sockjs",
".",
"ErrSessionNotOpen",
",",
"websocket",
".",
"ErrCloseSent",
":",
"return",
"true",
"\n",
"}",
"\n",
"if",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"ErrSession",
")",
";",
"ok",
"&&",
"e",
".",
"State",
">",
"sockjs",
".",
"SessionActive",
"{",
"return",
"true",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"websocket",
".",
"CloseError",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsSessionClosed tests whether given error is caused
// by a closed session. | [
"IsSessionClosed",
"tests",
"whether",
"given",
"error",
"is",
"caused",
"by",
"a",
"closed",
"session",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/sockjsclient.go#L60-L70 | train |
koding/kite | sockjsclient/sockjsclient.go | DialWebsocket | func DialWebsocket(uri string, cfg *config.Config) (*WebsocketSession, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
h := http.Header{
"Origin": {u.Scheme + "://" + u.Host},
}
serverID := threeDigits()
sessionID := utils.RandomString(20)
u = makeWebsocketURL(u, serverID, sessionID)
conn, _, err := cfg.Websocket.Dial(u.String(), h)
if err != nil {
return nil, err
}
session := NewWebsocketSession(conn)
session.id = sessionID
session.req = &http.Request{
URL: u,
Header: h,
}
return session, nil
} | go | func DialWebsocket(uri string, cfg *config.Config) (*WebsocketSession, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
h := http.Header{
"Origin": {u.Scheme + "://" + u.Host},
}
serverID := threeDigits()
sessionID := utils.RandomString(20)
u = makeWebsocketURL(u, serverID, sessionID)
conn, _, err := cfg.Websocket.Dial(u.String(), h)
if err != nil {
return nil, err
}
session := NewWebsocketSession(conn)
session.id = sessionID
session.req = &http.Request{
URL: u,
Header: h,
}
return session, nil
} | [
"func",
"DialWebsocket",
"(",
"uri",
"string",
",",
"cfg",
"*",
"config",
".",
"Config",
")",
"(",
"*",
"WebsocketSession",
",",
"error",
")",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"h",
":=",
"http",
".",
"Header",
"{",
"\"Origin\"",
":",
"{",
"u",
".",
"Scheme",
"+",
"\"://\"",
"+",
"u",
".",
"Host",
"}",
",",
"}",
"\n",
"serverID",
":=",
"threeDigits",
"(",
")",
"\n",
"sessionID",
":=",
"utils",
".",
"RandomString",
"(",
"20",
")",
"\n",
"u",
"=",
"makeWebsocketURL",
"(",
"u",
",",
"serverID",
",",
"sessionID",
")",
"\n",
"conn",
",",
"_",
",",
"err",
":=",
"cfg",
".",
"Websocket",
".",
"Dial",
"(",
"u",
".",
"String",
"(",
")",
",",
"h",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"session",
":=",
"NewWebsocketSession",
"(",
"conn",
")",
"\n",
"session",
".",
"id",
"=",
"sessionID",
"\n",
"session",
".",
"req",
"=",
"&",
"http",
".",
"Request",
"{",
"URL",
":",
"u",
",",
"Header",
":",
"h",
",",
"}",
"\n",
"return",
"session",
",",
"nil",
"\n",
"}"
] | // DialWebsocket establishes a SockJS session over a websocket connection.
//
// Requires cfg.Websocket to be a valid client. | [
"DialWebsocket",
"establishes",
"a",
"SockJS",
"session",
"over",
"a",
"websocket",
"connection",
".",
"Requires",
"cfg",
".",
"Websocket",
"to",
"be",
"a",
"valid",
"client",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/sockjsclient.go#L136-L164 | train |
koding/kite | sockjsclient/sockjsclient.go | Recv | func (w *WebsocketSession) Recv() (string, error) {
// Return previously received messages if there is any.
if len(w.messages) > 0 {
msg := w.messages[0]
w.messages = w.messages[1:]
return msg, nil
}
read_frame:
if atomic.LoadInt32(&w.closed) == 1 {
return "", ErrSessionClosed
}
// Read one SockJS frame.
_, buf, err := w.conn.ReadMessage()
if err != nil {
return "", err
}
if len(buf) == 0 {
return "", errors.New("unexpected empty message")
}
frameType := buf[0]
data := buf[1:]
switch frameType {
case 'o':
w.setState(sockjs.SessionActive)
goto read_frame
case 'a':
var messages []string
err = json.Unmarshal(data, &messages)
if err != nil {
return "", err
}
w.messages = append(w.messages, messages...)
case 'm':
var message string
err = json.Unmarshal(data, &message)
if err != nil {
return "", err
}
w.messages = append(w.messages, message)
case 'c':
w.setState(sockjs.SessionClosed)
return "", ErrSessionClosed
case 'h':
// TODO handle heartbeat
goto read_frame
default:
return "", errors.New("invalid frame type")
}
// Return first message in slice.
if len(w.messages) == 0 {
return "", errors.New("no message")
}
msg := w.messages[0]
w.messages = w.messages[1:]
return msg, nil
} | go | func (w *WebsocketSession) Recv() (string, error) {
// Return previously received messages if there is any.
if len(w.messages) > 0 {
msg := w.messages[0]
w.messages = w.messages[1:]
return msg, nil
}
read_frame:
if atomic.LoadInt32(&w.closed) == 1 {
return "", ErrSessionClosed
}
// Read one SockJS frame.
_, buf, err := w.conn.ReadMessage()
if err != nil {
return "", err
}
if len(buf) == 0 {
return "", errors.New("unexpected empty message")
}
frameType := buf[0]
data := buf[1:]
switch frameType {
case 'o':
w.setState(sockjs.SessionActive)
goto read_frame
case 'a':
var messages []string
err = json.Unmarshal(data, &messages)
if err != nil {
return "", err
}
w.messages = append(w.messages, messages...)
case 'm':
var message string
err = json.Unmarshal(data, &message)
if err != nil {
return "", err
}
w.messages = append(w.messages, message)
case 'c':
w.setState(sockjs.SessionClosed)
return "", ErrSessionClosed
case 'h':
// TODO handle heartbeat
goto read_frame
default:
return "", errors.New("invalid frame type")
}
// Return first message in slice.
if len(w.messages) == 0 {
return "", errors.New("no message")
}
msg := w.messages[0]
w.messages = w.messages[1:]
return msg, nil
} | [
"func",
"(",
"w",
"*",
"WebsocketSession",
")",
"Recv",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"w",
".",
"messages",
")",
">",
"0",
"{",
"msg",
":=",
"w",
".",
"messages",
"[",
"0",
"]",
"\n",
"w",
".",
"messages",
"=",
"w",
".",
"messages",
"[",
"1",
":",
"]",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}",
"\n",
"read_frame",
":",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"w",
".",
"closed",
")",
"==",
"1",
"{",
"return",
"\"\"",
",",
"ErrSessionClosed",
"\n",
"}",
"\n",
"_",
",",
"buf",
",",
"err",
":=",
"w",
".",
"conn",
".",
"ReadMessage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"buf",
")",
"==",
"0",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"unexpected empty message\"",
")",
"\n",
"}",
"\n",
"frameType",
":=",
"buf",
"[",
"0",
"]",
"\n",
"data",
":=",
"buf",
"[",
"1",
":",
"]",
"\n",
"switch",
"frameType",
"{",
"case",
"'o'",
":",
"w",
".",
"setState",
"(",
"sockjs",
".",
"SessionActive",
")",
"\n",
"goto",
"read_frame",
"\n",
"case",
"'a'",
":",
"var",
"messages",
"[",
"]",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"messages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"w",
".",
"messages",
"=",
"append",
"(",
"w",
".",
"messages",
",",
"messages",
"...",
")",
"\n",
"case",
"'m'",
":",
"var",
"message",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"message",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"w",
".",
"messages",
"=",
"append",
"(",
"w",
".",
"messages",
",",
"message",
")",
"\n",
"case",
"'c'",
":",
"w",
".",
"setState",
"(",
"sockjs",
".",
"SessionClosed",
")",
"\n",
"return",
"\"\"",
",",
"ErrSessionClosed",
"\n",
"case",
"'h'",
":",
"goto",
"read_frame",
"\n",
"default",
":",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"invalid frame type\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"w",
".",
"messages",
")",
"==",
"0",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"no message\"",
")",
"\n",
"}",
"\n",
"msg",
":=",
"w",
".",
"messages",
"[",
"0",
"]",
"\n",
"w",
".",
"messages",
"=",
"w",
".",
"messages",
"[",
"1",
":",
"]",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // Recv reads one text frame from session. | [
"Recv",
"reads",
"one",
"text",
"frame",
"from",
"session",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/sockjsclient.go#L198-L259 | train |
koding/kite | sockjsclient/sockjsclient.go | Send | func (w *WebsocketSession) Send(str string) error {
if atomic.LoadInt32(&w.closed) == 1 {
return ErrSessionClosed
}
w.mu.Lock()
defer w.mu.Unlock()
b, _ := json.Marshal([]string{str})
return w.conn.WriteMessage(websocket.TextMessage, b)
} | go | func (w *WebsocketSession) Send(str string) error {
if atomic.LoadInt32(&w.closed) == 1 {
return ErrSessionClosed
}
w.mu.Lock()
defer w.mu.Unlock()
b, _ := json.Marshal([]string{str})
return w.conn.WriteMessage(websocket.TextMessage, b)
} | [
"func",
"(",
"w",
"*",
"WebsocketSession",
")",
"Send",
"(",
"str",
"string",
")",
"error",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"w",
".",
"closed",
")",
"==",
"1",
"{",
"return",
"ErrSessionClosed",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"b",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"[",
"]",
"string",
"{",
"str",
"}",
")",
"\n",
"return",
"w",
".",
"conn",
".",
"WriteMessage",
"(",
"websocket",
".",
"TextMessage",
",",
"b",
")",
"\n",
"}"
] | // Send sends one text frame to session | [
"Send",
"sends",
"one",
"text",
"frame",
"to",
"session"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/sockjsclient.go#L262-L272 | train |
koding/kite | sockjsclient/sockjsclient.go | Close | func (w *WebsocketSession) Close(uint32, string) error {
if atomic.CompareAndSwapInt32(&w.closed, 0, 1) {
return w.conn.Close()
}
return ErrSessionClosed
} | go | func (w *WebsocketSession) Close(uint32, string) error {
if atomic.CompareAndSwapInt32(&w.closed, 0, 1) {
return w.conn.Close()
}
return ErrSessionClosed
} | [
"func",
"(",
"w",
"*",
"WebsocketSession",
")",
"Close",
"(",
"uint32",
",",
"string",
")",
"error",
"{",
"if",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"w",
".",
"closed",
",",
"0",
",",
"1",
")",
"{",
"return",
"w",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"ErrSessionClosed",
"\n",
"}"
] | // Close closes the session with provided code and reason. | [
"Close",
"closes",
"the",
"session",
"with",
"provided",
"code",
"and",
"reason",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/sockjsclient.go#L275-L281 | train |
koding/kite | kitectl/command/uninstall.go | isInstalled | func isInstalled(fullKiteName string) (bool, error) {
bundlePath, err := getBundlePath(fullKiteName)
if err != nil {
return false, err
}
return exists(bundlePath)
} | go | func isInstalled(fullKiteName string) (bool, error) {
bundlePath, err := getBundlePath(fullKiteName)
if err != nil {
return false, err
}
return exists(bundlePath)
} | [
"func",
"isInstalled",
"(",
"fullKiteName",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"bundlePath",
",",
"err",
":=",
"getBundlePath",
"(",
"fullKiteName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"exists",
"(",
"bundlePath",
")",
"\n",
"}"
] | // isInstalled returns true if the kite is installed. | [
"isInstalled",
"returns",
"true",
"if",
"the",
"kite",
"is",
"installed",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kitectl/command/uninstall.go#L83-L89 | train |
koding/kite | kontrol/keypair.go | NewCachedStorage | func NewCachedStorage(backend KeyPairStorage, cache KeyPairStorage) *CachedStorage {
return &CachedStorage{
cache: cache,
backend: backend,
}
} | go | func NewCachedStorage(backend KeyPairStorage, cache KeyPairStorage) *CachedStorage {
return &CachedStorage{
cache: cache,
backend: backend,
}
} | [
"func",
"NewCachedStorage",
"(",
"backend",
"KeyPairStorage",
",",
"cache",
"KeyPairStorage",
")",
"*",
"CachedStorage",
"{",
"return",
"&",
"CachedStorage",
"{",
"cache",
":",
"cache",
",",
"backend",
":",
"backend",
",",
"}",
"\n",
"}"
] | // NewCachedStorage creates a new CachedStorage | [
"NewCachedStorage",
"creates",
"a",
"new",
"CachedStorage"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/keypair.go#L150-L155 | train |
koding/kite | kontrol/kites.go | Attach | func (k Kites) Attach(token string) {
for _, kite := range k {
kite.Token = token
}
} | go | func (k Kites) Attach(token string) {
for _, kite := range k {
kite.Token = token
}
} | [
"func",
"(",
"k",
"Kites",
")",
"Attach",
"(",
"token",
"string",
")",
"{",
"for",
"_",
",",
"kite",
":=",
"range",
"k",
"{",
"kite",
".",
"Token",
"=",
"token",
"\n",
"}",
"\n",
"}"
] | // Attach attaches the given token to each kite. It replaces any previous
// token. | [
"Attach",
"attaches",
"the",
"given",
"token",
"to",
"each",
"kite",
".",
"It",
"replaces",
"any",
"previous",
"token",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kites.go#L16-L20 | train |
koding/kite | kontrol/kites.go | Shuffle | func (k *Kites) Shuffle() {
shuffled := make(Kites, len(*k))
for i, v := range rand.Perm(len(*k)) {
shuffled[v] = (*k)[i]
}
*k = shuffled
} | go | func (k *Kites) Shuffle() {
shuffled := make(Kites, len(*k))
for i, v := range rand.Perm(len(*k)) {
shuffled[v] = (*k)[i]
}
*k = shuffled
} | [
"func",
"(",
"k",
"*",
"Kites",
")",
"Shuffle",
"(",
")",
"{",
"shuffled",
":=",
"make",
"(",
"Kites",
",",
"len",
"(",
"*",
"k",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"rand",
".",
"Perm",
"(",
"len",
"(",
"*",
"k",
")",
")",
"{",
"shuffled",
"[",
"v",
"]",
"=",
"(",
"*",
"k",
")",
"[",
"i",
"]",
"\n",
"}",
"\n",
"*",
"k",
"=",
"shuffled",
"\n",
"}"
] | // Shuffle shuffles the order of the kites. This is useful if you want send
// back a randomized list of kites. | [
"Shuffle",
"shuffles",
"the",
"order",
"of",
"the",
"kites",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"send",
"back",
"a",
"randomized",
"list",
"of",
"kites",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kites.go#L24-L31 | train |
koding/kite | kontrol/kites.go | Filter | func (k *Kites) Filter(constraint version.Constraints, keyRest string) {
filtered := make(Kites, 0)
for _, kite := range *k {
if isValid(&kite.Kite, constraint, keyRest) {
filtered = append(filtered, kite)
}
}
*k = filtered
} | go | func (k *Kites) Filter(constraint version.Constraints, keyRest string) {
filtered := make(Kites, 0)
for _, kite := range *k {
if isValid(&kite.Kite, constraint, keyRest) {
filtered = append(filtered, kite)
}
}
*k = filtered
} | [
"func",
"(",
"k",
"*",
"Kites",
")",
"Filter",
"(",
"constraint",
"version",
".",
"Constraints",
",",
"keyRest",
"string",
")",
"{",
"filtered",
":=",
"make",
"(",
"Kites",
",",
"0",
")",
"\n",
"for",
"_",
",",
"kite",
":=",
"range",
"*",
"k",
"{",
"if",
"isValid",
"(",
"&",
"kite",
".",
"Kite",
",",
"constraint",
",",
"keyRest",
")",
"{",
"filtered",
"=",
"append",
"(",
"filtered",
",",
"kite",
")",
"\n",
"}",
"\n",
"}",
"\n",
"*",
"k",
"=",
"filtered",
"\n",
"}"
] | // Filter filters out kites with the given constraints | [
"Filter",
"filters",
"out",
"kites",
"with",
"the",
"given",
"constraints"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kites.go#L34-L43 | train |
koding/kite | client.go | DialForever | func (c *Client) DialForever() (connected chan bool, err error) {
c.Reconnect = true
connected = make(chan bool, 1) // This will be closed on first connection.
go c.dialForever(connected)
return
} | go | func (c *Client) DialForever() (connected chan bool, err error) {
c.Reconnect = true
connected = make(chan bool, 1) // This will be closed on first connection.
go c.dialForever(connected)
return
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DialForever",
"(",
")",
"(",
"connected",
"chan",
"bool",
",",
"err",
"error",
")",
"{",
"c",
".",
"Reconnect",
"=",
"true",
"\n",
"connected",
"=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"go",
"c",
".",
"dialForever",
"(",
"connected",
")",
"\n",
"return",
"\n",
"}"
] | // Dial connects to the remote Kite. If it can't connect, it retries
// indefinitely. It returns a channel to check if it's connected or not. | [
"Dial",
"connects",
"to",
"the",
"remote",
"Kite",
".",
"If",
"it",
"can",
"t",
"connect",
"it",
"retries",
"indefinitely",
".",
"It",
"returns",
"a",
"channel",
"to",
"check",
"if",
"it",
"s",
"connected",
"or",
"not",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L256-L261 | train |
koding/kite | client.go | run | func (c *Client) run() {
err := c.readLoop()
if err != nil {
c.LocalKite.Log.Debug("readloop err: %s", err)
}
// falls here when connection disconnects
c.callOnDisconnectHandlers()
// let others know that the client has disconnected
c.disconnectMu.Lock()
if c.disconnect != nil {
close(c.disconnect)
c.disconnect = nil
}
c.disconnectMu.Unlock()
if c.reconnect() {
// we override it so it doesn't get selected next time. Because we are
// redialing, so after redial if a new method is called, the disconnect
// channel is being read and the local "disconnect" message will be the
// final response. This shouldn't be happen for redials.
c.disconnectMu.Lock()
c.disconnect = make(chan struct{}, 1)
c.disconnectMu.Unlock()
go c.dialForever(nil)
}
} | go | func (c *Client) run() {
err := c.readLoop()
if err != nil {
c.LocalKite.Log.Debug("readloop err: %s", err)
}
// falls here when connection disconnects
c.callOnDisconnectHandlers()
// let others know that the client has disconnected
c.disconnectMu.Lock()
if c.disconnect != nil {
close(c.disconnect)
c.disconnect = nil
}
c.disconnectMu.Unlock()
if c.reconnect() {
// we override it so it doesn't get selected next time. Because we are
// redialing, so after redial if a new method is called, the disconnect
// channel is being read and the local "disconnect" message will be the
// final response. This shouldn't be happen for redials.
c.disconnectMu.Lock()
c.disconnect = make(chan struct{}, 1)
c.disconnectMu.Unlock()
go c.dialForever(nil)
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"run",
"(",
")",
"{",
"err",
":=",
"c",
".",
"readLoop",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Debug",
"(",
"\"readloop err: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"c",
".",
"callOnDisconnectHandlers",
"(",
")",
"\n",
"c",
".",
"disconnectMu",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"disconnect",
"!=",
"nil",
"{",
"close",
"(",
"c",
".",
"disconnect",
")",
"\n",
"c",
".",
"disconnect",
"=",
"nil",
"\n",
"}",
"\n",
"c",
".",
"disconnectMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"c",
".",
"reconnect",
"(",
")",
"{",
"c",
".",
"disconnectMu",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"disconnect",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n",
"c",
".",
"disconnectMu",
".",
"Unlock",
"(",
")",
"\n",
"go",
"c",
".",
"dialForever",
"(",
"nil",
")",
"\n",
"}",
"\n",
"}"
] | // run consumes incoming dnode messages. Reconnects if necessary. | [
"run",
"consumes",
"incoming",
"dnode",
"messages",
".",
"Reconnects",
"if",
"necessary",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L388-L415 | train |
koding/kite | client.go | readLoop | func (c *Client) readLoop() error {
for {
p, err := c.receiveData()
c.LocalKite.Log.Debug("readloop received: %s %v", p, err)
if err != nil {
return err
}
msg, fn, err := c.processMessage(p)
if err != nil {
if _, ok := err.(dnode.CallbackNotFoundError); !ok {
c.LocalKite.Log.Warning("error processing message err: %s message: %s", err, msg)
}
}
switch v := fn.(type) {
case *Method: // invoke method
if c.Concurrent {
go c.runMethod(v, msg.Arguments)
} else {
c.runMethod(v, msg.Arguments)
}
case func(*dnode.Partial): // invoke callback
if c.Concurrent && c.ConcurrentCallbacks {
go c.runCallback(v, msg.Arguments)
} else {
c.runCallback(v, msg.Arguments)
}
}
}
} | go | func (c *Client) readLoop() error {
for {
p, err := c.receiveData()
c.LocalKite.Log.Debug("readloop received: %s %v", p, err)
if err != nil {
return err
}
msg, fn, err := c.processMessage(p)
if err != nil {
if _, ok := err.(dnode.CallbackNotFoundError); !ok {
c.LocalKite.Log.Warning("error processing message err: %s message: %s", err, msg)
}
}
switch v := fn.(type) {
case *Method: // invoke method
if c.Concurrent {
go c.runMethod(v, msg.Arguments)
} else {
c.runMethod(v, msg.Arguments)
}
case func(*dnode.Partial): // invoke callback
if c.Concurrent && c.ConcurrentCallbacks {
go c.runCallback(v, msg.Arguments)
} else {
c.runCallback(v, msg.Arguments)
}
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"readLoop",
"(",
")",
"error",
"{",
"for",
"{",
"p",
",",
"err",
":=",
"c",
".",
"receiveData",
"(",
")",
"\n",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Debug",
"(",
"\"readloop received: %s %v\"",
",",
"p",
",",
"err",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"msg",
",",
"fn",
",",
"err",
":=",
"c",
".",
"processMessage",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"dnode",
".",
"CallbackNotFoundError",
")",
";",
"!",
"ok",
"{",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Warning",
"(",
"\"error processing message err: %s message: %s\"",
",",
"err",
",",
"msg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"switch",
"v",
":=",
"fn",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Method",
":",
"if",
"c",
".",
"Concurrent",
"{",
"go",
"c",
".",
"runMethod",
"(",
"v",
",",
"msg",
".",
"Arguments",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"runMethod",
"(",
"v",
",",
"msg",
".",
"Arguments",
")",
"\n",
"}",
"\n",
"case",
"func",
"(",
"*",
"dnode",
".",
"Partial",
")",
":",
"if",
"c",
".",
"Concurrent",
"&&",
"c",
".",
"ConcurrentCallbacks",
"{",
"go",
"c",
".",
"runCallback",
"(",
"v",
",",
"msg",
".",
"Arguments",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"runCallback",
"(",
"v",
",",
"msg",
".",
"Arguments",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // readLoop reads a message from websocket and processes it. | [
"readLoop",
"reads",
"a",
"message",
"from",
"websocket",
"and",
"processes",
"it",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L425-L457 | train |
koding/kite | client.go | receiveData | func (c *Client) receiveData() ([]byte, error) {
type recv struct {
msg []byte
err error
}
session := c.getSession()
if session == nil {
return nil, errors.New("not connected")
}
done := make(chan recv, 1)
go func() {
msg, err := session.Recv()
done <- recv{[]byte(msg), err}
}()
select {
case r := <-done:
return r.msg, r.err
case err := <-c.interrupt:
return nil, err
}
} | go | func (c *Client) receiveData() ([]byte, error) {
type recv struct {
msg []byte
err error
}
session := c.getSession()
if session == nil {
return nil, errors.New("not connected")
}
done := make(chan recv, 1)
go func() {
msg, err := session.Recv()
done <- recv{[]byte(msg), err}
}()
select {
case r := <-done:
return r.msg, r.err
case err := <-c.interrupt:
return nil, err
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"receiveData",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"type",
"recv",
"struct",
"{",
"msg",
"[",
"]",
"byte",
"\n",
"err",
"error",
"\n",
"}",
"\n",
"session",
":=",
"c",
".",
"getSession",
"(",
")",
"\n",
"if",
"session",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"not connected\"",
")",
"\n",
"}",
"\n",
"done",
":=",
"make",
"(",
"chan",
"recv",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"msg",
",",
"err",
":=",
"session",
".",
"Recv",
"(",
")",
"\n",
"done",
"<-",
"recv",
"{",
"[",
"]",
"byte",
"(",
"msg",
")",
",",
"err",
"}",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"r",
":=",
"<-",
"done",
":",
"return",
"r",
".",
"msg",
",",
"r",
".",
"err",
"\n",
"case",
"err",
":=",
"<-",
"c",
".",
"interrupt",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // receiveData reads a message from session. | [
"receiveData",
"reads",
"a",
"message",
"from",
"session",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L460-L484 | train |
koding/kite | client.go | processMessage | func (c *Client) processMessage(data []byte) (msg *dnode.Message, fn interface{}, err error) {
// Call error handler.
defer func() {
if err != nil {
onError(err)
}
}()
msg = &dnode.Message{}
if err = json.Unmarshal(data, &msg); err != nil {
return nil, nil, err
}
sender := func(id uint64, args []interface{}) error {
// do not name the error variable to "err" here, it's a trap for
// shadowing variables
_, _, e := c.marshalAndSend(id, args)
return e
}
// Replace function placeholders with real functions.
if err := dnode.ParseCallbacks(msg, sender); err != nil {
return nil, nil, err
}
// Find the handler function. Method may be string or integer.
switch method := msg.Method.(type) {
case float64:
id := uint64(method)
callback := c.scrubber.GetCallback(id)
if callback == nil {
err = dnode.CallbackNotFoundError{
ID: id,
Args: msg.Arguments,
}
return nil, nil, err
}
return msg, callback, nil
case string:
m, ok := c.LocalKite.handlers[method]
if !ok {
err = dnode.MethodNotFoundError{
Method: method,
Args: msg.Arguments,
}
return nil, nil, err
}
return msg, m, nil
default:
return nil, nil, fmt.Errorf("Method is not string or integer: %+v (%T)", msg.Method, msg.Method)
}
} | go | func (c *Client) processMessage(data []byte) (msg *dnode.Message, fn interface{}, err error) {
// Call error handler.
defer func() {
if err != nil {
onError(err)
}
}()
msg = &dnode.Message{}
if err = json.Unmarshal(data, &msg); err != nil {
return nil, nil, err
}
sender := func(id uint64, args []interface{}) error {
// do not name the error variable to "err" here, it's a trap for
// shadowing variables
_, _, e := c.marshalAndSend(id, args)
return e
}
// Replace function placeholders with real functions.
if err := dnode.ParseCallbacks(msg, sender); err != nil {
return nil, nil, err
}
// Find the handler function. Method may be string or integer.
switch method := msg.Method.(type) {
case float64:
id := uint64(method)
callback := c.scrubber.GetCallback(id)
if callback == nil {
err = dnode.CallbackNotFoundError{
ID: id,
Args: msg.Arguments,
}
return nil, nil, err
}
return msg, callback, nil
case string:
m, ok := c.LocalKite.handlers[method]
if !ok {
err = dnode.MethodNotFoundError{
Method: method,
Args: msg.Arguments,
}
return nil, nil, err
}
return msg, m, nil
default:
return nil, nil, fmt.Errorf("Method is not string or integer: %+v (%T)", msg.Method, msg.Method)
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"processMessage",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"msg",
"*",
"dnode",
".",
"Message",
",",
"fn",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"onError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"msg",
"=",
"&",
"dnode",
".",
"Message",
"{",
"}",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sender",
":=",
"func",
"(",
"id",
"uint64",
",",
"args",
"[",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"_",
",",
"_",
",",
"e",
":=",
"c",
".",
"marshalAndSend",
"(",
"id",
",",
"args",
")",
"\n",
"return",
"e",
"\n",
"}",
"\n",
"if",
"err",
":=",
"dnode",
".",
"ParseCallbacks",
"(",
"msg",
",",
"sender",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"switch",
"method",
":=",
"msg",
".",
"Method",
".",
"(",
"type",
")",
"{",
"case",
"float64",
":",
"id",
":=",
"uint64",
"(",
"method",
")",
"\n",
"callback",
":=",
"c",
".",
"scrubber",
".",
"GetCallback",
"(",
"id",
")",
"\n",
"if",
"callback",
"==",
"nil",
"{",
"err",
"=",
"dnode",
".",
"CallbackNotFoundError",
"{",
"ID",
":",
"id",
",",
"Args",
":",
"msg",
".",
"Arguments",
",",
"}",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"msg",
",",
"callback",
",",
"nil",
"\n",
"case",
"string",
":",
"m",
",",
"ok",
":=",
"c",
".",
"LocalKite",
".",
"handlers",
"[",
"method",
"]",
"\n",
"if",
"!",
"ok",
"{",
"err",
"=",
"dnode",
".",
"MethodNotFoundError",
"{",
"Method",
":",
"method",
",",
"Args",
":",
"msg",
".",
"Arguments",
",",
"}",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"msg",
",",
"m",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Method is not string or integer: %+v (%T)\"",
",",
"msg",
".",
"Method",
",",
"msg",
".",
"Method",
")",
"\n",
"}",
"\n",
"}"
] | // processMessage processes a single message and calls a handler or callback. | [
"processMessage",
"processes",
"a",
"single",
"message",
"and",
"calls",
"a",
"handler",
"or",
"callback",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L487-L541 | train |
koding/kite | client.go | sendHub | func (c *Client) sendHub() {
defer c.wg.Done()
for {
select {
case msg := <-c.send:
c.LocalKite.Log.Debug("sending: %s", msg)
session := c.getSession()
if session == nil {
c.LocalKite.Log.Error("not connected")
continue
}
err := session.Send(string(msg.p))
if err != nil {
if msg.errC != nil {
msg.errC <- err
}
if sockjsclient.IsSessionClosed(err) {
// The readloop may already be interrupted, thus the non-blocking send.
select {
case c.interrupt <- err:
default:
}
c.LocalKite.Log.Error("error sending to %s: %s", session.ID(), err)
return
}
}
case <-c.closeChan:
c.LocalKite.Log.Debug("Send hub is closed")
return
}
}
} | go | func (c *Client) sendHub() {
defer c.wg.Done()
for {
select {
case msg := <-c.send:
c.LocalKite.Log.Debug("sending: %s", msg)
session := c.getSession()
if session == nil {
c.LocalKite.Log.Error("not connected")
continue
}
err := session.Send(string(msg.p))
if err != nil {
if msg.errC != nil {
msg.errC <- err
}
if sockjsclient.IsSessionClosed(err) {
// The readloop may already be interrupted, thus the non-blocking send.
select {
case c.interrupt <- err:
default:
}
c.LocalKite.Log.Error("error sending to %s: %s", session.ID(), err)
return
}
}
case <-c.closeChan:
c.LocalKite.Log.Debug("Send hub is closed")
return
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"sendHub",
"(",
")",
"{",
"defer",
"c",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"msg",
":=",
"<-",
"c",
".",
"send",
":",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Debug",
"(",
"\"sending: %s\"",
",",
"msg",
")",
"\n",
"session",
":=",
"c",
".",
"getSession",
"(",
")",
"\n",
"if",
"session",
"==",
"nil",
"{",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Error",
"(",
"\"not connected\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"err",
":=",
"session",
".",
"Send",
"(",
"string",
"(",
"msg",
".",
"p",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"msg",
".",
"errC",
"!=",
"nil",
"{",
"msg",
".",
"errC",
"<-",
"err",
"\n",
"}",
"\n",
"if",
"sockjsclient",
".",
"IsSessionClosed",
"(",
"err",
")",
"{",
"select",
"{",
"case",
"c",
".",
"interrupt",
"<-",
"err",
":",
"default",
":",
"}",
"\n",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Error",
"(",
"\"error sending to %s: %s\"",
",",
"session",
".",
"ID",
"(",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"<-",
"c",
".",
"closeChan",
":",
"c",
".",
"LocalKite",
".",
"Log",
".",
"Debug",
"(",
"\"Send hub is closed\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // sendhub sends the msg received from the send channel to the remote client | [
"sendhub",
"sends",
"the",
"msg",
"received",
"from",
"the",
"send",
"channel",
"to",
"the",
"remote",
"client"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L572-L607 | train |
koding/kite | client.go | OnConnect | func (c *Client) OnConnect(handler func()) {
c.m.Lock()
c.onConnectHandlers = append(c.onConnectHandlers, handler)
c.m.Unlock()
} | go | func (c *Client) OnConnect(handler func()) {
c.m.Lock()
c.onConnectHandlers = append(c.onConnectHandlers, handler)
c.m.Unlock()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OnConnect",
"(",
"handler",
"func",
"(",
")",
")",
"{",
"c",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"onConnectHandlers",
"=",
"append",
"(",
"c",
".",
"onConnectHandlers",
",",
"handler",
")",
"\n",
"c",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // OnConnect adds a callback which is called when client connects
// to a remote kite. | [
"OnConnect",
"adds",
"a",
"callback",
"which",
"is",
"called",
"when",
"client",
"connects",
"to",
"a",
"remote",
"kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L611-L615 | train |
koding/kite | client.go | OnDisconnect | func (c *Client) OnDisconnect(handler func()) {
c.m.Lock()
c.onDisconnectHandlers = append(c.onDisconnectHandlers, handler)
c.m.Unlock()
} | go | func (c *Client) OnDisconnect(handler func()) {
c.m.Lock()
c.onDisconnectHandlers = append(c.onDisconnectHandlers, handler)
c.m.Unlock()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OnDisconnect",
"(",
"handler",
"func",
"(",
")",
")",
"{",
"c",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"onDisconnectHandlers",
"=",
"append",
"(",
"c",
".",
"onDisconnectHandlers",
",",
"handler",
")",
"\n",
"c",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // OnDisconnect adds a callback which is called when client disconnects
// from a remote kite. | [
"OnDisconnect",
"adds",
"a",
"callback",
"which",
"is",
"called",
"when",
"client",
"disconnects",
"from",
"a",
"remote",
"kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L619-L623 | train |
koding/kite | client.go | OnTokenExpire | func (c *Client) OnTokenExpire(handler func()) {
c.m.Lock()
c.onTokenExpireHandlers = append(c.onTokenExpireHandlers, handler)
c.m.Unlock()
} | go | func (c *Client) OnTokenExpire(handler func()) {
c.m.Lock()
c.onTokenExpireHandlers = append(c.onTokenExpireHandlers, handler)
c.m.Unlock()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OnTokenExpire",
"(",
"handler",
"func",
"(",
")",
")",
"{",
"c",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"onTokenExpireHandlers",
"=",
"append",
"(",
"c",
".",
"onTokenExpireHandlers",
",",
"handler",
")",
"\n",
"c",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // OnTokenExpire adds a callback which is called when client receives
// token-is-expired error from a remote kite. | [
"OnTokenExpire",
"adds",
"a",
"callback",
"which",
"is",
"called",
"when",
"client",
"receives",
"token",
"-",
"is",
"-",
"expired",
"error",
"from",
"a",
"remote",
"kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/client.go#L627-L631 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.