id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
148,200
emersion/go-imap
server/server.go
Serve
func (s *Server) Serve(l net.Listener) error { s.locker.Lock() s.listeners[l] = struct{}{} s.locker.Unlock() defer func() { s.locker.Lock() defer s.locker.Unlock() l.Close() delete(s.listeners, l) }() updater, ok := s.Backend.(backend.BackendUpdater) if ok { s.Updates = updater.Updates() go s.listenUpdates() } for { c, err := l.Accept() if err != nil { return err } var conn Conn = newConn(s, c) for _, ext := range s.extensions { if ext, ok := ext.(ConnExtension); ok { conn = ext.NewConn(conn) } } go s.serveConn(conn) } }
go
func (s *Server) Serve(l net.Listener) error { s.locker.Lock() s.listeners[l] = struct{}{} s.locker.Unlock() defer func() { s.locker.Lock() defer s.locker.Unlock() l.Close() delete(s.listeners, l) }() updater, ok := s.Backend.(backend.BackendUpdater) if ok { s.Updates = updater.Updates() go s.listenUpdates() } for { c, err := l.Accept() if err != nil { return err } var conn Conn = newConn(s, c) for _, ext := range s.extensions { if ext, ok := ext.(ConnExtension); ok { conn = ext.NewConn(conn) } } go s.serveConn(conn) } }
[ "func", "(", "s", "*", "Server", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "s", ".", "locker", ".", "Lock", "(", ")", "\n", "s", ".", "listeners", "[", "l", "]", "=", "struct", "{", "}", "{", "}", "\n", "s", ".", "locker", ".", "Unlock", "(", ")", "\n\n", "defer", "func", "(", ")", "{", "s", ".", "locker", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "locker", ".", "Unlock", "(", ")", "\n", "l", ".", "Close", "(", ")", "\n", "delete", "(", "s", ".", "listeners", ",", "l", ")", "\n", "}", "(", ")", "\n\n", "updater", ",", "ok", ":=", "s", ".", "Backend", ".", "(", "backend", ".", "BackendUpdater", ")", "\n", "if", "ok", "{", "s", ".", "Updates", "=", "updater", ".", "Updates", "(", ")", "\n", "go", "s", ".", "listenUpdates", "(", ")", "\n", "}", "\n\n", "for", "{", "c", ",", "err", ":=", "l", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "conn", "Conn", "=", "newConn", "(", "s", ",", "c", ")", "\n", "for", "_", ",", "ext", ":=", "range", "s", ".", "extensions", "{", "if", "ext", ",", "ok", ":=", "ext", ".", "(", "ConnExtension", ")", ";", "ok", "{", "conn", "=", "ext", ".", "NewConn", "(", "conn", ")", "\n", "}", "\n", "}", "\n\n", "go", "s", ".", "serveConn", "(", "conn", ")", "\n", "}", "\n", "}" ]
// Serve accepts incoming connections on the Listener l.
[ "Serve", "accepts", "incoming", "connections", "on", "the", "Listener", "l", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/server/server.go#L198-L231
148,201
emersion/go-imap
server/server.go
Command
func (s *Server) Command(name string) HandlerFactory { // Extensions can override builtin commands for _, ext := range s.extensions { if h := ext.Command(name); h != nil { return h } } return s.commands[name] }
go
func (s *Server) Command(name string) HandlerFactory { // Extensions can override builtin commands for _, ext := range s.extensions { if h := ext.Command(name); h != nil { return h } } return s.commands[name] }
[ "func", "(", "s", "*", "Server", ")", "Command", "(", "name", "string", ")", "HandlerFactory", "{", "// Extensions can override builtin commands", "for", "_", ",", "ext", ":=", "range", "s", ".", "extensions", "{", "if", "h", ":=", "ext", ".", "Command", "(", "name", ")", ";", "h", "!=", "nil", "{", "return", "h", "\n", "}", "\n", "}", "\n\n", "return", "s", ".", "commands", "[", "name", "]", "\n", "}" ]
// Command gets a command handler factory for the provided command name.
[ "Command", "gets", "a", "command", "handler", "factory", "for", "the", "provided", "command", "name", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/server/server.go#L285-L294
148,202
emersion/go-imap
server/server.go
ForEachConn
func (s *Server) ForEachConn(f func(Conn)) { s.locker.Lock() defer s.locker.Unlock() for conn := range s.conns { f(conn) } }
go
func (s *Server) ForEachConn(f func(Conn)) { s.locker.Lock() defer s.locker.Unlock() for conn := range s.conns { f(conn) } }
[ "func", "(", "s", "*", "Server", ")", "ForEachConn", "(", "f", "func", "(", "Conn", ")", ")", "{", "s", ".", "locker", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "locker", ".", "Unlock", "(", ")", "\n", "for", "conn", ":=", "range", "s", ".", "conns", "{", "f", "(", "conn", ")", "\n", "}", "\n", "}" ]
// ForEachConn iterates through all opened connections.
[ "ForEachConn", "iterates", "through", "all", "opened", "connections", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/server/server.go#L374-L380
148,203
emersion/go-imap
server/server.go
Close
func (s *Server) Close() error { s.locker.Lock() defer s.locker.Unlock() for l := range s.listeners { l.Close() } for conn := range s.conns { conn.Close() } return nil }
go
func (s *Server) Close() error { s.locker.Lock() defer s.locker.Unlock() for l := range s.listeners { l.Close() } for conn := range s.conns { conn.Close() } return nil }
[ "func", "(", "s", "*", "Server", ")", "Close", "(", ")", "error", "{", "s", ".", "locker", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "locker", ".", "Unlock", "(", ")", "\n\n", "for", "l", ":=", "range", "s", ".", "listeners", "{", "l", ".", "Close", "(", ")", "\n", "}", "\n\n", "for", "conn", ":=", "range", "s", ".", "conns", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Stops listening and closes all current connections.
[ "Stops", "listening", "and", "closes", "all", "current", "connections", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/server/server.go#L383-L396
148,204
emersion/go-imap
server/server.go
Enable
func (s *Server) Enable(extensions ...Extension) { s.extensions = append(s.extensions, extensions...) }
go
func (s *Server) Enable(extensions ...Extension) { s.extensions = append(s.extensions, extensions...) }
[ "func", "(", "s", "*", "Server", ")", "Enable", "(", "extensions", "...", "Extension", ")", "{", "s", ".", "extensions", "=", "append", "(", "s", ".", "extensions", ",", "extensions", "...", ")", "\n", "}" ]
// Enable some IMAP extensions on this server. // // This function should not be called directly, it must only be used by // libraries implementing extensions of the IMAP protocol.
[ "Enable", "some", "IMAP", "extensions", "on", "this", "server", ".", "This", "function", "should", "not", "be", "called", "directly", "it", "must", "only", "be", "used", "by", "libraries", "implementing", "extensions", "of", "the", "IMAP", "protocol", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/server/server.go#L402-L404
148,205
emersion/go-imap
server/server.go
EnableAuth
func (s *Server) EnableAuth(name string, f SASLServerFactory) { s.auths[name] = f }
go
func (s *Server) EnableAuth(name string, f SASLServerFactory) { s.auths[name] = f }
[ "func", "(", "s", "*", "Server", ")", "EnableAuth", "(", "name", "string", ",", "f", "SASLServerFactory", ")", "{", "s", ".", "auths", "[", "name", "]", "=", "f", "\n", "}" ]
// Enable an authentication mechanism on this server. // // This function should not be called directly, it must only be used by // libraries implementing extensions of the IMAP protocol.
[ "Enable", "an", "authentication", "mechanism", "on", "this", "server", ".", "This", "function", "should", "not", "be", "called", "directly", "it", "must", "only", "be", "used", "by", "libraries", "implementing", "extensions", "of", "the", "IMAP", "protocol", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/server/server.go#L410-L412
148,206
emersion/go-imap
backend/backendutil/bodystructure.go
FetchBodyStructure
func FetchBodyStructure(e *message.Entity, extended bool) (*imap.BodyStructure, error) { bs := new(imap.BodyStructure) mediaType, mediaParams, _ := e.Header.ContentType() typeParts := strings.SplitN(mediaType, "/", 2) bs.MIMEType = typeParts[0] if len(typeParts) == 2 { bs.MIMESubType = typeParts[1] } bs.Params = mediaParams bs.Id = e.Header.Get("Content-Id") bs.Description = e.Header.Get("Content-Description") bs.Encoding = e.Header.Get("Content-Encoding") // TODO: bs.Size if mr := e.MultipartReader(); mr != nil { var parts []*imap.BodyStructure for { p, err := mr.NextPart() if err == io.EOF { break } else if err != nil { return nil, err } pbs, err := FetchBodyStructure(p, extended) if err != nil { return nil, err } parts = append(parts, pbs) } bs.Parts = parts } // TODO: bs.Envelope, bs.BodyStructure // TODO: bs.Lines if extended { bs.Extended = true bs.Disposition, bs.DispositionParams, _ = e.Header.ContentDisposition() // TODO: bs.Language, bs.Location // TODO: bs.MD5 } return bs, nil }
go
func FetchBodyStructure(e *message.Entity, extended bool) (*imap.BodyStructure, error) { bs := new(imap.BodyStructure) mediaType, mediaParams, _ := e.Header.ContentType() typeParts := strings.SplitN(mediaType, "/", 2) bs.MIMEType = typeParts[0] if len(typeParts) == 2 { bs.MIMESubType = typeParts[1] } bs.Params = mediaParams bs.Id = e.Header.Get("Content-Id") bs.Description = e.Header.Get("Content-Description") bs.Encoding = e.Header.Get("Content-Encoding") // TODO: bs.Size if mr := e.MultipartReader(); mr != nil { var parts []*imap.BodyStructure for { p, err := mr.NextPart() if err == io.EOF { break } else if err != nil { return nil, err } pbs, err := FetchBodyStructure(p, extended) if err != nil { return nil, err } parts = append(parts, pbs) } bs.Parts = parts } // TODO: bs.Envelope, bs.BodyStructure // TODO: bs.Lines if extended { bs.Extended = true bs.Disposition, bs.DispositionParams, _ = e.Header.ContentDisposition() // TODO: bs.Language, bs.Location // TODO: bs.MD5 } return bs, nil }
[ "func", "FetchBodyStructure", "(", "e", "*", "message", ".", "Entity", ",", "extended", "bool", ")", "(", "*", "imap", ".", "BodyStructure", ",", "error", ")", "{", "bs", ":=", "new", "(", "imap", ".", "BodyStructure", ")", "\n\n", "mediaType", ",", "mediaParams", ",", "_", ":=", "e", ".", "Header", ".", "ContentType", "(", ")", "\n", "typeParts", ":=", "strings", ".", "SplitN", "(", "mediaType", ",", "\"", "\"", ",", "2", ")", "\n", "bs", ".", "MIMEType", "=", "typeParts", "[", "0", "]", "\n", "if", "len", "(", "typeParts", ")", "==", "2", "{", "bs", ".", "MIMESubType", "=", "typeParts", "[", "1", "]", "\n", "}", "\n", "bs", ".", "Params", "=", "mediaParams", "\n\n", "bs", ".", "Id", "=", "e", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "bs", ".", "Description", "=", "e", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "bs", ".", "Encoding", "=", "e", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "// TODO: bs.Size", "if", "mr", ":=", "e", ".", "MultipartReader", "(", ")", ";", "mr", "!=", "nil", "{", "var", "parts", "[", "]", "*", "imap", ".", "BodyStructure", "\n", "for", "{", "p", ",", "err", ":=", "mr", ".", "NextPart", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pbs", ",", "err", ":=", "FetchBodyStructure", "(", "p", ",", "extended", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "parts", "=", "append", "(", "parts", ",", "pbs", ")", "\n", "}", "\n", "bs", ".", "Parts", "=", "parts", "\n", "}", "\n\n", "// TODO: bs.Envelope, bs.BodyStructure", "// TODO: bs.Lines", "if", "extended", "{", "bs", ".", "Extended", "=", "true", "\n\n", "bs", ".", "Disposition", ",", "bs", ".", "DispositionParams", ",", "_", "=", "e", ".", "Header", ".", "ContentDisposition", "(", ")", "\n\n", "// TODO: bs.Language, bs.Location", "// TODO: bs.MD5", "}", "\n\n", "return", "bs", ",", "nil", "\n", "}" ]
// FetchBodyStructure computes a message's body structure from its content.
[ "FetchBodyStructure", "computes", "a", "message", "s", "body", "structure", "from", "its", "content", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/backend/backendutil/bodystructure.go#L12-L60
148,207
emersion/go-imap
backend/backendutil/body.go
FetchBodySection
func FetchBodySection(e *message.Entity, section *imap.BodySectionName) (imap.Literal, error) { // First, find the requested part using the provided path for i := 0; i < len(section.Path); i++ { n := section.Path[i] mr := e.MultipartReader() if mr == nil { return nil, errNoSuchPart } for j := 1; j <= n; j++ { p, err := mr.NextPart() if err == io.EOF { return nil, errNoSuchPart } else if err != nil { return nil, err } if j == n { e = p break } } } // Then, write the requested data to a buffer b := new(bytes.Buffer) // Write the header mw, err := message.CreateWriter(b, e.Header) if err != nil { return nil, err } defer mw.Close() switch section.Specifier { case imap.TextSpecifier: // The header hasn't been requested. Discard it. b.Reset() case imap.EntireSpecifier: if len(section.Path) > 0 { // When selecting a specific part by index, IMAP servers // return only the text, not the associated MIME header. b.Reset() } } // Write the body, if requested switch section.Specifier { case imap.EntireSpecifier, imap.TextSpecifier: if _, err := io.Copy(mw, e.Body); err != nil { return nil, err } } var l imap.Literal = b if section.Partial != nil { l = bytes.NewReader(section.ExtractPartial(b.Bytes())) } return l, nil }
go
func FetchBodySection(e *message.Entity, section *imap.BodySectionName) (imap.Literal, error) { // First, find the requested part using the provided path for i := 0; i < len(section.Path); i++ { n := section.Path[i] mr := e.MultipartReader() if mr == nil { return nil, errNoSuchPart } for j := 1; j <= n; j++ { p, err := mr.NextPart() if err == io.EOF { return nil, errNoSuchPart } else if err != nil { return nil, err } if j == n { e = p break } } } // Then, write the requested data to a buffer b := new(bytes.Buffer) // Write the header mw, err := message.CreateWriter(b, e.Header) if err != nil { return nil, err } defer mw.Close() switch section.Specifier { case imap.TextSpecifier: // The header hasn't been requested. Discard it. b.Reset() case imap.EntireSpecifier: if len(section.Path) > 0 { // When selecting a specific part by index, IMAP servers // return only the text, not the associated MIME header. b.Reset() } } // Write the body, if requested switch section.Specifier { case imap.EntireSpecifier, imap.TextSpecifier: if _, err := io.Copy(mw, e.Body); err != nil { return nil, err } } var l imap.Literal = b if section.Partial != nil { l = bytes.NewReader(section.ExtractPartial(b.Bytes())) } return l, nil }
[ "func", "FetchBodySection", "(", "e", "*", "message", ".", "Entity", ",", "section", "*", "imap", ".", "BodySectionName", ")", "(", "imap", ".", "Literal", ",", "error", ")", "{", "// First, find the requested part using the provided path", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "section", ".", "Path", ")", ";", "i", "++", "{", "n", ":=", "section", ".", "Path", "[", "i", "]", "\n\n", "mr", ":=", "e", ".", "MultipartReader", "(", ")", "\n", "if", "mr", "==", "nil", "{", "return", "nil", ",", "errNoSuchPart", "\n", "}", "\n\n", "for", "j", ":=", "1", ";", "j", "<=", "n", ";", "j", "++", "{", "p", ",", "err", ":=", "mr", ".", "NextPart", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", ",", "errNoSuchPart", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "j", "==", "n", "{", "e", "=", "p", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Then, write the requested data to a buffer", "b", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "// Write the header", "mw", ",", "err", ":=", "message", ".", "CreateWriter", "(", "b", ",", "e", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "mw", ".", "Close", "(", ")", "\n\n", "switch", "section", ".", "Specifier", "{", "case", "imap", ".", "TextSpecifier", ":", "// The header hasn't been requested. Discard it.", "b", ".", "Reset", "(", ")", "\n", "case", "imap", ".", "EntireSpecifier", ":", "if", "len", "(", "section", ".", "Path", ")", ">", "0", "{", "// When selecting a specific part by index, IMAP servers", "// return only the text, not the associated MIME header.", "b", ".", "Reset", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Write the body, if requested", "switch", "section", ".", "Specifier", "{", "case", "imap", ".", "EntireSpecifier", ",", "imap", ".", "TextSpecifier", ":", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "mw", ",", "e", ".", "Body", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "var", "l", "imap", ".", "Literal", "=", "b", "\n", "if", "section", ".", "Partial", "!=", "nil", "{", "l", "=", "bytes", ".", "NewReader", "(", "section", ".", "ExtractPartial", "(", "b", ".", "Bytes", "(", ")", ")", ")", "\n", "}", "\n", "return", "l", ",", "nil", "\n", "}" ]
// FetchBodySection extracts a body section from a message.
[ "FetchBodySection", "extracts", "a", "body", "section", "from", "a", "message", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/backend/backendutil/body.go#L15-L75
148,208
emersion/go-imap
read.go
ParseNumber
func ParseNumber(f interface{}) (uint32, error) { // Useful for tests if n, ok := f.(uint32); ok { return n, nil } s, ok := f.(string) if !ok { return 0, newParseError("expected a number, got a non-atom") } nbr, err := strconv.ParseUint(s, 10, 32) if err != nil { return 0, &parseError{err} } return uint32(nbr), nil }
go
func ParseNumber(f interface{}) (uint32, error) { // Useful for tests if n, ok := f.(uint32); ok { return n, nil } s, ok := f.(string) if !ok { return 0, newParseError("expected a number, got a non-atom") } nbr, err := strconv.ParseUint(s, 10, 32) if err != nil { return 0, &parseError{err} } return uint32(nbr), nil }
[ "func", "ParseNumber", "(", "f", "interface", "{", "}", ")", "(", "uint32", ",", "error", ")", "{", "// Useful for tests", "if", "n", ",", "ok", ":=", "f", ".", "(", "uint32", ")", ";", "ok", "{", "return", "n", ",", "nil", "\n", "}", "\n\n", "s", ",", "ok", ":=", "f", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "0", ",", "newParseError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "nbr", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "&", "parseError", "{", "err", "}", "\n", "}", "\n\n", "return", "uint32", "(", "nbr", ")", ",", "nil", "\n", "}" ]
// ParseNumber parses a number.
[ "ParseNumber", "parses", "a", "number", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/read.go#L66-L83
148,209
emersion/go-imap
read.go
ParseString
func ParseString(f interface{}) (string, error) { if s, ok := f.(string); ok { return s, nil } // Useful for tests if q, ok := f.(Quoted); ok { return string(q), nil } if a, ok := f.(Atom); ok { return string(a), nil } if l, ok := f.(Literal); ok { b := make([]byte, l.Len()) if _, err := io.ReadFull(l, b); err != nil { return "", err } return string(b), nil } return "", newParseError("expected a string") }
go
func ParseString(f interface{}) (string, error) { if s, ok := f.(string); ok { return s, nil } // Useful for tests if q, ok := f.(Quoted); ok { return string(q), nil } if a, ok := f.(Atom); ok { return string(a), nil } if l, ok := f.(Literal); ok { b := make([]byte, l.Len()) if _, err := io.ReadFull(l, b); err != nil { return "", err } return string(b), nil } return "", newParseError("expected a string") }
[ "func", "ParseString", "(", "f", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "if", "s", ",", "ok", ":=", "f", ".", "(", "string", ")", ";", "ok", "{", "return", "s", ",", "nil", "\n", "}", "\n\n", "// Useful for tests", "if", "q", ",", "ok", ":=", "f", ".", "(", "Quoted", ")", ";", "ok", "{", "return", "string", "(", "q", ")", ",", "nil", "\n", "}", "\n", "if", "a", ",", "ok", ":=", "f", ".", "(", "Atom", ")", ";", "ok", "{", "return", "string", "(", "a", ")", ",", "nil", "\n", "}", "\n\n", "if", "l", ",", "ok", ":=", "f", ".", "(", "Literal", ")", ";", "ok", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "l", ".", "Len", "(", ")", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "l", ",", "b", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "b", ")", ",", "nil", "\n", "}", "\n\n", "return", "\"", "\"", ",", "newParseError", "(", "\"", "\"", ")", "\n", "}" ]
// ParseString parses a string, which is either a literal, a quoted string or an // atom.
[ "ParseString", "parses", "a", "string", "which", "is", "either", "a", "literal", "a", "quoted", "string", "or", "an", "atom", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/read.go#L87-L109
148,210
emersion/go-imap
read.go
ParseStringList
func ParseStringList(f interface{}) ([]string, error) { fields, ok := f.([]interface{}) if !ok { return nil, newParseError("expected a string list, got a non-list") } list := make([]string, len(fields)) for i, f := range fields { var err error if list[i], err = ParseString(f); err != nil { return nil, newParseError("cannot parse string in string list: " + err.Error()) } } return list, nil }
go
func ParseStringList(f interface{}) ([]string, error) { fields, ok := f.([]interface{}) if !ok { return nil, newParseError("expected a string list, got a non-list") } list := make([]string, len(fields)) for i, f := range fields { var err error if list[i], err = ParseString(f); err != nil { return nil, newParseError("cannot parse string in string list: " + err.Error()) } } return list, nil }
[ "func", "ParseStringList", "(", "f", "interface", "{", "}", ")", "(", "[", "]", "string", ",", "error", ")", "{", "fields", ",", "ok", ":=", "f", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "newParseError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "list", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "fields", ")", ")", "\n", "for", "i", ",", "f", ":=", "range", "fields", "{", "var", "err", "error", "\n", "if", "list", "[", "i", "]", ",", "err", "=", "ParseString", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "newParseError", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "list", ",", "nil", "\n", "}" ]
// Convert a field list to a string list.
[ "Convert", "a", "field", "list", "to", "a", "string", "list", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/read.go#L112-L126
148,211
alecthomas/chroma
formatters/api.go
Names
func Names() []string { out := []string{} for name := range Registry { out = append(out, name) } sort.Strings(out) return out }
go
func Names() []string { out := []string{} for name := range Registry { out = append(out, name) } sort.Strings(out) return out }
[ "func", "Names", "(", ")", "[", "]", "string", "{", "out", ":=", "[", "]", "string", "{", "}", "\n", "for", "name", ":=", "range", "Registry", "{", "out", "=", "append", "(", "out", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// Names of registered formatters.
[ "Names", "of", "registered", "formatters", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/api.go#L32-L39
148,212
alecthomas/chroma
formatters/api.go
Get
func Get(name string) chroma.Formatter { if f, ok := Registry[name]; ok { return f } return Fallback }
go
func Get(name string) chroma.Formatter { if f, ok := Registry[name]; ok { return f } return Fallback }
[ "func", "Get", "(", "name", "string", ")", "chroma", ".", "Formatter", "{", "if", "f", ",", "ok", ":=", "Registry", "[", "name", "]", ";", "ok", "{", "return", "f", "\n", "}", "\n", "return", "Fallback", "\n", "}" ]
// Get formatter by name. // // If the given formatter is not found, the Fallback formatter will be returned.
[ "Get", "formatter", "by", "name", ".", "If", "the", "given", "formatter", "is", "not", "found", "the", "Fallback", "formatter", "will", "be", "returned", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/api.go#L44-L49
148,213
alecthomas/chroma
formatters/api.go
Register
func Register(name string, formatter chroma.Formatter) chroma.Formatter { Registry[name] = formatter return formatter }
go
func Register(name string, formatter chroma.Formatter) chroma.Formatter { Registry[name] = formatter return formatter }
[ "func", "Register", "(", "name", "string", ",", "formatter", "chroma", ".", "Formatter", ")", "chroma", ".", "Formatter", "{", "Registry", "[", "name", "]", "=", "formatter", "\n", "return", "formatter", "\n", "}" ]
// Register a named formatter.
[ "Register", "a", "named", "formatter", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/api.go#L52-L55
148,214
alecthomas/chroma
style.go
Prefix
func (t Trilean) Prefix(s string) string { if t == Yes { return s } else if t == No { return "no" + s } return "" }
go
func (t Trilean) Prefix(s string) string { if t == Yes { return s } else if t == No { return "no" + s } return "" }
[ "func", "(", "t", "Trilean", ")", "Prefix", "(", "s", "string", ")", "string", "{", "if", "t", "==", "Yes", "{", "return", "s", "\n", "}", "else", "if", "t", "==", "No", "{", "return", "\"", "\"", "+", "s", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Prefix returns s with "no" as a prefix if Trilean is no.
[ "Prefix", "returns", "s", "with", "no", "as", "a", "prefix", "if", "Trilean", "is", "no", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L30-L37
148,215
alecthomas/chroma
style.go
Sub
func (s StyleEntry) Sub(e StyleEntry) StyleEntry { out := StyleEntry{} if e.Colour != s.Colour { out.Colour = s.Colour } if e.Background != s.Background { out.Background = s.Background } if e.Bold != s.Bold { out.Bold = s.Bold } if e.Italic != s.Italic { out.Italic = s.Italic } if e.Underline != s.Underline { out.Underline = s.Underline } if e.Border != s.Border { out.Border = s.Border } return out }
go
func (s StyleEntry) Sub(e StyleEntry) StyleEntry { out := StyleEntry{} if e.Colour != s.Colour { out.Colour = s.Colour } if e.Background != s.Background { out.Background = s.Background } if e.Bold != s.Bold { out.Bold = s.Bold } if e.Italic != s.Italic { out.Italic = s.Italic } if e.Underline != s.Underline { out.Underline = s.Underline } if e.Border != s.Border { out.Border = s.Border } return out }
[ "func", "(", "s", "StyleEntry", ")", "Sub", "(", "e", "StyleEntry", ")", "StyleEntry", "{", "out", ":=", "StyleEntry", "{", "}", "\n", "if", "e", ".", "Colour", "!=", "s", ".", "Colour", "{", "out", ".", "Colour", "=", "s", ".", "Colour", "\n", "}", "\n", "if", "e", ".", "Background", "!=", "s", ".", "Background", "{", "out", ".", "Background", "=", "s", ".", "Background", "\n", "}", "\n", "if", "e", ".", "Bold", "!=", "s", ".", "Bold", "{", "out", ".", "Bold", "=", "s", ".", "Bold", "\n", "}", "\n", "if", "e", ".", "Italic", "!=", "s", ".", "Italic", "{", "out", ".", "Italic", "=", "s", ".", "Italic", "\n", "}", "\n", "if", "e", ".", "Underline", "!=", "s", ".", "Underline", "{", "out", ".", "Underline", "=", "s", ".", "Underline", "\n", "}", "\n", "if", "e", ".", "Border", "!=", "s", ".", "Border", "{", "out", ".", "Border", "=", "s", ".", "Border", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Sub subtracts e from s where elements match.
[ "Sub", "subtracts", "e", "from", "s", "where", "elements", "match", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L79-L100
148,216
alecthomas/chroma
style.go
Inherit
func (s StyleEntry) Inherit(ancestors ...StyleEntry) StyleEntry { out := s for i := len(ancestors) - 1; i >= 0; i-- { if out.NoInherit { return out } ancestor := ancestors[i] if !out.Colour.IsSet() { out.Colour = ancestor.Colour } if !out.Background.IsSet() { out.Background = ancestor.Background } if !out.Border.IsSet() { out.Border = ancestor.Border } if out.Bold == Pass { out.Bold = ancestor.Bold } if out.Italic == Pass { out.Italic = ancestor.Italic } if out.Underline == Pass { out.Underline = ancestor.Underline } } return out }
go
func (s StyleEntry) Inherit(ancestors ...StyleEntry) StyleEntry { out := s for i := len(ancestors) - 1; i >= 0; i-- { if out.NoInherit { return out } ancestor := ancestors[i] if !out.Colour.IsSet() { out.Colour = ancestor.Colour } if !out.Background.IsSet() { out.Background = ancestor.Background } if !out.Border.IsSet() { out.Border = ancestor.Border } if out.Bold == Pass { out.Bold = ancestor.Bold } if out.Italic == Pass { out.Italic = ancestor.Italic } if out.Underline == Pass { out.Underline = ancestor.Underline } } return out }
[ "func", "(", "s", "StyleEntry", ")", "Inherit", "(", "ancestors", "...", "StyleEntry", ")", "StyleEntry", "{", "out", ":=", "s", "\n", "for", "i", ":=", "len", "(", "ancestors", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "out", ".", "NoInherit", "{", "return", "out", "\n", "}", "\n", "ancestor", ":=", "ancestors", "[", "i", "]", "\n", "if", "!", "out", ".", "Colour", ".", "IsSet", "(", ")", "{", "out", ".", "Colour", "=", "ancestor", ".", "Colour", "\n", "}", "\n", "if", "!", "out", ".", "Background", ".", "IsSet", "(", ")", "{", "out", ".", "Background", "=", "ancestor", ".", "Background", "\n", "}", "\n", "if", "!", "out", ".", "Border", ".", "IsSet", "(", ")", "{", "out", ".", "Border", "=", "ancestor", ".", "Border", "\n", "}", "\n", "if", "out", ".", "Bold", "==", "Pass", "{", "out", ".", "Bold", "=", "ancestor", ".", "Bold", "\n", "}", "\n", "if", "out", ".", "Italic", "==", "Pass", "{", "out", ".", "Italic", "=", "ancestor", ".", "Italic", "\n", "}", "\n", "if", "out", ".", "Underline", "==", "Pass", "{", "out", ".", "Underline", "=", "ancestor", ".", "Underline", "\n", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Inherit styles from ancestors. // // Ancestors should be provided from oldest to newest.
[ "Inherit", "styles", "from", "ancestors", ".", "Ancestors", "should", "be", "provided", "from", "oldest", "to", "newest", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L105-L132
148,217
alecthomas/chroma
style.go
NewStyle
func NewStyle(name string, entries StyleEntries) (*Style, error) { return NewStyleBuilder(name).AddAll(entries).Build() }
go
func NewStyle(name string, entries StyleEntries) (*Style, error) { return NewStyleBuilder(name).AddAll(entries).Build() }
[ "func", "NewStyle", "(", "name", "string", ",", "entries", "StyleEntries", ")", "(", "*", "Style", ",", "error", ")", "{", "return", "NewStyleBuilder", "(", "name", ")", ".", "AddAll", "(", "entries", ")", ".", "Build", "(", ")", "\n", "}" ]
// NewStyle creates a new style definition.
[ "NewStyle", "creates", "a", "new", "style", "definition", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L198-L200
148,218
alecthomas/chroma
style.go
MustNewStyle
func MustNewStyle(name string, entries StyleEntries) *Style { style, err := NewStyle(name, entries) if err != nil { panic(err) } return style }
go
func MustNewStyle(name string, entries StyleEntries) *Style { style, err := NewStyle(name, entries) if err != nil { panic(err) } return style }
[ "func", "MustNewStyle", "(", "name", "string", ",", "entries", "StyleEntries", ")", "*", "Style", "{", "style", ",", "err", ":=", "NewStyle", "(", "name", ",", "entries", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "style", "\n", "}" ]
// MustNewStyle creates a new style or panics.
[ "MustNewStyle", "creates", "a", "new", "style", "or", "panics", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L203-L209
148,219
alecthomas/chroma
style.go
Types
func (s *Style) Types() []TokenType { dedupe := map[TokenType]bool{} for tt := range s.entries { dedupe[tt] = true } if s.parent != nil { for _, tt := range s.parent.Types() { dedupe[tt] = true } } out := make([]TokenType, 0, len(dedupe)) for tt := range dedupe { out = append(out, tt) } return out }
go
func (s *Style) Types() []TokenType { dedupe := map[TokenType]bool{} for tt := range s.entries { dedupe[tt] = true } if s.parent != nil { for _, tt := range s.parent.Types() { dedupe[tt] = true } } out := make([]TokenType, 0, len(dedupe)) for tt := range dedupe { out = append(out, tt) } return out }
[ "func", "(", "s", "*", "Style", ")", "Types", "(", ")", "[", "]", "TokenType", "{", "dedupe", ":=", "map", "[", "TokenType", "]", "bool", "{", "}", "\n", "for", "tt", ":=", "range", "s", ".", "entries", "{", "dedupe", "[", "tt", "]", "=", "true", "\n", "}", "\n", "if", "s", ".", "parent", "!=", "nil", "{", "for", "_", ",", "tt", ":=", "range", "s", ".", "parent", ".", "Types", "(", ")", "{", "dedupe", "[", "tt", "]", "=", "true", "\n", "}", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "TokenType", ",", "0", ",", "len", "(", "dedupe", ")", ")", "\n", "for", "tt", ":=", "range", "dedupe", "{", "out", "=", "append", "(", "out", ",", "tt", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Types that are styled.
[ "Types", "that", "are", "styled", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L221-L236
148,220
alecthomas/chroma
style.go
Builder
func (s *Style) Builder() *StyleBuilder { return &StyleBuilder{ name: s.Name, entries: map[TokenType]string{}, parent: s, } }
go
func (s *Style) Builder() *StyleBuilder { return &StyleBuilder{ name: s.Name, entries: map[TokenType]string{}, parent: s, } }
[ "func", "(", "s", "*", "Style", ")", "Builder", "(", ")", "*", "StyleBuilder", "{", "return", "&", "StyleBuilder", "{", "name", ":", "s", ".", "Name", ",", "entries", ":", "map", "[", "TokenType", "]", "string", "{", "}", ",", "parent", ":", "s", ",", "}", "\n", "}" ]
// Builder creates a mutable builder from this Style. // // The builder can then be safely modified. This is a cheap operation.
[ "Builder", "creates", "a", "mutable", "builder", "from", "this", "Style", ".", "The", "builder", "can", "then", "be", "safely", "modified", ".", "This", "is", "a", "cheap", "operation", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L241-L247
148,221
alecthomas/chroma
style.go
Get
func (s *Style) Get(ttype TokenType) StyleEntry { return s.get(ttype).Inherit( s.get(Background), s.get(Text), s.get(ttype.Category()), s.get(ttype.SubCategory())) }
go
func (s *Style) Get(ttype TokenType) StyleEntry { return s.get(ttype).Inherit( s.get(Background), s.get(Text), s.get(ttype.Category()), s.get(ttype.SubCategory())) }
[ "func", "(", "s", "*", "Style", ")", "Get", "(", "ttype", "TokenType", ")", "StyleEntry", "{", "return", "s", ".", "get", "(", "ttype", ")", ".", "Inherit", "(", "s", ".", "get", "(", "Background", ")", ",", "s", ".", "get", "(", "Text", ")", ",", "s", ".", "get", "(", "ttype", ".", "Category", "(", ")", ")", ",", "s", ".", "get", "(", "ttype", ".", "SubCategory", "(", ")", ")", ")", "\n", "}" ]
// Get a style entry. Will try sub-category or category if an exact match is not found, and // finally return the Background.
[ "Get", "a", "style", "entry", ".", "Will", "try", "sub", "-", "category", "or", "category", "if", "an", "exact", "match", "is", "not", "found", "and", "finally", "return", "the", "Background", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L258-L264
148,222
alecthomas/chroma
style.go
ParseStyleEntry
func ParseStyleEntry(entry string) (StyleEntry, error) { // nolint: gocyclo out := StyleEntry{} parts := strings.Fields(entry) for _, part := range parts { switch { case part == "italic": out.Italic = Yes case part == "noitalic": out.Italic = No case part == "bold": out.Bold = Yes case part == "nobold": out.Bold = No case part == "underline": out.Underline = Yes case part == "nounderline": out.Underline = No case part == "inherit": out.NoInherit = false case part == "noinherit": out.NoInherit = true case part == "bg:": out.Background = 0 case strings.HasPrefix(part, "bg:#"): out.Background = ParseColour(part[3:]) if !out.Background.IsSet() { return StyleEntry{}, fmt.Errorf("invalid background colour %q", part) } case strings.HasPrefix(part, "border:#"): out.Border = ParseColour(part[7:]) if !out.Border.IsSet() { return StyleEntry{}, fmt.Errorf("invalid border colour %q", part) } case strings.HasPrefix(part, "#"): out.Colour = ParseColour(part) if !out.Colour.IsSet() { return StyleEntry{}, fmt.Errorf("invalid colour %q", part) } default: return StyleEntry{}, fmt.Errorf("unknown style element %q", part) } } return out, nil }
go
func ParseStyleEntry(entry string) (StyleEntry, error) { // nolint: gocyclo out := StyleEntry{} parts := strings.Fields(entry) for _, part := range parts { switch { case part == "italic": out.Italic = Yes case part == "noitalic": out.Italic = No case part == "bold": out.Bold = Yes case part == "nobold": out.Bold = No case part == "underline": out.Underline = Yes case part == "nounderline": out.Underline = No case part == "inherit": out.NoInherit = false case part == "noinherit": out.NoInherit = true case part == "bg:": out.Background = 0 case strings.HasPrefix(part, "bg:#"): out.Background = ParseColour(part[3:]) if !out.Background.IsSet() { return StyleEntry{}, fmt.Errorf("invalid background colour %q", part) } case strings.HasPrefix(part, "border:#"): out.Border = ParseColour(part[7:]) if !out.Border.IsSet() { return StyleEntry{}, fmt.Errorf("invalid border colour %q", part) } case strings.HasPrefix(part, "#"): out.Colour = ParseColour(part) if !out.Colour.IsSet() { return StyleEntry{}, fmt.Errorf("invalid colour %q", part) } default: return StyleEntry{}, fmt.Errorf("unknown style element %q", part) } } return out, nil }
[ "func", "ParseStyleEntry", "(", "entry", "string", ")", "(", "StyleEntry", ",", "error", ")", "{", "// nolint: gocyclo", "out", ":=", "StyleEntry", "{", "}", "\n", "parts", ":=", "strings", ".", "Fields", "(", "entry", ")", "\n", "for", "_", ",", "part", ":=", "range", "parts", "{", "switch", "{", "case", "part", "==", "\"", "\"", ":", "out", ".", "Italic", "=", "Yes", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "Italic", "=", "No", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "Bold", "=", "Yes", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "Bold", "=", "No", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "Underline", "=", "Yes", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "Underline", "=", "No", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "NoInherit", "=", "false", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "NoInherit", "=", "true", "\n", "case", "part", "==", "\"", "\"", ":", "out", ".", "Background", "=", "0", "\n", "case", "strings", ".", "HasPrefix", "(", "part", ",", "\"", "\"", ")", ":", "out", ".", "Background", "=", "ParseColour", "(", "part", "[", "3", ":", "]", ")", "\n", "if", "!", "out", ".", "Background", ".", "IsSet", "(", ")", "{", "return", "StyleEntry", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "part", ")", "\n", "}", "\n", "case", "strings", ".", "HasPrefix", "(", "part", ",", "\"", "\"", ")", ":", "out", ".", "Border", "=", "ParseColour", "(", "part", "[", "7", ":", "]", ")", "\n", "if", "!", "out", ".", "Border", ".", "IsSet", "(", ")", "{", "return", "StyleEntry", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "part", ")", "\n", "}", "\n", "case", "strings", ".", "HasPrefix", "(", "part", ",", "\"", "\"", ")", ":", "out", ".", "Colour", "=", "ParseColour", "(", "part", ")", "\n", "if", "!", "out", ".", "Colour", ".", "IsSet", "(", ")", "{", "return", "StyleEntry", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "part", ")", "\n", "}", "\n", "default", ":", "return", "StyleEntry", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "part", ")", "\n", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// ParseStyleEntry parses a Pygments style entry.
[ "ParseStyleEntry", "parses", "a", "Pygments", "style", "entry", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L299-L342
148,223
alecthomas/chroma
styles/api.go
Register
func Register(style *chroma.Style) *chroma.Style { Registry[style.Name] = style return style }
go
func Register(style *chroma.Style) *chroma.Style { Registry[style.Name] = style return style }
[ "func", "Register", "(", "style", "*", "chroma", ".", "Style", ")", "*", "chroma", ".", "Style", "{", "Registry", "[", "style", ".", "Name", "]", "=", "style", "\n", "return", "style", "\n", "}" ]
// Register a chroma.Style.
[ "Register", "a", "chroma", ".", "Style", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/styles/api.go#L16-L19
148,224
alecthomas/chroma
styles/api.go
Get
func Get(name string) *chroma.Style { if style, ok := Registry[name]; ok { return style } return Fallback }
go
func Get(name string) *chroma.Style { if style, ok := Registry[name]; ok { return style } return Fallback }
[ "func", "Get", "(", "name", "string", ")", "*", "chroma", ".", "Style", "{", "if", "style", ",", "ok", ":=", "Registry", "[", "name", "]", ";", "ok", "{", "return", "style", "\n", "}", "\n", "return", "Fallback", "\n", "}" ]
// Get named style, or Fallback.
[ "Get", "named", "style", "or", "Fallback", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/styles/api.go#L32-L37
148,225
alecthomas/chroma
colour.go
NewColour
func NewColour(r, g, b uint8) Colour { return ParseColour(fmt.Sprintf("%02x%02x%02x", r, g, b)) }
go
func NewColour(r, g, b uint8) Colour { return ParseColour(fmt.Sprintf("%02x%02x%02x", r, g, b)) }
[ "func", "NewColour", "(", "r", ",", "g", ",", "b", "uint8", ")", "Colour", "{", "return", "ParseColour", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ",", "g", ",", "b", ")", ")", "\n", "}" ]
// NewColour creates a Colour directly from RGB values.
[ "NewColour", "creates", "a", "Colour", "directly", "from", "RGB", "values", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/colour.go#L54-L56
148,226
alecthomas/chroma
colour.go
MustParseColour
func MustParseColour(colour string) Colour { parsed := ParseColour(colour) if !parsed.IsSet() { panic(fmt.Errorf("invalid colour %q", colour)) } return parsed }
go
func MustParseColour(colour string) Colour { parsed := ParseColour(colour) if !parsed.IsSet() { panic(fmt.Errorf("invalid colour %q", colour)) } return parsed }
[ "func", "MustParseColour", "(", "colour", "string", ")", "Colour", "{", "parsed", ":=", "ParseColour", "(", "colour", ")", "\n", "if", "!", "parsed", ".", "IsSet", "(", ")", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "colour", ")", ")", "\n", "}", "\n", "return", "parsed", "\n", "}" ]
// MustParseColour is like ParseColour except it panics if the colour is invalid. // // Will panic if colour is in an invalid format.
[ "MustParseColour", "is", "like", "ParseColour", "except", "it", "panics", "if", "the", "colour", "is", "invalid", ".", "Will", "panic", "if", "colour", "is", "in", "an", "invalid", "format", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/colour.go#L122-L128
148,227
alecthomas/chroma
formatters/html/html.go
HighlightLines
func HighlightLines(ranges [][2]int) Option { return func(f *Formatter) { f.highlightRanges = ranges sort.Sort(f.highlightRanges) } }
go
func HighlightLines(ranges [][2]int) Option { return func(f *Formatter) { f.highlightRanges = ranges sort.Sort(f.highlightRanges) } }
[ "func", "HighlightLines", "(", "ranges", "[", "]", "[", "2", "]", "int", ")", "Option", "{", "return", "func", "(", "f", "*", "Formatter", ")", "{", "f", ".", "highlightRanges", "=", "ranges", "\n", "sort", ".", "Sort", "(", "f", ".", "highlightRanges", ")", "\n", "}", "\n", "}" ]
// HighlightLines higlights the given line ranges with the Highlight style. // // A range is the beginning and ending of a range as 1-based line numbers, inclusive.
[ "HighlightLines", "higlights", "the", "given", "line", "ranges", "with", "the", "Highlight", "style", ".", "A", "range", "is", "the", "beginning", "and", "ending", "of", "a", "range", "as", "1", "-", "based", "line", "numbers", "inclusive", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/html/html.go#L49-L54
148,228
alecthomas/chroma
formatters/html/html.go
New
func New(options ...Option) *Formatter { f := &Formatter{ baseLineNumber: 1, } for _, option := range options { option(f) } return f }
go
func New(options ...Option) *Formatter { f := &Formatter{ baseLineNumber: 1, } for _, option := range options { option(f) } return f }
[ "func", "New", "(", "options", "...", "Option", ")", "*", "Formatter", "{", "f", ":=", "&", "Formatter", "{", "baseLineNumber", ":", "1", ",", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "f", ")", "\n", "}", "\n", "return", "f", "\n", "}" ]
// New HTML formatter.
[ "New", "HTML", "formatter", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/html/html.go#L64-L72
148,229
alecthomas/chroma
formatters/html/html.go
StyleEntryToCSS
func StyleEntryToCSS(e chroma.StyleEntry) string { styles := []string{} if e.Colour.IsSet() { styles = append(styles, "color: "+e.Colour.String()) } if e.Background.IsSet() { styles = append(styles, "background-color: "+e.Background.String()) } if e.Bold == chroma.Yes { styles = append(styles, "font-weight: bold") } if e.Italic == chroma.Yes { styles = append(styles, "font-style: italic") } if e.Underline == chroma.Yes { styles = append(styles, "text-decoration: underline") } return strings.Join(styles, "; ") }
go
func StyleEntryToCSS(e chroma.StyleEntry) string { styles := []string{} if e.Colour.IsSet() { styles = append(styles, "color: "+e.Colour.String()) } if e.Background.IsSet() { styles = append(styles, "background-color: "+e.Background.String()) } if e.Bold == chroma.Yes { styles = append(styles, "font-weight: bold") } if e.Italic == chroma.Yes { styles = append(styles, "font-style: italic") } if e.Underline == chroma.Yes { styles = append(styles, "text-decoration: underline") } return strings.Join(styles, "; ") }
[ "func", "StyleEntryToCSS", "(", "e", "chroma", ".", "StyleEntry", ")", "string", "{", "styles", ":=", "[", "]", "string", "{", "}", "\n", "if", "e", ".", "Colour", ".", "IsSet", "(", ")", "{", "styles", "=", "append", "(", "styles", ",", "\"", "\"", "+", "e", ".", "Colour", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "e", ".", "Background", ".", "IsSet", "(", ")", "{", "styles", "=", "append", "(", "styles", ",", "\"", "\"", "+", "e", ".", "Background", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "e", ".", "Bold", "==", "chroma", ".", "Yes", "{", "styles", "=", "append", "(", "styles", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "e", ".", "Italic", "==", "chroma", ".", "Yes", "{", "styles", "=", "append", "(", "styles", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "e", ".", "Underline", "==", "chroma", ".", "Yes", "{", "styles", "=", "append", "(", "styles", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "styles", ",", "\"", "\"", ")", "\n", "}" ]
// StyleEntryToCSS converts a chroma.StyleEntry to CSS attributes.
[ "StyleEntryToCSS", "converts", "a", "chroma", ".", "StyleEntry", "to", "CSS", "attributes", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/html/html.go#L328-L346
148,230
alecthomas/chroma
formatters/html/html.go
compressStyle
func compressStyle(s string) string { parts := strings.Split(s, ";") out := []string{} for _, p := range parts { p = strings.Join(strings.Fields(p), " ") p = strings.Replace(p, ": ", ":", 1) if strings.Contains(p, "#") { c := p[len(p)-6:] if c[0] == c[1] && c[2] == c[3] && c[4] == c[5] { p = p[:len(p)-6] + c[0:1] + c[2:3] + c[4:5] } } out = append(out, p) } return strings.Join(out, ";") }
go
func compressStyle(s string) string { parts := strings.Split(s, ";") out := []string{} for _, p := range parts { p = strings.Join(strings.Fields(p), " ") p = strings.Replace(p, ": ", ":", 1) if strings.Contains(p, "#") { c := p[len(p)-6:] if c[0] == c[1] && c[2] == c[3] && c[4] == c[5] { p = p[:len(p)-6] + c[0:1] + c[2:3] + c[4:5] } } out = append(out, p) } return strings.Join(out, ";") }
[ "func", "compressStyle", "(", "s", "string", ")", "string", "{", "parts", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "out", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "p", ":=", "range", "parts", "{", "p", "=", "strings", ".", "Join", "(", "strings", ".", "Fields", "(", "p", ")", ",", "\"", "\"", ")", "\n", "p", "=", "strings", ".", "Replace", "(", "p", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", "\n", "if", "strings", ".", "Contains", "(", "p", ",", "\"", "\"", ")", "{", "c", ":=", "p", "[", "len", "(", "p", ")", "-", "6", ":", "]", "\n", "if", "c", "[", "0", "]", "==", "c", "[", "1", "]", "&&", "c", "[", "2", "]", "==", "c", "[", "3", "]", "&&", "c", "[", "4", "]", "==", "c", "[", "5", "]", "{", "p", "=", "p", "[", ":", "len", "(", "p", ")", "-", "6", "]", "+", "c", "[", "0", ":", "1", "]", "+", "c", "[", "2", ":", "3", "]", "+", "c", "[", "4", ":", "5", "]", "\n", "}", "\n", "}", "\n", "out", "=", "append", "(", "out", ",", "p", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "out", ",", "\"", "\"", ")", "\n", "}" ]
// Compress CSS attributes - remove spaces, transform 6-digit colours to 3.
[ "Compress", "CSS", "attributes", "-", "remove", "spaces", "transform", "6", "-", "digit", "colours", "to", "3", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/html/html.go#L349-L364
148,231
alecthomas/chroma
remap.go
RemappingLexer
func RemappingLexer(lexer Lexer, mapper func(Token) []Token) Lexer { return &remappingLexer{lexer, mapper} }
go
func RemappingLexer(lexer Lexer, mapper func(Token) []Token) Lexer { return &remappingLexer{lexer, mapper} }
[ "func", "RemappingLexer", "(", "lexer", "Lexer", ",", "mapper", "func", "(", "Token", ")", "[", "]", "Token", ")", "Lexer", "{", "return", "&", "remappingLexer", "{", "lexer", ",", "mapper", "}", "\n", "}" ]
// RemappingLexer remaps a token to a set of, potentially empty, tokens.
[ "RemappingLexer", "remaps", "a", "token", "to", "a", "set", "of", "potentially", "empty", "tokens", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/remap.go#L9-L11
148,232
alecthomas/chroma
regexp.go
ByGroups
func ByGroups(emitters ...Emitter) Emitter { return EmitterFunc(func(groups []string, lexer Lexer) Iterator { iterators := make([]Iterator, 0, len(groups)-1) // NOTE: If this panics, there is a mismatch with groups for i, group := range groups[1:] { iterators = append(iterators, emitters[i].Emit([]string{group}, lexer)) } return Concaterator(iterators...) }) }
go
func ByGroups(emitters ...Emitter) Emitter { return EmitterFunc(func(groups []string, lexer Lexer) Iterator { iterators := make([]Iterator, 0, len(groups)-1) // NOTE: If this panics, there is a mismatch with groups for i, group := range groups[1:] { iterators = append(iterators, emitters[i].Emit([]string{group}, lexer)) } return Concaterator(iterators...) }) }
[ "func", "ByGroups", "(", "emitters", "...", "Emitter", ")", "Emitter", "{", "return", "EmitterFunc", "(", "func", "(", "groups", "[", "]", "string", ",", "lexer", "Lexer", ")", "Iterator", "{", "iterators", ":=", "make", "(", "[", "]", "Iterator", ",", "0", ",", "len", "(", "groups", ")", "-", "1", ")", "\n", "// NOTE: If this panics, there is a mismatch with groups", "for", "i", ",", "group", ":=", "range", "groups", "[", "1", ":", "]", "{", "iterators", "=", "append", "(", "iterators", ",", "emitters", "[", "i", "]", ".", "Emit", "(", "[", "]", "string", "{", "group", "}", ",", "lexer", ")", ")", "\n", "}", "\n", "return", "Concaterator", "(", "iterators", "...", ")", "\n", "}", ")", "\n", "}" ]
// ByGroups emits a token for each matching group in the rule's regex.
[ "ByGroups", "emits", "a", "token", "for", "each", "matching", "group", "in", "the", "rule", "s", "regex", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L34-L43
148,233
alecthomas/chroma
regexp.go
Using
func Using(lexer Lexer) Emitter { return EmitterFunc(func(groups []string, _ Lexer) Iterator { it, err := lexer.Tokenise(&TokeniseOptions{State: "root", Nested: true}, groups[0]) if err != nil { panic(err) } return it }) }
go
func Using(lexer Lexer) Emitter { return EmitterFunc(func(groups []string, _ Lexer) Iterator { it, err := lexer.Tokenise(&TokeniseOptions{State: "root", Nested: true}, groups[0]) if err != nil { panic(err) } return it }) }
[ "func", "Using", "(", "lexer", "Lexer", ")", "Emitter", "{", "return", "EmitterFunc", "(", "func", "(", "groups", "[", "]", "string", ",", "_", "Lexer", ")", "Iterator", "{", "it", ",", "err", ":=", "lexer", ".", "Tokenise", "(", "&", "TokeniseOptions", "{", "State", ":", "\"", "\"", ",", "Nested", ":", "true", "}", ",", "groups", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "it", "\n", "}", ")", "\n", "}" ]
// Using returns an Emitter that uses a given Lexer for parsing and emitting.
[ "Using", "returns", "an", "Emitter", "that", "uses", "a", "given", "Lexer", "for", "parsing", "and", "emitting", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L114-L122
148,234
alecthomas/chroma
regexp.go
Words
func Words(prefix, suffix string, words ...string) string { for i, word := range words { words[i] = regexp.QuoteMeta(word) } return prefix + `(` + strings.Join(words, `|`) + `)` + suffix }
go
func Words(prefix, suffix string, words ...string) string { for i, word := range words { words[i] = regexp.QuoteMeta(word) } return prefix + `(` + strings.Join(words, `|`) + `)` + suffix }
[ "func", "Words", "(", "prefix", ",", "suffix", "string", ",", "words", "...", "string", ")", "string", "{", "for", "i", ",", "word", ":=", "range", "words", "{", "words", "[", "i", "]", "=", "regexp", ".", "QuoteMeta", "(", "word", ")", "\n", "}", "\n", "return", "prefix", "+", "`(`", "+", "strings", ".", "Join", "(", "words", ",", "`|`", ")", "+", "`)`", "+", "suffix", "\n", "}" ]
// Words creates a regex that matches any of the given literal words.
[ "Words", "creates", "a", "regex", "that", "matches", "any", "of", "the", "given", "literal", "words", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L136-L141
148,235
alecthomas/chroma
regexp.go
Tokenise
func Tokenise(lexer Lexer, options *TokeniseOptions, text string) ([]Token, error) { var out []Token it, err := lexer.Tokenise(options, text) if err != nil { return nil, err } for t := it(); t != EOF; t = it() { out = append(out, t) } return out, nil }
go
func Tokenise(lexer Lexer, options *TokeniseOptions, text string) ([]Token, error) { var out []Token it, err := lexer.Tokenise(options, text) if err != nil { return nil, err } for t := it(); t != EOF; t = it() { out = append(out, t) } return out, nil }
[ "func", "Tokenise", "(", "lexer", "Lexer", ",", "options", "*", "TokeniseOptions", ",", "text", "string", ")", "(", "[", "]", "Token", ",", "error", ")", "{", "var", "out", "[", "]", "Token", "\n", "it", ",", "err", ":=", "lexer", ".", "Tokenise", "(", "options", ",", "text", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "t", ":=", "it", "(", ")", ";", "t", "!=", "EOF", ";", "t", "=", "it", "(", ")", "{", "out", "=", "append", "(", "out", ",", "t", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Tokenise text using lexer, returning tokens as a slice.
[ "Tokenise", "text", "using", "lexer", "returning", "tokens", "as", "a", "slice", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L144-L154
148,236
alecthomas/chroma
regexp.go
Clone
func (r Rules) Clone() Rules { out := map[string][]Rule{} for key, rules := range r { out[key] = make([]Rule, len(rules)) copy(out[key], rules) } return out }
go
func (r Rules) Clone() Rules { out := map[string][]Rule{} for key, rules := range r { out[key] = make([]Rule, len(rules)) copy(out[key], rules) } return out }
[ "func", "(", "r", "Rules", ")", "Clone", "(", ")", "Rules", "{", "out", ":=", "map", "[", "string", "]", "[", "]", "Rule", "{", "}", "\n", "for", "key", ",", "rules", ":=", "range", "r", "{", "out", "[", "key", "]", "=", "make", "(", "[", "]", "Rule", ",", "len", "(", "rules", ")", ")", "\n", "copy", "(", "out", "[", "key", "]", ",", "rules", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Clone returns a clone of the Rules.
[ "Clone", "returns", "a", "clone", "of", "the", "Rules", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L160-L167
148,237
alecthomas/chroma
regexp.go
MustNewLexer
func MustNewLexer(config *Config, rules Rules) *RegexLexer { lexer, err := NewLexer(config, rules) if err != nil { panic(err) } return lexer }
go
func MustNewLexer(config *Config, rules Rules) *RegexLexer { lexer, err := NewLexer(config, rules) if err != nil { panic(err) } return lexer }
[ "func", "MustNewLexer", "(", "config", "*", "Config", ",", "rules", "Rules", ")", "*", "RegexLexer", "{", "lexer", ",", "err", ":=", "NewLexer", "(", "config", ",", "rules", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "lexer", "\n", "}" ]
// MustNewLexer creates a new Lexer or panics.
[ "MustNewLexer", "creates", "a", "new", "Lexer", "or", "panics", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L170-L176
148,238
alecthomas/chroma
regexp.go
NewLexer
func NewLexer(config *Config, rules Rules) (*RegexLexer, error) { if config == nil { config = &Config{} } if _, ok := rules["root"]; !ok { return nil, fmt.Errorf("no \"root\" state") } compiledRules := map[string][]*CompiledRule{} for state, rules := range rules { compiledRules[state] = nil for _, rule := range rules { flags := "" if !config.NotMultiline { flags += "m" } if config.CaseInsensitive { flags += "i" } if config.DotAll { flags += "s" } compiledRules[state] = append(compiledRules[state], &CompiledRule{Rule: rule, flags: flags}) } } return &RegexLexer{ config: config, rules: compiledRules, }, nil }
go
func NewLexer(config *Config, rules Rules) (*RegexLexer, error) { if config == nil { config = &Config{} } if _, ok := rules["root"]; !ok { return nil, fmt.Errorf("no \"root\" state") } compiledRules := map[string][]*CompiledRule{} for state, rules := range rules { compiledRules[state] = nil for _, rule := range rules { flags := "" if !config.NotMultiline { flags += "m" } if config.CaseInsensitive { flags += "i" } if config.DotAll { flags += "s" } compiledRules[state] = append(compiledRules[state], &CompiledRule{Rule: rule, flags: flags}) } } return &RegexLexer{ config: config, rules: compiledRules, }, nil }
[ "func", "NewLexer", "(", "config", "*", "Config", ",", "rules", "Rules", ")", "(", "*", "RegexLexer", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "config", "=", "&", "Config", "{", "}", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "rules", "[", "\"", "\"", "]", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n", "compiledRules", ":=", "map", "[", "string", "]", "[", "]", "*", "CompiledRule", "{", "}", "\n", "for", "state", ",", "rules", ":=", "range", "rules", "{", "compiledRules", "[", "state", "]", "=", "nil", "\n", "for", "_", ",", "rule", ":=", "range", "rules", "{", "flags", ":=", "\"", "\"", "\n", "if", "!", "config", ".", "NotMultiline", "{", "flags", "+=", "\"", "\"", "\n", "}", "\n", "if", "config", ".", "CaseInsensitive", "{", "flags", "+=", "\"", "\"", "\n", "}", "\n", "if", "config", ".", "DotAll", "{", "flags", "+=", "\"", "\"", "\n", "}", "\n", "compiledRules", "[", "state", "]", "=", "append", "(", "compiledRules", "[", "state", "]", ",", "&", "CompiledRule", "{", "Rule", ":", "rule", ",", "flags", ":", "flags", "}", ")", "\n", "}", "\n", "}", "\n", "return", "&", "RegexLexer", "{", "config", ":", "config", ",", "rules", ":", "compiledRules", ",", "}", ",", "nil", "\n", "}" ]
// NewLexer creates a new regex-based Lexer. // // "rules" is a state machine transitition map. Each key is a state. Values are sets of rules // that match input, optionally modify lexer state, and output tokens.
[ "NewLexer", "creates", "a", "new", "regex", "-", "based", "Lexer", ".", "rules", "is", "a", "state", "machine", "transitition", "map", ".", "Each", "key", "is", "a", "state", ".", "Values", "are", "sets", "of", "rules", "that", "match", "input", "optionally", "modify", "lexer", "state", "and", "output", "tokens", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L182-L210
148,239
alecthomas/chroma
regexp.go
Trace
func (r *RegexLexer) Trace(trace bool) *RegexLexer { r.trace = trace return r }
go
func (r *RegexLexer) Trace(trace bool) *RegexLexer { r.trace = trace return r }
[ "func", "(", "r", "*", "RegexLexer", ")", "Trace", "(", "trace", "bool", ")", "*", "RegexLexer", "{", "r", ".", "trace", "=", "trace", "\n", "return", "r", "\n", "}" ]
// Trace enables debug tracing.
[ "Trace", "enables", "debug", "tracing", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L213-L216
148,240
alecthomas/chroma
regexp.go
Iterator
func (l *LexerState) Iterator() Token { for l.Pos < len(l.Text) && len(l.Stack) > 0 { // Exhaust the iterator stack, if any. for len(l.iteratorStack) > 0 { n := len(l.iteratorStack) - 1 t := l.iteratorStack[n]() if t == EOF { l.iteratorStack = l.iteratorStack[:n] continue } return t } l.State = l.Stack[len(l.Stack)-1] if l.Lexer.trace { fmt.Fprintf(os.Stderr, "%s: pos=%d, text=%q\n", l.State, l.Pos, string(l.Text[l.Pos:])) } selectedRule, ok := l.Rules[l.State] if !ok { panic("unknown state " + l.State) } ruleIndex, rule, groups := matchRules(l.Text[l.Pos:], selectedRule) // No match. if groups == nil { // From Pygments :\ // // If the RegexLexer encounters a newline that is flagged as an error token, the stack is // emptied and the lexer continues scanning in the 'root' state. This can help producing // error-tolerant highlighting for erroneous input, e.g. when a single-line string is not // closed. if l.Text[l.Pos] == '\n' && l.State != l.options.State { l.Stack = []string{l.options.State} continue } l.Pos++ return Token{Error, string(l.Text[l.Pos-1 : l.Pos])} } l.Rule = ruleIndex l.Groups = groups l.Pos += utf8.RuneCountInString(groups[0]) if rule.Mutator != nil { if err := rule.Mutator.Mutate(l); err != nil { panic(err) } } if rule.Type != nil { l.iteratorStack = append(l.iteratorStack, rule.Type.Emit(l.Groups, l.Lexer)) } } // Exhaust the IteratorStack, if any. // Duplicate code, but eh. for len(l.iteratorStack) > 0 { n := len(l.iteratorStack) - 1 t := l.iteratorStack[n]() if t == EOF { l.iteratorStack = l.iteratorStack[:n] continue } return t } // If we get to here and we still have text, return it as an error. if l.Pos != len(l.Text) && len(l.Stack) == 0 { value := string(l.Text[l.Pos:]) l.Pos = len(l.Text) return Token{Type: Error, Value: value} } return EOF }
go
func (l *LexerState) Iterator() Token { for l.Pos < len(l.Text) && len(l.Stack) > 0 { // Exhaust the iterator stack, if any. for len(l.iteratorStack) > 0 { n := len(l.iteratorStack) - 1 t := l.iteratorStack[n]() if t == EOF { l.iteratorStack = l.iteratorStack[:n] continue } return t } l.State = l.Stack[len(l.Stack)-1] if l.Lexer.trace { fmt.Fprintf(os.Stderr, "%s: pos=%d, text=%q\n", l.State, l.Pos, string(l.Text[l.Pos:])) } selectedRule, ok := l.Rules[l.State] if !ok { panic("unknown state " + l.State) } ruleIndex, rule, groups := matchRules(l.Text[l.Pos:], selectedRule) // No match. if groups == nil { // From Pygments :\ // // If the RegexLexer encounters a newline that is flagged as an error token, the stack is // emptied and the lexer continues scanning in the 'root' state. This can help producing // error-tolerant highlighting for erroneous input, e.g. when a single-line string is not // closed. if l.Text[l.Pos] == '\n' && l.State != l.options.State { l.Stack = []string{l.options.State} continue } l.Pos++ return Token{Error, string(l.Text[l.Pos-1 : l.Pos])} } l.Rule = ruleIndex l.Groups = groups l.Pos += utf8.RuneCountInString(groups[0]) if rule.Mutator != nil { if err := rule.Mutator.Mutate(l); err != nil { panic(err) } } if rule.Type != nil { l.iteratorStack = append(l.iteratorStack, rule.Type.Emit(l.Groups, l.Lexer)) } } // Exhaust the IteratorStack, if any. // Duplicate code, but eh. for len(l.iteratorStack) > 0 { n := len(l.iteratorStack) - 1 t := l.iteratorStack[n]() if t == EOF { l.iteratorStack = l.iteratorStack[:n] continue } return t } // If we get to here and we still have text, return it as an error. if l.Pos != len(l.Text) && len(l.Stack) == 0 { value := string(l.Text[l.Pos:]) l.Pos = len(l.Text) return Token{Type: Error, Value: value} } return EOF }
[ "func", "(", "l", "*", "LexerState", ")", "Iterator", "(", ")", "Token", "{", "for", "l", ".", "Pos", "<", "len", "(", "l", ".", "Text", ")", "&&", "len", "(", "l", ".", "Stack", ")", ">", "0", "{", "// Exhaust the iterator stack, if any.", "for", "len", "(", "l", ".", "iteratorStack", ")", ">", "0", "{", "n", ":=", "len", "(", "l", ".", "iteratorStack", ")", "-", "1", "\n", "t", ":=", "l", ".", "iteratorStack", "[", "n", "]", "(", ")", "\n", "if", "t", "==", "EOF", "{", "l", ".", "iteratorStack", "=", "l", ".", "iteratorStack", "[", ":", "n", "]", "\n", "continue", "\n", "}", "\n", "return", "t", "\n", "}", "\n\n", "l", ".", "State", "=", "l", ".", "Stack", "[", "len", "(", "l", ".", "Stack", ")", "-", "1", "]", "\n", "if", "l", ".", "Lexer", ".", "trace", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "l", ".", "State", ",", "l", ".", "Pos", ",", "string", "(", "l", ".", "Text", "[", "l", ".", "Pos", ":", "]", ")", ")", "\n", "}", "\n", "selectedRule", ",", "ok", ":=", "l", ".", "Rules", "[", "l", ".", "State", "]", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", "+", "l", ".", "State", ")", "\n", "}", "\n", "ruleIndex", ",", "rule", ",", "groups", ":=", "matchRules", "(", "l", ".", "Text", "[", "l", ".", "Pos", ":", "]", ",", "selectedRule", ")", "\n", "// No match.", "if", "groups", "==", "nil", "{", "// From Pygments :\\", "//", "// If the RegexLexer encounters a newline that is flagged as an error token, the stack is", "// emptied and the lexer continues scanning in the 'root' state. This can help producing", "// error-tolerant highlighting for erroneous input, e.g. when a single-line string is not", "// closed.", "if", "l", ".", "Text", "[", "l", ".", "Pos", "]", "==", "'\\n'", "&&", "l", ".", "State", "!=", "l", ".", "options", ".", "State", "{", "l", ".", "Stack", "=", "[", "]", "string", "{", "l", ".", "options", ".", "State", "}", "\n", "continue", "\n", "}", "\n", "l", ".", "Pos", "++", "\n", "return", "Token", "{", "Error", ",", "string", "(", "l", ".", "Text", "[", "l", ".", "Pos", "-", "1", ":", "l", ".", "Pos", "]", ")", "}", "\n", "}", "\n", "l", ".", "Rule", "=", "ruleIndex", "\n", "l", ".", "Groups", "=", "groups", "\n", "l", ".", "Pos", "+=", "utf8", ".", "RuneCountInString", "(", "groups", "[", "0", "]", ")", "\n", "if", "rule", ".", "Mutator", "!=", "nil", "{", "if", "err", ":=", "rule", ".", "Mutator", ".", "Mutate", "(", "l", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "rule", ".", "Type", "!=", "nil", "{", "l", ".", "iteratorStack", "=", "append", "(", "l", ".", "iteratorStack", ",", "rule", ".", "Type", ".", "Emit", "(", "l", ".", "Groups", ",", "l", ".", "Lexer", ")", ")", "\n", "}", "\n", "}", "\n", "// Exhaust the IteratorStack, if any.", "// Duplicate code, but eh.", "for", "len", "(", "l", ".", "iteratorStack", ")", ">", "0", "{", "n", ":=", "len", "(", "l", ".", "iteratorStack", ")", "-", "1", "\n", "t", ":=", "l", ".", "iteratorStack", "[", "n", "]", "(", ")", "\n", "if", "t", "==", "EOF", "{", "l", ".", "iteratorStack", "=", "l", ".", "iteratorStack", "[", ":", "n", "]", "\n", "continue", "\n", "}", "\n", "return", "t", "\n", "}", "\n\n", "// If we get to here and we still have text, return it as an error.", "if", "l", ".", "Pos", "!=", "len", "(", "l", ".", "Text", ")", "&&", "len", "(", "l", ".", "Stack", ")", "==", "0", "{", "value", ":=", "string", "(", "l", ".", "Text", "[", "l", ".", "Pos", ":", "]", ")", "\n", "l", ".", "Pos", "=", "len", "(", "l", ".", "Text", ")", "\n", "return", "Token", "{", "Type", ":", "Error", ",", "Value", ":", "value", "}", "\n", "}", "\n", "return", "EOF", "\n", "}" ]
// Iterator returns the next Token from the lexer.
[ "Iterator", "returns", "the", "next", "Token", "from", "the", "lexer", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L258-L326
148,241
alecthomas/chroma
regexp.go
SetAnalyser
func (r *RegexLexer) SetAnalyser(analyser func(text string) float32) *RegexLexer { r.analyser = analyser return r }
go
func (r *RegexLexer) SetAnalyser(analyser func(text string) float32) *RegexLexer { r.analyser = analyser return r }
[ "func", "(", "r", "*", "RegexLexer", ")", "SetAnalyser", "(", "analyser", "func", "(", "text", "string", ")", "float32", ")", "*", "RegexLexer", "{", "r", ".", "analyser", "=", "analyser", "\n", "return", "r", "\n", "}" ]
// SetAnalyser sets the analyser function used to perform content inspection.
[ "SetAnalyser", "sets", "the", "analyser", "function", "used", "to", "perform", "content", "inspection", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L340-L343
148,242
alecthomas/chroma
iterator.go
Tokens
func (i Iterator) Tokens() []Token { var out []Token for t := i(); t != EOF; t = i() { out = append(out, t) } return out }
go
func (i Iterator) Tokens() []Token { var out []Token for t := i(); t != EOF; t = i() { out = append(out, t) } return out }
[ "func", "(", "i", "Iterator", ")", "Tokens", "(", ")", "[", "]", "Token", "{", "var", "out", "[", "]", "Token", "\n", "for", "t", ":=", "i", "(", ")", ";", "t", "!=", "EOF", ";", "t", "=", "i", "(", ")", "{", "out", "=", "append", "(", "out", ",", "t", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Tokens consumes all tokens from the iterator and returns them as a slice.
[ "Tokens", "consumes", "all", "tokens", "from", "the", "iterator", "and", "returns", "them", "as", "a", "slice", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/iterator.go#L13-L19
148,243
alecthomas/chroma
iterator.go
Concaterator
func Concaterator(iterators ...Iterator) Iterator { return func() Token { for len(iterators) > 0 { t := iterators[0]() if t != EOF { return t } iterators = iterators[1:] } return EOF } }
go
func Concaterator(iterators ...Iterator) Iterator { return func() Token { for len(iterators) > 0 { t := iterators[0]() if t != EOF { return t } iterators = iterators[1:] } return EOF } }
[ "func", "Concaterator", "(", "iterators", "...", "Iterator", ")", "Iterator", "{", "return", "func", "(", ")", "Token", "{", "for", "len", "(", "iterators", ")", ">", "0", "{", "t", ":=", "iterators", "[", "0", "]", "(", ")", "\n", "if", "t", "!=", "EOF", "{", "return", "t", "\n", "}", "\n", "iterators", "=", "iterators", "[", "1", ":", "]", "\n", "}", "\n", "return", "EOF", "\n", "}", "\n", "}" ]
// Concaterator concatenates tokens from a series of iterators.
[ "Concaterator", "concatenates", "tokens", "from", "a", "series", "of", "iterators", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/iterator.go#L22-L33
148,244
alecthomas/chroma
iterator.go
Literator
func Literator(tokens ...Token) Iterator { return func() Token { if len(tokens) == 0 { return EOF } token := tokens[0] tokens = tokens[1:] return token } }
go
func Literator(tokens ...Token) Iterator { return func() Token { if len(tokens) == 0 { return EOF } token := tokens[0] tokens = tokens[1:] return token } }
[ "func", "Literator", "(", "tokens", "...", "Token", ")", "Iterator", "{", "return", "func", "(", ")", "Token", "{", "if", "len", "(", "tokens", ")", "==", "0", "{", "return", "EOF", "\n", "}", "\n", "token", ":=", "tokens", "[", "0", "]", "\n", "tokens", "=", "tokens", "[", "1", ":", "]", "\n", "return", "token", "\n", "}", "\n", "}" ]
// Literator converts a sequence of literal Tokens into an Iterator.
[ "Literator", "converts", "a", "sequence", "of", "literal", "Tokens", "into", "an", "Iterator", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/iterator.go#L36-L45
148,245
alecthomas/chroma
iterator.go
SplitTokensIntoLines
func SplitTokensIntoLines(tokens []Token) (out [][]Token) { var line []Token // nolint: prealloc for _, token := range tokens { for strings.Contains(token.Value, "\n") { parts := strings.SplitAfterN(token.Value, "\n", 2) // Token becomes the tail. token.Value = parts[1] // Append the head to the line and flush the line. clone := token.Clone() clone.Value = parts[0] line = append(line, clone) out = append(out, line) line = nil } line = append(line, token) } if len(line) > 0 { out = append(out, line) } // Strip empty trailing token line. if len(out) > 0 { last := out[len(out)-1] if len(last) == 1 && last[0].Value == "" { out = out[:len(out)-1] } } return }
go
func SplitTokensIntoLines(tokens []Token) (out [][]Token) { var line []Token // nolint: prealloc for _, token := range tokens { for strings.Contains(token.Value, "\n") { parts := strings.SplitAfterN(token.Value, "\n", 2) // Token becomes the tail. token.Value = parts[1] // Append the head to the line and flush the line. clone := token.Clone() clone.Value = parts[0] line = append(line, clone) out = append(out, line) line = nil } line = append(line, token) } if len(line) > 0 { out = append(out, line) } // Strip empty trailing token line. if len(out) > 0 { last := out[len(out)-1] if len(last) == 1 && last[0].Value == "" { out = out[:len(out)-1] } } return }
[ "func", "SplitTokensIntoLines", "(", "tokens", "[", "]", "Token", ")", "(", "out", "[", "]", "[", "]", "Token", ")", "{", "var", "line", "[", "]", "Token", "// nolint: prealloc", "\n", "for", "_", ",", "token", ":=", "range", "tokens", "{", "for", "strings", ".", "Contains", "(", "token", ".", "Value", ",", "\"", "\\n", "\"", ")", "{", "parts", ":=", "strings", ".", "SplitAfterN", "(", "token", ".", "Value", ",", "\"", "\\n", "\"", ",", "2", ")", "\n", "// Token becomes the tail.", "token", ".", "Value", "=", "parts", "[", "1", "]", "\n\n", "// Append the head to the line and flush the line.", "clone", ":=", "token", ".", "Clone", "(", ")", "\n", "clone", ".", "Value", "=", "parts", "[", "0", "]", "\n", "line", "=", "append", "(", "line", ",", "clone", ")", "\n", "out", "=", "append", "(", "out", ",", "line", ")", "\n", "line", "=", "nil", "\n", "}", "\n", "line", "=", "append", "(", "line", ",", "token", ")", "\n", "}", "\n", "if", "len", "(", "line", ")", ">", "0", "{", "out", "=", "append", "(", "out", ",", "line", ")", "\n", "}", "\n", "// Strip empty trailing token line.", "if", "len", "(", "out", ")", ">", "0", "{", "last", ":=", "out", "[", "len", "(", "out", ")", "-", "1", "]", "\n", "if", "len", "(", "last", ")", "==", "1", "&&", "last", "[", "0", "]", ".", "Value", "==", "\"", "\"", "{", "out", "=", "out", "[", ":", "len", "(", "out", ")", "-", "1", "]", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// SplitTokensIntoLines splits tokens containing newlines in two.
[ "SplitTokensIntoLines", "splits", "tokens", "containing", "newlines", "in", "two", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/iterator.go#L48-L76
148,246
alecthomas/chroma
lexers/internal/api.go
Names
func Names(withAliases bool) []string { out := []string{} for _, lexer := range Registry.Lexers { config := lexer.Config() out = append(out, config.Name) if withAliases { out = append(out, config.Aliases...) } } sort.Strings(out) return out }
go
func Names(withAliases bool) []string { out := []string{} for _, lexer := range Registry.Lexers { config := lexer.Config() out = append(out, config.Name) if withAliases { out = append(out, config.Aliases...) } } sort.Strings(out) return out }
[ "func", "Names", "(", "withAliases", "bool", ")", "[", "]", "string", "{", "out", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "lexer", ":=", "range", "Registry", ".", "Lexers", "{", "config", ":=", "lexer", ".", "Config", "(", ")", "\n", "out", "=", "append", "(", "out", ",", "config", ".", "Name", ")", "\n", "if", "withAliases", "{", "out", "=", "append", "(", "out", ",", "config", ".", "Aliases", "...", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// Names of all lexers, optionally including aliases.
[ "Names", "of", "all", "lexers", "optionally", "including", "aliases", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/lexers/internal/api.go#L24-L35
148,247
alecthomas/chroma
lexers/internal/api.go
Get
func Get(name string) chroma.Lexer { candidates := chroma.PrioritisedLexers{} if lexer := Registry.byName[name]; lexer != nil { candidates = append(candidates, lexer) } if lexer := Registry.byAlias[name]; lexer != nil { candidates = append(candidates, lexer) } if lexer := Registry.byName[strings.ToLower(name)]; lexer != nil { candidates = append(candidates, lexer) } if lexer := Registry.byAlias[strings.ToLower(name)]; lexer != nil { candidates = append(candidates, lexer) } // Try file extension. if lexer := Match("filename." + name); lexer != nil { candidates = append(candidates, lexer) } // Try exact filename. if lexer := Match(name); lexer != nil { candidates = append(candidates, lexer) } if len(candidates) == 0 { return nil } sort.Sort(candidates) return candidates[0] }
go
func Get(name string) chroma.Lexer { candidates := chroma.PrioritisedLexers{} if lexer := Registry.byName[name]; lexer != nil { candidates = append(candidates, lexer) } if lexer := Registry.byAlias[name]; lexer != nil { candidates = append(candidates, lexer) } if lexer := Registry.byName[strings.ToLower(name)]; lexer != nil { candidates = append(candidates, lexer) } if lexer := Registry.byAlias[strings.ToLower(name)]; lexer != nil { candidates = append(candidates, lexer) } // Try file extension. if lexer := Match("filename." + name); lexer != nil { candidates = append(candidates, lexer) } // Try exact filename. if lexer := Match(name); lexer != nil { candidates = append(candidates, lexer) } if len(candidates) == 0 { return nil } sort.Sort(candidates) return candidates[0] }
[ "func", "Get", "(", "name", "string", ")", "chroma", ".", "Lexer", "{", "candidates", ":=", "chroma", ".", "PrioritisedLexers", "{", "}", "\n", "if", "lexer", ":=", "Registry", ".", "byName", "[", "name", "]", ";", "lexer", "!=", "nil", "{", "candidates", "=", "append", "(", "candidates", ",", "lexer", ")", "\n", "}", "\n", "if", "lexer", ":=", "Registry", ".", "byAlias", "[", "name", "]", ";", "lexer", "!=", "nil", "{", "candidates", "=", "append", "(", "candidates", ",", "lexer", ")", "\n", "}", "\n", "if", "lexer", ":=", "Registry", ".", "byName", "[", "strings", ".", "ToLower", "(", "name", ")", "]", ";", "lexer", "!=", "nil", "{", "candidates", "=", "append", "(", "candidates", ",", "lexer", ")", "\n", "}", "\n", "if", "lexer", ":=", "Registry", ".", "byAlias", "[", "strings", ".", "ToLower", "(", "name", ")", "]", ";", "lexer", "!=", "nil", "{", "candidates", "=", "append", "(", "candidates", ",", "lexer", ")", "\n", "}", "\n", "// Try file extension.", "if", "lexer", ":=", "Match", "(", "\"", "\"", "+", "name", ")", ";", "lexer", "!=", "nil", "{", "candidates", "=", "append", "(", "candidates", ",", "lexer", ")", "\n", "}", "\n", "// Try exact filename.", "if", "lexer", ":=", "Match", "(", "name", ")", ";", "lexer", "!=", "nil", "{", "candidates", "=", "append", "(", "candidates", ",", "lexer", ")", "\n", "}", "\n", "if", "len", "(", "candidates", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "sort", ".", "Sort", "(", "candidates", ")", "\n", "return", "candidates", "[", "0", "]", "\n", "}" ]
// Get a Lexer by name, alias or file extension.
[ "Get", "a", "Lexer", "by", "name", "alias", "or", "file", "extension", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/lexers/internal/api.go#L38-L65
148,248
alecthomas/chroma
lexers/internal/api.go
MatchMimeType
func MatchMimeType(mimeType string) chroma.Lexer { matched := chroma.PrioritisedLexers{} for _, l := range Registry.Lexers { for _, lmt := range l.Config().MimeTypes { if mimeType == lmt { matched = append(matched, l) } } } if len(matched) != 0 { sort.Sort(matched) return matched[0] } return nil }
go
func MatchMimeType(mimeType string) chroma.Lexer { matched := chroma.PrioritisedLexers{} for _, l := range Registry.Lexers { for _, lmt := range l.Config().MimeTypes { if mimeType == lmt { matched = append(matched, l) } } } if len(matched) != 0 { sort.Sort(matched) return matched[0] } return nil }
[ "func", "MatchMimeType", "(", "mimeType", "string", ")", "chroma", ".", "Lexer", "{", "matched", ":=", "chroma", ".", "PrioritisedLexers", "{", "}", "\n", "for", "_", ",", "l", ":=", "range", "Registry", ".", "Lexers", "{", "for", "_", ",", "lmt", ":=", "range", "l", ".", "Config", "(", ")", ".", "MimeTypes", "{", "if", "mimeType", "==", "lmt", "{", "matched", "=", "append", "(", "matched", ",", "l", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "matched", ")", "!=", "0", "{", "sort", ".", "Sort", "(", "matched", ")", "\n", "return", "matched", "[", "0", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MatchMimeType attempts to find a lexer for the given MIME type.
[ "MatchMimeType", "attempts", "to", "find", "a", "lexer", "for", "the", "given", "MIME", "type", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/lexers/internal/api.go#L68-L82
148,249
alecthomas/chroma
lexers/internal/api.go
Match
func Match(filename string) chroma.Lexer { filename = filepath.Base(filename) matched := chroma.PrioritisedLexers{} // First, try primary filename matches. for _, lexer := range Registry.Lexers { config := lexer.Config() for _, glob := range config.Filenames { if fnmatch.Match(glob, filename, 0) { matched = append(matched, lexer) } } } if len(matched) > 0 { sort.Sort(matched) return matched[0] } matched = nil // Next, try filename aliases. for _, lexer := range Registry.Lexers { config := lexer.Config() for _, glob := range config.AliasFilenames { if fnmatch.Match(glob, filename, 0) { matched = append(matched, lexer) } } } if len(matched) > 0 { sort.Sort(matched) return matched[0] } return nil }
go
func Match(filename string) chroma.Lexer { filename = filepath.Base(filename) matched := chroma.PrioritisedLexers{} // First, try primary filename matches. for _, lexer := range Registry.Lexers { config := lexer.Config() for _, glob := range config.Filenames { if fnmatch.Match(glob, filename, 0) { matched = append(matched, lexer) } } } if len(matched) > 0 { sort.Sort(matched) return matched[0] } matched = nil // Next, try filename aliases. for _, lexer := range Registry.Lexers { config := lexer.Config() for _, glob := range config.AliasFilenames { if fnmatch.Match(glob, filename, 0) { matched = append(matched, lexer) } } } if len(matched) > 0 { sort.Sort(matched) return matched[0] } return nil }
[ "func", "Match", "(", "filename", "string", ")", "chroma", ".", "Lexer", "{", "filename", "=", "filepath", ".", "Base", "(", "filename", ")", "\n", "matched", ":=", "chroma", ".", "PrioritisedLexers", "{", "}", "\n", "// First, try primary filename matches.", "for", "_", ",", "lexer", ":=", "range", "Registry", ".", "Lexers", "{", "config", ":=", "lexer", ".", "Config", "(", ")", "\n", "for", "_", ",", "glob", ":=", "range", "config", ".", "Filenames", "{", "if", "fnmatch", ".", "Match", "(", "glob", ",", "filename", ",", "0", ")", "{", "matched", "=", "append", "(", "matched", ",", "lexer", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "matched", ")", ">", "0", "{", "sort", ".", "Sort", "(", "matched", ")", "\n", "return", "matched", "[", "0", "]", "\n", "}", "\n", "matched", "=", "nil", "\n", "// Next, try filename aliases.", "for", "_", ",", "lexer", ":=", "range", "Registry", ".", "Lexers", "{", "config", ":=", "lexer", ".", "Config", "(", ")", "\n", "for", "_", ",", "glob", ":=", "range", "config", ".", "AliasFilenames", "{", "if", "fnmatch", ".", "Match", "(", "glob", ",", "filename", ",", "0", ")", "{", "matched", "=", "append", "(", "matched", ",", "lexer", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "matched", ")", ">", "0", "{", "sort", ".", "Sort", "(", "matched", ")", "\n", "return", "matched", "[", "0", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Match returns the first lexer matching filename.
[ "Match", "returns", "the", "first", "lexer", "matching", "filename", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/lexers/internal/api.go#L85-L116
148,250
alecthomas/chroma
lexers/internal/api.go
Analyse
func Analyse(text string) chroma.Lexer { var picked chroma.Lexer highest := float32(0.0) for _, lexer := range Registry.Lexers { if analyser, ok := lexer.(chroma.Analyser); ok { weight := analyser.AnalyseText(text) if weight > highest { picked = lexer highest = weight } } } return picked }
go
func Analyse(text string) chroma.Lexer { var picked chroma.Lexer highest := float32(0.0) for _, lexer := range Registry.Lexers { if analyser, ok := lexer.(chroma.Analyser); ok { weight := analyser.AnalyseText(text) if weight > highest { picked = lexer highest = weight } } } return picked }
[ "func", "Analyse", "(", "text", "string", ")", "chroma", ".", "Lexer", "{", "var", "picked", "chroma", ".", "Lexer", "\n", "highest", ":=", "float32", "(", "0.0", ")", "\n", "for", "_", ",", "lexer", ":=", "range", "Registry", ".", "Lexers", "{", "if", "analyser", ",", "ok", ":=", "lexer", ".", "(", "chroma", ".", "Analyser", ")", ";", "ok", "{", "weight", ":=", "analyser", ".", "AnalyseText", "(", "text", ")", "\n", "if", "weight", ">", "highest", "{", "picked", "=", "lexer", "\n", "highest", "=", "weight", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "picked", "\n", "}" ]
// Analyse text content and return the "best" lexer..
[ "Analyse", "text", "content", "and", "return", "the", "best", "lexer", ".." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/lexers/internal/api.go#L119-L132
148,251
alecthomas/chroma
lexers/internal/api.go
Register
func Register(lexer chroma.Lexer) chroma.Lexer { config := lexer.Config() Registry.byName[config.Name] = lexer Registry.byName[strings.ToLower(config.Name)] = lexer for _, alias := range config.Aliases { Registry.byAlias[alias] = lexer Registry.byAlias[strings.ToLower(alias)] = lexer } Registry.Lexers = append(Registry.Lexers, lexer) return lexer }
go
func Register(lexer chroma.Lexer) chroma.Lexer { config := lexer.Config() Registry.byName[config.Name] = lexer Registry.byName[strings.ToLower(config.Name)] = lexer for _, alias := range config.Aliases { Registry.byAlias[alias] = lexer Registry.byAlias[strings.ToLower(alias)] = lexer } Registry.Lexers = append(Registry.Lexers, lexer) return lexer }
[ "func", "Register", "(", "lexer", "chroma", ".", "Lexer", ")", "chroma", ".", "Lexer", "{", "config", ":=", "lexer", ".", "Config", "(", ")", "\n", "Registry", ".", "byName", "[", "config", ".", "Name", "]", "=", "lexer", "\n", "Registry", ".", "byName", "[", "strings", ".", "ToLower", "(", "config", ".", "Name", ")", "]", "=", "lexer", "\n", "for", "_", ",", "alias", ":=", "range", "config", ".", "Aliases", "{", "Registry", ".", "byAlias", "[", "alias", "]", "=", "lexer", "\n", "Registry", ".", "byAlias", "[", "strings", ".", "ToLower", "(", "alias", ")", "]", "=", "lexer", "\n", "}", "\n", "Registry", ".", "Lexers", "=", "append", "(", "Registry", ".", "Lexers", ",", "lexer", ")", "\n", "return", "lexer", "\n", "}" ]
// Register a Lexer with the global registry.
[ "Register", "a", "Lexer", "with", "the", "global", "registry", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/lexers/internal/api.go#L135-L145
148,252
alecthomas/chroma
mutators.go
Mutators
func Mutators(modifiers ...Mutator) MutatorFunc { return func(state *LexerState) error { for _, modifier := range modifiers { if err := modifier.Mutate(state); err != nil { return err } } return nil } }
go
func Mutators(modifiers ...Mutator) MutatorFunc { return func(state *LexerState) error { for _, modifier := range modifiers { if err := modifier.Mutate(state); err != nil { return err } } return nil } }
[ "func", "Mutators", "(", "modifiers", "...", "Mutator", ")", "MutatorFunc", "{", "return", "func", "(", "state", "*", "LexerState", ")", "error", "{", "for", "_", ",", "modifier", ":=", "range", "modifiers", "{", "if", "err", ":=", "modifier", ".", "Mutate", "(", "state", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Mutators applies a set of Mutators in order.
[ "Mutators", "applies", "a", "set", "of", "Mutators", "in", "order", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/mutators.go#L27-L36
148,253
alecthomas/chroma
mutators.go
Push
func Push(states ...string) MutatorFunc { return func(s *LexerState) error { if len(states) == 0 { s.Stack = append(s.Stack, s.State) } else { for _, state := range states { if state == "#pop" { s.Stack = s.Stack[:len(s.Stack)-1] } else { s.Stack = append(s.Stack, state) } } } return nil } }
go
func Push(states ...string) MutatorFunc { return func(s *LexerState) error { if len(states) == 0 { s.Stack = append(s.Stack, s.State) } else { for _, state := range states { if state == "#pop" { s.Stack = s.Stack[:len(s.Stack)-1] } else { s.Stack = append(s.Stack, state) } } } return nil } }
[ "func", "Push", "(", "states", "...", "string", ")", "MutatorFunc", "{", "return", "func", "(", "s", "*", "LexerState", ")", "error", "{", "if", "len", "(", "states", ")", "==", "0", "{", "s", ".", "Stack", "=", "append", "(", "s", ".", "Stack", ",", "s", ".", "State", ")", "\n", "}", "else", "{", "for", "_", ",", "state", ":=", "range", "states", "{", "if", "state", "==", "\"", "\"", "{", "s", ".", "Stack", "=", "s", ".", "Stack", "[", ":", "len", "(", "s", ".", "Stack", ")", "-", "1", "]", "\n", "}", "else", "{", "s", ".", "Stack", "=", "append", "(", "s", ".", "Stack", ",", "state", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Push states onto the stack.
[ "Push", "states", "onto", "the", "stack", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/mutators.go#L91-L106
148,254
alecthomas/chroma
mutators.go
Pop
func Pop(n int) MutatorFunc { return func(state *LexerState) error { if len(state.Stack) == 0 { return fmt.Errorf("nothing to pop") } state.Stack = state.Stack[:len(state.Stack)-n] return nil } }
go
func Pop(n int) MutatorFunc { return func(state *LexerState) error { if len(state.Stack) == 0 { return fmt.Errorf("nothing to pop") } state.Stack = state.Stack[:len(state.Stack)-n] return nil } }
[ "func", "Pop", "(", "n", "int", ")", "MutatorFunc", "{", "return", "func", "(", "state", "*", "LexerState", ")", "error", "{", "if", "len", "(", "state", ".", "Stack", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "state", ".", "Stack", "=", "state", ".", "Stack", "[", ":", "len", "(", "state", ".", "Stack", ")", "-", "n", "]", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Pop state from the stack when rule matches.
[ "Pop", "state", "from", "the", "stack", "when", "rule", "matches", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/mutators.go#L109-L117
148,255
alecthomas/chroma
mutators.go
Stringify
func Stringify(tokens ...Token) string { out := []string{} for _, t := range tokens { out = append(out, t.Value) } return strings.Join(out, "") }
go
func Stringify(tokens ...Token) string { out := []string{} for _, t := range tokens { out = append(out, t.Value) } return strings.Join(out, "") }
[ "func", "Stringify", "(", "tokens", "...", "Token", ")", "string", "{", "out", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "t", ":=", "range", "tokens", "{", "out", "=", "append", "(", "out", ",", "t", ".", "Value", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "out", ",", "\"", "\"", ")", "\n", "}" ]
// Stringify returns the raw string for a set of tokens.
[ "Stringify", "returns", "the", "raw", "string", "for", "a", "set", "of", "tokens", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/mutators.go#L125-L131
148,256
stripe/stripe-go
issuing_transaction.go
UnmarshalJSON
func (i *IssuingTransaction) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { i.ID = id return nil } type issuingTransaction IssuingTransaction var v issuingTransaction if err := json.Unmarshal(data, &v); err != nil { return err } *i = IssuingTransaction(v) return nil }
go
func (i *IssuingTransaction) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { i.ID = id return nil } type issuingTransaction IssuingTransaction var v issuingTransaction if err := json.Unmarshal(data, &v); err != nil { return err } *i = IssuingTransaction(v) return nil }
[ "func", "(", "i", "*", "IssuingTransaction", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "i", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "issuingTransaction", "IssuingTransaction", "\n", "var", "v", "issuingTransaction", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "i", "=", "IssuingTransaction", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of an IssuingTransaction. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "an", "IssuingTransaction", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/issuing_transaction.go#L58-L72
148,257
stripe/stripe-go
paymentintent/client.go
Cancel
func Cancel(id string, params *stripe.PaymentIntentCancelParams) (*stripe.PaymentIntent, error) { return getC().Cancel(id, params) }
go
func Cancel(id string, params *stripe.PaymentIntentCancelParams) (*stripe.PaymentIntent, error) { return getC().Cancel(id, params) }
[ "func", "Cancel", "(", "id", "string", ",", "params", "*", "stripe", ".", "PaymentIntentCancelParams", ")", "(", "*", "stripe", ".", "PaymentIntent", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "Cancel", "(", "id", ",", "params", ")", "\n", "}" ]
// Cancel cancels a payment intent.
[ "Cancel", "cancels", "a", "payment", "intent", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/paymentintent/client.go#L58-L60
148,258
stripe/stripe-go
paymentintent/client.go
Capture
func Capture(id string, params *stripe.PaymentIntentCaptureParams) (*stripe.PaymentIntent, error) { return getC().Capture(id, params) }
go
func Capture(id string, params *stripe.PaymentIntentCaptureParams) (*stripe.PaymentIntent, error) { return getC().Capture(id, params) }
[ "func", "Capture", "(", "id", "string", ",", "params", "*", "stripe", ".", "PaymentIntentCaptureParams", ")", "(", "*", "stripe", ".", "PaymentIntent", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "Capture", "(", "id", ",", "params", ")", "\n", "}" ]
// Capture captures a payment intent.
[ "Capture", "captures", "a", "payment", "intent", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/paymentintent/client.go#L71-L73
148,259
stripe/stripe-go
paymentintent/client.go
Confirm
func Confirm(id string, params *stripe.PaymentIntentConfirmParams) (*stripe.PaymentIntent, error) { return getC().Confirm(id, params) }
go
func Confirm(id string, params *stripe.PaymentIntentConfirmParams) (*stripe.PaymentIntent, error) { return getC().Confirm(id, params) }
[ "func", "Confirm", "(", "id", "string", ",", "params", "*", "stripe", ".", "PaymentIntentConfirmParams", ")", "(", "*", "stripe", ".", "PaymentIntent", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "Confirm", "(", "id", ",", "params", ")", "\n", "}" ]
// Confirm confirms a payment intent.
[ "Confirm", "confirms", "a", "payment", "intent", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/paymentintent/client.go#L84-L86
148,260
stripe/stripe-go
payout.go
UnmarshalJSON
func (p *Payout) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { p.ID = id return nil } type payout Payout var v payout if err := json.Unmarshal(data, &v); err != nil { return err } *p = Payout(v) return nil }
go
func (p *Payout) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { p.ID = id return nil } type payout Payout var v payout if err := json.Unmarshal(data, &v); err != nil { return err } *p = Payout(v) return nil }
[ "func", "(", "p", "*", "Payout", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "p", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "payout", "Payout", "\n", "var", "v", "payout", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "p", "=", "Payout", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of a Payout. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "Payout", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/payout.go#L142-L156
148,261
stripe/stripe-go
payout.go
UnmarshalJSON
func (d *PayoutDestination) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { d.ID = id return nil } type payoutDestination PayoutDestination var v payoutDestination if err := json.Unmarshal(data, &v); err != nil { return err } var err error *d = PayoutDestination(v) switch d.Type { case PayoutDestinationTypeBankAccount: err = json.Unmarshal(data, &d.BankAccount) case PayoutDestinationTypeCard: err = json.Unmarshal(data, &d.Card) } return err }
go
func (d *PayoutDestination) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { d.ID = id return nil } type payoutDestination PayoutDestination var v payoutDestination if err := json.Unmarshal(data, &v); err != nil { return err } var err error *d = PayoutDestination(v) switch d.Type { case PayoutDestinationTypeBankAccount: err = json.Unmarshal(data, &d.BankAccount) case PayoutDestinationTypeCard: err = json.Unmarshal(data, &d.Card) } return err }
[ "func", "(", "d", "*", "PayoutDestination", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "d", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "payoutDestination", "PayoutDestination", "\n", "var", "v", "payoutDestination", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "err", "error", "\n", "*", "d", "=", "PayoutDestination", "(", "v", ")", "\n\n", "switch", "d", ".", "Type", "{", "case", "PayoutDestinationTypeBankAccount", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "d", ".", "BankAccount", ")", "\n", "case", "PayoutDestinationTypeCard", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "d", ".", "Card", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// UnmarshalJSON handles deserialization of a PayoutDestination. // This custom unmarshaling is needed because the specific // type of destination it refers to is specified in the JSON
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "PayoutDestination", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "specific", "type", "of", "destination", "it", "refers", "to", "is", "specified", "in", "the", "JSON" ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/payout.go#L161-L184
148,262
stripe/stripe-go
plan/client.go
Get
func (c Client) Get(id string, params *stripe.PlanParams) (*stripe.Plan, error) { path := stripe.FormatURLPath("/v1/plans/%s", id) plan := &stripe.Plan{} err := c.B.Call(http.MethodGet, path, c.Key, params, plan) return plan, err }
go
func (c Client) Get(id string, params *stripe.PlanParams) (*stripe.Plan, error) { path := stripe.FormatURLPath("/v1/plans/%s", id) plan := &stripe.Plan{} err := c.B.Call(http.MethodGet, path, c.Key, params, plan) return plan, err }
[ "func", "(", "c", "Client", ")", "Get", "(", "id", "string", ",", "params", "*", "stripe", ".", "PlanParams", ")", "(", "*", "stripe", ".", "Plan", ",", "error", ")", "{", "path", ":=", "stripe", ".", "FormatURLPath", "(", "\"", "\"", ",", "id", ")", "\n", "plan", ":=", "&", "stripe", ".", "Plan", "{", "}", "\n", "err", ":=", "c", ".", "B", ".", "Call", "(", "http", ".", "MethodGet", ",", "path", ",", "c", ".", "Key", ",", "params", ",", "plan", ")", "\n", "return", "plan", ",", "err", "\n", "}" ]
// Get returns the details of a plan.
[ "Get", "returns", "the", "details", "of", "a", "plan", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/plan/client.go#L35-L40
148,263
stripe/stripe-go
plan/client.go
Update
func Update(id string, params *stripe.PlanParams) (*stripe.Plan, error) { return getC().Update(id, params) }
go
func Update(id string, params *stripe.PlanParams) (*stripe.Plan, error) { return getC().Update(id, params) }
[ "func", "Update", "(", "id", "string", ",", "params", "*", "stripe", ".", "PlanParams", ")", "(", "*", "stripe", ".", "Plan", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "Update", "(", "id", ",", "params", ")", "\n", "}" ]
// Update updates a plan's properties.
[ "Update", "updates", "a", "plan", "s", "properties", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/plan/client.go#L43-L45
148,264
stripe/stripe-go
stripe.go
formatUserAgent
func (a *AppInfo) formatUserAgent() string { str := a.Name if a.Version != "" { str += "/" + a.Version } if a.URL != "" { str += " (" + a.URL + ")" } return str }
go
func (a *AppInfo) formatUserAgent() string { str := a.Name if a.Version != "" { str += "/" + a.Version } if a.URL != "" { str += " (" + a.URL + ")" } return str }
[ "func", "(", "a", "*", "AppInfo", ")", "formatUserAgent", "(", ")", "string", "{", "str", ":=", "a", ".", "Name", "\n", "if", "a", ".", "Version", "!=", "\"", "\"", "{", "str", "+=", "\"", "\"", "+", "a", ".", "Version", "\n", "}", "\n", "if", "a", ".", "URL", "!=", "\"", "\"", "{", "str", "+=", "\"", "\"", "+", "a", ".", "URL", "+", "\"", "\"", "\n", "}", "\n", "return", "str", "\n", "}" ]
// formatUserAgent formats an AppInfo in a way that's suitable to be appended // to a User-Agent string. Note that this format is shared between all // libraries so if it's changed, it should be changed everywhere.
[ "formatUserAgent", "formats", "an", "AppInfo", "in", "a", "way", "that", "s", "suitable", "to", "be", "appended", "to", "a", "User", "-", "Agent", "string", ".", "Note", "that", "this", "format", "is", "shared", "between", "all", "libraries", "so", "if", "it", "s", "changed", "it", "should", "be", "changed", "everywhere", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L82-L91
148,265
stripe/stripe-go
stripe.go
Call
func (s *BackendImplementation) Call(method, path, key string, params ParamsContainer, v interface{}) error { var body *form.Values var commonParams *Params if params != nil { // This is a little unfortunate, but Go makes it impossible to compare // an interface value to nil without the use of the reflect package and // its true disciples insist that this is a feature and not a bug. // // Here we do invoke reflect because (1) we have to reflect anyway to // use encode with the form package, and (2) the corresponding removal // of boilerplate that this enables makes the small performance penalty // worth it. reflectValue := reflect.ValueOf(params) if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { commonParams = params.GetParams() body = &form.Values{} form.AppendTo(body, params) } } return s.CallRaw(method, path, key, body, commonParams, v) }
go
func (s *BackendImplementation) Call(method, path, key string, params ParamsContainer, v interface{}) error { var body *form.Values var commonParams *Params if params != nil { // This is a little unfortunate, but Go makes it impossible to compare // an interface value to nil without the use of the reflect package and // its true disciples insist that this is a feature and not a bug. // // Here we do invoke reflect because (1) we have to reflect anyway to // use encode with the form package, and (2) the corresponding removal // of boilerplate that this enables makes the small performance penalty // worth it. reflectValue := reflect.ValueOf(params) if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { commonParams = params.GetParams() body = &form.Values{} form.AppendTo(body, params) } } return s.CallRaw(method, path, key, body, commonParams, v) }
[ "func", "(", "s", "*", "BackendImplementation", ")", "Call", "(", "method", ",", "path", ",", "key", "string", ",", "params", "ParamsContainer", ",", "v", "interface", "{", "}", ")", "error", "{", "var", "body", "*", "form", ".", "Values", "\n", "var", "commonParams", "*", "Params", "\n\n", "if", "params", "!=", "nil", "{", "// This is a little unfortunate, but Go makes it impossible to compare", "// an interface value to nil without the use of the reflect package and", "// its true disciples insist that this is a feature and not a bug.", "//", "// Here we do invoke reflect because (1) we have to reflect anyway to", "// use encode with the form package, and (2) the corresponding removal", "// of boilerplate that this enables makes the small performance penalty", "// worth it.", "reflectValue", ":=", "reflect", ".", "ValueOf", "(", "params", ")", "\n\n", "if", "reflectValue", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "!", "reflectValue", ".", "IsNil", "(", ")", "{", "commonParams", "=", "params", ".", "GetParams", "(", ")", "\n", "body", "=", "&", "form", ".", "Values", "{", "}", "\n", "form", ".", "AppendTo", "(", "body", ",", "params", ")", "\n", "}", "\n", "}", "\n\n", "return", "s", ".", "CallRaw", "(", "method", ",", "path", ",", "key", ",", "body", ",", "commonParams", ",", "v", ")", "\n", "}" ]
// Call is the Backend.Call implementation for invoking Stripe APIs.
[ "Call", "is", "the", "Backend", ".", "Call", "implementation", "for", "invoking", "Stripe", "APIs", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L182-L205
148,266
stripe/stripe-go
stripe.go
CallMultipart
func (s *BackendImplementation) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v interface{}) error { contentType := "multipart/form-data; boundary=" + boundary req, err := s.NewRequest(method, path, key, contentType, params) if err != nil { return err } if err := s.Do(req, body, v); err != nil { return err } return nil }
go
func (s *BackendImplementation) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v interface{}) error { contentType := "multipart/form-data; boundary=" + boundary req, err := s.NewRequest(method, path, key, contentType, params) if err != nil { return err } if err := s.Do(req, body, v); err != nil { return err } return nil }
[ "func", "(", "s", "*", "BackendImplementation", ")", "CallMultipart", "(", "method", ",", "path", ",", "key", ",", "boundary", "string", ",", "body", "*", "bytes", ".", "Buffer", ",", "params", "*", "Params", ",", "v", "interface", "{", "}", ")", "error", "{", "contentType", ":=", "\"", "\"", "+", "boundary", "\n\n", "req", ",", "err", ":=", "s", ".", "NewRequest", "(", "method", ",", "path", ",", "key", ",", "contentType", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "Do", "(", "req", ",", "body", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CallMultipart is the Backend.CallMultipart implementation for invoking Stripe APIs.
[ "CallMultipart", "is", "the", "Backend", ".", "CallMultipart", "implementation", "for", "invoking", "Stripe", "APIs", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L208-L221
148,267
stripe/stripe-go
stripe.go
CallRaw
func (s *BackendImplementation) CallRaw(method, path, key string, form *form.Values, params *Params, v interface{}) error { var body string if form != nil && !form.Empty() { body = form.Encode() // On `GET`, move the payload into the URL if method == http.MethodGet { path += "?" + body body = "" } } bodyBuffer := bytes.NewBufferString(body) req, err := s.NewRequest(method, path, key, "application/x-www-form-urlencoded", params) if err != nil { return err } if err := s.Do(req, bodyBuffer, v); err != nil { return err } return nil }
go
func (s *BackendImplementation) CallRaw(method, path, key string, form *form.Values, params *Params, v interface{}) error { var body string if form != nil && !form.Empty() { body = form.Encode() // On `GET`, move the payload into the URL if method == http.MethodGet { path += "?" + body body = "" } } bodyBuffer := bytes.NewBufferString(body) req, err := s.NewRequest(method, path, key, "application/x-www-form-urlencoded", params) if err != nil { return err } if err := s.Do(req, bodyBuffer, v); err != nil { return err } return nil }
[ "func", "(", "s", "*", "BackendImplementation", ")", "CallRaw", "(", "method", ",", "path", ",", "key", "string", ",", "form", "*", "form", ".", "Values", ",", "params", "*", "Params", ",", "v", "interface", "{", "}", ")", "error", "{", "var", "body", "string", "\n", "if", "form", "!=", "nil", "&&", "!", "form", ".", "Empty", "(", ")", "{", "body", "=", "form", ".", "Encode", "(", ")", "\n\n", "// On `GET`, move the payload into the URL", "if", "method", "==", "http", ".", "MethodGet", "{", "path", "+=", "\"", "\"", "+", "body", "\n", "body", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "bodyBuffer", ":=", "bytes", ".", "NewBufferString", "(", "body", ")", "\n\n", "req", ",", "err", ":=", "s", ".", "NewRequest", "(", "method", ",", "path", ",", "key", ",", "\"", "\"", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "Do", "(", "req", ",", "bodyBuffer", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CallRaw is the implementation for invoking Stripe APIs internally without a backend.
[ "CallRaw", "is", "the", "implementation", "for", "invoking", "Stripe", "APIs", "internally", "without", "a", "backend", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L224-L247
148,268
stripe/stripe-go
stripe.go
NewRequest
func (s *BackendImplementation) NewRequest(method, path, key, contentType string, params *Params) (*http.Request, error) { if !strings.HasPrefix(path, "/") { path = "/" + path } path = s.URL + path // Body is set later by `Do`. req, err := http.NewRequest(method, path, nil) if err != nil { s.LeveledLogger.Errorf("Cannot create Stripe request: %v", err) return nil, err } authorization := "Bearer " + key req.Header.Add("Authorization", authorization) req.Header.Add("Content-Type", contentType) req.Header.Add("Stripe-Version", APIVersion) req.Header.Add("User-Agent", encodedUserAgent) req.Header.Add("X-Stripe-Client-User-Agent", encodedStripeUserAgent) if params != nil { if params.Context != nil { req = req.WithContext(params.Context) } if params.IdempotencyKey != nil { idempotencyKey := strings.TrimSpace(*params.IdempotencyKey) if len(idempotencyKey) > 255 { return nil, errors.New("cannot use an idempotency key longer than 255 characters") } req.Header.Add("Idempotency-Key", idempotencyKey) } else if isHTTPWriteMethod(method) { req.Header.Add("Idempotency-Key", NewIdempotencyKey()) } if params.StripeAccount != nil { req.Header.Add("Stripe-Account", strings.TrimSpace(*params.StripeAccount)) } for k, v := range params.Headers { for _, line := range v { // Use Set to override the default value possibly set before req.Header.Set(k, line) } } } return req, nil }
go
func (s *BackendImplementation) NewRequest(method, path, key, contentType string, params *Params) (*http.Request, error) { if !strings.HasPrefix(path, "/") { path = "/" + path } path = s.URL + path // Body is set later by `Do`. req, err := http.NewRequest(method, path, nil) if err != nil { s.LeveledLogger.Errorf("Cannot create Stripe request: %v", err) return nil, err } authorization := "Bearer " + key req.Header.Add("Authorization", authorization) req.Header.Add("Content-Type", contentType) req.Header.Add("Stripe-Version", APIVersion) req.Header.Add("User-Agent", encodedUserAgent) req.Header.Add("X-Stripe-Client-User-Agent", encodedStripeUserAgent) if params != nil { if params.Context != nil { req = req.WithContext(params.Context) } if params.IdempotencyKey != nil { idempotencyKey := strings.TrimSpace(*params.IdempotencyKey) if len(idempotencyKey) > 255 { return nil, errors.New("cannot use an idempotency key longer than 255 characters") } req.Header.Add("Idempotency-Key", idempotencyKey) } else if isHTTPWriteMethod(method) { req.Header.Add("Idempotency-Key", NewIdempotencyKey()) } if params.StripeAccount != nil { req.Header.Add("Stripe-Account", strings.TrimSpace(*params.StripeAccount)) } for k, v := range params.Headers { for _, line := range v { // Use Set to override the default value possibly set before req.Header.Set(k, line) } } } return req, nil }
[ "func", "(", "s", "*", "BackendImplementation", ")", "NewRequest", "(", "method", ",", "path", ",", "key", ",", "contentType", "string", ",", "params", "*", "Params", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "path", ",", "\"", "\"", ")", "{", "path", "=", "\"", "\"", "+", "path", "\n", "}", "\n\n", "path", "=", "s", ".", "URL", "+", "path", "\n\n", "// Body is set later by `Do`.", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "LeveledLogger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "authorization", ":=", "\"", "\"", "+", "key", "\n\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "authorization", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "contentType", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "APIVersion", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "encodedUserAgent", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "encodedStripeUserAgent", ")", "\n\n", "if", "params", "!=", "nil", "{", "if", "params", ".", "Context", "!=", "nil", "{", "req", "=", "req", ".", "WithContext", "(", "params", ".", "Context", ")", "\n", "}", "\n\n", "if", "params", ".", "IdempotencyKey", "!=", "nil", "{", "idempotencyKey", ":=", "strings", ".", "TrimSpace", "(", "*", "params", ".", "IdempotencyKey", ")", "\n", "if", "len", "(", "idempotencyKey", ")", ">", "255", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "idempotencyKey", ")", "\n", "}", "else", "if", "isHTTPWriteMethod", "(", "method", ")", "{", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "NewIdempotencyKey", "(", ")", ")", "\n", "}", "\n\n", "if", "params", ".", "StripeAccount", "!=", "nil", "{", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "strings", ".", "TrimSpace", "(", "*", "params", ".", "StripeAccount", ")", ")", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "params", ".", "Headers", "{", "for", "_", ",", "line", ":=", "range", "v", "{", "// Use Set to override the default value possibly set before", "req", ".", "Header", ".", "Set", "(", "k", ",", "line", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// NewRequest is used by Call to generate an http.Request. It handles encoding // parameters and attaching the appropriate headers.
[ "NewRequest", "is", "used", "by", "Call", "to", "generate", "an", "http", ".", "Request", ".", "It", "handles", "encoding", "parameters", "and", "attaching", "the", "appropriate", "headers", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L251-L302
148,269
stripe/stripe-go
stripe.go
ResponseToError
func (s *BackendImplementation) ResponseToError(res *http.Response, resBody []byte) error { var raw rawError if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &raw); err != nil { return err } // no error in resBody if raw.E == nil { err := errors.New(string(resBody)) s.LeveledLogger.Errorf("Unparsable error returned from Stripe: %v", err) return err } raw.E.HTTPStatusCode = res.StatusCode raw.E.RequestID = res.Header.Get("Request-Id") var typedError error switch raw.E.Type { case ErrorTypeAPI: typedError = &APIError{stripeErr: raw.E.Error} case ErrorTypeAPIConnection: typedError = &APIConnectionError{stripeErr: raw.E.Error} case ErrorTypeAuthentication: typedError = &AuthenticationError{stripeErr: raw.E.Error} case ErrorTypeCard: cardErr := &CardError{stripeErr: raw.E.Error} if raw.E.DeclineCode != nil { cardErr.DeclineCode = *raw.E.DeclineCode } typedError = cardErr case ErrorTypeInvalidRequest: typedError = &InvalidRequestError{stripeErr: raw.E.Error} case ErrorTypePermission: typedError = &PermissionError{stripeErr: raw.E.Error} case ErrorTypeRateLimit: typedError = &RateLimitError{stripeErr: raw.E.Error} } raw.E.Err = typedError s.LeveledLogger.Errorf("Error encountered from Stripe: %v", raw.E.Error) return raw.E.Error }
go
func (s *BackendImplementation) ResponseToError(res *http.Response, resBody []byte) error { var raw rawError if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &raw); err != nil { return err } // no error in resBody if raw.E == nil { err := errors.New(string(resBody)) s.LeveledLogger.Errorf("Unparsable error returned from Stripe: %v", err) return err } raw.E.HTTPStatusCode = res.StatusCode raw.E.RequestID = res.Header.Get("Request-Id") var typedError error switch raw.E.Type { case ErrorTypeAPI: typedError = &APIError{stripeErr: raw.E.Error} case ErrorTypeAPIConnection: typedError = &APIConnectionError{stripeErr: raw.E.Error} case ErrorTypeAuthentication: typedError = &AuthenticationError{stripeErr: raw.E.Error} case ErrorTypeCard: cardErr := &CardError{stripeErr: raw.E.Error} if raw.E.DeclineCode != nil { cardErr.DeclineCode = *raw.E.DeclineCode } typedError = cardErr case ErrorTypeInvalidRequest: typedError = &InvalidRequestError{stripeErr: raw.E.Error} case ErrorTypePermission: typedError = &PermissionError{stripeErr: raw.E.Error} case ErrorTypeRateLimit: typedError = &RateLimitError{stripeErr: raw.E.Error} } raw.E.Err = typedError s.LeveledLogger.Errorf("Error encountered from Stripe: %v", raw.E.Error) return raw.E.Error }
[ "func", "(", "s", "*", "BackendImplementation", ")", "ResponseToError", "(", "res", "*", "http", ".", "Response", ",", "resBody", "[", "]", "byte", ")", "error", "{", "var", "raw", "rawError", "\n", "if", "err", ":=", "s", ".", "UnmarshalJSONVerbose", "(", "res", ".", "StatusCode", ",", "resBody", ",", "&", "raw", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// no error in resBody", "if", "raw", ".", "E", "==", "nil", "{", "err", ":=", "errors", ".", "New", "(", "string", "(", "resBody", ")", ")", "\n", "s", ".", "LeveledLogger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "raw", ".", "E", ".", "HTTPStatusCode", "=", "res", ".", "StatusCode", "\n", "raw", ".", "E", ".", "RequestID", "=", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n\n", "var", "typedError", "error", "\n", "switch", "raw", ".", "E", ".", "Type", "{", "case", "ErrorTypeAPI", ":", "typedError", "=", "&", "APIError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "case", "ErrorTypeAPIConnection", ":", "typedError", "=", "&", "APIConnectionError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "case", "ErrorTypeAuthentication", ":", "typedError", "=", "&", "AuthenticationError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "case", "ErrorTypeCard", ":", "cardErr", ":=", "&", "CardError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "if", "raw", ".", "E", ".", "DeclineCode", "!=", "nil", "{", "cardErr", ".", "DeclineCode", "=", "*", "raw", ".", "E", ".", "DeclineCode", "\n", "}", "\n", "typedError", "=", "cardErr", "\n", "case", "ErrorTypeInvalidRequest", ":", "typedError", "=", "&", "InvalidRequestError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "case", "ErrorTypePermission", ":", "typedError", "=", "&", "PermissionError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "case", "ErrorTypeRateLimit", ":", "typedError", "=", "&", "RateLimitError", "{", "stripeErr", ":", "raw", ".", "E", ".", "Error", "}", "\n", "}", "\n", "raw", ".", "E", ".", "Err", "=", "typedError", "\n\n", "s", ".", "LeveledLogger", ".", "Errorf", "(", "\"", "\"", ",", "raw", ".", "E", ".", "Error", ")", "\n", "return", "raw", ".", "E", ".", "Error", "\n", "}" ]
// ResponseToError converts a stripe response to an Error.
[ "ResponseToError", "converts", "a", "stripe", "response", "to", "an", "Error", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L451-L491
148,270
stripe/stripe-go
stripe.go
UnmarshalJSONVerbose
func (s *BackendImplementation) UnmarshalJSONVerbose(statusCode int, body []byte, v interface{}) error { err := json.Unmarshal(body, v) if err != nil { // If we got invalid JSON back then something totally unexpected is // happening (caused by a bug on the server side). Put a sample of the // response body into the error message so we can get a better feel for // what the problem was. bodySample := string(body) if len(bodySample) > 500 { bodySample = bodySample[0:500] + " ..." } // Make sure a multi-line response ends up all on one line bodySample = strings.Replace(bodySample, "\n", "\\n", -1) newErr := fmt.Errorf("Couldn't deserialize JSON (response status: %v, body sample: '%s'): %v", statusCode, bodySample, err) s.LeveledLogger.Errorf("%s", newErr.Error()) return newErr } return nil }
go
func (s *BackendImplementation) UnmarshalJSONVerbose(statusCode int, body []byte, v interface{}) error { err := json.Unmarshal(body, v) if err != nil { // If we got invalid JSON back then something totally unexpected is // happening (caused by a bug on the server side). Put a sample of the // response body into the error message so we can get a better feel for // what the problem was. bodySample := string(body) if len(bodySample) > 500 { bodySample = bodySample[0:500] + " ..." } // Make sure a multi-line response ends up all on one line bodySample = strings.Replace(bodySample, "\n", "\\n", -1) newErr := fmt.Errorf("Couldn't deserialize JSON (response status: %v, body sample: '%s'): %v", statusCode, bodySample, err) s.LeveledLogger.Errorf("%s", newErr.Error()) return newErr } return nil }
[ "func", "(", "s", "*", "BackendImplementation", ")", "UnmarshalJSONVerbose", "(", "statusCode", "int", ",", "body", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "error", "{", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "// If we got invalid JSON back then something totally unexpected is", "// happening (caused by a bug on the server side). Put a sample of the", "// response body into the error message so we can get a better feel for", "// what the problem was.", "bodySample", ":=", "string", "(", "body", ")", "\n", "if", "len", "(", "bodySample", ")", ">", "500", "{", "bodySample", "=", "bodySample", "[", "0", ":", "500", "]", "+", "\"", "\"", "\n", "}", "\n\n", "// Make sure a multi-line response ends up all on one line", "bodySample", "=", "strings", ".", "Replace", "(", "bodySample", ",", "\"", "\\n", "\"", ",", "\"", "\\\\", "\"", ",", "-", "1", ")", "\n\n", "newErr", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "statusCode", ",", "bodySample", ",", "err", ")", "\n", "s", ".", "LeveledLogger", ".", "Errorf", "(", "\"", "\"", ",", "newErr", ".", "Error", "(", ")", ")", "\n", "return", "newErr", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSONVerbose unmarshals JSON, but in case of a failure logs and // produces a more descriptive error.
[ "UnmarshalJSONVerbose", "unmarshals", "JSON", "but", "in", "case", "of", "a", "failure", "logs", "and", "produces", "a", "more", "descriptive", "error", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L511-L533
148,271
stripe/stripe-go
stripe.go
shouldRetry
func (s *BackendImplementation) shouldRetry(err error, resp *http.Response, numRetries int) bool { if numRetries >= s.MaxNetworkRetries { return false } if err != nil { return true } if resp.StatusCode == http.StatusConflict { return true } return false }
go
func (s *BackendImplementation) shouldRetry(err error, resp *http.Response, numRetries int) bool { if numRetries >= s.MaxNetworkRetries { return false } if err != nil { return true } if resp.StatusCode == http.StatusConflict { return true } return false }
[ "func", "(", "s", "*", "BackendImplementation", ")", "shouldRetry", "(", "err", "error", ",", "resp", "*", "http", ".", "Response", ",", "numRetries", "int", ")", "bool", "{", "if", "numRetries", ">=", "s", ".", "MaxNetworkRetries", "{", "return", "false", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n\n", "if", "resp", ".", "StatusCode", "==", "http", ".", "StatusConflict", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Checks if an error is a problem that we should retry on. This includes both // socket errors that may represent an intermittent problem and some special // HTTP statuses.
[ "Checks", "if", "an", "error", "is", "a", "problem", "that", "we", "should", "retry", "on", ".", "This", "includes", "both", "socket", "errors", "that", "may", "represent", "an", "intermittent", "problem", "and", "some", "special", "HTTP", "statuses", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L538-L551
148,272
stripe/stripe-go
stripe.go
BoolSlice
func BoolSlice(v []bool) []*bool { out := make([]*bool, len(v)) for i := range v { out[i] = &v[i] } return out }
go
func BoolSlice(v []bool) []*bool { out := make([]*bool, len(v)) for i := range v { out[i] = &v[i] } return out }
[ "func", "BoolSlice", "(", "v", "[", "]", "bool", ")", "[", "]", "*", "bool", "{", "out", ":=", "make", "(", "[", "]", "*", "bool", ",", "len", "(", "v", ")", ")", "\n", "for", "i", ":=", "range", "v", "{", "out", "[", "i", "]", "=", "&", "v", "[", "i", "]", "\n", "}", "\n", "return", "out", "\n", "}" ]
// BoolSlice returns a slice of bool pointers given a slice of bools.
[ "BoolSlice", "returns", "a", "slice", "of", "bool", "pointers", "given", "a", "slice", "of", "bools", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L610-L616
148,273
stripe/stripe-go
stripe.go
Float64Slice
func Float64Slice(v []float64) []*float64 { out := make([]*float64, len(v)) for i := range v { out[i] = &v[i] } return out }
go
func Float64Slice(v []float64) []*float64 { out := make([]*float64, len(v)) for i := range v { out[i] = &v[i] } return out }
[ "func", "Float64Slice", "(", "v", "[", "]", "float64", ")", "[", "]", "*", "float64", "{", "out", ":=", "make", "(", "[", "]", "*", "float64", ",", "len", "(", "v", ")", ")", "\n", "for", "i", ":=", "range", "v", "{", "out", "[", "i", "]", "=", "&", "v", "[", "i", "]", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Float64Slice returns a slice of float64 pointers given a slice of float64s.
[ "Float64Slice", "returns", "a", "slice", "of", "float64", "pointers", "given", "a", "slice", "of", "float64s", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L633-L639
148,274
stripe/stripe-go
stripe.go
GetBackend
func GetBackend(backendType SupportedBackend) Backend { var backend Backend backends.mu.RLock() switch backendType { case APIBackend: backend = backends.API case UploadsBackend: backend = backends.Uploads } backends.mu.RUnlock() if backend != nil { return backend } backend = GetBackendWithConfig( backendType, &BackendConfig{ HTTPClient: httpClient, LeveledLogger: DefaultLeveledLogger, LogLevel: LogLevel, Logger: Logger, MaxNetworkRetries: 0, URL: "", // Set by GetBackendWithConfiguation when empty }, ) backends.mu.Lock() defer backends.mu.Unlock() switch backendType { case APIBackend: backends.API = backend case UploadsBackend: backends.Uploads = backend } return backend }
go
func GetBackend(backendType SupportedBackend) Backend { var backend Backend backends.mu.RLock() switch backendType { case APIBackend: backend = backends.API case UploadsBackend: backend = backends.Uploads } backends.mu.RUnlock() if backend != nil { return backend } backend = GetBackendWithConfig( backendType, &BackendConfig{ HTTPClient: httpClient, LeveledLogger: DefaultLeveledLogger, LogLevel: LogLevel, Logger: Logger, MaxNetworkRetries: 0, URL: "", // Set by GetBackendWithConfiguation when empty }, ) backends.mu.Lock() defer backends.mu.Unlock() switch backendType { case APIBackend: backends.API = backend case UploadsBackend: backends.Uploads = backend } return backend }
[ "func", "GetBackend", "(", "backendType", "SupportedBackend", ")", "Backend", "{", "var", "backend", "Backend", "\n\n", "backends", ".", "mu", ".", "RLock", "(", ")", "\n", "switch", "backendType", "{", "case", "APIBackend", ":", "backend", "=", "backends", ".", "API", "\n", "case", "UploadsBackend", ":", "backend", "=", "backends", ".", "Uploads", "\n", "}", "\n", "backends", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "backend", "!=", "nil", "{", "return", "backend", "\n", "}", "\n\n", "backend", "=", "GetBackendWithConfig", "(", "backendType", ",", "&", "BackendConfig", "{", "HTTPClient", ":", "httpClient", ",", "LeveledLogger", ":", "DefaultLeveledLogger", ",", "LogLevel", ":", "LogLevel", ",", "Logger", ":", "Logger", ",", "MaxNetworkRetries", ":", "0", ",", "URL", ":", "\"", "\"", ",", "// Set by GetBackendWithConfiguation when empty", "}", ",", ")", "\n\n", "backends", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "backends", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "switch", "backendType", "{", "case", "APIBackend", ":", "backends", ".", "API", "=", "backend", "\n", "case", "UploadsBackend", ":", "backends", ".", "Uploads", "=", "backend", "\n", "}", "\n\n", "return", "backend", "\n", "}" ]
// GetBackend returns one of the library's supported backends based off of the // given argument. // // It returns an existing default backend if one's already been created.
[ "GetBackend", "returns", "one", "of", "the", "library", "s", "supported", "backends", "based", "off", "of", "the", "given", "argument", ".", "It", "returns", "an", "existing", "default", "backend", "if", "one", "s", "already", "been", "created", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L666-L704
148,275
stripe/stripe-go
stripe.go
GetBackendWithConfig
func GetBackendWithConfig(backendType SupportedBackend, config *BackendConfig) Backend { if config.HTTPClient == nil { config.HTTPClient = httpClient } if config.LeveledLogger == nil { if config.Logger == nil { config.Logger = Logger } config.LeveledLogger = &leveledLoggerPrintferShim{ level: printferLevel(config.LogLevel), logger: config.Logger, } } switch backendType { case APIBackend: if config.URL == "" { config.URL = apiURL } config.URL = normalizeURL(config.URL) return newBackendImplementation(backendType, config) case UploadsBackend: if config.URL == "" { config.URL = uploadsURL } config.URL = normalizeURL(config.URL) return newBackendImplementation(backendType, config) } return nil }
go
func GetBackendWithConfig(backendType SupportedBackend, config *BackendConfig) Backend { if config.HTTPClient == nil { config.HTTPClient = httpClient } if config.LeveledLogger == nil { if config.Logger == nil { config.Logger = Logger } config.LeveledLogger = &leveledLoggerPrintferShim{ level: printferLevel(config.LogLevel), logger: config.Logger, } } switch backendType { case APIBackend: if config.URL == "" { config.URL = apiURL } config.URL = normalizeURL(config.URL) return newBackendImplementation(backendType, config) case UploadsBackend: if config.URL == "" { config.URL = uploadsURL } config.URL = normalizeURL(config.URL) return newBackendImplementation(backendType, config) } return nil }
[ "func", "GetBackendWithConfig", "(", "backendType", "SupportedBackend", ",", "config", "*", "BackendConfig", ")", "Backend", "{", "if", "config", ".", "HTTPClient", "==", "nil", "{", "config", ".", "HTTPClient", "=", "httpClient", "\n", "}", "\n\n", "if", "config", ".", "LeveledLogger", "==", "nil", "{", "if", "config", ".", "Logger", "==", "nil", "{", "config", ".", "Logger", "=", "Logger", "\n", "}", "\n\n", "config", ".", "LeveledLogger", "=", "&", "leveledLoggerPrintferShim", "{", "level", ":", "printferLevel", "(", "config", ".", "LogLevel", ")", ",", "logger", ":", "config", ".", "Logger", ",", "}", "\n", "}", "\n\n", "switch", "backendType", "{", "case", "APIBackend", ":", "if", "config", ".", "URL", "==", "\"", "\"", "{", "config", ".", "URL", "=", "apiURL", "\n", "}", "\n\n", "config", ".", "URL", "=", "normalizeURL", "(", "config", ".", "URL", ")", "\n\n", "return", "newBackendImplementation", "(", "backendType", ",", "config", ")", "\n\n", "case", "UploadsBackend", ":", "if", "config", ".", "URL", "==", "\"", "\"", "{", "config", ".", "URL", "=", "uploadsURL", "\n", "}", "\n\n", "config", ".", "URL", "=", "normalizeURL", "(", "config", ".", "URL", ")", "\n\n", "return", "newBackendImplementation", "(", "backendType", ",", "config", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// GetBackendWithConfig is the same as GetBackend except that it can be given a // configuration struct that will configure certain aspects of the backend // that's return.
[ "GetBackendWithConfig", "is", "the", "same", "as", "GetBackend", "except", "that", "it", "can", "be", "given", "a", "configuration", "struct", "that", "will", "configure", "certain", "aspects", "of", "the", "backend", "that", "s", "return", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L709-L746
148,276
stripe/stripe-go
stripe.go
Int64Slice
func Int64Slice(v []int64) []*int64 { out := make([]*int64, len(v)) for i := range v { out[i] = &v[i] } return out }
go
func Int64Slice(v []int64) []*int64 { out := make([]*int64, len(v)) for i := range v { out[i] = &v[i] } return out }
[ "func", "Int64Slice", "(", "v", "[", "]", "int64", ")", "[", "]", "*", "int64", "{", "out", ":=", "make", "(", "[", "]", "*", "int64", ",", "len", "(", "v", ")", ")", "\n", "for", "i", ":=", "range", "v", "{", "out", "[", "i", "]", "=", "&", "v", "[", "i", "]", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Int64Slice returns a slice of int64 pointers given a slice of int64s.
[ "Int64Slice", "returns", "a", "slice", "of", "int64", "pointers", "given", "a", "slice", "of", "int64s", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L763-L769
148,277
stripe/stripe-go
stripe.go
NewBackends
func NewBackends(httpClient *http.Client) *Backends { apiConfig := &BackendConfig{HTTPClient: httpClient} uploadConfig := &BackendConfig{HTTPClient: httpClient} return &Backends{ API: GetBackendWithConfig(APIBackend, apiConfig), Uploads: GetBackendWithConfig(UploadsBackend, uploadConfig), } }
go
func NewBackends(httpClient *http.Client) *Backends { apiConfig := &BackendConfig{HTTPClient: httpClient} uploadConfig := &BackendConfig{HTTPClient: httpClient} return &Backends{ API: GetBackendWithConfig(APIBackend, apiConfig), Uploads: GetBackendWithConfig(UploadsBackend, uploadConfig), } }
[ "func", "NewBackends", "(", "httpClient", "*", "http", ".", "Client", ")", "*", "Backends", "{", "apiConfig", ":=", "&", "BackendConfig", "{", "HTTPClient", ":", "httpClient", "}", "\n", "uploadConfig", ":=", "&", "BackendConfig", "{", "HTTPClient", ":", "httpClient", "}", "\n", "return", "&", "Backends", "{", "API", ":", "GetBackendWithConfig", "(", "APIBackend", ",", "apiConfig", ")", ",", "Uploads", ":", "GetBackendWithConfig", "(", "UploadsBackend", ",", "uploadConfig", ")", ",", "}", "\n", "}" ]
// NewBackends creates a new set of backends with the given HTTP client. You // should only need to use this for testing purposes or on App Engine.
[ "NewBackends", "creates", "a", "new", "set", "of", "backends", "with", "the", "given", "HTTP", "client", ".", "You", "should", "only", "need", "to", "use", "this", "for", "testing", "purposes", "or", "on", "App", "Engine", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L773-L780
148,278
stripe/stripe-go
stripe.go
SetAppInfo
func SetAppInfo(info *AppInfo) { if info != nil && info.Name == "" { panic(fmt.Errorf("App info name cannot be empty")) } appInfo = info // This is run in init, but we need to reinitialize it now that we have // some app info. initUserAgent() }
go
func SetAppInfo(info *AppInfo) { if info != nil && info.Name == "" { panic(fmt.Errorf("App info name cannot be empty")) } appInfo = info // This is run in init, but we need to reinitialize it now that we have // some app info. initUserAgent() }
[ "func", "SetAppInfo", "(", "info", "*", "AppInfo", ")", "{", "if", "info", "!=", "nil", "&&", "info", ".", "Name", "==", "\"", "\"", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "appInfo", "=", "info", "\n\n", "// This is run in init, but we need to reinitialize it now that we have", "// some app info.", "initUserAgent", "(", ")", "\n", "}" ]
// SetAppInfo sets app information. See AppInfo.
[ "SetAppInfo", "sets", "app", "information", ".", "See", "AppInfo", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L804-L813
148,279
stripe/stripe-go
stripe.go
SetBackend
func SetBackend(backend SupportedBackend, b Backend) { switch backend { case APIBackend: backends.API = b case UploadsBackend: backends.Uploads = b } }
go
func SetBackend(backend SupportedBackend, b Backend) { switch backend { case APIBackend: backends.API = b case UploadsBackend: backends.Uploads = b } }
[ "func", "SetBackend", "(", "backend", "SupportedBackend", ",", "b", "Backend", ")", "{", "switch", "backend", "{", "case", "APIBackend", ":", "backends", ".", "API", "=", "b", "\n", "case", "UploadsBackend", ":", "backends", ".", "Uploads", "=", "b", "\n", "}", "\n", "}" ]
// SetBackend sets the backend used in the binding.
[ "SetBackend", "sets", "the", "backend", "used", "in", "the", "binding", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L816-L823
148,280
stripe/stripe-go
stripe.go
StringSlice
func StringSlice(v []string) []*string { out := make([]*string, len(v)) for i := range v { out[i] = &v[i] } return out }
go
func StringSlice(v []string) []*string { out := make([]*string, len(v)) for i := range v { out[i] = &v[i] } return out }
[ "func", "StringSlice", "(", "v", "[", "]", "string", ")", "[", "]", "*", "string", "{", "out", ":=", "make", "(", "[", "]", "*", "string", ",", "len", "(", "v", ")", ")", "\n", "for", "i", ":=", "range", "v", "{", "out", "[", "i", "]", "=", "&", "v", "[", "i", "]", "\n", "}", "\n", "return", "out", "\n", "}" ]
// StringSlice returns a slice of string pointers given a slice of strings.
[ "StringSlice", "returns", "a", "slice", "of", "string", "pointers", "given", "a", "slice", "of", "strings", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L847-L853
148,281
stripe/stripe-go
stripe.go
newBackendImplementation
func newBackendImplementation(backendType SupportedBackend, config *BackendConfig) Backend { var requestMetricsBuffer chan requestMetrics enableTelemetry := config.EnableTelemetry || EnableTelemetry // only allocate the requestMetrics buffer if client telemetry is enabled. if enableTelemetry { requestMetricsBuffer = make(chan requestMetrics, telemetryBufferSize) } return &BackendImplementation{ HTTPClient: config.HTTPClient, LeveledLogger: config.LeveledLogger, MaxNetworkRetries: config.MaxNetworkRetries, Type: backendType, URL: config.URL, enableTelemetry: enableTelemetry, networkRetriesSleep: true, requestMetricsBuffer: requestMetricsBuffer, } }
go
func newBackendImplementation(backendType SupportedBackend, config *BackendConfig) Backend { var requestMetricsBuffer chan requestMetrics enableTelemetry := config.EnableTelemetry || EnableTelemetry // only allocate the requestMetrics buffer if client telemetry is enabled. if enableTelemetry { requestMetricsBuffer = make(chan requestMetrics, telemetryBufferSize) } return &BackendImplementation{ HTTPClient: config.HTTPClient, LeveledLogger: config.LeveledLogger, MaxNetworkRetries: config.MaxNetworkRetries, Type: backendType, URL: config.URL, enableTelemetry: enableTelemetry, networkRetriesSleep: true, requestMetricsBuffer: requestMetricsBuffer, } }
[ "func", "newBackendImplementation", "(", "backendType", "SupportedBackend", ",", "config", "*", "BackendConfig", ")", "Backend", "{", "var", "requestMetricsBuffer", "chan", "requestMetrics", "\n", "enableTelemetry", ":=", "config", ".", "EnableTelemetry", "||", "EnableTelemetry", "\n\n", "// only allocate the requestMetrics buffer if client telemetry is enabled.", "if", "enableTelemetry", "{", "requestMetricsBuffer", "=", "make", "(", "chan", "requestMetrics", ",", "telemetryBufferSize", ")", "\n", "}", "\n\n", "return", "&", "BackendImplementation", "{", "HTTPClient", ":", "config", ".", "HTTPClient", ",", "LeveledLogger", ":", "config", ".", "LeveledLogger", ",", "MaxNetworkRetries", ":", "config", ".", "MaxNetworkRetries", ",", "Type", ":", "backendType", ",", "URL", ":", "config", ".", "URL", ",", "enableTelemetry", ":", "enableTelemetry", ",", "networkRetriesSleep", ":", "true", ",", "requestMetricsBuffer", ":", "requestMetricsBuffer", ",", "}", "\n", "}" ]
// newBackendImplementation returns a new Backend based off a given type and // fully initialized BackendConfig struct. // // The vast majority of the time you should be calling GetBackendWithConfig // instead of this function.
[ "newBackendImplementation", "returns", "a", "new", "Backend", "based", "off", "a", "given", "type", "and", "fully", "initialized", "BackendConfig", "struct", ".", "The", "vast", "majority", "of", "the", "time", "you", "should", "be", "calling", "GetBackendWithConfig", "instead", "of", "this", "function", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L989-L1008
148,282
stripe/stripe-go
dispute.go
UnmarshalJSON
func (d *Dispute) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { d.ID = id return nil } type dispute Dispute var v dispute if err := json.Unmarshal(data, &v); err != nil { return err } *d = Dispute(v) return nil }
go
func (d *Dispute) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { d.ID = id return nil } type dispute Dispute var v dispute if err := json.Unmarshal(data, &v); err != nil { return err } *d = Dispute(v) return nil }
[ "func", "(", "d", "*", "Dispute", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "d", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "dispute", "Dispute", "\n", "var", "v", "dispute", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "d", "=", "Dispute", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of a Dispute. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "Dispute", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/dispute.go#L155-L169
148,283
stripe/stripe-go
account/client.go
Get
func (c Client) Get() (*stripe.Account, error) { account := &stripe.Account{} err := c.B.Call(http.MethodGet, "/v1/account", c.Key, nil, account) return account, err }
go
func (c Client) Get() (*stripe.Account, error) { account := &stripe.Account{} err := c.B.Call(http.MethodGet, "/v1/account", c.Key, nil, account) return account, err }
[ "func", "(", "c", "Client", ")", "Get", "(", ")", "(", "*", "stripe", ".", "Account", ",", "error", ")", "{", "account", ":=", "&", "stripe", ".", "Account", "{", "}", "\n", "err", ":=", "c", ".", "B", ".", "Call", "(", "http", ".", "MethodGet", ",", "\"", "\"", ",", "c", ".", "Key", ",", "nil", ",", "account", ")", "\n", "return", "account", ",", "err", "\n", "}" ]
// Get retrieves the authenticating account.
[ "Get", "retrieves", "the", "authenticating", "account", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/account/client.go#L37-L41
148,284
stripe/stripe-go
account/client.go
Del
func (c Client) Del(id string, params *stripe.AccountParams) (*stripe.Account, error) { path := stripe.FormatURLPath("/v1/accounts/%s", id) acct := &stripe.Account{} err := c.B.Call(http.MethodDelete, path, c.Key, params, acct) return acct, err }
go
func (c Client) Del(id string, params *stripe.AccountParams) (*stripe.Account, error) { path := stripe.FormatURLPath("/v1/accounts/%s", id) acct := &stripe.Account{} err := c.B.Call(http.MethodDelete, path, c.Key, params, acct) return acct, err }
[ "func", "(", "c", "Client", ")", "Del", "(", "id", "string", ",", "params", "*", "stripe", ".", "AccountParams", ")", "(", "*", "stripe", ".", "Account", ",", "error", ")", "{", "path", ":=", "stripe", ".", "FormatURLPath", "(", "\"", "\"", ",", "id", ")", "\n", "acct", ":=", "&", "stripe", ".", "Account", "{", "}", "\n", "err", ":=", "c", ".", "B", ".", "Call", "(", "http", ".", "MethodDelete", ",", "path", ",", "c", ".", "Key", ",", "params", ",", "acct", ")", "\n", "return", "acct", ",", "err", "\n", "}" ]
// Del deletes an account.
[ "Del", "deletes", "an", "account", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/account/client.go#L75-L80
148,285
stripe/stripe-go
account/client.go
Reject
func Reject(id string, params *stripe.AccountRejectParams) (*stripe.Account, error) { return getC().Reject(id, params) }
go
func Reject(id string, params *stripe.AccountRejectParams) (*stripe.Account, error) { return getC().Reject(id, params) }
[ "func", "Reject", "(", "id", "string", ",", "params", "*", "stripe", ".", "AccountRejectParams", ")", "(", "*", "stripe", ".", "Account", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "Reject", "(", "id", ",", "params", ")", "\n", "}" ]
// Reject rejects an account.
[ "Reject", "rejects", "an", "account", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/account/client.go#L83-L85
148,286
stripe/stripe-go
reversal/client.go
New
func New(params *stripe.ReversalParams) (*stripe.Reversal, error) { return getC().New(params) }
go
func New(params *stripe.ReversalParams) (*stripe.Reversal, error) { return getC().New(params) }
[ "func", "New", "(", "params", "*", "stripe", ".", "ReversalParams", ")", "(", "*", "stripe", ".", "Reversal", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "New", "(", "params", ")", "\n", "}" ]
// New creates a new transfer reversal.
[ "New", "creates", "a", "new", "transfer", "reversal", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/reversal/client.go#L19-L21
148,287
stripe/stripe-go
reversal/client.go
Update
func (c Client) Update(id string, params *stripe.ReversalParams) (*stripe.Reversal, error) { path := stripe.FormatURLPath("/v1/transfers/%s/reversals/%s", stripe.StringValue(params.Transfer), id) reversal := &stripe.Reversal{} err := c.B.Call(http.MethodPost, path, c.Key, params, reversal) return reversal, err }
go
func (c Client) Update(id string, params *stripe.ReversalParams) (*stripe.Reversal, error) { path := stripe.FormatURLPath("/v1/transfers/%s/reversals/%s", stripe.StringValue(params.Transfer), id) reversal := &stripe.Reversal{} err := c.B.Call(http.MethodPost, path, c.Key, params, reversal) return reversal, err }
[ "func", "(", "c", "Client", ")", "Update", "(", "id", "string", ",", "params", "*", "stripe", ".", "ReversalParams", ")", "(", "*", "stripe", ".", "Reversal", ",", "error", ")", "{", "path", ":=", "stripe", ".", "FormatURLPath", "(", "\"", "\"", ",", "stripe", ".", "StringValue", "(", "params", ".", "Transfer", ")", ",", "id", ")", "\n", "reversal", ":=", "&", "stripe", ".", "Reversal", "{", "}", "\n", "err", ":=", "c", ".", "B", ".", "Call", "(", "http", ".", "MethodPost", ",", "path", ",", "c", ".", "Key", ",", "params", ",", "reversal", ")", "\n", "return", "reversal", ",", "err", "\n", "}" ]
// Update updates a transfer reversal's properties.
[ "Update", "updates", "a", "transfer", "reversal", "s", "properties", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/reversal/client.go#L55-L61
148,288
stripe/stripe-go
bitcoinreceiver/client.go
Get
func (c Client) Get(id string) (*stripe.BitcoinReceiver, error) { path := stripe.FormatURLPath("/v1/bitcoin/receivers/%s", id) bitcoinReceiver := &stripe.BitcoinReceiver{} err := c.B.Call(http.MethodGet, path, c.Key, nil, bitcoinReceiver) return bitcoinReceiver, err }
go
func (c Client) Get(id string) (*stripe.BitcoinReceiver, error) { path := stripe.FormatURLPath("/v1/bitcoin/receivers/%s", id) bitcoinReceiver := &stripe.BitcoinReceiver{} err := c.B.Call(http.MethodGet, path, c.Key, nil, bitcoinReceiver) return bitcoinReceiver, err }
[ "func", "(", "c", "Client", ")", "Get", "(", "id", "string", ")", "(", "*", "stripe", ".", "BitcoinReceiver", ",", "error", ")", "{", "path", ":=", "stripe", ".", "FormatURLPath", "(", "\"", "\"", ",", "id", ")", "\n", "bitcoinReceiver", ":=", "&", "stripe", ".", "BitcoinReceiver", "{", "}", "\n", "err", ":=", "c", ".", "B", ".", "Call", "(", "http", ".", "MethodGet", ",", "path", ",", "c", ".", "Key", ",", "nil", ",", "bitcoinReceiver", ")", "\n", "return", "bitcoinReceiver", ",", "err", "\n", "}" ]
// Get returns the details of a bitcoin receiver.
[ "Get", "returns", "the", "details", "of", "a", "bitcoin", "receiver", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/bitcoinreceiver/client.go#L26-L31
148,289
stripe/stripe-go
subitem/client.go
Get
func (c Client) Get(id string, params *stripe.SubscriptionItemParams) (*stripe.SubscriptionItem, error) { path := stripe.FormatURLPath("/v1/subscription_items/%s", id) item := &stripe.SubscriptionItem{} err := c.B.Call(http.MethodGet, path, c.Key, params, item) return item, err }
go
func (c Client) Get(id string, params *stripe.SubscriptionItemParams) (*stripe.SubscriptionItem, error) { path := stripe.FormatURLPath("/v1/subscription_items/%s", id) item := &stripe.SubscriptionItem{} err := c.B.Call(http.MethodGet, path, c.Key, params, item) return item, err }
[ "func", "(", "c", "Client", ")", "Get", "(", "id", "string", ",", "params", "*", "stripe", ".", "SubscriptionItemParams", ")", "(", "*", "stripe", ".", "SubscriptionItem", ",", "error", ")", "{", "path", ":=", "stripe", ".", "FormatURLPath", "(", "\"", "\"", ",", "id", ")", "\n", "item", ":=", "&", "stripe", ".", "SubscriptionItem", "{", "}", "\n", "err", ":=", "c", ".", "B", ".", "Call", "(", "http", ".", "MethodGet", ",", "path", ",", "c", ".", "Key", ",", "params", ",", "item", ")", "\n", "return", "item", ",", "err", "\n", "}" ]
// Get returns the details of a subscription item.
[ "Get", "returns", "the", "details", "of", "a", "subscription", "item", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/subitem/client.go#L35-L40
148,290
stripe/stripe-go
coupon.go
UnmarshalJSON
func (c *Coupon) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { c.ID = id return nil } type coupon Coupon var v coupon if err := json.Unmarshal(data, &v); err != nil { return err } *c = Coupon(v) return nil }
go
func (c *Coupon) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { c.ID = id return nil } type coupon Coupon var v coupon if err := json.Unmarshal(data, &v); err != nil { return err } *c = Coupon(v) return nil }
[ "func", "(", "c", "*", "Coupon", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "c", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "coupon", "Coupon", "\n", "var", "v", "coupon", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "c", "=", "Coupon", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of a Coupon. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "Coupon", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/coupon.go#L67-L81
148,291
stripe/stripe-go
balance.go
UnmarshalJSON
func (t *BalanceTransaction) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { t.ID = id return nil } type balanceTransaction BalanceTransaction var v balanceTransaction if err := json.Unmarshal(data, &v); err != nil { return err } *t = BalanceTransaction(v) return nil }
go
func (t *BalanceTransaction) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { t.ID = id return nil } type balanceTransaction BalanceTransaction var v balanceTransaction if err := json.Unmarshal(data, &v); err != nil { return err } *t = BalanceTransaction(v) return nil }
[ "func", "(", "t", "*", "BalanceTransaction", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "t", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "balanceTransaction", "BalanceTransaction", "\n", "var", "v", "balanceTransaction", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "t", "=", "BalanceTransaction", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of a Transaction. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "Transaction", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/balance.go#L153-L167
148,292
stripe/stripe-go
balance.go
UnmarshalJSON
func (s *BalanceTransactionSource) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { s.ID = id return nil } type balanceTransactionSource BalanceTransactionSource var v balanceTransactionSource if err := json.Unmarshal(data, &v); err != nil { return err } var err error *s = BalanceTransactionSource(v) switch s.Type { case BalanceTransactionSourceTypeApplicationFee: err = json.Unmarshal(data, &s.ApplicationFee) case BalanceTransactionSourceTypeCharge: err = json.Unmarshal(data, &s.Charge) case BalanceTransactionSourceTypeDispute: err = json.Unmarshal(data, &s.Dispute) case BalanceTransactionSourceTypeIssuingAuthorization: err = json.Unmarshal(data, &s.IssuingAuthorization) case BalanceTransactionSourceTypeIssuingTransaction: err = json.Unmarshal(data, &s.IssuingTransaction) case BalanceTransactionSourceTypePayout: err = json.Unmarshal(data, &s.Payout) case BalanceTransactionSourceTypeRecipientTransfer: err = json.Unmarshal(data, &s.RecipientTransfer) case BalanceTransactionSourceTypeRefund: err = json.Unmarshal(data, &s.Refund) case BalanceTransactionSourceTypeReversal: err = json.Unmarshal(data, &s.Reversal) case BalanceTransactionSourceTypeTransfer: err = json.Unmarshal(data, &s.Transfer) } return err }
go
func (s *BalanceTransactionSource) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { s.ID = id return nil } type balanceTransactionSource BalanceTransactionSource var v balanceTransactionSource if err := json.Unmarshal(data, &v); err != nil { return err } var err error *s = BalanceTransactionSource(v) switch s.Type { case BalanceTransactionSourceTypeApplicationFee: err = json.Unmarshal(data, &s.ApplicationFee) case BalanceTransactionSourceTypeCharge: err = json.Unmarshal(data, &s.Charge) case BalanceTransactionSourceTypeDispute: err = json.Unmarshal(data, &s.Dispute) case BalanceTransactionSourceTypeIssuingAuthorization: err = json.Unmarshal(data, &s.IssuingAuthorization) case BalanceTransactionSourceTypeIssuingTransaction: err = json.Unmarshal(data, &s.IssuingTransaction) case BalanceTransactionSourceTypePayout: err = json.Unmarshal(data, &s.Payout) case BalanceTransactionSourceTypeRecipientTransfer: err = json.Unmarshal(data, &s.RecipientTransfer) case BalanceTransactionSourceTypeRefund: err = json.Unmarshal(data, &s.Refund) case BalanceTransactionSourceTypeReversal: err = json.Unmarshal(data, &s.Reversal) case BalanceTransactionSourceTypeTransfer: err = json.Unmarshal(data, &s.Transfer) } return err }
[ "func", "(", "s", "*", "BalanceTransactionSource", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "s", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "balanceTransactionSource", "BalanceTransactionSource", "\n", "var", "v", "balanceTransactionSource", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "err", "error", "\n", "*", "s", "=", "BalanceTransactionSource", "(", "v", ")", "\n\n", "switch", "s", ".", "Type", "{", "case", "BalanceTransactionSourceTypeApplicationFee", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "ApplicationFee", ")", "\n", "case", "BalanceTransactionSourceTypeCharge", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "Charge", ")", "\n", "case", "BalanceTransactionSourceTypeDispute", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "Dispute", ")", "\n", "case", "BalanceTransactionSourceTypeIssuingAuthorization", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "IssuingAuthorization", ")", "\n", "case", "BalanceTransactionSourceTypeIssuingTransaction", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "IssuingTransaction", ")", "\n", "case", "BalanceTransactionSourceTypePayout", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "Payout", ")", "\n", "case", "BalanceTransactionSourceTypeRecipientTransfer", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "RecipientTransfer", ")", "\n", "case", "BalanceTransactionSourceTypeRefund", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "Refund", ")", "\n", "case", "BalanceTransactionSourceTypeReversal", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "Reversal", ")", "\n", "case", "BalanceTransactionSourceTypeTransfer", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "Transfer", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// UnmarshalJSON handles deserialization of a BalanceTransactionSource. // This custom unmarshaling is needed because the specific // type of transaction source it refers to is specified in the JSON
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "BalanceTransactionSource", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "specific", "type", "of", "transaction", "source", "it", "refers", "to", "is", "specified", "in", "the", "JSON" ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/balance.go#L172-L211
148,293
stripe/stripe-go
fee/client.go
Get
func Get(id string, params *stripe.ApplicationFeeParams) (*stripe.ApplicationFee, error) { return getC().Get(id, params) }
go
func Get(id string, params *stripe.ApplicationFeeParams) (*stripe.ApplicationFee, error) { return getC().Get(id, params) }
[ "func", "Get", "(", "id", "string", ",", "params", "*", "stripe", ".", "ApplicationFeeParams", ")", "(", "*", "stripe", ".", "ApplicationFee", ",", "error", ")", "{", "return", "getC", "(", ")", ".", "Get", "(", "id", ",", "params", ")", "\n", "}" ]
// Get returns the details of an application fee.
[ "Get", "returns", "the", "details", "of", "an", "application", "fee", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/fee/client.go#L18-L20
148,294
stripe/stripe-go
order.go
SetSource
func (op *OrderPayParams) SetSource(sp interface{}) error { source, err := SourceParamsFor(sp) op.Source = source return err }
go
func (op *OrderPayParams) SetSource(sp interface{}) error { source, err := SourceParamsFor(sp) op.Source = source return err }
[ "func", "(", "op", "*", "OrderPayParams", ")", "SetSource", "(", "sp", "interface", "{", "}", ")", "error", "{", "source", ",", "err", ":=", "SourceParamsFor", "(", "sp", ")", "\n", "op", ".", "Source", "=", "source", "\n", "return", "err", "\n", "}" ]
// SetSource adds valid sources to a OrderParams object, // returning an error for unsupported sources.
[ "SetSource", "adds", "valid", "sources", "to", "a", "OrderParams", "object", "returning", "an", "error", "for", "unsupported", "sources", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/order.go#L224-L228
148,295
stripe/stripe-go
order.go
UnmarshalJSON
func (p *OrderItemParent) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { p.ID = id return nil } type orderItemParent OrderItemParent var v orderItemParent if err := json.Unmarshal(data, &v); err != nil { return err } var err error *p = OrderItemParent(v) switch p.Type { case OrderItemParentTypeSKU: // Currently only SKUs `parent` is returned as an object when expanded. // For other items only IDs are returned. if err = json.Unmarshal(data, &p.SKU); err != nil { return err } p.ID = p.SKU.ID } return nil }
go
func (p *OrderItemParent) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { p.ID = id return nil } type orderItemParent OrderItemParent var v orderItemParent if err := json.Unmarshal(data, &v); err != nil { return err } var err error *p = OrderItemParent(v) switch p.Type { case OrderItemParentTypeSKU: // Currently only SKUs `parent` is returned as an object when expanded. // For other items only IDs are returned. if err = json.Unmarshal(data, &p.SKU); err != nil { return err } p.ID = p.SKU.ID } return nil }
[ "func", "(", "p", "*", "OrderItemParent", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "p", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "orderItemParent", "OrderItemParent", "\n", "var", "v", "orderItemParent", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "err", "error", "\n", "*", "p", "=", "OrderItemParent", "(", "v", ")", "\n\n", "switch", "p", ".", "Type", "{", "case", "OrderItemParentTypeSKU", ":", "// Currently only SKUs `parent` is returned as an object when expanded.", "// For other items only IDs are returned.", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "p", ".", "SKU", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "ID", "=", "p", ".", "SKU", ".", "ID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of an OrderItemParent. // This custom unmarshaling is needed because the resulting // property may be an id or a full SKU struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "an", "OrderItemParent", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "a", "full", "SKU", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/order.go#L233-L259
148,296
stripe/stripe-go
order.go
UnmarshalJSON
func (o *Order) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { o.ID = id return nil } type order Order var v order if err := json.Unmarshal(data, &v); err != nil { return err } *o = Order(v) return nil }
go
func (o *Order) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { o.ID = id return nil } type order Order var v order if err := json.Unmarshal(data, &v); err != nil { return err } *o = Order(v) return nil }
[ "func", "(", "o", "*", "Order", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "o", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "order", "Order", "\n", "var", "v", "order", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "o", "=", "Order", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of an Order. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "an", "Order", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/order.go#L264-L278
148,297
stripe/stripe-go
paymentmethod.go
UnmarshalJSON
func (i *PaymentMethod) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { i.ID = id return nil } type pm PaymentMethod var v pm if err := json.Unmarshal(data, &v); err != nil { return err } *i = PaymentMethod(v) return nil }
go
func (i *PaymentMethod) UnmarshalJSON(data []byte) error { if id, ok := ParseID(data); ok { i.ID = id return nil } type pm PaymentMethod var v pm if err := json.Unmarshal(data, &v); err != nil { return err } *i = PaymentMethod(v) return nil }
[ "func", "(", "i", "*", "PaymentMethod", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "id", ",", "ok", ":=", "ParseID", "(", "data", ")", ";", "ok", "{", "i", ".", "ID", "=", "id", "\n", "return", "nil", "\n", "}", "\n\n", "type", "pm", "PaymentMethod", "\n", "var", "v", "pm", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "i", "=", "PaymentMethod", "(", "v", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON handles deserialization of a PaymentMethod. // This custom unmarshaling is needed because the resulting // property may be an id or the full struct if it was expanded.
[ "UnmarshalJSON", "handles", "deserialization", "of", "a", "PaymentMethod", ".", "This", "custom", "unmarshaling", "is", "needed", "because", "the", "resulting", "property", "may", "be", "an", "id", "or", "the", "full", "struct", "if", "it", "was", "expanded", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/paymentmethod.go#L169-L183
148,298
stripe/stripe-go
form/form.go
AppendTo
func AppendTo(values *Values, i interface{}) { reflectValue(values, reflect.ValueOf(i), false, nil) }
go
func AppendTo(values *Values, i interface{}) { reflectValue(values, reflect.ValueOf(i), false, nil) }
[ "func", "AppendTo", "(", "values", "*", "Values", ",", "i", "interface", "{", "}", ")", "{", "reflectValue", "(", "values", ",", "reflect", ".", "ValueOf", "(", "i", ")", ",", "false", ",", "nil", ")", "\n", "}" ]
// AppendTo uses reflection to form encode into the given values collection // based off the form tags that it defines.
[ "AppendTo", "uses", "reflection", "to", "form", "encode", "into", "the", "given", "values", "collection", "based", "off", "the", "form", "tags", "that", "it", "defines", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/form/form.go#L104-L106
148,299
stripe/stripe-go
form/form.go
AppendToPrefixed
func AppendToPrefixed(values *Values, i interface{}, keyParts []string) { reflectValue(values, reflect.ValueOf(i), false, keyParts) }
go
func AppendToPrefixed(values *Values, i interface{}, keyParts []string) { reflectValue(values, reflect.ValueOf(i), false, keyParts) }
[ "func", "AppendToPrefixed", "(", "values", "*", "Values", ",", "i", "interface", "{", "}", ",", "keyParts", "[", "]", "string", ")", "{", "reflectValue", "(", "values", ",", "reflect", ".", "ValueOf", "(", "i", ")", ",", "false", ",", "keyParts", ")", "\n", "}" ]
// AppendToPrefixed is the same as AppendTo, but it allows a slice of key parts // to be specified to prefix the form values. // // I was hoping not to have to expose this function, but I ended up needing it // for recipients. Recipients is going away, and when it does, we can probably // remove it again.
[ "AppendToPrefixed", "is", "the", "same", "as", "AppendTo", "but", "it", "allows", "a", "slice", "of", "key", "parts", "to", "be", "specified", "to", "prefix", "the", "form", "values", ".", "I", "was", "hoping", "not", "to", "have", "to", "expose", "this", "function", "but", "I", "ended", "up", "needing", "it", "for", "recipients", ".", "Recipients", "is", "going", "away", "and", "when", "it", "does", "we", "can", "probably", "remove", "it", "again", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/form/form.go#L114-L116