repository_name
stringlengths
5
54
func_path_in_repository
stringlengths
4
155
func_name
stringlengths
1
118
whole_func_string
stringlengths
52
3.87M
language
stringclasses
1 value
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
21
188k
func_documentation_string
stringlengths
4
26.3k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
252
markbates/grift
grift/grift.go
List
func List() []string { keys := []string{} for k := range griftList { keys = append(keys, k) } sort.Strings(keys) return keys }
go
func List() []string { keys := []string{} for k := range griftList { keys = append(keys, k) } sort.Strings(keys) return keys }
[ "func", "List", "(", ")", "[", "]", "string", "{", "keys", ":=", "[", "]", "string", "{", "}", "\n", "for", "k", ":=", "range", "griftList", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "return", "keys", "\n", "}" ]
// List of the names of the defined grifts.
[ "List", "of", "the", "names", "of", "the", "defined", "grifts", "." ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L148-L155
markbates/grift
grift/grift.go
Exec
func Exec(args []string, verbose bool) error { name := "list" if len(args) >= 1 { name = args[0] } switch name { case "list": PrintGrifts(os.Stdout) default: c := NewContext(name) c.Verbose = verbose if len(args) >= 1 { c.Args = args[1:] } return Run(name, c) } return nil }
go
func Exec(args []string, verbose bool) error { name := "list" if len(args) >= 1 { name = args[0] } switch name { case "list": PrintGrifts(os.Stdout) default: c := NewContext(name) c.Verbose = verbose if len(args) >= 1 { c.Args = args[1:] } return Run(name, c) } return nil }
[ "func", "Exec", "(", "args", "[", "]", "string", ",", "verbose", "bool", ")", "error", "{", "name", ":=", "\"", "\"", "\n", "if", "len", "(", "args", ")", ">=", "1", "{", "name", "=", "args", "[", "0", "]", "\n", "}", "\n", "switch", "name", "{", "case", "\"", "\"", ":", "PrintGrifts", "(", "os", ".", "Stdout", ")", "\n", "default", ":", "c", ":=", "NewContext", "(", "name", ")", "\n", "c", ".", "Verbose", "=", "verbose", "\n", "if", "len", "(", "args", ")", ">=", "1", "{", "c", ".", "Args", "=", "args", "[", "1", ":", "]", "\n", "}", "\n", "return", "Run", "(", "name", ",", "c", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Exec the grift stack. This is the main "entry point" to // the grift system.
[ "Exec", "the", "grift", "stack", ".", "This", "is", "the", "main", "entry", "point", "to", "the", "grift", "system", "." ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L159-L176
markbates/grift
grift/grift.go
PrintGrifts
func PrintGrifts(w io.Writer) { fmt.Fprint(w, "Available grifts\n================\n") cnLen := len(CommandName) maxLen := cnLen l := List() for _, k := range l { if (len(k) + cnLen) > maxLen { maxLen = len(k) + cnLen } } for _, k := range l { m := strings.Join([]string{CommandName, k}, " ") suffix := strings.Repeat(" ", (maxLen+3)-len(m)) + " #" fmt.Fprintln(w, strings.Join([]string{m, suffix, descriptions[k]}, " ")) } }
go
func PrintGrifts(w io.Writer) { fmt.Fprint(w, "Available grifts\n================\n") cnLen := len(CommandName) maxLen := cnLen l := List() for _, k := range l { if (len(k) + cnLen) > maxLen { maxLen = len(k) + cnLen } } for _, k := range l { m := strings.Join([]string{CommandName, k}, " ") suffix := strings.Repeat(" ", (maxLen+3)-len(m)) + " #" fmt.Fprintln(w, strings.Join([]string{m, suffix, descriptions[k]}, " ")) } }
[ "func", "PrintGrifts", "(", "w", "io", ".", "Writer", ")", "{", "fmt", ".", "Fprint", "(", "w", ",", "\"", "\\n", "\\n", "\"", ")", "\n\n", "cnLen", ":=", "len", "(", "CommandName", ")", "\n", "maxLen", ":=", "cnLen", "\n", "l", ":=", "List", "(", ")", "\n\n", "for", "_", ",", "k", ":=", "range", "l", "{", "if", "(", "len", "(", "k", ")", "+", "cnLen", ")", ">", "maxLen", "{", "maxLen", "=", "len", "(", "k", ")", "+", "cnLen", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "k", ":=", "range", "l", "{", "m", ":=", "strings", ".", "Join", "(", "[", "]", "string", "{", "CommandName", ",", "k", "}", ",", "\"", "\"", ")", "\n", "suffix", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "(", "maxLen", "+", "3", ")", "-", "len", "(", "m", ")", ")", "+", "\"", "\"", "\n\n", "fmt", ".", "Fprintln", "(", "w", ",", "strings", ".", "Join", "(", "[", "]", "string", "{", "m", ",", "suffix", ",", "descriptions", "[", "k", "]", "}", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}" ]
// PrintGrifts to the screen, nice, sorted, and with descriptions, // should they exist.
[ "PrintGrifts", "to", "the", "screen", "nice", "sorted", "and", "with", "descriptions", "should", "they", "exist", "." ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L180-L199
markbates/grift
grift/grift.go
RunSource
func RunSource(cmd *exec.Cmd) error { cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout return cmd.Run() }
go
func RunSource(cmd *exec.Cmd) error { cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout return cmd.Run() }
[ "func", "RunSource", "(", "cmd", "*", "exec", ".", "Cmd", ")", "error", "{", "cmd", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// RunSource executes the command passed as argument, // in the current shell/context
[ "RunSource", "executes", "the", "command", "passed", "as", "argument", "in", "the", "current", "shell", "/", "context" ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L203-L208
markbates/grift
grift/context.go
Value
func (c *Context) Value(key interface{}) interface{} { if s, ok := key.(string); ok { if v, ok := c.data[s]; ok { return v } } return c.Context.Value(key) }
go
func (c *Context) Value(key interface{}) interface{} { if s, ok := key.(string); ok { if v, ok := c.data[s]; ok { return v } } return c.Context.Value(key) }
[ "func", "(", "c", "*", "Context", ")", "Value", "(", "key", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "s", ",", "ok", ":=", "key", ".", "(", "string", ")", ";", "ok", "{", "if", "v", ",", "ok", ":=", "c", ".", "data", "[", "s", "]", ";", "ok", "{", "return", "v", "\n", "}", "\n", "}", "\n", "return", "c", ".", "Context", ".", "Value", "(", "key", ")", "\n", "}" ]
// Value returns a value from the context for the given key
[ "Value", "returns", "a", "value", "from", "the", "context", "for", "the", "given", "key" ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/context.go#L19-L26
markbates/grift
grift/context.go
Set
func (c *Context) Set(key string, val interface{}) { c.moot.Lock() defer c.moot.Unlock() c.data[key] = val }
go
func (c *Context) Set(key string, val interface{}) { c.moot.Lock() defer c.moot.Unlock() c.data[key] = val }
[ "func", "(", "c", "*", "Context", ")", "Set", "(", "key", "string", ",", "val", "interface", "{", "}", ")", "{", "c", ".", "moot", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "moot", ".", "Unlock", "(", ")", "\n", "c", ".", "data", "[", "key", "]", "=", "val", "\n", "}" ]
// Set a piece of data onto the Context.
[ "Set", "a", "piece", "of", "data", "onto", "the", "Context", "." ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/context.go#L29-L33
markbates/grift
grift/context.go
NewContextWithContext
func NewContextWithContext(name string, ctx context.Context) *Context { return &Context{ Context: ctx, Name: name, Args: []string{}, data: map[interface{}]interface{}{}, moot: &sync.Mutex{}, } }
go
func NewContextWithContext(name string, ctx context.Context) *Context { return &Context{ Context: ctx, Name: name, Args: []string{}, data: map[interface{}]interface{}{}, moot: &sync.Mutex{}, } }
[ "func", "NewContextWithContext", "(", "name", "string", ",", "ctx", "context", ".", "Context", ")", "*", "Context", "{", "return", "&", "Context", "{", "Context", ":", "ctx", ",", "Name", ":", "name", ",", "Args", ":", "[", "]", "string", "{", "}", ",", "data", ":", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", "{", "}", ",", "moot", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "}", "\n", "}" ]
// NewContextWithContext builds and returns a new default Context given an existing context
[ "NewContextWithContext", "builds", "and", "returns", "a", "new", "default", "Context", "given", "an", "existing", "context" ]
train
https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/context.go#L41-L49
aymerick/douceur
parser/parser.go
ParseStylesheet
func (parser *Parser) ParseStylesheet() (*css.Stylesheet, error) { result := css.NewStylesheet() // Parse BOM if _, err := parser.parseBOM(); err != nil { return result, err } // Parse list of rules rules, err := parser.ParseRules() if err != nil { return result, err } result.Rules = rules return result, nil }
go
func (parser *Parser) ParseStylesheet() (*css.Stylesheet, error) { result := css.NewStylesheet() // Parse BOM if _, err := parser.parseBOM(); err != nil { return result, err } // Parse list of rules rules, err := parser.ParseRules() if err != nil { return result, err } result.Rules = rules return result, nil }
[ "func", "(", "parser", "*", "Parser", ")", "ParseStylesheet", "(", ")", "(", "*", "css", ".", "Stylesheet", ",", "error", ")", "{", "result", ":=", "css", ".", "NewStylesheet", "(", ")", "\n\n", "// Parse BOM", "if", "_", ",", "err", ":=", "parser", ".", "parseBOM", "(", ")", ";", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "// Parse list of rules", "rules", ",", "err", ":=", "parser", ".", "ParseRules", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", ".", "Rules", "=", "rules", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// ParseStylesheet parses a stylesheet
[ "ParseStylesheet", "parses", "a", "stylesheet" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L55-L72
aymerick/douceur
parser/parser.go
ParseRules
func (parser *Parser) ParseRules() ([]*css.Rule, error) { result := []*css.Rule{} inBlock := false if parser.tokenChar("{") { // parsing a block of rules inBlock = true parser.embedLevel++ parser.shiftToken() } for parser.tokenParsable() { if parser.tokenIgnorable() { parser.shiftToken() } else if parser.tokenChar("}") { if !inBlock { errMsg := fmt.Sprintf("Unexpected } character: %s", parser.nextToken().String()) return result, errors.New(errMsg) } parser.shiftToken() parser.embedLevel-- // finished break } else { rule, err := parser.ParseRule() if err != nil { return result, err } rule.EmbedLevel = parser.embedLevel result = append(result, rule) } } return result, parser.err() }
go
func (parser *Parser) ParseRules() ([]*css.Rule, error) { result := []*css.Rule{} inBlock := false if parser.tokenChar("{") { // parsing a block of rules inBlock = true parser.embedLevel++ parser.shiftToken() } for parser.tokenParsable() { if parser.tokenIgnorable() { parser.shiftToken() } else if parser.tokenChar("}") { if !inBlock { errMsg := fmt.Sprintf("Unexpected } character: %s", parser.nextToken().String()) return result, errors.New(errMsg) } parser.shiftToken() parser.embedLevel-- // finished break } else { rule, err := parser.ParseRule() if err != nil { return result, err } rule.EmbedLevel = parser.embedLevel result = append(result, rule) } } return result, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "ParseRules", "(", ")", "(", "[", "]", "*", "css", ".", "Rule", ",", "error", ")", "{", "result", ":=", "[", "]", "*", "css", ".", "Rule", "{", "}", "\n\n", "inBlock", ":=", "false", "\n", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "// parsing a block of rules", "inBlock", "=", "true", "\n", "parser", ".", "embedLevel", "++", "\n\n", "parser", ".", "shiftToken", "(", ")", "\n", "}", "\n\n", "for", "parser", ".", "tokenParsable", "(", ")", "{", "if", "parser", ".", "tokenIgnorable", "(", ")", "{", "parser", ".", "shiftToken", "(", ")", "\n", "}", "else", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "if", "!", "inBlock", "{", "errMsg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parser", ".", "nextToken", "(", ")", ".", "String", "(", ")", ")", "\n", "return", "result", ",", "errors", ".", "New", "(", "errMsg", ")", "\n", "}", "\n\n", "parser", ".", "shiftToken", "(", ")", "\n", "parser", ".", "embedLevel", "--", "\n\n", "// finished", "break", "\n", "}", "else", "{", "rule", ",", "err", ":=", "parser", ".", "ParseRule", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "rule", ".", "EmbedLevel", "=", "parser", ".", "embedLevel", "\n", "result", "=", "append", "(", "result", ",", "rule", ")", "\n", "}", "\n", "}", "\n\n", "return", "result", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// ParseRules parses a list of rules
[ "ParseRules", "parses", "a", "list", "of", "rules" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L75-L113
aymerick/douceur
parser/parser.go
ParseRule
func (parser *Parser) ParseRule() (*css.Rule, error) { if parser.tokenAtKeyword() { return parser.parseAtRule() } return parser.parseQualifiedRule() }
go
func (parser *Parser) ParseRule() (*css.Rule, error) { if parser.tokenAtKeyword() { return parser.parseAtRule() } return parser.parseQualifiedRule() }
[ "func", "(", "parser", "*", "Parser", ")", "ParseRule", "(", ")", "(", "*", "css", ".", "Rule", ",", "error", ")", "{", "if", "parser", ".", "tokenAtKeyword", "(", ")", "{", "return", "parser", ".", "parseAtRule", "(", ")", "\n", "}", "\n\n", "return", "parser", ".", "parseQualifiedRule", "(", ")", "\n", "}" ]
// ParseRule parses a rule
[ "ParseRule", "parses", "a", "rule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L116-L122
aymerick/douceur
parser/parser.go
ParseDeclarations
func (parser *Parser) ParseDeclarations() ([]*css.Declaration, error) { result := []*css.Declaration{} if parser.tokenChar("{") { parser.shiftToken() } for parser.tokenParsable() { if parser.tokenIgnorable() { parser.shiftToken() } else if parser.tokenChar("}") { // end of block parser.shiftToken() break } else { declaration, err := parser.ParseDeclaration() if err != nil { return result, err } result = append(result, declaration) } } return result, parser.err() }
go
func (parser *Parser) ParseDeclarations() ([]*css.Declaration, error) { result := []*css.Declaration{} if parser.tokenChar("{") { parser.shiftToken() } for parser.tokenParsable() { if parser.tokenIgnorable() { parser.shiftToken() } else if parser.tokenChar("}") { // end of block parser.shiftToken() break } else { declaration, err := parser.ParseDeclaration() if err != nil { return result, err } result = append(result, declaration) } } return result, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "ParseDeclarations", "(", ")", "(", "[", "]", "*", "css", ".", "Declaration", ",", "error", ")", "{", "result", ":=", "[", "]", "*", "css", ".", "Declaration", "{", "}", "\n\n", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "parser", ".", "shiftToken", "(", ")", "\n", "}", "\n\n", "for", "parser", ".", "tokenParsable", "(", ")", "{", "if", "parser", ".", "tokenIgnorable", "(", ")", "{", "parser", ".", "shiftToken", "(", ")", "\n", "}", "else", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "// end of block", "parser", ".", "shiftToken", "(", ")", "\n", "break", "\n", "}", "else", "{", "declaration", ",", "err", ":=", "parser", ".", "ParseDeclaration", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", "=", "append", "(", "result", ",", "declaration", ")", "\n", "}", "\n", "}", "\n\n", "return", "result", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// ParseDeclarations parses a list of declarations
[ "ParseDeclarations", "parses", "a", "list", "of", "declarations" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L125-L150
aymerick/douceur
parser/parser.go
ParseDeclaration
func (parser *Parser) ParseDeclaration() (*css.Declaration, error) { result := css.NewDeclaration() curValue := "" for parser.tokenParsable() { if parser.tokenChar(":") { result.Property = strings.TrimSpace(curValue) curValue = "" parser.shiftToken() } else if parser.tokenChar(";") || parser.tokenChar("}") { if result.Property == "" { errMsg := fmt.Sprintf("Unexpected ; character: %s", parser.nextToken().String()) return result, errors.New(errMsg) } if importantRegexp.MatchString(curValue) { result.Important = true curValue = importantRegexp.ReplaceAllString(curValue, "") } result.Value = strings.TrimSpace(curValue) if parser.tokenChar(";") { parser.shiftToken() } // finished break } else { token := parser.shiftToken() curValue += token.Value } } // log.Printf("[parsed] Declaration: %s", result.String()) return result, parser.err() }
go
func (parser *Parser) ParseDeclaration() (*css.Declaration, error) { result := css.NewDeclaration() curValue := "" for parser.tokenParsable() { if parser.tokenChar(":") { result.Property = strings.TrimSpace(curValue) curValue = "" parser.shiftToken() } else if parser.tokenChar(";") || parser.tokenChar("}") { if result.Property == "" { errMsg := fmt.Sprintf("Unexpected ; character: %s", parser.nextToken().String()) return result, errors.New(errMsg) } if importantRegexp.MatchString(curValue) { result.Important = true curValue = importantRegexp.ReplaceAllString(curValue, "") } result.Value = strings.TrimSpace(curValue) if parser.tokenChar(";") { parser.shiftToken() } // finished break } else { token := parser.shiftToken() curValue += token.Value } } // log.Printf("[parsed] Declaration: %s", result.String()) return result, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "ParseDeclaration", "(", ")", "(", "*", "css", ".", "Declaration", ",", "error", ")", "{", "result", ":=", "css", ".", "NewDeclaration", "(", ")", "\n", "curValue", ":=", "\"", "\"", "\n\n", "for", "parser", ".", "tokenParsable", "(", ")", "{", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "result", ".", "Property", "=", "strings", ".", "TrimSpace", "(", "curValue", ")", "\n", "curValue", "=", "\"", "\"", "\n\n", "parser", ".", "shiftToken", "(", ")", "\n", "}", "else", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "||", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "if", "result", ".", "Property", "==", "\"", "\"", "{", "errMsg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parser", ".", "nextToken", "(", ")", ".", "String", "(", ")", ")", "\n", "return", "result", ",", "errors", ".", "New", "(", "errMsg", ")", "\n", "}", "\n\n", "if", "importantRegexp", ".", "MatchString", "(", "curValue", ")", "{", "result", ".", "Important", "=", "true", "\n", "curValue", "=", "importantRegexp", ".", "ReplaceAllString", "(", "curValue", ",", "\"", "\"", ")", "\n", "}", "\n\n", "result", ".", "Value", "=", "strings", ".", "TrimSpace", "(", "curValue", ")", "\n\n", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "parser", ".", "shiftToken", "(", ")", "\n", "}", "\n\n", "// finished", "break", "\n", "}", "else", "{", "token", ":=", "parser", ".", "shiftToken", "(", ")", "\n", "curValue", "+=", "token", ".", "Value", "\n", "}", "\n", "}", "\n\n", "// log.Printf(\"[parsed] Declaration: %s\", result.String())", "return", "result", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// ParseDeclaration parses a declaration
[ "ParseDeclaration", "parses", "a", "declaration" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L153-L191
aymerick/douceur
parser/parser.go
parseAtRule
func (parser *Parser) parseAtRule() (*css.Rule, error) { // parse rule name (eg: "@import") token := parser.shiftToken() result := css.NewRule(css.AtRule) result.Name = token.Value for parser.tokenParsable() { if parser.tokenChar(";") { parser.shiftToken() // finished break } else if parser.tokenChar("{") { if result.EmbedsRules() { // parse rules block rules, err := parser.ParseRules() if err != nil { return result, err } result.Rules = rules } else { // parse declarations block declarations, err := parser.ParseDeclarations() if err != nil { return result, err } result.Declarations = declarations } // finished break } else { // parse prelude prelude, err := parser.parsePrelude() if err != nil { return result, err } result.Prelude = prelude } } // log.Printf("[parsed] Rule: %s", result.String()) return result, parser.err() }
go
func (parser *Parser) parseAtRule() (*css.Rule, error) { // parse rule name (eg: "@import") token := parser.shiftToken() result := css.NewRule(css.AtRule) result.Name = token.Value for parser.tokenParsable() { if parser.tokenChar(";") { parser.shiftToken() // finished break } else if parser.tokenChar("{") { if result.EmbedsRules() { // parse rules block rules, err := parser.ParseRules() if err != nil { return result, err } result.Rules = rules } else { // parse declarations block declarations, err := parser.ParseDeclarations() if err != nil { return result, err } result.Declarations = declarations } // finished break } else { // parse prelude prelude, err := parser.parsePrelude() if err != nil { return result, err } result.Prelude = prelude } } // log.Printf("[parsed] Rule: %s", result.String()) return result, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "parseAtRule", "(", ")", "(", "*", "css", ".", "Rule", ",", "error", ")", "{", "// parse rule name (eg: \"@import\")", "token", ":=", "parser", ".", "shiftToken", "(", ")", "\n\n", "result", ":=", "css", ".", "NewRule", "(", "css", ".", "AtRule", ")", "\n", "result", ".", "Name", "=", "token", ".", "Value", "\n\n", "for", "parser", ".", "tokenParsable", "(", ")", "{", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "parser", ".", "shiftToken", "(", ")", "\n\n", "// finished", "break", "\n", "}", "else", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "if", "result", ".", "EmbedsRules", "(", ")", "{", "// parse rules block", "rules", ",", "err", ":=", "parser", ".", "ParseRules", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", ".", "Rules", "=", "rules", "\n", "}", "else", "{", "// parse declarations block", "declarations", ",", "err", ":=", "parser", ".", "ParseDeclarations", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", ".", "Declarations", "=", "declarations", "\n", "}", "\n\n", "// finished", "break", "\n", "}", "else", "{", "// parse prelude", "prelude", ",", "err", ":=", "parser", ".", "parsePrelude", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", ".", "Prelude", "=", "prelude", "\n", "}", "\n", "}", "\n\n", "// log.Printf(\"[parsed] Rule: %s\", result.String())", "return", "result", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// Parse an At Rule
[ "Parse", "an", "At", "Rule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L194-L242
aymerick/douceur
parser/parser.go
parseQualifiedRule
func (parser *Parser) parseQualifiedRule() (*css.Rule, error) { result := css.NewRule(css.QualifiedRule) for parser.tokenParsable() { if parser.tokenChar("{") { if result.Prelude == "" { errMsg := fmt.Sprintf("Unexpected { character: %s", parser.nextToken().String()) return result, errors.New(errMsg) } // parse declarations block declarations, err := parser.ParseDeclarations() if err != nil { return result, err } result.Declarations = declarations // finished break } else { // parse prelude prelude, err := parser.parsePrelude() if err != nil { return result, err } result.Prelude = prelude } } result.Selectors = strings.Split(result.Prelude, ",") for i, sel := range result.Selectors { result.Selectors[i] = strings.TrimSpace(sel) } // log.Printf("[parsed] Rule: %s", result.String()) return result, parser.err() }
go
func (parser *Parser) parseQualifiedRule() (*css.Rule, error) { result := css.NewRule(css.QualifiedRule) for parser.tokenParsable() { if parser.tokenChar("{") { if result.Prelude == "" { errMsg := fmt.Sprintf("Unexpected { character: %s", parser.nextToken().String()) return result, errors.New(errMsg) } // parse declarations block declarations, err := parser.ParseDeclarations() if err != nil { return result, err } result.Declarations = declarations // finished break } else { // parse prelude prelude, err := parser.parsePrelude() if err != nil { return result, err } result.Prelude = prelude } } result.Selectors = strings.Split(result.Prelude, ",") for i, sel := range result.Selectors { result.Selectors[i] = strings.TrimSpace(sel) } // log.Printf("[parsed] Rule: %s", result.String()) return result, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "parseQualifiedRule", "(", ")", "(", "*", "css", ".", "Rule", ",", "error", ")", "{", "result", ":=", "css", ".", "NewRule", "(", "css", ".", "QualifiedRule", ")", "\n\n", "for", "parser", ".", "tokenParsable", "(", ")", "{", "if", "parser", ".", "tokenChar", "(", "\"", "\"", ")", "{", "if", "result", ".", "Prelude", "==", "\"", "\"", "{", "errMsg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parser", ".", "nextToken", "(", ")", ".", "String", "(", ")", ")", "\n", "return", "result", ",", "errors", ".", "New", "(", "errMsg", ")", "\n", "}", "\n\n", "// parse declarations block", "declarations", ",", "err", ":=", "parser", ".", "ParseDeclarations", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", ".", "Declarations", "=", "declarations", "\n\n", "// finished", "break", "\n", "}", "else", "{", "// parse prelude", "prelude", ",", "err", ":=", "parser", ".", "parsePrelude", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", ".", "Prelude", "=", "prelude", "\n", "}", "\n", "}", "\n\n", "result", ".", "Selectors", "=", "strings", ".", "Split", "(", "result", ".", "Prelude", ",", "\"", "\"", ")", "\n", "for", "i", ",", "sel", ":=", "range", "result", ".", "Selectors", "{", "result", ".", "Selectors", "[", "i", "]", "=", "strings", ".", "TrimSpace", "(", "sel", ")", "\n", "}", "\n\n", "// log.Printf(\"[parsed] Rule: %s\", result.String())", "return", "result", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// Parse a Qualified Rule
[ "Parse", "a", "Qualified", "Rule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L245-L284
aymerick/douceur
parser/parser.go
parsePrelude
func (parser *Parser) parsePrelude() (string, error) { result := "" for parser.tokenParsable() && !parser.tokenEndOfPrelude() { token := parser.shiftToken() result += token.Value } result = strings.TrimSpace(result) // log.Printf("[parsed] prelude: %s", result) return result, parser.err() }
go
func (parser *Parser) parsePrelude() (string, error) { result := "" for parser.tokenParsable() && !parser.tokenEndOfPrelude() { token := parser.shiftToken() result += token.Value } result = strings.TrimSpace(result) // log.Printf("[parsed] prelude: %s", result) return result, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "parsePrelude", "(", ")", "(", "string", ",", "error", ")", "{", "result", ":=", "\"", "\"", "\n\n", "for", "parser", ".", "tokenParsable", "(", ")", "&&", "!", "parser", ".", "tokenEndOfPrelude", "(", ")", "{", "token", ":=", "parser", ".", "shiftToken", "(", ")", "\n", "result", "+=", "token", ".", "Value", "\n", "}", "\n\n", "result", "=", "strings", ".", "TrimSpace", "(", "result", ")", "\n\n", "// log.Printf(\"[parsed] prelude: %s\", result)", "return", "result", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// Parse Rule prelude
[ "Parse", "Rule", "prelude" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L287-L300
aymerick/douceur
parser/parser.go
parseBOM
func (parser *Parser) parseBOM() (bool, error) { if parser.nextToken().Type == scanner.TokenBOM { parser.shiftToken() return true, nil } return false, parser.err() }
go
func (parser *Parser) parseBOM() (bool, error) { if parser.nextToken().Type == scanner.TokenBOM { parser.shiftToken() return true, nil } return false, parser.err() }
[ "func", "(", "parser", "*", "Parser", ")", "parseBOM", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "parser", ".", "nextToken", "(", ")", ".", "Type", "==", "scanner", ".", "TokenBOM", "{", "parser", ".", "shiftToken", "(", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n\n", "return", "false", ",", "parser", ".", "err", "(", ")", "\n", "}" ]
// Parse BOM
[ "Parse", "BOM" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L303-L310
aymerick/douceur
parser/parser.go
nextToken
func (parser *Parser) nextToken() *scanner.Token { if len(parser.tokens) == 0 { // fetch next token nextToken := parser.scan.Next() // log.Printf("[token] %s => %v", nextToken.Type.String(), nextToken.Value) // queue it parser.tokens = append(parser.tokens, nextToken) } return parser.tokens[0] }
go
func (parser *Parser) nextToken() *scanner.Token { if len(parser.tokens) == 0 { // fetch next token nextToken := parser.scan.Next() // log.Printf("[token] %s => %v", nextToken.Type.String(), nextToken.Value) // queue it parser.tokens = append(parser.tokens, nextToken) } return parser.tokens[0] }
[ "func", "(", "parser", "*", "Parser", ")", "nextToken", "(", ")", "*", "scanner", ".", "Token", "{", "if", "len", "(", "parser", ".", "tokens", ")", "==", "0", "{", "// fetch next token", "nextToken", ":=", "parser", ".", "scan", ".", "Next", "(", ")", "\n\n", "// log.Printf(\"[token] %s => %v\", nextToken.Type.String(), nextToken.Value)", "// queue it", "parser", ".", "tokens", "=", "append", "(", "parser", ".", "tokens", ",", "nextToken", ")", "\n", "}", "\n\n", "return", "parser", ".", "tokens", "[", "0", "]", "\n", "}" ]
// Returns next token without removing it from tokens buffer
[ "Returns", "next", "token", "without", "removing", "it", "from", "tokens", "buffer" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L313-L325
aymerick/douceur
parser/parser.go
shiftToken
func (parser *Parser) shiftToken() *scanner.Token { var result *scanner.Token result, parser.tokens = parser.tokens[0], parser.tokens[1:] return result }
go
func (parser *Parser) shiftToken() *scanner.Token { var result *scanner.Token result, parser.tokens = parser.tokens[0], parser.tokens[1:] return result }
[ "func", "(", "parser", "*", "Parser", ")", "shiftToken", "(", ")", "*", "scanner", ".", "Token", "{", "var", "result", "*", "scanner", ".", "Token", "\n\n", "result", ",", "parser", ".", "tokens", "=", "parser", ".", "tokens", "[", "0", "]", ",", "parser", ".", "tokens", "[", "1", ":", "]", "\n", "return", "result", "\n", "}" ]
// Returns next token and remove it from the tokens buffer
[ "Returns", "next", "token", "and", "remove", "it", "from", "the", "tokens", "buffer" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L328-L333
aymerick/douceur
parser/parser.go
err
func (parser *Parser) err() error { if parser.tokenError() { token := parser.nextToken() return fmt.Errorf("Tokenizer error: %s", token.String()) } return nil }
go
func (parser *Parser) err() error { if parser.tokenError() { token := parser.nextToken() return fmt.Errorf("Tokenizer error: %s", token.String()) } return nil }
[ "func", "(", "parser", "*", "Parser", ")", "err", "(", ")", "error", "{", "if", "parser", ".", "tokenError", "(", ")", "{", "token", ":=", "parser", ".", "nextToken", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Returns tokenizer error, or nil if no error
[ "Returns", "tokenizer", "error", "or", "nil", "if", "no", "error" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L336-L343
aymerick/douceur
parser/parser.go
tokenCDOorCDC
func (parser *Parser) tokenCDOorCDC() bool { switch parser.nextToken().Type { case scanner.TokenCDO, scanner.TokenCDC: return true default: return false } }
go
func (parser *Parser) tokenCDOorCDC() bool { switch parser.nextToken().Type { case scanner.TokenCDO, scanner.TokenCDC: return true default: return false } }
[ "func", "(", "parser", "*", "Parser", ")", "tokenCDOorCDC", "(", ")", "bool", "{", "switch", "parser", ".", "nextToken", "(", ")", ".", "Type", "{", "case", "scanner", ".", "TokenCDO", ",", "scanner", ".", "TokenCDC", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// Returns true if next token is a CDO or a CDC
[ "Returns", "true", "if", "next", "token", "is", "a", "CDO", "or", "a", "CDC" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L366-L373
aymerick/douceur
parser/parser.go
tokenIgnorable
func (parser *Parser) tokenIgnorable() bool { return parser.tokenWS() || parser.tokenComment() || parser.tokenCDOorCDC() }
go
func (parser *Parser) tokenIgnorable() bool { return parser.tokenWS() || parser.tokenComment() || parser.tokenCDOorCDC() }
[ "func", "(", "parser", "*", "Parser", ")", "tokenIgnorable", "(", ")", "bool", "{", "return", "parser", ".", "tokenWS", "(", ")", "||", "parser", ".", "tokenComment", "(", ")", "||", "parser", ".", "tokenCDOorCDC", "(", ")", "\n", "}" ]
// Returns true if next token is ignorable
[ "Returns", "true", "if", "next", "token", "is", "ignorable" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L376-L378
aymerick/douceur
parser/parser.go
tokenChar
func (parser *Parser) tokenChar(value string) bool { token := parser.nextToken() return (token.Type == scanner.TokenChar) && (token.Value == value) }
go
func (parser *Parser) tokenChar(value string) bool { token := parser.nextToken() return (token.Type == scanner.TokenChar) && (token.Value == value) }
[ "func", "(", "parser", "*", "Parser", ")", "tokenChar", "(", "value", "string", ")", "bool", "{", "token", ":=", "parser", ".", "nextToken", "(", ")", "\n", "return", "(", "token", ".", "Type", "==", "scanner", ".", "TokenChar", ")", "&&", "(", "token", ".", "Value", "==", "value", ")", "\n", "}" ]
// Returns true if next token is given character
[ "Returns", "true", "if", "next", "token", "is", "given", "character" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L391-L394
aymerick/douceur
css/stylesheet.go
String
func (sheet *Stylesheet) String() string { result := "" for _, rule := range sheet.Rules { if result != "" { result += "\n" } result += rule.String() } return result }
go
func (sheet *Stylesheet) String() string { result := "" for _, rule := range sheet.Rules { if result != "" { result += "\n" } result += rule.String() } return result }
[ "func", "(", "sheet", "*", "Stylesheet", ")", "String", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "for", "_", ",", "rule", ":=", "range", "sheet", ".", "Rules", "{", "if", "result", "!=", "\"", "\"", "{", "result", "+=", "\"", "\\n", "\"", "\n", "}", "\n", "result", "+=", "rule", ".", "String", "(", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Returns string representation of the Stylesheet
[ "Returns", "string", "representation", "of", "the", "Stylesheet" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/stylesheet.go#L14-L25
aymerick/douceur
css/rule.go
EmbedsRules
func (rule *Rule) EmbedsRules() bool { if rule.Kind == AtRule { for _, atRuleName := range atRulesWithRulesBlock { if rule.Name == atRuleName { return true } } } return false }
go
func (rule *Rule) EmbedsRules() bool { if rule.Kind == AtRule { for _, atRuleName := range atRulesWithRulesBlock { if rule.Name == atRuleName { return true } } } return false }
[ "func", "(", "rule", "*", "Rule", ")", "EmbedsRules", "(", ")", "bool", "{", "if", "rule", ".", "Kind", "==", "AtRule", "{", "for", "_", ",", "atRuleName", ":=", "range", "atRulesWithRulesBlock", "{", "if", "rule", ".", "Name", "==", "atRuleName", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// EmbedsRules returns true if this rule embeds another rules
[ "EmbedsRules", "returns", "true", "if", "this", "rule", "embeds", "another", "rules" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/rule.go#L69-L79
aymerick/douceur
css/rule.go
Equal
func (rule *Rule) Equal(other *Rule) bool { if (rule.Kind != other.Kind) || (rule.Prelude != other.Prelude) || (rule.Name != other.Name) { return false } if (len(rule.Selectors) != len(other.Selectors)) || (len(rule.Declarations) != len(other.Declarations)) || (len(rule.Rules) != len(other.Rules)) { return false } for i, sel := range rule.Selectors { if sel != other.Selectors[i] { return false } } for i, decl := range rule.Declarations { if !decl.Equal(other.Declarations[i]) { return false } } for i, rule := range rule.Rules { if !rule.Equal(other.Rules[i]) { return false } } return true }
go
func (rule *Rule) Equal(other *Rule) bool { if (rule.Kind != other.Kind) || (rule.Prelude != other.Prelude) || (rule.Name != other.Name) { return false } if (len(rule.Selectors) != len(other.Selectors)) || (len(rule.Declarations) != len(other.Declarations)) || (len(rule.Rules) != len(other.Rules)) { return false } for i, sel := range rule.Selectors { if sel != other.Selectors[i] { return false } } for i, decl := range rule.Declarations { if !decl.Equal(other.Declarations[i]) { return false } } for i, rule := range rule.Rules { if !rule.Equal(other.Rules[i]) { return false } } return true }
[ "func", "(", "rule", "*", "Rule", ")", "Equal", "(", "other", "*", "Rule", ")", "bool", "{", "if", "(", "rule", ".", "Kind", "!=", "other", ".", "Kind", ")", "||", "(", "rule", ".", "Prelude", "!=", "other", ".", "Prelude", ")", "||", "(", "rule", ".", "Name", "!=", "other", ".", "Name", ")", "{", "return", "false", "\n", "}", "\n\n", "if", "(", "len", "(", "rule", ".", "Selectors", ")", "!=", "len", "(", "other", ".", "Selectors", ")", ")", "||", "(", "len", "(", "rule", ".", "Declarations", ")", "!=", "len", "(", "other", ".", "Declarations", ")", ")", "||", "(", "len", "(", "rule", ".", "Rules", ")", "!=", "len", "(", "other", ".", "Rules", ")", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "i", ",", "sel", ":=", "range", "rule", ".", "Selectors", "{", "if", "sel", "!=", "other", ".", "Selectors", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "for", "i", ",", "decl", ":=", "range", "rule", ".", "Declarations", "{", "if", "!", "decl", ".", "Equal", "(", "other", ".", "Declarations", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "for", "i", ",", "rule", ":=", "range", "rule", ".", "Rules", "{", "if", "!", "rule", ".", "Equal", "(", "other", ".", "Rules", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Equal returns true if both rules are equals
[ "Equal", "returns", "true", "if", "both", "rules", "are", "equals" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/rule.go#L82-L114
aymerick/douceur
css/rule.go
Diff
func (rule *Rule) Diff(other *Rule) []string { result := []string{} if rule.Kind != other.Kind { result = append(result, fmt.Sprintf("Kind: %s | %s", rule.Kind.String(), other.Kind.String())) } if rule.Prelude != other.Prelude { result = append(result, fmt.Sprintf("Prelude: \"%s\" | \"%s\"", rule.Prelude, other.Prelude)) } if rule.Name != other.Name { result = append(result, fmt.Sprintf("Name: \"%s\" | \"%s\"", rule.Name, other.Name)) } if len(rule.Selectors) != len(other.Selectors) { result = append(result, fmt.Sprintf("Selectors: %v | %v", strings.Join(rule.Selectors, ", "), strings.Join(other.Selectors, ", "))) } else { for i, sel := range rule.Selectors { if sel != other.Selectors[i] { result = append(result, fmt.Sprintf("Selector: \"%s\" | \"%s\"", sel, other.Selectors[i])) } } } if len(rule.Declarations) != len(other.Declarations) { result = append(result, fmt.Sprintf("Declarations Nb: %d | %d", len(rule.Declarations), len(other.Declarations))) } else { for i, decl := range rule.Declarations { if !decl.Equal(other.Declarations[i]) { result = append(result, fmt.Sprintf("Declaration: \"%s\" | \"%s\"", decl.String(), other.Declarations[i].String())) } } } if len(rule.Rules) != len(other.Rules) { result = append(result, fmt.Sprintf("Rules Nb: %d | %d", len(rule.Rules), len(other.Rules))) } else { for i, rule := range rule.Rules { if !rule.Equal(other.Rules[i]) { result = append(result, fmt.Sprintf("Rule: \"%s\" | \"%s\"", rule.String(), other.Rules[i].String())) } } } return result }
go
func (rule *Rule) Diff(other *Rule) []string { result := []string{} if rule.Kind != other.Kind { result = append(result, fmt.Sprintf("Kind: %s | %s", rule.Kind.String(), other.Kind.String())) } if rule.Prelude != other.Prelude { result = append(result, fmt.Sprintf("Prelude: \"%s\" | \"%s\"", rule.Prelude, other.Prelude)) } if rule.Name != other.Name { result = append(result, fmt.Sprintf("Name: \"%s\" | \"%s\"", rule.Name, other.Name)) } if len(rule.Selectors) != len(other.Selectors) { result = append(result, fmt.Sprintf("Selectors: %v | %v", strings.Join(rule.Selectors, ", "), strings.Join(other.Selectors, ", "))) } else { for i, sel := range rule.Selectors { if sel != other.Selectors[i] { result = append(result, fmt.Sprintf("Selector: \"%s\" | \"%s\"", sel, other.Selectors[i])) } } } if len(rule.Declarations) != len(other.Declarations) { result = append(result, fmt.Sprintf("Declarations Nb: %d | %d", len(rule.Declarations), len(other.Declarations))) } else { for i, decl := range rule.Declarations { if !decl.Equal(other.Declarations[i]) { result = append(result, fmt.Sprintf("Declaration: \"%s\" | \"%s\"", decl.String(), other.Declarations[i].String())) } } } if len(rule.Rules) != len(other.Rules) { result = append(result, fmt.Sprintf("Rules Nb: %d | %d", len(rule.Rules), len(other.Rules))) } else { for i, rule := range rule.Rules { if !rule.Equal(other.Rules[i]) { result = append(result, fmt.Sprintf("Rule: \"%s\" | \"%s\"", rule.String(), other.Rules[i].String())) } } } return result }
[ "func", "(", "rule", "*", "Rule", ")", "Diff", "(", "other", "*", "Rule", ")", "[", "]", "string", "{", "result", ":=", "[", "]", "string", "{", "}", "\n\n", "if", "rule", ".", "Kind", "!=", "other", ".", "Kind", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rule", ".", "Kind", ".", "String", "(", ")", ",", "other", ".", "Kind", ".", "String", "(", ")", ")", ")", "\n", "}", "\n\n", "if", "rule", ".", "Prelude", "!=", "other", ".", "Prelude", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "rule", ".", "Prelude", ",", "other", ".", "Prelude", ")", ")", "\n", "}", "\n\n", "if", "rule", ".", "Name", "!=", "other", ".", "Name", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "rule", ".", "Name", ",", "other", ".", "Name", ")", ")", "\n", "}", "\n\n", "if", "len", "(", "rule", ".", "Selectors", ")", "!=", "len", "(", "other", ".", "Selectors", ")", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "rule", ".", "Selectors", ",", "\"", "\"", ")", ",", "strings", ".", "Join", "(", "other", ".", "Selectors", ",", "\"", "\"", ")", ")", ")", "\n", "}", "else", "{", "for", "i", ",", "sel", ":=", "range", "rule", ".", "Selectors", "{", "if", "sel", "!=", "other", ".", "Selectors", "[", "i", "]", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "sel", ",", "other", ".", "Selectors", "[", "i", "]", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "rule", ".", "Declarations", ")", "!=", "len", "(", "other", ".", "Declarations", ")", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "rule", ".", "Declarations", ")", ",", "len", "(", "other", ".", "Declarations", ")", ")", ")", "\n", "}", "else", "{", "for", "i", ",", "decl", ":=", "range", "rule", ".", "Declarations", "{", "if", "!", "decl", ".", "Equal", "(", "other", ".", "Declarations", "[", "i", "]", ")", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "decl", ".", "String", "(", ")", ",", "other", ".", "Declarations", "[", "i", "]", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "rule", ".", "Rules", ")", "!=", "len", "(", "other", ".", "Rules", ")", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "rule", ".", "Rules", ")", ",", "len", "(", "other", ".", "Rules", ")", ")", ")", "\n", "}", "else", "{", "for", "i", ",", "rule", ":=", "range", "rule", ".", "Rules", "{", "if", "!", "rule", ".", "Equal", "(", "other", ".", "Rules", "[", "i", "]", ")", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "rule", ".", "String", "(", ")", ",", "other", ".", "Rules", "[", "i", "]", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Diff returns a string representation of rules differences
[ "Diff", "returns", "a", "string", "representation", "of", "rules", "differences" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/rule.go#L117-L164
aymerick/douceur
css/rule.go
String
func (rule *Rule) String() string { result := "" if rule.Kind == QualifiedRule { for i, sel := range rule.Selectors { if i != 0 { result += ", " } result += sel } } else { // AtRule result += fmt.Sprintf("%s", rule.Name) if rule.Prelude != "" { if result != "" { result += " " } result += fmt.Sprintf("%s", rule.Prelude) } } if (len(rule.Declarations) == 0) && (len(rule.Rules) == 0) { result += ";" } else { result += " {\n" if rule.EmbedsRules() { for _, subRule := range rule.Rules { result += fmt.Sprintf("%s%s\n", rule.indent(), subRule.String()) } } else { for _, decl := range rule.Declarations { result += fmt.Sprintf("%s%s\n", rule.indent(), decl.String()) } } result += fmt.Sprintf("%s}", rule.indentEndBlock()) } return result }
go
func (rule *Rule) String() string { result := "" if rule.Kind == QualifiedRule { for i, sel := range rule.Selectors { if i != 0 { result += ", " } result += sel } } else { // AtRule result += fmt.Sprintf("%s", rule.Name) if rule.Prelude != "" { if result != "" { result += " " } result += fmt.Sprintf("%s", rule.Prelude) } } if (len(rule.Declarations) == 0) && (len(rule.Rules) == 0) { result += ";" } else { result += " {\n" if rule.EmbedsRules() { for _, subRule := range rule.Rules { result += fmt.Sprintf("%s%s\n", rule.indent(), subRule.String()) } } else { for _, decl := range rule.Declarations { result += fmt.Sprintf("%s%s\n", rule.indent(), decl.String()) } } result += fmt.Sprintf("%s}", rule.indentEndBlock()) } return result }
[ "func", "(", "rule", "*", "Rule", ")", "String", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "if", "rule", ".", "Kind", "==", "QualifiedRule", "{", "for", "i", ",", "sel", ":=", "range", "rule", ".", "Selectors", "{", "if", "i", "!=", "0", "{", "result", "+=", "\"", "\"", "\n", "}", "\n", "result", "+=", "sel", "\n", "}", "\n", "}", "else", "{", "// AtRule", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rule", ".", "Name", ")", "\n\n", "if", "rule", ".", "Prelude", "!=", "\"", "\"", "{", "if", "result", "!=", "\"", "\"", "{", "result", "+=", "\"", "\"", "\n", "}", "\n", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rule", ".", "Prelude", ")", "\n", "}", "\n", "}", "\n\n", "if", "(", "len", "(", "rule", ".", "Declarations", ")", "==", "0", ")", "&&", "(", "len", "(", "rule", ".", "Rules", ")", "==", "0", ")", "{", "result", "+=", "\"", "\"", "\n", "}", "else", "{", "result", "+=", "\"", "\\n", "\"", "\n\n", "if", "rule", ".", "EmbedsRules", "(", ")", "{", "for", "_", ",", "subRule", ":=", "range", "rule", ".", "Rules", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "rule", ".", "indent", "(", ")", ",", "subRule", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "decl", ":=", "range", "rule", ".", "Declarations", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "rule", ".", "indent", "(", ")", ",", "decl", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rule", ".", "indentEndBlock", "(", ")", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Returns the string representation of a rule
[ "Returns", "the", "string", "representation", "of", "a", "rule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/rule.go#L167-L208
aymerick/douceur
css/rule.go
indent
func (rule *Rule) indent() string { result := "" for i := 0; i < ((rule.EmbedLevel + 1) * indentSpace); i++ { result += " " } return result }
go
func (rule *Rule) indent() string { result := "" for i := 0; i < ((rule.EmbedLevel + 1) * indentSpace); i++ { result += " " } return result }
[ "func", "(", "rule", "*", "Rule", ")", "indent", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "(", "(", "rule", ".", "EmbedLevel", "+", "1", ")", "*", "indentSpace", ")", ";", "i", "++", "{", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Returns identation spaces for declarations and rules
[ "Returns", "identation", "spaces", "for", "declarations", "and", "rules" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/rule.go#L211-L219
aymerick/douceur
css/rule.go
indentEndBlock
func (rule *Rule) indentEndBlock() string { result := "" for i := 0; i < (rule.EmbedLevel * indentSpace); i++ { result += " " } return result }
go
func (rule *Rule) indentEndBlock() string { result := "" for i := 0; i < (rule.EmbedLevel * indentSpace); i++ { result += " " } return result }
[ "func", "(", "rule", "*", "Rule", ")", "indentEndBlock", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "(", "rule", ".", "EmbedLevel", "*", "indentSpace", ")", ";", "i", "++", "{", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Returns identation spaces for end of block character
[ "Returns", "identation", "spaces", "for", "end", "of", "block", "character" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/rule.go#L222-L230
aymerick/douceur
douceur.go
parseCSS
func parseCSS(filePath string) { input := readFile(filePath) stylesheet, err := parser.Parse(string(input)) if err != nil { fmt.Println("Parsing error: ", err) os.Exit(1) } fmt.Println(stylesheet.String()) }
go
func parseCSS(filePath string) { input := readFile(filePath) stylesheet, err := parser.Parse(string(input)) if err != nil { fmt.Println("Parsing error: ", err) os.Exit(1) } fmt.Println(stylesheet.String()) }
[ "func", "parseCSS", "(", "filePath", "string", ")", "{", "input", ":=", "readFile", "(", "filePath", ")", "\n\n", "stylesheet", ",", "err", ":=", "parser", ".", "Parse", "(", "string", "(", "input", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "stylesheet", ".", "String", "(", ")", ")", "\n", "}" ]
// parse and display CSS file
[ "parse", "and", "display", "CSS", "file" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/douceur.go#L63-L73
aymerick/douceur
douceur.go
inlineCSS
func inlineCSS(filePath string) { input := readFile(filePath) output, err := inliner.Inline(string(input)) if err != nil { fmt.Println("Inlining error: ", err) os.Exit(1) } fmt.Println(output) }
go
func inlineCSS(filePath string) { input := readFile(filePath) output, err := inliner.Inline(string(input)) if err != nil { fmt.Println("Inlining error: ", err) os.Exit(1) } fmt.Println(output) }
[ "func", "inlineCSS", "(", "filePath", "string", ")", "{", "input", ":=", "readFile", "(", "filePath", ")", "\n\n", "output", ",", "err", ":=", "inliner", ".", "Inline", "(", "string", "(", "input", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "output", ")", "\n", "}" ]
// inlines CSS into HTML and display result
[ "inlines", "CSS", "into", "HTML", "and", "display", "result" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/douceur.go#L76-L86
aymerick/douceur
inliner/element.go
addStyleRule
func (element *Element) addStyleRule(styleRule *StyleRule) { element.styleRules = append(element.styleRules, styleRule) }
go
func (element *Element) addStyleRule(styleRule *StyleRule) { element.styleRules = append(element.styleRules, styleRule) }
[ "func", "(", "element", "*", "Element", ")", "addStyleRule", "(", "styleRule", "*", "StyleRule", ")", "{", "element", ".", "styleRules", "=", "append", "(", "element", ".", "styleRules", ",", "styleRule", ")", "\n", "}" ]
// Add a Style Rule to Element
[ "Add", "a", "Style", "Rule", "to", "Element" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L66-L68
aymerick/douceur
inliner/element.go
inline
func (element *Element) inline() error { // compute declarations declarations, err := element.computeDeclarations() if err != nil { return err } // set style attribute styleValue := computeStyleValue(declarations) if styleValue != "" { element.elt.SetAttr("style", styleValue) } // set additionnal attributes element.setAttributesFromStyle(declarations) return nil }
go
func (element *Element) inline() error { // compute declarations declarations, err := element.computeDeclarations() if err != nil { return err } // set style attribute styleValue := computeStyleValue(declarations) if styleValue != "" { element.elt.SetAttr("style", styleValue) } // set additionnal attributes element.setAttributesFromStyle(declarations) return nil }
[ "func", "(", "element", "*", "Element", ")", "inline", "(", ")", "error", "{", "// compute declarations", "declarations", ",", "err", ":=", "element", ".", "computeDeclarations", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// set style attribute", "styleValue", ":=", "computeStyleValue", "(", "declarations", ")", "\n", "if", "styleValue", "!=", "\"", "\"", "{", "element", ".", "elt", ".", "SetAttr", "(", "\"", "\"", ",", "styleValue", ")", "\n", "}", "\n\n", "// set additionnal attributes", "element", ".", "setAttributesFromStyle", "(", "declarations", ")", "\n\n", "return", "nil", "\n", "}" ]
// Inline styles on element
[ "Inline", "styles", "on", "element" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L71-L88
aymerick/douceur
inliner/element.go
computeDeclarations
func (element *Element) computeDeclarations() ([]*css.Declaration, error) { result := []*css.Declaration{} styles := make(map[string]*StyleDeclaration) // First: parsed stylesheets rules mergeStyleDeclarations(element.styleRules, styles) // Then: inline rules inlineRules, err := element.parseInlineStyle() if err != nil { return result, err } mergeStyleDeclarations(inlineRules, styles) // map to array for _, styleDecl := range styles { result = append(result, styleDecl.Declaration) } // sort declarations by property name sort.Sort(css.DeclarationsByProperty(result)) return result, nil }
go
func (element *Element) computeDeclarations() ([]*css.Declaration, error) { result := []*css.Declaration{} styles := make(map[string]*StyleDeclaration) // First: parsed stylesheets rules mergeStyleDeclarations(element.styleRules, styles) // Then: inline rules inlineRules, err := element.parseInlineStyle() if err != nil { return result, err } mergeStyleDeclarations(inlineRules, styles) // map to array for _, styleDecl := range styles { result = append(result, styleDecl.Declaration) } // sort declarations by property name sort.Sort(css.DeclarationsByProperty(result)) return result, nil }
[ "func", "(", "element", "*", "Element", ")", "computeDeclarations", "(", ")", "(", "[", "]", "*", "css", ".", "Declaration", ",", "error", ")", "{", "result", ":=", "[", "]", "*", "css", ".", "Declaration", "{", "}", "\n\n", "styles", ":=", "make", "(", "map", "[", "string", "]", "*", "StyleDeclaration", ")", "\n\n", "// First: parsed stylesheets rules", "mergeStyleDeclarations", "(", "element", ".", "styleRules", ",", "styles", ")", "\n\n", "// Then: inline rules", "inlineRules", ",", "err", ":=", "element", ".", "parseInlineStyle", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "mergeStyleDeclarations", "(", "inlineRules", ",", "styles", ")", "\n\n", "// map to array", "for", "_", ",", "styleDecl", ":=", "range", "styles", "{", "result", "=", "append", "(", "result", ",", "styleDecl", ".", "Declaration", ")", "\n", "}", "\n\n", "// sort declarations by property name", "sort", ".", "Sort", "(", "css", ".", "DeclarationsByProperty", "(", "result", ")", ")", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Compute css declarations
[ "Compute", "css", "declarations" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L91-L116
aymerick/douceur
inliner/element.go
parseInlineStyle
func (element *Element) parseInlineStyle() ([]*StyleRule, error) { result := []*StyleRule{} styleValue, exists := element.elt.Attr("style") if (styleValue == "") || !exists { return result, nil } declarations, err := parser.ParseDeclarations(styleValue) if err != nil { return result, err } result = append(result, NewStyleRule(inlineFakeSelector, declarations)) return result, nil }
go
func (element *Element) parseInlineStyle() ([]*StyleRule, error) { result := []*StyleRule{} styleValue, exists := element.elt.Attr("style") if (styleValue == "") || !exists { return result, nil } declarations, err := parser.ParseDeclarations(styleValue) if err != nil { return result, err } result = append(result, NewStyleRule(inlineFakeSelector, declarations)) return result, nil }
[ "func", "(", "element", "*", "Element", ")", "parseInlineStyle", "(", ")", "(", "[", "]", "*", "StyleRule", ",", "error", ")", "{", "result", ":=", "[", "]", "*", "StyleRule", "{", "}", "\n\n", "styleValue", ",", "exists", ":=", "element", ".", "elt", ".", "Attr", "(", "\"", "\"", ")", "\n", "if", "(", "styleValue", "==", "\"", "\"", ")", "||", "!", "exists", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "declarations", ",", "err", ":=", "parser", ".", "ParseDeclarations", "(", "styleValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "result", "=", "append", "(", "result", ",", "NewStyleRule", "(", "inlineFakeSelector", ",", "declarations", ")", ")", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Parse inline style rules
[ "Parse", "inline", "style", "rules" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L119-L135
aymerick/douceur
inliner/element.go
setAttributesFromStyle
func (element *Element) setAttributesFromStyle(declarations []*css.Declaration) { // for each style declarations for _, declaration := range declarations { if eltAttr := styleToAttr[declaration.Property]; eltAttr != nil { // check if element is allowed for that attribute for _, eltAllowed := range eltAttr.elements { if element.elt.Nodes[0].Data == eltAllowed { element.elt.SetAttr(eltAttr.attr, declaration.Value) break } } } } }
go
func (element *Element) setAttributesFromStyle(declarations []*css.Declaration) { // for each style declarations for _, declaration := range declarations { if eltAttr := styleToAttr[declaration.Property]; eltAttr != nil { // check if element is allowed for that attribute for _, eltAllowed := range eltAttr.elements { if element.elt.Nodes[0].Data == eltAllowed { element.elt.SetAttr(eltAttr.attr, declaration.Value) break } } } } }
[ "func", "(", "element", "*", "Element", ")", "setAttributesFromStyle", "(", "declarations", "[", "]", "*", "css", ".", "Declaration", ")", "{", "// for each style declarations", "for", "_", ",", "declaration", ":=", "range", "declarations", "{", "if", "eltAttr", ":=", "styleToAttr", "[", "declaration", ".", "Property", "]", ";", "eltAttr", "!=", "nil", "{", "// check if element is allowed for that attribute", "for", "_", ",", "eltAllowed", ":=", "range", "eltAttr", ".", "elements", "{", "if", "element", ".", "elt", ".", "Nodes", "[", "0", "]", ".", "Data", "==", "eltAllowed", "{", "element", ".", "elt", ".", "SetAttr", "(", "eltAttr", ".", "attr", ",", "declaration", ".", "Value", ")", "\n\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Set additional attributes from style declarations
[ "Set", "additional", "attributes", "from", "style", "declarations" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L138-L152
aymerick/douceur
inliner/element.go
computeStyleValue
func computeStyleValue(declarations []*css.Declaration) string { result := "" // set style attribute value for _, declaration := range declarations { if result != "" { result += " " } result += declaration.StringWithImportant(false) } return result }
go
func computeStyleValue(declarations []*css.Declaration) string { result := "" // set style attribute value for _, declaration := range declarations { if result != "" { result += " " } result += declaration.StringWithImportant(false) } return result }
[ "func", "computeStyleValue", "(", "declarations", "[", "]", "*", "css", ".", "Declaration", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "// set style attribute value", "for", "_", ",", "declaration", ":=", "range", "declarations", "{", "if", "result", "!=", "\"", "\"", "{", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "result", "+=", "declaration", ".", "StringWithImportant", "(", "false", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// helper
[ "helper" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L155-L168
aymerick/douceur
inliner/element.go
mergeStyleDeclarations
func mergeStyleDeclarations(styleRules []*StyleRule, output map[string]*StyleDeclaration) { for _, styleRule := range styleRules { for _, declaration := range styleRule.Declarations { styleDecl := NewStyleDeclaration(styleRule, declaration) if (output[declaration.Property] == nil) || (styleDecl.Specificity() >= output[declaration.Property].Specificity()) { output[declaration.Property] = styleDecl } } } }
go
func mergeStyleDeclarations(styleRules []*StyleRule, output map[string]*StyleDeclaration) { for _, styleRule := range styleRules { for _, declaration := range styleRule.Declarations { styleDecl := NewStyleDeclaration(styleRule, declaration) if (output[declaration.Property] == nil) || (styleDecl.Specificity() >= output[declaration.Property].Specificity()) { output[declaration.Property] = styleDecl } } } }
[ "func", "mergeStyleDeclarations", "(", "styleRules", "[", "]", "*", "StyleRule", ",", "output", "map", "[", "string", "]", "*", "StyleDeclaration", ")", "{", "for", "_", ",", "styleRule", ":=", "range", "styleRules", "{", "for", "_", ",", "declaration", ":=", "range", "styleRule", ".", "Declarations", "{", "styleDecl", ":=", "NewStyleDeclaration", "(", "styleRule", ",", "declaration", ")", "\n\n", "if", "(", "output", "[", "declaration", ".", "Property", "]", "==", "nil", ")", "||", "(", "styleDecl", ".", "Specificity", "(", ")", ">=", "output", "[", "declaration", ".", "Property", "]", ".", "Specificity", "(", ")", ")", "{", "output", "[", "declaration", ".", "Property", "]", "=", "styleDecl", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// helper
[ "helper" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/element.go#L171-L181
aymerick/douceur
inliner/style_rule.go
NewStyleRule
func NewStyleRule(selector string, declarations []*css.Declaration) *StyleRule { return &StyleRule{ Selector: selector, Declarations: declarations, Specificity: ComputeSpecificity(selector), } }
go
func NewStyleRule(selector string, declarations []*css.Declaration) *StyleRule { return &StyleRule{ Selector: selector, Declarations: declarations, Specificity: ComputeSpecificity(selector), } }
[ "func", "NewStyleRule", "(", "selector", "string", ",", "declarations", "[", "]", "*", "css", ".", "Declaration", ")", "*", "StyleRule", "{", "return", "&", "StyleRule", "{", "Selector", ":", "selector", ",", "Declarations", ":", "declarations", ",", "Specificity", ":", "ComputeSpecificity", "(", "selector", ")", ",", "}", "\n", "}" ]
// NewStyleRule instanciates a new StyleRule
[ "NewStyleRule", "instanciates", "a", "new", "StyleRule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/style_rule.go#L43-L49
aymerick/douceur
inliner/style_rule.go
String
func (styleRule *StyleRule) String() string { result := "" result += styleRule.Selector if len(styleRule.Declarations) == 0 { result += ";" } else { result += " {\n" for _, decl := range styleRule.Declarations { result += fmt.Sprintf(" %s\n", decl.String()) } result += "}" } return result }
go
func (styleRule *StyleRule) String() string { result := "" result += styleRule.Selector if len(styleRule.Declarations) == 0 { result += ";" } else { result += " {\n" for _, decl := range styleRule.Declarations { result += fmt.Sprintf(" %s\n", decl.String()) } result += "}" } return result }
[ "func", "(", "styleRule", "*", "StyleRule", ")", "String", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "result", "+=", "styleRule", ".", "Selector", "\n\n", "if", "len", "(", "styleRule", ".", "Declarations", ")", "==", "0", "{", "result", "+=", "\"", "\"", "\n", "}", "else", "{", "result", "+=", "\"", "\\n", "\"", "\n\n", "for", "_", ",", "decl", ":=", "range", "styleRule", ".", "Declarations", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "decl", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Returns the string representation of a style rule
[ "Returns", "the", "string", "representation", "of", "a", "style", "rule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/style_rule.go#L52-L70
aymerick/douceur
inliner/style_rule.go
ComputeSpecificity
func ComputeSpecificity(selector string) int { result := 0 if selector == inlineFakeSelector { result += 1000 } result += 100 * strings.Count(selector, "#") result += 10 * len(nonIDAttrAndPseudoClassesRegexp.FindAllStringSubmatch(selector, -1)) result += len(elementsAndPseudoElementsRegexp.FindAllStringSubmatch(selector, -1)) return result }
go
func ComputeSpecificity(selector string) int { result := 0 if selector == inlineFakeSelector { result += 1000 } result += 100 * strings.Count(selector, "#") result += 10 * len(nonIDAttrAndPseudoClassesRegexp.FindAllStringSubmatch(selector, -1)) result += len(elementsAndPseudoElementsRegexp.FindAllStringSubmatch(selector, -1)) return result }
[ "func", "ComputeSpecificity", "(", "selector", "string", ")", "int", "{", "result", ":=", "0", "\n\n", "if", "selector", "==", "inlineFakeSelector", "{", "result", "+=", "1000", "\n", "}", "\n\n", "result", "+=", "100", "*", "strings", ".", "Count", "(", "selector", ",", "\"", "\"", ")", "\n", "result", "+=", "10", "*", "len", "(", "nonIDAttrAndPseudoClassesRegexp", ".", "FindAllStringSubmatch", "(", "selector", ",", "-", "1", ")", ")", "\n", "result", "+=", "len", "(", "elementsAndPseudoElementsRegexp", ".", "FindAllStringSubmatch", "(", "selector", ",", "-", "1", ")", ")", "\n\n", "return", "result", "\n", "}" ]
// ComputeSpecificity computes style rule specificity // // cf. http://www.w3.org/TR/selectors/#specificity
[ "ComputeSpecificity", "computes", "style", "rule", "specificity", "cf", ".", "http", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "selectors", "/", "#specificity" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/style_rule.go#L75-L87
aymerick/douceur
css/declaration.go
StringWithImportant
func (decl *Declaration) StringWithImportant(option bool) string { result := fmt.Sprintf("%s: %s", decl.Property, decl.Value) if option && decl.Important { result += " !important" } result += ";" return result }
go
func (decl *Declaration) StringWithImportant(option bool) string { result := fmt.Sprintf("%s: %s", decl.Property, decl.Value) if option && decl.Important { result += " !important" } result += ";" return result }
[ "func", "(", "decl", "*", "Declaration", ")", "StringWithImportant", "(", "option", "bool", ")", "string", "{", "result", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "decl", ".", "Property", ",", "decl", ".", "Value", ")", "\n\n", "if", "option", "&&", "decl", ".", "Important", "{", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "result", "+=", "\"", "\"", "\n\n", "return", "result", "\n", "}" ]
// StringWithImportant returns string representation with optional !important part
[ "StringWithImportant", "returns", "string", "representation", "with", "optional", "!important", "part" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/declaration.go#L23-L33
aymerick/douceur
css/declaration.go
Equal
func (decl *Declaration) Equal(other *Declaration) bool { return (decl.Property == other.Property) && (decl.Value == other.Value) && (decl.Important == other.Important) }
go
func (decl *Declaration) Equal(other *Declaration) bool { return (decl.Property == other.Property) && (decl.Value == other.Value) && (decl.Important == other.Important) }
[ "func", "(", "decl", "*", "Declaration", ")", "Equal", "(", "other", "*", "Declaration", ")", "bool", "{", "return", "(", "decl", ".", "Property", "==", "other", ".", "Property", ")", "&&", "(", "decl", ".", "Value", "==", "other", ".", "Value", ")", "&&", "(", "decl", ".", "Important", "==", "other", ".", "Important", ")", "\n", "}" ]
// Equal returns true if both Declarations are equals
[ "Equal", "returns", "true", "if", "both", "Declarations", "are", "equals" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/declaration.go#L36-L38
aymerick/douceur
css/declaration.go
Swap
func (declarations DeclarationsByProperty) Swap(i, j int) { declarations[i], declarations[j] = declarations[j], declarations[i] }
go
func (declarations DeclarationsByProperty) Swap(i, j int) { declarations[i], declarations[j] = declarations[j], declarations[i] }
[ "func", "(", "declarations", "DeclarationsByProperty", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "declarations", "[", "i", "]", ",", "declarations", "[", "j", "]", "=", "declarations", "[", "j", "]", ",", "declarations", "[", "i", "]", "\n", "}" ]
// Implements sort.Interface
[ "Implements", "sort", ".", "Interface" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/declaration.go#L53-L55
aymerick/douceur
css/declaration.go
Less
func (declarations DeclarationsByProperty) Less(i, j int) bool { return declarations[i].Property < declarations[j].Property }
go
func (declarations DeclarationsByProperty) Less(i, j int) bool { return declarations[i].Property < declarations[j].Property }
[ "func", "(", "declarations", "DeclarationsByProperty", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "declarations", "[", "i", "]", ".", "Property", "<", "declarations", "[", "j", "]", ".", "Property", "\n", "}" ]
// Implements sort.Interface
[ "Implements", "sort", ".", "Interface" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/css/declaration.go#L58-L60
aymerick/douceur
inliner/inliner.go
NewInliner
func NewInliner(html string) *Inliner { return &Inliner{ html: html, elements: make(map[string]*Element), } }
go
func NewInliner(html string) *Inliner { return &Inliner{ html: html, elements: make(map[string]*Element), } }
[ "func", "NewInliner", "(", "html", "string", ")", "*", "Inliner", "{", "return", "&", "Inliner", "{", "html", ":", "html", ",", "elements", ":", "make", "(", "map", "[", "string", "]", "*", "Element", ")", ",", "}", "\n", "}" ]
// NewInliner instanciates a new Inliner
[ "NewInliner", "instanciates", "a", "new", "Inliner" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L48-L53
aymerick/douceur
inliner/inliner.go
Inline
func Inline(html string) (string, error) { result, err := NewInliner(html).Inline() if err != nil { return "", err } return result, nil }
go
func Inline(html string) (string, error) { result, err := NewInliner(html).Inline() if err != nil { return "", err } return result, nil }
[ "func", "Inline", "(", "html", "string", ")", "(", "string", ",", "error", ")", "{", "result", ",", "err", ":=", "NewInliner", "(", "html", ")", ".", "Inline", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Inline inlines css into html document
[ "Inline", "inlines", "css", "into", "html", "document" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L56-L63
aymerick/douceur
inliner/inliner.go
Inline
func (inliner *Inliner) Inline() (string, error) { // parse HTML document if err := inliner.parseHTML(); err != nil { return "", err } // parse stylesheets if err := inliner.parseStylesheets(); err != nil { return "", err } // collect elements and style rules inliner.collectElementsAndRules() // inline css if err := inliner.inlineStyleRules(); err != nil { return "", err } // insert raw stylesheet inliner.insertRawStylesheet() // generate HTML document return inliner.genHTML() }
go
func (inliner *Inliner) Inline() (string, error) { // parse HTML document if err := inliner.parseHTML(); err != nil { return "", err } // parse stylesheets if err := inliner.parseStylesheets(); err != nil { return "", err } // collect elements and style rules inliner.collectElementsAndRules() // inline css if err := inliner.inlineStyleRules(); err != nil { return "", err } // insert raw stylesheet inliner.insertRawStylesheet() // generate HTML document return inliner.genHTML() }
[ "func", "(", "inliner", "*", "Inliner", ")", "Inline", "(", ")", "(", "string", ",", "error", ")", "{", "// parse HTML document", "if", "err", ":=", "inliner", ".", "parseHTML", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// parse stylesheets", "if", "err", ":=", "inliner", ".", "parseStylesheets", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// collect elements and style rules", "inliner", ".", "collectElementsAndRules", "(", ")", "\n\n", "// inline css", "if", "err", ":=", "inliner", ".", "inlineStyleRules", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// insert raw stylesheet", "inliner", ".", "insertRawStylesheet", "(", ")", "\n\n", "// generate HTML document", "return", "inliner", ".", "genHTML", "(", ")", "\n", "}" ]
// Inline inlines CSS and returns HTML
[ "Inline", "inlines", "CSS", "and", "returns", "HTML" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L66-L90
aymerick/douceur
inliner/inliner.go
parseHTML
func (inliner *Inliner) parseHTML() error { doc, err := goquery.NewDocumentFromReader(strings.NewReader(inliner.html)) if err != nil { return err } inliner.doc = doc return nil }
go
func (inliner *Inliner) parseHTML() error { doc, err := goquery.NewDocumentFromReader(strings.NewReader(inliner.html)) if err != nil { return err } inliner.doc = doc return nil }
[ "func", "(", "inliner", "*", "Inliner", ")", "parseHTML", "(", ")", "error", "{", "doc", ",", "err", ":=", "goquery", ".", "NewDocumentFromReader", "(", "strings", ".", "NewReader", "(", "inliner", ".", "html", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "inliner", ".", "doc", "=", "doc", "\n\n", "return", "nil", "\n", "}" ]
// Parses raw html
[ "Parses", "raw", "html" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L93-L102
aymerick/douceur
inliner/inliner.go
parseStylesheets
func (inliner *Inliner) parseStylesheets() error { var result error inliner.doc.Find("style").EachWithBreak(func(i int, s *goquery.Selection) bool { stylesheet, err := parser.Parse(s.Text()) if err != nil { result = err return false } inliner.stylesheets = append(inliner.stylesheets, stylesheet) // removes parsed stylesheet s.Remove() return true }) return result }
go
func (inliner *Inliner) parseStylesheets() error { var result error inliner.doc.Find("style").EachWithBreak(func(i int, s *goquery.Selection) bool { stylesheet, err := parser.Parse(s.Text()) if err != nil { result = err return false } inliner.stylesheets = append(inliner.stylesheets, stylesheet) // removes parsed stylesheet s.Remove() return true }) return result }
[ "func", "(", "inliner", "*", "Inliner", ")", "parseStylesheets", "(", ")", "error", "{", "var", "result", "error", "\n\n", "inliner", ".", "doc", ".", "Find", "(", "\"", "\"", ")", ".", "EachWithBreak", "(", "func", "(", "i", "int", ",", "s", "*", "goquery", ".", "Selection", ")", "bool", "{", "stylesheet", ",", "err", ":=", "parser", ".", "Parse", "(", "s", ".", "Text", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", "=", "err", "\n", "return", "false", "\n", "}", "\n\n", "inliner", ".", "stylesheets", "=", "append", "(", "inliner", ".", "stylesheets", ",", "stylesheet", ")", "\n\n", "// removes parsed stylesheet", "s", ".", "Remove", "(", ")", "\n\n", "return", "true", "\n", "}", ")", "\n\n", "return", "result", "\n", "}" ]
// Parses and removes stylesheets from HTML document
[ "Parses", "and", "removes", "stylesheets", "from", "HTML", "document" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L105-L124
aymerick/douceur
inliner/inliner.go
collectElementsAndRules
func (inliner *Inliner) collectElementsAndRules() { for _, stylesheet := range inliner.stylesheets { for _, rule := range stylesheet.Rules { if rule.Kind == css.QualifiedRule { // Let's go! inliner.handleQualifiedRule(rule) } else { // Keep it 'as is' inliner.rawRules = append(inliner.rawRules, rule) } } } }
go
func (inliner *Inliner) collectElementsAndRules() { for _, stylesheet := range inliner.stylesheets { for _, rule := range stylesheet.Rules { if rule.Kind == css.QualifiedRule { // Let's go! inliner.handleQualifiedRule(rule) } else { // Keep it 'as is' inliner.rawRules = append(inliner.rawRules, rule) } } } }
[ "func", "(", "inliner", "*", "Inliner", ")", "collectElementsAndRules", "(", ")", "{", "for", "_", ",", "stylesheet", ":=", "range", "inliner", ".", "stylesheets", "{", "for", "_", ",", "rule", ":=", "range", "stylesheet", ".", "Rules", "{", "if", "rule", ".", "Kind", "==", "css", ".", "QualifiedRule", "{", "// Let's go!", "inliner", ".", "handleQualifiedRule", "(", "rule", ")", "\n", "}", "else", "{", "// Keep it 'as is'", "inliner", ".", "rawRules", "=", "append", "(", "inliner", ".", "rawRules", ",", "rule", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Collects HTML elements matching parsed stylesheets, and thus collect used style rules
[ "Collects", "HTML", "elements", "matching", "parsed", "stylesheets", "and", "thus", "collect", "used", "style", "rules" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L127-L139
aymerick/douceur
inliner/inliner.go
handleQualifiedRule
func (inliner *Inliner) handleQualifiedRule(rule *css.Rule) { for _, selector := range rule.Selectors { if Inlinable(selector) { inliner.doc.Find(selector).Each(func(i int, s *goquery.Selection) { // get marker eltMarker, exists := s.Attr(eltMarkerAttr) if !exists { // mark element eltMarker = strconv.Itoa(inliner.eltMarker) s.SetAttr(eltMarkerAttr, eltMarker) inliner.eltMarker++ // add new element inliner.elements[eltMarker] = NewElement(s) } // add style rule for element inliner.elements[eltMarker].addStyleRule(NewStyleRule(selector, rule.Declarations)) }) } else { // Keep it 'as is' inliner.rawRules = append(inliner.rawRules, NewStyleRule(selector, rule.Declarations)) } } }
go
func (inliner *Inliner) handleQualifiedRule(rule *css.Rule) { for _, selector := range rule.Selectors { if Inlinable(selector) { inliner.doc.Find(selector).Each(func(i int, s *goquery.Selection) { // get marker eltMarker, exists := s.Attr(eltMarkerAttr) if !exists { // mark element eltMarker = strconv.Itoa(inliner.eltMarker) s.SetAttr(eltMarkerAttr, eltMarker) inliner.eltMarker++ // add new element inliner.elements[eltMarker] = NewElement(s) } // add style rule for element inliner.elements[eltMarker].addStyleRule(NewStyleRule(selector, rule.Declarations)) }) } else { // Keep it 'as is' inliner.rawRules = append(inliner.rawRules, NewStyleRule(selector, rule.Declarations)) } } }
[ "func", "(", "inliner", "*", "Inliner", ")", "handleQualifiedRule", "(", "rule", "*", "css", ".", "Rule", ")", "{", "for", "_", ",", "selector", ":=", "range", "rule", ".", "Selectors", "{", "if", "Inlinable", "(", "selector", ")", "{", "inliner", ".", "doc", ".", "Find", "(", "selector", ")", ".", "Each", "(", "func", "(", "i", "int", ",", "s", "*", "goquery", ".", "Selection", ")", "{", "// get marker", "eltMarker", ",", "exists", ":=", "s", ".", "Attr", "(", "eltMarkerAttr", ")", "\n", "if", "!", "exists", "{", "// mark element", "eltMarker", "=", "strconv", ".", "Itoa", "(", "inliner", ".", "eltMarker", ")", "\n", "s", ".", "SetAttr", "(", "eltMarkerAttr", ",", "eltMarker", ")", "\n", "inliner", ".", "eltMarker", "++", "\n\n", "// add new element", "inliner", ".", "elements", "[", "eltMarker", "]", "=", "NewElement", "(", "s", ")", "\n", "}", "\n\n", "// add style rule for element", "inliner", ".", "elements", "[", "eltMarker", "]", ".", "addStyleRule", "(", "NewStyleRule", "(", "selector", ",", "rule", ".", "Declarations", ")", ")", "\n", "}", ")", "\n", "}", "else", "{", "// Keep it 'as is'", "inliner", ".", "rawRules", "=", "append", "(", "inliner", ".", "rawRules", ",", "NewStyleRule", "(", "selector", ",", "rule", ".", "Declarations", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Handles parsed qualified rule
[ "Handles", "parsed", "qualified", "rule" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L142-L166
aymerick/douceur
inliner/inliner.go
inlineStyleRules
func (inliner *Inliner) inlineStyleRules() error { for _, element := range inliner.elements { // remove marker element.elt.RemoveAttr(eltMarkerAttr) // inline element err := element.inline() if err != nil { return err } } return nil }
go
func (inliner *Inliner) inlineStyleRules() error { for _, element := range inliner.elements { // remove marker element.elt.RemoveAttr(eltMarkerAttr) // inline element err := element.inline() if err != nil { return err } } return nil }
[ "func", "(", "inliner", "*", "Inliner", ")", "inlineStyleRules", "(", ")", "error", "{", "for", "_", ",", "element", ":=", "range", "inliner", ".", "elements", "{", "// remove marker", "element", ".", "elt", ".", "RemoveAttr", "(", "eltMarkerAttr", ")", "\n\n", "// inline element", "err", ":=", "element", ".", "inline", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Inline style rules in HTML document
[ "Inline", "style", "rules", "in", "HTML", "document" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L169-L182
aymerick/douceur
inliner/inliner.go
computeRawCSS
func (inliner *Inliner) computeRawCSS() string { result := "" for _, rawRule := range inliner.rawRules { result += rawRule.String() result += "\n" } return result }
go
func (inliner *Inliner) computeRawCSS() string { result := "" for _, rawRule := range inliner.rawRules { result += rawRule.String() result += "\n" } return result }
[ "func", "(", "inliner", "*", "Inliner", ")", "computeRawCSS", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "for", "_", ",", "rawRule", ":=", "range", "inliner", ".", "rawRules", "{", "result", "+=", "rawRule", ".", "String", "(", ")", "\n", "result", "+=", "\"", "\\n", "\"", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Computes raw CSS rules
[ "Computes", "raw", "CSS", "rules" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L185-L194
aymerick/douceur
inliner/inliner.go
insertRawStylesheet
func (inliner *Inliner) insertRawStylesheet() { rawCSS := inliner.computeRawCSS() if rawCSS != "" { // create <style> element cssNode := &html.Node{ Type: html.TextNode, Data: "\n" + rawCSS, } styleNode := &html.Node{ Type: html.ElementNode, Data: "style", Attr: []html.Attribute{{Key: "type", Val: "text/css"}}, } styleNode.AppendChild(cssNode) // append to <head> element headNode := inliner.doc.Find("head") if headNode == nil { // @todo Create head node ! panic("NOT IMPLEMENTED: create missing <head> node") } headNode.AppendNodes(styleNode) } }
go
func (inliner *Inliner) insertRawStylesheet() { rawCSS := inliner.computeRawCSS() if rawCSS != "" { // create <style> element cssNode := &html.Node{ Type: html.TextNode, Data: "\n" + rawCSS, } styleNode := &html.Node{ Type: html.ElementNode, Data: "style", Attr: []html.Attribute{{Key: "type", Val: "text/css"}}, } styleNode.AppendChild(cssNode) // append to <head> element headNode := inliner.doc.Find("head") if headNode == nil { // @todo Create head node ! panic("NOT IMPLEMENTED: create missing <head> node") } headNode.AppendNodes(styleNode) } }
[ "func", "(", "inliner", "*", "Inliner", ")", "insertRawStylesheet", "(", ")", "{", "rawCSS", ":=", "inliner", ".", "computeRawCSS", "(", ")", "\n", "if", "rawCSS", "!=", "\"", "\"", "{", "// create <style> element", "cssNode", ":=", "&", "html", ".", "Node", "{", "Type", ":", "html", ".", "TextNode", ",", "Data", ":", "\"", "\\n", "\"", "+", "rawCSS", ",", "}", "\n\n", "styleNode", ":=", "&", "html", ".", "Node", "{", "Type", ":", "html", ".", "ElementNode", ",", "Data", ":", "\"", "\"", ",", "Attr", ":", "[", "]", "html", ".", "Attribute", "{", "{", "Key", ":", "\"", "\"", ",", "Val", ":", "\"", "\"", "}", "}", ",", "}", "\n\n", "styleNode", ".", "AppendChild", "(", "cssNode", ")", "\n\n", "// append to <head> element", "headNode", ":=", "inliner", ".", "doc", ".", "Find", "(", "\"", "\"", ")", "\n", "if", "headNode", "==", "nil", "{", "// @todo Create head node !", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "headNode", ".", "AppendNodes", "(", "styleNode", ")", "\n", "}", "\n", "}" ]
// Insert raw CSS rules into HTML document
[ "Insert", "raw", "CSS", "rules", "into", "HTML", "document" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L197-L223
aymerick/douceur
inliner/inliner.go
Inlinable
func Inlinable(selector string) bool { if strings.Contains(selector, "::") { return false } for _, badSel := range unsupportedSelectors { if strings.Contains(selector, badSel) { return false } } return true }
go
func Inlinable(selector string) bool { if strings.Contains(selector, "::") { return false } for _, badSel := range unsupportedSelectors { if strings.Contains(selector, badSel) { return false } } return true }
[ "func", "Inlinable", "(", "selector", "string", ")", "bool", "{", "if", "strings", ".", "Contains", "(", "selector", ",", "\"", "\"", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "badSel", ":=", "range", "unsupportedSelectors", "{", "if", "strings", ".", "Contains", "(", "selector", ",", "badSel", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Inlinable returns true if given selector is inlinable
[ "Inlinable", "returns", "true", "if", "given", "selector", "is", "inlinable" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L231-L243
aymerick/douceur
inliner/style_declaration.go
NewStyleDeclaration
func NewStyleDeclaration(styleRule *StyleRule, declaration *css.Declaration) *StyleDeclaration { return &StyleDeclaration{ StyleRule: styleRule, Declaration: declaration, } }
go
func NewStyleDeclaration(styleRule *StyleRule, declaration *css.Declaration) *StyleDeclaration { return &StyleDeclaration{ StyleRule: styleRule, Declaration: declaration, } }
[ "func", "NewStyleDeclaration", "(", "styleRule", "*", "StyleRule", ",", "declaration", "*", "css", ".", "Declaration", ")", "*", "StyleDeclaration", "{", "return", "&", "StyleDeclaration", "{", "StyleRule", ":", "styleRule", ",", "Declaration", ":", "declaration", ",", "}", "\n", "}" ]
// NewStyleDeclaration instanciates a new StyleDeclaration
[ "NewStyleDeclaration", "instanciates", "a", "new", "StyleDeclaration" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/style_declaration.go#L12-L17
aymerick/douceur
inliner/style_declaration.go
Specificity
func (styleDecl *StyleDeclaration) Specificity() int { if styleDecl.Declaration.Important { return 10000 } return styleDecl.StyleRule.Specificity }
go
func (styleDecl *StyleDeclaration) Specificity() int { if styleDecl.Declaration.Important { return 10000 } return styleDecl.StyleRule.Specificity }
[ "func", "(", "styleDecl", "*", "StyleDeclaration", ")", "Specificity", "(", ")", "int", "{", "if", "styleDecl", ".", "Declaration", ".", "Important", "{", "return", "10000", "\n", "}", "\n\n", "return", "styleDecl", ".", "StyleRule", ".", "Specificity", "\n", "}" ]
// Specificity computes style declaration specificity
[ "Specificity", "computes", "style", "declaration", "specificity" ]
train
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/style_declaration.go#L20-L26
oleiade/reflections
reflections.go
GetField
func GetField(obj interface{}, name string) (interface{}, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return nil, errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) field := objValue.FieldByName(name) if !field.IsValid() { return nil, fmt.Errorf("No such field: %s in obj", name) } return field.Interface(), nil }
go
func GetField(obj interface{}, name string) (interface{}, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return nil, errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) field := objValue.FieldByName(name) if !field.IsValid() { return nil, fmt.Errorf("No such field: %s in obj", name) } return field.Interface(), nil }
[ "func", "GetField", "(", "obj", "interface", "{", "}", ",", "name", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "!", "hasValidType", "(", "obj", ",", "[", "]", "reflect", ".", "Kind", "{", "reflect", ".", "Struct", ",", "reflect", ".", "Ptr", "}", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "objValue", ":=", "reflectValue", "(", "obj", ")", "\n", "field", ":=", "objValue", ".", "FieldByName", "(", "name", ")", "\n", "if", "!", "field", ".", "IsValid", "(", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "return", "field", ".", "Interface", "(", ")", ",", "nil", "\n", "}" ]
// GetField returns the value of the provided obj field. obj can whether // be a structure or pointer to structure.
[ "GetField", "returns", "the", "value", "of", "the", "provided", "obj", "field", ".", "obj", "can", "whether", "be", "a", "structure", "or", "pointer", "to", "structure", "." ]
train
https://github.com/oleiade/reflections/blob/0e86b3c98b2ff33e30c85cfe97d9a63d439fe7eb/reflections.go#L24-L36
oleiade/reflections
reflections.go
GetFieldKind
func GetFieldKind(obj interface{}, name string) (reflect.Kind, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return reflect.Invalid, errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) field := objValue.FieldByName(name) if !field.IsValid() { return reflect.Invalid, fmt.Errorf("No such field: %s in obj", name) } return field.Type().Kind(), nil }
go
func GetFieldKind(obj interface{}, name string) (reflect.Kind, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return reflect.Invalid, errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) field := objValue.FieldByName(name) if !field.IsValid() { return reflect.Invalid, fmt.Errorf("No such field: %s in obj", name) } return field.Type().Kind(), nil }
[ "func", "GetFieldKind", "(", "obj", "interface", "{", "}", ",", "name", "string", ")", "(", "reflect", ".", "Kind", ",", "error", ")", "{", "if", "!", "hasValidType", "(", "obj", ",", "[", "]", "reflect", ".", "Kind", "{", "reflect", ".", "Struct", ",", "reflect", ".", "Ptr", "}", ")", "{", "return", "reflect", ".", "Invalid", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "objValue", ":=", "reflectValue", "(", "obj", ")", "\n", "field", ":=", "objValue", ".", "FieldByName", "(", "name", ")", "\n\n", "if", "!", "field", ".", "IsValid", "(", ")", "{", "return", "reflect", ".", "Invalid", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "return", "field", ".", "Type", "(", ")", ".", "Kind", "(", ")", ",", "nil", "\n", "}" ]
// GetFieldKind returns the kind of the provided obj field. obj can whether // be a structure or pointer to structure.
[ "GetFieldKind", "returns", "the", "kind", "of", "the", "provided", "obj", "field", ".", "obj", "can", "whether", "be", "a", "structure", "or", "pointer", "to", "structure", "." ]
train
https://github.com/oleiade/reflections/blob/0e86b3c98b2ff33e30c85cfe97d9a63d439fe7eb/reflections.go#L40-L53
oleiade/reflections
reflections.go
GetFieldTag
func GetFieldTag(obj interface{}, fieldName, tagKey string) (string, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return "", errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) objType := objValue.Type() field, ok := objType.FieldByName(fieldName) if !ok { return "", fmt.Errorf("No such field: %s in obj", fieldName) } if !isExportableField(field) { return "", errors.New("Cannot GetFieldTag on a non-exported struct field") } return field.Tag.Get(tagKey), nil }
go
func GetFieldTag(obj interface{}, fieldName, tagKey string) (string, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return "", errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) objType := objValue.Type() field, ok := objType.FieldByName(fieldName) if !ok { return "", fmt.Errorf("No such field: %s in obj", fieldName) } if !isExportableField(field) { return "", errors.New("Cannot GetFieldTag on a non-exported struct field") } return field.Tag.Get(tagKey), nil }
[ "func", "GetFieldTag", "(", "obj", "interface", "{", "}", ",", "fieldName", ",", "tagKey", "string", ")", "(", "string", ",", "error", ")", "{", "if", "!", "hasValidType", "(", "obj", ",", "[", "]", "reflect", ".", "Kind", "{", "reflect", ".", "Struct", ",", "reflect", ".", "Ptr", "}", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "objValue", ":=", "reflectValue", "(", "obj", ")", "\n", "objType", ":=", "objValue", ".", "Type", "(", ")", "\n\n", "field", ",", "ok", ":=", "objType", ".", "FieldByName", "(", "fieldName", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fieldName", ")", "\n", "}", "\n\n", "if", "!", "isExportableField", "(", "field", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "field", ".", "Tag", ".", "Get", "(", "tagKey", ")", ",", "nil", "\n", "}" ]
// GetFieldTag returns the provided obj field tag value. obj can whether // be a structure or pointer to structure.
[ "GetFieldTag", "returns", "the", "provided", "obj", "field", "tag", "value", ".", "obj", "can", "whether", "be", "a", "structure", "or", "pointer", "to", "structure", "." ]
train
https://github.com/oleiade/reflections/blob/0e86b3c98b2ff33e30c85cfe97d9a63d439fe7eb/reflections.go#L74-L92
oleiade/reflections
reflections.go
HasField
func HasField(obj interface{}, name string) (bool, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return false, errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) objType := objValue.Type() field, ok := objType.FieldByName(name) if !ok || !isExportableField(field) { return false, nil } return true, nil }
go
func HasField(obj interface{}, name string) (bool, error) { if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { return false, errors.New("Cannot use GetField on a non-struct interface") } objValue := reflectValue(obj) objType := objValue.Type() field, ok := objType.FieldByName(name) if !ok || !isExportableField(field) { return false, nil } return true, nil }
[ "func", "HasField", "(", "obj", "interface", "{", "}", ",", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "!", "hasValidType", "(", "obj", ",", "[", "]", "reflect", ".", "Kind", "{", "reflect", ".", "Struct", ",", "reflect", ".", "Ptr", "}", ")", "{", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "objValue", ":=", "reflectValue", "(", "obj", ")", "\n", "objType", ":=", "objValue", ".", "Type", "(", ")", "\n", "field", ",", "ok", ":=", "objType", ".", "FieldByName", "(", "name", ")", "\n", "if", "!", "ok", "||", "!", "isExportableField", "(", "field", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// HasField checks if the provided field name is part of a struct. obj can whether // be a structure or pointer to structure.
[ "HasField", "checks", "if", "the", "provided", "field", "name", "is", "part", "of", "a", "struct", ".", "obj", "can", "whether", "be", "a", "structure", "or", "pointer", "to", "structure", "." ]
train
https://github.com/oleiade/reflections/blob/0e86b3c98b2ff33e30c85cfe97d9a63d439fe7eb/reflections.go#L124-L137
oleiade/reflections
reflections.go
Tags
func Tags(obj interface{}, key string) (map[string]string, error) { return tags(obj, key, false) }
go
func Tags(obj interface{}, key string) (map[string]string, error) { return tags(obj, key, false) }
[ "func", "Tags", "(", "obj", "interface", "{", "}", ",", "key", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "tags", "(", "obj", ",", "key", ",", "false", ")", "\n", "}" ]
// Tags lists the struct tag fields. obj can whether // be a structure or pointer to structure.
[ "Tags", "lists", "the", "struct", "tag", "fields", ".", "obj", "can", "whether", "be", "a", "structure", "or", "pointer", "to", "structure", "." ]
train
https://github.com/oleiade/reflections/blob/0e86b3c98b2ff33e30c85cfe97d9a63d439fe7eb/reflections.go#L226-L228
oleiade/reflections
reflections.go
TagsDeep
func TagsDeep(obj interface{}, key string) (map[string]string, error) { return tags(obj, key, true) }
go
func TagsDeep(obj interface{}, key string) (map[string]string, error) { return tags(obj, key, true) }
[ "func", "TagsDeep", "(", "obj", "interface", "{", "}", ",", "key", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "tags", "(", "obj", ",", "key", ",", "true", ")", "\n", "}" ]
// FieldsDeep returns "flattened" tags (fields from anonymous // inner structs are treated as normal fields)
[ "FieldsDeep", "returns", "flattened", "tags", "(", "fields", "from", "anonymous", "inner", "structs", "are", "treated", "as", "normal", "fields", ")" ]
train
https://github.com/oleiade/reflections/blob/0e86b3c98b2ff33e30c85cfe97d9a63d439fe7eb/reflections.go#L232-L234
timshannon/bolthold
index.go
indexAdd
func indexAdd(storer Storer, tx *bolt.Tx, key []byte, data interface{}) error { indexes := storer.Indexes() for name, index := range indexes { err := indexUpdate(storer.Type(), name, index, tx, key, data, false) if err != nil { return err } } return nil }
go
func indexAdd(storer Storer, tx *bolt.Tx, key []byte, data interface{}) error { indexes := storer.Indexes() for name, index := range indexes { err := indexUpdate(storer.Type(), name, index, tx, key, data, false) if err != nil { return err } } return nil }
[ "func", "indexAdd", "(", "storer", "Storer", ",", "tx", "*", "bolt", ".", "Tx", ",", "key", "[", "]", "byte", ",", "data", "interface", "{", "}", ")", "error", "{", "indexes", ":=", "storer", ".", "Indexes", "(", ")", "\n", "for", "name", ",", "index", ":=", "range", "indexes", "{", "err", ":=", "indexUpdate", "(", "storer", ".", "Type", "(", ")", ",", "name", ",", "index", ",", "tx", ",", "key", ",", "data", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// adds an item to the index
[ "adds", "an", "item", "to", "the", "index" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/index.go#L27-L37
timshannon/bolthold
index.go
indexDelete
func indexDelete(storer Storer, tx *bolt.Tx, key []byte, originalData interface{}) error { indexes := storer.Indexes() for name, index := range indexes { err := indexUpdate(storer.Type(), name, index, tx, key, originalData, true) if err != nil { return err } } return nil }
go
func indexDelete(storer Storer, tx *bolt.Tx, key []byte, originalData interface{}) error { indexes := storer.Indexes() for name, index := range indexes { err := indexUpdate(storer.Type(), name, index, tx, key, originalData, true) if err != nil { return err } } return nil }
[ "func", "indexDelete", "(", "storer", "Storer", ",", "tx", "*", "bolt", ".", "Tx", ",", "key", "[", "]", "byte", ",", "originalData", "interface", "{", "}", ")", "error", "{", "indexes", ":=", "storer", ".", "Indexes", "(", ")", "\n\n", "for", "name", ",", "index", ":=", "range", "indexes", "{", "err", ":=", "indexUpdate", "(", "storer", ".", "Type", "(", ")", ",", "name", ",", "index", ",", "tx", ",", "key", ",", "originalData", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// removes an item from the index // be sure to pass the data from the old record, not the new one
[ "removes", "an", "item", "from", "the", "index", "be", "sure", "to", "pass", "the", "data", "from", "the", "old", "record", "not", "the", "new", "one" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/index.go#L41-L52
timshannon/bolthold
index.go
indexUpdate
func indexUpdate(typeName, indexName string, index Index, tx *bolt.Tx, key []byte, value interface{}, delete bool) error { indexKey, err := index(indexName, value) if indexKey == nil { return nil } indexValue := make(keyList, 0) if err != nil { return err } b, err := tx.CreateBucketIfNotExists(indexBucketName(typeName, indexName)) if err != nil { return err } iVal := b.Get(indexKey) if iVal != nil { err = decode(iVal, &indexValue) if err != nil { return err } } if delete { indexValue.remove(key) } else { indexValue.add(key) } if len(indexValue) == 0 { return b.Delete(indexKey) } iVal, err = encode(indexValue) if err != nil { return err } return b.Put(indexKey, iVal) }
go
func indexUpdate(typeName, indexName string, index Index, tx *bolt.Tx, key []byte, value interface{}, delete bool) error { indexKey, err := index(indexName, value) if indexKey == nil { return nil } indexValue := make(keyList, 0) if err != nil { return err } b, err := tx.CreateBucketIfNotExists(indexBucketName(typeName, indexName)) if err != nil { return err } iVal := b.Get(indexKey) if iVal != nil { err = decode(iVal, &indexValue) if err != nil { return err } } if delete { indexValue.remove(key) } else { indexValue.add(key) } if len(indexValue) == 0 { return b.Delete(indexKey) } iVal, err = encode(indexValue) if err != nil { return err } return b.Put(indexKey, iVal) }
[ "func", "indexUpdate", "(", "typeName", ",", "indexName", "string", ",", "index", "Index", ",", "tx", "*", "bolt", ".", "Tx", ",", "key", "[", "]", "byte", ",", "value", "interface", "{", "}", ",", "delete", "bool", ")", "error", "{", "indexKey", ",", "err", ":=", "index", "(", "indexName", ",", "value", ")", "\n", "if", "indexKey", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "indexValue", ":=", "make", "(", "keyList", ",", "0", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "b", ",", "err", ":=", "tx", ".", "CreateBucketIfNotExists", "(", "indexBucketName", "(", "typeName", ",", "indexName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "iVal", ":=", "b", ".", "Get", "(", "indexKey", ")", "\n", "if", "iVal", "!=", "nil", "{", "err", "=", "decode", "(", "iVal", ",", "&", "indexValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "delete", "{", "indexValue", ".", "remove", "(", "key", ")", "\n", "}", "else", "{", "indexValue", ".", "add", "(", "key", ")", "\n", "}", "\n\n", "if", "len", "(", "indexValue", ")", "==", "0", "{", "return", "b", ".", "Delete", "(", "indexKey", ")", "\n", "}", "\n\n", "iVal", ",", "err", "=", "encode", "(", "indexValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "b", ".", "Put", "(", "indexKey", ",", "iVal", ")", "\n", "}" ]
// adds or removes a specific index on an item
[ "adds", "or", "removes", "a", "specific", "index", "on", "an", "item" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/index.go#L55-L96
timshannon/bolthold
index.go
IndexExists
func (s *Store) IndexExists(tx *bolt.Tx, typeName, indexName string) bool { return (tx.Bucket(indexBucketName(typeName, indexName)) != nil) }
go
func (s *Store) IndexExists(tx *bolt.Tx, typeName, indexName string) bool { return (tx.Bucket(indexBucketName(typeName, indexName)) != nil) }
[ "func", "(", "s", "*", "Store", ")", "IndexExists", "(", "tx", "*", "bolt", ".", "Tx", ",", "typeName", ",", "indexName", "string", ")", "bool", "{", "return", "(", "tx", ".", "Bucket", "(", "indexBucketName", "(", "typeName", ",", "indexName", ")", ")", "!=", "nil", ")", "\n", "}" ]
// IndexExists tests if an index exists for the passed in field name
[ "IndexExists", "tests", "if", "an", "index", "exists", "for", "the", "passed", "in", "field", "name" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/index.go#L99-L101
timshannon/bolthold
index.go
seekCursor
func seekCursor(cursor *bolt.Cursor, criteria []*Criterion) (key, value []byte) { if len(criteria) != 1 { return cursor.First() } if criteria[0].operator == gt || criteria[0].operator == ge || criteria[0].operator == eq { seek, err := encode(criteria[0].value) if err != nil { return cursor.First() } return cursor.Seek(seek) } return cursor.First() }
go
func seekCursor(cursor *bolt.Cursor, criteria []*Criterion) (key, value []byte) { if len(criteria) != 1 { return cursor.First() } if criteria[0].operator == gt || criteria[0].operator == ge || criteria[0].operator == eq { seek, err := encode(criteria[0].value) if err != nil { return cursor.First() } return cursor.Seek(seek) } return cursor.First() }
[ "func", "seekCursor", "(", "cursor", "*", "bolt", ".", "Cursor", ",", "criteria", "[", "]", "*", "Criterion", ")", "(", "key", ",", "value", "[", "]", "byte", ")", "{", "if", "len", "(", "criteria", ")", "!=", "1", "{", "return", "cursor", ".", "First", "(", ")", "\n", "}", "\n\n", "if", "criteria", "[", "0", "]", ".", "operator", "==", "gt", "||", "criteria", "[", "0", "]", ".", "operator", "==", "ge", "||", "criteria", "[", "0", "]", ".", "operator", "==", "eq", "{", "seek", ",", "err", ":=", "encode", "(", "criteria", "[", "0", "]", ".", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cursor", ".", "First", "(", ")", "\n", "}", "\n\n", "return", "cursor", ".", "Seek", "(", "seek", ")", "\n", "}", "\n\n", "return", "cursor", ".", "First", "(", ")", "\n", "}" ]
// seekCursor preps usually will simply set the cursor to the first k/v and return it, // however if there is only one critrion and it is either > = or >= then we can seek to the value and // save reads
[ "seekCursor", "preps", "usually", "will", "simply", "set", "the", "cursor", "to", "the", "first", "k", "/", "v", "and", "return", "it", "however", "if", "there", "is", "only", "one", "critrion", "and", "it", "is", "either", ">", "=", "or", ">", "=", "then", "we", "can", "seek", "to", "the", "value", "and", "save", "reads" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/index.go#L290-L305
timshannon/bolthold
index.go
Next
func (i *iterator) Next() (key []byte, value []byte) { if i.err != nil { return nil, nil } if i.dataBucket == nil { return nil, nil } if i.nextKeys == nil { return nil, nil } if len(i.keyCache) == 0 { newKeys, err := i.nextKeys(i.prepCursor, i.indexCursor) i.prepCursor = false if err != nil { i.err = err return nil, nil } if len(newKeys) == 0 { return nil, nil } i.keyCache = append(i.keyCache, newKeys...) } nextKey := i.keyCache[0] i.keyCache = i.keyCache[1:] val := i.dataBucket.Get(nextKey) return nextKey, val }
go
func (i *iterator) Next() (key []byte, value []byte) { if i.err != nil { return nil, nil } if i.dataBucket == nil { return nil, nil } if i.nextKeys == nil { return nil, nil } if len(i.keyCache) == 0 { newKeys, err := i.nextKeys(i.prepCursor, i.indexCursor) i.prepCursor = false if err != nil { i.err = err return nil, nil } if len(newKeys) == 0 { return nil, nil } i.keyCache = append(i.keyCache, newKeys...) } nextKey := i.keyCache[0] i.keyCache = i.keyCache[1:] val := i.dataBucket.Get(nextKey) return nextKey, val }
[ "func", "(", "i", "*", "iterator", ")", "Next", "(", ")", "(", "key", "[", "]", "byte", ",", "value", "[", "]", "byte", ")", "{", "if", "i", ".", "err", "!=", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "i", ".", "dataBucket", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "i", ".", "nextKeys", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "len", "(", "i", ".", "keyCache", ")", "==", "0", "{", "newKeys", ",", "err", ":=", "i", ".", "nextKeys", "(", "i", ".", "prepCursor", ",", "i", ".", "indexCursor", ")", "\n", "i", ".", "prepCursor", "=", "false", "\n", "if", "err", "!=", "nil", "{", "i", ".", "err", "=", "err", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "len", "(", "newKeys", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "i", ".", "keyCache", "=", "append", "(", "i", ".", "keyCache", ",", "newKeys", "...", ")", "\n", "}", "\n\n", "nextKey", ":=", "i", ".", "keyCache", "[", "0", "]", "\n", "i", ".", "keyCache", "=", "i", ".", "keyCache", "[", "1", ":", "]", "\n\n", "val", ":=", "i", ".", "dataBucket", ".", "Get", "(", "nextKey", ")", "\n\n", "return", "nextKey", ",", "val", "\n", "}" ]
// Next returns the next key value that matches the iterators criteria // If no more kv's are available the return nil, if there is an error, they return nil // and iterator.Error() will return the error
[ "Next", "returns", "the", "next", "key", "value", "that", "matches", "the", "iterators", "criteria", "If", "no", "more", "kv", "s", "are", "available", "the", "return", "nil", "if", "there", "is", "an", "error", "they", "return", "nil", "and", "iterator", ".", "Error", "()", "will", "return", "the", "error" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/index.go#L310-L344
timshannon/bolthold
delete.go
Delete
func (s *Store) Delete(key, dataType interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxDelete(tx, key, dataType) }) }
go
func (s *Store) Delete(key, dataType interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxDelete(tx, key, dataType) }) }
[ "func", "(", "s", "*", "Store", ")", "Delete", "(", "key", ",", "dataType", "interface", "{", "}", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxDelete", "(", "tx", ",", "key", ",", "dataType", ")", "\n", "}", ")", "\n", "}" ]
// Delete deletes a record from the bolthold, datatype just needs to be an example of the type stored so that // the proper bucket and indexes are updated
[ "Delete", "deletes", "a", "record", "from", "the", "bolthold", "datatype", "just", "needs", "to", "be", "an", "example", "of", "the", "type", "stored", "so", "that", "the", "proper", "bucket", "and", "indexes", "are", "updated" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/delete.go#L15-L19
timshannon/bolthold
delete.go
TxDelete
func (s *Store) TxDelete(tx *bolt.Tx, key, dataType interface{}) error { if !tx.Writable() { return bolt.ErrTxNotWritable } storer := newStorer(dataType) gk, err := encode(key) if err != nil { return err } b := tx.Bucket([]byte(storer.Type())) if b == nil { return ErrNotFound } value := reflect.New(reflect.TypeOf(dataType)).Interface() bVal := b.Get(gk) err = decode(bVal, value) if err != nil { return err } // delete data err = b.Delete(gk) if err != nil { return err } // remove any indexes return indexDelete(storer, tx, gk, value) }
go
func (s *Store) TxDelete(tx *bolt.Tx, key, dataType interface{}) error { if !tx.Writable() { return bolt.ErrTxNotWritable } storer := newStorer(dataType) gk, err := encode(key) if err != nil { return err } b := tx.Bucket([]byte(storer.Type())) if b == nil { return ErrNotFound } value := reflect.New(reflect.TypeOf(dataType)).Interface() bVal := b.Get(gk) err = decode(bVal, value) if err != nil { return err } // delete data err = b.Delete(gk) if err != nil { return err } // remove any indexes return indexDelete(storer, tx, gk, value) }
[ "func", "(", "s", "*", "Store", ")", "TxDelete", "(", "tx", "*", "bolt", ".", "Tx", ",", "key", ",", "dataType", "interface", "{", "}", ")", "error", "{", "if", "!", "tx", ".", "Writable", "(", ")", "{", "return", "bolt", ".", "ErrTxNotWritable", "\n", "}", "\n\n", "storer", ":=", "newStorer", "(", "dataType", ")", "\n", "gk", ",", "err", ":=", "encode", "(", "key", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "b", ":=", "tx", ".", "Bucket", "(", "[", "]", "byte", "(", "storer", ".", "Type", "(", ")", ")", ")", "\n", "if", "b", "==", "nil", "{", "return", "ErrNotFound", "\n", "}", "\n\n", "value", ":=", "reflect", ".", "New", "(", "reflect", ".", "TypeOf", "(", "dataType", ")", ")", ".", "Interface", "(", ")", "\n\n", "bVal", ":=", "b", ".", "Get", "(", "gk", ")", "\n\n", "err", "=", "decode", "(", "bVal", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// delete data", "err", "=", "b", ".", "Delete", "(", "gk", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// remove any indexes", "return", "indexDelete", "(", "storer", ",", "tx", ",", "gk", ",", "value", ")", "\n", "}" ]
// TxDelete is the same as Delete except it allows you specify your own transaction
[ "TxDelete", "is", "the", "same", "as", "Delete", "except", "it", "allows", "you", "specify", "your", "own", "transaction" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/delete.go#L22-L57
timshannon/bolthold
delete.go
DeleteMatching
func (s *Store) DeleteMatching(dataType interface{}, query *Query) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxDeleteMatching(tx, dataType, query) }) }
go
func (s *Store) DeleteMatching(dataType interface{}, query *Query) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxDeleteMatching(tx, dataType, query) }) }
[ "func", "(", "s", "*", "Store", ")", "DeleteMatching", "(", "dataType", "interface", "{", "}", ",", "query", "*", "Query", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxDeleteMatching", "(", "tx", ",", "dataType", ",", "query", ")", "\n", "}", ")", "\n", "}" ]
// DeleteMatching deletes all of the records that match the passed in query
[ "DeleteMatching", "deletes", "all", "of", "the", "records", "that", "match", "the", "passed", "in", "query" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/delete.go#L60-L64
timshannon/bolthold
delete.go
TxDeleteMatching
func (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error { return deleteQuery(tx, dataType, query) }
go
func (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error { return deleteQuery(tx, dataType, query) }
[ "func", "(", "s", "*", "Store", ")", "TxDeleteMatching", "(", "tx", "*", "bolt", ".", "Tx", ",", "dataType", "interface", "{", "}", ",", "query", "*", "Query", ")", "error", "{", "return", "deleteQuery", "(", "tx", ",", "dataType", ",", "query", ")", "\n", "}" ]
// TxDeleteMatching does the same as DeleteMatching, but allows you to specify your own transaction
[ "TxDeleteMatching", "does", "the", "same", "as", "DeleteMatching", "but", "allows", "you", "to", "specify", "your", "own", "transaction" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/delete.go#L67-L69
timshannon/bolthold
get.go
Get
func (s *Store) Get(key, result interface{}) error { return s.Bolt().View(func(tx *bolt.Tx) error { return s.TxGet(tx, key, result) }) }
go
func (s *Store) Get(key, result interface{}) error { return s.Bolt().View(func(tx *bolt.Tx) error { return s.TxGet(tx, key, result) }) }
[ "func", "(", "s", "*", "Store", ")", "Get", "(", "key", ",", "result", "interface", "{", "}", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "View", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxGet", "(", "tx", ",", "key", ",", "result", ")", "\n", "}", ")", "\n", "}" ]
// Get retrieves a value from bolthold and puts it into result. Result must be a pointer
[ "Get", "retrieves", "a", "value", "from", "bolthold", "and", "puts", "it", "into", "result", ".", "Result", "must", "be", "a", "pointer" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/get.go#L17-L21
timshannon/bolthold
get.go
TxGet
func (s *Store) TxGet(tx *bolt.Tx, key, result interface{}) error { storer := newStorer(result) gk, err := encode(key) if err != nil { return err } bkt := tx.Bucket([]byte(storer.Type())) if bkt == nil { return ErrNotFound } value := bkt.Get(gk) if value == nil { return ErrNotFound } return decode(value, result) }
go
func (s *Store) TxGet(tx *bolt.Tx, key, result interface{}) error { storer := newStorer(result) gk, err := encode(key) if err != nil { return err } bkt := tx.Bucket([]byte(storer.Type())) if bkt == nil { return ErrNotFound } value := bkt.Get(gk) if value == nil { return ErrNotFound } return decode(value, result) }
[ "func", "(", "s", "*", "Store", ")", "TxGet", "(", "tx", "*", "bolt", ".", "Tx", ",", "key", ",", "result", "interface", "{", "}", ")", "error", "{", "storer", ":=", "newStorer", "(", "result", ")", "\n\n", "gk", ",", "err", ":=", "encode", "(", "key", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bkt", ":=", "tx", ".", "Bucket", "(", "[", "]", "byte", "(", "storer", ".", "Type", "(", ")", ")", ")", "\n", "if", "bkt", "==", "nil", "{", "return", "ErrNotFound", "\n", "}", "\n\n", "value", ":=", "bkt", ".", "Get", "(", "gk", ")", "\n", "if", "value", "==", "nil", "{", "return", "ErrNotFound", "\n", "}", "\n\n", "return", "decode", "(", "value", ",", "result", ")", "\n", "}" ]
// TxGet allows you to pass in your own bolt transaction to retrieve a value from the bolthold and puts it into result
[ "TxGet", "allows", "you", "to", "pass", "in", "your", "own", "bolt", "transaction", "to", "retrieve", "a", "value", "from", "the", "bolthold", "and", "puts", "it", "into", "result" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/get.go#L24-L44
timshannon/bolthold
get.go
Find
func (s *Store) Find(result interface{}, query *Query) error { return s.Bolt().View(func(tx *bolt.Tx) error { return s.TxFind(tx, result, query) }) }
go
func (s *Store) Find(result interface{}, query *Query) error { return s.Bolt().View(func(tx *bolt.Tx) error { return s.TxFind(tx, result, query) }) }
[ "func", "(", "s", "*", "Store", ")", "Find", "(", "result", "interface", "{", "}", ",", "query", "*", "Query", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "View", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxFind", "(", "tx", ",", "result", ",", "query", ")", "\n", "}", ")", "\n", "}" ]
// Find retrieves a set of values from the bolthold that matches the passed in query // result must be a pointer to a slice. // The result of the query will be appended to the passed in result slice, rather than the passed in slice being // emptied.
[ "Find", "retrieves", "a", "set", "of", "values", "from", "the", "bolthold", "that", "matches", "the", "passed", "in", "query", "result", "must", "be", "a", "pointer", "to", "a", "slice", ".", "The", "result", "of", "the", "query", "will", "be", "appended", "to", "the", "passed", "in", "result", "slice", "rather", "than", "the", "passed", "in", "slice", "being", "emptied", "." ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/get.go#L50-L54
timshannon/bolthold
get.go
TxFind
func (s *Store) TxFind(tx *bolt.Tx, result interface{}, query *Query) error { return findQuery(tx, result, query) }
go
func (s *Store) TxFind(tx *bolt.Tx, result interface{}, query *Query) error { return findQuery(tx, result, query) }
[ "func", "(", "s", "*", "Store", ")", "TxFind", "(", "tx", "*", "bolt", ".", "Tx", ",", "result", "interface", "{", "}", ",", "query", "*", "Query", ")", "error", "{", "return", "findQuery", "(", "tx", ",", "result", ",", "query", ")", "\n", "}" ]
// TxFind allows you to pass in your own bolt transaction to retrieve a set of values from the bolthold
[ "TxFind", "allows", "you", "to", "pass", "in", "your", "own", "bolt", "transaction", "to", "retrieve", "a", "set", "of", "values", "from", "the", "bolthold" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/get.go#L57-L59
timshannon/bolthold
put.go
Insert
func (s *Store) Insert(key, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxInsert(tx, key, data) }) }
go
func (s *Store) Insert(key, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxInsert(tx, key, data) }) }
[ "func", "(", "s", "*", "Store", ")", "Insert", "(", "key", ",", "data", "interface", "{", "}", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxInsert", "(", "tx", ",", "key", ",", "data", ")", "\n", "}", ")", "\n", "}" ]
// Insert inserts the passed in data into the the bolthold // // If the the key already exists in the bolthold, then an ErrKeyExists is returned // If the data struct has a field tagged as `boltholdKey` and it is the same type // as the Insert key, AND the data struct is passed by reference, AND the key field // is currently set to the zero-value for that type, then that field will be set to // the value of the insert key. // // To use this with bolthold.NextSequence() use a type of `uint64` for the key field.
[ "Insert", "inserts", "the", "passed", "in", "data", "into", "the", "the", "bolthold", "If", "the", "the", "key", "already", "exists", "in", "the", "bolthold", "then", "an", "ErrKeyExists", "is", "returned", "If", "the", "data", "struct", "has", "a", "field", "tagged", "as", "boltholdKey", "and", "it", "is", "the", "same", "type", "as", "the", "Insert", "key", "AND", "the", "data", "struct", "is", "passed", "by", "reference", "AND", "the", "key", "field", "is", "currently", "set", "to", "the", "zero", "-", "value", "for", "that", "type", "then", "that", "field", "will", "be", "set", "to", "the", "value", "of", "the", "insert", "key", ".", "To", "use", "this", "with", "bolthold", ".", "NextSequence", "()", "use", "a", "type", "of", "uint64", "for", "the", "key", "field", "." ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L36-L40
timshannon/bolthold
put.go
TxInsert
func (s *Store) TxInsert(tx *bolt.Tx, key, data interface{}) error { if !tx.Writable() { return bolt.ErrTxNotWritable } storer := newStorer(data) b, err := tx.CreateBucketIfNotExists([]byte(storer.Type())) if err != nil { return err } if _, ok := key.(sequence); ok { key, err = b.NextSequence() if err != nil { return err } } gk, err := encode(key) if err != nil { return err } if b.Get(gk) != nil { return ErrKeyExists } value, err := encode(data) if err != nil { return err } // insert data err = b.Put(gk, value) if err != nil { return err } // insert any indexes err = indexAdd(storer, tx, gk, data) if err != nil { return err } dataVal := reflect.Indirect(reflect.ValueOf(data)) if !dataVal.CanSet() { return nil } dataType := dataVal.Type() for i := 0; i < dataType.NumField(); i++ { tf := dataType.Field(i) // XXX: should we require standard tag format so we can use StructTag.Lookup()? // XXX: should we use strings.Contains(string(tf.Tag), BoltholdKeyTag) so we don't require proper tags? if _, ok := tf.Tag.Lookup(BoltholdKeyTag); ok { fieldValue := dataVal.Field(i) keyValue := reflect.ValueOf(key) if keyValue.Type() != tf.Type { break } if !fieldValue.CanSet() { break } if !reflect.DeepEqual(fieldValue.Interface(), reflect.Zero(tf.Type).Interface()) { break } fieldValue.Set(keyValue) break } } return nil }
go
func (s *Store) TxInsert(tx *bolt.Tx, key, data interface{}) error { if !tx.Writable() { return bolt.ErrTxNotWritable } storer := newStorer(data) b, err := tx.CreateBucketIfNotExists([]byte(storer.Type())) if err != nil { return err } if _, ok := key.(sequence); ok { key, err = b.NextSequence() if err != nil { return err } } gk, err := encode(key) if err != nil { return err } if b.Get(gk) != nil { return ErrKeyExists } value, err := encode(data) if err != nil { return err } // insert data err = b.Put(gk, value) if err != nil { return err } // insert any indexes err = indexAdd(storer, tx, gk, data) if err != nil { return err } dataVal := reflect.Indirect(reflect.ValueOf(data)) if !dataVal.CanSet() { return nil } dataType := dataVal.Type() for i := 0; i < dataType.NumField(); i++ { tf := dataType.Field(i) // XXX: should we require standard tag format so we can use StructTag.Lookup()? // XXX: should we use strings.Contains(string(tf.Tag), BoltholdKeyTag) so we don't require proper tags? if _, ok := tf.Tag.Lookup(BoltholdKeyTag); ok { fieldValue := dataVal.Field(i) keyValue := reflect.ValueOf(key) if keyValue.Type() != tf.Type { break } if !fieldValue.CanSet() { break } if !reflect.DeepEqual(fieldValue.Interface(), reflect.Zero(tf.Type).Interface()) { break } fieldValue.Set(keyValue) break } } return nil }
[ "func", "(", "s", "*", "Store", ")", "TxInsert", "(", "tx", "*", "bolt", ".", "Tx", ",", "key", ",", "data", "interface", "{", "}", ")", "error", "{", "if", "!", "tx", ".", "Writable", "(", ")", "{", "return", "bolt", ".", "ErrTxNotWritable", "\n", "}", "\n\n", "storer", ":=", "newStorer", "(", "data", ")", "\n\n", "b", ",", "err", ":=", "tx", ".", "CreateBucketIfNotExists", "(", "[", "]", "byte", "(", "storer", ".", "Type", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "key", ".", "(", "sequence", ")", ";", "ok", "{", "key", ",", "err", "=", "b", ".", "NextSequence", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "gk", ",", "err", ":=", "encode", "(", "key", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "b", ".", "Get", "(", "gk", ")", "!=", "nil", "{", "return", "ErrKeyExists", "\n", "}", "\n\n", "value", ",", "err", ":=", "encode", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// insert data", "err", "=", "b", ".", "Put", "(", "gk", ",", "value", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// insert any indexes", "err", "=", "indexAdd", "(", "storer", ",", "tx", ",", "gk", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "dataVal", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "data", ")", ")", "\n", "if", "!", "dataVal", ".", "CanSet", "(", ")", "{", "return", "nil", "\n", "}", "\n", "dataType", ":=", "dataVal", ".", "Type", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "dataType", ".", "NumField", "(", ")", ";", "i", "++", "{", "tf", ":=", "dataType", ".", "Field", "(", "i", ")", "\n", "// XXX: should we require standard tag format so we can use StructTag.Lookup()?", "// XXX: should we use strings.Contains(string(tf.Tag), BoltholdKeyTag) so we don't require proper tags?", "if", "_", ",", "ok", ":=", "tf", ".", "Tag", ".", "Lookup", "(", "BoltholdKeyTag", ")", ";", "ok", "{", "fieldValue", ":=", "dataVal", ".", "Field", "(", "i", ")", "\n", "keyValue", ":=", "reflect", ".", "ValueOf", "(", "key", ")", "\n", "if", "keyValue", ".", "Type", "(", ")", "!=", "tf", ".", "Type", "{", "break", "\n", "}", "\n", "if", "!", "fieldValue", ".", "CanSet", "(", ")", "{", "break", "\n", "}", "\n", "if", "!", "reflect", ".", "DeepEqual", "(", "fieldValue", ".", "Interface", "(", ")", ",", "reflect", ".", "Zero", "(", "tf", ".", "Type", ")", ".", "Interface", "(", ")", ")", "{", "break", "\n", "}", "\n", "fieldValue", ".", "Set", "(", "keyValue", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// TxInsert is the same as Insert except it allows you specify your own transaction
[ "TxInsert", "is", "the", "same", "as", "Insert", "except", "it", "allows", "you", "specify", "your", "own", "transaction" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L43-L118
timshannon/bolthold
put.go
Update
func (s *Store) Update(key interface{}, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpdate(tx, key, data) }) }
go
func (s *Store) Update(key interface{}, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpdate(tx, key, data) }) }
[ "func", "(", "s", "*", "Store", ")", "Update", "(", "key", "interface", "{", "}", ",", "data", "interface", "{", "}", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxUpdate", "(", "tx", ",", "key", ",", "data", ")", "\n", "}", ")", "\n", "}" ]
// Update updates an existing record in the bolthold // if the Key doesn't already exist in the store, then it fails with ErrNotFound
[ "Update", "updates", "an", "existing", "record", "in", "the", "bolthold", "if", "the", "Key", "doesn", "t", "already", "exist", "in", "the", "store", "then", "it", "fails", "with", "ErrNotFound" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L122-L126
timshannon/bolthold
put.go
TxUpdate
func (s *Store) TxUpdate(tx *bolt.Tx, key interface{}, data interface{}) error { if !tx.Writable() { return bolt.ErrTxNotWritable } storer := newStorer(data) gk, err := encode(key) if err != nil { return err } b, err := tx.CreateBucketIfNotExists([]byte(storer.Type())) if err != nil { return err } existing := b.Get(gk) if existing == nil { return ErrNotFound } // delete any existing indexes existingVal := reflect.New(reflect.TypeOf(data)).Interface() err = decode(existing, existingVal) if err != nil { return err } err = indexDelete(storer, tx, gk, existingVal) if err != nil { return err } value, err := encode(data) if err != nil { return err } // put data err = b.Put(gk, value) if err != nil { return err } // insert any new indexes return indexAdd(storer, tx, gk, data) }
go
func (s *Store) TxUpdate(tx *bolt.Tx, key interface{}, data interface{}) error { if !tx.Writable() { return bolt.ErrTxNotWritable } storer := newStorer(data) gk, err := encode(key) if err != nil { return err } b, err := tx.CreateBucketIfNotExists([]byte(storer.Type())) if err != nil { return err } existing := b.Get(gk) if existing == nil { return ErrNotFound } // delete any existing indexes existingVal := reflect.New(reflect.TypeOf(data)).Interface() err = decode(existing, existingVal) if err != nil { return err } err = indexDelete(storer, tx, gk, existingVal) if err != nil { return err } value, err := encode(data) if err != nil { return err } // put data err = b.Put(gk, value) if err != nil { return err } // insert any new indexes return indexAdd(storer, tx, gk, data) }
[ "func", "(", "s", "*", "Store", ")", "TxUpdate", "(", "tx", "*", "bolt", ".", "Tx", ",", "key", "interface", "{", "}", ",", "data", "interface", "{", "}", ")", "error", "{", "if", "!", "tx", ".", "Writable", "(", ")", "{", "return", "bolt", ".", "ErrTxNotWritable", "\n", "}", "\n\n", "storer", ":=", "newStorer", "(", "data", ")", "\n\n", "gk", ",", "err", ":=", "encode", "(", "key", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "b", ",", "err", ":=", "tx", ".", "CreateBucketIfNotExists", "(", "[", "]", "byte", "(", "storer", ".", "Type", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "existing", ":=", "b", ".", "Get", "(", "gk", ")", "\n\n", "if", "existing", "==", "nil", "{", "return", "ErrNotFound", "\n", "}", "\n\n", "// delete any existing indexes", "existingVal", ":=", "reflect", ".", "New", "(", "reflect", ".", "TypeOf", "(", "data", ")", ")", ".", "Interface", "(", ")", "\n\n", "err", "=", "decode", "(", "existing", ",", "existingVal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "indexDelete", "(", "storer", ",", "tx", ",", "gk", ",", "existingVal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "value", ",", "err", ":=", "encode", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// put data", "err", "=", "b", ".", "Put", "(", "gk", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// insert any new indexes", "return", "indexAdd", "(", "storer", ",", "tx", ",", "gk", ",", "data", ")", "\n", "}" ]
// TxUpdate is the same as Update except it allows you to specify your own transaction
[ "TxUpdate", "is", "the", "same", "as", "Update", "except", "it", "allows", "you", "to", "specify", "your", "own", "transaction" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L129-L179
timshannon/bolthold
put.go
Upsert
func (s *Store) Upsert(key interface{}, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpsert(tx, key, data) }) }
go
func (s *Store) Upsert(key interface{}, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpsert(tx, key, data) }) }
[ "func", "(", "s", "*", "Store", ")", "Upsert", "(", "key", "interface", "{", "}", ",", "data", "interface", "{", "}", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxUpsert", "(", "tx", ",", "key", ",", "data", ")", "\n", "}", ")", "\n", "}" ]
// Upsert inserts the record into the bolthold if it doesn't exist. If it does already exist, then it updates // the existing record
[ "Upsert", "inserts", "the", "record", "into", "the", "bolthold", "if", "it", "doesn", "t", "exist", ".", "If", "it", "does", "already", "exist", "then", "it", "updates", "the", "existing", "record" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L183-L187
timshannon/bolthold
put.go
UpdateMatching
func (s *Store) UpdateMatching(dataType interface{}, query *Query, update func(record interface{}) error) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpdateMatching(tx, dataType, query, update) }) }
go
func (s *Store) UpdateMatching(dataType interface{}, query *Query, update func(record interface{}) error) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpdateMatching(tx, dataType, query, update) }) }
[ "func", "(", "s", "*", "Store", ")", "UpdateMatching", "(", "dataType", "interface", "{", "}", ",", "query", "*", "Query", ",", "update", "func", "(", "record", "interface", "{", "}", ")", "error", ")", "error", "{", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "s", ".", "TxUpdateMatching", "(", "tx", ",", "dataType", ",", "query", ",", "update", ")", "\n", "}", ")", "\n", "}" ]
// UpdateMatching runs the update function for every record that match the passed in query // Note that the type of record in the update func always has to be a pointer
[ "UpdateMatching", "runs", "the", "update", "function", "for", "every", "record", "that", "match", "the", "passed", "in", "query", "Note", "that", "the", "type", "of", "record", "in", "the", "update", "func", "always", "has", "to", "be", "a", "pointer" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L244-L248
timshannon/bolthold
put.go
TxUpdateMatching
func (s *Store) TxUpdateMatching(tx *bolt.Tx, dataType interface{}, query *Query, update func(record interface{}) error) error { return updateQuery(tx, dataType, query, update) }
go
func (s *Store) TxUpdateMatching(tx *bolt.Tx, dataType interface{}, query *Query, update func(record interface{}) error) error { return updateQuery(tx, dataType, query, update) }
[ "func", "(", "s", "*", "Store", ")", "TxUpdateMatching", "(", "tx", "*", "bolt", ".", "Tx", ",", "dataType", "interface", "{", "}", ",", "query", "*", "Query", ",", "update", "func", "(", "record", "interface", "{", "}", ")", "error", ")", "error", "{", "return", "updateQuery", "(", "tx", ",", "dataType", ",", "query", ",", "update", ")", "\n", "}" ]
// TxUpdateMatching does the same as UpdateMatching, but allows you to specify your own transaction
[ "TxUpdateMatching", "does", "the", "same", "as", "UpdateMatching", "but", "allows", "you", "to", "specify", "your", "own", "transaction" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/put.go#L251-L253
timshannon/bolthold
store.go
Open
func Open(filename string, mode os.FileMode, options *Options) (*Store, error) { options = fillOptions(options) encode = options.Encoder decode = options.Decoder db, err := bolt.Open(filename, mode, options.Options) if err != nil { return nil, err } return &Store{ db: db, }, nil }
go
func Open(filename string, mode os.FileMode, options *Options) (*Store, error) { options = fillOptions(options) encode = options.Encoder decode = options.Decoder db, err := bolt.Open(filename, mode, options.Options) if err != nil { return nil, err } return &Store{ db: db, }, nil }
[ "func", "Open", "(", "filename", "string", ",", "mode", "os", ".", "FileMode", ",", "options", "*", "Options", ")", "(", "*", "Store", ",", "error", ")", "{", "options", "=", "fillOptions", "(", "options", ")", "\n\n", "encode", "=", "options", ".", "Encoder", "\n", "decode", "=", "options", ".", "Decoder", "\n\n", "db", ",", "err", ":=", "bolt", ".", "Open", "(", "filename", ",", "mode", ",", "options", ".", "Options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Store", "{", "db", ":", "db", ",", "}", ",", "nil", "\n", "}" ]
// Open opens or creates a bolthold file.
[ "Open", "opens", "or", "creates", "a", "bolthold", "file", "." ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/store.go#L29-L43
timshannon/bolthold
store.go
fillOptions
func fillOptions(options *Options) *Options { if options == nil { options = &Options{} } if options.Encoder == nil { options.Encoder = DefaultEncode } if options.Decoder == nil { options.Decoder = DefaultDecode } return options }
go
func fillOptions(options *Options) *Options { if options == nil { options = &Options{} } if options.Encoder == nil { options.Encoder = DefaultEncode } if options.Decoder == nil { options.Decoder = DefaultDecode } return options }
[ "func", "fillOptions", "(", "options", "*", "Options", ")", "*", "Options", "{", "if", "options", "==", "nil", "{", "options", "=", "&", "Options", "{", "}", "\n", "}", "\n\n", "if", "options", ".", "Encoder", "==", "nil", "{", "options", ".", "Encoder", "=", "DefaultEncode", "\n", "}", "\n", "if", "options", ".", "Decoder", "==", "nil", "{", "options", ".", "Decoder", "=", "DefaultDecode", "\n", "}", "\n\n", "return", "options", "\n", "}" ]
// set any unspecified options to defaults
[ "set", "any", "unspecified", "options", "to", "defaults" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/store.go#L46-L59
timshannon/bolthold
store.go
ReIndex
func (s *Store) ReIndex(exampleType interface{}, bucketName []byte) error { storer := newStorer(exampleType) return s.Bolt().Update(func(tx *bolt.Tx) error { indexes := storer.Indexes() // delete existing indexes // TODO: Remove indexes not specified the storer index list? // good for cleanup, bad for possible side effects for indexName := range indexes { err := tx.DeleteBucket(indexBucketName(storer.Type(), indexName)) if err != nil && err != bolt.ErrBucketNotFound { return err } } copyData := true if bucketName == nil { bucketName = []byte(storer.Type()) copyData = false } c := tx.Bucket(bucketName).Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { if copyData { b, err := tx.CreateBucketIfNotExists([]byte(storer.Type())) if err != nil { return err } err = b.Put(k, v) if err != nil { return err } } err := decode(v, exampleType) if err != nil { return err } err = indexAdd(storer, tx, k, exampleType) if err != nil { return err } } return nil }) }
go
func (s *Store) ReIndex(exampleType interface{}, bucketName []byte) error { storer := newStorer(exampleType) return s.Bolt().Update(func(tx *bolt.Tx) error { indexes := storer.Indexes() // delete existing indexes // TODO: Remove indexes not specified the storer index list? // good for cleanup, bad for possible side effects for indexName := range indexes { err := tx.DeleteBucket(indexBucketName(storer.Type(), indexName)) if err != nil && err != bolt.ErrBucketNotFound { return err } } copyData := true if bucketName == nil { bucketName = []byte(storer.Type()) copyData = false } c := tx.Bucket(bucketName).Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { if copyData { b, err := tx.CreateBucketIfNotExists([]byte(storer.Type())) if err != nil { return err } err = b.Put(k, v) if err != nil { return err } } err := decode(v, exampleType) if err != nil { return err } err = indexAdd(storer, tx, k, exampleType) if err != nil { return err } } return nil }) }
[ "func", "(", "s", "*", "Store", ")", "ReIndex", "(", "exampleType", "interface", "{", "}", ",", "bucketName", "[", "]", "byte", ")", "error", "{", "storer", ":=", "newStorer", "(", "exampleType", ")", "\n\n", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "indexes", ":=", "storer", ".", "Indexes", "(", ")", "\n", "// delete existing indexes", "// TODO: Remove indexes not specified the storer index list?", "// good for cleanup, bad for possible side effects", "for", "indexName", ":=", "range", "indexes", "{", "err", ":=", "tx", ".", "DeleteBucket", "(", "indexBucketName", "(", "storer", ".", "Type", "(", ")", ",", "indexName", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "bolt", ".", "ErrBucketNotFound", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "copyData", ":=", "true", "\n\n", "if", "bucketName", "==", "nil", "{", "bucketName", "=", "[", "]", "byte", "(", "storer", ".", "Type", "(", ")", ")", "\n", "copyData", "=", "false", "\n", "}", "\n\n", "c", ":=", "tx", ".", "Bucket", "(", "bucketName", ")", ".", "Cursor", "(", ")", "\n\n", "for", "k", ",", "v", ":=", "c", ".", "First", "(", ")", ";", "k", "!=", "nil", ";", "k", ",", "v", "=", "c", ".", "Next", "(", ")", "{", "if", "copyData", "{", "b", ",", "err", ":=", "tx", ".", "CreateBucketIfNotExists", "(", "[", "]", "byte", "(", "storer", ".", "Type", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "b", ".", "Put", "(", "k", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "err", ":=", "decode", "(", "v", ",", "exampleType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "indexAdd", "(", "storer", ",", "tx", ",", "k", ",", "exampleType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// ReIndex removes any existing indexes and adds all the indexes defined by the passed in datatype example // This function allows you to index an already existing boltDB file, or refresh any missing indexes // if bucketName is nil, then we'll assume a bucketName of storer.Type() // if a bucketname is specified, then the data will be copied to the bolthold standard bucket of storer.Type()
[ "ReIndex", "removes", "any", "existing", "indexes", "and", "adds", "all", "the", "indexes", "defined", "by", "the", "passed", "in", "datatype", "example", "This", "function", "allows", "you", "to", "index", "an", "already", "existing", "boltDB", "file", "or", "refresh", "any", "missing", "indexes", "if", "bucketName", "is", "nil", "then", "we", "ll", "assume", "a", "bucketName", "of", "storer", ".", "Type", "()", "if", "a", "bucketname", "is", "specified", "then", "the", "data", "will", "be", "copied", "to", "the", "bolthold", "standard", "bucket", "of", "storer", ".", "Type", "()" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/store.go#L75-L124
timshannon/bolthold
store.go
RemoveIndex
func (s *Store) RemoveIndex(dataType interface{}, indexName string) error { storer := newStorer(dataType) return s.Bolt().Update(func(tx *bolt.Tx) error { return tx.DeleteBucket(indexBucketName(storer.Type(), indexName)) }) }
go
func (s *Store) RemoveIndex(dataType interface{}, indexName string) error { storer := newStorer(dataType) return s.Bolt().Update(func(tx *bolt.Tx) error { return tx.DeleteBucket(indexBucketName(storer.Type(), indexName)) }) }
[ "func", "(", "s", "*", "Store", ")", "RemoveIndex", "(", "dataType", "interface", "{", "}", ",", "indexName", "string", ")", "error", "{", "storer", ":=", "newStorer", "(", "dataType", ")", "\n", "return", "s", ".", "Bolt", "(", ")", ".", "Update", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", "{", "return", "tx", ".", "DeleteBucket", "(", "indexBucketName", "(", "storer", ".", "Type", "(", ")", ",", "indexName", ")", ")", "\n\n", "}", ")", "\n", "}" ]
// RemoveIndex removes an index from the store.
[ "RemoveIndex", "removes", "an", "index", "from", "the", "store", "." ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/store.go#L127-L133
timshannon/bolthold
store.go
newStorer
func newStorer(dataType interface{}) Storer { s, ok := dataType.(Storer) if ok { return s } tp := reflect.TypeOf(dataType) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } storer := &anonStorer{ rType: tp, indexes: make(map[string]Index), } if storer.rType.Name() == "" { panic("Invalid Type for Storer. Type is unnamed") } if storer.rType.Kind() != reflect.Struct { panic("Invalid Type for Storer. BoltHold only works with structs") } for i := 0; i < storer.rType.NumField(); i++ { if strings.Contains(string(storer.rType.Field(i).Tag), BoltholdIndexTag) { indexName := storer.rType.Field(i).Tag.Get(BoltholdIndexTag) if indexName != "" { indexName = storer.rType.Field(i).Name } storer.indexes[indexName] = func(name string, value interface{}) ([]byte, error) { tp := reflect.ValueOf(value) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } return encode(tp.FieldByName(name).Interface()) } } } return storer }
go
func newStorer(dataType interface{}) Storer { s, ok := dataType.(Storer) if ok { return s } tp := reflect.TypeOf(dataType) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } storer := &anonStorer{ rType: tp, indexes: make(map[string]Index), } if storer.rType.Name() == "" { panic("Invalid Type for Storer. Type is unnamed") } if storer.rType.Kind() != reflect.Struct { panic("Invalid Type for Storer. BoltHold only works with structs") } for i := 0; i < storer.rType.NumField(); i++ { if strings.Contains(string(storer.rType.Field(i).Tag), BoltholdIndexTag) { indexName := storer.rType.Field(i).Tag.Get(BoltholdIndexTag) if indexName != "" { indexName = storer.rType.Field(i).Name } storer.indexes[indexName] = func(name string, value interface{}) ([]byte, error) { tp := reflect.ValueOf(value) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } return encode(tp.FieldByName(name).Interface()) } } } return storer }
[ "func", "newStorer", "(", "dataType", "interface", "{", "}", ")", "Storer", "{", "s", ",", "ok", ":=", "dataType", ".", "(", "Storer", ")", "\n\n", "if", "ok", "{", "return", "s", "\n", "}", "\n\n", "tp", ":=", "reflect", ".", "TypeOf", "(", "dataType", ")", "\n\n", "for", "tp", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "tp", "=", "tp", ".", "Elem", "(", ")", "\n", "}", "\n\n", "storer", ":=", "&", "anonStorer", "{", "rType", ":", "tp", ",", "indexes", ":", "make", "(", "map", "[", "string", "]", "Index", ")", ",", "}", "\n\n", "if", "storer", ".", "rType", ".", "Name", "(", ")", "==", "\"", "\"", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "storer", ".", "rType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "storer", ".", "rType", ".", "NumField", "(", ")", ";", "i", "++", "{", "if", "strings", ".", "Contains", "(", "string", "(", "storer", ".", "rType", ".", "Field", "(", "i", ")", ".", "Tag", ")", ",", "BoltholdIndexTag", ")", "{", "indexName", ":=", "storer", ".", "rType", ".", "Field", "(", "i", ")", ".", "Tag", ".", "Get", "(", "BoltholdIndexTag", ")", "\n\n", "if", "indexName", "!=", "\"", "\"", "{", "indexName", "=", "storer", ".", "rType", ".", "Field", "(", "i", ")", ".", "Name", "\n", "}", "\n\n", "storer", ".", "indexes", "[", "indexName", "]", "=", "func", "(", "name", "string", ",", "value", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "tp", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n", "for", "tp", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "tp", "=", "tp", ".", "Elem", "(", ")", "\n", "}", "\n\n", "return", "encode", "(", "tp", ".", "FieldByName", "(", "name", ")", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "storer", "\n", "}" ]
// newStorer creates a type which satisfies the Storer interface based on reflection of the passed in dataType // if the Type doesn't meet the requirements of a Storer (i.e. doesn't have a name) it panics // You can avoid any reflection costs, by implementing the Storer interface on a type
[ "newStorer", "creates", "a", "type", "which", "satisfies", "the", "Storer", "interface", "based", "on", "reflection", "of", "the", "passed", "in", "dataType", "if", "the", "Type", "doesn", "t", "meet", "the", "requirements", "of", "a", "Storer", "(", "i", ".", "e", ".", "doesn", "t", "have", "a", "name", ")", "it", "panics", "You", "can", "avoid", "any", "reflection", "costs", "by", "implementing", "the", "Storer", "interface", "on", "a", "type" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/store.go#L160-L206
timshannon/bolthold
query.go
IsEmpty
func (q *Query) IsEmpty() bool { if q.index != "" { return false } if len(q.fieldCriteria) != 0 { return false } if q.ors != nil { return false } return true }
go
func (q *Query) IsEmpty() bool { if q.index != "" { return false } if len(q.fieldCriteria) != 0 { return false } if q.ors != nil { return false } return true }
[ "func", "(", "q", "*", "Query", ")", "IsEmpty", "(", ")", "bool", "{", "if", "q", ".", "index", "!=", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "q", ".", "fieldCriteria", ")", "!=", "0", "{", "return", "false", "\n", "}", "\n\n", "if", "q", ".", "ors", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// IsEmpty returns true if the query is an empty query // an empty query matches against everything
[ "IsEmpty", "returns", "true", "if", "the", "query", "is", "an", "empty", "query", "an", "empty", "query", "matches", "against", "everything" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L58-L71
timshannon/bolthold
query.go
Where
func Where(field string) *Criterion { if !startsUpper(field) { panic("The first letter of a field in a bolthold query must be upper-case") } return &Criterion{ query: &Query{ currentField: field, fieldCriteria: make(map[string][]*Criterion), }, } }
go
func Where(field string) *Criterion { if !startsUpper(field) { panic("The first letter of a field in a bolthold query must be upper-case") } return &Criterion{ query: &Query{ currentField: field, fieldCriteria: make(map[string][]*Criterion), }, } }
[ "func", "Where", "(", "field", "string", ")", "*", "Criterion", "{", "if", "!", "startsUpper", "(", "field", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "Criterion", "{", "query", ":", "&", "Query", "{", "currentField", ":", "field", ",", "fieldCriteria", ":", "make", "(", "map", "[", "string", "]", "[", "]", "*", "Criterion", ")", ",", "}", ",", "}", "\n", "}" ]
// Where starts a query for specifying the criteria that an object in the bolthold needs to match to // be returned in a Find result /* Query API Example s.Find(bolthold.Where("FieldName").Eq(value).And("AnotherField").Lt(AnotherValue).Or(bolthold.Where("FieldName").Eq(anotherValue) Since Gobs only encode exported fields, this will panic if you pass in a field with a lower case first letter */
[ "Where", "starts", "a", "query", "for", "specifying", "the", "criteria", "that", "an", "object", "in", "the", "bolthold", "needs", "to", "match", "to", "be", "returned", "in", "a", "Find", "result", "/", "*", "Query", "API", "Example" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L102-L113
timshannon/bolthold
query.go
And
func (q *Query) And(field string) *Criterion { if !startsUpper(field) { panic("The first letter of a field in a bolthold query must be upper-case") } q.currentField = field return &Criterion{ query: q, } }
go
func (q *Query) And(field string) *Criterion { if !startsUpper(field) { panic("The first letter of a field in a bolthold query must be upper-case") } q.currentField = field return &Criterion{ query: q, } }
[ "func", "(", "q", "*", "Query", ")", "And", "(", "field", "string", ")", "*", "Criterion", "{", "if", "!", "startsUpper", "(", "field", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "q", ".", "currentField", "=", "field", "\n", "return", "&", "Criterion", "{", "query", ":", "q", ",", "}", "\n", "}" ]
// And creates a nother set of criterion the needs to apply to a query
[ "And", "creates", "a", "nother", "set", "of", "criterion", "the", "needs", "to", "apply", "to", "a", "query" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L116-L125
timshannon/bolthold
query.go
Skip
func (q *Query) Skip(amount int) *Query { if amount < 0 { panic("Skip must be set to a positive number") } if q.skip != 0 { panic(fmt.Sprintf("Skip has already been set to %d", q.skip)) } q.skip = amount return q }
go
func (q *Query) Skip(amount int) *Query { if amount < 0 { panic("Skip must be set to a positive number") } if q.skip != 0 { panic(fmt.Sprintf("Skip has already been set to %d", q.skip)) } q.skip = amount return q }
[ "func", "(", "q", "*", "Query", ")", "Skip", "(", "amount", "int", ")", "*", "Query", "{", "if", "amount", "<", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "q", ".", "skip", "!=", "0", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "q", ".", "skip", ")", ")", "\n", "}", "\n\n", "q", ".", "skip", "=", "amount", "\n\n", "return", "q", "\n", "}" ]
// Skip skips the number of records that match all the rest of the query criteria, and does not return them // in the result set. Setting skip multiple times, or to a negative value will panic
[ "Skip", "skips", "the", "number", "of", "records", "that", "match", "all", "the", "rest", "of", "the", "query", "criteria", "and", "does", "not", "return", "them", "in", "the", "result", "set", ".", "Setting", "skip", "multiple", "times", "or", "to", "a", "negative", "value", "will", "panic" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L129-L141
timshannon/bolthold
query.go
Limit
func (q *Query) Limit(amount int) *Query { if amount < 0 { panic("Limit must be set to a positive number") } if q.limit != 0 { panic(fmt.Sprintf("Limit has already been set to %d", q.limit)) } q.limit = amount return q }
go
func (q *Query) Limit(amount int) *Query { if amount < 0 { panic("Limit must be set to a positive number") } if q.limit != 0 { panic(fmt.Sprintf("Limit has already been set to %d", q.limit)) } q.limit = amount return q }
[ "func", "(", "q", "*", "Query", ")", "Limit", "(", "amount", "int", ")", "*", "Query", "{", "if", "amount", "<", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "q", ".", "limit", "!=", "0", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "q", ".", "limit", ")", ")", "\n", "}", "\n\n", "q", ".", "limit", "=", "amount", "\n\n", "return", "q", "\n", "}" ]
// Limit sets the maximum number of records that can be returned by a query // Setting Limit multiple times, or to a negative value will panic
[ "Limit", "sets", "the", "maximum", "number", "of", "records", "that", "can", "be", "returned", "by", "a", "query", "Setting", "Limit", "multiple", "times", "or", "to", "a", "negative", "value", "will", "panic" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L145-L157
timshannon/bolthold
query.go
SortBy
func (q *Query) SortBy(fields ...string) *Query { for i := range fields { if fields[i] == Key { panic("Cannot sort by Key.") } found := false for k := range q.sort { if q.sort[k] == fields[i] { found = true break } } if !found { q.sort = append(q.sort, fields[i]) } } return q }
go
func (q *Query) SortBy(fields ...string) *Query { for i := range fields { if fields[i] == Key { panic("Cannot sort by Key.") } found := false for k := range q.sort { if q.sort[k] == fields[i] { found = true break } } if !found { q.sort = append(q.sort, fields[i]) } } return q }
[ "func", "(", "q", "*", "Query", ")", "SortBy", "(", "fields", "...", "string", ")", "*", "Query", "{", "for", "i", ":=", "range", "fields", "{", "if", "fields", "[", "i", "]", "==", "Key", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "found", ":=", "false", "\n", "for", "k", ":=", "range", "q", ".", "sort", "{", "if", "q", ".", "sort", "[", "k", "]", "==", "fields", "[", "i", "]", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "q", ".", "sort", "=", "append", "(", "q", ".", "sort", ",", "fields", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "return", "q", "\n", "}" ]
// SortBy sorts the results by the given fields name // Multiple fields can be used
[ "SortBy", "sorts", "the", "results", "by", "the", "given", "fields", "name", "Multiple", "fields", "can", "be", "used" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L161-L178
timshannon/bolthold
query.go
Index
func (q *Query) Index(indexName string) *Query { if strings.Contains(indexName, ".") { // NOTE: I may reconsider this in the future panic("Nested indexes are not supported. Only top level structures can be indexed") } q.index = indexName return q }
go
func (q *Query) Index(indexName string) *Query { if strings.Contains(indexName, ".") { // NOTE: I may reconsider this in the future panic("Nested indexes are not supported. Only top level structures can be indexed") } q.index = indexName return q }
[ "func", "(", "q", "*", "Query", ")", "Index", "(", "indexName", "string", ")", "*", "Query", "{", "if", "strings", ".", "Contains", "(", "indexName", ",", "\"", "\"", ")", "{", "// NOTE: I may reconsider this in the future", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "q", ".", "index", "=", "indexName", "\n", "return", "q", "\n", "}" ]
// Index specifies the index to use when running this query
[ "Index", "specifies", "the", "index", "to", "use", "when", "running", "this", "query" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L188-L195
timshannon/bolthold
query.go
Or
func (q *Query) Or(query *Query) *Query { if query.skip != 0 || query.limit != 0 { panic("Or'd queries cannot contain skip or limit values") } q.ors = append(q.ors, query) return q }
go
func (q *Query) Or(query *Query) *Query { if query.skip != 0 || query.limit != 0 { panic("Or'd queries cannot contain skip or limit values") } q.ors = append(q.ors, query) return q }
[ "func", "(", "q", "*", "Query", ")", "Or", "(", "query", "*", "Query", ")", "*", "Query", "{", "if", "query", ".", "skip", "!=", "0", "||", "query", ".", "limit", "!=", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "q", ".", "ors", "=", "append", "(", "q", ".", "ors", ",", "query", ")", "\n", "return", "q", "\n", "}" ]
// Or creates another separate query that gets unioned with any other results in the query // Or will panic if the query passed in contains a limit or skip value, as they are only // allowed on top level queries
[ "Or", "creates", "another", "separate", "query", "that", "gets", "unioned", "with", "any", "other", "results", "in", "the", "query", "Or", "will", "panic", "if", "the", "query", "passed", "in", "contains", "a", "limit", "or", "skip", "value", "as", "they", "are", "only", "allowed", "on", "top", "level", "queries" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L200-L206
timshannon/bolthold
query.go
In
func (c *Criterion) In(values ...interface{}) *Query { c.operator = in c.inValues = values q := c.query q.fieldCriteria[q.currentField] = append(q.fieldCriteria[q.currentField], c) return q }
go
func (c *Criterion) In(values ...interface{}) *Query { c.operator = in c.inValues = values q := c.query q.fieldCriteria[q.currentField] = append(q.fieldCriteria[q.currentField], c) return q }
[ "func", "(", "c", "*", "Criterion", ")", "In", "(", "values", "...", "interface", "{", "}", ")", "*", "Query", "{", "c", ".", "operator", "=", "in", "\n", "c", ".", "inValues", "=", "values", "\n\n", "q", ":=", "c", ".", "query", "\n", "q", ".", "fieldCriteria", "[", "q", ".", "currentField", "]", "=", "append", "(", "q", ".", "fieldCriteria", "[", "q", ".", "currentField", "]", ",", "c", ")", "\n\n", "return", "q", "\n", "}" ]
// In test if the current field is a member of the slice of values passed in
[ "In", "test", "if", "the", "current", "field", "is", "a", "member", "of", "the", "slice", "of", "values", "passed", "in" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L306-L314
timshannon/bolthold
query.go
RegExp
func (c *Criterion) RegExp(expression *regexp.Regexp) *Query { return c.op(re, expression) }
go
func (c *Criterion) RegExp(expression *regexp.Regexp) *Query { return c.op(re, expression) }
[ "func", "(", "c", "*", "Criterion", ")", "RegExp", "(", "expression", "*", "regexp", ".", "Regexp", ")", "*", "Query", "{", "return", "c", ".", "op", "(", "re", ",", "expression", ")", "\n", "}" ]
// RegExp will test if a field matches against the regular expression // The Field Value will be converted to string (%s) before testing
[ "RegExp", "will", "test", "if", "a", "field", "matches", "against", "the", "regular", "expression", "The", "Field", "Value", "will", "be", "converted", "to", "string", "(", "%s", ")", "before", "testing" ]
train
https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L318-L320