text
stringlengths
76
10.6k
// List of the names of the defined grifts. func List() []string { keys := []string{} for k := range griftList { keys = append(keys, k) } sort.Strings(keys) return keys }
// Exec the grift stack. This is the main "entry point" to // the grift system. 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 }
// PrintGrifts to the screen, nice, sorted, and with descriptions, // should they exist. 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]}, " ")) } }
// RunSource executes the command passed as argument, // in the current shell/context func RunSource(cmd *exec.Cmd) error { cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout return cmd.Run() }
// Value returns a value from the context for the given key 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) }
// Set a piece of data onto the Context. func (c *Context) Set(key string, val interface{}) { c.moot.Lock() defer c.moot.Unlock() c.data[key] = val }
// NewContextWithContext builds and returns a new default Context given an existing context func NewContextWithContext(name string, ctx context.Context) *Context { return &Context{ Context: ctx, Name: name, Args: []string{}, data: map[interface{}]interface{}{}, moot: &sync.Mutex{}, } }
// ParseStylesheet parses a stylesheet 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 }
// ParseRules parses a list of rules 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() }
// ParseRule parses a rule func (parser *Parser) ParseRule() (*css.Rule, error) { if parser.tokenAtKeyword() { return parser.parseAtRule() } return parser.parseQualifiedRule() }
// ParseDeclarations parses a list of declarations 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() }
// ParseDeclaration parses a declaration 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() }
// Parse an At Rule 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() }
// Parse a Qualified Rule 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() }
// Parse Rule prelude 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() }
// Parse BOM func (parser *Parser) parseBOM() (bool, error) { if parser.nextToken().Type == scanner.TokenBOM { parser.shiftToken() return true, nil } return false, parser.err() }
// Returns next token without removing it from tokens buffer 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] }
// Returns next token and remove it from the tokens buffer func (parser *Parser) shiftToken() *scanner.Token { var result *scanner.Token result, parser.tokens = parser.tokens[0], parser.tokens[1:] return result }
// Returns tokenizer error, or nil if no error func (parser *Parser) err() error { if parser.tokenError() { token := parser.nextToken() return fmt.Errorf("Tokenizer error: %s", token.String()) } return nil }
// Returns true if next token is a CDO or a CDC func (parser *Parser) tokenCDOorCDC() bool { switch parser.nextToken().Type { case scanner.TokenCDO, scanner.TokenCDC: return true default: return false } }
// Returns true if next token is ignorable func (parser *Parser) tokenIgnorable() bool { return parser.tokenWS() || parser.tokenComment() || parser.tokenCDOorCDC() }
// Returns true if next token is given character func (parser *Parser) tokenChar(value string) bool { token := parser.nextToken() return (token.Type == scanner.TokenChar) && (token.Value == value) }
// Returns string representation of the Stylesheet func (sheet *Stylesheet) String() string { result := "" for _, rule := range sheet.Rules { if result!= "" { result += "\n" } result += rule.String() } return result }
// EmbedsRules returns true if this rule embeds another rules func (rule *Rule) EmbedsRules() bool { if rule.Kind == AtRule { for _, atRuleName := range atRulesWithRulesBlock { if rule.Name == atRuleName { return true } } } return false }
// Equal returns true if both rules are equals 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 }
// Diff returns a string representation of rules differences 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 }
// Returns the string representation of a rule 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 }
// Returns identation spaces for declarations and rules func (rule *Rule) indent() string { result := "" for i := 0; i < ((rule.EmbedLevel + 1) * indentSpace); i++ { result += " " } return result }
// Returns identation spaces for end of block character func (rule *Rule) indentEndBlock() string { result := "" for i := 0; i < (rule.EmbedLevel * indentSpace); i++ { result += " " } return result }
// parse and display CSS file 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()) }
// inlines CSS into HTML and display result 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) }
// Add a Style Rule to Element func (element *Element) addStyleRule(styleRule *StyleRule) { element.styleRules = append(element.styleRules, styleRule) }
// Inline styles on element 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 }
// Compute css declarations 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 }
// Parse inline style rules 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 }
// Set additional attributes from style declarations 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 } } } } }
// helper func computeStyleValue(declarations []*css.Declaration) string { result := "" // set style attribute value for _, declaration := range declarations { if result!= "" { result += " " } result += declaration.StringWithImportant(false) } return result }
// helper 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 } } } }
// NewStyleRule instanciates a new StyleRule func NewStyleRule(selector string, declarations []*css.Declaration) *StyleRule { return &StyleRule{ Selector: selector, Declarations: declarations, Specificity: ComputeSpecificity(selector), } }
// Returns the string representation of a style rule 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 }
// ComputeSpecificity computes style rule specificity // // cf. http://www.w3.org/TR/selectors/#specificity 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 }
// StringWithImportant returns string representation with optional!important part 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 }
// Equal returns true if both Declarations are equals func (decl *Declaration) Equal(other *Declaration) bool { return (decl.Property == other.Property) && (decl.Value == other.Value) && (decl.Important == other.Important) }
// Implements sort.Interface func (declarations DeclarationsByProperty) Swap(i, j int) { declarations[i], declarations[j] = declarations[j], declarations[i] }
// Implements sort.Interface func (declarations DeclarationsByProperty) Less(i, j int) bool { return declarations[i].Property < declarations[j].Property }
// NewInliner instanciates a new Inliner func NewInliner(html string) *Inliner { return &Inliner{ html: html, elements: make(map[string]*Element), } }
// Inline inlines css into html document func Inline(html string) (string, error) { result, err := NewInliner(html).Inline() if err!= nil { return "", err } return result, nil }
// Inline inlines CSS and returns HTML 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() }
// Parses raw html func (inliner *Inliner) parseHTML() error { doc, err := goquery.NewDocumentFromReader(strings.NewReader(inliner.html)) if err!= nil { return err } inliner.doc = doc return nil }
// Parses and removes stylesheets from HTML document 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 }
// Collects HTML elements matching parsed stylesheets, and thus collect used style rules 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) } } } }
// Handles parsed qualified rule 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)) } } }
// Inline style rules in HTML document 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 }
// Computes raw CSS rules func (inliner *Inliner) computeRawCSS() string { result := "" for _, rawRule := range inliner.rawRules { result += rawRule.String() result += "\n" } return result }
// Insert raw CSS rules into HTML document 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) } }
// Inlinable returns true if given selector is 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 }
// NewStyleDeclaration instanciates a new StyleDeclaration func NewStyleDeclaration(styleRule *StyleRule, declaration *css.Declaration) *StyleDeclaration { return &StyleDeclaration{ StyleRule: styleRule, Declaration: declaration, } }
// Specificity computes style declaration specificity func (styleDecl *StyleDeclaration) Specificity() int { if styleDecl.Declaration.Important { return 10000 } return styleDecl.StyleRule.Specificity }
// GetField returns the value of the provided obj field. obj can whether // be a structure or pointer to structure. 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 }
// GetFieldKind returns the kind of the provided obj field. obj can whether // be a structure or pointer to structure. 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 }
// GetFieldTag returns the provided obj field tag value. obj can whether // be a structure or pointer to structure. 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 }
// HasField checks if the provided field name is part of a struct. obj can whether // be a structure or pointer to structure. 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 }
// Tags lists the struct tag fields. obj can whether // be a structure or pointer to structure. func Tags(obj interface{}, key string) (map[string]string, error) { return tags(obj, key, false) }
// FieldsDeep returns "flattened" tags (fields from anonymous // inner structs are treated as normal fields) func TagsDeep(obj interface{}, key string) (map[string]string, error) { return tags(obj, key, true) }
// adds an item to the index 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 }
// removes an item from the index // be sure to pass the data from the old record, not the new one 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 }
// adds or removes a specific index on an item 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) }
// IndexExists tests if an index exists for the passed in field name func (s *Store) IndexExists(tx *bolt.Tx, typeName, indexName string) bool { return (tx.Bucket(indexBucketName(typeName, indexName))!= nil) }
// 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 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() }
// 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 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 }
// 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 func (s *Store) Delete(key, dataType interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxDelete(tx, key, dataType) }) }
// TxDelete is the same as Delete except it allows you specify your own transaction 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) }
// DeleteMatching deletes all of the records that match the passed in 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) }) }
// TxDeleteMatching does the same as DeleteMatching, but allows you to specify your own transaction func (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error { return deleteQuery(tx, dataType, query) }
// Get retrieves a value from bolthold and puts it into result. Result must be a pointer func (s *Store) Get(key, result interface{}) error { return s.Bolt().View(func(tx *bolt.Tx) error { return s.TxGet(tx, key, result) }) }
// TxGet allows you to pass in your own bolt transaction to retrieve a value from the bolthold and puts it into result 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) }
// 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. func (s *Store) Find(result interface{}, query *Query) error { return s.Bolt().View(func(tx *bolt.Tx) error { return s.TxFind(tx, result, query) }) }
// TxFind allows you to pass in your own bolt transaction to retrieve a set of values from the bolthold func (s *Store) TxFind(tx *bolt.Tx, result interface{}, query *Query) error { return findQuery(tx, result, query) }
// 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. func (s *Store) Insert(key, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxInsert(tx, key, data) }) }
// TxInsert is the same as Insert except it allows you specify your own transaction 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 }
// Update updates an existing record in the bolthold // if the Key doesn't already exist in the store, then it fails with ErrNotFound func (s *Store) Update(key interface{}, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpdate(tx, key, data) }) }
// TxUpdate is the same as Update except it allows you to specify your own transaction 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) }
// Upsert inserts the record into the bolthold if it doesn't exist. If it does already exist, then it updates // the existing record func (s *Store) Upsert(key interface{}, data interface{}) error { return s.Bolt().Update(func(tx *bolt.Tx) error { return s.TxUpsert(tx, key, data) }) }
// 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 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) }) }
// TxUpdateMatching does the same as UpdateMatching, but allows you to specify your own transaction func (s *Store) TxUpdateMatching(tx *bolt.Tx, dataType interface{}, query *Query, update func(record interface{}) error) error { return updateQuery(tx, dataType, query, update) }
// Open opens or creates a bolthold file. 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 }
// set any unspecified options to defaults 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 }
// 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() 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 }) }
// RemoveIndex removes an index from the store. 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)) }) }
// 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 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 }
// IsEmpty returns true if the query is an empty query // an empty query matches against everything 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 }
// 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 */ 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), }, } }
// And creates a nother set of criterion the needs to apply to a query 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, } }
// 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 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 }
// 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 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 }
// SortBy sorts the results by the given fields name // Multiple fields can be used 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 }
// Index specifies the index to use when running this query 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 }
// 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 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 }
// In test if the current field is a member of the slice of values passed 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 }
// RegExp will test if a field matches against the regular expression // The Field Value will be converted to string (%s) before testing func (c *Criterion) RegExp(expression *regexp.Regexp) *Query { return c.op(re, expression) }