repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
emersion/go-imap
command.go
Parse
func (cmd *Command) Parse(fields []interface{}) error { if len(fields) < 2 { return errors.New("imap: cannot parse command: no enough fields") } var ok bool if cmd.Tag, ok = fields[0].(string); !ok { return errors.New("imap: cannot parse command: invalid tag") } if cmd.Name, ok = fields[1].(string); !ok { return errors.New("imap: cannot parse command: invalid name") } cmd.Name = strings.ToUpper(cmd.Name) // Command names are case-insensitive cmd.Arguments = fields[2:] return nil }
go
func (cmd *Command) Parse(fields []interface{}) error { if len(fields) < 2 { return errors.New("imap: cannot parse command: no enough fields") } var ok bool if cmd.Tag, ok = fields[0].(string); !ok { return errors.New("imap: cannot parse command: invalid tag") } if cmd.Name, ok = fields[1].(string); !ok { return errors.New("imap: cannot parse command: invalid name") } cmd.Name = strings.ToUpper(cmd.Name) // Command names are case-insensitive cmd.Arguments = fields[2:] return nil }
[ "func", "(", "cmd", "*", "Command", ")", "Parse", "(", "fields", "[", "]", "interface", "{", "}", ")", "error", "{", "if", "len", "(", "fields", ")", "<", "2", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var",...
// Parse a command from fields.
[ "Parse", "a", "command", "from", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/command.go#L41-L57
train
emersion/go-imap
client/cmd_auth.go
Select
func (c *Client) Select(name string, readOnly bool) (*imap.MailboxStatus, error) { if err := c.ensureAuthenticated(); err != nil { return nil, err } cmd := &commands.Select{ Mailbox: name, ReadOnly: readOnly, } mbox := &imap.MailboxStatus{Name: name, Items: make(map[imap.StatusItem]interface{})} res := &responses.Select{ Mailbox: mbox, } c.locker.Lock() c.mailbox = mbox c.locker.Unlock() status, err := c.execute(cmd, res) if err != nil { c.locker.Lock() c.mailbox = nil c.locker.Unlock() return nil, err } if err := status.Err(); err != nil { c.locker.Lock() c.mailbox = nil c.locker.Unlock() return nil, err } c.locker.Lock() mbox.ReadOnly = (status.Code == imap.CodeReadOnly) c.state = imap.SelectedState c.locker.Unlock() return mbox, nil }
go
func (c *Client) Select(name string, readOnly bool) (*imap.MailboxStatus, error) { if err := c.ensureAuthenticated(); err != nil { return nil, err } cmd := &commands.Select{ Mailbox: name, ReadOnly: readOnly, } mbox := &imap.MailboxStatus{Name: name, Items: make(map[imap.StatusItem]interface{})} res := &responses.Select{ Mailbox: mbox, } c.locker.Lock() c.mailbox = mbox c.locker.Unlock() status, err := c.execute(cmd, res) if err != nil { c.locker.Lock() c.mailbox = nil c.locker.Unlock() return nil, err } if err := status.Err(); err != nil { c.locker.Lock() c.mailbox = nil c.locker.Unlock() return nil, err } c.locker.Lock() mbox.ReadOnly = (status.Code == imap.CodeReadOnly) c.state = imap.SelectedState c.locker.Unlock() return mbox, nil }
[ "func", "(", "c", "*", "Client", ")", "Select", "(", "name", "string", ",", "readOnly", "bool", ")", "(", "*", "imap", ".", "MailboxStatus", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "ensureAuthenticated", "(", ")", ";", "err", "!=", "ni...
// Select selects a mailbox so that messages in the mailbox can be accessed. Any // currently selected mailbox is deselected before attempting the new selection. // Even if the readOnly parameter is set to false, the server can decide to open // the mailbox in read-only mode.
[ "Select", "selects", "a", "mailbox", "so", "that", "messages", "in", "the", "mailbox", "can", "be", "accessed", ".", "Any", "currently", "selected", "mailbox", "is", "deselected", "before", "attempting", "the", "new", "selection", ".", "Even", "if", "the", "...
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_auth.go#L28-L65
train
emersion/go-imap
client/cmd_auth.go
Rename
func (c *Client) Rename(existingName, newName string) error { if err := c.ensureAuthenticated(); err != nil { return err } cmd := &commands.Rename{ Existing: existingName, New: newName, } status, err := c.execute(cmd, nil) if err != nil { return err } return status.Err() }
go
func (c *Client) Rename(existingName, newName string) error { if err := c.ensureAuthenticated(); err != nil { return err } cmd := &commands.Rename{ Existing: existingName, New: newName, } status, err := c.execute(cmd, nil) if err != nil { return err } return status.Err() }
[ "func", "(", "c", "*", "Client", ")", "Rename", "(", "existingName", ",", "newName", "string", ")", "error", "{", "if", "err", ":=", "c", ".", "ensureAuthenticated", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cmd", ...
// Rename changes the name of a mailbox.
[ "Rename", "changes", "the", "name", "of", "a", "mailbox", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_auth.go#L102-L117
train
emersion/go-imap
client/cmd_auth.go
Subscribe
func (c *Client) Subscribe(name string) error { if err := c.ensureAuthenticated(); err != nil { return err } cmd := &commands.Subscribe{ Mailbox: name, } status, err := c.execute(cmd, nil) if err != nil { return err } return status.Err() }
go
func (c *Client) Subscribe(name string) error { if err := c.ensureAuthenticated(); err != nil { return err } cmd := &commands.Subscribe{ Mailbox: name, } status, err := c.execute(cmd, nil) if err != nil { return err } return status.Err() }
[ "func", "(", "c", "*", "Client", ")", "Subscribe", "(", "name", "string", ")", "error", "{", "if", "err", ":=", "c", ".", "ensureAuthenticated", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cmd", ":=", "&", "commands...
// Subscribe adds the specified mailbox name to the server's set of "active" or // "subscribed" mailboxes.
[ "Subscribe", "adds", "the", "specified", "mailbox", "name", "to", "the", "server", "s", "set", "of", "active", "or", "subscribed", "mailboxes", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_auth.go#L121-L135
train
emersion/go-imap
client/cmd_auth.go
Status
func (c *Client) Status(name string, items []imap.StatusItem) (*imap.MailboxStatus, error) { if err := c.ensureAuthenticated(); err != nil { return nil, err } cmd := &commands.Status{ Mailbox: name, Items: items, } res := &responses.Status{ Mailbox: new(imap.MailboxStatus), } status, err := c.execute(cmd, res) if err != nil { return nil, err } return res.Mailbox, status.Err() }
go
func (c *Client) Status(name string, items []imap.StatusItem) (*imap.MailboxStatus, error) { if err := c.ensureAuthenticated(); err != nil { return nil, err } cmd := &commands.Status{ Mailbox: name, Items: items, } res := &responses.Status{ Mailbox: new(imap.MailboxStatus), } status, err := c.execute(cmd, res) if err != nil { return nil, err } return res.Mailbox, status.Err() }
[ "func", "(", "c", "*", "Client", ")", "Status", "(", "name", "string", ",", "items", "[", "]", "imap", ".", "StatusItem", ")", "(", "*", "imap", ".", "MailboxStatus", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "ensureAuthenticated", "(", ...
// Status requests the status of the indicated mailbox. It does not change the // currently selected mailbox, nor does it affect the state of any messages in // the queried mailbox. // // See RFC 3501 section 6.3.10 for a list of items that can be requested.
[ "Status", "requests", "the", "status", "of", "the", "indicated", "mailbox", ".", "It", "does", "not", "change", "the", "currently", "selected", "mailbox", "nor", "does", "it", "affect", "the", "state", "of", "any", "messages", "in", "the", "queried", "mailbo...
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_auth.go#L213-L231
train
emersion/go-imap
client/cmd_auth.go
Append
func (c *Client) Append(mbox string, flags []string, date time.Time, msg imap.Literal) error { if err := c.ensureAuthenticated(); err != nil { return err } cmd := &commands.Append{ Mailbox: mbox, Flags: flags, Date: date, Message: msg, } status, err := c.execute(cmd, nil) if err != nil { return err } return status.Err() }
go
func (c *Client) Append(mbox string, flags []string, date time.Time, msg imap.Literal) error { if err := c.ensureAuthenticated(); err != nil { return err } cmd := &commands.Append{ Mailbox: mbox, Flags: flags, Date: date, Message: msg, } status, err := c.execute(cmd, nil) if err != nil { return err } return status.Err() }
[ "func", "(", "c", "*", "Client", ")", "Append", "(", "mbox", "string", ",", "flags", "[", "]", "string", ",", "date", "time", ".", "Time", ",", "msg", "imap", ".", "Literal", ")", "error", "{", "if", "err", ":=", "c", ".", "ensureAuthenticated", "(...
// Append appends the literal argument as a new message to the end of the // specified destination mailbox. This argument SHOULD be in the format of an // RFC 2822 message. flags and date are optional arguments and can be set to // nil.
[ "Append", "appends", "the", "literal", "argument", "as", "a", "new", "message", "to", "the", "end", "of", "the", "specified", "destination", "mailbox", ".", "This", "argument", "SHOULD", "be", "in", "the", "format", "of", "an", "RFC", "2822", "message", "....
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_auth.go#L237-L254
train
emersion/go-imap
backend/backendutil/search.go
MatchFlags
func MatchFlags(flags []string, c *imap.SearchCriteria) bool { flagsMap := make(map[string]bool) for _, f := range flags { flagsMap[f] = true } return matchFlags(flagsMap, c) }
go
func MatchFlags(flags []string, c *imap.SearchCriteria) bool { flagsMap := make(map[string]bool) for _, f := range flags { flagsMap[f] = true } return matchFlags(flagsMap, c) }
[ "func", "MatchFlags", "(", "flags", "[", "]", "string", ",", "c", "*", "imap", ".", "SearchCriteria", ")", "bool", "{", "flagsMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "f", ":=", "range", "flags", "{", ...
// MatchFlags returns true if a flag list matches the provided criteria.
[ "MatchFlags", "returns", "true", "if", "a", "flag", "list", "matches", "the", "provided", "criteria", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/backend/backendutil/search.go#L172-L179
train
emersion/go-imap
backend/backendutil/search.go
MatchSeqNumAndUid
func MatchSeqNumAndUid(seqNum uint32, uid uint32, c *imap.SearchCriteria) bool { if c.SeqNum != nil && !c.SeqNum.Contains(seqNum) { return false } if c.Uid != nil && !c.Uid.Contains(uid) { return false } for _, not := range c.Not { if MatchSeqNumAndUid(seqNum, uid, not) { return false } } for _, or := range c.Or { if !MatchSeqNumAndUid(seqNum, uid, or[0]) && !MatchSeqNumAndUid(seqNum, uid, or[1]) { return false } } return true }
go
func MatchSeqNumAndUid(seqNum uint32, uid uint32, c *imap.SearchCriteria) bool { if c.SeqNum != nil && !c.SeqNum.Contains(seqNum) { return false } if c.Uid != nil && !c.Uid.Contains(uid) { return false } for _, not := range c.Not { if MatchSeqNumAndUid(seqNum, uid, not) { return false } } for _, or := range c.Or { if !MatchSeqNumAndUid(seqNum, uid, or[0]) && !MatchSeqNumAndUid(seqNum, uid, or[1]) { return false } } return true }
[ "func", "MatchSeqNumAndUid", "(", "seqNum", "uint32", ",", "uid", "uint32", ",", "c", "*", "imap", ".", "SearchCriteria", ")", "bool", "{", "if", "c", ".", "SeqNum", "!=", "nil", "&&", "!", "c", ".", "SeqNum", ".", "Contains", "(", "seqNum", ")", "{"...
// MatchSeqNumAndUid returns true if a sequence number and a UID matches the // provided criteria.
[ "MatchSeqNumAndUid", "returns", "true", "if", "a", "sequence", "number", "and", "a", "UID", "matches", "the", "provided", "criteria", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/backend/backendutil/search.go#L183-L202
train
emersion/go-imap
backend/backendutil/search.go
MatchDate
func MatchDate(date time.Time, c *imap.SearchCriteria) bool { date = date.Round(24 * time.Hour) if !c.Since.IsZero() && !date.After(c.Since) { return false } if !c.Before.IsZero() && !date.Before(c.Before) { return false } for _, not := range c.Not { if MatchDate(date, not) { return false } } for _, or := range c.Or { if !MatchDate(date, or[0]) && !MatchDate(date, or[1]) { return false } } return true }
go
func MatchDate(date time.Time, c *imap.SearchCriteria) bool { date = date.Round(24 * time.Hour) if !c.Since.IsZero() && !date.After(c.Since) { return false } if !c.Before.IsZero() && !date.Before(c.Before) { return false } for _, not := range c.Not { if MatchDate(date, not) { return false } } for _, or := range c.Or { if !MatchDate(date, or[0]) && !MatchDate(date, or[1]) { return false } } return true }
[ "func", "MatchDate", "(", "date", "time", ".", "Time", ",", "c", "*", "imap", ".", "SearchCriteria", ")", "bool", "{", "date", "=", "date", ".", "Round", "(", "24", "*", "time", ".", "Hour", ")", "\n", "if", "!", "c", ".", "Since", ".", "IsZero",...
// MatchDate returns true if a date matches the provided criteria.
[ "MatchDate", "returns", "true", "if", "a", "date", "matches", "the", "provided", "criteria", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/backend/backendutil/search.go#L205-L225
train
emersion/go-imap
client/cmd_noauth.go
StartTLS
func (c *Client) StartTLS(tlsConfig *tls.Config) error { if c.isTLS { return ErrTLSAlreadyEnabled } cmd := new(commands.StartTLS) err := c.Upgrade(func(conn net.Conn) (net.Conn, error) { // Flag connection as in upgrading c.upgrading = true if status, err := c.execute(cmd, nil); err != nil { return nil, err } else if err := status.Err(); err != nil { return nil, err } // Wait for reader to block. c.conn.WaitReady() tlsConn := tls.Client(conn, tlsConfig) if err := tlsConn.Handshake(); err != nil { return nil, err } // Capabilities change when TLS is enabled c.locker.Lock() c.caps = nil c.locker.Unlock() return tlsConn, nil }) if err != nil { return err } c.isTLS = true return nil }
go
func (c *Client) StartTLS(tlsConfig *tls.Config) error { if c.isTLS { return ErrTLSAlreadyEnabled } cmd := new(commands.StartTLS) err := c.Upgrade(func(conn net.Conn) (net.Conn, error) { // Flag connection as in upgrading c.upgrading = true if status, err := c.execute(cmd, nil); err != nil { return nil, err } else if err := status.Err(); err != nil { return nil, err } // Wait for reader to block. c.conn.WaitReady() tlsConn := tls.Client(conn, tlsConfig) if err := tlsConn.Handshake(); err != nil { return nil, err } // Capabilities change when TLS is enabled c.locker.Lock() c.caps = nil c.locker.Unlock() return tlsConn, nil }) if err != nil { return err } c.isTLS = true return nil }
[ "func", "(", "c", "*", "Client", ")", "StartTLS", "(", "tlsConfig", "*", "tls", ".", "Config", ")", "error", "{", "if", "c", ".", "isTLS", "{", "return", "ErrTLSAlreadyEnabled", "\n", "}", "\n\n", "cmd", ":=", "new", "(", "commands", ".", "StartTLS", ...
// StartTLS starts TLS negotiation.
[ "StartTLS", "starts", "TLS", "negotiation", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_noauth.go#L33-L69
train
emersion/go-imap
client/cmd_noauth.go
SupportAuth
func (c *Client) SupportAuth(mech string) (bool, error) { return c.Support("AUTH=" + mech) }
go
func (c *Client) SupportAuth(mech string) (bool, error) { return c.Support("AUTH=" + mech) }
[ "func", "(", "c", "*", "Client", ")", "SupportAuth", "(", "mech", "string", ")", "(", "bool", ",", "error", ")", "{", "return", "c", ".", "Support", "(", "\"", "\"", "+", "mech", ")", "\n", "}" ]
// SupportAuth checks if the server supports a given authentication mechanism.
[ "SupportAuth", "checks", "if", "the", "server", "supports", "a", "given", "authentication", "mechanism", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_noauth.go#L72-L74
train
emersion/go-imap
client/cmd_noauth.go
Authenticate
func (c *Client) Authenticate(auth sasl.Client) error { if c.State() != imap.NotAuthenticatedState { return ErrAlreadyLoggedIn } mech, ir, err := auth.Start() if err != nil { return err } cmd := &commands.Authenticate{ Mechanism: mech, } res := &responses.Authenticate{ Mechanism: auth, InitialResponse: ir, AuthReply: func(reply []byte) error { c.replies <- reply return nil }, } status, err := c.execute(cmd, res) if err != nil { return err } if err = status.Err(); err != nil { return err } c.locker.Lock() c.state = imap.AuthenticatedState c.caps = nil // Capabilities change when user is logged in c.locker.Unlock() if status.Code == "CAPABILITY" { c.gotStatusCaps(status.Arguments) } return nil }
go
func (c *Client) Authenticate(auth sasl.Client) error { if c.State() != imap.NotAuthenticatedState { return ErrAlreadyLoggedIn } mech, ir, err := auth.Start() if err != nil { return err } cmd := &commands.Authenticate{ Mechanism: mech, } res := &responses.Authenticate{ Mechanism: auth, InitialResponse: ir, AuthReply: func(reply []byte) error { c.replies <- reply return nil }, } status, err := c.execute(cmd, res) if err != nil { return err } if err = status.Err(); err != nil { return err } c.locker.Lock() c.state = imap.AuthenticatedState c.caps = nil // Capabilities change when user is logged in c.locker.Unlock() if status.Code == "CAPABILITY" { c.gotStatusCaps(status.Arguments) } return nil }
[ "func", "(", "c", "*", "Client", ")", "Authenticate", "(", "auth", "sasl", ".", "Client", ")", "error", "{", "if", "c", ".", "State", "(", ")", "!=", "imap", ".", "NotAuthenticatedState", "{", "return", "ErrAlreadyLoggedIn", "\n", "}", "\n\n", "mech", ...
// Authenticate indicates a SASL authentication mechanism to the server. If the // server supports the requested authentication mechanism, it performs an // authentication protocol exchange to authenticate and identify the client.
[ "Authenticate", "indicates", "a", "SASL", "authentication", "mechanism", "to", "the", "server", ".", "If", "the", "server", "supports", "the", "requested", "authentication", "mechanism", "it", "performs", "an", "authentication", "protocol", "exchange", "to", "authen...
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_noauth.go#L79-L120
train
emersion/go-imap
client/cmd_noauth.go
Login
func (c *Client) Login(username, password string) error { if state := c.State(); state == imap.AuthenticatedState || state == imap.SelectedState { return ErrAlreadyLoggedIn } c.locker.Lock() loginDisabled := c.caps != nil && c.caps["LOGINDISABLED"] c.locker.Unlock() if loginDisabled { return ErrLoginDisabled } cmd := &commands.Login{ Username: username, Password: password, } status, err := c.execute(cmd, nil) if err != nil { return err } if err = status.Err(); err != nil { return err } c.locker.Lock() c.state = imap.AuthenticatedState c.caps = nil // Capabilities change when user is logged in c.locker.Unlock() if status.Code == "CAPABILITY" { c.gotStatusCaps(status.Arguments) } return nil }
go
func (c *Client) Login(username, password string) error { if state := c.State(); state == imap.AuthenticatedState || state == imap.SelectedState { return ErrAlreadyLoggedIn } c.locker.Lock() loginDisabled := c.caps != nil && c.caps["LOGINDISABLED"] c.locker.Unlock() if loginDisabled { return ErrLoginDisabled } cmd := &commands.Login{ Username: username, Password: password, } status, err := c.execute(cmd, nil) if err != nil { return err } if err = status.Err(); err != nil { return err } c.locker.Lock() c.state = imap.AuthenticatedState c.caps = nil // Capabilities change when user is logged in c.locker.Unlock() if status.Code == "CAPABILITY" { c.gotStatusCaps(status.Arguments) } return nil }
[ "func", "(", "c", "*", "Client", ")", "Login", "(", "username", ",", "password", "string", ")", "error", "{", "if", "state", ":=", "c", ".", "State", "(", ")", ";", "state", "==", "imap", ".", "AuthenticatedState", "||", "state", "==", "imap", ".", ...
// Login identifies the client to the server and carries the plaintext password // authenticating this user.
[ "Login", "identifies", "the", "client", "to", "the", "server", "and", "carries", "the", "plaintext", "password", "authenticating", "this", "user", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/client/cmd_noauth.go#L124-L158
train
emersion/go-imap
message.go
CanonicalFlag
func CanonicalFlag(flag string) string { flag = strings.ToLower(flag) for _, f := range flags { if strings.ToLower(f) == flag { return f } } return flag }
go
func CanonicalFlag(flag string) string { flag = strings.ToLower(flag) for _, f := range flags { if strings.ToLower(f) == flag { return f } } return flag }
[ "func", "CanonicalFlag", "(", "flag", "string", ")", "string", "{", "flag", "=", "strings", ".", "ToLower", "(", "flag", ")", "\n", "for", "_", ",", "f", ":=", "range", "flags", "{", "if", "strings", ".", "ToLower", "(", "f", ")", "==", "flag", "{"...
// CanonicalFlag returns the canonical form of a flag. Flags are case-insensitive. // // If the flag is defined in RFC 3501, it returns the flag with the case of the // RFC. Otherwise, it returns the lowercase version of the flag.
[ "CanonicalFlag", "returns", "the", "canonical", "form", "of", "a", "flag", ".", "Flags", "are", "case", "-", "insensitive", ".", "If", "the", "flag", "is", "defined", "in", "RFC", "3501", "it", "returns", "the", "flag", "with", "the", "case", "of", "the"...
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L54-L62
train
emersion/go-imap
message.go
NewMessage
func NewMessage(seqNum uint32, items []FetchItem) *Message { msg := &Message{ SeqNum: seqNum, Items: make(map[FetchItem]interface{}), Body: make(map[*BodySectionName]Literal), itemsOrder: items, } for _, k := range items { msg.Items[k] = nil } return msg }
go
func NewMessage(seqNum uint32, items []FetchItem) *Message { msg := &Message{ SeqNum: seqNum, Items: make(map[FetchItem]interface{}), Body: make(map[*BodySectionName]Literal), itemsOrder: items, } for _, k := range items { msg.Items[k] = nil } return msg }
[ "func", "NewMessage", "(", "seqNum", "uint32", ",", "items", "[", "]", "FetchItem", ")", "*", "Message", "{", "msg", ":=", "&", "Message", "{", "SeqNum", ":", "seqNum", ",", "Items", ":", "make", "(", "map", "[", "FetchItem", "]", "interface", "{", "...
// Create a new empty message that will contain the specified items.
[ "Create", "a", "new", "empty", "message", "that", "will", "contain", "the", "specified", "items", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L168-L181
train
emersion/go-imap
message.go
Parse
func (m *Message) Parse(fields []interface{}) error { m.Items = make(map[FetchItem]interface{}) m.Body = map[*BodySectionName]Literal{} m.itemsOrder = nil var k FetchItem for i, f := range fields { if i%2 == 0 { // It's a key if kstr, ok := f.(string); !ok { return fmt.Errorf("cannot parse message: key is not a string, but a %T", f) } else { k = FetchItem(strings.ToUpper(kstr)) } } else { // It's a value m.Items[k] = nil m.itemsOrder = append(m.itemsOrder, k) switch k { case FetchBody, FetchBodyStructure: bs, ok := f.([]interface{}) if !ok { return fmt.Errorf("cannot parse message: BODYSTRUCTURE is not a list, but a %T", f) } m.BodyStructure = &BodyStructure{Extended: k == FetchBodyStructure} if err := m.BodyStructure.Parse(bs); err != nil { return err } case FetchEnvelope: env, ok := f.([]interface{}) if !ok { return fmt.Errorf("cannot parse message: ENVELOPE is not a list, but a %T", f) } m.Envelope = &Envelope{} if err := m.Envelope.Parse(env); err != nil { return err } case FetchFlags: flags, ok := f.([]interface{}) if !ok { return fmt.Errorf("cannot parse message: FLAGS is not a list, but a %T", f) } m.Flags = make([]string, len(flags)) for i, flag := range flags { s, _ := ParseString(flag) m.Flags[i] = CanonicalFlag(s) } case FetchInternalDate: date, _ := f.(string) m.InternalDate, _ = time.Parse(DateTimeLayout, date) case FetchRFC822Size: m.Size, _ = ParseNumber(f) case FetchUid: m.Uid, _ = ParseNumber(f) default: // Likely to be a section of the body // First check that the section name is correct if section, err := ParseBodySectionName(k); err != nil { // Not a section name, maybe an attribute defined in an IMAP extension m.Items[k] = f } else { m.Body[section], _ = f.(Literal) } } } } return nil }
go
func (m *Message) Parse(fields []interface{}) error { m.Items = make(map[FetchItem]interface{}) m.Body = map[*BodySectionName]Literal{} m.itemsOrder = nil var k FetchItem for i, f := range fields { if i%2 == 0 { // It's a key if kstr, ok := f.(string); !ok { return fmt.Errorf("cannot parse message: key is not a string, but a %T", f) } else { k = FetchItem(strings.ToUpper(kstr)) } } else { // It's a value m.Items[k] = nil m.itemsOrder = append(m.itemsOrder, k) switch k { case FetchBody, FetchBodyStructure: bs, ok := f.([]interface{}) if !ok { return fmt.Errorf("cannot parse message: BODYSTRUCTURE is not a list, but a %T", f) } m.BodyStructure = &BodyStructure{Extended: k == FetchBodyStructure} if err := m.BodyStructure.Parse(bs); err != nil { return err } case FetchEnvelope: env, ok := f.([]interface{}) if !ok { return fmt.Errorf("cannot parse message: ENVELOPE is not a list, but a %T", f) } m.Envelope = &Envelope{} if err := m.Envelope.Parse(env); err != nil { return err } case FetchFlags: flags, ok := f.([]interface{}) if !ok { return fmt.Errorf("cannot parse message: FLAGS is not a list, but a %T", f) } m.Flags = make([]string, len(flags)) for i, flag := range flags { s, _ := ParseString(flag) m.Flags[i] = CanonicalFlag(s) } case FetchInternalDate: date, _ := f.(string) m.InternalDate, _ = time.Parse(DateTimeLayout, date) case FetchRFC822Size: m.Size, _ = ParseNumber(f) case FetchUid: m.Uid, _ = ParseNumber(f) default: // Likely to be a section of the body // First check that the section name is correct if section, err := ParseBodySectionName(k); err != nil { // Not a section name, maybe an attribute defined in an IMAP extension m.Items[k] = f } else { m.Body[section], _ = f.(Literal) } } } } return nil }
[ "func", "(", "m", "*", "Message", ")", "Parse", "(", "fields", "[", "]", "interface", "{", "}", ")", "error", "{", "m", ".", "Items", "=", "make", "(", "map", "[", "FetchItem", "]", "interface", "{", "}", ")", "\n", "m", ".", "Body", "=", "map"...
// Parse a message from fields.
[ "Parse", "a", "message", "from", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L184-L254
train
emersion/go-imap
message.go
GetBody
func (m *Message) GetBody(section *BodySectionName) Literal { section = section.resp() for s, body := range m.Body { if section.Equal(s) { return body } } return nil }
go
func (m *Message) GetBody(section *BodySectionName) Literal { section = section.resp() for s, body := range m.Body { if section.Equal(s) { return body } } return nil }
[ "func", "(", "m", "*", "Message", ")", "GetBody", "(", "section", "*", "BodySectionName", ")", "Literal", "{", "section", "=", "section", ".", "resp", "(", ")", "\n\n", "for", "s", ",", "body", ":=", "range", "m", ".", "Body", "{", "if", "section", ...
// GetBody gets the body section with the specified name. Returns nil if it's not found.
[ "GetBody", "gets", "the", "body", "section", "with", "the", "specified", "name", ".", "Returns", "nil", "if", "it", "s", "not", "found", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L316-L325
train
emersion/go-imap
message.go
Equal
func (section *BodySectionName) Equal(other *BodySectionName) bool { if section.Peek != other.Peek { return false } if len(section.Partial) != len(other.Partial) { return false } if len(section.Partial) > 0 && section.Partial[0] != other.Partial[0] { return false } if len(section.Partial) > 1 && section.Partial[1] != other.Partial[1] { return false } return section.BodyPartName.Equal(&other.BodyPartName) }
go
func (section *BodySectionName) Equal(other *BodySectionName) bool { if section.Peek != other.Peek { return false } if len(section.Partial) != len(other.Partial) { return false } if len(section.Partial) > 0 && section.Partial[0] != other.Partial[0] { return false } if len(section.Partial) > 1 && section.Partial[1] != other.Partial[1] { return false } return section.BodyPartName.Equal(&other.BodyPartName) }
[ "func", "(", "section", "*", "BodySectionName", ")", "Equal", "(", "other", "*", "BodySectionName", ")", "bool", "{", "if", "section", ".", "Peek", "!=", "other", ".", "Peek", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "section", ".", ...
// Equal checks whether two sections are equal.
[ "Equal", "checks", "whether", "two", "sections", "are", "equal", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L439-L453
train
emersion/go-imap
message.go
ExtractPartial
func (section *BodySectionName) ExtractPartial(b []byte) []byte { if len(section.Partial) != 2 { return b } from := section.Partial[0] length := section.Partial[1] to := from + length if from > len(b) { return nil } if to > len(b) { to = len(b) } return b[from:to] }
go
func (section *BodySectionName) ExtractPartial(b []byte) []byte { if len(section.Partial) != 2 { return b } from := section.Partial[0] length := section.Partial[1] to := from + length if from > len(b) { return nil } if to > len(b) { to = len(b) } return b[from:to] }
[ "func", "(", "section", "*", "BodySectionName", ")", "ExtractPartial", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "if", "len", "(", "section", ".", "Partial", ")", "!=", "2", "{", "return", "b", "\n", "}", "\n\n", "from", ":=", "sectio...
// ExtractPartial returns a subset of the specified bytes matching the partial requested in the // section name.
[ "ExtractPartial", "returns", "a", "subset", "of", "the", "specified", "bytes", "matching", "the", "partial", "requested", "in", "the", "section", "name", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L469-L484
train
emersion/go-imap
message.go
ParseBodySectionName
func ParseBodySectionName(s FetchItem) (*BodySectionName, error) { section := new(BodySectionName) err := section.parse(string(s)) return section, err }
go
func ParseBodySectionName(s FetchItem) (*BodySectionName, error) { section := new(BodySectionName) err := section.parse(string(s)) return section, err }
[ "func", "ParseBodySectionName", "(", "s", "FetchItem", ")", "(", "*", "BodySectionName", ",", "error", ")", "{", "section", ":=", "new", "(", "BodySectionName", ")", "\n", "err", ":=", "section", ".", "parse", "(", "string", "(", "s", ")", ")", "\n", "...
// ParseBodySectionName parses a body section name.
[ "ParseBodySectionName", "parses", "a", "body", "section", "name", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L487-L491
train
emersion/go-imap
message.go
Equal
func (part *BodyPartName) Equal(other *BodyPartName) bool { if part.Specifier != other.Specifier { return false } if part.NotFields != other.NotFields { return false } if len(part.Path) != len(other.Path) { return false } for i, node := range part.Path { if node != other.Path[i] { return false } } if len(part.Fields) != len(other.Fields) { return false } for _, field := range part.Fields { found := false for _, f := range other.Fields { if strings.EqualFold(field, f) { found = true break } } if !found { return false } } return true }
go
func (part *BodyPartName) Equal(other *BodyPartName) bool { if part.Specifier != other.Specifier { return false } if part.NotFields != other.NotFields { return false } if len(part.Path) != len(other.Path) { return false } for i, node := range part.Path { if node != other.Path[i] { return false } } if len(part.Fields) != len(other.Fields) { return false } for _, field := range part.Fields { found := false for _, f := range other.Fields { if strings.EqualFold(field, f) { found = true break } } if !found { return false } } return true }
[ "func", "(", "part", "*", "BodyPartName", ")", "Equal", "(", "other", "*", "BodyPartName", ")", "bool", "{", "if", "part", ".", "Specifier", "!=", "other", ".", "Specifier", "{", "return", "false", "\n", "}", "\n", "if", "part", ".", "NotFields", "!=",...
// Equal checks whether two body part names are equal.
[ "Equal", "checks", "whether", "two", "body", "part", "names", "are", "equal", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L590-L621
train
emersion/go-imap
message.go
Parse
func (addr *Address) Parse(fields []interface{}) error { if len(fields) < 4 { return errors.New("Address doesn't contain 4 fields") } if s, err := ParseString(fields[0]); err == nil { addr.PersonalName, _ = decodeHeader(s) } if s, err := ParseString(fields[1]); err == nil { addr.AtDomainList, _ = decodeHeader(s) } if s, err := ParseString(fields[2]); err == nil { addr.MailboxName, _ = decodeHeader(s) } if s, err := ParseString(fields[3]); err == nil { addr.HostName, _ = decodeHeader(s) } return nil }
go
func (addr *Address) Parse(fields []interface{}) error { if len(fields) < 4 { return errors.New("Address doesn't contain 4 fields") } if s, err := ParseString(fields[0]); err == nil { addr.PersonalName, _ = decodeHeader(s) } if s, err := ParseString(fields[1]); err == nil { addr.AtDomainList, _ = decodeHeader(s) } if s, err := ParseString(fields[2]); err == nil { addr.MailboxName, _ = decodeHeader(s) } if s, err := ParseString(fields[3]); err == nil { addr.HostName, _ = decodeHeader(s) } return nil }
[ "func", "(", "addr", "*", "Address", ")", "Parse", "(", "fields", "[", "]", "interface", "{", "}", ")", "error", "{", "if", "len", "(", "fields", ")", "<", "4", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if",...
// Parse an address from fields.
[ "Parse", "an", "address", "from", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L636-L655
train
emersion/go-imap
message.go
Format
func (addr *Address) Format() []interface{} { fields := make([]interface{}, 4) if addr.PersonalName != "" { fields[0] = encodeHeader(addr.PersonalName) } if addr.AtDomainList != "" { fields[1] = addr.AtDomainList } if addr.MailboxName != "" { fields[2] = addr.MailboxName } if addr.HostName != "" { fields[3] = addr.HostName } return fields }
go
func (addr *Address) Format() []interface{} { fields := make([]interface{}, 4) if addr.PersonalName != "" { fields[0] = encodeHeader(addr.PersonalName) } if addr.AtDomainList != "" { fields[1] = addr.AtDomainList } if addr.MailboxName != "" { fields[2] = addr.MailboxName } if addr.HostName != "" { fields[3] = addr.HostName } return fields }
[ "func", "(", "addr", "*", "Address", ")", "Format", "(", ")", "[", "]", "interface", "{", "}", "{", "fields", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "4", ")", "\n\n", "if", "addr", ".", "PersonalName", "!=", "\"", "\"", "{", "...
// Format an address to fields.
[ "Format", "an", "address", "to", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L658-L675
train
emersion/go-imap
message.go
ParseAddressList
func ParseAddressList(fields []interface{}) (addrs []*Address) { addrs = make([]*Address, len(fields)) for i, f := range fields { if addrFields, ok := f.([]interface{}); ok { addr := &Address{} if err := addr.Parse(addrFields); err == nil { addrs[i] = addr } } } return }
go
func ParseAddressList(fields []interface{}) (addrs []*Address) { addrs = make([]*Address, len(fields)) for i, f := range fields { if addrFields, ok := f.([]interface{}); ok { addr := &Address{} if err := addr.Parse(addrFields); err == nil { addrs[i] = addr } } } return }
[ "func", "ParseAddressList", "(", "fields", "[", "]", "interface", "{", "}", ")", "(", "addrs", "[", "]", "*", "Address", ")", "{", "addrs", "=", "make", "(", "[", "]", "*", "Address", ",", "len", "(", "fields", ")", ")", "\n\n", "for", "i", ",", ...
// Parse an address list from fields.
[ "Parse", "an", "address", "list", "from", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L678-L691
train
emersion/go-imap
message.go
FormatAddressList
func FormatAddressList(addrs []*Address) (fields []interface{}) { fields = make([]interface{}, len(addrs)) for i, addr := range addrs { fields[i] = addr.Format() } return }
go
func FormatAddressList(addrs []*Address) (fields []interface{}) { fields = make([]interface{}, len(addrs)) for i, addr := range addrs { fields[i] = addr.Format() } return }
[ "func", "FormatAddressList", "(", "addrs", "[", "]", "*", "Address", ")", "(", "fields", "[", "]", "interface", "{", "}", ")", "{", "fields", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "addrs", ")", ")", "\n\n", "for", "i...
// Format an address list to fields.
[ "Format", "an", "address", "list", "to", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L694-L702
train
emersion/go-imap
message.go
Parse
func (e *Envelope) Parse(fields []interface{}) error { if len(fields) < 10 { return errors.New("ENVELOPE doesn't contain 10 fields") } if date, ok := fields[0].(string); ok { e.Date, _ = parseMessageDateTime(date) } if subject, err := ParseString(fields[1]); err == nil { e.Subject, _ = decodeHeader(subject) } if from, ok := fields[2].([]interface{}); ok { e.From = ParseAddressList(from) } if sender, ok := fields[3].([]interface{}); ok { e.Sender = ParseAddressList(sender) } if replyTo, ok := fields[4].([]interface{}); ok { e.ReplyTo = ParseAddressList(replyTo) } if to, ok := fields[5].([]interface{}); ok { e.To = ParseAddressList(to) } if cc, ok := fields[6].([]interface{}); ok { e.Cc = ParseAddressList(cc) } if bcc, ok := fields[7].([]interface{}); ok { e.Bcc = ParseAddressList(bcc) } if inReplyTo, ok := fields[8].(string); ok { e.InReplyTo = inReplyTo } if msgId, ok := fields[9].(string); ok { e.MessageId = msgId } return nil }
go
func (e *Envelope) Parse(fields []interface{}) error { if len(fields) < 10 { return errors.New("ENVELOPE doesn't contain 10 fields") } if date, ok := fields[0].(string); ok { e.Date, _ = parseMessageDateTime(date) } if subject, err := ParseString(fields[1]); err == nil { e.Subject, _ = decodeHeader(subject) } if from, ok := fields[2].([]interface{}); ok { e.From = ParseAddressList(from) } if sender, ok := fields[3].([]interface{}); ok { e.Sender = ParseAddressList(sender) } if replyTo, ok := fields[4].([]interface{}); ok { e.ReplyTo = ParseAddressList(replyTo) } if to, ok := fields[5].([]interface{}); ok { e.To = ParseAddressList(to) } if cc, ok := fields[6].([]interface{}); ok { e.Cc = ParseAddressList(cc) } if bcc, ok := fields[7].([]interface{}); ok { e.Bcc = ParseAddressList(bcc) } if inReplyTo, ok := fields[8].(string); ok { e.InReplyTo = inReplyTo } if msgId, ok := fields[9].(string); ok { e.MessageId = msgId } return nil }
[ "func", "(", "e", "*", "Envelope", ")", "Parse", "(", "fields", "[", "]", "interface", "{", "}", ")", "error", "{", "if", "len", "(", "fields", ")", "<", "10", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", ...
// Parse an envelope from fields.
[ "Parse", "an", "envelope", "from", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L730-L767
train
emersion/go-imap
message.go
Format
func (e *Envelope) Format() (fields []interface{}) { return []interface{}{ envelopeDateTime(e.Date), encodeHeader(e.Subject), FormatAddressList(e.From), FormatAddressList(e.Sender), FormatAddressList(e.ReplyTo), FormatAddressList(e.To), FormatAddressList(e.Cc), FormatAddressList(e.Bcc), e.InReplyTo, e.MessageId, } }
go
func (e *Envelope) Format() (fields []interface{}) { return []interface{}{ envelopeDateTime(e.Date), encodeHeader(e.Subject), FormatAddressList(e.From), FormatAddressList(e.Sender), FormatAddressList(e.ReplyTo), FormatAddressList(e.To), FormatAddressList(e.Cc), FormatAddressList(e.Bcc), e.InReplyTo, e.MessageId, } }
[ "func", "(", "e", "*", "Envelope", ")", "Format", "(", ")", "(", "fields", "[", "]", "interface", "{", "}", ")", "{", "return", "[", "]", "interface", "{", "}", "{", "envelopeDateTime", "(", "e", ".", "Date", ")", ",", "encodeHeader", "(", "e", "...
// Format an envelope to fields.
[ "Format", "an", "envelope", "to", "fields", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/message.go#L770-L783
train
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", ".", "l...
// 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
train
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", "...
// 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
train
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", ...
// 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
train
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", ...
// 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
train
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
train
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
train
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", ",", "m...
// 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
train
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"...
// 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
train
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"...
// ParseNumber parses a number.
[ "ParseNumber", "parses", "a", "number", "." ]
b7db4a2bc5cc04fb568fb036a438da43ee9a9f78
https://github.com/emersion/go-imap/blob/b7db4a2bc5cc04fb568fb036a438da43ee9a9f78/read.go#L66-L83
train
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...
// 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
train
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", ",", ...
// 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
train
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", "("...
// Names of registered formatters.
[ "Names", "of", "registered", "formatters", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/api.go#L32-L39
train
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
train
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
train
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", "\"", "\...
// 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
train
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", "...
// 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
train
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"...
// 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
train
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
train
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", "}", ...
// 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
train
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...
// Types that are styled.
[ "Types", "that", "are", "styled", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L221-L236
train
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", ...
// 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
train
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", ")", "...
// 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
train
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",...
// ParseStyleEntry parses a Pygments style entry.
[ "ParseStyleEntry", "parses", "a", "Pygments", "style", "entry", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/style.go#L299-L342
train
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
train
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
train
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
train
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", ")"...
// 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
train
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", ".", "highlightRange...
// 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
train
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", "}", ...
// New HTML formatter.
[ "New", "HTML", "formatter", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/formatters/html/html.go#L64-L72
train
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", ",", "\"", "\""...
// 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
train
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", "{", "...
// 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
train
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
train
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", ",", ...
// 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
train
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"...
// 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
train
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", "}", ...
// 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
train
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", ...
// 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
train
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", "(", "[", "...
// 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
train
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", ...
// 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
train
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", ":=", ...
// 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", "optiona...
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/regexp.go#L182-L210
train
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
train
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", ...
// 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
train
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
train
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", "(", "o...
// 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
train
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", "!=",...
// 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
train
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", "...
// 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
train
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", "s...
// 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
train
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", "(", ")", ...
// 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
train
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", "{", "candidate...
// 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
train
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", ":="...
// 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
train
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.", ...
// 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
train
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...
// 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
train
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", ".", "byNa...
// 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
train
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", ".", "Muta...
// 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
train
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", ...
// Push states onto the stack.
[ "Push", "states", "onto", "the", "stack", "." ]
1327f9145ea6a0c6e7651d973270190a814bd92b
https://github.com/alecthomas/chroma/blob/1327f9145ea6a0c6e7651d973270190a814bd92b/mutators.go#L91-L106
train
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...
// 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
train
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", "}...
// 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
train
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",...
// 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", "expande...
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/issuing_transaction.go#L58-L72
train
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
train
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", ")", "...
// Capture captures a payment intent.
[ "Capture", "captures", "a", "payment", "intent", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/paymentintent/client.go#L71-L73
train
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", ")", "...
// Confirm confirms a payment intent.
[ "Confirm", "confirms", "a", "payment", "intent", "." ]
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/paymentintent/client.go#L84-L86
train
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", "}", "\...
// 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
train
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", ...
// 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
train
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", ...
// 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
train
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
train
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", ...
// 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", ...
aa901d66c475fdd6d86581c5e1f2f85ec1f074f6
https://github.com/stripe/stripe-go/blob/aa901d66c475fdd6d86581c5e1f2f85ec1f074f6/stripe.go#L82-L91
train
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",...
// 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
train
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", "{", "}", ")", "erro...
// 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
train
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"...
// 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
train
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", ...
// 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
train
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", "(...
// 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
train
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", ")",...
// 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
train
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",...
// 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
train
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", "]", "=", "&", ...
// 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
train