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
chromedp/cdproto
fetch/fetch.go
WithMethod
func (p ContinueRequestParams) WithMethod(method string) *ContinueRequestParams { p.Method = method return &p }
go
func (p ContinueRequestParams) WithMethod(method string) *ContinueRequestParams { p.Method = method return &p }
[ "func", "(", "p", "ContinueRequestParams", ")", "WithMethod", "(", "method", "string", ")", "*", "ContinueRequestParams", "{", "p", ".", "Method", "=", "method", "\n", "return", "&", "p", "\n", "}" ]
// WithMethod if set, the request method is overridden.
[ "WithMethod", "if", "set", "the", "request", "method", "is", "overridden", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L174-L177
test
chromedp/cdproto
fetch/fetch.go
WithPostData
func (p ContinueRequestParams) WithPostData(postData string) *ContinueRequestParams { p.PostData = postData return &p }
go
func (p ContinueRequestParams) WithPostData(postData string) *ContinueRequestParams { p.PostData = postData return &p }
[ "func", "(", "p", "ContinueRequestParams", ")", "WithPostData", "(", "postData", "string", ")", "*", "ContinueRequestParams", "{", "p", ".", "PostData", "=", "postData", "\n", "return", "&", "p", "\n", "}" ]
// WithPostData if set, overrides the post data in the request.
[ "WithPostData", "if", "set", "overrides", "the", "post", "data", "in", "the", "request", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L180-L183
test
chromedp/cdproto
fetch/fetch.go
WithHeaders
func (p ContinueRequestParams) WithHeaders(headers []*HeaderEntry) *ContinueRequestParams { p.Headers = headers return &p }
go
func (p ContinueRequestParams) WithHeaders(headers []*HeaderEntry) *ContinueRequestParams { p.Headers = headers return &p }
[ "func", "(", "p", "ContinueRequestParams", ")", "WithHeaders", "(", "headers", "[", "]", "*", "HeaderEntry", ")", "*", "ContinueRequestParams", "{", "p", ".", "Headers", "=", "headers", "\n", "return", "&", "p", "\n", "}" ]
// WithHeaders if set, overrides the request headrts.
[ "WithHeaders", "if", "set", "overrides", "the", "request", "headrts", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L186-L189
test
chromedp/cdproto
fetch/fetch.go
Do
func (p *ContinueRequestParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueRequest, p, nil) }
go
func (p *ContinueRequestParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueRequest, p, nil) }
[ "func", "(", "p", "*", "ContinueRequestParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandContinueRequest", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Fetch.continueRequest against the provided context.
[ "Do", "executes", "Fetch", ".", "continueRequest", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L192-L194
test
chromedp/cdproto
fetch/fetch.go
Do
func (p *ContinueWithAuthParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueWithAuth, p, nil) }
go
func (p *ContinueWithAuthParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueWithAuth, p, nil) }
[ "func", "(", "p", "*", "ContinueWithAuthParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandContinueWithAuth", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Fetch.continueWithAuth against the provided context.
[ "Do", "executes", "Fetch", ".", "continueWithAuth", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L219-L221
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *ContinueToLocationParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueToLocation, p, nil) }
go
func (p *ContinueToLocationParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandContinueToLocation, p, nil) }
[ "func", "(", "p", "*", "ContinueToLocationParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandContinueToLocation", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.continueToLocation against the provided context.
[ "Do", "executes", "Debugger", ".", "continueToLocation", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L46-L48
test
chromedp/cdproto
debugger/debugger.go
WithIncludeCommandLineAPI
func (p EvaluateOnCallFrameParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *EvaluateOnCallFrameParams { p.IncludeCommandLineAPI = includeCommandLineAPI return &p }
go
func (p EvaluateOnCallFrameParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *EvaluateOnCallFrameParams { p.IncludeCommandLineAPI = includeCommandLineAPI return &p }
[ "func", "(", "p", "EvaluateOnCallFrameParams", ")", "WithIncludeCommandLineAPI", "(", "includeCommandLineAPI", "bool", ")", "*", "EvaluateOnCallFrameParams", "{", "p", ".", "IncludeCommandLineAPI", "=", "includeCommandLineAPI", "\n", "return", "&", "p", "\n", "}" ]
// WithIncludeCommandLineAPI specifies whether command line API should be // available to the evaluated expression, defaults to false.
[ "WithIncludeCommandLineAPI", "specifies", "whether", "command", "line", "API", "should", "be", "available", "to", "the", "evaluated", "expression", "defaults", "to", "false", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L146-L149
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *PauseParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandPause, nil, nil) }
go
func (p *PauseParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandPause, nil, nil) }
[ "func", "(", "p", "*", "PauseParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandPause", ",", "nil", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.pause against the provided context.
[ "Do", "executes", "Debugger", ".", "pause", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L346-L348
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *PauseOnAsyncCallParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandPauseOnAsyncCall, p, nil) }
go
func (p *PauseOnAsyncCallParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandPauseOnAsyncCall, p, nil) }
[ "func", "(", "p", "*", "PauseOnAsyncCallParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandPauseOnAsyncCall", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.pauseOnAsyncCall against the provided context.
[ "Do", "executes", "Debugger", ".", "pauseOnAsyncCall", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L368-L370
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *RemoveBreakpointParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRemoveBreakpoint, p, nil) }
go
func (p *RemoveBreakpointParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRemoveBreakpoint, p, nil) }
[ "func", "(", "p", "*", "RemoveBreakpointParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandRemoveBreakpoint", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.removeBreakpoint against the provided context.
[ "Do", "executes", "Debugger", ".", "removeBreakpoint", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L390-L392
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *ResumeParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandResume, nil, nil) }
go
func (p *ResumeParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandResume, nil, nil) }
[ "func", "(", "p", "*", "ResumeParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandResume", ",", "nil", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.resume against the provided context.
[ "Do", "executes", "Debugger", ".", "resume", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L446-L448
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetAsyncCallStackDepthParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetAsyncCallStackDepth, p, nil) }
go
func (p *SetAsyncCallStackDepthParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetAsyncCallStackDepth, p, nil) }
[ "func", "(", "p", "*", "SetAsyncCallStackDepthParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetAsyncCallStackDepth", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setAsyncCallStackDepth against the provided context.
[ "Do", "executes", "Debugger", ".", "setAsyncCallStackDepth", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L523-L525
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetBlackboxPatternsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxPatterns, p, nil) }
go
func (p *SetBlackboxPatternsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxPatterns, p, nil) }
[ "func", "(", "p", "*", "SetBlackboxPatternsParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetBlackboxPatterns", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setBlackboxPatterns against the provided context.
[ "Do", "executes", "Debugger", ".", "setBlackboxPatterns", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L551-L553
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetBlackboxedRangesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxedRanges, p, nil) }
go
func (p *SetBlackboxedRangesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxedRanges, p, nil) }
[ "func", "(", "p", "*", "SetBlackboxedRangesParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetBlackboxedRanges", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setBlackboxedRanges against the provided context.
[ "Do", "executes", "Debugger", ".", "setBlackboxedRanges", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L584-L586
test
chromedp/cdproto
debugger/debugger.go
WithURL
func (p SetBreakpointByURLParams) WithURL(url string) *SetBreakpointByURLParams { p.URL = url return &p }
go
func (p SetBreakpointByURLParams) WithURL(url string) *SetBreakpointByURLParams { p.URL = url return &p }
[ "func", "(", "p", "SetBreakpointByURLParams", ")", "WithURL", "(", "url", "string", ")", "*", "SetBreakpointByURLParams", "{", "p", ".", "URL", "=", "url", "\n", "return", "&", "p", "\n", "}" ]
// WithURL URL of the resources to set breakpoint on.
[ "WithURL", "URL", "of", "the", "resources", "to", "set", "breakpoint", "on", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L668-L671
test
chromedp/cdproto
debugger/debugger.go
WithURLRegex
func (p SetBreakpointByURLParams) WithURLRegex(urlRegex string) *SetBreakpointByURLParams { p.URLRegex = urlRegex return &p }
go
func (p SetBreakpointByURLParams) WithURLRegex(urlRegex string) *SetBreakpointByURLParams { p.URLRegex = urlRegex return &p }
[ "func", "(", "p", "SetBreakpointByURLParams", ")", "WithURLRegex", "(", "urlRegex", "string", ")", "*", "SetBreakpointByURLParams", "{", "p", ".", "URLRegex", "=", "urlRegex", "\n", "return", "&", "p", "\n", "}" ]
// WithURLRegex regex pattern for the URLs of the resources to set // breakpoints on. Either url or urlRegex must be specified.
[ "WithURLRegex", "regex", "pattern", "for", "the", "URLs", "of", "the", "resources", "to", "set", "breakpoints", "on", ".", "Either", "url", "or", "urlRegex", "must", "be", "specified", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L675-L678
test
chromedp/cdproto
debugger/debugger.go
WithScriptHash
func (p SetBreakpointByURLParams) WithScriptHash(scriptHash string) *SetBreakpointByURLParams { p.ScriptHash = scriptHash return &p }
go
func (p SetBreakpointByURLParams) WithScriptHash(scriptHash string) *SetBreakpointByURLParams { p.ScriptHash = scriptHash return &p }
[ "func", "(", "p", "SetBreakpointByURLParams", ")", "WithScriptHash", "(", "scriptHash", "string", ")", "*", "SetBreakpointByURLParams", "{", "p", ".", "ScriptHash", "=", "scriptHash", "\n", "return", "&", "p", "\n", "}" ]
// WithScriptHash script hash of the resources to set breakpoint on.
[ "WithScriptHash", "script", "hash", "of", "the", "resources", "to", "set", "breakpoint", "on", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L681-L684
test
chromedp/cdproto
debugger/debugger.go
WithColumnNumber
func (p SetBreakpointByURLParams) WithColumnNumber(columnNumber int64) *SetBreakpointByURLParams { p.ColumnNumber = columnNumber return &p }
go
func (p SetBreakpointByURLParams) WithColumnNumber(columnNumber int64) *SetBreakpointByURLParams { p.ColumnNumber = columnNumber return &p }
[ "func", "(", "p", "SetBreakpointByURLParams", ")", "WithColumnNumber", "(", "columnNumber", "int64", ")", "*", "SetBreakpointByURLParams", "{", "p", ".", "ColumnNumber", "=", "columnNumber", "\n", "return", "&", "p", "\n", "}" ]
// WithColumnNumber offset in the line to set breakpoint at.
[ "WithColumnNumber", "offset", "in", "the", "line", "to", "set", "breakpoint", "at", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L687-L690
test
chromedp/cdproto
debugger/debugger.go
WithCondition
func (p SetBreakpointOnFunctionCallParams) WithCondition(condition string) *SetBreakpointOnFunctionCallParams { p.Condition = condition return &p }
go
func (p SetBreakpointOnFunctionCallParams) WithCondition(condition string) *SetBreakpointOnFunctionCallParams { p.Condition = condition return &p }
[ "func", "(", "p", "SetBreakpointOnFunctionCallParams", ")", "WithCondition", "(", "condition", "string", ")", "*", "SetBreakpointOnFunctionCallParams", "{", "p", ".", "Condition", "=", "condition", "\n", "return", "&", "p", "\n", "}" ]
// WithCondition expression to use as a breakpoint condition. When specified, // debugger will stop on the breakpoint if this expression evaluates to true.
[ "WithCondition", "expression", "to", "use", "as", "a", "breakpoint", "condition", ".", "When", "specified", "debugger", "will", "stop", "on", "the", "breakpoint", "if", "this", "expression", "evaluates", "to", "true", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L746-L749
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetBreakpointsActiveParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBreakpointsActive, p, nil) }
go
func (p *SetBreakpointsActiveParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBreakpointsActive, p, nil) }
[ "func", "(", "p", "*", "SetBreakpointsActiveParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetBreakpointsActive", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setBreakpointsActive against the provided context.
[ "Do", "executes", "Debugger", ".", "setBreakpointsActive", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L790-L792
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetPauseOnExceptionsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetPauseOnExceptions, p, nil) }
go
func (p *SetPauseOnExceptionsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetPauseOnExceptions, p, nil) }
[ "func", "(", "p", "*", "SetPauseOnExceptionsParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetPauseOnExceptions", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setPauseOnExceptions against the provided context.
[ "Do", "executes", "Debugger", ".", "setPauseOnExceptions", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L816-L818
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetReturnValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetReturnValue, p, nil) }
go
func (p *SetReturnValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetReturnValue, p, nil) }
[ "func", "(", "p", "*", "SetReturnValueParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetReturnValue", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setReturnValue against the provided context.
[ "Do", "executes", "Debugger", ".", "setReturnValue", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L840-L842
test
chromedp/cdproto
debugger/debugger.go
WithDryRun
func (p SetScriptSourceParams) WithDryRun(dryRun bool) *SetScriptSourceParams { p.DryRun = dryRun return &p }
go
func (p SetScriptSourceParams) WithDryRun(dryRun bool) *SetScriptSourceParams { p.DryRun = dryRun return &p }
[ "func", "(", "p", "SetScriptSourceParams", ")", "WithDryRun", "(", "dryRun", "bool", ")", "*", "SetScriptSourceParams", "{", "p", ".", "DryRun", "=", "dryRun", "\n", "return", "&", "p", "\n", "}" ]
// WithDryRun if true the change will not actually be applied. Dry run may be // used to get result description without actually modifying the code.
[ "WithDryRun", "if", "true", "the", "change", "will", "not", "actually", "be", "applied", ".", "Dry", "run", "may", "be", "used", "to", "get", "result", "description", "without", "actually", "modifying", "the", "code", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L867-L870
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetSkipAllPausesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetSkipAllPauses, p, nil) }
go
func (p *SetSkipAllPausesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetSkipAllPauses, p, nil) }
[ "func", "(", "p", "*", "SetSkipAllPausesParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetSkipAllPauses", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setSkipAllPauses against the provided context.
[ "Do", "executes", "Debugger", ".", "setSkipAllPauses", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L920-L922
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *SetVariableValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetVariableValue, p, nil) }
go
func (p *SetVariableValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetVariableValue, p, nil) }
[ "func", "(", "p", "*", "SetVariableValueParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandSetVariableValue", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.setVariableValue against the provided context.
[ "Do", "executes", "Debugger", ".", "setVariableValue", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L953-L955
test
chromedp/cdproto
debugger/debugger.go
WithBreakOnAsyncCall
func (p StepIntoParams) WithBreakOnAsyncCall(breakOnAsyncCall bool) *StepIntoParams { p.BreakOnAsyncCall = breakOnAsyncCall return &p }
go
func (p StepIntoParams) WithBreakOnAsyncCall(breakOnAsyncCall bool) *StepIntoParams { p.BreakOnAsyncCall = breakOnAsyncCall return &p }
[ "func", "(", "p", "StepIntoParams", ")", "WithBreakOnAsyncCall", "(", "breakOnAsyncCall", "bool", ")", "*", "StepIntoParams", "{", "p", ".", "BreakOnAsyncCall", "=", "breakOnAsyncCall", "\n", "return", "&", "p", "\n", "}" ]
// WithBreakOnAsyncCall debugger will issue additional Debugger.paused // notification if any async task is scheduled before next pause.
[ "WithBreakOnAsyncCall", "debugger", "will", "issue", "additional", "Debugger", ".", "paused", "notification", "if", "any", "async", "task", "is", "scheduled", "before", "next", "pause", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L973-L976
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *StepIntoParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepInto, p, nil) }
go
func (p *StepIntoParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepInto, p, nil) }
[ "func", "(", "p", "*", "StepIntoParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandStepInto", ",", "p", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.stepInto against the provided context.
[ "Do", "executes", "Debugger", ".", "stepInto", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L979-L981
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *StepOutParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOut, nil, nil) }
go
func (p *StepOutParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOut, nil, nil) }
[ "func", "(", "p", "*", "StepOutParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandStepOut", ",", "nil", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.stepOut against the provided context.
[ "Do", "executes", "Debugger", ".", "stepOut", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L994-L996
test
chromedp/cdproto
debugger/debugger.go
Do
func (p *StepOverParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOver, nil, nil) }
go
func (p *StepOverParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOver, nil, nil) }
[ "func", "(", "p", "*", "StepOverParams", ")", "Do", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "return", "cdp", ".", "Execute", "(", "ctx", ",", "CommandStepOver", ",", "nil", ",", "nil", ")", "\n", "}" ]
// Do executes Debugger.stepOver against the provided context.
[ "Do", "executes", "Debugger", ".", "stepOver", "against", "the", "provided", "context", "." ]
d40c70bcdf242660a32f2eadf323662dd75378b5
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L1009-L1011
test
libp2p/go-libp2p-net
notifiee.go
Listen
func (nb *NotifyBundle) Listen(n Network, a ma.Multiaddr) { if nb.ListenF != nil { nb.ListenF(n, a) } }
go
func (nb *NotifyBundle) Listen(n Network, a ma.Multiaddr) { if nb.ListenF != nil { nb.ListenF(n, a) } }
[ "func", "(", "nb", "*", "NotifyBundle", ")", "Listen", "(", "n", "Network", ",", "a", "ma", ".", "Multiaddr", ")", "{", "if", "nb", ".", "ListenF", "!=", "nil", "{", "nb", ".", "ListenF", "(", "n", ",", "a", ")", "\n", "}", "\n", "}" ]
// Listen calls ListenF if it is not null.
[ "Listen", "calls", "ListenF", "if", "it", "is", "not", "null", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L24-L28
test
libp2p/go-libp2p-net
notifiee.go
ListenClose
func (nb *NotifyBundle) ListenClose(n Network, a ma.Multiaddr) { if nb.ListenCloseF != nil { nb.ListenCloseF(n, a) } }
go
func (nb *NotifyBundle) ListenClose(n Network, a ma.Multiaddr) { if nb.ListenCloseF != nil { nb.ListenCloseF(n, a) } }
[ "func", "(", "nb", "*", "NotifyBundle", ")", "ListenClose", "(", "n", "Network", ",", "a", "ma", ".", "Multiaddr", ")", "{", "if", "nb", ".", "ListenCloseF", "!=", "nil", "{", "nb", ".", "ListenCloseF", "(", "n", ",", "a", ")", "\n", "}", "\n", "}" ]
// ListenClose calls ListenCloseF if it is not null.
[ "ListenClose", "calls", "ListenCloseF", "if", "it", "is", "not", "null", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L31-L35
test
libp2p/go-libp2p-net
notifiee.go
Connected
func (nb *NotifyBundle) Connected(n Network, c Conn) { if nb.ConnectedF != nil { nb.ConnectedF(n, c) } }
go
func (nb *NotifyBundle) Connected(n Network, c Conn) { if nb.ConnectedF != nil { nb.ConnectedF(n, c) } }
[ "func", "(", "nb", "*", "NotifyBundle", ")", "Connected", "(", "n", "Network", ",", "c", "Conn", ")", "{", "if", "nb", ".", "ConnectedF", "!=", "nil", "{", "nb", ".", "ConnectedF", "(", "n", ",", "c", ")", "\n", "}", "\n", "}" ]
// Connected calls ConnectedF if it is not null.
[ "Connected", "calls", "ConnectedF", "if", "it", "is", "not", "null", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L38-L42
test
libp2p/go-libp2p-net
notifiee.go
Disconnected
func (nb *NotifyBundle) Disconnected(n Network, c Conn) { if nb.DisconnectedF != nil { nb.DisconnectedF(n, c) } }
go
func (nb *NotifyBundle) Disconnected(n Network, c Conn) { if nb.DisconnectedF != nil { nb.DisconnectedF(n, c) } }
[ "func", "(", "nb", "*", "NotifyBundle", ")", "Disconnected", "(", "n", "Network", ",", "c", "Conn", ")", "{", "if", "nb", ".", "DisconnectedF", "!=", "nil", "{", "nb", ".", "DisconnectedF", "(", "n", ",", "c", ")", "\n", "}", "\n", "}" ]
// Disconnected calls DisconnectedF if it is not null.
[ "Disconnected", "calls", "DisconnectedF", "if", "it", "is", "not", "null", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L45-L49
test
libp2p/go-libp2p-net
notifiee.go
OpenedStream
func (nb *NotifyBundle) OpenedStream(n Network, s Stream) { if nb.OpenedStreamF != nil { nb.OpenedStreamF(n, s) } }
go
func (nb *NotifyBundle) OpenedStream(n Network, s Stream) { if nb.OpenedStreamF != nil { nb.OpenedStreamF(n, s) } }
[ "func", "(", "nb", "*", "NotifyBundle", ")", "OpenedStream", "(", "n", "Network", ",", "s", "Stream", ")", "{", "if", "nb", ".", "OpenedStreamF", "!=", "nil", "{", "nb", ".", "OpenedStreamF", "(", "n", ",", "s", ")", "\n", "}", "\n", "}" ]
// OpenedStream calls OpenedStreamF if it is not null.
[ "OpenedStream", "calls", "OpenedStreamF", "if", "it", "is", "not", "null", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L52-L56
test
libp2p/go-libp2p-net
notifiee.go
ClosedStream
func (nb *NotifyBundle) ClosedStream(n Network, s Stream) { if nb.ClosedStreamF != nil { nb.ClosedStreamF(n, s) } }
go
func (nb *NotifyBundle) ClosedStream(n Network, s Stream) { if nb.ClosedStreamF != nil { nb.ClosedStreamF(n, s) } }
[ "func", "(", "nb", "*", "NotifyBundle", ")", "ClosedStream", "(", "n", "Network", ",", "s", "Stream", ")", "{", "if", "nb", ".", "ClosedStreamF", "!=", "nil", "{", "nb", ".", "ClosedStreamF", "(", "n", ",", "s", ")", "\n", "}", "\n", "}" ]
// ClosedStream calls ClosedStreamF if it is not null.
[ "ClosedStream", "calls", "ClosedStreamF", "if", "it", "is", "not", "null", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L59-L63
test
libp2p/go-libp2p-net
options.go
WithNoDial
func WithNoDial(ctx context.Context, reason string) context.Context { return context.WithValue(ctx, noDial, reason) }
go
func WithNoDial(ctx context.Context, reason string) context.Context { return context.WithValue(ctx, noDial, reason) }
[ "func", "WithNoDial", "(", "ctx", "context", ".", "Context", ",", "reason", "string", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "noDial", ",", "reason", ")", "\n", "}" ]
// WithNoDial constructs a new context with an option that instructs the network // to not attempt a new dial when opening a stream.
[ "WithNoDial", "constructs", "a", "new", "context", "with", "an", "option", "that", "instructs", "the", "network", "to", "not", "attempt", "a", "new", "dial", "when", "opening", "a", "stream", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/options.go#L13-L15
test
libp2p/go-libp2p-net
options.go
GetNoDial
func GetNoDial(ctx context.Context) (nodial bool, reason string) { v := ctx.Value(noDial) if v != nil { return true, v.(string) } return false, "" }
go
func GetNoDial(ctx context.Context) (nodial bool, reason string) { v := ctx.Value(noDial) if v != nil { return true, v.(string) } return false, "" }
[ "func", "GetNoDial", "(", "ctx", "context", ".", "Context", ")", "(", "nodial", "bool", ",", "reason", "string", ")", "{", "v", ":=", "ctx", ".", "Value", "(", "noDial", ")", "\n", "if", "v", "!=", "nil", "{", "return", "true", ",", "v", ".", "(", "string", ")", "\n", "}", "\n", "return", "false", ",", "\"\"", "\n", "}" ]
// GetNoDial returns true if the no dial option is set in the context.
[ "GetNoDial", "returns", "true", "if", "the", "no", "dial", "option", "is", "set", "in", "the", "context", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/options.go#L18-L25
test
libp2p/go-libp2p-net
timeouts.go
WithDialPeerTimeout
func WithDialPeerTimeout(ctx context.Context, timeout time.Duration) context.Context { return context.WithValue(ctx, dialPeerTimeoutCtxKey{}, timeout) }
go
func WithDialPeerTimeout(ctx context.Context, timeout time.Duration) context.Context { return context.WithValue(ctx, dialPeerTimeoutCtxKey{}, timeout) }
[ "func", "WithDialPeerTimeout", "(", "ctx", "context", ".", "Context", ",", "timeout", "time", ".", "Duration", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "dialPeerTimeoutCtxKey", "{", "}", ",", "timeout", ")", "\n", "}" ]
// WithDialPeerTimeout returns a new context with the DialPeer timeout applied. // // This timeout overrides the default DialPeerTimeout and applies per-dial // independently.
[ "WithDialPeerTimeout", "returns", "a", "new", "context", "with", "the", "DialPeer", "timeout", "applied", ".", "This", "timeout", "overrides", "the", "default", "DialPeerTimeout", "and", "applies", "per", "-", "dial", "independently", "." ]
a60cde50df6872512892ca85019341d281f72a42
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/timeouts.go#L27-L29
test
gchaincl/sqlhooks
sqlhooks.go
Open
func (drv *Driver) Open(name string) (driver.Conn, error) { conn, err := drv.Driver.Open(name) if err != nil { return conn, err } wrapped := &Conn{conn, drv.hooks} if isExecer(conn) && isQueryer(conn) && isSessionResetter(conn) { return &ExecerQueryerContextWithSessionResetter{wrapped, &ExecerContext{wrapped}, &QueryerContext{wrapped}, &SessionResetter{wrapped}}, nil } else if isExecer(conn) && isQueryer(conn) { return &ExecerQueryerContext{wrapped, &ExecerContext{wrapped}, &QueryerContext{wrapped}}, nil } else if isExecer(conn) { // If conn implements an Execer interface, return a driver.Conn which // also implements Execer return &ExecerContext{wrapped}, nil } else if isQueryer(conn) { // If conn implements an Queryer interface, return a driver.Conn which // also implements Queryer return &QueryerContext{wrapped}, nil } return wrapped, nil }
go
func (drv *Driver) Open(name string) (driver.Conn, error) { conn, err := drv.Driver.Open(name) if err != nil { return conn, err } wrapped := &Conn{conn, drv.hooks} if isExecer(conn) && isQueryer(conn) && isSessionResetter(conn) { return &ExecerQueryerContextWithSessionResetter{wrapped, &ExecerContext{wrapped}, &QueryerContext{wrapped}, &SessionResetter{wrapped}}, nil } else if isExecer(conn) && isQueryer(conn) { return &ExecerQueryerContext{wrapped, &ExecerContext{wrapped}, &QueryerContext{wrapped}}, nil } else if isExecer(conn) { // If conn implements an Execer interface, return a driver.Conn which // also implements Execer return &ExecerContext{wrapped}, nil } else if isQueryer(conn) { // If conn implements an Queryer interface, return a driver.Conn which // also implements Queryer return &QueryerContext{wrapped}, nil } return wrapped, nil }
[ "func", "(", "drv", "*", "Driver", ")", "Open", "(", "name", "string", ")", "(", "driver", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "drv", ".", "Driver", ".", "Open", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "conn", ",", "err", "\n", "}", "\n", "wrapped", ":=", "&", "Conn", "{", "conn", ",", "drv", ".", "hooks", "}", "\n", "if", "isExecer", "(", "conn", ")", "&&", "isQueryer", "(", "conn", ")", "&&", "isSessionResetter", "(", "conn", ")", "{", "return", "&", "ExecerQueryerContextWithSessionResetter", "{", "wrapped", ",", "&", "ExecerContext", "{", "wrapped", "}", ",", "&", "QueryerContext", "{", "wrapped", "}", ",", "&", "SessionResetter", "{", "wrapped", "}", "}", ",", "nil", "\n", "}", "else", "if", "isExecer", "(", "conn", ")", "&&", "isQueryer", "(", "conn", ")", "{", "return", "&", "ExecerQueryerContext", "{", "wrapped", ",", "&", "ExecerContext", "{", "wrapped", "}", ",", "&", "QueryerContext", "{", "wrapped", "}", "}", ",", "nil", "\n", "}", "else", "if", "isExecer", "(", "conn", ")", "{", "return", "&", "ExecerContext", "{", "wrapped", "}", ",", "nil", "\n", "}", "else", "if", "isQueryer", "(", "conn", ")", "{", "return", "&", "QueryerContext", "{", "wrapped", "}", ",", "nil", "\n", "}", "\n", "return", "wrapped", ",", "nil", "\n", "}" ]
// Open opens a connection
[ "Open", "opens", "a", "connection" ]
1932c8dd22f2283687586008bf2d58c2c5c014d0
https://github.com/gchaincl/sqlhooks/blob/1932c8dd22f2283687586008bf2d58c2c5c014d0/sqlhooks.go#L46-L70
test
glycerine/rbuf
rbuf.go
Prevpos
func (f *FixedSizeRingBuf) Prevpos(from int) int { if from >= f.N || from < 0 { return -2 } if f.Readable == 0 { return -1 } if from == f.Beg { return -1 } a0, a1, b0, b1 := f.LegalPos() switch { case from == a0: return -1 case from > a0 && from <= a1: return from - 1 case from == b0: return a1 case from > b0 && from <= b1: return from - 1 } return -1 }
go
func (f *FixedSizeRingBuf) Prevpos(from int) int { if from >= f.N || from < 0 { return -2 } if f.Readable == 0 { return -1 } if from == f.Beg { return -1 } a0, a1, b0, b1 := f.LegalPos() switch { case from == a0: return -1 case from > a0 && from <= a1: return from - 1 case from == b0: return a1 case from > b0 && from <= b1: return from - 1 } return -1 }
[ "func", "(", "f", "*", "FixedSizeRingBuf", ")", "Prevpos", "(", "from", "int", ")", "int", "{", "if", "from", ">=", "f", ".", "N", "||", "from", "<", "0", "{", "return", "-", "2", "\n", "}", "\n", "if", "f", ".", "Readable", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "if", "from", "==", "f", ".", "Beg", "{", "return", "-", "1", "\n", "}", "\n", "a0", ",", "a1", ",", "b0", ",", "b1", ":=", "f", ".", "LegalPos", "(", ")", "\n", "switch", "{", "case", "from", "==", "a0", ":", "return", "-", "1", "\n", "case", "from", ">", "a0", "&&", "from", "<=", "a1", ":", "return", "from", "-", "1", "\n", "case", "from", "==", "b0", ":", "return", "a1", "\n", "case", "from", ">", "b0", "&&", "from", "<=", "b1", ":", "return", "from", "-", "1", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Prevpos returns the index of the element before // from, or -1 if no more and from is the // first in the ring. Returns -2 on bad // from position.
[ "Prevpos", "returns", "the", "index", "of", "the", "element", "before", "from", "or", "-", "1", "if", "no", "more", "and", "from", "is", "the", "first", "in", "the", "ring", ".", "Returns", "-", "2", "on", "bad", "from", "position", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L471-L493
test
glycerine/rbuf
rbuf.go
Last
func (f *FixedSizeRingBuf) Last() int { if f.Readable == 0 { return -1 } last := f.Beg + f.Readable - 1 if last < f.N { // we fit without wrapping return last } return last % f.N }
go
func (f *FixedSizeRingBuf) Last() int { if f.Readable == 0 { return -1 } last := f.Beg + f.Readable - 1 if last < f.N { // we fit without wrapping return last } return last % f.N }
[ "func", "(", "f", "*", "FixedSizeRingBuf", ")", "Last", "(", ")", "int", "{", "if", "f", ".", "Readable", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "last", ":=", "f", ".", "Beg", "+", "f", ".", "Readable", "-", "1", "\n", "if", "last", "<", "f", ".", "N", "{", "return", "last", "\n", "}", "\n", "return", "last", "%", "f", ".", "N", "\n", "}" ]
// Last returns the index of the last element, // or -1 if the ring is empty.
[ "Last", "returns", "the", "index", "of", "the", "last", "element", "or", "-", "1", "if", "the", "ring", "is", "empty", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L497-L509
test
glycerine/rbuf
rbuf.go
DeleteMostRecentBytes
func (f *FixedSizeRingBuf) DeleteMostRecentBytes(n int) { if n <= 0 { return } if n >= f.Readable { f.Readable = 0 return } f.Readable -= n }
go
func (f *FixedSizeRingBuf) DeleteMostRecentBytes(n int) { if n <= 0 { return } if n >= f.Readable { f.Readable = 0 return } f.Readable -= n }
[ "func", "(", "f", "*", "FixedSizeRingBuf", ")", "DeleteMostRecentBytes", "(", "n", "int", ")", "{", "if", "n", "<=", "0", "{", "return", "\n", "}", "\n", "if", "n", ">=", "f", ".", "Readable", "{", "f", ".", "Readable", "=", "0", "\n", "return", "\n", "}", "\n", "f", ".", "Readable", "-=", "n", "\n", "}" ]
// DeleteMostRecentBytes trims back the last n bytes written.
[ "DeleteMostRecentBytes", "trims", "back", "the", "last", "n", "bytes", "written", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L530-L539
test
glycerine/rbuf
fbuf.go
NewFloat64RingBuf
func NewFloat64RingBuf(maxViewItems int) *Float64RingBuf { n := maxViewItems r := &Float64RingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]float64, n, n) return r }
go
func NewFloat64RingBuf(maxViewItems int) *Float64RingBuf { n := maxViewItems r := &Float64RingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]float64, n, n) return r }
[ "func", "NewFloat64RingBuf", "(", "maxViewItems", "int", ")", "*", "Float64RingBuf", "{", "n", ":=", "maxViewItems", "\n", "r", ":=", "&", "Float64RingBuf", "{", "N", ":", "n", ",", "Beg", ":", "0", ",", "Readable", ":", "0", ",", "}", "\n", "r", ".", "A", "=", "make", "(", "[", "]", "float64", ",", "n", ",", "n", ")", "\n", "return", "r", "\n", "}" ]
// constructor. NewFloat64RingBuf will allocate internally // a slice of maxViewItems float64.
[ "constructor", ".", "NewFloat64RingBuf", "will", "allocate", "internally", "a", "slice", "of", "maxViewItems", "float64", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L23-L33
test
glycerine/rbuf
fbuf.go
TwoContig
func (b *Float64RingBuf) TwoContig(makeCopy bool) (first []float64, second []float64) { extent := b.Beg + b.Readable if extent <= b.N { // we fit contiguously in this buffer without wrapping to the other. // Let second stay an empty slice. return b.A[b.Beg:(b.Beg + b.Readable)], second } return b.A[b.Beg:b.N], b.A[0:(extent % b.N)] }
go
func (b *Float64RingBuf) TwoContig(makeCopy bool) (first []float64, second []float64) { extent := b.Beg + b.Readable if extent <= b.N { // we fit contiguously in this buffer without wrapping to the other. // Let second stay an empty slice. return b.A[b.Beg:(b.Beg + b.Readable)], second } return b.A[b.Beg:b.N], b.A[0:(extent % b.N)] }
[ "func", "(", "b", "*", "Float64RingBuf", ")", "TwoContig", "(", "makeCopy", "bool", ")", "(", "first", "[", "]", "float64", ",", "second", "[", "]", "float64", ")", "{", "extent", ":=", "b", ".", "Beg", "+", "b", ".", "Readable", "\n", "if", "extent", "<=", "b", ".", "N", "{", "return", "b", ".", "A", "[", "b", ".", "Beg", ":", "(", "b", ".", "Beg", "+", "b", ".", "Readable", ")", "]", ",", "second", "\n", "}", "\n", "return", "b", ".", "A", "[", "b", ".", "Beg", ":", "b", ".", "N", "]", ",", "b", ".", "A", "[", "0", ":", "(", "extent", "%", "b", ".", "N", ")", "]", "\n", "}" ]
// TwoContig returns all readable float64, but in two separate slices, // to avoid copying. The two slices are from the same buffer, but // are not contiguous. Either or both may be empty slices.
[ "TwoContig", "returns", "all", "readable", "float64", "but", "in", "two", "separate", "slices", "to", "avoid", "copying", ".", "The", "two", "slices", "are", "from", "the", "same", "buffer", "but", "are", "not", "contiguous", ".", "Either", "or", "both", "may", "be", "empty", "slices", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L38-L48
test
glycerine/rbuf
fbuf.go
Earliest
func (b *Float64RingBuf) Earliest() (v float64, ok bool) { if b.Readable == 0 { return } return b.A[b.Beg], true }
go
func (b *Float64RingBuf) Earliest() (v float64, ok bool) { if b.Readable == 0 { return } return b.A[b.Beg], true }
[ "func", "(", "b", "*", "Float64RingBuf", ")", "Earliest", "(", ")", "(", "v", "float64", ",", "ok", "bool", ")", "{", "if", "b", ".", "Readable", "==", "0", "{", "return", "\n", "}", "\n", "return", "b", ".", "A", "[", "b", ".", "Beg", "]", ",", "true", "\n", "}" ]
// Earliest returns the earliest written value v. ok will be // true unless the ring is empty, in which case ok will be false, // and v will be zero.
[ "Earliest", "returns", "the", "earliest", "written", "value", "v", ".", "ok", "will", "be", "true", "unless", "the", "ring", "is", "empty", "in", "which", "case", "ok", "will", "be", "false", "and", "v", "will", "be", "zero", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L53-L59
test
glycerine/rbuf
fbuf.go
Values
func (b *Float64RingBuf) Values() []float64 { first, second := b.TwoContig(false) if len(first) == 0 { return second } if len(second) == 0 { return first } out := make([]float64, len(first) + len(second)) copy(out, first) copy(out[len(first):], second) return out }
go
func (b *Float64RingBuf) Values() []float64 { first, second := b.TwoContig(false) if len(first) == 0 { return second } if len(second) == 0 { return first } out := make([]float64, len(first) + len(second)) copy(out, first) copy(out[len(first):], second) return out }
[ "func", "(", "b", "*", "Float64RingBuf", ")", "Values", "(", ")", "[", "]", "float64", "{", "first", ",", "second", ":=", "b", ".", "TwoContig", "(", "false", ")", "\n", "if", "len", "(", "first", ")", "==", "0", "{", "return", "second", "\n", "}", "\n", "if", "len", "(", "second", ")", "==", "0", "{", "return", "first", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "first", ")", "+", "len", "(", "second", ")", ")", "\n", "copy", "(", "out", ",", "first", ")", "\n", "copy", "(", "out", "[", "len", "(", "first", ")", ":", "]", ",", "second", ")", "\n", "return", "out", "\n", "}" ]
// Values returns all readable float64 in a single buffer. Calling this function // might allocate a new buffer to store the elements contiguously.
[ "Values", "returns", "all", "readable", "float64", "in", "a", "single", "buffer", ".", "Calling", "this", "function", "might", "allocate", "a", "new", "buffer", "to", "store", "the", "elements", "contiguously", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L63-L80
test
glycerine/rbuf
atomic_rbuf.go
NewAtomicFixedSizeRingBuf
func NewAtomicFixedSizeRingBuf(maxViewInBytes int) *AtomicFixedSizeRingBuf { n := maxViewInBytes r := &AtomicFixedSizeRingBuf{ Use: 0, // 0 or 1, whichever is actually in use at the moment. // If we are asked for Bytes() and we wrap, linearize into the other. N: n, Beg: 0, readable: 0, } r.A[0] = make([]byte, n, n) r.A[1] = make([]byte, n, n) return r }
go
func NewAtomicFixedSizeRingBuf(maxViewInBytes int) *AtomicFixedSizeRingBuf { n := maxViewInBytes r := &AtomicFixedSizeRingBuf{ Use: 0, // 0 or 1, whichever is actually in use at the moment. // If we are asked for Bytes() and we wrap, linearize into the other. N: n, Beg: 0, readable: 0, } r.A[0] = make([]byte, n, n) r.A[1] = make([]byte, n, n) return r }
[ "func", "NewAtomicFixedSizeRingBuf", "(", "maxViewInBytes", "int", ")", "*", "AtomicFixedSizeRingBuf", "{", "n", ":=", "maxViewInBytes", "\n", "r", ":=", "&", "AtomicFixedSizeRingBuf", "{", "Use", ":", "0", ",", "N", ":", "n", ",", "Beg", ":", "0", ",", "readable", ":", "0", ",", "}", "\n", "r", ".", "A", "[", "0", "]", "=", "make", "(", "[", "]", "byte", ",", "n", ",", "n", ")", "\n", "r", ".", "A", "[", "1", "]", "=", "make", "(", "[", "]", "byte", ",", "n", ",", "n", ")", "\n", "return", "r", "\n", "}" ]
// constructor. NewAtomicFixedSizeRingBuf will allocate internally // two buffers of size maxViewInBytes.
[ "constructor", ".", "NewAtomicFixedSizeRingBuf", "will", "allocate", "internally", "two", "buffers", "of", "size", "maxViewInBytes", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L56-L70
test
glycerine/rbuf
atomic_rbuf.go
Reset
func (b *AtomicFixedSizeRingBuf) Reset() { b.tex.Lock() defer b.tex.Unlock() b.Beg = 0 b.readable = 0 b.Use = 0 }
go
func (b *AtomicFixedSizeRingBuf) Reset() { b.tex.Lock() defer b.tex.Unlock() b.Beg = 0 b.readable = 0 b.Use = 0 }
[ "func", "(", "b", "*", "AtomicFixedSizeRingBuf", ")", "Reset", "(", ")", "{", "b", ".", "tex", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "tex", ".", "Unlock", "(", ")", "\n", "b", ".", "Beg", "=", "0", "\n", "b", ".", "readable", "=", "0", "\n", "b", ".", "Use", "=", "0", "\n", "}" ]
// Reset quickly forgets any data stored in the ring buffer. The // data is still there, but the ring buffer will ignore it and // overwrite those buffers as new data comes in.
[ "Reset", "quickly", "forgets", "any", "data", "stored", "in", "the", "ring", "buffer", ".", "The", "data", "is", "still", "there", "but", "the", "ring", "buffer", "will", "ignore", "it", "and", "overwrite", "those", "buffers", "as", "new", "data", "comes", "in", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L403-L410
test
glycerine/rbuf
pbuf.go
NewPointerRingBuf
func NewPointerRingBuf(sliceN int) *PointerRingBuf { n := sliceN r := &PointerRingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]interface{}, n, n) return r }
go
func NewPointerRingBuf(sliceN int) *PointerRingBuf { n := sliceN r := &PointerRingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]interface{}, n, n) return r }
[ "func", "NewPointerRingBuf", "(", "sliceN", "int", ")", "*", "PointerRingBuf", "{", "n", ":=", "sliceN", "\n", "r", ":=", "&", "PointerRingBuf", "{", "N", ":", "n", ",", "Beg", ":", "0", ",", "Readable", ":", "0", ",", "}", "\n", "r", ".", "A", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "n", ",", "n", ")", "\n", "return", "r", "\n", "}" ]
// constructor. NewPointerRingBuf will allocate internally // a slice of size sliceN
[ "constructor", ".", "NewPointerRingBuf", "will", "allocate", "internally", "a", "slice", "of", "size", "sliceN" ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L21-L31
test
glycerine/rbuf
pbuf.go
TwoContig
func (b *PointerRingBuf) TwoContig() (first []interface{}, second []interface{}) { extent := b.Beg + b.Readable if extent <= b.N { // we fit contiguously in this buffer without wrapping to the other. // Let second stay an empty slice. return b.A[b.Beg:(b.Beg + b.Readable)], second } return b.A[b.Beg:b.N], b.A[0:(extent % b.N)] }
go
func (b *PointerRingBuf) TwoContig() (first []interface{}, second []interface{}) { extent := b.Beg + b.Readable if extent <= b.N { // we fit contiguously in this buffer without wrapping to the other. // Let second stay an empty slice. return b.A[b.Beg:(b.Beg + b.Readable)], second } return b.A[b.Beg:b.N], b.A[0:(extent % b.N)] }
[ "func", "(", "b", "*", "PointerRingBuf", ")", "TwoContig", "(", ")", "(", "first", "[", "]", "interface", "{", "}", ",", "second", "[", "]", "interface", "{", "}", ")", "{", "extent", ":=", "b", ".", "Beg", "+", "b", ".", "Readable", "\n", "if", "extent", "<=", "b", ".", "N", "{", "return", "b", ".", "A", "[", "b", ".", "Beg", ":", "(", "b", ".", "Beg", "+", "b", ".", "Readable", ")", "]", ",", "second", "\n", "}", "\n", "return", "b", ".", "A", "[", "b", ".", "Beg", ":", "b", ".", "N", "]", ",", "b", ".", "A", "[", "0", ":", "(", "extent", "%", "b", ".", "N", ")", "]", "\n", "}" ]
// TwoContig returns all readable pointers, but in two separate slices, // to avoid copying. The two slices are from the same buffer, but // are not contiguous. Either or both may be empty slices.
[ "TwoContig", "returns", "all", "readable", "pointers", "but", "in", "two", "separate", "slices", "to", "avoid", "copying", ".", "The", "two", "slices", "are", "from", "the", "same", "buffer", "but", "are", "not", "contiguous", ".", "Either", "or", "both", "may", "be", "empty", "slices", "." ]
75b78581bebe959bc9a3df4c5f64e82c187d7531
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L36-L46
test
rsc/pdf
page.go
NumPage
func (r *Reader) NumPage() int { return int(r.Trailer().Key("Root").Key("Pages").Key("Count").Int64()) }
go
func (r *Reader) NumPage() int { return int(r.Trailer().Key("Root").Key("Pages").Key("Count").Int64()) }
[ "func", "(", "r", "*", "Reader", ")", "NumPage", "(", ")", "int", "{", "return", "int", "(", "r", ".", "Trailer", "(", ")", ".", "Key", "(", "\"Root\"", ")", ".", "Key", "(", "\"Pages\"", ")", ".", "Key", "(", "\"Count\"", ")", ".", "Int64", "(", ")", ")", "\n", "}" ]
// NumPage returns the number of pages in the PDF file.
[ "NumPage", "returns", "the", "number", "of", "pages", "in", "the", "PDF", "file", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L55-L57
test
rsc/pdf
page.go
Font
func (p Page) Font(name string) Font { return Font{p.Resources().Key("Font").Key(name)} }
go
func (p Page) Font(name string) Font { return Font{p.Resources().Key("Font").Key(name)} }
[ "func", "(", "p", "Page", ")", "Font", "(", "name", "string", ")", "Font", "{", "return", "Font", "{", "p", ".", "Resources", "(", ")", ".", "Key", "(", "\"Font\"", ")", ".", "Key", "(", "name", ")", "}", "\n", "}" ]
// Font returns the font with the given name associated with the page.
[ "Font", "returns", "the", "font", "with", "the", "given", "name", "associated", "with", "the", "page", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L89-L91
test
rsc/pdf
page.go
Width
func (f Font) Width(code int) float64 { first := f.FirstChar() last := f.LastChar() if code < first || last < code { return 0 } return f.V.Key("Widths").Index(code - first).Float64() }
go
func (f Font) Width(code int) float64 { first := f.FirstChar() last := f.LastChar() if code < first || last < code { return 0 } return f.V.Key("Widths").Index(code - first).Float64() }
[ "func", "(", "f", "Font", ")", "Width", "(", "code", "int", ")", "float64", "{", "first", ":=", "f", ".", "FirstChar", "(", ")", "\n", "last", ":=", "f", ".", "LastChar", "(", ")", "\n", "if", "code", "<", "first", "||", "last", "<", "code", "{", "return", "0", "\n", "}", "\n", "return", "f", ".", "V", ".", "Key", "(", "\"Widths\"", ")", ".", "Index", "(", "code", "-", "first", ")", ".", "Float64", "(", ")", "\n", "}" ]
// Width returns the width of the given code point.
[ "Width", "returns", "the", "width", "of", "the", "given", "code", "point", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L126-L133
test
rsc/pdf
page.go
Encoder
func (f Font) Encoder() TextEncoding { enc := f.V.Key("Encoding") switch enc.Kind() { case Name: switch enc.Name() { case "WinAnsiEncoding": return &byteEncoder{&winAnsiEncoding} case "MacRomanEncoding": return &byteEncoder{&macRomanEncoding} case "Identity-H": // TODO: Should be big-endian UCS-2 decoder return &nopEncoder{} default: println("unknown encoding", enc.Name()) return &nopEncoder{} } case Dict: return &dictEncoder{enc.Key("Differences")} case Null: // ok, try ToUnicode default: println("unexpected encoding", enc.String()) return &nopEncoder{} } toUnicode := f.V.Key("ToUnicode") if toUnicode.Kind() == Dict { m := readCmap(toUnicode) if m == nil { return &nopEncoder{} } return m } return &byteEncoder{&pdfDocEncoding} }
go
func (f Font) Encoder() TextEncoding { enc := f.V.Key("Encoding") switch enc.Kind() { case Name: switch enc.Name() { case "WinAnsiEncoding": return &byteEncoder{&winAnsiEncoding} case "MacRomanEncoding": return &byteEncoder{&macRomanEncoding} case "Identity-H": // TODO: Should be big-endian UCS-2 decoder return &nopEncoder{} default: println("unknown encoding", enc.Name()) return &nopEncoder{} } case Dict: return &dictEncoder{enc.Key("Differences")} case Null: // ok, try ToUnicode default: println("unexpected encoding", enc.String()) return &nopEncoder{} } toUnicode := f.V.Key("ToUnicode") if toUnicode.Kind() == Dict { m := readCmap(toUnicode) if m == nil { return &nopEncoder{} } return m } return &byteEncoder{&pdfDocEncoding} }
[ "func", "(", "f", "Font", ")", "Encoder", "(", ")", "TextEncoding", "{", "enc", ":=", "f", ".", "V", ".", "Key", "(", "\"Encoding\"", ")", "\n", "switch", "enc", ".", "Kind", "(", ")", "{", "case", "Name", ":", "switch", "enc", ".", "Name", "(", ")", "{", "case", "\"WinAnsiEncoding\"", ":", "return", "&", "byteEncoder", "{", "&", "winAnsiEncoding", "}", "\n", "case", "\"MacRomanEncoding\"", ":", "return", "&", "byteEncoder", "{", "&", "macRomanEncoding", "}", "\n", "case", "\"Identity-H\"", ":", "return", "&", "nopEncoder", "{", "}", "\n", "default", ":", "println", "(", "\"unknown encoding\"", ",", "enc", ".", "Name", "(", ")", ")", "\n", "return", "&", "nopEncoder", "{", "}", "\n", "}", "\n", "case", "Dict", ":", "return", "&", "dictEncoder", "{", "enc", ".", "Key", "(", "\"Differences\"", ")", "}", "\n", "case", "Null", ":", "default", ":", "println", "(", "\"unexpected encoding\"", ",", "enc", ".", "String", "(", ")", ")", "\n", "return", "&", "nopEncoder", "{", "}", "\n", "}", "\n", "toUnicode", ":=", "f", ".", "V", ".", "Key", "(", "\"ToUnicode\"", ")", "\n", "if", "toUnicode", ".", "Kind", "(", ")", "==", "Dict", "{", "m", ":=", "readCmap", "(", "toUnicode", ")", "\n", "if", "m", "==", "nil", "{", "return", "&", "nopEncoder", "{", "}", "\n", "}", "\n", "return", "m", "\n", "}", "\n", "return", "&", "byteEncoder", "{", "&", "pdfDocEncoding", "}", "\n", "}" ]
// Encoder returns the encoding between font code point sequences and UTF-8.
[ "Encoder", "returns", "the", "encoding", "between", "font", "code", "point", "sequences", "and", "UTF", "-", "8", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L136-L171
test
rsc/pdf
ps.go
Interpret
func Interpret(strm Value, do func(stk *Stack, op string)) { rd := strm.Reader() b := newBuffer(rd, 0) b.allowEOF = true b.allowObjptr = false b.allowStream = false var stk Stack var dicts []dict Reading: for { tok := b.readToken() if tok == io.EOF { break } if kw, ok := tok.(keyword); ok { switch kw { case "null", "[", "]", "<<", ">>": break default: for i := len(dicts) - 1; i >= 0; i-- { if v, ok := dicts[i][name(kw)]; ok { stk.Push(Value{nil, objptr{}, v}) continue Reading } } do(&stk, string(kw)) continue case "dict": stk.Pop() stk.Push(Value{nil, objptr{}, make(dict)}) continue case "currentdict": if len(dicts) == 0 { panic("no current dictionary") } stk.Push(Value{nil, objptr{}, dicts[len(dicts)-1]}) continue case "begin": d := stk.Pop() if d.Kind() != Dict { panic("cannot begin non-dict") } dicts = append(dicts, d.data.(dict)) continue case "end": if len(dicts) <= 0 { panic("mismatched begin/end") } dicts = dicts[:len(dicts)-1] continue case "def": if len(dicts) <= 0 { panic("def without open dict") } val := stk.Pop() key, ok := stk.Pop().data.(name) if !ok { panic("def of non-name") } dicts[len(dicts)-1][key] = val.data continue case "pop": stk.Pop() continue } } b.unreadToken(tok) obj := b.readObject() stk.Push(Value{nil, objptr{}, obj}) } }
go
func Interpret(strm Value, do func(stk *Stack, op string)) { rd := strm.Reader() b := newBuffer(rd, 0) b.allowEOF = true b.allowObjptr = false b.allowStream = false var stk Stack var dicts []dict Reading: for { tok := b.readToken() if tok == io.EOF { break } if kw, ok := tok.(keyword); ok { switch kw { case "null", "[", "]", "<<", ">>": break default: for i := len(dicts) - 1; i >= 0; i-- { if v, ok := dicts[i][name(kw)]; ok { stk.Push(Value{nil, objptr{}, v}) continue Reading } } do(&stk, string(kw)) continue case "dict": stk.Pop() stk.Push(Value{nil, objptr{}, make(dict)}) continue case "currentdict": if len(dicts) == 0 { panic("no current dictionary") } stk.Push(Value{nil, objptr{}, dicts[len(dicts)-1]}) continue case "begin": d := stk.Pop() if d.Kind() != Dict { panic("cannot begin non-dict") } dicts = append(dicts, d.data.(dict)) continue case "end": if len(dicts) <= 0 { panic("mismatched begin/end") } dicts = dicts[:len(dicts)-1] continue case "def": if len(dicts) <= 0 { panic("def without open dict") } val := stk.Pop() key, ok := stk.Pop().data.(name) if !ok { panic("def of non-name") } dicts[len(dicts)-1][key] = val.data continue case "pop": stk.Pop() continue } } b.unreadToken(tok) obj := b.readObject() stk.Push(Value{nil, objptr{}, obj}) } }
[ "func", "Interpret", "(", "strm", "Value", ",", "do", "func", "(", "stk", "*", "Stack", ",", "op", "string", ")", ")", "{", "rd", ":=", "strm", ".", "Reader", "(", ")", "\n", "b", ":=", "newBuffer", "(", "rd", ",", "0", ")", "\n", "b", ".", "allowEOF", "=", "true", "\n", "b", ".", "allowObjptr", "=", "false", "\n", "b", ".", "allowStream", "=", "false", "\n", "var", "stk", "Stack", "\n", "var", "dicts", "[", "]", "dict", "\n", "Reading", ":", "for", "{", "tok", ":=", "b", ".", "readToken", "(", ")", "\n", "if", "tok", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "kw", ",", "ok", ":=", "tok", ".", "(", "keyword", ")", ";", "ok", "{", "switch", "kw", "{", "case", "\"null\"", ",", "\"[\"", ",", "\"]\"", ",", "\"<<\"", ",", "\">>\"", ":", "break", "\n", "default", ":", "for", "i", ":=", "len", "(", "dicts", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "v", ",", "ok", ":=", "dicts", "[", "i", "]", "[", "name", "(", "kw", ")", "]", ";", "ok", "{", "stk", ".", "Push", "(", "Value", "{", "nil", ",", "objptr", "{", "}", ",", "v", "}", ")", "\n", "continue", "Reading", "\n", "}", "\n", "}", "\n", "do", "(", "&", "stk", ",", "string", "(", "kw", ")", ")", "\n", "continue", "\n", "case", "\"dict\"", ":", "stk", ".", "Pop", "(", ")", "\n", "stk", ".", "Push", "(", "Value", "{", "nil", ",", "objptr", "{", "}", ",", "make", "(", "dict", ")", "}", ")", "\n", "continue", "\n", "case", "\"currentdict\"", ":", "if", "len", "(", "dicts", ")", "==", "0", "{", "panic", "(", "\"no current dictionary\"", ")", "\n", "}", "\n", "stk", ".", "Push", "(", "Value", "{", "nil", ",", "objptr", "{", "}", ",", "dicts", "[", "len", "(", "dicts", ")", "-", "1", "]", "}", ")", "\n", "continue", "\n", "case", "\"begin\"", ":", "d", ":=", "stk", ".", "Pop", "(", ")", "\n", "if", "d", ".", "Kind", "(", ")", "!=", "Dict", "{", "panic", "(", "\"cannot begin non-dict\"", ")", "\n", "}", "\n", "dicts", "=", "append", "(", "dicts", ",", "d", ".", "data", ".", "(", "dict", ")", ")", "\n", "continue", "\n", "case", "\"end\"", ":", "if", "len", "(", "dicts", ")", "<=", "0", "{", "panic", "(", "\"mismatched begin/end\"", ")", "\n", "}", "\n", "dicts", "=", "dicts", "[", ":", "len", "(", "dicts", ")", "-", "1", "]", "\n", "continue", "\n", "case", "\"def\"", ":", "if", "len", "(", "dicts", ")", "<=", "0", "{", "panic", "(", "\"def without open dict\"", ")", "\n", "}", "\n", "val", ":=", "stk", ".", "Pop", "(", ")", "\n", "key", ",", "ok", ":=", "stk", ".", "Pop", "(", ")", ".", "data", ".", "(", "name", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"def of non-name\"", ")", "\n", "}", "\n", "dicts", "[", "len", "(", "dicts", ")", "-", "1", "]", "[", "key", "]", "=", "val", ".", "data", "\n", "continue", "\n", "case", "\"pop\"", ":", "stk", ".", "Pop", "(", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "b", ".", "unreadToken", "(", "tok", ")", "\n", "obj", ":=", "b", ".", "readObject", "(", ")", "\n", "stk", ".", "Push", "(", "Value", "{", "nil", ",", "objptr", "{", "}", ",", "obj", "}", ")", "\n", "}", "\n", "}" ]
// Interpret interprets the content in a stream as a basic PostScript program, // pushing values onto a stack and then calling the do function to execute // operators. The do function may push or pop values from the stack as needed // to implement op. // // Interpret handles the operators "dict", "currentdict", "begin", "end", "def", and "pop" itself. // // Interpret is not a full-blown PostScript interpreter. Its job is to handle the // very limited PostScript found in certain supporting file formats embedded // in PDF files, such as cmap files that describe the mapping from font code // points to Unicode code points. // // There is no support for executable blocks, among other limitations. //
[ "Interpret", "interprets", "the", "content", "in", "a", "stream", "as", "a", "basic", "PostScript", "program", "pushing", "values", "onto", "a", "stack", "and", "then", "calling", "the", "do", "function", "to", "execute", "operators", ".", "The", "do", "function", "may", "push", "or", "pop", "values", "from", "the", "stack", "as", "needed", "to", "implement", "op", ".", "Interpret", "handles", "the", "operators", "dict", "currentdict", "begin", "end", "def", "and", "pop", "itself", ".", "Interpret", "is", "not", "a", "full", "-", "blown", "PostScript", "interpreter", ".", "Its", "job", "is", "to", "handle", "the", "very", "limited", "PostScript", "found", "in", "certain", "supporting", "file", "formats", "embedded", "in", "PDF", "files", "such", "as", "cmap", "files", "that", "describe", "the", "mapping", "from", "font", "code", "points", "to", "Unicode", "code", "points", ".", "There", "is", "no", "support", "for", "executable", "blocks", "among", "other", "limitations", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/ps.go#L54-L124
test
rsc/pdf
read.go
Open
func Open(file string) (*Reader, error) { // TODO: Deal with closing file. f, err := os.Open(file) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { f.Close() return nil, err } return NewReader(f, fi.Size()) }
go
func Open(file string) (*Reader, error) { // TODO: Deal with closing file. f, err := os.Open(file) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { f.Close() return nil, err } return NewReader(f, fi.Size()) }
[ "func", "Open", "(", "file", "string", ")", "(", "*", "Reader", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fi", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "f", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewReader", "(", "f", ",", "fi", ".", "Size", "(", ")", ")", "\n", "}" ]
// Open opens a file for reading.
[ "Open", "opens", "a", "file", "for", "reading", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L101-L113
test
rsc/pdf
read.go
NewReader
func NewReader(f io.ReaderAt, size int64) (*Reader, error) { return NewReaderEncrypted(f, size, nil) }
go
func NewReader(f io.ReaderAt, size int64) (*Reader, error) { return NewReaderEncrypted(f, size, nil) }
[ "func", "NewReader", "(", "f", "io", ".", "ReaderAt", ",", "size", "int64", ")", "(", "*", "Reader", ",", "error", ")", "{", "return", "NewReaderEncrypted", "(", "f", ",", "size", ",", "nil", ")", "\n", "}" ]
// NewReader opens a file for reading, using the data in f with the given total size.
[ "NewReader", "opens", "a", "file", "for", "reading", "using", "the", "data", "in", "f", "with", "the", "given", "total", "size", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L116-L118
test
rsc/pdf
read.go
NewReaderEncrypted
func NewReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (*Reader, error) { buf := make([]byte, 10) f.ReadAt(buf, 0) if !bytes.HasPrefix(buf, []byte("%PDF-1.")) || buf[7] < '0' || buf[7] > '7' || buf[8] != '\r' && buf[8] != '\n' { return nil, fmt.Errorf("not a PDF file: invalid header") } end := size const endChunk = 100 buf = make([]byte, endChunk) f.ReadAt(buf, end-endChunk) for len(buf) > 0 && buf[len(buf)-1] == '\n' || buf[len(buf)-1] == '\r' { buf = buf[:len(buf)-1] } buf = bytes.TrimRight(buf, "\r\n\t ") if !bytes.HasSuffix(buf, []byte("%%EOF")) { return nil, fmt.Errorf("not a PDF file: missing %%%%EOF") } i := findLastLine(buf, "startxref") if i < 0 { return nil, fmt.Errorf("malformed PDF file: missing final startxref") } r := &Reader{ f: f, end: end, } pos := end - endChunk + int64(i) b := newBuffer(io.NewSectionReader(f, pos, end-pos), pos) if b.readToken() != keyword("startxref") { return nil, fmt.Errorf("malformed PDF file: missing startxref") } startxref, ok := b.readToken().(int64) if !ok { return nil, fmt.Errorf("malformed PDF file: startxref not followed by integer") } b = newBuffer(io.NewSectionReader(r.f, startxref, r.end-startxref), startxref) xref, trailerptr, trailer, err := readXref(r, b) if err != nil { return nil, err } r.xref = xref r.trailer = trailer r.trailerptr = trailerptr if trailer["Encrypt"] == nil { return r, nil } err = r.initEncrypt("") if err == nil { return r, nil } if pw == nil || err != ErrInvalidPassword { return nil, err } for { next := pw() if next == "" { break } if r.initEncrypt(next) == nil { return r, nil } } return nil, err }
go
func NewReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (*Reader, error) { buf := make([]byte, 10) f.ReadAt(buf, 0) if !bytes.HasPrefix(buf, []byte("%PDF-1.")) || buf[7] < '0' || buf[7] > '7' || buf[8] != '\r' && buf[8] != '\n' { return nil, fmt.Errorf("not a PDF file: invalid header") } end := size const endChunk = 100 buf = make([]byte, endChunk) f.ReadAt(buf, end-endChunk) for len(buf) > 0 && buf[len(buf)-1] == '\n' || buf[len(buf)-1] == '\r' { buf = buf[:len(buf)-1] } buf = bytes.TrimRight(buf, "\r\n\t ") if !bytes.HasSuffix(buf, []byte("%%EOF")) { return nil, fmt.Errorf("not a PDF file: missing %%%%EOF") } i := findLastLine(buf, "startxref") if i < 0 { return nil, fmt.Errorf("malformed PDF file: missing final startxref") } r := &Reader{ f: f, end: end, } pos := end - endChunk + int64(i) b := newBuffer(io.NewSectionReader(f, pos, end-pos), pos) if b.readToken() != keyword("startxref") { return nil, fmt.Errorf("malformed PDF file: missing startxref") } startxref, ok := b.readToken().(int64) if !ok { return nil, fmt.Errorf("malformed PDF file: startxref not followed by integer") } b = newBuffer(io.NewSectionReader(r.f, startxref, r.end-startxref), startxref) xref, trailerptr, trailer, err := readXref(r, b) if err != nil { return nil, err } r.xref = xref r.trailer = trailer r.trailerptr = trailerptr if trailer["Encrypt"] == nil { return r, nil } err = r.initEncrypt("") if err == nil { return r, nil } if pw == nil || err != ErrInvalidPassword { return nil, err } for { next := pw() if next == "" { break } if r.initEncrypt(next) == nil { return r, nil } } return nil, err }
[ "func", "NewReaderEncrypted", "(", "f", "io", ".", "ReaderAt", ",", "size", "int64", ",", "pw", "func", "(", ")", "string", ")", "(", "*", "Reader", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "10", ")", "\n", "f", ".", "ReadAt", "(", "buf", ",", "0", ")", "\n", "if", "!", "bytes", ".", "HasPrefix", "(", "buf", ",", "[", "]", "byte", "(", "\"%PDF-1.\"", ")", ")", "||", "buf", "[", "7", "]", "<", "'0'", "||", "buf", "[", "7", "]", ">", "'7'", "||", "buf", "[", "8", "]", "!=", "'\\r'", "&&", "buf", "[", "8", "]", "!=", "'\\n'", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"not a PDF file: invalid header\"", ")", "\n", "}", "\n", "end", ":=", "size", "\n", "const", "endChunk", "=", "100", "\n", "buf", "=", "make", "(", "[", "]", "byte", ",", "endChunk", ")", "\n", "f", ".", "ReadAt", "(", "buf", ",", "end", "-", "endChunk", ")", "\n", "for", "len", "(", "buf", ")", ">", "0", "&&", "buf", "[", "len", "(", "buf", ")", "-", "1", "]", "==", "'\\n'", "||", "buf", "[", "len", "(", "buf", ")", "-", "1", "]", "==", "'\\r'", "{", "buf", "=", "buf", "[", ":", "len", "(", "buf", ")", "-", "1", "]", "\n", "}", "\n", "buf", "=", "bytes", ".", "TrimRight", "(", "buf", ",", "\"\\r\\n\\t \"", ")", "\n", "\\r", "\n", "\\n", "\n", "\\t", "\n", "if", "!", "bytes", ".", "HasSuffix", "(", "buf", ",", "[", "]", "byte", "(", "\"%%EOF\"", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"not a PDF file: missing %%%%EOF\"", ")", "\n", "}", "\n", "i", ":=", "findLastLine", "(", "buf", ",", "\"startxref\"", ")", "\n", "if", "i", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"malformed PDF file: missing final startxref\"", ")", "\n", "}", "\n", "r", ":=", "&", "Reader", "{", "f", ":", "f", ",", "end", ":", "end", ",", "}", "\n", "pos", ":=", "end", "-", "endChunk", "+", "int64", "(", "i", ")", "\n", "b", ":=", "newBuffer", "(", "io", ".", "NewSectionReader", "(", "f", ",", "pos", ",", "end", "-", "pos", ")", ",", "pos", ")", "\n", "if", "b", ".", "readToken", "(", ")", "!=", "keyword", "(", "\"startxref\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"malformed PDF file: missing startxref\"", ")", "\n", "}", "\n", "startxref", ",", "ok", ":=", "b", ".", "readToken", "(", ")", ".", "(", "int64", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"malformed PDF file: startxref not followed by integer\"", ")", "\n", "}", "\n", "b", "=", "newBuffer", "(", "io", ".", "NewSectionReader", "(", "r", ".", "f", ",", "startxref", ",", "r", ".", "end", "-", "startxref", ")", ",", "startxref", ")", "\n", "xref", ",", "trailerptr", ",", "trailer", ",", "err", ":=", "readXref", "(", "r", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "r", ".", "xref", "=", "xref", "\n", "r", ".", "trailer", "=", "trailer", "\n", "r", ".", "trailerptr", "=", "trailerptr", "\n", "if", "trailer", "[", "\"Encrypt\"", "]", "==", "nil", "{", "return", "r", ",", "nil", "\n", "}", "\n", "err", "=", "r", ".", "initEncrypt", "(", "\"\"", ")", "\n", "if", "err", "==", "nil", "{", "return", "r", ",", "nil", "\n", "}", "\n", "}" ]
// NewReaderEncrypted opens a file for reading, using the data in f with the given total size. // If the PDF is encrypted, NewReaderEncrypted calls pw repeatedly to obtain passwords // to try. If pw returns the empty string, NewReaderEncrypted stops trying to decrypt // the file and returns an error.
[ "NewReaderEncrypted", "opens", "a", "file", "for", "reading", "using", "the", "data", "in", "f", "with", "the", "given", "total", "size", ".", "If", "the", "PDF", "is", "encrypted", "NewReaderEncrypted", "calls", "pw", "repeatedly", "to", "obtain", "passwords", "to", "try", ".", "If", "pw", "returns", "the", "empty", "string", "NewReaderEncrypted", "stops", "trying", "to", "decrypt", "the", "file", "and", "returns", "an", "error", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L124-L187
test
rsc/pdf
read.go
Trailer
func (r *Reader) Trailer() Value { return Value{r, r.trailerptr, r.trailer} }
go
func (r *Reader) Trailer() Value { return Value{r, r.trailerptr, r.trailer} }
[ "func", "(", "r", "*", "Reader", ")", "Trailer", "(", ")", "Value", "{", "return", "Value", "{", "r", ",", "r", ".", "trailerptr", ",", "r", ".", "trailer", "}", "\n", "}" ]
// Trailer returns the file's Trailer value.
[ "Trailer", "returns", "the", "file", "s", "Trailer", "value", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L190-L192
test
rsc/pdf
read.go
Kind
func (v Value) Kind() ValueKind { switch v.data.(type) { default: return Null case bool: return Bool case int64: return Integer case float64: return Real case string: return String case name: return Name case dict: return Dict case array: return Array case stream: return Stream } }
go
func (v Value) Kind() ValueKind { switch v.data.(type) { default: return Null case bool: return Bool case int64: return Integer case float64: return Real case string: return String case name: return Name case dict: return Dict case array: return Array case stream: return Stream } }
[ "func", "(", "v", "Value", ")", "Kind", "(", ")", "ValueKind", "{", "switch", "v", ".", "data", ".", "(", "type", ")", "{", "default", ":", "return", "Null", "\n", "case", "bool", ":", "return", "Bool", "\n", "case", "int64", ":", "return", "Integer", "\n", "case", "float64", ":", "return", "Real", "\n", "case", "string", ":", "return", "String", "\n", "case", "name", ":", "return", "Name", "\n", "case", "dict", ":", "return", "Dict", "\n", "case", "array", ":", "return", "Array", "\n", "case", "stream", ":", "return", "Stream", "\n", "}", "\n", "}" ]
// Kind reports the kind of value underlying v.
[ "Kind", "reports", "the", "kind", "of", "value", "underlying", "v", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L471-L492
test
rsc/pdf
lex.go
newBuffer
func newBuffer(r io.Reader, offset int64) *buffer { return &buffer{ r: r, offset: offset, buf: make([]byte, 0, 4096), allowObjptr: true, allowStream: true, } }
go
func newBuffer(r io.Reader, offset int64) *buffer { return &buffer{ r: r, offset: offset, buf: make([]byte, 0, 4096), allowObjptr: true, allowStream: true, } }
[ "func", "newBuffer", "(", "r", "io", ".", "Reader", ",", "offset", "int64", ")", "*", "buffer", "{", "return", "&", "buffer", "{", "r", ":", "r", ",", "offset", ":", "offset", ",", "buf", ":", "make", "(", "[", "]", "byte", ",", "0", ",", "4096", ")", ",", "allowObjptr", ":", "true", ",", "allowStream", ":", "true", ",", "}", "\n", "}" ]
// newBuffer returns a new buffer reading from r at the given offset.
[ "newBuffer", "returns", "a", "new", "buffer", "reading", "from", "r", "at", "the", "given", "offset", "." ]
c47d69cf462f804ff58ca63c61a8fb2aed76587e
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/lex.go#L52-L60
test
go-bongo/bongo
resultSet.go
Paginate
func (r *ResultSet) Paginate(perPage, page int) (*PaginationInfo, error) { info := new(PaginationInfo) // Get count on a different session to avoid blocking sess := r.Collection.Connection.Session.Copy() count, err := sess.DB(r.Collection.Database).C(r.Collection.Name).Find(r.Params).Count() sess.Close() if err != nil { return info, err } // Calculate how many pages totalPages := int(math.Ceil(float64(count) / float64(perPage))) if page < 1 { page = 1 } else if page > totalPages { page = totalPages } skip := (page - 1) * perPage r.Query.Skip(skip).Limit(perPage) info.TotalPages = totalPages info.PerPage = perPage info.Current = page info.TotalRecords = count if info.Current < info.TotalPages { info.RecordsOnPage = info.PerPage } else { info.RecordsOnPage = int(math.Mod(float64(count), float64(perPage))) if info.RecordsOnPage == 0 && count > 0 { info.RecordsOnPage = perPage } } return info, nil }
go
func (r *ResultSet) Paginate(perPage, page int) (*PaginationInfo, error) { info := new(PaginationInfo) // Get count on a different session to avoid blocking sess := r.Collection.Connection.Session.Copy() count, err := sess.DB(r.Collection.Database).C(r.Collection.Name).Find(r.Params).Count() sess.Close() if err != nil { return info, err } // Calculate how many pages totalPages := int(math.Ceil(float64(count) / float64(perPage))) if page < 1 { page = 1 } else if page > totalPages { page = totalPages } skip := (page - 1) * perPage r.Query.Skip(skip).Limit(perPage) info.TotalPages = totalPages info.PerPage = perPage info.Current = page info.TotalRecords = count if info.Current < info.TotalPages { info.RecordsOnPage = info.PerPage } else { info.RecordsOnPage = int(math.Mod(float64(count), float64(perPage))) if info.RecordsOnPage == 0 && count > 0 { info.RecordsOnPage = perPage } } return info, nil }
[ "func", "(", "r", "*", "ResultSet", ")", "Paginate", "(", "perPage", ",", "page", "int", ")", "(", "*", "PaginationInfo", ",", "error", ")", "{", "info", ":=", "new", "(", "PaginationInfo", ")", "\n", "sess", ":=", "r", ".", "Collection", ".", "Connection", ".", "Session", ".", "Copy", "(", ")", "\n", "count", ",", "err", ":=", "sess", ".", "DB", "(", "r", ".", "Collection", ".", "Database", ")", ".", "C", "(", "r", ".", "Collection", ".", "Name", ")", ".", "Find", "(", "r", ".", "Params", ")", ".", "Count", "(", ")", "\n", "sess", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "info", ",", "err", "\n", "}", "\n", "totalPages", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "count", ")", "/", "float64", "(", "perPage", ")", ")", ")", "\n", "if", "page", "<", "1", "{", "page", "=", "1", "\n", "}", "else", "if", "page", ">", "totalPages", "{", "page", "=", "totalPages", "\n", "}", "\n", "skip", ":=", "(", "page", "-", "1", ")", "*", "perPage", "\n", "r", ".", "Query", ".", "Skip", "(", "skip", ")", ".", "Limit", "(", "perPage", ")", "\n", "info", ".", "TotalPages", "=", "totalPages", "\n", "info", ".", "PerPage", "=", "perPage", "\n", "info", ".", "Current", "=", "page", "\n", "info", ".", "TotalRecords", "=", "count", "\n", "if", "info", ".", "Current", "<", "info", ".", "TotalPages", "{", "info", ".", "RecordsOnPage", "=", "info", ".", "PerPage", "\n", "}", "else", "{", "info", ".", "RecordsOnPage", "=", "int", "(", "math", ".", "Mod", "(", "float64", "(", "count", ")", ",", "float64", "(", "perPage", ")", ")", ")", "\n", "if", "info", ".", "RecordsOnPage", "==", "0", "&&", "count", ">", "0", "{", "info", ".", "RecordsOnPage", "=", "perPage", "\n", "}", "\n", "}", "\n", "return", "info", ",", "nil", "\n", "}" ]
// Set skip + limit on the current query and generates a PaginationInfo struct with info for your front end
[ "Set", "skip", "+", "limit", "on", "the", "current", "query", "and", "generates", "a", "PaginationInfo", "struct", "with", "info", "for", "your", "front", "end" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/resultSet.go#L70-L115
test
go-bongo/bongo
cascade.go
CascadeDelete
func CascadeDelete(collection *Collection, doc interface{}) { // Find out which properties to cascade if conv, ok := doc.(interface { GetCascade(*Collection) []*CascadeConfig }); ok { toCascade := conv.GetCascade(collection) // Get the ID for _, conf := range toCascade { if len(conf.ReferenceQuery) == 0 { id, err := reflections.GetField(doc, "Id") if err != nil { panic(err) } conf.ReferenceQuery = []*ReferenceField{&ReferenceField{"_id", id}} } cascadeDeleteWithConfig(conf) } } }
go
func CascadeDelete(collection *Collection, doc interface{}) { // Find out which properties to cascade if conv, ok := doc.(interface { GetCascade(*Collection) []*CascadeConfig }); ok { toCascade := conv.GetCascade(collection) // Get the ID for _, conf := range toCascade { if len(conf.ReferenceQuery) == 0 { id, err := reflections.GetField(doc, "Id") if err != nil { panic(err) } conf.ReferenceQuery = []*ReferenceField{&ReferenceField{"_id", id}} } cascadeDeleteWithConfig(conf) } } }
[ "func", "CascadeDelete", "(", "collection", "*", "Collection", ",", "doc", "interface", "{", "}", ")", "{", "if", "conv", ",", "ok", ":=", "doc", ".", "(", "interface", "{", "GetCascade", "(", "*", "Collection", ")", "[", "]", "*", "CascadeConfig", "\n", "}", ")", ";", "ok", "{", "toCascade", ":=", "conv", ".", "GetCascade", "(", "collection", ")", "\n", "for", "_", ",", "conf", ":=", "range", "toCascade", "{", "if", "len", "(", "conf", ".", "ReferenceQuery", ")", "==", "0", "{", "id", ",", "err", ":=", "reflections", ".", "GetField", "(", "doc", ",", "\"Id\"", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "conf", ".", "ReferenceQuery", "=", "[", "]", "*", "ReferenceField", "{", "&", "ReferenceField", "{", "\"_id\"", ",", "id", "}", "}", "\n", "}", "\n", "cascadeDeleteWithConfig", "(", "conf", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Deletes references to a document from its related documents
[ "Deletes", "references", "to", "a", "document", "from", "its", "related", "documents" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L95-L118
test
go-bongo/bongo
cascade.go
cascadeDeleteWithConfig
func cascadeDeleteWithConfig(conf *CascadeConfig) (*mgo.ChangeInfo, error) { switch conf.RelType { case REL_ONE: update := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update["$set"][p] = nil } } return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update["$pull"][conf.ThroughProp] = q return conf.Collection.Collection().UpdateAll(conf.Query, update) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
go
func cascadeDeleteWithConfig(conf *CascadeConfig) (*mgo.ChangeInfo, error) { switch conf.RelType { case REL_ONE: update := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update["$set"][p] = nil } } return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update["$pull"][conf.ThroughProp] = q return conf.Collection.Collection().UpdateAll(conf.Query, update) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
[ "func", "cascadeDeleteWithConfig", "(", "conf", "*", "CascadeConfig", ")", "(", "*", "mgo", ".", "ChangeInfo", ",", "error", ")", "{", "switch", "conf", ".", "RelType", "{", "case", "REL_ONE", ":", "update", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "\"$set\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "}", "\n", "if", "len", "(", "conf", ".", "ThroughProp", ")", ">", "0", "{", "update", "[", "\"$set\"", "]", "[", "conf", ".", "ThroughProp", "]", "=", "nil", "\n", "}", "else", "{", "for", "_", ",", "p", ":=", "range", "conf", ".", "Properties", "{", "update", "[", "\"$set\"", "]", "[", "p", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "return", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "Query", ",", "update", ")", "\n", "case", "REL_MANY", ":", "update", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "\"$pull\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "}", "\n", "q", ":=", "bson", ".", "M", "{", "}", "\n", "for", "_", ",", "f", ":=", "range", "conf", ".", "ReferenceQuery", "{", "q", "[", "f", ".", "BsonName", "]", "=", "f", ".", "Value", "\n", "}", "\n", "update", "[", "\"$pull\"", "]", "[", "conf", ".", "ThroughProp", "]", "=", "q", "\n", "return", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "Query", ",", "update", ")", "\n", "}", "\n", "return", "&", "mgo", ".", "ChangeInfo", "{", "}", ",", "errors", ".", "New", "(", "\"Invalid relation type\"", ")", "\n", "}" ]
// Runs a cascaded delete operation with one configuration
[ "Runs", "a", "cascaded", "delete", "operation", "with", "one", "configuration" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L121-L152
test
go-bongo/bongo
cascade.go
cascadeSaveWithConfig
func cascadeSaveWithConfig(conf *CascadeConfig, doc Document) (*mgo.ChangeInfo, error) { // Create a new map with just the props to cascade data := conf.Data switch conf.RelType { case REL_ONE: if len(conf.OldQuery) > 0 { update1 := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update1["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update1["$set"][p] = nil } } ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } update := make(map[string]interface{}) if len(conf.ThroughProp) > 0 { m := bson.M{} m[conf.ThroughProp] = data update["$set"] = m } else { update["$set"] = data } // Just update return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update1 := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update1["$pull"][conf.ThroughProp] = q if len(conf.OldQuery) > 0 { ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } // Remove self from current relations, so we can replace it conf.Collection.Collection().UpdateAll(conf.Query, update1) update2 := map[string]map[string]interface{}{ "$push": map[string]interface{}{}, } update2["$push"][conf.ThroughProp] = data return conf.Collection.Collection().UpdateAll(conf.Query, update2) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
go
func cascadeSaveWithConfig(conf *CascadeConfig, doc Document) (*mgo.ChangeInfo, error) { // Create a new map with just the props to cascade data := conf.Data switch conf.RelType { case REL_ONE: if len(conf.OldQuery) > 0 { update1 := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update1["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update1["$set"][p] = nil } } ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } update := make(map[string]interface{}) if len(conf.ThroughProp) > 0 { m := bson.M{} m[conf.ThroughProp] = data update["$set"] = m } else { update["$set"] = data } // Just update return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update1 := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update1["$pull"][conf.ThroughProp] = q if len(conf.OldQuery) > 0 { ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } // Remove self from current relations, so we can replace it conf.Collection.Collection().UpdateAll(conf.Query, update1) update2 := map[string]map[string]interface{}{ "$push": map[string]interface{}{}, } update2["$push"][conf.ThroughProp] = data return conf.Collection.Collection().UpdateAll(conf.Query, update2) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
[ "func", "cascadeSaveWithConfig", "(", "conf", "*", "CascadeConfig", ",", "doc", "Document", ")", "(", "*", "mgo", ".", "ChangeInfo", ",", "error", ")", "{", "data", ":=", "conf", ".", "Data", "\n", "switch", "conf", ".", "RelType", "{", "case", "REL_ONE", ":", "if", "len", "(", "conf", ".", "OldQuery", ")", ">", "0", "{", "update1", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "\"$set\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "}", "\n", "if", "len", "(", "conf", ".", "ThroughProp", ")", ">", "0", "{", "update1", "[", "\"$set\"", "]", "[", "conf", ".", "ThroughProp", "]", "=", "nil", "\n", "}", "else", "{", "for", "_", ",", "p", ":=", "range", "conf", ".", "Properties", "{", "update1", "[", "\"$set\"", "]", "[", "p", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "ret", ",", "err", ":=", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "OldQuery", ",", "update1", ")", "\n", "if", "conf", ".", "RemoveOnly", "{", "return", "ret", ",", "err", "\n", "}", "\n", "}", "\n", "update", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "len", "(", "conf", ".", "ThroughProp", ")", ">", "0", "{", "m", ":=", "bson", ".", "M", "{", "}", "\n", "m", "[", "conf", ".", "ThroughProp", "]", "=", "data", "\n", "update", "[", "\"$set\"", "]", "=", "m", "\n", "}", "else", "{", "update", "[", "\"$set\"", "]", "=", "data", "\n", "}", "\n", "return", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "Query", ",", "update", ")", "\n", "case", "REL_MANY", ":", "update1", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "\"$pull\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "}", "\n", "q", ":=", "bson", ".", "M", "{", "}", "\n", "for", "_", ",", "f", ":=", "range", "conf", ".", "ReferenceQuery", "{", "q", "[", "f", ".", "BsonName", "]", "=", "f", ".", "Value", "\n", "}", "\n", "update1", "[", "\"$pull\"", "]", "[", "conf", ".", "ThroughProp", "]", "=", "q", "\n", "if", "len", "(", "conf", ".", "OldQuery", ")", ">", "0", "{", "ret", ",", "err", ":=", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "OldQuery", ",", "update1", ")", "\n", "if", "conf", ".", "RemoveOnly", "{", "return", "ret", ",", "err", "\n", "}", "\n", "}", "\n", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "Query", ",", "update1", ")", "\n", "update2", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "\"$push\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "}", "\n", "update2", "[", "\"$push\"", "]", "[", "conf", ".", "ThroughProp", "]", "=", "data", "\n", "return", "conf", ".", "Collection", ".", "Collection", "(", ")", ".", "UpdateAll", "(", "conf", ".", "Query", ",", "update2", ")", "\n", "}", "\n", "return", "&", "mgo", ".", "ChangeInfo", "{", "}", ",", "errors", ".", "New", "(", "\"Invalid relation type\"", ")", "\n", "}" ]
// Runs a cascaded save operation with one configuration
[ "Runs", "a", "cascaded", "save", "operation", "with", "one", "configuration" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L155-L228
test
go-bongo/bongo
cascade.go
MapFromCascadeProperties
func MapFromCascadeProperties(properties []string, doc Document) map[string]interface{} { data := make(map[string]interface{}) for _, prop := range properties { split := strings.Split(prop, ".") if len(split) == 1 { data[prop], _ = dotaccess.Get(doc, prop) } else { actualProp := split[len(split)-1] split := append([]string{}, split[:len(split)-1]...) curData := data for _, s := range split { if _, ok := curData[s]; ok { if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } else { curData[s] = make(map[string]interface{}) if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } } val, _ := dotaccess.Get(doc, prop) // if bsonId, ok := val.(bson.ObjectId); ok { // if !bsonId.Valid() { // curData[actualProp] = "" // continue // } // } curData[actualProp] = val } } return data }
go
func MapFromCascadeProperties(properties []string, doc Document) map[string]interface{} { data := make(map[string]interface{}) for _, prop := range properties { split := strings.Split(prop, ".") if len(split) == 1 { data[prop], _ = dotaccess.Get(doc, prop) } else { actualProp := split[len(split)-1] split := append([]string{}, split[:len(split)-1]...) curData := data for _, s := range split { if _, ok := curData[s]; ok { if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } else { curData[s] = make(map[string]interface{}) if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } } val, _ := dotaccess.Get(doc, prop) // if bsonId, ok := val.(bson.ObjectId); ok { // if !bsonId.Valid() { // curData[actualProp] = "" // continue // } // } curData[actualProp] = val } } return data }
[ "func", "MapFromCascadeProperties", "(", "properties", "[", "]", "string", ",", "doc", "Document", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "data", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "_", ",", "prop", ":=", "range", "properties", "{", "split", ":=", "strings", ".", "Split", "(", "prop", ",", "\".\"", ")", "\n", "if", "len", "(", "split", ")", "==", "1", "{", "data", "[", "prop", "]", ",", "_", "=", "dotaccess", ".", "Get", "(", "doc", ",", "prop", ")", "\n", "}", "else", "{", "actualProp", ":=", "split", "[", "len", "(", "split", ")", "-", "1", "]", "\n", "split", ":=", "append", "(", "[", "]", "string", "{", "}", ",", "split", "[", ":", "len", "(", "split", ")", "-", "1", "]", "...", ")", "\n", "curData", ":=", "data", "\n", "for", "_", ",", "s", ":=", "range", "split", "{", "if", "_", ",", "ok", ":=", "curData", "[", "s", "]", ";", "ok", "{", "if", "mapped", ",", "ok", ":=", "curData", "[", "s", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "curData", "=", "mapped", "\n", "}", "else", "{", "panic", "(", "\"Cannot access non-map property via dot notation\"", ")", "\n", "}", "\n", "}", "else", "{", "curData", "[", "s", "]", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "mapped", ",", "ok", ":=", "curData", "[", "s", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "curData", "=", "mapped", "\n", "}", "else", "{", "panic", "(", "\"Cannot access non-map property via dot notation\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "val", ",", "_", ":=", "dotaccess", ".", "Get", "(", "doc", ",", "prop", ")", "\n", "curData", "[", "actualProp", "]", "=", "val", "\n", "}", "\n", "}", "\n", "return", "data", "\n", "}" ]
// If you need to, you can use this to construct the data map that will be cascaded down to // related documents. Doing this is not recommended unless the cascaded fields are dynamic.
[ "If", "you", "need", "to", "you", "can", "use", "this", "to", "construct", "the", "data", "map", "that", "will", "be", "cascaded", "down", "to", "related", "documents", ".", "Doing", "this", "is", "not", "recommended", "unless", "the", "cascaded", "fields", "are", "dynamic", "." ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L232-L275
test
go-bongo/bongo
main.go
Connect
func (m *Connection) Connect() (err error) { defer func() { if r := recover(); r != nil { // panic(r) // return if e, ok := r.(error); ok { err = e } else if e, ok := r.(string); ok { err = errors.New(e) } else { err = errors.New(fmt.Sprint(r)) } } }() if m.Config.DialInfo == nil { if m.Config.DialInfo, err = mgo.ParseURL(m.Config.ConnectionString); err != nil { panic(fmt.Sprintf("cannot parse given URI %s due to error: %s", m.Config.ConnectionString, err.Error())) } } session, err := mgo.DialWithInfo(m.Config.DialInfo) if err != nil { return err } m.Session = session m.Session.SetMode(mgo.Monotonic, true) return nil }
go
func (m *Connection) Connect() (err error) { defer func() { if r := recover(); r != nil { // panic(r) // return if e, ok := r.(error); ok { err = e } else if e, ok := r.(string); ok { err = errors.New(e) } else { err = errors.New(fmt.Sprint(r)) } } }() if m.Config.DialInfo == nil { if m.Config.DialInfo, err = mgo.ParseURL(m.Config.ConnectionString); err != nil { panic(fmt.Sprintf("cannot parse given URI %s due to error: %s", m.Config.ConnectionString, err.Error())) } } session, err := mgo.DialWithInfo(m.Config.DialInfo) if err != nil { return err } m.Session = session m.Session.SetMode(mgo.Monotonic, true) return nil }
[ "func", "(", "m", "*", "Connection", ")", "Connect", "(", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "if", "e", ",", "ok", ":=", "r", ".", "(", "error", ")", ";", "ok", "{", "err", "=", "e", "\n", "}", "else", "if", "e", ",", "ok", ":=", "r", ".", "(", "string", ")", ";", "ok", "{", "err", "=", "errors", ".", "New", "(", "e", ")", "\n", "}", "else", "{", "err", "=", "errors", ".", "New", "(", "fmt", ".", "Sprint", "(", "r", ")", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "m", ".", "Config", ".", "DialInfo", "==", "nil", "{", "if", "m", ".", "Config", ".", "DialInfo", ",", "err", "=", "mgo", ".", "ParseURL", "(", "m", ".", "Config", ".", "ConnectionString", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"cannot parse given URI %s due to error: %s\"", ",", "m", ".", "Config", ".", "ConnectionString", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "session", ",", "err", ":=", "mgo", ".", "DialWithInfo", "(", "m", ".", "Config", ".", "DialInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "m", ".", "Session", "=", "session", "\n", "m", ".", "Session", ".", "SetMode", "(", "mgo", ".", "Monotonic", ",", "true", ")", "\n", "return", "nil", "\n", "}" ]
// Connect to the database using the provided config
[ "Connect", "to", "the", "database", "using", "the", "provided", "config" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/main.go#L39-L71
test
go-bongo/bongo
utils.go
lowerInitial
func lowerInitial(str string) string { for i, v := range str { return string(unicode.ToLower(v)) + str[i+1:] } return "" }
go
func lowerInitial(str string) string { for i, v := range str { return string(unicode.ToLower(v)) + str[i+1:] } return "" }
[ "func", "lowerInitial", "(", "str", "string", ")", "string", "{", "for", "i", ",", "v", ":=", "range", "str", "{", "return", "string", "(", "unicode", ".", "ToLower", "(", "v", ")", ")", "+", "str", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
//Lower cases first char of string
[ "Lower", "cases", "first", "char", "of", "string" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/utils.go#L10-L15
test
go-bongo/bongo
collection.go
Find
func (c *Collection) Find(query interface{}) *ResultSet { col := c.Collection() // Count for testing q := col.Find(query) resultset := new(ResultSet) resultset.Query = q resultset.Params = query resultset.Collection = c return resultset }
go
func (c *Collection) Find(query interface{}) *ResultSet { col := c.Collection() // Count for testing q := col.Find(query) resultset := new(ResultSet) resultset.Query = q resultset.Params = query resultset.Collection = c return resultset }
[ "func", "(", "c", "*", "Collection", ")", "Find", "(", "query", "interface", "{", "}", ")", "*", "ResultSet", "{", "col", ":=", "c", ".", "Collection", "(", ")", "\n", "q", ":=", "col", ".", "Find", "(", "query", ")", "\n", "resultset", ":=", "new", "(", "ResultSet", ")", "\n", "resultset", ".", "Query", "=", "q", "\n", "resultset", ".", "Params", "=", "query", "\n", "resultset", ".", "Collection", "=", "c", "\n", "return", "resultset", "\n", "}" ]
// This doesn't actually do any DB interaction, it just creates the result set so we can // start looping through on the iterator
[ "This", "doesn", "t", "actually", "do", "any", "DB", "interaction", "it", "just", "creates", "the", "result", "set", "so", "we", "can", "start", "looping", "through", "on", "the", "iterator" ]
761759e31d8fed917377aa7085db01d218ce50d8
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/collection.go#L212-L225
test
mattn/go-xmpp
xmpp_information_query.go
RawInformationQuery
func (c *Client) RawInformationQuery(from, to, id, iqType, requestNamespace, body string) (string, error) { const xmlIQ = "<iq from='%s' to='%s' id='%s' type='%s'><query xmlns='%s'>%s</query></iq>" _, err := fmt.Fprintf(c.conn, xmlIQ, xmlEscape(from), xmlEscape(to), id, iqType, requestNamespace, body) return id, err }
go
func (c *Client) RawInformationQuery(from, to, id, iqType, requestNamespace, body string) (string, error) { const xmlIQ = "<iq from='%s' to='%s' id='%s' type='%s'><query xmlns='%s'>%s</query></iq>" _, err := fmt.Fprintf(c.conn, xmlIQ, xmlEscape(from), xmlEscape(to), id, iqType, requestNamespace, body) return id, err }
[ "func", "(", "c", "*", "Client", ")", "RawInformationQuery", "(", "from", ",", "to", ",", "id", ",", "iqType", ",", "requestNamespace", ",", "body", "string", ")", "(", "string", ",", "error", ")", "{", "const", "xmlIQ", "=", "\"<iq from='%s' to='%s' id='%s' type='%s'><query xmlns='%s'>%s</query></iq>\"", "\n", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "xmlIQ", ",", "xmlEscape", "(", "from", ")", ",", "xmlEscape", "(", "to", ")", ",", "id", ",", "iqType", ",", "requestNamespace", ",", "body", ")", "\n", "return", "id", ",", "err", "\n", "}" ]
// RawInformationQuery sends an information query request to the server.
[ "RawInformationQuery", "sends", "an", "information", "query", "request", "to", "the", "server", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp_information_query.go#L20-L24
test
mattn/go-xmpp
xmpp.go
NewClient
func (o Options) NewClient() (*Client, error) { host := o.Host c, err := connect(host, o.User, o.Password) if err != nil { return nil, err } if strings.LastIndex(o.Host, ":") > 0 { host = host[:strings.LastIndex(o.Host, ":")] } client := new(Client) if o.NoTLS { client.conn = c } else { var tlsconn *tls.Conn if o.TLSConfig != nil { tlsconn = tls.Client(c, o.TLSConfig) } else { DefaultConfig.ServerName = host newconfig := DefaultConfig newconfig.ServerName = host tlsconn = tls.Client(c, &newconfig) } if err = tlsconn.Handshake(); err != nil { return nil, err } insecureSkipVerify := DefaultConfig.InsecureSkipVerify if o.TLSConfig != nil { insecureSkipVerify = o.TLSConfig.InsecureSkipVerify } if !insecureSkipVerify { if err = tlsconn.VerifyHostname(host); err != nil { return nil, err } } client.conn = tlsconn } if err := client.init(&o); err != nil { client.Close() return nil, err } return client, nil }
go
func (o Options) NewClient() (*Client, error) { host := o.Host c, err := connect(host, o.User, o.Password) if err != nil { return nil, err } if strings.LastIndex(o.Host, ":") > 0 { host = host[:strings.LastIndex(o.Host, ":")] } client := new(Client) if o.NoTLS { client.conn = c } else { var tlsconn *tls.Conn if o.TLSConfig != nil { tlsconn = tls.Client(c, o.TLSConfig) } else { DefaultConfig.ServerName = host newconfig := DefaultConfig newconfig.ServerName = host tlsconn = tls.Client(c, &newconfig) } if err = tlsconn.Handshake(); err != nil { return nil, err } insecureSkipVerify := DefaultConfig.InsecureSkipVerify if o.TLSConfig != nil { insecureSkipVerify = o.TLSConfig.InsecureSkipVerify } if !insecureSkipVerify { if err = tlsconn.VerifyHostname(host); err != nil { return nil, err } } client.conn = tlsconn } if err := client.init(&o); err != nil { client.Close() return nil, err } return client, nil }
[ "func", "(", "o", "Options", ")", "NewClient", "(", ")", "(", "*", "Client", ",", "error", ")", "{", "host", ":=", "o", ".", "Host", "\n", "c", ",", "err", ":=", "connect", "(", "host", ",", "o", ".", "User", ",", "o", ".", "Password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "strings", ".", "LastIndex", "(", "o", ".", "Host", ",", "\":\"", ")", ">", "0", "{", "host", "=", "host", "[", ":", "strings", ".", "LastIndex", "(", "o", ".", "Host", ",", "\":\"", ")", "]", "\n", "}", "\n", "client", ":=", "new", "(", "Client", ")", "\n", "if", "o", ".", "NoTLS", "{", "client", ".", "conn", "=", "c", "\n", "}", "else", "{", "var", "tlsconn", "*", "tls", ".", "Conn", "\n", "if", "o", ".", "TLSConfig", "!=", "nil", "{", "tlsconn", "=", "tls", ".", "Client", "(", "c", ",", "o", ".", "TLSConfig", ")", "\n", "}", "else", "{", "DefaultConfig", ".", "ServerName", "=", "host", "\n", "newconfig", ":=", "DefaultConfig", "\n", "newconfig", ".", "ServerName", "=", "host", "\n", "tlsconn", "=", "tls", ".", "Client", "(", "c", ",", "&", "newconfig", ")", "\n", "}", "\n", "if", "err", "=", "tlsconn", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "insecureSkipVerify", ":=", "DefaultConfig", ".", "InsecureSkipVerify", "\n", "if", "o", ".", "TLSConfig", "!=", "nil", "{", "insecureSkipVerify", "=", "o", ".", "TLSConfig", ".", "InsecureSkipVerify", "\n", "}", "\n", "if", "!", "insecureSkipVerify", "{", "if", "err", "=", "tlsconn", ".", "VerifyHostname", "(", "host", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "client", ".", "conn", "=", "tlsconn", "\n", "}", "\n", "if", "err", ":=", "client", ".", "init", "(", "&", "o", ")", ";", "err", "!=", "nil", "{", "client", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "client", ",", "nil", "\n", "}" ]
// NewClient establishes a new Client connection based on a set of Options.
[ "NewClient", "establishes", "a", "new", "Client", "connection", "based", "on", "a", "set", "of", "Options", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L200-L245
test
mattn/go-xmpp
xmpp.go
Close
func (c *Client) Close() error { if c.conn != (*tls.Conn)(nil) { return c.conn.Close() } return nil }
go
func (c *Client) Close() error { if c.conn != (*tls.Conn)(nil) { return c.conn.Close() } return nil }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", ")", "error", "{", "if", "c", ".", "conn", "!=", "(", "*", "tls", ".", "Conn", ")", "(", "nil", ")", "{", "return", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes the XMPP connection
[ "Close", "closes", "the", "XMPP", "connection" ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L275-L280
test
mattn/go-xmpp
xmpp.go
startTLSIfRequired
func (c *Client) startTLSIfRequired(f *streamFeatures, o *Options, domain string) (*streamFeatures, error) { // whether we start tls is a matter of opinion: the server's and the user's. switch { case f.StartTLS == nil: // the server does not support STARTTLS return f, nil case !o.StartTLS && f.StartTLS.Required == nil: return f, nil case f.StartTLS.Required != nil: // the server requires STARTTLS. case !o.StartTLS: // the user wants STARTTLS and the server supports it. } var err error fmt.Fprintf(c.conn, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n") var k tlsProceed if err = c.p.DecodeElement(&k, nil); err != nil { return f, errors.New("unmarshal <proceed>: " + err.Error()) } tc := o.TLSConfig if tc == nil { tc = new(tls.Config) *tc = DefaultConfig //TODO(scott): we should consider using the server's address or reverse lookup tc.ServerName = domain } t := tls.Client(c.conn, tc) if err = t.Handshake(); err != nil { return f, errors.New("starttls handshake: " + err.Error()) } c.conn = t // restart our declaration of XMPP stream intentions. tf, err := c.startStream(o, domain) if err != nil { return f, err } return tf, nil }
go
func (c *Client) startTLSIfRequired(f *streamFeatures, o *Options, domain string) (*streamFeatures, error) { // whether we start tls is a matter of opinion: the server's and the user's. switch { case f.StartTLS == nil: // the server does not support STARTTLS return f, nil case !o.StartTLS && f.StartTLS.Required == nil: return f, nil case f.StartTLS.Required != nil: // the server requires STARTTLS. case !o.StartTLS: // the user wants STARTTLS and the server supports it. } var err error fmt.Fprintf(c.conn, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n") var k tlsProceed if err = c.p.DecodeElement(&k, nil); err != nil { return f, errors.New("unmarshal <proceed>: " + err.Error()) } tc := o.TLSConfig if tc == nil { tc = new(tls.Config) *tc = DefaultConfig //TODO(scott): we should consider using the server's address or reverse lookup tc.ServerName = domain } t := tls.Client(c.conn, tc) if err = t.Handshake(); err != nil { return f, errors.New("starttls handshake: " + err.Error()) } c.conn = t // restart our declaration of XMPP stream intentions. tf, err := c.startStream(o, domain) if err != nil { return f, err } return tf, nil }
[ "func", "(", "c", "*", "Client", ")", "startTLSIfRequired", "(", "f", "*", "streamFeatures", ",", "o", "*", "Options", ",", "domain", "string", ")", "(", "*", "streamFeatures", ",", "error", ")", "{", "switch", "{", "case", "f", ".", "StartTLS", "==", "nil", ":", "return", "f", ",", "nil", "\n", "case", "!", "o", ".", "StartTLS", "&&", "f", ".", "StartTLS", ".", "Required", "==", "nil", ":", "return", "f", ",", "nil", "\n", "case", "f", ".", "StartTLS", ".", "Required", "!=", "nil", ":", "case", "!", "o", ".", "StartTLS", ":", "}", "\n", "var", "err", "error", "\n", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\"<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\\n\"", ")", "\n", "\\n", "\n", "var", "k", "tlsProceed", "\n", "if", "err", "=", "c", ".", "p", ".", "DecodeElement", "(", "&", "k", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "f", ",", "errors", ".", "New", "(", "\"unmarshal <proceed>: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "tc", ":=", "o", ".", "TLSConfig", "\n", "if", "tc", "==", "nil", "{", "tc", "=", "new", "(", "tls", ".", "Config", ")", "\n", "*", "tc", "=", "DefaultConfig", "\n", "tc", ".", "ServerName", "=", "domain", "\n", "}", "\n", "t", ":=", "tls", ".", "Client", "(", "c", ".", "conn", ",", "tc", ")", "\n", "if", "err", "=", "t", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "return", "f", ",", "errors", ".", "New", "(", "\"starttls handshake: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "c", ".", "conn", "=", "t", "\n", "tf", ",", "err", ":=", "c", ".", "startStream", "(", "o", ",", "domain", ")", "\n", "if", "err", "!=", "nil", "{", "return", "f", ",", "err", "\n", "}", "\n", "}" ]
// startTlsIfRequired examines the server's stream features and, if STARTTLS is required or supported, performs the TLS handshake. // f will be updated if the handshake completes, as the new stream's features are typically different from the original.
[ "startTlsIfRequired", "examines", "the", "server", "s", "stream", "features", "and", "if", "STARTTLS", "is", "required", "or", "supported", "performs", "the", "TLS", "handshake", ".", "f", "will", "be", "updated", "if", "the", "handshake", "completes", "as", "the", "new", "stream", "s", "features", "are", "typically", "different", "from", "the", "original", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L484-L525
test
mattn/go-xmpp
xmpp.go
startStream
func (c *Client) startStream(o *Options, domain string) (*streamFeatures, error) { if o.Debug { c.p = xml.NewDecoder(tee{c.conn, DebugWriter}) } else { c.p = xml.NewDecoder(c.conn) } _, err := fmt.Fprintf(c.conn, "<?xml version='1.0'?>\n"+ "<stream:stream to='%s' xmlns='%s'\n"+ " xmlns:stream='%s' version='1.0'>\n", xmlEscape(domain), nsClient, nsStream) if err != nil { return nil, err } // We expect the server to start a <stream>. se, err := nextStart(c.p) if err != nil { return nil, err } if se.Name.Space != nsStream || se.Name.Local != "stream" { return nil, fmt.Errorf("expected <stream> but got <%v> in %v", se.Name.Local, se.Name.Space) } // Now we're in the stream and can use Unmarshal. // Next message should be <features> to tell us authentication options. // See section 4.6 in RFC 3920. f := new(streamFeatures) if err = c.p.DecodeElement(f, nil); err != nil { return f, errors.New("unmarshal <features>: " + err.Error()) } return f, nil }
go
func (c *Client) startStream(o *Options, domain string) (*streamFeatures, error) { if o.Debug { c.p = xml.NewDecoder(tee{c.conn, DebugWriter}) } else { c.p = xml.NewDecoder(c.conn) } _, err := fmt.Fprintf(c.conn, "<?xml version='1.0'?>\n"+ "<stream:stream to='%s' xmlns='%s'\n"+ " xmlns:stream='%s' version='1.0'>\n", xmlEscape(domain), nsClient, nsStream) if err != nil { return nil, err } // We expect the server to start a <stream>. se, err := nextStart(c.p) if err != nil { return nil, err } if se.Name.Space != nsStream || se.Name.Local != "stream" { return nil, fmt.Errorf("expected <stream> but got <%v> in %v", se.Name.Local, se.Name.Space) } // Now we're in the stream and can use Unmarshal. // Next message should be <features> to tell us authentication options. // See section 4.6 in RFC 3920. f := new(streamFeatures) if err = c.p.DecodeElement(f, nil); err != nil { return f, errors.New("unmarshal <features>: " + err.Error()) } return f, nil }
[ "func", "(", "c", "*", "Client", ")", "startStream", "(", "o", "*", "Options", ",", "domain", "string", ")", "(", "*", "streamFeatures", ",", "error", ")", "{", "if", "o", ".", "Debug", "{", "c", ".", "p", "=", "xml", ".", "NewDecoder", "(", "tee", "{", "c", ".", "conn", ",", "DebugWriter", "}", ")", "\n", "}", "else", "{", "c", ".", "p", "=", "xml", ".", "NewDecoder", "(", "c", ".", "conn", ")", "\n", "}", "\n", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\"<?xml version='1.0'?>\\n\"", "+", "\\n", "+", "\"<stream:stream to='%s' xmlns='%s'\\n\"", ",", "\\n", ",", "\" xmlns:stream='%s' version='1.0'>\\n\"", ",", "\\n", ")", "\n", "xmlEscape", "(", "domain", ")", "\n", "nsClient", "\n", "nsStream", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "se", ",", "err", ":=", "nextStart", "(", "c", ".", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "se", ".", "Name", ".", "Space", "!=", "nsStream", "||", "se", ".", "Name", ".", "Local", "!=", "\"stream\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"expected <stream> but got <%v> in %v\"", ",", "se", ".", "Name", ".", "Local", ",", "se", ".", "Name", ".", "Space", ")", "\n", "}", "\n", "}" ]
// startStream will start a new XML decoder for the connection, signal the start of a stream to the server and verify that the server has // also started the stream; if o.Debug is true, startStream will tee decoded XML data to stderr. The features advertised by the server // will be returned.
[ "startStream", "will", "start", "a", "new", "XML", "decoder", "for", "the", "connection", "signal", "the", "start", "of", "a", "stream", "to", "the", "server", "and", "verify", "that", "the", "server", "has", "also", "started", "the", "stream", ";", "if", "o", ".", "Debug", "is", "true", "startStream", "will", "tee", "decoded", "XML", "data", "to", "stderr", ".", "The", "features", "advertised", "by", "the", "server", "will", "be", "returned", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L530-L562
test
mattn/go-xmpp
xmpp.go
IsEncrypted
func (c *Client) IsEncrypted() bool { _, ok := c.conn.(*tls.Conn) return ok }
go
func (c *Client) IsEncrypted() bool { _, ok := c.conn.(*tls.Conn) return ok }
[ "func", "(", "c", "*", "Client", ")", "IsEncrypted", "(", ")", "bool", "{", "_", ",", "ok", ":=", "c", ".", "conn", ".", "(", "*", "tls", ".", "Conn", ")", "\n", "return", "ok", "\n", "}" ]
// IsEncrypted will return true if the client is connected using a TLS transport, either because it used. // TLS to connect from the outset, or because it successfully used STARTTLS to promote a TCP connection to TLS.
[ "IsEncrypted", "will", "return", "true", "if", "the", "client", "is", "connected", "using", "a", "TLS", "transport", "either", "because", "it", "used", ".", "TLS", "to", "connect", "from", "the", "outset", "or", "because", "it", "successfully", "used", "STARTTLS", "to", "promote", "a", "TCP", "connection", "to", "TLS", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L566-L569
test
mattn/go-xmpp
xmpp.go
Recv
func (c *Client) Recv() (stanza interface{}, err error) { for { _, val, err := next(c.p) if err != nil { return Chat{}, err } switch v := val.(type) { case *clientMessage: stamp, _ := time.Parse( "2006-01-02T15:04:05Z", v.Delay.Stamp, ) chat := Chat{ Remote: v.From, Type: v.Type, Text: v.Body, Subject: v.Subject, Thread: v.Thread, Other: v.OtherStrings(), OtherElem: v.Other, Stamp: stamp, } return chat, nil case *clientQuery: var r Roster for _, item := range v.Item { r = append(r, Contact{item.Jid, item.Name, item.Group}) } return Chat{Type: "roster", Roster: r}, nil case *clientPresence: return Presence{v.From, v.To, v.Type, v.Show, v.Status}, nil case *clientIQ: // TODO check more strictly if bytes.Equal(bytes.TrimSpace(v.Query), []byte(`<ping xmlns='urn:xmpp:ping'/>`)) || bytes.Equal(bytes.TrimSpace(v.Query), []byte(`<ping xmlns="urn:xmpp:ping"/>`)) { err := c.SendResultPing(v.ID, v.From) if err != nil { return Chat{}, err } } return IQ{ID: v.ID, From: v.From, To: v.To, Type: v.Type, Query: v.Query}, nil } } }
go
func (c *Client) Recv() (stanza interface{}, err error) { for { _, val, err := next(c.p) if err != nil { return Chat{}, err } switch v := val.(type) { case *clientMessage: stamp, _ := time.Parse( "2006-01-02T15:04:05Z", v.Delay.Stamp, ) chat := Chat{ Remote: v.From, Type: v.Type, Text: v.Body, Subject: v.Subject, Thread: v.Thread, Other: v.OtherStrings(), OtherElem: v.Other, Stamp: stamp, } return chat, nil case *clientQuery: var r Roster for _, item := range v.Item { r = append(r, Contact{item.Jid, item.Name, item.Group}) } return Chat{Type: "roster", Roster: r}, nil case *clientPresence: return Presence{v.From, v.To, v.Type, v.Show, v.Status}, nil case *clientIQ: // TODO check more strictly if bytes.Equal(bytes.TrimSpace(v.Query), []byte(`<ping xmlns='urn:xmpp:ping'/>`)) || bytes.Equal(bytes.TrimSpace(v.Query), []byte(`<ping xmlns="urn:xmpp:ping"/>`)) { err := c.SendResultPing(v.ID, v.From) if err != nil { return Chat{}, err } } return IQ{ID: v.ID, From: v.From, To: v.To, Type: v.Type, Query: v.Query}, nil } } }
[ "func", "(", "c", "*", "Client", ")", "Recv", "(", ")", "(", "stanza", "interface", "{", "}", ",", "err", "error", ")", "{", "for", "{", "_", ",", "val", ",", "err", ":=", "next", "(", "c", ".", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Chat", "{", "}", ",", "err", "\n", "}", "\n", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "*", "clientMessage", ":", "stamp", ",", "_", ":=", "time", ".", "Parse", "(", "\"2006-01-02T15:04:05Z\"", ",", "v", ".", "Delay", ".", "Stamp", ",", ")", "\n", "chat", ":=", "Chat", "{", "Remote", ":", "v", ".", "From", ",", "Type", ":", "v", ".", "Type", ",", "Text", ":", "v", ".", "Body", ",", "Subject", ":", "v", ".", "Subject", ",", "Thread", ":", "v", ".", "Thread", ",", "Other", ":", "v", ".", "OtherStrings", "(", ")", ",", "OtherElem", ":", "v", ".", "Other", ",", "Stamp", ":", "stamp", ",", "}", "\n", "return", "chat", ",", "nil", "\n", "case", "*", "clientQuery", ":", "var", "r", "Roster", "\n", "for", "_", ",", "item", ":=", "range", "v", ".", "Item", "{", "r", "=", "append", "(", "r", ",", "Contact", "{", "item", ".", "Jid", ",", "item", ".", "Name", ",", "item", ".", "Group", "}", ")", "\n", "}", "\n", "return", "Chat", "{", "Type", ":", "\"roster\"", ",", "Roster", ":", "r", "}", ",", "nil", "\n", "case", "*", "clientPresence", ":", "return", "Presence", "{", "v", ".", "From", ",", "v", ".", "To", ",", "v", ".", "Type", ",", "v", ".", "Show", ",", "v", ".", "Status", "}", ",", "nil", "\n", "case", "*", "clientIQ", ":", "if", "bytes", ".", "Equal", "(", "bytes", ".", "TrimSpace", "(", "v", ".", "Query", ")", ",", "[", "]", "byte", "(", "`<ping xmlns='urn:xmpp:ping'/>`", ")", ")", "||", "bytes", ".", "Equal", "(", "bytes", ".", "TrimSpace", "(", "v", ".", "Query", ")", ",", "[", "]", "byte", "(", "`<ping xmlns=\"urn:xmpp:ping\"/>`", ")", ")", "{", "err", ":=", "c", ".", "SendResultPing", "(", "v", ".", "ID", ",", "v", ".", "From", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Chat", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n", "return", "IQ", "{", "ID", ":", "v", ".", "ID", ",", "From", ":", "v", ".", "From", ",", "To", ":", "v", ".", "To", ",", "Type", ":", "v", ".", "Type", ",", "Query", ":", "v", ".", "Query", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// Recv waits to receive the next XMPP stanza. // Return type is either a presence notification or a chat message.
[ "Recv", "waits", "to", "receive", "the", "next", "XMPP", "stanza", ".", "Return", "type", "is", "either", "a", "presence", "notification", "or", "a", "chat", "message", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L611-L653
test
mattn/go-xmpp
xmpp.go
Send
func (c *Client) Send(chat Chat) (n int, err error) { var subtext = `` var thdtext = `` if chat.Subject != `` { subtext = `<subject>` + xmlEscape(chat.Subject) + `</subject>` } if chat.Thread != `` { thdtext = `<thread>` + xmlEscape(chat.Thread) + `</thread>` } stanza := "<message to='%s' type='%s' id='%s' xml:lang='en'>" + subtext + "<body>%s</body>" + thdtext + "</message>" return fmt.Fprintf(c.conn, stanza, xmlEscape(chat.Remote), xmlEscape(chat.Type), cnonce(), xmlEscape(chat.Text)) }
go
func (c *Client) Send(chat Chat) (n int, err error) { var subtext = `` var thdtext = `` if chat.Subject != `` { subtext = `<subject>` + xmlEscape(chat.Subject) + `</subject>` } if chat.Thread != `` { thdtext = `<thread>` + xmlEscape(chat.Thread) + `</thread>` } stanza := "<message to='%s' type='%s' id='%s' xml:lang='en'>" + subtext + "<body>%s</body>" + thdtext + "</message>" return fmt.Fprintf(c.conn, stanza, xmlEscape(chat.Remote), xmlEscape(chat.Type), cnonce(), xmlEscape(chat.Text)) }
[ "func", "(", "c", "*", "Client", ")", "Send", "(", "chat", "Chat", ")", "(", "n", "int", ",", "err", "error", ")", "{", "var", "subtext", "=", "``", "\n", "var", "thdtext", "=", "``", "\n", "if", "chat", ".", "Subject", "!=", "``", "{", "subtext", "=", "`<subject>`", "+", "xmlEscape", "(", "chat", ".", "Subject", ")", "+", "`</subject>`", "\n", "}", "\n", "if", "chat", ".", "Thread", "!=", "``", "{", "thdtext", "=", "`<thread>`", "+", "xmlEscape", "(", "chat", ".", "Thread", ")", "+", "`</thread>`", "\n", "}", "\n", "stanza", ":=", "\"<message to='%s' type='%s' id='%s' xml:lang='en'>\"", "+", "subtext", "+", "\"<body>%s</body>\"", "+", "thdtext", "+", "\"</message>\"", "\n", "return", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "stanza", ",", "xmlEscape", "(", "chat", ".", "Remote", ")", ",", "xmlEscape", "(", "chat", ".", "Type", ")", ",", "cnonce", "(", ")", ",", "xmlEscape", "(", "chat", ".", "Text", ")", ")", "\n", "}" ]
// Send sends the message wrapped inside an XMPP message stanza body.
[ "Send", "sends", "the", "message", "wrapped", "inside", "an", "XMPP", "message", "stanza", "body", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L656-L670
test
mattn/go-xmpp
xmpp.go
SendOrg
func (c *Client) SendOrg(org string) (n int, err error) { return fmt.Fprint(c.conn, org) }
go
func (c *Client) SendOrg(org string) (n int, err error) { return fmt.Fprint(c.conn, org) }
[ "func", "(", "c", "*", "Client", ")", "SendOrg", "(", "org", "string", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "fmt", ".", "Fprint", "(", "c", ".", "conn", ",", "org", ")", "\n", "}" ]
// SendOrg sends the original text without being wrapped in an XMPP message stanza.
[ "SendOrg", "sends", "the", "original", "text", "without", "being", "wrapped", "in", "an", "XMPP", "message", "stanza", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L673-L675
test
mattn/go-xmpp
xmpp.go
SendKeepAlive
func (c *Client) SendKeepAlive() (n int, err error) { return fmt.Fprintf(c.conn, " ") }
go
func (c *Client) SendKeepAlive() (n int, err error) { return fmt.Fprintf(c.conn, " ") }
[ "func", "(", "c", "*", "Client", ")", "SendKeepAlive", "(", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\" \"", ")", "\n", "}" ]
// SendKeepAlive sends a "whitespace keepalive" as described in chapter 4.6.1 of RFC6120.
[ "SendKeepAlive", "sends", "a", "whitespace", "keepalive", "as", "described", "in", "chapter", "4", ".", "6", ".", "1", "of", "RFC6120", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L682-L684
test
mattn/go-xmpp
xmpp.go
SendHtml
func (c *Client) SendHtml(chat Chat) (n int, err error) { return fmt.Fprintf(c.conn, "<message to='%s' type='%s' xml:lang='en'>"+ "<body>%s</body>"+ "<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns='http://www.w3.org/1999/xhtml'>%s</body></html></message>", xmlEscape(chat.Remote), xmlEscape(chat.Type), xmlEscape(chat.Text), chat.Text) }
go
func (c *Client) SendHtml(chat Chat) (n int, err error) { return fmt.Fprintf(c.conn, "<message to='%s' type='%s' xml:lang='en'>"+ "<body>%s</body>"+ "<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns='http://www.w3.org/1999/xhtml'>%s</body></html></message>", xmlEscape(chat.Remote), xmlEscape(chat.Type), xmlEscape(chat.Text), chat.Text) }
[ "func", "(", "c", "*", "Client", ")", "SendHtml", "(", "chat", "Chat", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\"<message to='%s' type='%s' xml:lang='en'>\"", "+", "\"<body>%s</body>\"", "+", "\"<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns='http://www.w3.org/1999/xhtml'>%s</body></html></message>\"", ",", "xmlEscape", "(", "chat", ".", "Remote", ")", ",", "xmlEscape", "(", "chat", ".", "Type", ")", ",", "xmlEscape", "(", "chat", ".", "Text", ")", ",", "chat", ".", "Text", ")", "\n", "}" ]
// SendHtml sends the message as HTML as defined by XEP-0071
[ "SendHtml", "sends", "the", "message", "as", "HTML", "as", "defined", "by", "XEP", "-", "0071" ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L687-L692
test
mattn/go-xmpp
xmpp.go
nextStart
func nextStart(p *xml.Decoder) (xml.StartElement, error) { for { t, err := p.Token() if err != nil || t == nil { return xml.StartElement{}, err } switch t := t.(type) { case xml.StartElement: return t, nil } } }
go
func nextStart(p *xml.Decoder) (xml.StartElement, error) { for { t, err := p.Token() if err != nil || t == nil { return xml.StartElement{}, err } switch t := t.(type) { case xml.StartElement: return t, nil } } }
[ "func", "nextStart", "(", "p", "*", "xml", ".", "Decoder", ")", "(", "xml", ".", "StartElement", ",", "error", ")", "{", "for", "{", "t", ",", "err", ":=", "p", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "||", "t", "==", "nil", "{", "return", "xml", ".", "StartElement", "{", "}", ",", "err", "\n", "}", "\n", "switch", "t", ":=", "t", ".", "(", "type", ")", "{", "case", "xml", ".", "StartElement", ":", "return", "t", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// Scan XML token stream to find next StartElement.
[ "Scan", "XML", "token", "stream", "to", "find", "next", "StartElement", "." ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L877-L888
test
mattn/go-xmpp
xmpp_muc.go
JoinProtectedMUC
func (c *Client) JoinProtectedMUC(jid, nick string, password string, history_type, history int, history_date *time.Time) (n int, err error) { if nick == "" { nick = c.jid } switch history_type { case NoHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>"+ "</x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password)) case CharHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history maxchars='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case StanzaHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history maxstanzas='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case SecondsHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history seconds='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case SinceHistory: if history_date != nil { return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history since='%s'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history_date.Format(time.RFC3339)) } } return 0, errors.New("Unknown history option") }
go
func (c *Client) JoinProtectedMUC(jid, nick string, password string, history_type, history int, history_date *time.Time) (n int, err error) { if nick == "" { nick = c.jid } switch history_type { case NoHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>"+ "</x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password)) case CharHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history maxchars='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case StanzaHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history maxstanzas='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case SecondsHistory: return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history seconds='%d'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history) case SinceHistory: if history_date != nil { return fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+ "<x xmlns='%s'>\n"+ "<password>%s</password>\n"+ "<history since='%s'/></x>\n"+ "</presence>", xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password), history_date.Format(time.RFC3339)) } } return 0, errors.New("Unknown history option") }
[ "func", "(", "c", "*", "Client", ")", "JoinProtectedMUC", "(", "jid", ",", "nick", "string", ",", "password", "string", ",", "history_type", ",", "history", "int", ",", "history_date", "*", "time", ".", "Time", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "nick", "==", "\"\"", "{", "nick", "=", "c", ".", "jid", "\n", "}", "\n", "switch", "history_type", "{", "case", "NoHistory", ":", "return", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\"<presence to='%s/%s'>\\n\"", "+", "\\n", "+", "\"<x xmlns='%s'>\\n\"", "+", "\\n", "+", "\"<password>%s</password>\"", ",", "\"</x>\\n\"", ",", "\\n", ",", "\"</presence>\"", ",", "xmlEscape", "(", "jid", ")", ")", "\n", "xmlEscape", "(", "nick", ")", "nsMUC", "xmlEscape", "(", "password", ")", "case", "CharHistory", ":", "return", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\"<presence to='%s/%s'>\\n\"", "+", "\\n", "+", "\"<x xmlns='%s'>\\n\"", "+", "\\n", "+", "\"<password>%s</password>\\n\"", ",", "\\n", ",", "\"<history maxchars='%d'/></x>\\n\"", ",", "\\n", ",", "\"</presence>\"", ",", "xmlEscape", "(", "jid", ")", ")", "\n", "}", "\n", "xmlEscape", "(", "nick", ")", "\n", "}" ]
// xep-0045 7.2.6
[ "xep", "-", "0045", "7", ".", "2", ".", "6" ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp_muc.go#L85-L129
test
mattn/go-xmpp
xmpp_muc.go
LeaveMUC
func (c *Client) LeaveMUC(jid string) (n int, err error) { return fmt.Fprintf(c.conn, "<presence from='%s' to='%s' type='unavailable' />", c.jid, xmlEscape(jid)) }
go
func (c *Client) LeaveMUC(jid string) (n int, err error) { return fmt.Fprintf(c.conn, "<presence from='%s' to='%s' type='unavailable' />", c.jid, xmlEscape(jid)) }
[ "func", "(", "c", "*", "Client", ")", "LeaveMUC", "(", "jid", "string", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "fmt", ".", "Fprintf", "(", "c", ".", "conn", ",", "\"<presence from='%s' to='%s' type='unavailable' />\"", ",", "c", ".", "jid", ",", "xmlEscape", "(", "jid", ")", ")", "\n", "}" ]
// xep-0045 7.14
[ "xep", "-", "0045", "7", ".", "14" ]
6093f50721ed2204a87a81109ca5a466a5bec6c1
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp_muc.go#L132-L135
test
scorredoira/email
email.go
AttachBuffer
func (m *Message) AttachBuffer(filename string, buf []byte, inline bool) error { m.Attachments[filename] = &Attachment{ Filename: filename, Data: buf, Inline: inline, } return nil }
go
func (m *Message) AttachBuffer(filename string, buf []byte, inline bool) error { m.Attachments[filename] = &Attachment{ Filename: filename, Data: buf, Inline: inline, } return nil }
[ "func", "(", "m", "*", "Message", ")", "AttachBuffer", "(", "filename", "string", ",", "buf", "[", "]", "byte", ",", "inline", "bool", ")", "error", "{", "m", ".", "Attachments", "[", "filename", "]", "=", "&", "Attachment", "{", "Filename", ":", "filename", ",", "Data", ":", "buf", ",", "Inline", ":", "inline", ",", "}", "\n", "return", "nil", "\n", "}" ]
// AttachBuffer attaches a binary attachment.
[ "AttachBuffer", "attaches", "a", "binary", "attachment", "." ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L77-L84
test
scorredoira/email
email.go
Attach
func (m *Message) Attach(file string) error { return m.attach(file, false) }
go
func (m *Message) Attach(file string) error { return m.attach(file, false) }
[ "func", "(", "m", "*", "Message", ")", "Attach", "(", "file", "string", ")", "error", "{", "return", "m", ".", "attach", "(", "file", ",", "false", ")", "\n", "}" ]
// Attach attaches a file.
[ "Attach", "attaches", "a", "file", "." ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L87-L89
test
scorredoira/email
email.go
Inline
func (m *Message) Inline(file string) error { return m.attach(file, true) }
go
func (m *Message) Inline(file string) error { return m.attach(file, true) }
[ "func", "(", "m", "*", "Message", ")", "Inline", "(", "file", "string", ")", "error", "{", "return", "m", ".", "attach", "(", "file", ",", "true", ")", "\n", "}" ]
// Inline includes a file as an inline attachment.
[ "Inline", "includes", "a", "file", "as", "an", "inline", "attachment", "." ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L92-L94
test
scorredoira/email
email.go
AddHeader
func (m *Message) AddHeader(key string, value string) Header { newHeader := Header{Key: key, Value: value} m.Headers = append(m.Headers, newHeader) return newHeader }
go
func (m *Message) AddHeader(key string, value string) Header { newHeader := Header{Key: key, Value: value} m.Headers = append(m.Headers, newHeader) return newHeader }
[ "func", "(", "m", "*", "Message", ")", "AddHeader", "(", "key", "string", ",", "value", "string", ")", "Header", "{", "newHeader", ":=", "Header", "{", "Key", ":", "key", ",", "Value", ":", "value", "}", "\n", "m", ".", "Headers", "=", "append", "(", "m", ".", "Headers", ",", "newHeader", ")", "\n", "return", "newHeader", "\n", "}" ]
// Ads a Header to message
[ "Ads", "a", "Header", "to", "message" ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L97-L101
test
scorredoira/email
email.go
Tolist
func (m *Message) Tolist() []string { tolist := m.To for _, cc := range m.Cc { tolist = append(tolist, cc) } for _, bcc := range m.Bcc { tolist = append(tolist, bcc) } return tolist }
go
func (m *Message) Tolist() []string { tolist := m.To for _, cc := range m.Cc { tolist = append(tolist, cc) } for _, bcc := range m.Bcc { tolist = append(tolist, bcc) } return tolist }
[ "func", "(", "m", "*", "Message", ")", "Tolist", "(", ")", "[", "]", "string", "{", "tolist", ":=", "m", ".", "To", "\n", "for", "_", ",", "cc", ":=", "range", "m", ".", "Cc", "{", "tolist", "=", "append", "(", "tolist", ",", "cc", ")", "\n", "}", "\n", "for", "_", ",", "bcc", ":=", "range", "m", ".", "Bcc", "{", "tolist", "=", "append", "(", "tolist", ",", "bcc", ")", "\n", "}", "\n", "return", "tolist", "\n", "}" ]
// Tolist returns all the recipients of the email
[ "Tolist", "returns", "all", "the", "recipients", "of", "the", "email" ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L122-L134
test
scorredoira/email
email.go
Bytes
func (m *Message) Bytes() []byte { buf := bytes.NewBuffer(nil) buf.WriteString("From: " + m.From.String() + "\r\n") t := time.Now() buf.WriteString("Date: " + t.Format(time.RFC1123Z) + "\r\n") buf.WriteString("To: " + strings.Join(m.To, ",") + "\r\n") if len(m.Cc) > 0 { buf.WriteString("Cc: " + strings.Join(m.Cc, ",") + "\r\n") } //fix Encode var coder = base64.StdEncoding var subject = "=?UTF-8?B?" + coder.EncodeToString([]byte(m.Subject)) + "?=" buf.WriteString("Subject: " + subject + "\r\n") if len(m.ReplyTo) > 0 { buf.WriteString("Reply-To: " + m.ReplyTo + "\r\n") } buf.WriteString("MIME-Version: 1.0\r\n") // Add custom headers if len(m.Headers) > 0 { for _, header := range m.Headers { buf.WriteString(fmt.Sprintf("%s: %s\r\n", header.Key, header.Value)) } } boundary := "f46d043c813270fc6b04c2d223da" if len(m.Attachments) > 0 { buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\r\n") buf.WriteString("\r\n--" + boundary + "\r\n") } buf.WriteString(fmt.Sprintf("Content-Type: %s; charset=utf-8\r\n\r\n", m.BodyContentType)) buf.WriteString(m.Body) buf.WriteString("\r\n") if len(m.Attachments) > 0 { for _, attachment := range m.Attachments { buf.WriteString("\r\n\r\n--" + boundary + "\r\n") if attachment.Inline { buf.WriteString("Content-Type: message/rfc822\r\n") buf.WriteString("Content-Disposition: inline; filename=\"" + attachment.Filename + "\"\r\n\r\n") buf.Write(attachment.Data) } else { ext := filepath.Ext(attachment.Filename) mimetype := mime.TypeByExtension(ext) if mimetype != "" { mime := fmt.Sprintf("Content-Type: %s\r\n", mimetype) buf.WriteString(mime) } else { buf.WriteString("Content-Type: application/octet-stream\r\n") } buf.WriteString("Content-Transfer-Encoding: base64\r\n") buf.WriteString("Content-Disposition: attachment; filename=\"=?UTF-8?B?") buf.WriteString(coder.EncodeToString([]byte(attachment.Filename))) buf.WriteString("?=\"\r\n\r\n") b := make([]byte, base64.StdEncoding.EncodedLen(len(attachment.Data))) base64.StdEncoding.Encode(b, attachment.Data) // write base64 content in lines of up to 76 chars for i, l := 0, len(b); i < l; i++ { buf.WriteByte(b[i]) if (i+1)%76 == 0 { buf.WriteString("\r\n") } } } buf.WriteString("\r\n--" + boundary) } buf.WriteString("--") } return buf.Bytes() }
go
func (m *Message) Bytes() []byte { buf := bytes.NewBuffer(nil) buf.WriteString("From: " + m.From.String() + "\r\n") t := time.Now() buf.WriteString("Date: " + t.Format(time.RFC1123Z) + "\r\n") buf.WriteString("To: " + strings.Join(m.To, ",") + "\r\n") if len(m.Cc) > 0 { buf.WriteString("Cc: " + strings.Join(m.Cc, ",") + "\r\n") } //fix Encode var coder = base64.StdEncoding var subject = "=?UTF-8?B?" + coder.EncodeToString([]byte(m.Subject)) + "?=" buf.WriteString("Subject: " + subject + "\r\n") if len(m.ReplyTo) > 0 { buf.WriteString("Reply-To: " + m.ReplyTo + "\r\n") } buf.WriteString("MIME-Version: 1.0\r\n") // Add custom headers if len(m.Headers) > 0 { for _, header := range m.Headers { buf.WriteString(fmt.Sprintf("%s: %s\r\n", header.Key, header.Value)) } } boundary := "f46d043c813270fc6b04c2d223da" if len(m.Attachments) > 0 { buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\r\n") buf.WriteString("\r\n--" + boundary + "\r\n") } buf.WriteString(fmt.Sprintf("Content-Type: %s; charset=utf-8\r\n\r\n", m.BodyContentType)) buf.WriteString(m.Body) buf.WriteString("\r\n") if len(m.Attachments) > 0 { for _, attachment := range m.Attachments { buf.WriteString("\r\n\r\n--" + boundary + "\r\n") if attachment.Inline { buf.WriteString("Content-Type: message/rfc822\r\n") buf.WriteString("Content-Disposition: inline; filename=\"" + attachment.Filename + "\"\r\n\r\n") buf.Write(attachment.Data) } else { ext := filepath.Ext(attachment.Filename) mimetype := mime.TypeByExtension(ext) if mimetype != "" { mime := fmt.Sprintf("Content-Type: %s\r\n", mimetype) buf.WriteString(mime) } else { buf.WriteString("Content-Type: application/octet-stream\r\n") } buf.WriteString("Content-Transfer-Encoding: base64\r\n") buf.WriteString("Content-Disposition: attachment; filename=\"=?UTF-8?B?") buf.WriteString(coder.EncodeToString([]byte(attachment.Filename))) buf.WriteString("?=\"\r\n\r\n") b := make([]byte, base64.StdEncoding.EncodedLen(len(attachment.Data))) base64.StdEncoding.Encode(b, attachment.Data) // write base64 content in lines of up to 76 chars for i, l := 0, len(b); i < l; i++ { buf.WriteByte(b[i]) if (i+1)%76 == 0 { buf.WriteString("\r\n") } } } buf.WriteString("\r\n--" + boundary) } buf.WriteString("--") } return buf.Bytes() }
[ "func", "(", "m", "*", "Message", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "buf", ".", "WriteString", "(", "\"From: \"", "+", "m", ".", "From", ".", "String", "(", ")", "+", "\"\\r\\n\"", ")", "\n", "\\r", "\n", "\\n", "\n", "t", ":=", "time", ".", "Now", "(", ")", "\n", "buf", ".", "WriteString", "(", "\"Date: \"", "+", "t", ".", "Format", "(", "time", ".", "RFC1123Z", ")", "+", "\"\\r\\n\"", ")", "\n", "\\r", "\n", "\\n", "\n", "buf", ".", "WriteString", "(", "\"To: \"", "+", "strings", ".", "Join", "(", "m", ".", "To", ",", "\",\"", ")", "+", "\"\\r\\n\"", ")", "\n", "\\r", "\n", "\\n", "\n", "if", "len", "(", "m", ".", "Cc", ")", ">", "0", "{", "buf", ".", "WriteString", "(", "\"Cc: \"", "+", "strings", ".", "Join", "(", "m", ".", "Cc", ",", "\",\"", ")", "+", "\"\\r\\n\"", ")", "\n", "}", "\n", "\\r", "\n", "\\n", "\n", "var", "coder", "=", "base64", ".", "StdEncoding", "\n", "var", "subject", "=", "\"=?UTF-8?B?\"", "+", "coder", ".", "EncodeToString", "(", "[", "]", "byte", "(", "m", ".", "Subject", ")", ")", "+", "\"?=\"", "\n", "buf", ".", "WriteString", "(", "\"Subject: \"", "+", "subject", "+", "\"\\r\\n\"", ")", "\n", "\\r", "\n", "\\n", "\n", "}" ]
// Bytes returns the mail data
[ "Bytes", "returns", "the", "mail", "data" ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L137-L222
test
scorredoira/email
email.go
Send
func Send(addr string, auth smtp.Auth, m *Message) error { return smtp.SendMail(addr, auth, m.From.Address, m.Tolist(), m.Bytes()) }
go
func Send(addr string, auth smtp.Auth, m *Message) error { return smtp.SendMail(addr, auth, m.From.Address, m.Tolist(), m.Bytes()) }
[ "func", "Send", "(", "addr", "string", ",", "auth", "smtp", ".", "Auth", ",", "m", "*", "Message", ")", "error", "{", "return", "smtp", ".", "SendMail", "(", "addr", ",", "auth", ",", "m", ".", "From", ".", "Address", ",", "m", ".", "Tolist", "(", ")", ",", "m", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// Send sends the message.
[ "Send", "sends", "the", "message", "." ]
c1787f8317a847a7adc13673be80723268e6e639
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L225-L227
test
jhillyerd/enmime
envelope.go
GetHeader
func (e *Envelope) GetHeader(name string) string { if e.header == nil { return "" } return decodeHeader(e.header.Get(name)) }
go
func (e *Envelope) GetHeader(name string) string { if e.header == nil { return "" } return decodeHeader(e.header.Get(name)) }
[ "func", "(", "e", "*", "Envelope", ")", "GetHeader", "(", "name", "string", ")", "string", "{", "if", "e", ".", "header", "==", "nil", "{", "return", "\"\"", "\n", "}", "\n", "return", "decodeHeader", "(", "e", ".", "header", ".", "Get", "(", "name", ")", ")", "\n", "}" ]
// GetHeader processes the specified header for RFC 2047 encoded words and returns the result as a // UTF-8 string
[ "GetHeader", "processes", "the", "specified", "header", "for", "RFC", "2047", "encoded", "words", "and", "returns", "the", "result", "as", "a", "UTF", "-", "8", "string" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L44-L49
test
jhillyerd/enmime
envelope.go
GetHeaderValues
func (e *Envelope) GetHeaderValues(name string) []string { if e.header == nil { return []string{} } rawValues := (*e.header)[textproto.CanonicalMIMEHeaderKey(name)] var values []string for _, v := range rawValues { values = append(values, decodeHeader(v)) } return values }
go
func (e *Envelope) GetHeaderValues(name string) []string { if e.header == nil { return []string{} } rawValues := (*e.header)[textproto.CanonicalMIMEHeaderKey(name)] var values []string for _, v := range rawValues { values = append(values, decodeHeader(v)) } return values }
[ "func", "(", "e", "*", "Envelope", ")", "GetHeaderValues", "(", "name", "string", ")", "[", "]", "string", "{", "if", "e", ".", "header", "==", "nil", "{", "return", "[", "]", "string", "{", "}", "\n", "}", "\n", "rawValues", ":=", "(", "*", "e", ".", "header", ")", "[", "textproto", ".", "CanonicalMIMEHeaderKey", "(", "name", ")", "]", "\n", "var", "values", "[", "]", "string", "\n", "for", "_", ",", "v", ":=", "range", "rawValues", "{", "values", "=", "append", "(", "values", ",", "decodeHeader", "(", "v", ")", ")", "\n", "}", "\n", "return", "values", "\n", "}" ]
// GetHeaderValues processes the specified header for RFC 2047 encoded words and returns all existing // values as a list of UTF-8 strings
[ "GetHeaderValues", "processes", "the", "specified", "header", "for", "RFC", "2047", "encoded", "words", "and", "returns", "all", "existing", "values", "as", "a", "list", "of", "UTF", "-", "8", "strings" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L53-L64
test
jhillyerd/enmime
envelope.go
SetHeader
func (e *Envelope) SetHeader(name string, value []string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } for i, v := range value { if i == 0 { e.header.Set(name, mime.BEncoding.Encode("utf-8", v)) continue } e.header.Add(name, mime.BEncoding.Encode("utf-8", v)) } return nil }
go
func (e *Envelope) SetHeader(name string, value []string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } for i, v := range value { if i == 0 { e.header.Set(name, mime.BEncoding.Encode("utf-8", v)) continue } e.header.Add(name, mime.BEncoding.Encode("utf-8", v)) } return nil }
[ "func", "(", "e", "*", "Envelope", ")", "SetHeader", "(", "name", "string", ",", "value", "[", "]", "string", ")", "error", "{", "if", "name", "==", "\"\"", "{", "return", "fmt", ".", "Errorf", "(", "\"Provide non-empty header name\"", ")", "\n", "}", "\n", "for", "i", ",", "v", ":=", "range", "value", "{", "if", "i", "==", "0", "{", "e", ".", "header", ".", "Set", "(", "name", ",", "mime", ".", "BEncoding", ".", "Encode", "(", "\"utf-8\"", ",", "v", ")", ")", "\n", "continue", "\n", "}", "\n", "e", ".", "header", ".", "Add", "(", "name", ",", "mime", ".", "BEncoding", ".", "Encode", "(", "\"utf-8\"", ",", "v", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetHeader sets given header name to the given value. // If the header exists already, all existing values are replaced.
[ "SetHeader", "sets", "given", "header", "name", "to", "the", "given", "value", ".", "If", "the", "header", "exists", "already", "all", "existing", "values", "are", "replaced", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L68-L81
test
jhillyerd/enmime
envelope.go
AddHeader
func (e *Envelope) AddHeader(name string, value string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } e.header.Add(name, mime.BEncoding.Encode("utf-8", value)) return nil }
go
func (e *Envelope) AddHeader(name string, value string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } e.header.Add(name, mime.BEncoding.Encode("utf-8", value)) return nil }
[ "func", "(", "e", "*", "Envelope", ")", "AddHeader", "(", "name", "string", ",", "value", "string", ")", "error", "{", "if", "name", "==", "\"\"", "{", "return", "fmt", ".", "Errorf", "(", "\"Provide non-empty header name\"", ")", "\n", "}", "\n", "e", ".", "header", ".", "Add", "(", "name", ",", "mime", ".", "BEncoding", ".", "Encode", "(", "\"utf-8\"", ",", "value", ")", ")", "\n", "return", "nil", "\n", "}" ]
// AddHeader appends given header value to header name without changing existing values. // If the header does not exist already, it will be created.
[ "AddHeader", "appends", "given", "header", "value", "to", "header", "name", "without", "changing", "existing", "values", ".", "If", "the", "header", "does", "not", "exist", "already", "it", "will", "be", "created", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L85-L92
test
jhillyerd/enmime
envelope.go
DeleteHeader
func (e *Envelope) DeleteHeader(name string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } e.header.Del(name) return nil }
go
func (e *Envelope) DeleteHeader(name string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } e.header.Del(name) return nil }
[ "func", "(", "e", "*", "Envelope", ")", "DeleteHeader", "(", "name", "string", ")", "error", "{", "if", "name", "==", "\"\"", "{", "return", "fmt", ".", "Errorf", "(", "\"Provide non-empty header name\"", ")", "\n", "}", "\n", "e", ".", "header", ".", "Del", "(", "name", ")", "\n", "return", "nil", "\n", "}" ]
// DeleteHeader deletes given header.
[ "DeleteHeader", "deletes", "given", "header", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L95-L102
test
jhillyerd/enmime
envelope.go
AddressList
func (e *Envelope) AddressList(key string) ([]*mail.Address, error) { if e.header == nil { return nil, fmt.Errorf("No headers available") } if !AddressHeaders[strings.ToLower(key)] { return nil, fmt.Errorf("%s is not an address header", key) } str := decodeToUTF8Base64Header(e.header.Get(key)) if str == "" { return nil, mail.ErrHeaderNotPresent } // These statements are handy for debugging ParseAddressList errors // fmt.Println("in: ", m.header.Get(key)) // fmt.Println("out: ", str) ret, err := mail.ParseAddressList(str) switch { case err == nil: // carry on case err.Error() == "mail: expected comma": ret, err = mail.ParseAddressList(ensureCommaDelimitedAddresses(str)) if err != nil { return nil, err } default: return nil, err } return ret, nil }
go
func (e *Envelope) AddressList(key string) ([]*mail.Address, error) { if e.header == nil { return nil, fmt.Errorf("No headers available") } if !AddressHeaders[strings.ToLower(key)] { return nil, fmt.Errorf("%s is not an address header", key) } str := decodeToUTF8Base64Header(e.header.Get(key)) if str == "" { return nil, mail.ErrHeaderNotPresent } // These statements are handy for debugging ParseAddressList errors // fmt.Println("in: ", m.header.Get(key)) // fmt.Println("out: ", str) ret, err := mail.ParseAddressList(str) switch { case err == nil: // carry on case err.Error() == "mail: expected comma": ret, err = mail.ParseAddressList(ensureCommaDelimitedAddresses(str)) if err != nil { return nil, err } default: return nil, err } return ret, nil }
[ "func", "(", "e", "*", "Envelope", ")", "AddressList", "(", "key", "string", ")", "(", "[", "]", "*", "mail", ".", "Address", ",", "error", ")", "{", "if", "e", ".", "header", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"No headers available\"", ")", "\n", "}", "\n", "if", "!", "AddressHeaders", "[", "strings", ".", "ToLower", "(", "key", ")", "]", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"%s is not an address header\"", ",", "key", ")", "\n", "}", "\n", "str", ":=", "decodeToUTF8Base64Header", "(", "e", ".", "header", ".", "Get", "(", "key", ")", ")", "\n", "if", "str", "==", "\"\"", "{", "return", "nil", ",", "mail", ".", "ErrHeaderNotPresent", "\n", "}", "\n", "ret", ",", "err", ":=", "mail", ".", "ParseAddressList", "(", "str", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "case", "err", ".", "Error", "(", ")", "==", "\"mail: expected comma\"", ":", "ret", ",", "err", "=", "mail", ".", "ParseAddressList", "(", "ensureCommaDelimitedAddresses", "(", "str", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// AddressList returns a mail.Address slice with RFC 2047 encoded names converted to UTF-8
[ "AddressList", "returns", "a", "mail", ".", "Address", "slice", "with", "RFC", "2047", "encoded", "names", "converted", "to", "UTF", "-", "8" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L105-L134
test
jhillyerd/enmime
envelope.go
Clone
func (e *Envelope) Clone() *Envelope { if e == nil { return nil } newEnvelope := &Envelope{ e.Text, e.HTML, e.Root.Clone(nil), e.Attachments, e.Inlines, e.OtherParts, e.Errors, e.header, } return newEnvelope }
go
func (e *Envelope) Clone() *Envelope { if e == nil { return nil } newEnvelope := &Envelope{ e.Text, e.HTML, e.Root.Clone(nil), e.Attachments, e.Inlines, e.OtherParts, e.Errors, e.header, } return newEnvelope }
[ "func", "(", "e", "*", "Envelope", ")", "Clone", "(", ")", "*", "Envelope", "{", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "newEnvelope", ":=", "&", "Envelope", "{", "e", ".", "Text", ",", "e", ".", "HTML", ",", "e", ".", "Root", ".", "Clone", "(", "nil", ")", ",", "e", ".", "Attachments", ",", "e", ".", "Inlines", ",", "e", ".", "OtherParts", ",", "e", ".", "Errors", ",", "e", ".", "header", ",", "}", "\n", "return", "newEnvelope", "\n", "}" ]
// Clone returns a clone of the current Envelope
[ "Clone", "returns", "a", "clone", "of", "the", "current", "Envelope" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L137-L153
test
jhillyerd/enmime
envelope.go
ReadEnvelope
func ReadEnvelope(r io.Reader) (*Envelope, error) { // Read MIME parts from reader root, err := ReadParts(r) if err != nil { return nil, errors.WithMessage(err, "Failed to ReadParts") } return EnvelopeFromPart(root) }
go
func ReadEnvelope(r io.Reader) (*Envelope, error) { // Read MIME parts from reader root, err := ReadParts(r) if err != nil { return nil, errors.WithMessage(err, "Failed to ReadParts") } return EnvelopeFromPart(root) }
[ "func", "ReadEnvelope", "(", "r", "io", ".", "Reader", ")", "(", "*", "Envelope", ",", "error", ")", "{", "root", ",", "err", ":=", "ReadParts", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "WithMessage", "(", "err", ",", "\"Failed to ReadParts\"", ")", "\n", "}", "\n", "return", "EnvelopeFromPart", "(", "root", ")", "\n", "}" ]
// ReadEnvelope is a wrapper around ReadParts and EnvelopeFromPart. It parses the content of the // provided reader into an Envelope, downconverting HTML to plain text if needed, and sorting the // attachments, inlines and other parts into their respective slices. Errors are collected from all // Parts and placed into the Envelope.Errors slice.
[ "ReadEnvelope", "is", "a", "wrapper", "around", "ReadParts", "and", "EnvelopeFromPart", ".", "It", "parses", "the", "content", "of", "the", "provided", "reader", "into", "an", "Envelope", "downconverting", "HTML", "to", "plain", "text", "if", "needed", "and", "sorting", "the", "attachments", "inlines", "and", "other", "parts", "into", "their", "respective", "slices", ".", "Errors", "are", "collected", "from", "all", "Parts", "and", "placed", "into", "the", "Envelope", ".", "Errors", "slice", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L159-L166
test
jhillyerd/enmime
envelope.go
EnvelopeFromPart
func EnvelopeFromPart(root *Part) (*Envelope, error) { e := &Envelope{ Root: root, header: &root.Header, } if detectMultipartMessage(root) { // Multi-part message (message with attachments, etc) if err := parseMultiPartBody(root, e); err != nil { return nil, err } } else { if detectBinaryBody(root) { // Attachment only, no text if root.Disposition == cdInline { e.Inlines = append(e.Inlines, root) } else { e.Attachments = append(e.Attachments, root) } } else { // Only text, no attachments if err := parseTextOnlyBody(root, e); err != nil { return nil, err } } } // Down-convert HTML to text if necessary if e.Text == "" && e.HTML != "" { // We always warn when this happens e.Root.addWarning( ErrorPlainTextFromHTML, "Message did not contain a text/plain part") var err error if e.Text, err = html2text.FromString(e.HTML); err != nil { // Downcoversion shouldn't fail e.Text = "" p := e.Root.BreadthMatchFirst(matchHTMLBodyPart) p.addError( ErrorPlainTextFromHTML, "Failed to downconvert HTML: %v", err) } } // Copy part errors into Envelope. if e.Root != nil { _ = e.Root.DepthMatchAll(func(part *Part) bool { // Using DepthMatchAll to traverse all parts, don't care about result. for i := range part.Errors { // Range index is needed to get the correct address, because range value points to // a locally scoped variable. e.Errors = append(e.Errors, part.Errors[i]) } return false }) } return e, nil }
go
func EnvelopeFromPart(root *Part) (*Envelope, error) { e := &Envelope{ Root: root, header: &root.Header, } if detectMultipartMessage(root) { // Multi-part message (message with attachments, etc) if err := parseMultiPartBody(root, e); err != nil { return nil, err } } else { if detectBinaryBody(root) { // Attachment only, no text if root.Disposition == cdInline { e.Inlines = append(e.Inlines, root) } else { e.Attachments = append(e.Attachments, root) } } else { // Only text, no attachments if err := parseTextOnlyBody(root, e); err != nil { return nil, err } } } // Down-convert HTML to text if necessary if e.Text == "" && e.HTML != "" { // We always warn when this happens e.Root.addWarning( ErrorPlainTextFromHTML, "Message did not contain a text/plain part") var err error if e.Text, err = html2text.FromString(e.HTML); err != nil { // Downcoversion shouldn't fail e.Text = "" p := e.Root.BreadthMatchFirst(matchHTMLBodyPart) p.addError( ErrorPlainTextFromHTML, "Failed to downconvert HTML: %v", err) } } // Copy part errors into Envelope. if e.Root != nil { _ = e.Root.DepthMatchAll(func(part *Part) bool { // Using DepthMatchAll to traverse all parts, don't care about result. for i := range part.Errors { // Range index is needed to get the correct address, because range value points to // a locally scoped variable. e.Errors = append(e.Errors, part.Errors[i]) } return false }) } return e, nil }
[ "func", "EnvelopeFromPart", "(", "root", "*", "Part", ")", "(", "*", "Envelope", ",", "error", ")", "{", "e", ":=", "&", "Envelope", "{", "Root", ":", "root", ",", "header", ":", "&", "root", ".", "Header", ",", "}", "\n", "if", "detectMultipartMessage", "(", "root", ")", "{", "if", "err", ":=", "parseMultiPartBody", "(", "root", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "if", "detectBinaryBody", "(", "root", ")", "{", "if", "root", ".", "Disposition", "==", "cdInline", "{", "e", ".", "Inlines", "=", "append", "(", "e", ".", "Inlines", ",", "root", ")", "\n", "}", "else", "{", "e", ".", "Attachments", "=", "append", "(", "e", ".", "Attachments", ",", "root", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "parseTextOnlyBody", "(", "root", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "e", ".", "Text", "==", "\"\"", "&&", "e", ".", "HTML", "!=", "\"\"", "{", "e", ".", "Root", ".", "addWarning", "(", "ErrorPlainTextFromHTML", ",", "\"Message did not contain a text/plain part\"", ")", "\n", "var", "err", "error", "\n", "if", "e", ".", "Text", ",", "err", "=", "html2text", ".", "FromString", "(", "e", ".", "HTML", ")", ";", "err", "!=", "nil", "{", "e", ".", "Text", "=", "\"\"", "\n", "p", ":=", "e", ".", "Root", ".", "BreadthMatchFirst", "(", "matchHTMLBodyPart", ")", "\n", "p", ".", "addError", "(", "ErrorPlainTextFromHTML", ",", "\"Failed to downconvert HTML: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "e", ".", "Root", "!=", "nil", "{", "_", "=", "e", ".", "Root", ".", "DepthMatchAll", "(", "func", "(", "part", "*", "Part", ")", "bool", "{", "for", "i", ":=", "range", "part", ".", "Errors", "{", "e", ".", "Errors", "=", "append", "(", "e", ".", "Errors", ",", "part", ".", "Errors", "[", "i", "]", ")", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}", "\n", "return", "e", ",", "nil", "\n", "}" ]
// EnvelopeFromPart uses the provided Part tree to build an Envelope, downconverting HTML to plain // text if needed, and sorting the attachments, inlines and other parts into their respective // slices. Errors are collected from all Parts and placed into the Envelopes Errors slice.
[ "EnvelopeFromPart", "uses", "the", "provided", "Part", "tree", "to", "build", "an", "Envelope", "downconverting", "HTML", "to", "plain", "text", "if", "needed", "and", "sorting", "the", "attachments", "inlines", "and", "other", "parts", "into", "their", "respective", "slices", ".", "Errors", "are", "collected", "from", "all", "Parts", "and", "placed", "into", "the", "Envelopes", "Errors", "slice", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L171-L230
test
jhillyerd/enmime
envelope.go
parseTextOnlyBody
func parseTextOnlyBody(root *Part, e *Envelope) error { // Determine character set var charset string var isHTML bool if ctype := root.Header.Get(hnContentType); ctype != "" { if mediatype, mparams, _, err := parseMediaType(ctype); err == nil { isHTML = (mediatype == ctTextHTML) if mparams[hpCharset] != "" { charset = mparams[hpCharset] } } } // Read transcoded text if isHTML { rawHTML := string(root.Content) // Note: Empty e.Text will trigger html2text conversion e.HTML = rawHTML if charset == "" { // Search for charset in HTML metadata if charset = coding.FindCharsetInHTML(rawHTML); charset != "" { // Found charset in HTML if convHTML, err := coding.ConvertToUTF8String(charset, root.Content); err == nil { // Successful conversion e.HTML = convHTML } else { // Conversion failed root.addWarning(ErrorCharsetConversion, err.Error()) } } // Converted from charset in HTML return nil } } else { e.Text = string(root.Content) } return nil }
go
func parseTextOnlyBody(root *Part, e *Envelope) error { // Determine character set var charset string var isHTML bool if ctype := root.Header.Get(hnContentType); ctype != "" { if mediatype, mparams, _, err := parseMediaType(ctype); err == nil { isHTML = (mediatype == ctTextHTML) if mparams[hpCharset] != "" { charset = mparams[hpCharset] } } } // Read transcoded text if isHTML { rawHTML := string(root.Content) // Note: Empty e.Text will trigger html2text conversion e.HTML = rawHTML if charset == "" { // Search for charset in HTML metadata if charset = coding.FindCharsetInHTML(rawHTML); charset != "" { // Found charset in HTML if convHTML, err := coding.ConvertToUTF8String(charset, root.Content); err == nil { // Successful conversion e.HTML = convHTML } else { // Conversion failed root.addWarning(ErrorCharsetConversion, err.Error()) } } // Converted from charset in HTML return nil } } else { e.Text = string(root.Content) } return nil }
[ "func", "parseTextOnlyBody", "(", "root", "*", "Part", ",", "e", "*", "Envelope", ")", "error", "{", "var", "charset", "string", "\n", "var", "isHTML", "bool", "\n", "if", "ctype", ":=", "root", ".", "Header", ".", "Get", "(", "hnContentType", ")", ";", "ctype", "!=", "\"\"", "{", "if", "mediatype", ",", "mparams", ",", "_", ",", "err", ":=", "parseMediaType", "(", "ctype", ")", ";", "err", "==", "nil", "{", "isHTML", "=", "(", "mediatype", "==", "ctTextHTML", ")", "\n", "if", "mparams", "[", "hpCharset", "]", "!=", "\"\"", "{", "charset", "=", "mparams", "[", "hpCharset", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "isHTML", "{", "rawHTML", ":=", "string", "(", "root", ".", "Content", ")", "\n", "e", ".", "HTML", "=", "rawHTML", "\n", "if", "charset", "==", "\"\"", "{", "if", "charset", "=", "coding", ".", "FindCharsetInHTML", "(", "rawHTML", ")", ";", "charset", "!=", "\"\"", "{", "if", "convHTML", ",", "err", ":=", "coding", ".", "ConvertToUTF8String", "(", "charset", ",", "root", ".", "Content", ")", ";", "err", "==", "nil", "{", "e", ".", "HTML", "=", "convHTML", "\n", "}", "else", "{", "root", ".", "addWarning", "(", "ErrorCharsetConversion", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "else", "{", "e", ".", "Text", "=", "string", "(", "root", ".", "Content", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parseTextOnlyBody parses a plain text message in root that has MIME-like headers, but // only contains a single part - no boundaries, etc. The result is placed in e.
[ "parseTextOnlyBody", "parses", "a", "plain", "text", "message", "in", "root", "that", "has", "MIME", "-", "like", "headers", "but", "only", "contains", "a", "single", "part", "-", "no", "boundaries", "etc", ".", "The", "result", "is", "placed", "in", "e", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L234-L272
test