id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
12,300
peco/peco
pipeline/pipeline.go
SetDestination
func (p *Pipeline) SetDestination(d Destination) { p.mutex.Lock() defer p.mutex.Unlock() p.dst = d }
go
func (p *Pipeline) SetDestination(d Destination) { p.mutex.Lock() defer p.mutex.Unlock() p.dst = d }
[ "func", "(", "p", "*", "Pipeline", ")", "SetDestination", "(", "d", "Destination", ")", "{", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "p", ".", "dst", "=", "d", "\n", "}" ]
// SetDestination sets the destination. // If called during `Run`, this method will block.
[ "SetDestination", "sets", "the", "destination", ".", "If", "called", "during", "Run", "this", "method", "will", "block", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L102-L107
12,301
peco/peco
pipeline/pipeline.go
Run
func (p *Pipeline) Run(ctx context.Context) (err error) { if pdebug.Enabled { g := pdebug.Marker("Pipeline.Run (%s)", ctx.Value("query")).BindError(&err) defer g.End() } p.mutex.Lock() defer p.mutex.Unlock() defer close(p.done) if p.src == nil { return errors.New("source must be non-nil") } if p.dst == nil { return errors.New("destination must be non-nil") } // Reset is called on the source/destination to effectively reset // any state changes that may have happened in the end of // the previous call to Run() p.src.Reset() p.dst.Reset() // Setup the Acceptors, effectively chaining all nodes // starting from the destination, working all the way // up to the Source var prevCh ChanOutput = ChanOutput(make(chan interface{})) go p.dst.Accept(ctx, prevCh, nil) for i := len(p.nodes) - 1; i >= 0; i-- { cur := p.nodes[i] ch := make(chan interface{}) // go cur.Accept(ctx, ch, prevCh) prevCh = ChanOutput(ch) } // And now tell the Source to send the values so data chugs // through the pipeline go p.src.Start(ctx, prevCh) // Wait till we're done <-p.dst.Done() return nil }
go
func (p *Pipeline) Run(ctx context.Context) (err error) { if pdebug.Enabled { g := pdebug.Marker("Pipeline.Run (%s)", ctx.Value("query")).BindError(&err) defer g.End() } p.mutex.Lock() defer p.mutex.Unlock() defer close(p.done) if p.src == nil { return errors.New("source must be non-nil") } if p.dst == nil { return errors.New("destination must be non-nil") } // Reset is called on the source/destination to effectively reset // any state changes that may have happened in the end of // the previous call to Run() p.src.Reset() p.dst.Reset() // Setup the Acceptors, effectively chaining all nodes // starting from the destination, working all the way // up to the Source var prevCh ChanOutput = ChanOutput(make(chan interface{})) go p.dst.Accept(ctx, prevCh, nil) for i := len(p.nodes) - 1; i >= 0; i-- { cur := p.nodes[i] ch := make(chan interface{}) // go cur.Accept(ctx, ch, prevCh) prevCh = ChanOutput(ch) } // And now tell the Source to send the values so data chugs // through the pipeline go p.src.Start(ctx, prevCh) // Wait till we're done <-p.dst.Done() return nil }
[ "func", "(", "p", "*", "Pipeline", ")", "Run", "(", "ctx", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "if", "pdebug", ".", "Enabled", "{", "g", ":=", "pdebug", ".", "Marker", "(", "\"", "\"", ",", "ctx", ".", "Value", "(", "\"", "\"", ")", ")", ".", "BindError", "(", "&", "err", ")", "\n", "defer", "g", ".", "End", "(", ")", "\n", "}", "\n", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n", "defer", "close", "(", "p", ".", "done", ")", "\n\n", "if", "p", ".", "src", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "p", ".", "dst", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Reset is called on the source/destination to effectively reset", "// any state changes that may have happened in the end of", "// the previous call to Run()", "p", ".", "src", ".", "Reset", "(", ")", "\n", "p", ".", "dst", ".", "Reset", "(", ")", "\n\n", "// Setup the Acceptors, effectively chaining all nodes", "// starting from the destination, working all the way", "// up to the Source", "var", "prevCh", "ChanOutput", "=", "ChanOutput", "(", "make", "(", "chan", "interface", "{", "}", ")", ")", "\n", "go", "p", ".", "dst", ".", "Accept", "(", "ctx", ",", "prevCh", ",", "nil", ")", "\n\n", "for", "i", ":=", "len", "(", "p", ".", "nodes", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "cur", ":=", "p", ".", "nodes", "[", "i", "]", "\n", "ch", ":=", "make", "(", "chan", "interface", "{", "}", ")", "//", "\n", "go", "cur", ".", "Accept", "(", "ctx", ",", "ch", ",", "prevCh", ")", "\n", "prevCh", "=", "ChanOutput", "(", "ch", ")", "\n", "}", "\n\n", "// And now tell the Source to send the values so data chugs", "// through the pipeline", "go", "p", ".", "src", ".", "Start", "(", "ctx", ",", "prevCh", ")", "\n\n", "// Wait till we're done", "<-", "p", ".", "dst", ".", "Done", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Run starts the processing. Mutator methods for `Pipeline` cannot be // called while `Run` is running.
[ "Run", "starts", "the", "processing", ".", "Mutator", "methods", "for", "Pipeline", "cannot", "be", "called", "while", "Run", "is", "running", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L111-L155
12,302
peco/peco
selection.go
Add
func (s *Selection) Add(l line.Line) { s.mutex.Lock() defer s.mutex.Unlock() s.tree.ReplaceOrInsert(l) }
go
func (s *Selection) Add(l line.Line) { s.mutex.Lock() defer s.mutex.Unlock() s.tree.ReplaceOrInsert(l) }
[ "func", "(", "s", "*", "Selection", ")", "Add", "(", "l", "line", ".", "Line", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n", "s", ".", "tree", ".", "ReplaceOrInsert", "(", "l", ")", "\n", "}" ]
// Add adds a new line to the selection. If the line already // exists in the selection, it is silently ignored
[ "Add", "adds", "a", "new", "line", "to", "the", "selection", ".", "If", "the", "line", "already", "exists", "in", "the", "selection", "it", "is", "silently", "ignored" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/selection.go#L17-L21
12,303
peco/peco
selection.go
Remove
func (s *Selection) Remove(l line.Line) { s.mutex.Lock() defer s.mutex.Unlock() s.tree.Delete(l) }
go
func (s *Selection) Remove(l line.Line) { s.mutex.Lock() defer s.mutex.Unlock() s.tree.Delete(l) }
[ "func", "(", "s", "*", "Selection", ")", "Remove", "(", "l", "line", ".", "Line", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n", "s", ".", "tree", ".", "Delete", "(", "l", ")", "\n", "}" ]
// Remove removes the specified line from the selection
[ "Remove", "removes", "the", "specified", "line", "from", "the", "selection" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/selection.go#L31-L35
12,304
peco/peco
layout.go
NewAnchorSettings
func NewAnchorSettings(screen Screen, anchor VerticalAnchor, offset int) *AnchorSettings { if !IsValidVerticalAnchor(anchor) { panic("Invalid vertical anchor specified") } return &AnchorSettings{ anchor: anchor, anchorOffset: offset, screen: screen, } }
go
func NewAnchorSettings(screen Screen, anchor VerticalAnchor, offset int) *AnchorSettings { if !IsValidVerticalAnchor(anchor) { panic("Invalid vertical anchor specified") } return &AnchorSettings{ anchor: anchor, anchorOffset: offset, screen: screen, } }
[ "func", "NewAnchorSettings", "(", "screen", "Screen", ",", "anchor", "VerticalAnchor", ",", "offset", "int", ")", "*", "AnchorSettings", "{", "if", "!", "IsValidVerticalAnchor", "(", "anchor", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "AnchorSettings", "{", "anchor", ":", "anchor", ",", "anchorOffset", ":", "offset", ",", "screen", ":", "screen", ",", "}", "\n", "}" ]
// NewAnchorSettings creates a new AnchorSetting struct. Panics if // an unknown VerticalAnchor is sent
[ "NewAnchorSettings", "creates", "a", "new", "AnchorSetting", "struct", ".", "Panics", "if", "an", "unknown", "VerticalAnchor", "is", "sent" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L39-L49
12,305
peco/peco
layout.go
AnchorPosition
func (as AnchorSettings) AnchorPosition() int { var pos int switch as.anchor { case AnchorTop: pos = as.anchorOffset case AnchorBottom: _, h := as.screen.Size() pos = int(h) - as.anchorOffset - 1 // -1 is required because y is 0 base, but h is 1 base default: panic("Unknown anchor type!") } return pos }
go
func (as AnchorSettings) AnchorPosition() int { var pos int switch as.anchor { case AnchorTop: pos = as.anchorOffset case AnchorBottom: _, h := as.screen.Size() pos = int(h) - as.anchorOffset - 1 // -1 is required because y is 0 base, but h is 1 base default: panic("Unknown anchor type!") } return pos }
[ "func", "(", "as", "AnchorSettings", ")", "AnchorPosition", "(", ")", "int", "{", "var", "pos", "int", "\n", "switch", "as", ".", "anchor", "{", "case", "AnchorTop", ":", "pos", "=", "as", ".", "anchorOffset", "\n", "case", "AnchorBottom", ":", "_", ",", "h", ":=", "as", ".", "screen", ".", "Size", "(", ")", "\n", "pos", "=", "int", "(", "h", ")", "-", "as", ".", "anchorOffset", "-", "1", "// -1 is required because y is 0 base, but h is 1 base", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "pos", "\n", "}" ]
// AnchorPosition returns the starting y-offset, based on the // anchor type and offset
[ "AnchorPosition", "returns", "the", "starting", "y", "-", "offset", "based", "on", "the", "anchor", "type", "and", "offset" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L53-L66
12,306
peco/peco
layout.go
NewUserPrompt
func NewUserPrompt(screen Screen, anchor VerticalAnchor, anchorOffset int, prompt string, styles *StyleSet) *UserPrompt { if len(prompt) <= 0 { // default prompt = "QUERY>" } promptLen := runewidth.StringWidth(prompt) return &UserPrompt{ AnchorSettings: NewAnchorSettings(screen, anchor, anchorOffset), prompt: prompt, promptLen: int(promptLen), styles: styles, } }
go
func NewUserPrompt(screen Screen, anchor VerticalAnchor, anchorOffset int, prompt string, styles *StyleSet) *UserPrompt { if len(prompt) <= 0 { // default prompt = "QUERY>" } promptLen := runewidth.StringWidth(prompt) return &UserPrompt{ AnchorSettings: NewAnchorSettings(screen, anchor, anchorOffset), prompt: prompt, promptLen: int(promptLen), styles: styles, } }
[ "func", "NewUserPrompt", "(", "screen", "Screen", ",", "anchor", "VerticalAnchor", ",", "anchorOffset", "int", ",", "prompt", "string", ",", "styles", "*", "StyleSet", ")", "*", "UserPrompt", "{", "if", "len", "(", "prompt", ")", "<=", "0", "{", "// default", "prompt", "=", "\"", "\"", "\n", "}", "\n", "promptLen", ":=", "runewidth", ".", "StringWidth", "(", "prompt", ")", "\n\n", "return", "&", "UserPrompt", "{", "AnchorSettings", ":", "NewAnchorSettings", "(", "screen", ",", "anchor", ",", "anchorOffset", ")", ",", "prompt", ":", "prompt", ",", "promptLen", ":", "int", "(", "promptLen", ")", ",", "styles", ":", "styles", ",", "}", "\n", "}" ]
// NewUserPrompt creates a new UserPrompt struct
[ "NewUserPrompt", "creates", "a", "new", "UserPrompt", "struct" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L69-L81
12,307
peco/peco
layout.go
NewStatusBar
func NewStatusBar(screen Screen, anchor VerticalAnchor, anchorOffset int, styles *StyleSet) *StatusBar { return &StatusBar{ AnchorSettings: NewAnchorSettings(screen, anchor, anchorOffset), clearTimer: nil, styles: styles, } }
go
func NewStatusBar(screen Screen, anchor VerticalAnchor, anchorOffset int, styles *StyleSet) *StatusBar { return &StatusBar{ AnchorSettings: NewAnchorSettings(screen, anchor, anchorOffset), clearTimer: nil, styles: styles, } }
[ "func", "NewStatusBar", "(", "screen", "Screen", ",", "anchor", "VerticalAnchor", ",", "anchorOffset", "int", ",", "styles", "*", "StyleSet", ")", "*", "StatusBar", "{", "return", "&", "StatusBar", "{", "AnchorSettings", ":", "NewAnchorSettings", "(", "screen", ",", "anchor", ",", "anchorOffset", ")", ",", "clearTimer", ":", "nil", ",", "styles", ":", "styles", ",", "}", "\n", "}" ]
// NewStatusBar creates a new StatusBar struct
[ "NewStatusBar", "creates", "a", "new", "StatusBar", "struct" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L207-L213
12,308
peco/peco
layout.go
NewListArea
func NewListArea(screen Screen, anchor VerticalAnchor, anchorOffset int, sortTopDown bool, styles *StyleSet) *ListArea { return &ListArea{ AnchorSettings: NewAnchorSettings(screen, anchor, anchorOffset), displayCache: []line.Line{}, dirty: false, sortTopDown: sortTopDown, styles: styles, } }
go
func NewListArea(screen Screen, anchor VerticalAnchor, anchorOffset int, sortTopDown bool, styles *StyleSet) *ListArea { return &ListArea{ AnchorSettings: NewAnchorSettings(screen, anchor, anchorOffset), displayCache: []line.Line{}, dirty: false, sortTopDown: sortTopDown, styles: styles, } }
[ "func", "NewListArea", "(", "screen", "Screen", ",", "anchor", "VerticalAnchor", ",", "anchorOffset", "int", ",", "sortTopDown", "bool", ",", "styles", "*", "StyleSet", ")", "*", "ListArea", "{", "return", "&", "ListArea", "{", "AnchorSettings", ":", "NewAnchorSettings", "(", "screen", ",", "anchor", ",", "anchorOffset", ")", ",", "displayCache", ":", "[", "]", "line", ".", "Line", "{", "}", ",", "dirty", ":", "false", ",", "sortTopDown", ":", "sortTopDown", ",", "styles", ":", "styles", ",", "}", "\n", "}" ]
// NewListArea creates a new ListArea struct
[ "NewListArea", "creates", "a", "new", "ListArea", "struct" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L291-L299
12,309
peco/peco
layout.go
NewBottomUpLayout
func NewBottomUpLayout(state *Peco) *BasicLayout { return &BasicLayout{ StatusBar: NewStatusBar(state.Screen(), AnchorBottom, 0+extraOffset, state.Styles()), // The prompt is at the bottom, above the status bar prompt: NewUserPrompt(state.Screen(), AnchorBottom, 1+extraOffset, state.Prompt(), state.Styles()), // The list area is at the bottom, above the prompt // It's displayed in bottom-to-top order list: NewListArea(state.Screen(), AnchorBottom, 2+extraOffset, false, state.Styles()), } }
go
func NewBottomUpLayout(state *Peco) *BasicLayout { return &BasicLayout{ StatusBar: NewStatusBar(state.Screen(), AnchorBottom, 0+extraOffset, state.Styles()), // The prompt is at the bottom, above the status bar prompt: NewUserPrompt(state.Screen(), AnchorBottom, 1+extraOffset, state.Prompt(), state.Styles()), // The list area is at the bottom, above the prompt // It's displayed in bottom-to-top order list: NewListArea(state.Screen(), AnchorBottom, 2+extraOffset, false, state.Styles()), } }
[ "func", "NewBottomUpLayout", "(", "state", "*", "Peco", ")", "*", "BasicLayout", "{", "return", "&", "BasicLayout", "{", "StatusBar", ":", "NewStatusBar", "(", "state", ".", "Screen", "(", ")", ",", "AnchorBottom", ",", "0", "+", "extraOffset", ",", "state", ".", "Styles", "(", ")", ")", ",", "// The prompt is at the bottom, above the status bar", "prompt", ":", "NewUserPrompt", "(", "state", ".", "Screen", "(", ")", ",", "AnchorBottom", ",", "1", "+", "extraOffset", ",", "state", ".", "Prompt", "(", ")", ",", "state", ".", "Styles", "(", ")", ")", ",", "// The list area is at the bottom, above the prompt", "// It's displayed in bottom-to-top order", "list", ":", "NewListArea", "(", "state", ".", "Screen", "(", ")", ",", "AnchorBottom", ",", "2", "+", "extraOffset", ",", "false", ",", "state", ".", "Styles", "(", ")", ")", ",", "}", "\n", "}" ]
// NewBottomUpLayout creates a new Layout in bottom-up format
[ "NewBottomUpLayout", "creates", "a", "new", "Layout", "in", "bottom", "-", "up", "format" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L625-L634
12,310
peco/peco
layout.go
CalculatePage
func (l *BasicLayout) CalculatePage(state *Peco, perPage int) error { if pdebug.Enabled { g := pdebug.Marker("BasicLayout.Calculate %d", perPage) defer g.End() } buf := state.CurrentLineBuffer() loc := state.Location() loc.SetPage((loc.LineNumber() / perPage) + 1) loc.SetOffset((loc.Page() - 1) * perPage) loc.SetPerPage(perPage) loc.SetTotal(buf.Size()) if loc.Total() == 0 { loc.SetMaxPage(1) } else { loc.SetMaxPage((loc.Total() + perPage - 1) / perPage) } if loc.MaxPage() < loc.Page() { if buf.Size() == 0 { // wait for targets return errors.New("no targets or query. nothing to do") } loc.SetLineNumber(loc.Offset()) } return nil }
go
func (l *BasicLayout) CalculatePage(state *Peco, perPage int) error { if pdebug.Enabled { g := pdebug.Marker("BasicLayout.Calculate %d", perPage) defer g.End() } buf := state.CurrentLineBuffer() loc := state.Location() loc.SetPage((loc.LineNumber() / perPage) + 1) loc.SetOffset((loc.Page() - 1) * perPage) loc.SetPerPage(perPage) loc.SetTotal(buf.Size()) if loc.Total() == 0 { loc.SetMaxPage(1) } else { loc.SetMaxPage((loc.Total() + perPage - 1) / perPage) } if loc.MaxPage() < loc.Page() { if buf.Size() == 0 { // wait for targets return errors.New("no targets or query. nothing to do") } loc.SetLineNumber(loc.Offset()) } return nil }
[ "func", "(", "l", "*", "BasicLayout", ")", "CalculatePage", "(", "state", "*", "Peco", ",", "perPage", "int", ")", "error", "{", "if", "pdebug", ".", "Enabled", "{", "g", ":=", "pdebug", ".", "Marker", "(", "\"", "\"", ",", "perPage", ")", "\n", "defer", "g", ".", "End", "(", ")", "\n", "}", "\n", "buf", ":=", "state", ".", "CurrentLineBuffer", "(", ")", "\n", "loc", ":=", "state", ".", "Location", "(", ")", "\n", "loc", ".", "SetPage", "(", "(", "loc", ".", "LineNumber", "(", ")", "/", "perPage", ")", "+", "1", ")", "\n", "loc", ".", "SetOffset", "(", "(", "loc", ".", "Page", "(", ")", "-", "1", ")", "*", "perPage", ")", "\n", "loc", ".", "SetPerPage", "(", "perPage", ")", "\n", "loc", ".", "SetTotal", "(", "buf", ".", "Size", "(", ")", ")", "\n\n", "if", "loc", ".", "Total", "(", ")", "==", "0", "{", "loc", ".", "SetMaxPage", "(", "1", ")", "\n", "}", "else", "{", "loc", ".", "SetMaxPage", "(", "(", "loc", ".", "Total", "(", ")", "+", "perPage", "-", "1", ")", "/", "perPage", ")", "\n", "}", "\n\n", "if", "loc", ".", "MaxPage", "(", ")", "<", "loc", ".", "Page", "(", ")", "{", "if", "buf", ".", "Size", "(", ")", "==", "0", "{", "// wait for targets", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "loc", ".", "SetLineNumber", "(", "loc", ".", "Offset", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CalculatePage calculates which page we're displaying
[ "CalculatePage", "calculates", "which", "page", "we", "re", "displaying" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L641-L668
12,311
peco/peco
layout.go
DrawScreen
func (l *BasicLayout) DrawScreen(state *Peco, options *DrawOptions) { if pdebug.Enabled { g := pdebug.Marker("BasicLayout.DrawScreen") defer g.End() } perPage := l.linesPerPage() if err := l.CalculatePage(state, perPage); err != nil { return } l.DrawPrompt(state) l.list.Draw(state, l, perPage, options) if err := l.screen.Flush(); err != nil { return } }
go
func (l *BasicLayout) DrawScreen(state *Peco, options *DrawOptions) { if pdebug.Enabled { g := pdebug.Marker("BasicLayout.DrawScreen") defer g.End() } perPage := l.linesPerPage() if err := l.CalculatePage(state, perPage); err != nil { return } l.DrawPrompt(state) l.list.Draw(state, l, perPage, options) if err := l.screen.Flush(); err != nil { return } }
[ "func", "(", "l", "*", "BasicLayout", ")", "DrawScreen", "(", "state", "*", "Peco", ",", "options", "*", "DrawOptions", ")", "{", "if", "pdebug", ".", "Enabled", "{", "g", ":=", "pdebug", ".", "Marker", "(", "\"", "\"", ")", "\n", "defer", "g", ".", "End", "(", ")", "\n", "}", "\n\n", "perPage", ":=", "l", ".", "linesPerPage", "(", ")", "\n\n", "if", "err", ":=", "l", ".", "CalculatePage", "(", "state", ",", "perPage", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "l", ".", "DrawPrompt", "(", "state", ")", "\n", "l", ".", "list", ".", "Draw", "(", "state", ",", "l", ",", "perPage", ",", "options", ")", "\n\n", "if", "err", ":=", "l", ".", "screen", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}" ]
// DrawScreen draws the entire screen
[ "DrawScreen", "draws", "the", "entire", "screen" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L676-L694
12,312
peco/peco
layout.go
MovePage
func (l *BasicLayout) MovePage(state *Peco, p PagingRequest) (moved bool) { switch p.Type() { case ToScrollLeft, ToScrollRight: moved = horizontalScroll(state, l, p) default: moved = verticalScroll(state, l, p) } return }
go
func (l *BasicLayout) MovePage(state *Peco, p PagingRequest) (moved bool) { switch p.Type() { case ToScrollLeft, ToScrollRight: moved = horizontalScroll(state, l, p) default: moved = verticalScroll(state, l, p) } return }
[ "func", "(", "l", "*", "BasicLayout", ")", "MovePage", "(", "state", "*", "Peco", ",", "p", "PagingRequest", ")", "(", "moved", "bool", ")", "{", "switch", "p", ".", "Type", "(", ")", "{", "case", "ToScrollLeft", ",", "ToScrollRight", ":", "moved", "=", "horizontalScroll", "(", "state", ",", "l", ",", "p", ")", "\n", "default", ":", "moved", "=", "verticalScroll", "(", "state", ",", "l", ",", "p", ")", "\n", "}", "\n", "return", "\n", "}" ]
// MovePage scrolls the screen
[ "MovePage", "scrolls", "the", "screen" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L720-L728
12,313
peco/peco
layout.go
horizontalScroll
func horizontalScroll(state *Peco, l *BasicLayout, p PagingRequest) bool { width, _ := state.screen.Size() loc := state.Location() if p.Type() == ToScrollRight { loc.SetColumn(loc.Column() + width/2) } else if loc.Column() > 0 { loc.SetColumn(loc.Column() - width/2) if loc.Column() < 0 { loc.SetColumn(0) } } else { return false } l.list.SetDirty(true) return true }
go
func horizontalScroll(state *Peco, l *BasicLayout, p PagingRequest) bool { width, _ := state.screen.Size() loc := state.Location() if p.Type() == ToScrollRight { loc.SetColumn(loc.Column() + width/2) } else if loc.Column() > 0 { loc.SetColumn(loc.Column() - width/2) if loc.Column() < 0 { loc.SetColumn(0) } } else { return false } l.list.SetDirty(true) return true }
[ "func", "horizontalScroll", "(", "state", "*", "Peco", ",", "l", "*", "BasicLayout", ",", "p", "PagingRequest", ")", "bool", "{", "width", ",", "_", ":=", "state", ".", "screen", ".", "Size", "(", ")", "\n", "loc", ":=", "state", ".", "Location", "(", ")", "\n", "if", "p", ".", "Type", "(", ")", "==", "ToScrollRight", "{", "loc", ".", "SetColumn", "(", "loc", ".", "Column", "(", ")", "+", "width", "/", "2", ")", "\n", "}", "else", "if", "loc", ".", "Column", "(", ")", ">", "0", "{", "loc", ".", "SetColumn", "(", "loc", ".", "Column", "(", ")", "-", "width", "/", "2", ")", "\n", "if", "loc", ".", "Column", "(", ")", "<", "0", "{", "loc", ".", "SetColumn", "(", "0", ")", "\n", "}", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n\n", "l", ".", "list", ".", "SetDirty", "(", "true", ")", "\n\n", "return", "true", "\n", "}" ]
// horizontalScroll scrolls screen horizontal
[ "horizontalScroll", "scrolls", "screen", "horizontal" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/layout.go#L861-L878
12,314
peco/peco
internal/util/tty_windows.go
TtyReady
func TtyReady() error { var err error _stdin, err := os.Open("CONIN$") if err != nil { return err } stdin = os.Stdin os.Stdin = _stdin syscall.Stdin = syscall.Handle(os.Stdin.Fd()) return errors.Wrap(setStdHandle(syscall.STD_INPUT_HANDLE, syscall.Stdin), "failed to check for TtyReady") }
go
func TtyReady() error { var err error _stdin, err := os.Open("CONIN$") if err != nil { return err } stdin = os.Stdin os.Stdin = _stdin syscall.Stdin = syscall.Handle(os.Stdin.Fd()) return errors.Wrap(setStdHandle(syscall.STD_INPUT_HANDLE, syscall.Stdin), "failed to check for TtyReady") }
[ "func", "TtyReady", "(", ")", "error", "{", "var", "err", "error", "\n\n", "_stdin", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "stdin", "=", "os", ".", "Stdin", "\n", "os", ".", "Stdin", "=", "_stdin", "\n", "syscall", ".", "Stdin", "=", "syscall", ".", "Handle", "(", "os", ".", "Stdin", ".", "Fd", "(", ")", ")", "\n\n", "return", "errors", ".", "Wrap", "(", "setStdHandle", "(", "syscall", ".", "STD_INPUT_HANDLE", ",", "syscall", ".", "Stdin", ")", ",", "\"", "\"", ")", "\n", "}" ]
// TtyReady checks if the tty is ready to go
[ "TtyReady", "checks", "if", "the", "tty", "is", "ready", "to", "go" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/internal/util/tty_windows.go#L47-L59
12,315
peco/peco
internal/util/tty_windows.go
TtyTerm
func TtyTerm() { os.Stdin = stdin syscall.Stdin = syscall.Handle(os.Stdin.Fd()) setStdHandle(syscall.STD_INPUT_HANDLE, syscall.Stdin) }
go
func TtyTerm() { os.Stdin = stdin syscall.Stdin = syscall.Handle(os.Stdin.Fd()) setStdHandle(syscall.STD_INPUT_HANDLE, syscall.Stdin) }
[ "func", "TtyTerm", "(", ")", "{", "os", ".", "Stdin", "=", "stdin", "\n", "syscall", ".", "Stdin", "=", "syscall", ".", "Handle", "(", "os", ".", "Stdin", ".", "Fd", "(", ")", ")", "\n", "setStdHandle", "(", "syscall", ".", "STD_INPUT_HANDLE", ",", "syscall", ".", "Stdin", ")", "\n", "}" ]
// TtyTerm restores any state, if necessary
[ "TtyTerm", "restores", "any", "state", "if", "necessary" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/internal/util/tty_windows.go#L62-L66
12,316
peco/peco
filter/regexp.go
NewRegexp
func NewRegexp() *Regexp { return &Regexp{ factory: &regexpQueryFactory{ compiled: make(map[string]regexpQuery), threshold: time.Minute, }, flags: regexpFlagList(defaultFlags), quotemeta: false, name: "Regexp", outCh: pipeline.ChanOutput(make(chan interface{})), } }
go
func NewRegexp() *Regexp { return &Regexp{ factory: &regexpQueryFactory{ compiled: make(map[string]regexpQuery), threshold: time.Minute, }, flags: regexpFlagList(defaultFlags), quotemeta: false, name: "Regexp", outCh: pipeline.ChanOutput(make(chan interface{})), } }
[ "func", "NewRegexp", "(", ")", "*", "Regexp", "{", "return", "&", "Regexp", "{", "factory", ":", "&", "regexpQueryFactory", "{", "compiled", ":", "make", "(", "map", "[", "string", "]", "regexpQuery", ")", ",", "threshold", ":", "time", ".", "Minute", ",", "}", ",", "flags", ":", "regexpFlagList", "(", "defaultFlags", ")", ",", "quotemeta", ":", "false", ",", "name", ":", "\"", "\"", ",", "outCh", ":", "pipeline", ".", "ChanOutput", "(", "make", "(", "chan", "interface", "{", "}", ")", ")", ",", "}", "\n", "}" ]
// NewRegexp creates a new regexp based filter
[ "NewRegexp", "creates", "a", "new", "regexp", "based", "filter" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/filter/regexp.go#L62-L73
12,317
peco/peco
filter/regexp.go
NewSmartCase
func NewSmartCase() *Regexp { rf := NewRegexp() rf.quotemeta = true rf.name = "SmartCase" rf.flags = regexpFlagFunc(func(q string) []string { if util.ContainsUpper(q) { return defaultFlags } return []string{"i"} }) return rf }
go
func NewSmartCase() *Regexp { rf := NewRegexp() rf.quotemeta = true rf.name = "SmartCase" rf.flags = regexpFlagFunc(func(q string) []string { if util.ContainsUpper(q) { return defaultFlags } return []string{"i"} }) return rf }
[ "func", "NewSmartCase", "(", ")", "*", "Regexp", "{", "rf", ":=", "NewRegexp", "(", ")", "\n", "rf", ".", "quotemeta", "=", "true", "\n", "rf", ".", "name", "=", "\"", "\"", "\n", "rf", ".", "flags", "=", "regexpFlagFunc", "(", "func", "(", "q", "string", ")", "[", "]", "string", "{", "if", "util", ".", "ContainsUpper", "(", "q", ")", "{", "return", "defaultFlags", "\n", "}", "\n", "return", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", ")", "\n", "return", "rf", "\n", "}" ]
// SmartCase turns ON the ignore-case flag in the regexp // if the query contains a upper-case character
[ "SmartCase", "turns", "ON", "the", "ignore", "-", "case", "flag", "in", "the", "regexp", "if", "the", "query", "contains", "a", "upper", "-", "case", "character" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/filter/regexp.go#L187-L198
12,318
peco/peco
line/raw.go
NewRaw
func NewRaw(id uint64, v string, enableSep bool) *Raw { rl := &Raw{ id: id, buf: v, sepLoc: -1, displayString: "", dirty: false, } if !enableSep { return rl } if i := strings.IndexByte(rl.buf, '\000'); i != -1 { rl.sepLoc = i } return rl }
go
func NewRaw(id uint64, v string, enableSep bool) *Raw { rl := &Raw{ id: id, buf: v, sepLoc: -1, displayString: "", dirty: false, } if !enableSep { return rl } if i := strings.IndexByte(rl.buf, '\000'); i != -1 { rl.sepLoc = i } return rl }
[ "func", "NewRaw", "(", "id", "uint64", ",", "v", "string", ",", "enableSep", "bool", ")", "*", "Raw", "{", "rl", ":=", "&", "Raw", "{", "id", ":", "id", ",", "buf", ":", "v", ",", "sepLoc", ":", "-", "1", ",", "displayString", ":", "\"", "\"", ",", "dirty", ":", "false", ",", "}", "\n\n", "if", "!", "enableSep", "{", "return", "rl", "\n", "}", "\n\n", "if", "i", ":=", "strings", ".", "IndexByte", "(", "rl", ".", "buf", ",", "'\\000'", ")", ";", "i", "!=", "-", "1", "{", "rl", ".", "sepLoc", "=", "i", "\n", "}", "\n", "return", "rl", "\n", "}" ]
// NewRaw creates a new Raw. The `enableSep` flag tells // it if we should search for a null character to split the // string to display and the string to emit upon selection of // of said line
[ "NewRaw", "creates", "a", "new", "Raw", ".", "The", "enableSep", "flag", "tells", "it", "if", "we", "should", "search", "for", "a", "null", "character", "to", "split", "the", "string", "to", "display", "and", "the", "string", "to", "emit", "upon", "selection", "of", "of", "said", "line" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/line/raw.go#L14-L31
12,319
peco/peco
line/raw.go
Less
func (rl *Raw) Less(b btree.Item) bool { return rl.id < b.(Line).ID() }
go
func (rl *Raw) Less(b btree.Item) bool { return rl.id < b.(Line).ID() }
[ "func", "(", "rl", "*", "Raw", ")", "Less", "(", "b", "btree", ".", "Item", ")", "bool", "{", "return", "rl", ".", "id", "<", "b", ".", "(", "Line", ")", ".", "ID", "(", ")", "\n", "}" ]
// Less implements the btree.Item interface
[ "Less", "implements", "the", "btree", ".", "Item", "interface" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/line/raw.go#L34-L36
12,320
peco/peco
line/raw.go
DisplayString
func (rl Raw) DisplayString() string { if rl.displayString != "" { return rl.displayString } if i := rl.sepLoc; i > -1 { rl.displayString = util.StripANSISequence(rl.buf[:i]) } else { rl.displayString = util.StripANSISequence(rl.buf) } return rl.displayString }
go
func (rl Raw) DisplayString() string { if rl.displayString != "" { return rl.displayString } if i := rl.sepLoc; i > -1 { rl.displayString = util.StripANSISequence(rl.buf[:i]) } else { rl.displayString = util.StripANSISequence(rl.buf) } return rl.displayString }
[ "func", "(", "rl", "Raw", ")", "DisplayString", "(", ")", "string", "{", "if", "rl", ".", "displayString", "!=", "\"", "\"", "{", "return", "rl", ".", "displayString", "\n", "}", "\n\n", "if", "i", ":=", "rl", ".", "sepLoc", ";", "i", ">", "-", "1", "{", "rl", ".", "displayString", "=", "util", ".", "StripANSISequence", "(", "rl", ".", "buf", "[", ":", "i", "]", ")", "\n", "}", "else", "{", "rl", ".", "displayString", "=", "util", ".", "StripANSISequence", "(", "rl", ".", "buf", ")", "\n", "}", "\n", "return", "rl", ".", "displayString", "\n", "}" ]
// DisplayString returns the string to be displayed
[ "DisplayString", "returns", "the", "string", "to", "be", "displayed" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/line/raw.go#L59-L70
12,321
peco/peco
config.go
Init
func (c *Config) Init() error { c.Keymap = make(map[string]string) c.InitialMatcher = IgnoreCaseMatch c.Style.Init() c.Prompt = "QUERY>" c.Layout = LayoutTypeTopDown return nil }
go
func (c *Config) Init() error { c.Keymap = make(map[string]string) c.InitialMatcher = IgnoreCaseMatch c.Style.Init() c.Prompt = "QUERY>" c.Layout = LayoutTypeTopDown return nil }
[ "func", "(", "c", "*", "Config", ")", "Init", "(", ")", "error", "{", "c", ".", "Keymap", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "c", ".", "InitialMatcher", "=", "IgnoreCaseMatch", "\n", "c", ".", "Style", ".", "Init", "(", ")", "\n", "c", ".", "Prompt", "=", "\"", "\"", "\n", "c", ".", "Layout", "=", "LayoutTypeTopDown", "\n", "return", "nil", "\n", "}" ]
// NewConfig creates a new Config
[ "NewConfig", "creates", "a", "new", "Config" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/config.go#L19-L26
12,322
peco/peco
config.go
ReadFilename
func (c *Config) ReadFilename(filename string) error { f, err := os.Open(filename) if err != nil { return errors.Wrapf(err, "failed to open file %s", filename) } defer f.Close() err = json.NewDecoder(f).Decode(c) if err != nil { return errors.Wrap(err, "failed to decode JSON") } if !IsValidLayoutType(LayoutType(c.Layout)) { return errors.Errorf("invalid layout type: %s", c.Layout) } if len(c.CustomMatcher) > 0 { fmt.Fprintf(os.Stderr, "'CustomMatcher' is deprecated. Use CustomFilter instead\n") for n, cfg := range c.CustomMatcher { if _, ok := c.CustomFilter[n]; ok { return errors.Errorf("failed to create CustomFilter: '%s' already exists. Refusing to overwrite with deprecated CustomMatcher config", n) } c.CustomFilter[n] = CustomFilterConfig{ Cmd: cfg[0], Args: cfg[1:], BufferThreshold: filter.DefaultCustomFilterBufferThreshold, } } } return nil }
go
func (c *Config) ReadFilename(filename string) error { f, err := os.Open(filename) if err != nil { return errors.Wrapf(err, "failed to open file %s", filename) } defer f.Close() err = json.NewDecoder(f).Decode(c) if err != nil { return errors.Wrap(err, "failed to decode JSON") } if !IsValidLayoutType(LayoutType(c.Layout)) { return errors.Errorf("invalid layout type: %s", c.Layout) } if len(c.CustomMatcher) > 0 { fmt.Fprintf(os.Stderr, "'CustomMatcher' is deprecated. Use CustomFilter instead\n") for n, cfg := range c.CustomMatcher { if _, ok := c.CustomFilter[n]; ok { return errors.Errorf("failed to create CustomFilter: '%s' already exists. Refusing to overwrite with deprecated CustomMatcher config", n) } c.CustomFilter[n] = CustomFilterConfig{ Cmd: cfg[0], Args: cfg[1:], BufferThreshold: filter.DefaultCustomFilterBufferThreshold, } } } return nil }
[ "func", "(", "c", "*", "Config", ")", "ReadFilename", "(", "filename", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "filename", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "err", "=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "IsValidLayoutType", "(", "LayoutType", "(", "c", ".", "Layout", ")", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "Layout", ")", "\n", "}", "\n\n", "if", "len", "(", "c", ".", "CustomMatcher", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ")", "\n\n", "for", "n", ",", "cfg", ":=", "range", "c", ".", "CustomMatcher", "{", "if", "_", ",", "ok", ":=", "c", ".", "CustomFilter", "[", "n", "]", ";", "ok", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "c", ".", "CustomFilter", "[", "n", "]", "=", "CustomFilterConfig", "{", "Cmd", ":", "cfg", "[", "0", "]", ",", "Args", ":", "cfg", "[", "1", ":", "]", ",", "BufferThreshold", ":", "filter", ".", "DefaultCustomFilterBufferThreshold", ",", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ReadFilename reads the config from the given file, and // does the appropriate processing, if any
[ "ReadFilename", "reads", "the", "config", "from", "the", "given", "file", "and", "does", "the", "appropriate", "processing", "if", "any" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/config.go#L30-L63
12,323
peco/peco
config.go
UnmarshalJSON
func (s *Style) UnmarshalJSON(buf []byte) error { raw := []string{} if err := json.Unmarshal(buf, &raw); err != nil { return errors.Wrapf(err, "failed to unmarshal Style") } return stringsToStyle(s, raw) }
go
func (s *Style) UnmarshalJSON(buf []byte) error { raw := []string{} if err := json.Unmarshal(buf, &raw); err != nil { return errors.Wrapf(err, "failed to unmarshal Style") } return stringsToStyle(s, raw) }
[ "func", "(", "s", "*", "Style", ")", "UnmarshalJSON", "(", "buf", "[", "]", "byte", ")", "error", "{", "raw", ":=", "[", "]", "string", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "buf", ",", "&", "raw", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "stringsToStyle", "(", "s", ",", "raw", ")", "\n", "}" ]
// UnmarshalJSON satisfies json.RawMessage.
[ "UnmarshalJSON", "satisfies", "json", ".", "RawMessage", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/config.go#L119-L125
12,324
peco/peco
config.go
LocateRcfile
func LocateRcfile(locater configLocateFunc) (string, error) { // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html // // Try in this order: // $XDG_CONFIG_HOME/peco/config.json // $XDG_CONFIG_DIR/peco/config.json (where XDG_CONFIG_DIR is listed in $XDG_CONFIG_DIRS) // ~/.peco/config.json home, uErr := homedirFunc() // Try dir supplied via env var if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" { if file, err := locater(filepath.Join(dir, "peco")); err == nil { return file, nil } } else if uErr == nil { // silently ignore failure for homedir() // Try "default" XDG location, is user is available if file, err := locater(filepath.Join(home, ".config", "peco")); err == nil { return file, nil } } // this standard does not take into consideration windows (duh) // while the spec says use ":" as the separator, Go provides us // with filepath.ListSeparator, so use it if dirs := os.Getenv("XDG_CONFIG_DIRS"); dirs != "" { for _, dir := range strings.Split(dirs, fmt.Sprintf("%c", filepath.ListSeparator)) { if file, err := locater(filepath.Join(dir, "peco")); err == nil { return file, nil } } } if uErr == nil { // silently ignore failure for homedir() if file, err := locater(filepath.Join(home, ".peco")); err == nil { return file, nil } } return "", errors.New("config file not found") }
go
func LocateRcfile(locater configLocateFunc) (string, error) { // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html // // Try in this order: // $XDG_CONFIG_HOME/peco/config.json // $XDG_CONFIG_DIR/peco/config.json (where XDG_CONFIG_DIR is listed in $XDG_CONFIG_DIRS) // ~/.peco/config.json home, uErr := homedirFunc() // Try dir supplied via env var if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" { if file, err := locater(filepath.Join(dir, "peco")); err == nil { return file, nil } } else if uErr == nil { // silently ignore failure for homedir() // Try "default" XDG location, is user is available if file, err := locater(filepath.Join(home, ".config", "peco")); err == nil { return file, nil } } // this standard does not take into consideration windows (duh) // while the spec says use ":" as the separator, Go provides us // with filepath.ListSeparator, so use it if dirs := os.Getenv("XDG_CONFIG_DIRS"); dirs != "" { for _, dir := range strings.Split(dirs, fmt.Sprintf("%c", filepath.ListSeparator)) { if file, err := locater(filepath.Join(dir, "peco")); err == nil { return file, nil } } } if uErr == nil { // silently ignore failure for homedir() if file, err := locater(filepath.Join(home, ".peco")); err == nil { return file, nil } } return "", errors.New("config file not found") }
[ "func", "LocateRcfile", "(", "locater", "configLocateFunc", ")", "(", "string", ",", "error", ")", "{", "// http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html", "//", "// Try in this order:", "//\t $XDG_CONFIG_HOME/peco/config.json", "// $XDG_CONFIG_DIR/peco/config.json (where XDG_CONFIG_DIR is listed in $XDG_CONFIG_DIRS)", "//\t ~/.peco/config.json", "home", ",", "uErr", ":=", "homedirFunc", "(", ")", "\n\n", "// Try dir supplied via env var", "if", "dir", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "dir", "!=", "\"", "\"", "{", "if", "file", ",", "err", ":=", "locater", "(", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", ")", ";", "err", "==", "nil", "{", "return", "file", ",", "nil", "\n", "}", "\n", "}", "else", "if", "uErr", "==", "nil", "{", "// silently ignore failure for homedir()", "// Try \"default\" XDG location, is user is available", "if", "file", ",", "err", ":=", "locater", "(", "filepath", ".", "Join", "(", "home", ",", "\"", "\"", ",", "\"", "\"", ")", ")", ";", "err", "==", "nil", "{", "return", "file", ",", "nil", "\n", "}", "\n", "}", "\n\n", "// this standard does not take into consideration windows (duh)", "// while the spec says use \":\" as the separator, Go provides us", "// with filepath.ListSeparator, so use it", "if", "dirs", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "dirs", "!=", "\"", "\"", "{", "for", "_", ",", "dir", ":=", "range", "strings", ".", "Split", "(", "dirs", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filepath", ".", "ListSeparator", ")", ")", "{", "if", "file", ",", "err", ":=", "locater", "(", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", ")", ";", "err", "==", "nil", "{", "return", "file", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "uErr", "==", "nil", "{", "// silently ignore failure for homedir()", "if", "file", ",", "err", ":=", "locater", "(", "filepath", ".", "Join", "(", "home", ",", "\"", "\"", ")", ")", ";", "err", "==", "nil", "{", "return", "file", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// LocateRcfile attempts to find the config file in various locations
[ "LocateRcfile", "attempts", "to", "find", "the", "config", "file", "in", "various", "locations" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/config.go#L170-L210
12,325
peco/peco
filter.go
flusher
func flusher(ctx context.Context, f filter.Filter, incoming chan []line.Line, done chan struct{}, out pipeline.ChanOutput) { if pdebug.Enabled { g := pdebug.Marker("flusher goroutine") defer g.End() } defer close(done) defer out.SendEndMark("end of filter") for { select { case <-ctx.Done(): return case buf, ok := <-incoming: if !ok { return } pdebug.Printf("flusher: %#v", buf) f.Apply(ctx, buf, out) buffer.ReleaseLineListBuf(buf) } } }
go
func flusher(ctx context.Context, f filter.Filter, incoming chan []line.Line, done chan struct{}, out pipeline.ChanOutput) { if pdebug.Enabled { g := pdebug.Marker("flusher goroutine") defer g.End() } defer close(done) defer out.SendEndMark("end of filter") for { select { case <-ctx.Done(): return case buf, ok := <-incoming: if !ok { return } pdebug.Printf("flusher: %#v", buf) f.Apply(ctx, buf, out) buffer.ReleaseLineListBuf(buf) } } }
[ "func", "flusher", "(", "ctx", "context", ".", "Context", ",", "f", "filter", ".", "Filter", ",", "incoming", "chan", "[", "]", "line", ".", "Line", ",", "done", "chan", "struct", "{", "}", ",", "out", "pipeline", ".", "ChanOutput", ")", "{", "if", "pdebug", ".", "Enabled", "{", "g", ":=", "pdebug", ".", "Marker", "(", "\"", "\"", ")", "\n", "defer", "g", ".", "End", "(", ")", "\n", "}", "\n\n", "defer", "close", "(", "done", ")", "\n", "defer", "out", ".", "SendEndMark", "(", "\"", "\"", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "case", "buf", ",", "ok", ":=", "<-", "incoming", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n", "pdebug", ".", "Printf", "(", "\"", "\"", ",", "buf", ")", "\n", "f", ".", "Apply", "(", "ctx", ",", "buf", ",", "out", ")", "\n", "buffer", ".", "ReleaseLineListBuf", "(", "buf", ")", "\n", "}", "\n", "}", "\n", "}" ]
// This flusher is run in a separate goroutine so that the filter can // run separately from accepting incoming messages
[ "This", "flusher", "is", "run", "in", "a", "separate", "goroutine", "so", "that", "the", "filter", "can", "run", "separately", "from", "accepting", "incoming", "messages" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/filter.go#L30-L52
12,326
peco/peco
filter.go
Loop
func (f *Filter) Loop(ctx context.Context, cancel func()) error { defer cancel() // previous holds the function that can cancel the previous // query. This is used when multiple queries come in succession // and the previous query is discarded anyway var mutex sync.Mutex var previous func() for { select { case <-ctx.Done(): return nil case q := <-f.state.Hub().QueryCh(): workctx, workcancel := context.WithCancel(ctx) mutex.Lock() if previous != nil { if pdebug.Enabled { pdebug.Printf("Canceling previous query") } previous() } previous = workcancel mutex.Unlock() f.state.Hub().SendStatusMsg("Running query...") go f.Work(workctx, q) } } }
go
func (f *Filter) Loop(ctx context.Context, cancel func()) error { defer cancel() // previous holds the function that can cancel the previous // query. This is used when multiple queries come in succession // and the previous query is discarded anyway var mutex sync.Mutex var previous func() for { select { case <-ctx.Done(): return nil case q := <-f.state.Hub().QueryCh(): workctx, workcancel := context.WithCancel(ctx) mutex.Lock() if previous != nil { if pdebug.Enabled { pdebug.Printf("Canceling previous query") } previous() } previous = workcancel mutex.Unlock() f.state.Hub().SendStatusMsg("Running query...") go f.Work(workctx, q) } } }
[ "func", "(", "f", "*", "Filter", ")", "Loop", "(", "ctx", "context", ".", "Context", ",", "cancel", "func", "(", ")", ")", "error", "{", "defer", "cancel", "(", ")", "\n\n", "// previous holds the function that can cancel the previous", "// query. This is used when multiple queries come in succession", "// and the previous query is discarded anyway", "var", "mutex", "sync", ".", "Mutex", "\n", "var", "previous", "func", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "case", "q", ":=", "<-", "f", ".", "state", ".", "Hub", "(", ")", ".", "QueryCh", "(", ")", ":", "workctx", ",", "workcancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n\n", "mutex", ".", "Lock", "(", ")", "\n", "if", "previous", "!=", "nil", "{", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "previous", "(", ")", "\n", "}", "\n", "previous", "=", "workcancel", "\n", "mutex", ".", "Unlock", "(", ")", "\n\n", "f", ".", "state", ".", "Hub", "(", ")", ".", "SendStatusMsg", "(", "\"", "\"", ")", "\n\n", "go", "f", ".", "Work", "(", "workctx", ",", "q", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Loop keeps watching for incoming queries, and upon receiving // a query, spawns a goroutine to do the heavy work. It also // checks for previously running queries, so we can avoid // running many goroutines doing the grep at the same time
[ "Loop", "keeps", "watching", "for", "incoming", "queries", "and", "upon", "receiving", "a", "query", "spawns", "a", "goroutine", "to", "do", "the", "heavy", "work", ".", "It", "also", "checks", "for", "previously", "running", "queries", "so", "we", "can", "avoid", "running", "many", "goroutines", "doing", "the", "grep", "at", "the", "same", "time" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/filter.go#L196-L226
12,327
peco/peco
page.go
Crop
func (pf PageCrop) Crop(in Buffer) *FilteredBuffer { return NewFilteredBuffer(in, pf.currentPage, pf.perPage) }
go
func (pf PageCrop) Crop(in Buffer) *FilteredBuffer { return NewFilteredBuffer(in, pf.currentPage, pf.perPage) }
[ "func", "(", "pf", "PageCrop", ")", "Crop", "(", "in", "Buffer", ")", "*", "FilteredBuffer", "{", "return", "NewFilteredBuffer", "(", "in", ",", "pf", ".", "currentPage", ",", "pf", ".", "perPage", ")", "\n", "}" ]
// Crop returns a new Buffer whose contents are // bound within the given range
[ "Crop", "returns", "a", "new", "Buffer", "whose", "contents", "are", "bound", "within", "the", "given", "range" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/page.go#L68-L70
12,328
peco/peco
source.go
Setup
func (s *Source) Setup(ctx context.Context, state *Peco) { s.setupOnce.Do(func() { done := make(chan struct{}) refresh := make(chan struct{}, 1) defer close(done) defer close(refresh) // And also, close the done channel so we can tell the consumers // we have finished reading everything defer close(s.setupDone) draw := func(state *Peco) { state.Hub().SendDraw(nil) } go func() { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { select { case <-done: draw(state) return case <-ticker.C: draw(state) } } }() // This sync.Once var is used to receive the notification // that there was at least 1 line read from the source // This is wrapped in a sync.Notify so we can safely call // it in multiple places var notify sync.Once notifycb := func() { // close the ready channel so others can be notified // that there's at least 1 line in the buffer state.Hub().SendStatusMsg("") close(s.ready) } // Register this to be called in a defer, just in case we could bailed // out without reading a single line. // Note: this will be a no-op if notify.Do has been called before defer notify.Do(notifycb) if pdebug.Enabled { pdebug.Printf("Source: using buffer size of %dkb", state.maxScanBufferSize) } scanbuf := make([]byte, state.maxScanBufferSize*1024) scanner := bufio.NewScanner(s.in) scanner.Buffer(scanbuf, state.maxScanBufferSize*1024) defer func() { if util.IsTty(s.in) { return } if closer, ok := s.in.(io.Closer); ok { closer.Close() } }() lines := make(chan string) go func() { var scanned int if pdebug.Enabled { defer func() { pdebug.Printf("Source scanned %d lines", scanned) }() } defer close(lines) for scanner.Scan() { lines <- scanner.Text() scanned++ } }() state.Hub().SendStatusMsg("Waiting for input...") readCount := 0 for loop := true; loop; { select { case <-ctx.Done(): if pdebug.Enabled { pdebug.Printf("Bailing out of source setup, because ctx was canceled") } return case l, ok := <-lines: if !ok { if pdebug.Enabled { pdebug.Printf("No more lines to read...") } loop = false break } readCount++ s.Append(line.NewRaw(s.idgen.Next(), l, s.enableSep)) notify.Do(notifycb) } } if pdebug.Enabled { pdebug.Printf("Read all %d lines from source", readCount) } }) }
go
func (s *Source) Setup(ctx context.Context, state *Peco) { s.setupOnce.Do(func() { done := make(chan struct{}) refresh := make(chan struct{}, 1) defer close(done) defer close(refresh) // And also, close the done channel so we can tell the consumers // we have finished reading everything defer close(s.setupDone) draw := func(state *Peco) { state.Hub().SendDraw(nil) } go func() { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { select { case <-done: draw(state) return case <-ticker.C: draw(state) } } }() // This sync.Once var is used to receive the notification // that there was at least 1 line read from the source // This is wrapped in a sync.Notify so we can safely call // it in multiple places var notify sync.Once notifycb := func() { // close the ready channel so others can be notified // that there's at least 1 line in the buffer state.Hub().SendStatusMsg("") close(s.ready) } // Register this to be called in a defer, just in case we could bailed // out without reading a single line. // Note: this will be a no-op if notify.Do has been called before defer notify.Do(notifycb) if pdebug.Enabled { pdebug.Printf("Source: using buffer size of %dkb", state.maxScanBufferSize) } scanbuf := make([]byte, state.maxScanBufferSize*1024) scanner := bufio.NewScanner(s.in) scanner.Buffer(scanbuf, state.maxScanBufferSize*1024) defer func() { if util.IsTty(s.in) { return } if closer, ok := s.in.(io.Closer); ok { closer.Close() } }() lines := make(chan string) go func() { var scanned int if pdebug.Enabled { defer func() { pdebug.Printf("Source scanned %d lines", scanned) }() } defer close(lines) for scanner.Scan() { lines <- scanner.Text() scanned++ } }() state.Hub().SendStatusMsg("Waiting for input...") readCount := 0 for loop := true; loop; { select { case <-ctx.Done(): if pdebug.Enabled { pdebug.Printf("Bailing out of source setup, because ctx was canceled") } return case l, ok := <-lines: if !ok { if pdebug.Enabled { pdebug.Printf("No more lines to read...") } loop = false break } readCount++ s.Append(line.NewRaw(s.idgen.Next(), l, s.enableSep)) notify.Do(notifycb) } } if pdebug.Enabled { pdebug.Printf("Read all %d lines from source", readCount) } }) }
[ "func", "(", "s", "*", "Source", ")", "Setup", "(", "ctx", "context", ".", "Context", ",", "state", "*", "Peco", ")", "{", "s", ".", "setupOnce", ".", "Do", "(", "func", "(", ")", "{", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "refresh", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "defer", "close", "(", "done", ")", "\n", "defer", "close", "(", "refresh", ")", "\n", "// And also, close the done channel so we can tell the consumers", "// we have finished reading everything", "defer", "close", "(", "s", ".", "setupDone", ")", "\n\n", "draw", ":=", "func", "(", "state", "*", "Peco", ")", "{", "state", ".", "Hub", "(", ")", ".", "SendDraw", "(", "nil", ")", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "100", "*", "time", ".", "Millisecond", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "done", ":", "draw", "(", "state", ")", "\n", "return", "\n", "case", "<-", "ticker", ".", "C", ":", "draw", "(", "state", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "// This sync.Once var is used to receive the notification", "// that there was at least 1 line read from the source", "// This is wrapped in a sync.Notify so we can safely call", "// it in multiple places", "var", "notify", "sync", ".", "Once", "\n", "notifycb", ":=", "func", "(", ")", "{", "// close the ready channel so others can be notified", "// that there's at least 1 line in the buffer", "state", ".", "Hub", "(", ")", ".", "SendStatusMsg", "(", "\"", "\"", ")", "\n", "close", "(", "s", ".", "ready", ")", "\n", "}", "\n\n", "// Register this to be called in a defer, just in case we could bailed", "// out without reading a single line.", "// Note: this will be a no-op if notify.Do has been called before", "defer", "notify", ".", "Do", "(", "notifycb", ")", "\n\n", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ",", "state", ".", "maxScanBufferSize", ")", "\n", "}", "\n", "scanbuf", ":=", "make", "(", "[", "]", "byte", ",", "state", ".", "maxScanBufferSize", "*", "1024", ")", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "s", ".", "in", ")", "\n", "scanner", ".", "Buffer", "(", "scanbuf", ",", "state", ".", "maxScanBufferSize", "*", "1024", ")", "\n", "defer", "func", "(", ")", "{", "if", "util", ".", "IsTty", "(", "s", ".", "in", ")", "{", "return", "\n", "}", "\n", "if", "closer", ",", "ok", ":=", "s", ".", "in", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "closer", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "lines", ":=", "make", "(", "chan", "string", ")", "\n", "go", "func", "(", ")", "{", "var", "scanned", "int", "\n", "if", "pdebug", ".", "Enabled", "{", "defer", "func", "(", ")", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ",", "scanned", ")", "}", "(", ")", "\n", "}", "\n\n", "defer", "close", "(", "lines", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "lines", "<-", "scanner", ".", "Text", "(", ")", "\n", "scanned", "++", "\n", "}", "\n", "}", "(", ")", "\n\n", "state", ".", "Hub", "(", ")", ".", "SendStatusMsg", "(", "\"", "\"", ")", "\n\n", "readCount", ":=", "0", "\n", "for", "loop", ":=", "true", ";", "loop", ";", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\n", "case", "l", ",", "ok", ":=", "<-", "lines", ":", "if", "!", "ok", "{", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "loop", "=", "false", "\n", "break", "\n", "}", "\n\n", "readCount", "++", "\n", "s", ".", "Append", "(", "line", ".", "NewRaw", "(", "s", ".", "idgen", ".", "Next", "(", ")", ",", "l", ",", "s", ".", "enableSep", ")", ")", "\n", "notify", ".", "Do", "(", "notifycb", ")", "\n", "}", "\n", "}", "\n\n", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ",", "readCount", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Setup reads from the input os.File.
[ "Setup", "reads", "from", "the", "input", "os", ".", "File", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/source.go#L39-L143
12,329
peco/peco
source.go
Reset
func (s *Source) Reset() { if pdebug.Enabled { g := pdebug.Marker("Source.Reset") defer g.End() } s.ChanOutput = pipeline.ChanOutput(make(chan interface{})) }
go
func (s *Source) Reset() { if pdebug.Enabled { g := pdebug.Marker("Source.Reset") defer g.End() } s.ChanOutput = pipeline.ChanOutput(make(chan interface{})) }
[ "func", "(", "s", "*", "Source", ")", "Reset", "(", ")", "{", "if", "pdebug", ".", "Enabled", "{", "g", ":=", "pdebug", ".", "Marker", "(", "\"", "\"", ")", "\n", "defer", "g", ".", "End", "(", ")", "\n", "}", "\n", "s", ".", "ChanOutput", "=", "pipeline", ".", "ChanOutput", "(", "make", "(", "chan", "interface", "{", "}", ")", ")", "\n", "}" ]
// Reset resets the state of the source object so that it // is ready to feed the filters
[ "Reset", "resets", "the", "state", "of", "the", "source", "object", "so", "that", "it", "is", "ready", "to", "feed", "the", "filters" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/source.go#L223-L229
12,330
qor/worker
scheduler.go
GetScheduleTime
func (schedule Schedule) GetScheduleTime() *time.Time { if scheduleTime := schedule.ScheduleTime; scheduleTime != nil { if scheduleTime.After(time.Now().Add(time.Minute)) { return scheduleTime } } return nil }
go
func (schedule Schedule) GetScheduleTime() *time.Time { if scheduleTime := schedule.ScheduleTime; scheduleTime != nil { if scheduleTime.After(time.Now().Add(time.Minute)) { return scheduleTime } } return nil }
[ "func", "(", "schedule", "Schedule", ")", "GetScheduleTime", "(", ")", "*", "time", ".", "Time", "{", "if", "scheduleTime", ":=", "schedule", ".", "ScheduleTime", ";", "scheduleTime", "!=", "nil", "{", "if", "scheduleTime", ".", "After", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Minute", ")", ")", "{", "return", "scheduleTime", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetScheduleTime get scheduled time
[ "GetScheduleTime", "get", "scheduled", "time" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/scheduler.go#L16-L23
12,331
qor/worker
cron.go
Add
func (cron *Cron) Add(job QorJobInterface) (err error) { cron.parseJobs() defer cron.writeCronJob() var binaryFile string if binaryFile, err = filepath.Abs(os.Args[0]); err == nil { var jobs []*cronJob for _, cronJob := range cron.Jobs { if cronJob.JobID != job.GetJobID() { jobs = append(jobs, cronJob) } } if scheduler, ok := job.GetArgument().(Scheduler); ok && scheduler.GetScheduleTime() != nil { scheduleTime := scheduler.GetScheduleTime().In(time.Local) job.SetStatus(JobStatusScheduled) currentPath, _ := os.Getwd() jobs = append(jobs, &cronJob{ JobID: job.GetJobID(), Command: fmt.Sprintf("%d %d %d %d * cd %v; %v --qor-job %v\n", scheduleTime.Minute(), scheduleTime.Hour(), scheduleTime.Day(), scheduleTime.Month(), currentPath, binaryFile, job.GetJobID()), }) } else { cmd := exec.Command(binaryFile, "--qor-job", job.GetJobID()) if err = cmd.Start(); err == nil { jobs = append(jobs, &cronJob{JobID: job.GetJobID(), Pid: cmd.Process.Pid}) cmd.Process.Release() } } cron.Jobs = jobs } return }
go
func (cron *Cron) Add(job QorJobInterface) (err error) { cron.parseJobs() defer cron.writeCronJob() var binaryFile string if binaryFile, err = filepath.Abs(os.Args[0]); err == nil { var jobs []*cronJob for _, cronJob := range cron.Jobs { if cronJob.JobID != job.GetJobID() { jobs = append(jobs, cronJob) } } if scheduler, ok := job.GetArgument().(Scheduler); ok && scheduler.GetScheduleTime() != nil { scheduleTime := scheduler.GetScheduleTime().In(time.Local) job.SetStatus(JobStatusScheduled) currentPath, _ := os.Getwd() jobs = append(jobs, &cronJob{ JobID: job.GetJobID(), Command: fmt.Sprintf("%d %d %d %d * cd %v; %v --qor-job %v\n", scheduleTime.Minute(), scheduleTime.Hour(), scheduleTime.Day(), scheduleTime.Month(), currentPath, binaryFile, job.GetJobID()), }) } else { cmd := exec.Command(binaryFile, "--qor-job", job.GetJobID()) if err = cmd.Start(); err == nil { jobs = append(jobs, &cronJob{JobID: job.GetJobID(), Pid: cmd.Process.Pid}) cmd.Process.Release() } } cron.Jobs = jobs } return }
[ "func", "(", "cron", "*", "Cron", ")", "Add", "(", "job", "QorJobInterface", ")", "(", "err", "error", ")", "{", "cron", ".", "parseJobs", "(", ")", "\n", "defer", "cron", ".", "writeCronJob", "(", ")", "\n\n", "var", "binaryFile", "string", "\n", "if", "binaryFile", ",", "err", "=", "filepath", ".", "Abs", "(", "os", ".", "Args", "[", "0", "]", ")", ";", "err", "==", "nil", "{", "var", "jobs", "[", "]", "*", "cronJob", "\n", "for", "_", ",", "cronJob", ":=", "range", "cron", ".", "Jobs", "{", "if", "cronJob", ".", "JobID", "!=", "job", ".", "GetJobID", "(", ")", "{", "jobs", "=", "append", "(", "jobs", ",", "cronJob", ")", "\n", "}", "\n", "}", "\n\n", "if", "scheduler", ",", "ok", ":=", "job", ".", "GetArgument", "(", ")", ".", "(", "Scheduler", ")", ";", "ok", "&&", "scheduler", ".", "GetScheduleTime", "(", ")", "!=", "nil", "{", "scheduleTime", ":=", "scheduler", ".", "GetScheduleTime", "(", ")", ".", "In", "(", "time", ".", "Local", ")", "\n", "job", ".", "SetStatus", "(", "JobStatusScheduled", ")", "\n\n", "currentPath", ",", "_", ":=", "os", ".", "Getwd", "(", ")", "\n", "jobs", "=", "append", "(", "jobs", ",", "&", "cronJob", "{", "JobID", ":", "job", ".", "GetJobID", "(", ")", ",", "Command", ":", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "scheduleTime", ".", "Minute", "(", ")", ",", "scheduleTime", ".", "Hour", "(", ")", ",", "scheduleTime", ".", "Day", "(", ")", ",", "scheduleTime", ".", "Month", "(", ")", ",", "currentPath", ",", "binaryFile", ",", "job", ".", "GetJobID", "(", ")", ")", ",", "}", ")", "\n", "}", "else", "{", "cmd", ":=", "exec", ".", "Command", "(", "binaryFile", ",", "\"", "\"", ",", "job", ".", "GetJobID", "(", ")", ")", "\n", "if", "err", "=", "cmd", ".", "Start", "(", ")", ";", "err", "==", "nil", "{", "jobs", "=", "append", "(", "jobs", ",", "&", "cronJob", "{", "JobID", ":", "job", ".", "GetJobID", "(", ")", ",", "Pid", ":", "cmd", ".", "Process", ".", "Pid", "}", ")", "\n", "cmd", ".", "Process", ".", "Release", "(", ")", "\n", "}", "\n", "}", "\n", "cron", ".", "Jobs", "=", "jobs", "\n", "}", "\n\n", "return", "\n", "}" ]
// Add a job to cron queue
[ "Add", "a", "job", "to", "cron", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/cron.go#L93-L126
12,332
qor/worker
cron.go
Run
func (cron *Cron) Run(qorJob QorJobInterface) error { job := qorJob.GetJob() if job.Handler != nil { go func() { sigint := make(chan os.Signal, 1) // interrupt signal sent from terminal signal.Notify(sigint, syscall.SIGINT) // sigterm signal sent from kubernetes signal.Notify(sigint, syscall.SIGTERM) i := <-sigint qorJob.SetProgressText(fmt.Sprintf("Worker killed by signal %s", i.String())) qorJob.SetStatus(JobStatusKilled) qorJob.StopReferesh() os.Exit(int(reflect.ValueOf(i).Int())) }() qorJob.StartReferesh() defer qorJob.StopReferesh() err := job.Handler(qorJob.GetSerializableArgument(qorJob), qorJob) if err == nil { cron.parseJobs() defer cron.writeCronJob() for _, cronJob := range cron.Jobs { if cronJob.JobID == qorJob.GetJobID() { cronJob.Delete = true } } } return err } return errors.New("no handler found for job " + job.Name) }
go
func (cron *Cron) Run(qorJob QorJobInterface) error { job := qorJob.GetJob() if job.Handler != nil { go func() { sigint := make(chan os.Signal, 1) // interrupt signal sent from terminal signal.Notify(sigint, syscall.SIGINT) // sigterm signal sent from kubernetes signal.Notify(sigint, syscall.SIGTERM) i := <-sigint qorJob.SetProgressText(fmt.Sprintf("Worker killed by signal %s", i.String())) qorJob.SetStatus(JobStatusKilled) qorJob.StopReferesh() os.Exit(int(reflect.ValueOf(i).Int())) }() qorJob.StartReferesh() defer qorJob.StopReferesh() err := job.Handler(qorJob.GetSerializableArgument(qorJob), qorJob) if err == nil { cron.parseJobs() defer cron.writeCronJob() for _, cronJob := range cron.Jobs { if cronJob.JobID == qorJob.GetJobID() { cronJob.Delete = true } } } return err } return errors.New("no handler found for job " + job.Name) }
[ "func", "(", "cron", "*", "Cron", ")", "Run", "(", "qorJob", "QorJobInterface", ")", "error", "{", "job", ":=", "qorJob", ".", "GetJob", "(", ")", "\n\n", "if", "job", ".", "Handler", "!=", "nil", "{", "go", "func", "(", ")", "{", "sigint", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n\n", "// interrupt signal sent from terminal", "signal", ".", "Notify", "(", "sigint", ",", "syscall", ".", "SIGINT", ")", "\n", "// sigterm signal sent from kubernetes", "signal", ".", "Notify", "(", "sigint", ",", "syscall", ".", "SIGTERM", ")", "\n\n", "i", ":=", "<-", "sigint", "\n\n", "qorJob", ".", "SetProgressText", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "String", "(", ")", ")", ")", "\n", "qorJob", ".", "SetStatus", "(", "JobStatusKilled", ")", "\n\n", "qorJob", ".", "StopReferesh", "(", ")", "\n", "os", ".", "Exit", "(", "int", "(", "reflect", ".", "ValueOf", "(", "i", ")", ".", "Int", "(", ")", ")", ")", "\n", "}", "(", ")", "\n\n", "qorJob", ".", "StartReferesh", "(", ")", "\n", "defer", "qorJob", ".", "StopReferesh", "(", ")", "\n\n", "err", ":=", "job", ".", "Handler", "(", "qorJob", ".", "GetSerializableArgument", "(", "qorJob", ")", ",", "qorJob", ")", "\n", "if", "err", "==", "nil", "{", "cron", ".", "parseJobs", "(", ")", "\n", "defer", "cron", ".", "writeCronJob", "(", ")", "\n", "for", "_", ",", "cronJob", ":=", "range", "cron", ".", "Jobs", "{", "if", "cronJob", ".", "JobID", "==", "qorJob", ".", "GetJobID", "(", ")", "{", "cronJob", ".", "Delete", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "return", "errors", ".", "New", "(", "\"", "\"", "+", "job", ".", "Name", ")", "\n", "}" ]
// Run a job from cron queue
[ "Run", "a", "job", "from", "cron", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/cron.go#L129-L167
12,333
qor/worker
cron.go
Kill
func (cron *Cron) Kill(job QorJobInterface) (err error) { cron.parseJobs() defer cron.writeCronJob() for _, cronJob := range cron.Jobs { if cronJob.JobID == job.GetJobID() { if process, err := os.FindProcess(cronJob.Pid); err == nil { if err = process.Kill(); err == nil { cronJob.Delete = true return nil } } return err } } return errors.New("failed to find job") }
go
func (cron *Cron) Kill(job QorJobInterface) (err error) { cron.parseJobs() defer cron.writeCronJob() for _, cronJob := range cron.Jobs { if cronJob.JobID == job.GetJobID() { if process, err := os.FindProcess(cronJob.Pid); err == nil { if err = process.Kill(); err == nil { cronJob.Delete = true return nil } } return err } } return errors.New("failed to find job") }
[ "func", "(", "cron", "*", "Cron", ")", "Kill", "(", "job", "QorJobInterface", ")", "(", "err", "error", ")", "{", "cron", ".", "parseJobs", "(", ")", "\n", "defer", "cron", ".", "writeCronJob", "(", ")", "\n\n", "for", "_", ",", "cronJob", ":=", "range", "cron", ".", "Jobs", "{", "if", "cronJob", ".", "JobID", "==", "job", ".", "GetJobID", "(", ")", "{", "if", "process", ",", "err", ":=", "os", ".", "FindProcess", "(", "cronJob", ".", "Pid", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "process", ".", "Kill", "(", ")", ";", "err", "==", "nil", "{", "cronJob", ".", "Delete", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Kill a job from cron queue
[ "Kill", "a", "job", "from", "cron", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/cron.go#L170-L186
12,334
qor/worker
cron.go
Remove
func (cron *Cron) Remove(job QorJobInterface) error { cron.parseJobs() defer cron.writeCronJob() for _, cronJob := range cron.Jobs { if cronJob.JobID == job.GetJobID() { if cronJob.Pid == 0 { cronJob.Delete = true return nil } return errors.New("failed to remove current job as it is running") } } return errors.New("failed to find job") }
go
func (cron *Cron) Remove(job QorJobInterface) error { cron.parseJobs() defer cron.writeCronJob() for _, cronJob := range cron.Jobs { if cronJob.JobID == job.GetJobID() { if cronJob.Pid == 0 { cronJob.Delete = true return nil } return errors.New("failed to remove current job as it is running") } } return errors.New("failed to find job") }
[ "func", "(", "cron", "*", "Cron", ")", "Remove", "(", "job", "QorJobInterface", ")", "error", "{", "cron", ".", "parseJobs", "(", ")", "\n", "defer", "cron", ".", "writeCronJob", "(", ")", "\n\n", "for", "_", ",", "cronJob", ":=", "range", "cron", ".", "Jobs", "{", "if", "cronJob", ".", "JobID", "==", "job", ".", "GetJobID", "(", ")", "{", "if", "cronJob", ".", "Pid", "==", "0", "{", "cronJob", ".", "Delete", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Remove a job from cron queue
[ "Remove", "a", "job", "from", "cron", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/cron.go#L189-L203
12,335
qor/worker
worker.go
New
func New(config ...*Config) *Worker { var cfg = &Config{} if len(config) > 0 { cfg = config[0] } if cfg.Job == nil { cfg.Job = &QorJob{} } if cfg.Queue == nil { cfg.Queue = NewCronQueue() } return &Worker{Config: cfg} }
go
func New(config ...*Config) *Worker { var cfg = &Config{} if len(config) > 0 { cfg = config[0] } if cfg.Job == nil { cfg.Job = &QorJob{} } if cfg.Queue == nil { cfg.Queue = NewCronQueue() } return &Worker{Config: cfg} }
[ "func", "New", "(", "config", "...", "*", "Config", ")", "*", "Worker", "{", "var", "cfg", "=", "&", "Config", "{", "}", "\n", "if", "len", "(", "config", ")", ">", "0", "{", "cfg", "=", "config", "[", "0", "]", "\n", "}", "\n\n", "if", "cfg", ".", "Job", "==", "nil", "{", "cfg", ".", "Job", "=", "&", "QorJob", "{", "}", "\n", "}", "\n\n", "if", "cfg", ".", "Queue", "==", "nil", "{", "cfg", ".", "Queue", "=", "NewCronQueue", "(", ")", "\n", "}", "\n\n", "return", "&", "Worker", "{", "Config", ":", "cfg", "}", "\n", "}" ]
// New create Worker with Config
[ "New", "create", "Worker", "with", "Config" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L35-L50
12,336
qor/worker
worker.go
ConfigureQorResourceBeforeInitialize
func (worker *Worker) ConfigureQorResourceBeforeInitialize(res resource.Resourcer) { if res, ok := res.(*admin.Resource); ok { res.GetAdmin().RegisterViewPath("github.com/qor/worker/views") res.UseTheme("worker") worker.Admin = res.GetAdmin() worker.JobResource = worker.Admin.NewResource(worker.Config.Job) worker.JobResource.UseTheme("worker") worker.JobResource.Meta(&admin.Meta{Name: "Name", Valuer: func(record interface{}, context *qor.Context) interface{} { return record.(QorJobInterface).GetJobName() }}) worker.JobResource.IndexAttrs("ID", "Name", "Status", "CreatedAt") worker.JobResource.Name = res.Name for _, status := range []string{JobStatusScheduled, JobStatusNew, JobStatusRunning, JobStatusDone, JobStatusException} { var status = status worker.JobResource.Scope(&admin.Scope{Name: status, Handler: func(db *gorm.DB, ctx *qor.Context) *gorm.DB { return db.Where("status = ?", status) }}) } // default scope worker.JobResource.Scope(&admin.Scope{ Handler: func(db *gorm.DB, ctx *qor.Context) *gorm.DB { if jobName := ctx.Request.URL.Query().Get("job"); jobName != "" { return db.Where("kind = ?", jobName) } if groupName := ctx.Request.URL.Query().Get("group"); groupName != "" { var jobNames []string for _, job := range worker.Jobs { if groupName == job.Group { jobNames = append(jobNames, job.Name) } } if len(jobNames) > 0 { return db.Where("kind IN (?)", jobNames) } return db.Where("kind IS NULL") } { var jobNames []string for _, job := range worker.Jobs { jobNames = append(jobNames, job.Name) } if len(jobNames) > 0 { return db.Where("kind IN (?)", jobNames) } } return db }, Default: true, }) // Auto Migration worker.Admin.DB.AutoMigrate(worker.Config.Job) // Configure jobs for _, job := range worker.Jobs { if job.Resource == nil { job.Resource = worker.Admin.NewResource(worker.JobResource.Value) } } } }
go
func (worker *Worker) ConfigureQorResourceBeforeInitialize(res resource.Resourcer) { if res, ok := res.(*admin.Resource); ok { res.GetAdmin().RegisterViewPath("github.com/qor/worker/views") res.UseTheme("worker") worker.Admin = res.GetAdmin() worker.JobResource = worker.Admin.NewResource(worker.Config.Job) worker.JobResource.UseTheme("worker") worker.JobResource.Meta(&admin.Meta{Name: "Name", Valuer: func(record interface{}, context *qor.Context) interface{} { return record.(QorJobInterface).GetJobName() }}) worker.JobResource.IndexAttrs("ID", "Name", "Status", "CreatedAt") worker.JobResource.Name = res.Name for _, status := range []string{JobStatusScheduled, JobStatusNew, JobStatusRunning, JobStatusDone, JobStatusException} { var status = status worker.JobResource.Scope(&admin.Scope{Name: status, Handler: func(db *gorm.DB, ctx *qor.Context) *gorm.DB { return db.Where("status = ?", status) }}) } // default scope worker.JobResource.Scope(&admin.Scope{ Handler: func(db *gorm.DB, ctx *qor.Context) *gorm.DB { if jobName := ctx.Request.URL.Query().Get("job"); jobName != "" { return db.Where("kind = ?", jobName) } if groupName := ctx.Request.URL.Query().Get("group"); groupName != "" { var jobNames []string for _, job := range worker.Jobs { if groupName == job.Group { jobNames = append(jobNames, job.Name) } } if len(jobNames) > 0 { return db.Where("kind IN (?)", jobNames) } return db.Where("kind IS NULL") } { var jobNames []string for _, job := range worker.Jobs { jobNames = append(jobNames, job.Name) } if len(jobNames) > 0 { return db.Where("kind IN (?)", jobNames) } } return db }, Default: true, }) // Auto Migration worker.Admin.DB.AutoMigrate(worker.Config.Job) // Configure jobs for _, job := range worker.Jobs { if job.Resource == nil { job.Resource = worker.Admin.NewResource(worker.JobResource.Value) } } } }
[ "func", "(", "worker", "*", "Worker", ")", "ConfigureQorResourceBeforeInitialize", "(", "res", "resource", ".", "Resourcer", ")", "{", "if", "res", ",", "ok", ":=", "res", ".", "(", "*", "admin", ".", "Resource", ")", ";", "ok", "{", "res", ".", "GetAdmin", "(", ")", ".", "RegisterViewPath", "(", "\"", "\"", ")", "\n", "res", ".", "UseTheme", "(", "\"", "\"", ")", "\n\n", "worker", ".", "Admin", "=", "res", ".", "GetAdmin", "(", ")", "\n", "worker", ".", "JobResource", "=", "worker", ".", "Admin", ".", "NewResource", "(", "worker", ".", "Config", ".", "Job", ")", "\n", "worker", ".", "JobResource", ".", "UseTheme", "(", "\"", "\"", ")", "\n", "worker", ".", "JobResource", ".", "Meta", "(", "&", "admin", ".", "Meta", "{", "Name", ":", "\"", "\"", ",", "Valuer", ":", "func", "(", "record", "interface", "{", "}", ",", "context", "*", "qor", ".", "Context", ")", "interface", "{", "}", "{", "return", "record", ".", "(", "QorJobInterface", ")", ".", "GetJobName", "(", ")", "\n", "}", "}", ")", "\n", "worker", ".", "JobResource", ".", "IndexAttrs", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "worker", ".", "JobResource", ".", "Name", "=", "res", ".", "Name", "\n\n", "for", "_", ",", "status", ":=", "range", "[", "]", "string", "{", "JobStatusScheduled", ",", "JobStatusNew", ",", "JobStatusRunning", ",", "JobStatusDone", ",", "JobStatusException", "}", "{", "var", "status", "=", "status", "\n", "worker", ".", "JobResource", ".", "Scope", "(", "&", "admin", ".", "Scope", "{", "Name", ":", "status", ",", "Handler", ":", "func", "(", "db", "*", "gorm", ".", "DB", ",", "ctx", "*", "qor", ".", "Context", ")", "*", "gorm", ".", "DB", "{", "return", "db", ".", "Where", "(", "\"", "\"", ",", "status", ")", "\n", "}", "}", ")", "\n", "}", "\n\n", "// default scope", "worker", ".", "JobResource", ".", "Scope", "(", "&", "admin", ".", "Scope", "{", "Handler", ":", "func", "(", "db", "*", "gorm", ".", "DB", ",", "ctx", "*", "qor", ".", "Context", ")", "*", "gorm", ".", "DB", "{", "if", "jobName", ":=", "ctx", ".", "Request", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", ";", "jobName", "!=", "\"", "\"", "{", "return", "db", ".", "Where", "(", "\"", "\"", ",", "jobName", ")", "\n", "}", "\n\n", "if", "groupName", ":=", "ctx", ".", "Request", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", ";", "groupName", "!=", "\"", "\"", "{", "var", "jobNames", "[", "]", "string", "\n", "for", "_", ",", "job", ":=", "range", "worker", ".", "Jobs", "{", "if", "groupName", "==", "job", ".", "Group", "{", "jobNames", "=", "append", "(", "jobNames", ",", "job", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "jobNames", ")", ">", "0", "{", "return", "db", ".", "Where", "(", "\"", "\"", ",", "jobNames", ")", "\n", "}", "\n", "return", "db", ".", "Where", "(", "\"", "\"", ")", "\n", "}", "\n\n", "{", "var", "jobNames", "[", "]", "string", "\n", "for", "_", ",", "job", ":=", "range", "worker", ".", "Jobs", "{", "jobNames", "=", "append", "(", "jobNames", ",", "job", ".", "Name", ")", "\n", "}", "\n", "if", "len", "(", "jobNames", ")", ">", "0", "{", "return", "db", ".", "Where", "(", "\"", "\"", ",", "jobNames", ")", "\n", "}", "\n", "}", "\n\n", "return", "db", "\n", "}", ",", "Default", ":", "true", ",", "}", ")", "\n\n", "// Auto Migration", "worker", ".", "Admin", ".", "DB", ".", "AutoMigrate", "(", "worker", ".", "Config", ".", "Job", ")", "\n\n", "// Configure jobs", "for", "_", ",", "job", ":=", "range", "worker", ".", "Jobs", "{", "if", "job", ".", "Resource", "==", "nil", "{", "job", ".", "Resource", "=", "worker", ".", "Admin", ".", "NewResource", "(", "worker", ".", "JobResource", ".", "Value", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// ConfigureQorResourceBeforeInitialize a method used to config Worker for qor admin
[ "ConfigureQorResourceBeforeInitialize", "a", "method", "used", "to", "config", "Worker", "for", "qor", "admin" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L68-L134
12,337
qor/worker
worker.go
RegisterJob
func (worker *Worker) RegisterJob(job *Job) error { if worker.mounted { debug.PrintStack() fmt.Printf("Job should be registered before Worker mounted into admin, but %v is registered after that", job.Name) } job.Worker = worker worker.Jobs = append(worker.Jobs, job) return nil }
go
func (worker *Worker) RegisterJob(job *Job) error { if worker.mounted { debug.PrintStack() fmt.Printf("Job should be registered before Worker mounted into admin, but %v is registered after that", job.Name) } job.Worker = worker worker.Jobs = append(worker.Jobs, job) return nil }
[ "func", "(", "worker", "*", "Worker", ")", "RegisterJob", "(", "job", "*", "Job", ")", "error", "{", "if", "worker", ".", "mounted", "{", "debug", ".", "PrintStack", "(", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "job", ".", "Name", ")", "\n", "}", "\n\n", "job", ".", "Worker", "=", "worker", "\n", "worker", ".", "Jobs", "=", "append", "(", "worker", ".", "Jobs", ",", "job", ")", "\n", "return", "nil", "\n", "}" ]
// RegisterJob register a job into Worker
[ "RegisterJob", "register", "a", "job", "into", "Worker" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L204-L213
12,338
qor/worker
worker.go
GetRegisteredJob
func (worker *Worker) GetRegisteredJob(name string) *Job { for _, job := range worker.Jobs { if job.Name == name { return job } } return nil }
go
func (worker *Worker) GetRegisteredJob(name string) *Job { for _, job := range worker.Jobs { if job.Name == name { return job } } return nil }
[ "func", "(", "worker", "*", "Worker", ")", "GetRegisteredJob", "(", "name", "string", ")", "*", "Job", "{", "for", "_", ",", "job", ":=", "range", "worker", ".", "Jobs", "{", "if", "job", ".", "Name", "==", "name", "{", "return", "job", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetRegisteredJob register a job into Worker
[ "GetRegisteredJob", "register", "a", "job", "into", "Worker" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L216-L223
12,339
qor/worker
worker.go
GetJob
func (worker *Worker) GetJob(jobID string) (QorJobInterface, error) { qorJob := worker.JobResource.NewStruct().(QorJobInterface) context := worker.Admin.NewContext(nil, nil) context.ResourceID = jobID context.Resource = worker.JobResource if err := worker.JobResource.FindOneHandler(qorJob, nil, context.Context); err == nil { for _, job := range worker.Jobs { if job.Name == qorJob.GetJobName() { qorJob.SetJob(job) return qorJob, nil } } return nil, fmt.Errorf("failed to load job: %v, unregistered job type: %v", jobID, qorJob.GetJobName()) } return nil, fmt.Errorf("failed to find job: %v", jobID) }
go
func (worker *Worker) GetJob(jobID string) (QorJobInterface, error) { qorJob := worker.JobResource.NewStruct().(QorJobInterface) context := worker.Admin.NewContext(nil, nil) context.ResourceID = jobID context.Resource = worker.JobResource if err := worker.JobResource.FindOneHandler(qorJob, nil, context.Context); err == nil { for _, job := range worker.Jobs { if job.Name == qorJob.GetJobName() { qorJob.SetJob(job) return qorJob, nil } } return nil, fmt.Errorf("failed to load job: %v, unregistered job type: %v", jobID, qorJob.GetJobName()) } return nil, fmt.Errorf("failed to find job: %v", jobID) }
[ "func", "(", "worker", "*", "Worker", ")", "GetJob", "(", "jobID", "string", ")", "(", "QorJobInterface", ",", "error", ")", "{", "qorJob", ":=", "worker", ".", "JobResource", ".", "NewStruct", "(", ")", ".", "(", "QorJobInterface", ")", "\n\n", "context", ":=", "worker", ".", "Admin", ".", "NewContext", "(", "nil", ",", "nil", ")", "\n", "context", ".", "ResourceID", "=", "jobID", "\n", "context", ".", "Resource", "=", "worker", ".", "JobResource", "\n\n", "if", "err", ":=", "worker", ".", "JobResource", ".", "FindOneHandler", "(", "qorJob", ",", "nil", ",", "context", ".", "Context", ")", ";", "err", "==", "nil", "{", "for", "_", ",", "job", ":=", "range", "worker", ".", "Jobs", "{", "if", "job", ".", "Name", "==", "qorJob", ".", "GetJobName", "(", ")", "{", "qorJob", ".", "SetJob", "(", "job", ")", "\n", "return", "qorJob", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "jobID", ",", "qorJob", ".", "GetJobName", "(", ")", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "jobID", ")", "\n", "}" ]
// GetJob get job with id
[ "GetJob", "get", "job", "with", "id" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L226-L243
12,340
qor/worker
worker.go
AddJob
func (worker *Worker) AddJob(qorJob QorJobInterface) error { return worker.Queue.Add(qorJob) }
go
func (worker *Worker) AddJob(qorJob QorJobInterface) error { return worker.Queue.Add(qorJob) }
[ "func", "(", "worker", "*", "Worker", ")", "AddJob", "(", "qorJob", "QorJobInterface", ")", "error", "{", "return", "worker", ".", "Queue", ".", "Add", "(", "qorJob", ")", "\n", "}" ]
// AddJob add job to worker
[ "AddJob", "add", "job", "to", "worker" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L246-L248
12,341
qor/worker
worker.go
RunJob
func (worker *Worker) RunJob(jobID string) error { qorJob, err := worker.GetJob(jobID) if qorJob != nil && err == nil { defer func() { if r := recover(); r != nil { qorJob.AddLog(string(debug.Stack())) qorJob.SetProgressText(fmt.Sprint(r)) qorJob.SetStatus(JobStatusException) } }() if qorJob.GetStatus() != JobStatusNew && qorJob.GetStatus() != JobStatusScheduled { return errors.New("invalid job status, current status: " + qorJob.GetStatus()) } if err = qorJob.SetStatus(JobStatusRunning); err == nil { if err = qorJob.GetJob().GetQueue().Run(qorJob); err == nil { return qorJob.SetStatus(JobStatusDone) } qorJob.SetProgressText(err.Error()) qorJob.SetStatus(JobStatusException) } } return err }
go
func (worker *Worker) RunJob(jobID string) error { qorJob, err := worker.GetJob(jobID) if qorJob != nil && err == nil { defer func() { if r := recover(); r != nil { qorJob.AddLog(string(debug.Stack())) qorJob.SetProgressText(fmt.Sprint(r)) qorJob.SetStatus(JobStatusException) } }() if qorJob.GetStatus() != JobStatusNew && qorJob.GetStatus() != JobStatusScheduled { return errors.New("invalid job status, current status: " + qorJob.GetStatus()) } if err = qorJob.SetStatus(JobStatusRunning); err == nil { if err = qorJob.GetJob().GetQueue().Run(qorJob); err == nil { return qorJob.SetStatus(JobStatusDone) } qorJob.SetProgressText(err.Error()) qorJob.SetStatus(JobStatusException) } } return err }
[ "func", "(", "worker", "*", "Worker", ")", "RunJob", "(", "jobID", "string", ")", "error", "{", "qorJob", ",", "err", ":=", "worker", ".", "GetJob", "(", "jobID", ")", "\n\n", "if", "qorJob", "!=", "nil", "&&", "err", "==", "nil", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "qorJob", ".", "AddLog", "(", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", "\n", "qorJob", ".", "SetProgressText", "(", "fmt", ".", "Sprint", "(", "r", ")", ")", "\n", "qorJob", ".", "SetStatus", "(", "JobStatusException", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "qorJob", ".", "GetStatus", "(", ")", "!=", "JobStatusNew", "&&", "qorJob", ".", "GetStatus", "(", ")", "!=", "JobStatusScheduled", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "qorJob", ".", "GetStatus", "(", ")", ")", "\n", "}", "\n\n", "if", "err", "=", "qorJob", ".", "SetStatus", "(", "JobStatusRunning", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "qorJob", ".", "GetJob", "(", ")", ".", "GetQueue", "(", ")", ".", "Run", "(", "qorJob", ")", ";", "err", "==", "nil", "{", "return", "qorJob", ".", "SetStatus", "(", "JobStatusDone", ")", "\n", "}", "\n\n", "qorJob", ".", "SetProgressText", "(", "err", ".", "Error", "(", ")", ")", "\n", "qorJob", ".", "SetStatus", "(", "JobStatusException", ")", "\n", "}", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// RunJob run job with job id
[ "RunJob", "run", "job", "with", "job", "id" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L251-L278
12,342
qor/worker
worker.go
KillJob
func (worker *Worker) KillJob(jobID string) error { if qorJob, err := worker.GetJob(jobID); err == nil { if qorJob.GetStatus() == JobStatusRunning { if err = qorJob.GetJob().GetQueue().Kill(qorJob); err == nil { qorJob.SetStatus(JobStatusKilled) return nil } return err } else if qorJob.GetStatus() == JobStatusScheduled || qorJob.GetStatus() == JobStatusNew { qorJob.SetStatus(JobStatusKilled) return worker.RemoveJob(jobID) } else { return errors.New("invalid job status") } } else { return err } }
go
func (worker *Worker) KillJob(jobID string) error { if qorJob, err := worker.GetJob(jobID); err == nil { if qorJob.GetStatus() == JobStatusRunning { if err = qorJob.GetJob().GetQueue().Kill(qorJob); err == nil { qorJob.SetStatus(JobStatusKilled) return nil } return err } else if qorJob.GetStatus() == JobStatusScheduled || qorJob.GetStatus() == JobStatusNew { qorJob.SetStatus(JobStatusKilled) return worker.RemoveJob(jobID) } else { return errors.New("invalid job status") } } else { return err } }
[ "func", "(", "worker", "*", "Worker", ")", "KillJob", "(", "jobID", "string", ")", "error", "{", "if", "qorJob", ",", "err", ":=", "worker", ".", "GetJob", "(", "jobID", ")", ";", "err", "==", "nil", "{", "if", "qorJob", ".", "GetStatus", "(", ")", "==", "JobStatusRunning", "{", "if", "err", "=", "qorJob", ".", "GetJob", "(", ")", ".", "GetQueue", "(", ")", ".", "Kill", "(", "qorJob", ")", ";", "err", "==", "nil", "{", "qorJob", ".", "SetStatus", "(", "JobStatusKilled", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "else", "if", "qorJob", ".", "GetStatus", "(", ")", "==", "JobStatusScheduled", "||", "qorJob", ".", "GetStatus", "(", ")", "==", "JobStatusNew", "{", "qorJob", ".", "SetStatus", "(", "JobStatusKilled", ")", "\n", "return", "worker", ".", "RemoveJob", "(", "jobID", ")", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// KillJob kill job with job id
[ "KillJob", "kill", "job", "with", "job", "id" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L297-L314
12,343
qor/worker
worker.go
RemoveJob
func (worker *Worker) RemoveJob(jobID string) error { qorJob, err := worker.GetJob(jobID) if err == nil { return qorJob.GetJob().GetQueue().Remove(qorJob) } return err }
go
func (worker *Worker) RemoveJob(jobID string) error { qorJob, err := worker.GetJob(jobID) if err == nil { return qorJob.GetJob().GetQueue().Remove(qorJob) } return err }
[ "func", "(", "worker", "*", "Worker", ")", "RemoveJob", "(", "jobID", "string", ")", "error", "{", "qorJob", ",", "err", ":=", "worker", ".", "GetJob", "(", "jobID", ")", "\n", "if", "err", "==", "nil", "{", "return", "qorJob", ".", "GetJob", "(", ")", ".", "GetQueue", "(", ")", ".", "Remove", "(", "qorJob", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// RemoveJob remove job with job id
[ "RemoveJob", "remove", "job", "with", "job", "id" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/worker.go#L317-L323
12,344
qor/worker
job.go
NewStruct
func (job *Job) NewStruct() interface{} { qorJobInterface := job.Worker.JobResource.NewStruct().(QorJobInterface) qorJobInterface.SetJob(job) return qorJobInterface }
go
func (job *Job) NewStruct() interface{} { qorJobInterface := job.Worker.JobResource.NewStruct().(QorJobInterface) qorJobInterface.SetJob(job) return qorJobInterface }
[ "func", "(", "job", "*", "Job", ")", "NewStruct", "(", ")", "interface", "{", "}", "{", "qorJobInterface", ":=", "job", ".", "Worker", ".", "JobResource", ".", "NewStruct", "(", ")", ".", "(", "QorJobInterface", ")", "\n", "qorJobInterface", ".", "SetJob", "(", "job", ")", "\n", "return", "qorJobInterface", "\n", "}" ]
// NewStruct initialize job struct
[ "NewStruct", "initialize", "job", "struct" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/job.go#L21-L25
12,345
qor/worker
job.go
GetQueue
func (job *Job) GetQueue() Queue { if job.Queue != nil { return job.Queue } return job.Worker.Queue }
go
func (job *Job) GetQueue() Queue { if job.Queue != nil { return job.Queue } return job.Worker.Queue }
[ "func", "(", "job", "*", "Job", ")", "GetQueue", "(", ")", "Queue", "{", "if", "job", ".", "Queue", "!=", "nil", "{", "return", "job", ".", "Queue", "\n", "}", "\n", "return", "job", ".", "Worker", ".", "Queue", "\n", "}" ]
// GetQueue get defined job's queue
[ "GetQueue", "get", "defined", "job", "s", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/job.go#L28-L33
12,346
qor/worker
queue/kubernetes/kubernetes.go
New
func New(config *Config) (*Kubernetes, error) { var err error if config == nil { config = &Config{} } if config.ClusterConfig == nil { config.ClusterConfig, err = rest.InClusterConfig() } if err != nil { return nil, err } clientset, err := kubernetes.NewForConfig(config.ClusterConfig) if err != nil { return nil, err } return &Kubernetes{Clientset: clientset, Config: config}, nil }
go
func New(config *Config) (*Kubernetes, error) { var err error if config == nil { config = &Config{} } if config.ClusterConfig == nil { config.ClusterConfig, err = rest.InClusterConfig() } if err != nil { return nil, err } clientset, err := kubernetes.NewForConfig(config.ClusterConfig) if err != nil { return nil, err } return &Kubernetes{Clientset: clientset, Config: config}, nil }
[ "func", "New", "(", "config", "*", "Config", ")", "(", "*", "Kubernetes", ",", "error", ")", "{", "var", "err", "error", "\n\n", "if", "config", "==", "nil", "{", "config", "=", "&", "Config", "{", "}", "\n", "}", "\n\n", "if", "config", ".", "ClusterConfig", "==", "nil", "{", "config", ".", "ClusterConfig", ",", "err", "=", "rest", ".", "InClusterConfig", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "clientset", ",", "err", ":=", "kubernetes", ".", "NewForConfig", "(", "config", ".", "ClusterConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Kubernetes", "{", "Clientset", ":", "clientset", ",", "Config", ":", "config", "}", ",", "nil", "\n", "}" ]
// New initialize Kubernetes
[ "New", "initialize", "Kubernetes" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/queue/kubernetes/kubernetes.go#L36-L57
12,347
qor/worker
queue/kubernetes/kubernetes.go
GetCurrentPod
func (k8s *Kubernetes) GetCurrentPod() *corev1.Pod { var ( podlist, err = k8s.Clientset.Core().Pods("").List(metav1.ListOptions{}) localeIP = GetLocalIP() ) if err == nil { for _, item := range podlist.Items { if item.Status.PodIP == localeIP { return &item } } } return nil }
go
func (k8s *Kubernetes) GetCurrentPod() *corev1.Pod { var ( podlist, err = k8s.Clientset.Core().Pods("").List(metav1.ListOptions{}) localeIP = GetLocalIP() ) if err == nil { for _, item := range podlist.Items { if item.Status.PodIP == localeIP { return &item } } } return nil }
[ "func", "(", "k8s", "*", "Kubernetes", ")", "GetCurrentPod", "(", ")", "*", "corev1", ".", "Pod", "{", "var", "(", "podlist", ",", "err", "=", "k8s", ".", "Clientset", ".", "Core", "(", ")", ".", "Pods", "(", "\"", "\"", ")", ".", "List", "(", "metav1", ".", "ListOptions", "{", "}", ")", "\n", "localeIP", "=", "GetLocalIP", "(", ")", "\n", ")", "\n\n", "if", "err", "==", "nil", "{", "for", "_", ",", "item", ":=", "range", "podlist", ".", "Items", "{", "if", "item", ".", "Status", ".", "PodIP", "==", "localeIP", "{", "return", "&", "item", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetCurrentPod get current pod
[ "GetCurrentPod", "get", "current", "pod" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/queue/kubernetes/kubernetes.go#L60-L74
12,348
qor/worker
queue/kubernetes/kubernetes.go
GetJobSpec
func (k8s *Kubernetes) GetJobSpec(qorJob worker.QorJobInterface) (*v1.Job, error) { var ( k8sJob = &v1.Job{} currentPod = k8s.GetCurrentPod() namespace = currentPod.GetNamespace() ) if k8s.Config.Namespace != "" { namespace = k8s.Config.Namespace } if k8s.Config.JobTemplateMaker != nil { if err := yaml.Unmarshal([]byte(k8s.Config.JobTemplateMaker(qorJob)), k8sJob); err != nil { return nil, err } if k8sJob.ObjectMeta.Namespace != "" { namespace = k8sJob.ObjectMeta.Namespace } } else { if marshaledContainers, err := json.Marshal(currentPod.Spec.Containers); err == nil { json.Unmarshal(marshaledContainers, k8sJob.Spec.Template.Spec.Containers) } if marshaledVolumes, err := json.Marshal(currentPod.Spec.Volumes); err == nil { json.Unmarshal(marshaledVolumes, k8sJob.Spec.Template.Spec.Volumes) } } if k8sJob.TypeMeta.Kind == "" { k8sJob.TypeMeta.Kind = "Job" } if k8sJob.TypeMeta.APIVersion == "" { k8sJob.TypeMeta.APIVersion = "batch/v1" } if k8sJob.ObjectMeta.Namespace == "" { k8sJob.ObjectMeta.Namespace = namespace } return k8sJob, nil }
go
func (k8s *Kubernetes) GetJobSpec(qorJob worker.QorJobInterface) (*v1.Job, error) { var ( k8sJob = &v1.Job{} currentPod = k8s.GetCurrentPod() namespace = currentPod.GetNamespace() ) if k8s.Config.Namespace != "" { namespace = k8s.Config.Namespace } if k8s.Config.JobTemplateMaker != nil { if err := yaml.Unmarshal([]byte(k8s.Config.JobTemplateMaker(qorJob)), k8sJob); err != nil { return nil, err } if k8sJob.ObjectMeta.Namespace != "" { namespace = k8sJob.ObjectMeta.Namespace } } else { if marshaledContainers, err := json.Marshal(currentPod.Spec.Containers); err == nil { json.Unmarshal(marshaledContainers, k8sJob.Spec.Template.Spec.Containers) } if marshaledVolumes, err := json.Marshal(currentPod.Spec.Volumes); err == nil { json.Unmarshal(marshaledVolumes, k8sJob.Spec.Template.Spec.Volumes) } } if k8sJob.TypeMeta.Kind == "" { k8sJob.TypeMeta.Kind = "Job" } if k8sJob.TypeMeta.APIVersion == "" { k8sJob.TypeMeta.APIVersion = "batch/v1" } if k8sJob.ObjectMeta.Namespace == "" { k8sJob.ObjectMeta.Namespace = namespace } return k8sJob, nil }
[ "func", "(", "k8s", "*", "Kubernetes", ")", "GetJobSpec", "(", "qorJob", "worker", ".", "QorJobInterface", ")", "(", "*", "v1", ".", "Job", ",", "error", ")", "{", "var", "(", "k8sJob", "=", "&", "v1", ".", "Job", "{", "}", "\n", "currentPod", "=", "k8s", ".", "GetCurrentPod", "(", ")", "\n", "namespace", "=", "currentPod", ".", "GetNamespace", "(", ")", "\n", ")", "\n\n", "if", "k8s", ".", "Config", ".", "Namespace", "!=", "\"", "\"", "{", "namespace", "=", "k8s", ".", "Config", ".", "Namespace", "\n", "}", "\n\n", "if", "k8s", ".", "Config", ".", "JobTemplateMaker", "!=", "nil", "{", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "[", "]", "byte", "(", "k8s", ".", "Config", ".", "JobTemplateMaker", "(", "qorJob", ")", ")", ",", "k8sJob", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "k8sJob", ".", "ObjectMeta", ".", "Namespace", "!=", "\"", "\"", "{", "namespace", "=", "k8sJob", ".", "ObjectMeta", ".", "Namespace", "\n", "}", "\n", "}", "else", "{", "if", "marshaledContainers", ",", "err", ":=", "json", ".", "Marshal", "(", "currentPod", ".", "Spec", ".", "Containers", ")", ";", "err", "==", "nil", "{", "json", ".", "Unmarshal", "(", "marshaledContainers", ",", "k8sJob", ".", "Spec", ".", "Template", ".", "Spec", ".", "Containers", ")", "\n", "}", "\n\n", "if", "marshaledVolumes", ",", "err", ":=", "json", ".", "Marshal", "(", "currentPod", ".", "Spec", ".", "Volumes", ")", ";", "err", "==", "nil", "{", "json", ".", "Unmarshal", "(", "marshaledVolumes", ",", "k8sJob", ".", "Spec", ".", "Template", ".", "Spec", ".", "Volumes", ")", "\n", "}", "\n", "}", "\n\n", "if", "k8sJob", ".", "TypeMeta", ".", "Kind", "==", "\"", "\"", "{", "k8sJob", ".", "TypeMeta", ".", "Kind", "=", "\"", "\"", "\n", "}", "\n\n", "if", "k8sJob", ".", "TypeMeta", ".", "APIVersion", "==", "\"", "\"", "{", "k8sJob", ".", "TypeMeta", ".", "APIVersion", "=", "\"", "\"", "\n", "}", "\n\n", "if", "k8sJob", ".", "ObjectMeta", ".", "Namespace", "==", "\"", "\"", "{", "k8sJob", ".", "ObjectMeta", ".", "Namespace", "=", "namespace", "\n", "}", "\n\n", "return", "k8sJob", ",", "nil", "\n", "}" ]
// GetJobSpec get job spec
[ "GetJobSpec", "get", "job", "spec" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/queue/kubernetes/kubernetes.go#L77-L118
12,349
qor/worker
queue/kubernetes/kubernetes.go
Add
func (k8s *Kubernetes) Add(qorJob worker.QorJobInterface) error { var ( jobName = fmt.Sprintf("qor-job-%v", qorJob.GetJobID()) k8sJob, err = k8s.GetJobSpec(qorJob) currentPath, _ = os.Getwd() binaryFile, _ = filepath.Abs(os.Args[0]) ) if err == nil { k8sJob.ObjectMeta.Name = jobName k8sJob.Spec.Template.ObjectMeta.Name = jobName if k8sJob.Spec.Template.Spec.RestartPolicy == "" { k8sJob.Spec.Template.Spec.RestartPolicy = "Never" } for idx, container := range k8sJob.Spec.Template.Spec.Containers { if len(container.Command) == 0 || k8s.Config.JobTemplateMaker == nil { container.Command = []string{binaryFile, "--qor-job", qorJob.GetJobID()} } if container.WorkingDir == "" || k8s.Config.JobTemplateMaker == nil { container.WorkingDir = currentPath } k8sJob.Spec.Template.Spec.Containers[idx] = container } _, err = k8s.Clientset.Batch().Jobs(k8sJob.ObjectMeta.GetNamespace()).Create(k8sJob) } return err }
go
func (k8s *Kubernetes) Add(qorJob worker.QorJobInterface) error { var ( jobName = fmt.Sprintf("qor-job-%v", qorJob.GetJobID()) k8sJob, err = k8s.GetJobSpec(qorJob) currentPath, _ = os.Getwd() binaryFile, _ = filepath.Abs(os.Args[0]) ) if err == nil { k8sJob.ObjectMeta.Name = jobName k8sJob.Spec.Template.ObjectMeta.Name = jobName if k8sJob.Spec.Template.Spec.RestartPolicy == "" { k8sJob.Spec.Template.Spec.RestartPolicy = "Never" } for idx, container := range k8sJob.Spec.Template.Spec.Containers { if len(container.Command) == 0 || k8s.Config.JobTemplateMaker == nil { container.Command = []string{binaryFile, "--qor-job", qorJob.GetJobID()} } if container.WorkingDir == "" || k8s.Config.JobTemplateMaker == nil { container.WorkingDir = currentPath } k8sJob.Spec.Template.Spec.Containers[idx] = container } _, err = k8s.Clientset.Batch().Jobs(k8sJob.ObjectMeta.GetNamespace()).Create(k8sJob) } return err }
[ "func", "(", "k8s", "*", "Kubernetes", ")", "Add", "(", "qorJob", "worker", ".", "QorJobInterface", ")", "error", "{", "var", "(", "jobName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "qorJob", ".", "GetJobID", "(", ")", ")", "\n", "k8sJob", ",", "err", "=", "k8s", ".", "GetJobSpec", "(", "qorJob", ")", "\n", "currentPath", ",", "_", "=", "os", ".", "Getwd", "(", ")", "\n", "binaryFile", ",", "_", "=", "filepath", ".", "Abs", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", ")", "\n\n", "if", "err", "==", "nil", "{", "k8sJob", ".", "ObjectMeta", ".", "Name", "=", "jobName", "\n", "k8sJob", ".", "Spec", ".", "Template", ".", "ObjectMeta", ".", "Name", "=", "jobName", "\n\n", "if", "k8sJob", ".", "Spec", ".", "Template", ".", "Spec", ".", "RestartPolicy", "==", "\"", "\"", "{", "k8sJob", ".", "Spec", ".", "Template", ".", "Spec", ".", "RestartPolicy", "=", "\"", "\"", "\n", "}", "\n\n", "for", "idx", ",", "container", ":=", "range", "k8sJob", ".", "Spec", ".", "Template", ".", "Spec", ".", "Containers", "{", "if", "len", "(", "container", ".", "Command", ")", "==", "0", "||", "k8s", ".", "Config", ".", "JobTemplateMaker", "==", "nil", "{", "container", ".", "Command", "=", "[", "]", "string", "{", "binaryFile", ",", "\"", "\"", ",", "qorJob", ".", "GetJobID", "(", ")", "}", "\n", "}", "\n", "if", "container", ".", "WorkingDir", "==", "\"", "\"", "||", "k8s", ".", "Config", ".", "JobTemplateMaker", "==", "nil", "{", "container", ".", "WorkingDir", "=", "currentPath", "\n", "}", "\n\n", "k8sJob", ".", "Spec", ".", "Template", ".", "Spec", ".", "Containers", "[", "idx", "]", "=", "container", "\n", "}", "\n\n", "_", ",", "err", "=", "k8s", ".", "Clientset", ".", "Batch", "(", ")", ".", "Jobs", "(", "k8sJob", ".", "ObjectMeta", ".", "GetNamespace", "(", ")", ")", ".", "Create", "(", "k8sJob", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Add a job to k8s queue
[ "Add", "a", "job", "to", "k8s", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/queue/kubernetes/kubernetes.go#L121-L151
12,350
qor/worker
queue/kubernetes/kubernetes.go
Run
func (k8s *Kubernetes) Run(qorJob worker.QorJobInterface) error { job := qorJob.GetJob() if job.Handler != nil { return job.Handler(qorJob.GetSerializableArgument(qorJob), qorJob) } return errors.New("no handler found for job " + job.Name) }
go
func (k8s *Kubernetes) Run(qorJob worker.QorJobInterface) error { job := qorJob.GetJob() if job.Handler != nil { return job.Handler(qorJob.GetSerializableArgument(qorJob), qorJob) } return errors.New("no handler found for job " + job.Name) }
[ "func", "(", "k8s", "*", "Kubernetes", ")", "Run", "(", "qorJob", "worker", ".", "QorJobInterface", ")", "error", "{", "job", ":=", "qorJob", ".", "GetJob", "(", ")", "\n\n", "if", "job", ".", "Handler", "!=", "nil", "{", "return", "job", ".", "Handler", "(", "qorJob", ".", "GetSerializableArgument", "(", "qorJob", ")", ",", "qorJob", ")", "\n", "}", "\n\n", "return", "errors", ".", "New", "(", "\"", "\"", "+", "job", ".", "Name", ")", "\n", "}" ]
// Run a job from k8s queue
[ "Run", "a", "job", "from", "k8s", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/queue/kubernetes/kubernetes.go#L154-L162
12,351
qor/worker
queue/kubernetes/kubernetes.go
Kill
func (k8s *Kubernetes) Kill(qorJob worker.QorJobInterface) error { var ( k8sJob, err = k8s.GetJobSpec(qorJob) jobName = fmt.Sprintf("qor-job-%v", qorJob.GetJobID()) ) if err == nil { return k8s.Clientset.Batch().Jobs(k8sJob.ObjectMeta.GetNamespace()).Delete(jobName, &metav1.DeleteOptions{}) } return err }
go
func (k8s *Kubernetes) Kill(qorJob worker.QorJobInterface) error { var ( k8sJob, err = k8s.GetJobSpec(qorJob) jobName = fmt.Sprintf("qor-job-%v", qorJob.GetJobID()) ) if err == nil { return k8s.Clientset.Batch().Jobs(k8sJob.ObjectMeta.GetNamespace()).Delete(jobName, &metav1.DeleteOptions{}) } return err }
[ "func", "(", "k8s", "*", "Kubernetes", ")", "Kill", "(", "qorJob", "worker", ".", "QorJobInterface", ")", "error", "{", "var", "(", "k8sJob", ",", "err", "=", "k8s", ".", "GetJobSpec", "(", "qorJob", ")", "\n", "jobName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "qorJob", ".", "GetJobID", "(", ")", ")", "\n", ")", "\n\n", "if", "err", "==", "nil", "{", "return", "k8s", ".", "Clientset", ".", "Batch", "(", ")", ".", "Jobs", "(", "k8sJob", ".", "ObjectMeta", ".", "GetNamespace", "(", ")", ")", ".", "Delete", "(", "jobName", ",", "&", "metav1", ".", "DeleteOptions", "{", "}", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Kill a job from k8s queue
[ "Kill", "a", "job", "from", "k8s", "queue" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/queue/kubernetes/kubernetes.go#L165-L175
12,352
qor/worker
qor_job.go
Scan
func (resultsTable *ResultsTable) Scan(data interface{}) error { switch values := data.(type) { case []byte: return json.Unmarshal(values, resultsTable) case string: return resultsTable.Scan([]byte(values)) default: return errors.New("unsupported data type for Qor Job error table") } }
go
func (resultsTable *ResultsTable) Scan(data interface{}) error { switch values := data.(type) { case []byte: return json.Unmarshal(values, resultsTable) case string: return resultsTable.Scan([]byte(values)) default: return errors.New("unsupported data type for Qor Job error table") } }
[ "func", "(", "resultsTable", "*", "ResultsTable", ")", "Scan", "(", "data", "interface", "{", "}", ")", "error", "{", "switch", "values", ":=", "data", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "return", "json", ".", "Unmarshal", "(", "values", ",", "resultsTable", ")", "\n", "case", "string", ":", "return", "resultsTable", ".", "Scan", "(", "[", "]", "byte", "(", "values", ")", ")", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Scan used to scan value from database into itself
[ "Scan", "used", "to", "scan", "value", "from", "database", "into", "itself" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L51-L60
12,353
qor/worker
qor_job.go
Value
func (resultsTable ResultsTable) Value() (driver.Value, error) { result, err := json.Marshal(resultsTable) return string(result), err }
go
func (resultsTable ResultsTable) Value() (driver.Value, error) { result, err := json.Marshal(resultsTable) return string(result), err }
[ "func", "(", "resultsTable", "ResultsTable", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "result", ",", "err", ":=", "json", ".", "Marshal", "(", "resultsTable", ")", "\n", "return", "string", "(", "result", ")", ",", "err", "\n", "}" ]
// Value used to read value from itself and save it into databae
[ "Value", "used", "to", "read", "value", "from", "itself", "and", "save", "it", "into", "databae" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L63-L66
12,354
qor/worker
qor_job.go
SetStatus
func (job *QorJob) SetStatus(status string) error { job.mutex.Lock() defer job.mutex.Unlock() job.Status = status if status == JobStatusDone { job.Progress = 100 } if job.shouldCallSave() { return job.callSave() } return nil }
go
func (job *QorJob) SetStatus(status string) error { job.mutex.Lock() defer job.mutex.Unlock() job.Status = status if status == JobStatusDone { job.Progress = 100 } if job.shouldCallSave() { return job.callSave() } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "SetStatus", "(", "status", "string", ")", "error", "{", "job", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "job", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "job", ".", "Status", "=", "status", "\n", "if", "status", "==", "JobStatusDone", "{", "job", ".", "Progress", "=", "100", "\n", "}", "\n\n", "if", "job", ".", "shouldCallSave", "(", ")", "{", "return", "job", ".", "callSave", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetStatus set job's status to a qor job instance
[ "SetStatus", "set", "job", "s", "status", "to", "a", "qor", "job", "instance" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L114-L128
12,355
qor/worker
qor_job.go
SetJob
func (job *QorJob) SetJob(j *Job) { job.Kind = j.Name job.Job = j }
go
func (job *QorJob) SetJob(j *Job) { job.Kind = j.Name job.Job = j }
[ "func", "(", "job", "*", "QorJob", ")", "SetJob", "(", "j", "*", "Job", ")", "{", "job", ".", "Kind", "=", "j", ".", "Name", "\n", "job", ".", "Job", "=", "j", "\n", "}" ]
// SetJob set `Job` for a qor job instance
[ "SetJob", "set", "Job", "for", "a", "qor", "job", "instance" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L183-L186
12,356
qor/worker
qor_job.go
GetJob
func (job *QorJob) GetJob() *Job { if job.Job != nil { return job.Job } return nil }
go
func (job *QorJob) GetJob() *Job { if job.Job != nil { return job.Job } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "GetJob", "(", ")", "*", "Job", "{", "if", "job", ".", "Job", "!=", "nil", "{", "return", "job", ".", "Job", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetJob get predefined job for a qor job instance
[ "GetJob", "get", "predefined", "job", "for", "a", "qor", "job", "instance" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L189-L194
12,357
qor/worker
qor_job.go
GetSerializableArgumentResource
func (job *QorJob) GetSerializableArgumentResource() *admin.Resource { if j := job.GetJob(); j != nil { return j.Resource } return nil }
go
func (job *QorJob) GetSerializableArgumentResource() *admin.Resource { if j := job.GetJob(); j != nil { return j.Resource } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "GetSerializableArgumentResource", "(", ")", "*", "admin", ".", "Resource", "{", "if", "j", ":=", "job", ".", "GetJob", "(", ")", ";", "j", "!=", "nil", "{", "return", "j", ".", "Resource", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetSerializableArgumentResource get job's argument's resource
[ "GetSerializableArgumentResource", "get", "job", "s", "argument", "s", "resource" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L202-L207
12,358
qor/worker
qor_job.go
SetProgress
func (job *QorJob) SetProgress(progress uint) error { job.mutex.Lock() defer job.mutex.Unlock() if progress > 100 { progress = 100 } job.Progress = progress if job.shouldCallSave() { return job.callSave() } return nil }
go
func (job *QorJob) SetProgress(progress uint) error { job.mutex.Lock() defer job.mutex.Unlock() if progress > 100 { progress = 100 } job.Progress = progress if job.shouldCallSave() { return job.callSave() } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "SetProgress", "(", "progress", "uint", ")", "error", "{", "job", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "job", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "progress", ">", "100", "{", "progress", "=", "100", "\n", "}", "\n", "job", ".", "Progress", "=", "progress", "\n\n", "if", "job", ".", "shouldCallSave", "(", ")", "{", "return", "job", ".", "callSave", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetProgress set qor job's progress
[ "SetProgress", "set", "qor", "job", "s", "progress" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L215-L229
12,359
qor/worker
qor_job.go
SetProgressText
func (job *QorJob) SetProgressText(str string) error { job.mutex.Lock() defer job.mutex.Unlock() job.ProgressText = str if job.shouldCallSave() { return job.callSave() } return nil }
go
func (job *QorJob) SetProgressText(str string) error { job.mutex.Lock() defer job.mutex.Unlock() job.ProgressText = str if job.shouldCallSave() { return job.callSave() } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "SetProgressText", "(", "str", "string", ")", "error", "{", "job", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "job", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "job", ".", "ProgressText", "=", "str", "\n", "if", "job", ".", "shouldCallSave", "(", ")", "{", "return", "job", ".", "callSave", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetProgressText set qor job's progress text
[ "SetProgressText", "set", "qor", "job", "s", "progress", "text" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L237-L247
12,360
qor/worker
qor_job.go
AddLog
func (job *QorJob) AddLog(log string) error { job.mutex.Lock() defer job.mutex.Unlock() fmt.Println(log) job.Log += "\n" + log if job.shouldCallSave() { return job.callSave() } return nil }
go
func (job *QorJob) AddLog(log string) error { job.mutex.Lock() defer job.mutex.Unlock() fmt.Println(log) job.Log += "\n" + log if job.shouldCallSave() { return job.callSave() } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "AddLog", "(", "log", "string", ")", "error", "{", "job", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "job", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "fmt", ".", "Println", "(", "log", ")", "\n", "job", ".", "Log", "+=", "\"", "\\n", "\"", "+", "log", "\n", "if", "job", ".", "shouldCallSave", "(", ")", "{", "return", "job", ".", "callSave", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// AddLog add a log to qor job
[ "AddLog", "add", "a", "log", "to", "qor", "job" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L255-L266
12,361
qor/worker
qor_job.go
AddResultsRow
func (job *QorJob) AddResultsRow(cells ...TableCell) error { job.mutex.Lock() defer job.mutex.Unlock() job.ResultsTable.TableCells = append(job.ResultsTable.TableCells, cells) if job.shouldCallSave() { return job.callSave() } return nil }
go
func (job *QorJob) AddResultsRow(cells ...TableCell) error { job.mutex.Lock() defer job.mutex.Unlock() job.ResultsTable.TableCells = append(job.ResultsTable.TableCells, cells) if job.shouldCallSave() { return job.callSave() } return nil }
[ "func", "(", "job", "*", "QorJob", ")", "AddResultsRow", "(", "cells", "...", "TableCell", ")", "error", "{", "job", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "job", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "job", ".", "ResultsTable", ".", "TableCells", "=", "append", "(", "job", ".", "ResultsTable", ".", "TableCells", ",", "cells", ")", "\n", "if", "job", ".", "shouldCallSave", "(", ")", "{", "return", "job", ".", "callSave", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// AddResultsRow add a row of process results to a job
[ "AddResultsRow", "add", "a", "row", "of", "process", "results", "to", "a", "job" ]
5c9381791cdc76758df130894aa232d2e62a2ba7
https://github.com/qor/worker/blob/5c9381791cdc76758df130894aa232d2e62a2ba7/qor_job.go#L274-L284
12,362
google/badwolf
tools/vcli/bw/common/common.go
ParseChannelSizeFlag
func ParseChannelSizeFlag(flag string) (int, error) { ss := strings.Split(flag, "=") if len(ss) != 2 { return 0, fmt.Errorf("Failed split flag %s", flag) } if ss[0] != "--channel_size" { return 0, fmt.Errorf("Unknown flag %s", flag) } return strconv.Atoi(ss[1]) }
go
func ParseChannelSizeFlag(flag string) (int, error) { ss := strings.Split(flag, "=") if len(ss) != 2 { return 0, fmt.Errorf("Failed split flag %s", flag) } if ss[0] != "--channel_size" { return 0, fmt.Errorf("Unknown flag %s", flag) } return strconv.Atoi(ss[1]) }
[ "func", "ParseChannelSizeFlag", "(", "flag", "string", ")", "(", "int", ",", "error", ")", "{", "ss", ":=", "strings", ".", "Split", "(", "flag", ",", "\"", "\"", ")", "\n", "if", "len", "(", "ss", ")", "!=", "2", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "flag", ")", "\n", "}", "\n", "if", "ss", "[", "0", "]", "!=", "\"", "\"", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "flag", ")", "\n", "}", "\n", "return", "strconv", ".", "Atoi", "(", "ss", "[", "1", "]", ")", "\n", "}" ]
// ParseChannelSizeFlag attempts to parse the "channel_size" flag.
[ "ParseChannelSizeFlag", "attempts", "to", "parse", "the", "channel_size", "flag", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/vcli/bw/common/common.go#L41-L50
12,363
google/badwolf
tools/vcli/bw/common/common.go
Help
func Help(args []string, cmds []*command.Command) int { var ( cmd string ) if len(args) >= 3 { cmd = args[2] } // Prints the help if the command exist. for _, c := range cmds { if c.Name() == cmd { return c.Usage() } } if cmd == "" { fmt.Fprintf(os.Stderr, "missing help command. Usage:\n\n\t$ bw help [command]\n\nAvailable help commands\n\n") var usage []string for _, c := range cmds { name := c.Name() for i := len(name); i < 12; i++ { name += " " } usage = append(usage, fmt.Sprintf("\t%s\t- %s\n", name, c.Short)) } sort.Strings(usage) for _, u := range usage { fmt.Fprint(os.Stderr, u) } fmt.Fprintln(os.Stderr, "") return 0 } fmt.Fprintf(os.Stderr, "help command %q not recognized. Usage:\n\n\t$ bw help\n\n", cmd) return 2 }
go
func Help(args []string, cmds []*command.Command) int { var ( cmd string ) if len(args) >= 3 { cmd = args[2] } // Prints the help if the command exist. for _, c := range cmds { if c.Name() == cmd { return c.Usage() } } if cmd == "" { fmt.Fprintf(os.Stderr, "missing help command. Usage:\n\n\t$ bw help [command]\n\nAvailable help commands\n\n") var usage []string for _, c := range cmds { name := c.Name() for i := len(name); i < 12; i++ { name += " " } usage = append(usage, fmt.Sprintf("\t%s\t- %s\n", name, c.Short)) } sort.Strings(usage) for _, u := range usage { fmt.Fprint(os.Stderr, u) } fmt.Fprintln(os.Stderr, "") return 0 } fmt.Fprintf(os.Stderr, "help command %q not recognized. Usage:\n\n\t$ bw help\n\n", cmd) return 2 }
[ "func", "Help", "(", "args", "[", "]", "string", ",", "cmds", "[", "]", "*", "command", ".", "Command", ")", "int", "{", "var", "(", "cmd", "string", "\n", ")", "\n", "if", "len", "(", "args", ")", ">=", "3", "{", "cmd", "=", "args", "[", "2", "]", "\n", "}", "\n", "// Prints the help if the command exist.", "for", "_", ",", "c", ":=", "range", "cmds", "{", "if", "c", ".", "Name", "(", ")", "==", "cmd", "{", "return", "c", ".", "Usage", "(", ")", "\n", "}", "\n", "}", "\n", "if", "cmd", "==", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\\n", "\\t", "\\n", "\\n", "\\n", "\\n", "\"", ")", "\n", "var", "usage", "[", "]", "string", "\n", "for", "_", ",", "c", ":=", "range", "cmds", "{", "name", ":=", "c", ".", "Name", "(", ")", "\n", "for", "i", ":=", "len", "(", "name", ")", ";", "i", "<", "12", ";", "i", "++", "{", "name", "+=", "\"", "\"", "\n", "}", "\n", "usage", "=", "append", "(", "usage", ",", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\\t", "\\n", "\"", ",", "name", ",", "c", ".", "Short", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "usage", ")", "\n", "for", "_", ",", "u", ":=", "range", "usage", "{", "fmt", ".", "Fprint", "(", "os", ".", "Stderr", ",", "u", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "\"", "\"", ")", "\n", "return", "0", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\\n", "\\t", "\\n", "\\n", "\"", ",", "cmd", ")", "\n", "return", "2", "\n", "}" ]
// Help prints the requested help
[ "Help", "prints", "the", "requested", "help" ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/vcli/bw/common/common.go#L53-L85
12,364
google/badwolf
tools/vcli/bw/common/common.go
InitializeDriver
func InitializeDriver(driverName string, drivers map[string]StoreGenerator) (storage.Store, error) { f, ok := drivers[driverName] if !ok { var ds []string for k := range drivers { ds = append(ds, k) } return nil, fmt.Errorf("unknown driver name %q; valid drivers [%q]", driverName, strings.Join(ds, ", ")) } return f() }
go
func InitializeDriver(driverName string, drivers map[string]StoreGenerator) (storage.Store, error) { f, ok := drivers[driverName] if !ok { var ds []string for k := range drivers { ds = append(ds, k) } return nil, fmt.Errorf("unknown driver name %q; valid drivers [%q]", driverName, strings.Join(ds, ", ")) } return f() }
[ "func", "InitializeDriver", "(", "driverName", "string", ",", "drivers", "map", "[", "string", "]", "StoreGenerator", ")", "(", "storage", ".", "Store", ",", "error", ")", "{", "f", ",", "ok", ":=", "drivers", "[", "driverName", "]", "\n", "if", "!", "ok", "{", "var", "ds", "[", "]", "string", "\n", "for", "k", ":=", "range", "drivers", "{", "ds", "=", "append", "(", "ds", ",", "k", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "driverName", ",", "strings", ".", "Join", "(", "ds", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "f", "(", ")", "\n", "}" ]
// InitializeDriver attempts to initialize the driver.
[ "InitializeDriver", "attempts", "to", "initialize", "the", "driver", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/vcli/bw/common/common.go#L91-L101
12,365
google/badwolf
tools/vcli/bw/common/common.go
InitializeCommands
func InitializeCommands(driver storage.Store, chanSize, bulkTripleOpSize, builderSize int, rl repl.ReadLiner, done chan bool) []*command.Command { return []*command.Command{ assert.New(driver, literal.DefaultBuilder(), chanSize, bulkTripleOpSize), benchmark.New(driver, chanSize, bulkTripleOpSize), export.New(driver, bulkTripleOpSize), load.New(driver, bulkTripleOpSize, builderSize), run.New(driver, chanSize, bulkTripleOpSize), repl.New(driver, chanSize, bulkTripleOpSize, builderSize, rl, done), server.New(driver, chanSize, bulkTripleOpSize), version.New(), } }
go
func InitializeCommands(driver storage.Store, chanSize, bulkTripleOpSize, builderSize int, rl repl.ReadLiner, done chan bool) []*command.Command { return []*command.Command{ assert.New(driver, literal.DefaultBuilder(), chanSize, bulkTripleOpSize), benchmark.New(driver, chanSize, bulkTripleOpSize), export.New(driver, bulkTripleOpSize), load.New(driver, bulkTripleOpSize, builderSize), run.New(driver, chanSize, bulkTripleOpSize), repl.New(driver, chanSize, bulkTripleOpSize, builderSize, rl, done), server.New(driver, chanSize, bulkTripleOpSize), version.New(), } }
[ "func", "InitializeCommands", "(", "driver", "storage", ".", "Store", ",", "chanSize", ",", "bulkTripleOpSize", ",", "builderSize", "int", ",", "rl", "repl", ".", "ReadLiner", ",", "done", "chan", "bool", ")", "[", "]", "*", "command", ".", "Command", "{", "return", "[", "]", "*", "command", ".", "Command", "{", "assert", ".", "New", "(", "driver", ",", "literal", ".", "DefaultBuilder", "(", ")", ",", "chanSize", ",", "bulkTripleOpSize", ")", ",", "benchmark", ".", "New", "(", "driver", ",", "chanSize", ",", "bulkTripleOpSize", ")", ",", "export", ".", "New", "(", "driver", ",", "bulkTripleOpSize", ")", ",", "load", ".", "New", "(", "driver", ",", "bulkTripleOpSize", ",", "builderSize", ")", ",", "run", ".", "New", "(", "driver", ",", "chanSize", ",", "bulkTripleOpSize", ")", ",", "repl", ".", "New", "(", "driver", ",", "chanSize", ",", "bulkTripleOpSize", ",", "builderSize", ",", "rl", ",", "done", ")", ",", "server", ".", "New", "(", "driver", ",", "chanSize", ",", "bulkTripleOpSize", ")", ",", "version", ".", "New", "(", ")", ",", "}", "\n", "}" ]
// InitializeCommands initializes the available commands with the given storage // instance.
[ "InitializeCommands", "initializes", "the", "available", "commands", "with", "the", "given", "storage", "instance", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/vcli/bw/common/common.go#L105-L116
12,366
google/badwolf
tools/vcli/bw/common/common.go
Eval
func Eval(ctx context.Context, args []string, cmds []*command.Command) int { // Retrieve the provided command. if len(args) < 1 { return Help(args, cmds) } cmd := args[0] // Check for help request. if cmd == "help" { return Help(args, cmds) } // Run the requested command. for _, c := range cmds { if c.Name() == cmd { return c.Run(ctx, args) } } // The command was not found. if cmd != "" { fmt.Fprintf(os.Stderr, "command %q not recognized. Usage:\n\n\t$ bw [command]\n\nPlease run\n\n\t$ bw help\n\n", cmd) } return 1 }
go
func Eval(ctx context.Context, args []string, cmds []*command.Command) int { // Retrieve the provided command. if len(args) < 1 { return Help(args, cmds) } cmd := args[0] // Check for help request. if cmd == "help" { return Help(args, cmds) } // Run the requested command. for _, c := range cmds { if c.Name() == cmd { return c.Run(ctx, args) } } // The command was not found. if cmd != "" { fmt.Fprintf(os.Stderr, "command %q not recognized. Usage:\n\n\t$ bw [command]\n\nPlease run\n\n\t$ bw help\n\n", cmd) } return 1 }
[ "func", "Eval", "(", "ctx", "context", ".", "Context", ",", "args", "[", "]", "string", ",", "cmds", "[", "]", "*", "command", ".", "Command", ")", "int", "{", "// Retrieve the provided command.", "if", "len", "(", "args", ")", "<", "1", "{", "return", "Help", "(", "args", ",", "cmds", ")", "\n", "}", "\n", "cmd", ":=", "args", "[", "0", "]", "\n", "// Check for help request.", "if", "cmd", "==", "\"", "\"", "{", "return", "Help", "(", "args", ",", "cmds", ")", "\n", "}", "\n", "// Run the requested command.", "for", "_", ",", "c", ":=", "range", "cmds", "{", "if", "c", ".", "Name", "(", ")", "==", "cmd", "{", "return", "c", ".", "Run", "(", "ctx", ",", "args", ")", "\n", "}", "\n", "}", "\n", "// The command was not found.", "if", "cmd", "!=", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\\n", "\\t", "\\n", "\\n", "\\n", "\\n", "\\t", "\\n", "\\n", "\"", ",", "cmd", ")", "\n", "}", "\n", "return", "1", "\n", "}" ]
// Eval of the command line version tool. This allows injecting multiple // drivers.
[ "Eval", "of", "the", "command", "line", "version", "tool", ".", "This", "allows", "injecting", "multiple", "drivers", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/vcli/bw/common/common.go#L120-L141
12,367
google/badwolf
tools/vcli/bw/common/common.go
Run
func Run(driverName string, args []string, drivers map[string]StoreGenerator, chanSize, bulkTripleOpSize, builderSize int, rl repl.ReadLiner) int { driver, err := InitializeDriver(driverName, drivers) if err != nil { fmt.Fprintln(os.Stderr, err) return 2 } return Eval(context.Background(), args, InitializeCommands(driver, chanSize, bulkTripleOpSize, builderSize, rl, make(chan bool))) }
go
func Run(driverName string, args []string, drivers map[string]StoreGenerator, chanSize, bulkTripleOpSize, builderSize int, rl repl.ReadLiner) int { driver, err := InitializeDriver(driverName, drivers) if err != nil { fmt.Fprintln(os.Stderr, err) return 2 } return Eval(context.Background(), args, InitializeCommands(driver, chanSize, bulkTripleOpSize, builderSize, rl, make(chan bool))) }
[ "func", "Run", "(", "driverName", "string", ",", "args", "[", "]", "string", ",", "drivers", "map", "[", "string", "]", "StoreGenerator", ",", "chanSize", ",", "bulkTripleOpSize", ",", "builderSize", "int", ",", "rl", "repl", ".", "ReadLiner", ")", "int", "{", "driver", ",", "err", ":=", "InitializeDriver", "(", "driverName", ",", "drivers", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "return", "2", "\n", "}", "\n", "return", "Eval", "(", "context", ".", "Background", "(", ")", ",", "args", ",", "InitializeCommands", "(", "driver", ",", "chanSize", ",", "bulkTripleOpSize", ",", "builderSize", ",", "rl", ",", "make", "(", "chan", "bool", ")", ")", ")", "\n", "}" ]
// Run executes the main of the command line tool.
[ "Run", "executes", "the", "main", "of", "the", "command", "line", "tool", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/vcli/bw/common/common.go#L144-L151
12,368
google/badwolf
storage/memoization/memoization.go
Name
func (s *storeMemoizer) Name(ctx context.Context) string { return s.s.Name(ctx) }
go
func (s *storeMemoizer) Name(ctx context.Context) string { return s.s.Name(ctx) }
[ "func", "(", "s", "*", "storeMemoizer", ")", "Name", "(", "ctx", "context", ".", "Context", ")", "string", "{", "return", "s", ".", "s", ".", "Name", "(", "ctx", ")", "\n", "}" ]
// Name returns the ID of the backend being used.
[ "Name", "returns", "the", "ID", "of", "the", "backend", "being", "used", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L46-L48
12,369
google/badwolf
storage/memoization/memoization.go
Version
func (s *storeMemoizer) Version(ctx context.Context) string { return s.s.Version(ctx) }
go
func (s *storeMemoizer) Version(ctx context.Context) string { return s.s.Version(ctx) }
[ "func", "(", "s", "*", "storeMemoizer", ")", "Version", "(", "ctx", "context", ".", "Context", ")", "string", "{", "return", "s", ".", "s", ".", "Version", "(", "ctx", ")", "\n", "}" ]
// Version returns the version of the driver implementation.
[ "Version", "returns", "the", "version", "of", "the", "driver", "implementation", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L51-L53
12,370
google/badwolf
storage/memoization/memoization.go
NewGraph
func (s *storeMemoizer) NewGraph(ctx context.Context, id string) (storage.Graph, error) { g, err := s.s.NewGraph(ctx, id) if err != nil { return nil, err } return &graphMemoizer{ g: g, memN: make(map[string][]*node.Node), memP: make(map[string][]*predicate.Predicate), memO: make(map[string][]*triple.Object), memT: make(map[string][]*triple.Triple), memE: make(map[string]bool), }, nil }
go
func (s *storeMemoizer) NewGraph(ctx context.Context, id string) (storage.Graph, error) { g, err := s.s.NewGraph(ctx, id) if err != nil { return nil, err } return &graphMemoizer{ g: g, memN: make(map[string][]*node.Node), memP: make(map[string][]*predicate.Predicate), memO: make(map[string][]*triple.Object), memT: make(map[string][]*triple.Triple), memE: make(map[string]bool), }, nil }
[ "func", "(", "s", "*", "storeMemoizer", ")", "NewGraph", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "storage", ".", "Graph", ",", "error", ")", "{", "g", ",", "err", ":=", "s", ".", "s", ".", "NewGraph", "(", "ctx", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "graphMemoizer", "{", "g", ":", "g", ",", "memN", ":", "make", "(", "map", "[", "string", "]", "[", "]", "*", "node", ".", "Node", ")", ",", "memP", ":", "make", "(", "map", "[", "string", "]", "[", "]", "*", "predicate", ".", "Predicate", ")", ",", "memO", ":", "make", "(", "map", "[", "string", "]", "[", "]", "*", "triple", ".", "Object", ")", ",", "memT", ":", "make", "(", "map", "[", "string", "]", "[", "]", "*", "triple", ".", "Triple", ")", ",", "memE", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewGraph creates a new graph. Creating an already existing graph // should return an error.
[ "NewGraph", "creates", "a", "new", "graph", ".", "Creating", "an", "already", "existing", "graph", "should", "return", "an", "error", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L57-L70
12,371
google/badwolf
storage/memoization/memoization.go
ID
func (g *graphMemoizer) ID(ctx context.Context) string { return g.g.ID(ctx) }
go
func (g *graphMemoizer) ID(ctx context.Context) string { return g.g.ID(ctx) }
[ "func", "(", "g", "*", "graphMemoizer", ")", "ID", "(", "ctx", "context", ".", "Context", ")", "string", "{", "return", "g", ".", "g", ".", "ID", "(", "ctx", ")", "\n", "}" ]
// ID returns the id for this graph.
[ "ID", "returns", "the", "id", "for", "this", "graph", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L113-L115
12,372
google/badwolf
storage/memoization/memoization.go
AddTriples
func (g *graphMemoizer) AddTriples(ctx context.Context, ts []*triple.Triple) error { g.mu.Lock() // Update operations reset the memoization. g.memN = make(map[string][]*node.Node) g.memP = make(map[string][]*predicate.Predicate) g.memO = make(map[string][]*triple.Object) g.memT = make(map[string][]*triple.Triple) g.memE = make(map[string]bool) g.mu.Unlock() return g.g.AddTriples(ctx, ts) }
go
func (g *graphMemoizer) AddTriples(ctx context.Context, ts []*triple.Triple) error { g.mu.Lock() // Update operations reset the memoization. g.memN = make(map[string][]*node.Node) g.memP = make(map[string][]*predicate.Predicate) g.memO = make(map[string][]*triple.Object) g.memT = make(map[string][]*triple.Triple) g.memE = make(map[string]bool) g.mu.Unlock() return g.g.AddTriples(ctx, ts) }
[ "func", "(", "g", "*", "graphMemoizer", ")", "AddTriples", "(", "ctx", "context", ".", "Context", ",", "ts", "[", "]", "*", "triple", ".", "Triple", ")", "error", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "// Update operations reset the memoization.", "g", ".", "memN", "=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "node", ".", "Node", ")", "\n", "g", ".", "memP", "=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "predicate", ".", "Predicate", ")", "\n", "g", ".", "memO", "=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "triple", ".", "Object", ")", "\n", "g", ".", "memT", "=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "triple", ".", "Triple", ")", "\n", "g", ".", "memE", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "g", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "g", ".", "g", ".", "AddTriples", "(", "ctx", ",", "ts", ")", "\n", "}" ]
// AddTriples adds the triples to the storage. Adding a triple that already // exists should not fail.
[ "AddTriples", "adds", "the", "triples", "to", "the", "storage", ".", "Adding", "a", "triple", "that", "already", "exists", "should", "not", "fail", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L119-L130
12,373
google/badwolf
storage/memoization/memoization.go
Objects
func (g *graphMemoizer) Objects(ctx context.Context, s *node.Node, p *predicate.Predicate, lo *storage.LookupOptions, objs chan<- *triple.Object) error { k := combinedUUID("Objects", lo, s.UUID(), p.UUID()) g.mu.RLock() v := g.memO[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(objs) for _, o := range v { select { case <-ctx.Done(): return nil case objs <- o: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *triple.Object) defer close(objs) var ( err error wg sync.WaitGroup mobjs []*triple.Object ) wg.Add(1) go func() { err = g.g.Objects(ctx, s, p, lo, c) wg.Done() }() for o := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case objs <- o: // memoize the object. mobjs = append(mobjs, o) } } wg.Wait() g.mu.Lock() g.memO[k] = mobjs g.mu.Unlock() return err }
go
func (g *graphMemoizer) Objects(ctx context.Context, s *node.Node, p *predicate.Predicate, lo *storage.LookupOptions, objs chan<- *triple.Object) error { k := combinedUUID("Objects", lo, s.UUID(), p.UUID()) g.mu.RLock() v := g.memO[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(objs) for _, o := range v { select { case <-ctx.Done(): return nil case objs <- o: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *triple.Object) defer close(objs) var ( err error wg sync.WaitGroup mobjs []*triple.Object ) wg.Add(1) go func() { err = g.g.Objects(ctx, s, p, lo, c) wg.Done() }() for o := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case objs <- o: // memoize the object. mobjs = append(mobjs, o) } } wg.Wait() g.mu.Lock() g.memO[k] = mobjs g.mu.Unlock() return err }
[ "func", "(", "g", "*", "graphMemoizer", ")", "Objects", "(", "ctx", "context", ".", "Context", ",", "s", "*", "node", ".", "Node", ",", "p", "*", "predicate", ".", "Predicate", ",", "lo", "*", "storage", ".", "LookupOptions", ",", "objs", "chan", "<-", "*", "triple", ".", "Object", ")", "error", "{", "k", ":=", "combinedUUID", "(", "\"", "\"", ",", "lo", ",", "s", ".", "UUID", "(", ")", ",", "p", ".", "UUID", "(", ")", ")", "\n", "g", ".", "mu", ".", "RLock", "(", ")", "\n", "v", ":=", "g", ".", "memO", "[", "k", "]", "\n", "g", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "v", "!=", "nil", "{", "// Return the memoized results.", "defer", "close", "(", "objs", ")", "\n", "for", "_", ",", "o", ":=", "range", "v", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "case", "objs", "<-", "o", ":", "// Nothing to do.", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Query and memoize the results.", "c", ":=", "make", "(", "chan", "*", "triple", ".", "Object", ")", "\n", "defer", "close", "(", "objs", ")", "\n\n", "var", "(", "err", "error", "\n", "wg", "sync", ".", "WaitGroup", "\n", "mobjs", "[", "]", "*", "triple", ".", "Object", "\n", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "err", "=", "g", ".", "g", ".", "Objects", "(", "ctx", ",", "s", ",", "p", ",", "lo", ",", "c", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "for", "o", ":=", "range", "c", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "objs", "<-", "o", ":", "// memoize the object.", "mobjs", "=", "append", "(", "mobjs", ",", "o", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "g", ".", "memO", "[", "k", "]", "=", "mobjs", "\n", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Objects pushes to the provided channel the objects for the given object and // predicate. The function does not return immediately. // // Given a subject and a predicate, this method retrieves the objects of // triples that match them. By default, if does not limit the maximum number // of possible objects returned, unless properly specified by provided lookup // options. // // If the provided predicate is immutable it will return all the possible // subject values or the number of max elements specified. There is no // requirement on how to sample the returned max elements. // // If the predicate is an unanchored temporal triple and no time anchors are // provided in the lookup options, it will return all the available objects. // If time anchors are provided, it will return all the values anchored in the // provided time window. If max elements is also provided as part of the // lookup options it will return at most max elements. There is no // specifications on how that sample should be conducted.
[ "Objects", "pushes", "to", "the", "provided", "channel", "the", "objects", "for", "the", "given", "object", "and", "predicate", ".", "The", "function", "does", "not", "return", "immediately", ".", "Given", "a", "subject", "and", "a", "predicate", "this", "method", "retrieves", "the", "objects", "of", "triples", "that", "match", "them", ".", "By", "default", "if", "does", "not", "limit", "the", "maximum", "number", "of", "possible", "objects", "returned", "unless", "properly", "specified", "by", "provided", "lookup", "options", ".", "If", "the", "provided", "predicate", "is", "immutable", "it", "will", "return", "all", "the", "possible", "subject", "values", "or", "the", "number", "of", "max", "elements", "specified", ".", "There", "is", "no", "requirement", "on", "how", "to", "sample", "the", "returned", "max", "elements", ".", "If", "the", "predicate", "is", "an", "unanchored", "temporal", "triple", "and", "no", "time", "anchors", "are", "provided", "in", "the", "lookup", "options", "it", "will", "return", "all", "the", "available", "objects", ".", "If", "time", "anchors", "are", "provided", "it", "will", "return", "all", "the", "values", "anchored", "in", "the", "provided", "time", "window", ".", "If", "max", "elements", "is", "also", "provided", "as", "part", "of", "the", "lookup", "options", "it", "will", "return", "at", "most", "max", "elements", ".", "There", "is", "no", "specifications", "on", "how", "that", "sample", "should", "be", "conducted", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L173-L221
12,374
google/badwolf
storage/memoization/memoization.go
Subjects
func (g *graphMemoizer) Subjects(ctx context.Context, p *predicate.Predicate, o *triple.Object, lo *storage.LookupOptions, subs chan<- *node.Node) error { k := combinedUUID("Subjects", lo, p.UUID(), o.UUID()) g.mu.RLock() v := g.memN[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(subs) for _, s := range v { select { case <-ctx.Done(): return nil case subs <- s: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *node.Node) defer close(subs) var ( err error wg sync.WaitGroup msubs []*node.Node ) wg.Add(1) go func() { err = g.g.Subjects(ctx, p, o, lo, c) wg.Done() }() for s := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case subs <- s: // memoize the object. msubs = append(msubs, s) } } wg.Wait() g.mu.Lock() g.memN[k] = msubs g.mu.Unlock() return err }
go
func (g *graphMemoizer) Subjects(ctx context.Context, p *predicate.Predicate, o *triple.Object, lo *storage.LookupOptions, subs chan<- *node.Node) error { k := combinedUUID("Subjects", lo, p.UUID(), o.UUID()) g.mu.RLock() v := g.memN[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(subs) for _, s := range v { select { case <-ctx.Done(): return nil case subs <- s: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *node.Node) defer close(subs) var ( err error wg sync.WaitGroup msubs []*node.Node ) wg.Add(1) go func() { err = g.g.Subjects(ctx, p, o, lo, c) wg.Done() }() for s := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case subs <- s: // memoize the object. msubs = append(msubs, s) } } wg.Wait() g.mu.Lock() g.memN[k] = msubs g.mu.Unlock() return err }
[ "func", "(", "g", "*", "graphMemoizer", ")", "Subjects", "(", "ctx", "context", ".", "Context", ",", "p", "*", "predicate", ".", "Predicate", ",", "o", "*", "triple", ".", "Object", ",", "lo", "*", "storage", ".", "LookupOptions", ",", "subs", "chan", "<-", "*", "node", ".", "Node", ")", "error", "{", "k", ":=", "combinedUUID", "(", "\"", "\"", ",", "lo", ",", "p", ".", "UUID", "(", ")", ",", "o", ".", "UUID", "(", ")", ")", "\n", "g", ".", "mu", ".", "RLock", "(", ")", "\n", "v", ":=", "g", ".", "memN", "[", "k", "]", "\n", "g", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "v", "!=", "nil", "{", "// Return the memoized results.", "defer", "close", "(", "subs", ")", "\n", "for", "_", ",", "s", ":=", "range", "v", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "case", "subs", "<-", "s", ":", "// Nothing to do.", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Query and memoize the results.", "c", ":=", "make", "(", "chan", "*", "node", ".", "Node", ")", "\n", "defer", "close", "(", "subs", ")", "\n\n", "var", "(", "err", "error", "\n", "wg", "sync", ".", "WaitGroup", "\n", "msubs", "[", "]", "*", "node", ".", "Node", "\n", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "err", "=", "g", ".", "g", ".", "Subjects", "(", "ctx", ",", "p", ",", "o", ",", "lo", ",", "c", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "for", "s", ":=", "range", "c", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "subs", "<-", "s", ":", "// memoize the object.", "msubs", "=", "append", "(", "msubs", ",", "s", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "g", ".", "memN", "[", "k", "]", "=", "msubs", "\n", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Subject pushes to the provided channel the subjects for the give predicate // and object. The function does not return immediately. The caller is // expected to detach them into a go routine. // // Given a predicate and an object, this method retrieves the subjects of // triples that matches them. By default, it does not limit the maximum number // of possible subjects returned, unless properly specified by provided lookup // options. // // If the provided predicate is immutable it will return all the possible // subject values or the number of max elements specified. There is no // requirement on how to sample the returned max elements. // // If the predicate is an unanchored temporal triple and no time anchors are // provided in the lookup options, it will return all the available subjects. // If time anchors are provided, it will return all the values anchored in the // provided time window. If max elements is also provided as part of the // lookup options it will return the at most max elements. There is no // specifications on how that sample should be conducted.
[ "Subject", "pushes", "to", "the", "provided", "channel", "the", "subjects", "for", "the", "give", "predicate", "and", "object", ".", "The", "function", "does", "not", "return", "immediately", ".", "The", "caller", "is", "expected", "to", "detach", "them", "into", "a", "go", "routine", ".", "Given", "a", "predicate", "and", "an", "object", "this", "method", "retrieves", "the", "subjects", "of", "triples", "that", "matches", "them", ".", "By", "default", "it", "does", "not", "limit", "the", "maximum", "number", "of", "possible", "subjects", "returned", "unless", "properly", "specified", "by", "provided", "lookup", "options", ".", "If", "the", "provided", "predicate", "is", "immutable", "it", "will", "return", "all", "the", "possible", "subject", "values", "or", "the", "number", "of", "max", "elements", "specified", ".", "There", "is", "no", "requirement", "on", "how", "to", "sample", "the", "returned", "max", "elements", ".", "If", "the", "predicate", "is", "an", "unanchored", "temporal", "triple", "and", "no", "time", "anchors", "are", "provided", "in", "the", "lookup", "options", "it", "will", "return", "all", "the", "available", "subjects", ".", "If", "time", "anchors", "are", "provided", "it", "will", "return", "all", "the", "values", "anchored", "in", "the", "provided", "time", "window", ".", "If", "max", "elements", "is", "also", "provided", "as", "part", "of", "the", "lookup", "options", "it", "will", "return", "the", "at", "most", "max", "elements", ".", "There", "is", "no", "specifications", "on", "how", "that", "sample", "should", "be", "conducted", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L242-L290
12,375
google/badwolf
storage/memoization/memoization.go
PredicatesForSubjectAndObject
func (g *graphMemoizer) PredicatesForSubjectAndObject(ctx context.Context, s *node.Node, o *triple.Object, lo *storage.LookupOptions, prds chan<- *predicate.Predicate) error { k := combinedUUID("PredicatesForSubjectAndObject", lo, s.UUID(), o.UUID()) g.mu.RLock() v := g.memP[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(prds) for _, p := range v { select { case <-ctx.Done(): return nil case prds <- p: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *predicate.Predicate) defer close(prds) var ( err error wg sync.WaitGroup mpreds []*predicate.Predicate ) wg.Add(1) go func() { err = g.g.PredicatesForSubjectAndObject(ctx, s, o, lo, c) wg.Done() }() for p := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case prds <- p: // memoize the object. mpreds = append(mpreds, p) } } wg.Wait() g.mu.Lock() g.memP[k] = mpreds g.mu.Unlock() return err }
go
func (g *graphMemoizer) PredicatesForSubjectAndObject(ctx context.Context, s *node.Node, o *triple.Object, lo *storage.LookupOptions, prds chan<- *predicate.Predicate) error { k := combinedUUID("PredicatesForSubjectAndObject", lo, s.UUID(), o.UUID()) g.mu.RLock() v := g.memP[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(prds) for _, p := range v { select { case <-ctx.Done(): return nil case prds <- p: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *predicate.Predicate) defer close(prds) var ( err error wg sync.WaitGroup mpreds []*predicate.Predicate ) wg.Add(1) go func() { err = g.g.PredicatesForSubjectAndObject(ctx, s, o, lo, c) wg.Done() }() for p := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case prds <- p: // memoize the object. mpreds = append(mpreds, p) } } wg.Wait() g.mu.Lock() g.memP[k] = mpreds g.mu.Unlock() return err }
[ "func", "(", "g", "*", "graphMemoizer", ")", "PredicatesForSubjectAndObject", "(", "ctx", "context", ".", "Context", ",", "s", "*", "node", ".", "Node", ",", "o", "*", "triple", ".", "Object", ",", "lo", "*", "storage", ".", "LookupOptions", ",", "prds", "chan", "<-", "*", "predicate", ".", "Predicate", ")", "error", "{", "k", ":=", "combinedUUID", "(", "\"", "\"", ",", "lo", ",", "s", ".", "UUID", "(", ")", ",", "o", ".", "UUID", "(", ")", ")", "\n", "g", ".", "mu", ".", "RLock", "(", ")", "\n", "v", ":=", "g", ".", "memP", "[", "k", "]", "\n", "g", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "v", "!=", "nil", "{", "// Return the memoized results.", "defer", "close", "(", "prds", ")", "\n", "for", "_", ",", "p", ":=", "range", "v", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "case", "prds", "<-", "p", ":", "// Nothing to do.", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Query and memoize the results.", "c", ":=", "make", "(", "chan", "*", "predicate", ".", "Predicate", ")", "\n", "defer", "close", "(", "prds", ")", "\n\n", "var", "(", "err", "error", "\n", "wg", "sync", ".", "WaitGroup", "\n", "mpreds", "[", "]", "*", "predicate", ".", "Predicate", "\n", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "err", "=", "g", ".", "g", ".", "PredicatesForSubjectAndObject", "(", "ctx", ",", "s", ",", "o", ",", "lo", ",", "c", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "for", "p", ":=", "range", "c", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "prds", "<-", "p", ":", "// memoize the object.", "mpreds", "=", "append", "(", "mpreds", ",", "p", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "g", ".", "memP", "[", "k", "]", "=", "mpreds", "\n", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// PredicatesForSubjectAndObject pushes to the provided channel all predicates // available for the given subject and object. The function does not return // immediately. The caller is expected to detach them into a go routine. // // If the lookup options provide a max number of elements the function will // return a sample of the available predicates. If time anchor bounds are // provided in the lookup options, only predicates matching the provided type // window would be return. Same sampling consideration apply if max element is // provided.
[ "PredicatesForSubjectAndObject", "pushes", "to", "the", "provided", "channel", "all", "predicates", "available", "for", "the", "given", "subject", "and", "object", ".", "The", "function", "does", "not", "return", "immediately", ".", "The", "caller", "is", "expected", "to", "detach", "them", "into", "a", "go", "routine", ".", "If", "the", "lookup", "options", "provide", "a", "max", "number", "of", "elements", "the", "function", "will", "return", "a", "sample", "of", "the", "available", "predicates", ".", "If", "time", "anchor", "bounds", "are", "provided", "in", "the", "lookup", "options", "only", "predicates", "matching", "the", "provided", "type", "window", "would", "be", "return", ".", "Same", "sampling", "consideration", "apply", "if", "max", "element", "is", "provided", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L419-L467
12,376
google/badwolf
storage/memoization/memoization.go
TriplesForSubject
func (g *graphMemoizer) TriplesForSubject(ctx context.Context, s *node.Node, lo *storage.LookupOptions, trpls chan<- *triple.Triple) error { k := combinedUUID("TriplesForSubject", lo, s.UUID()) g.mu.RLock() v := g.memT[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(trpls) for _, t := range v { select { case <-ctx.Done(): return nil case trpls <- t: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *triple.Triple) defer close(trpls) var ( err error wg sync.WaitGroup mts []*triple.Triple ) wg.Add(1) go func() { err = g.g.TriplesForSubject(ctx, s, lo, c) wg.Done() }() for t := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case trpls <- t: // memoize the object. mts = append(mts, t) } } wg.Wait() g.mu.Lock() g.memT[k] = mts g.mu.Unlock() return err }
go
func (g *graphMemoizer) TriplesForSubject(ctx context.Context, s *node.Node, lo *storage.LookupOptions, trpls chan<- *triple.Triple) error { k := combinedUUID("TriplesForSubject", lo, s.UUID()) g.mu.RLock() v := g.memT[k] g.mu.RUnlock() if v != nil { // Return the memoized results. defer close(trpls) for _, t := range v { select { case <-ctx.Done(): return nil case trpls <- t: // Nothing to do. } } return nil } // Query and memoize the results. c := make(chan *triple.Triple) defer close(trpls) var ( err error wg sync.WaitGroup mts []*triple.Triple ) wg.Add(1) go func() { err = g.g.TriplesForSubject(ctx, s, lo, c) wg.Done() }() for t := range c { select { case <-ctx.Done(): return errors.New("context cancelled") case trpls <- t: // memoize the object. mts = append(mts, t) } } wg.Wait() g.mu.Lock() g.memT[k] = mts g.mu.Unlock() return err }
[ "func", "(", "g", "*", "graphMemoizer", ")", "TriplesForSubject", "(", "ctx", "context", ".", "Context", ",", "s", "*", "node", ".", "Node", ",", "lo", "*", "storage", ".", "LookupOptions", ",", "trpls", "chan", "<-", "*", "triple", ".", "Triple", ")", "error", "{", "k", ":=", "combinedUUID", "(", "\"", "\"", ",", "lo", ",", "s", ".", "UUID", "(", ")", ")", "\n", "g", ".", "mu", ".", "RLock", "(", ")", "\n", "v", ":=", "g", ".", "memT", "[", "k", "]", "\n", "g", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "v", "!=", "nil", "{", "// Return the memoized results.", "defer", "close", "(", "trpls", ")", "\n", "for", "_", ",", "t", ":=", "range", "v", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "case", "trpls", "<-", "t", ":", "// Nothing to do.", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Query and memoize the results.", "c", ":=", "make", "(", "chan", "*", "triple", ".", "Triple", ")", "\n", "defer", "close", "(", "trpls", ")", "\n\n", "var", "(", "err", "error", "\n", "wg", "sync", ".", "WaitGroup", "\n", "mts", "[", "]", "*", "triple", ".", "Triple", "\n", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "err", "=", "g", ".", "g", ".", "TriplesForSubject", "(", "ctx", ",", "s", ",", "lo", ",", "c", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "for", "t", ":=", "range", "c", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "trpls", "<-", "t", ":", "// memoize the object.", "mts", "=", "append", "(", "mts", ",", "t", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "g", ".", "memT", "[", "k", "]", "=", "mts", "\n", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// TriplesForSubject pushes to the provided channel all triples available for // the given subject. The function does not return immediately. The caller // is expected to detach them into a go routine. // // If the lookup options provide a max number of elements the function will // return a sample of the available triples. If time anchor bounds are // provided in the lookup options, only predicates matching the provided type // window would be return. Same sampling consideration apply if max element is // provided.
[ "TriplesForSubject", "pushes", "to", "the", "provided", "channel", "all", "triples", "available", "for", "the", "given", "subject", ".", "The", "function", "does", "not", "return", "immediately", ".", "The", "caller", "is", "expected", "to", "detach", "them", "into", "a", "go", "routine", ".", "If", "the", "lookup", "options", "provide", "a", "max", "number", "of", "elements", "the", "function", "will", "return", "a", "sample", "of", "the", "available", "triples", ".", "If", "time", "anchor", "bounds", "are", "provided", "in", "the", "lookup", "options", "only", "predicates", "matching", "the", "provided", "type", "window", "would", "be", "return", ".", "Same", "sampling", "consideration", "apply", "if", "max", "element", "is", "provided", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/storage/memoization/memoization.go#L478-L526
12,377
google/badwolf
bql/planner/planner.go
Execute
func (p *createPlan) Execute(ctx context.Context) (*table.Table, error) { t, err := table.New([]string{}) if err != nil { return nil, err } errs := []string{} for _, g := range p.stm.GraphNames() { tracer.Trace(p.tracer, func() []string { return []string{"Creating new graph \"" + g + "\""} }) if _, err := p.store.NewGraph(ctx, g); err != nil { errs = append(errs, err.Error()) } } if len(errs) > 0 { return nil, errors.New(strings.Join(errs, "; ")) } return t, nil }
go
func (p *createPlan) Execute(ctx context.Context) (*table.Table, error) { t, err := table.New([]string{}) if err != nil { return nil, err } errs := []string{} for _, g := range p.stm.GraphNames() { tracer.Trace(p.tracer, func() []string { return []string{"Creating new graph \"" + g + "\""} }) if _, err := p.store.NewGraph(ctx, g); err != nil { errs = append(errs, err.Error()) } } if len(errs) > 0 { return nil, errors.New(strings.Join(errs, "; ")) } return t, nil }
[ "func", "(", "p", "*", "createPlan", ")", "Execute", "(", "ctx", "context", ".", "Context", ")", "(", "*", "table", ".", "Table", ",", "error", ")", "{", "t", ",", "err", ":=", "table", ".", "New", "(", "[", "]", "string", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "errs", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "g", ":=", "range", "p", ".", "stm", ".", "GraphNames", "(", ")", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\\\"", "\"", "+", "g", "+", "\"", "\\\"", "\"", "}", "\n", "}", ")", "\n", "if", "_", ",", "err", ":=", "p", ".", "store", ".", "NewGraph", "(", "ctx", ",", "g", ")", ";", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "errs", ")", ">", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "strings", ".", "Join", "(", "errs", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}" ]
// Execute creates the indicated graphs.
[ "Execute", "creates", "the", "indicated", "graphs", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L66-L84
12,378
google/badwolf
bql/planner/planner.go
Execute
func (p *insertPlan) Execute(ctx context.Context) (*table.Table, error) { t, err := table.New([]string{}) if err != nil { return nil, err } return t, update(ctx, p.stm.Data(), p.stm.OutputGraphNames(), p.store, func(g storage.Graph, d []*triple.Triple) error { tracer.Trace(p.tracer, func() []string { return []string{"Inserting triples to graph \"" + g.ID(ctx) + "\""} }) return g.AddTriples(ctx, d) }) }
go
func (p *insertPlan) Execute(ctx context.Context) (*table.Table, error) { t, err := table.New([]string{}) if err != nil { return nil, err } return t, update(ctx, p.stm.Data(), p.stm.OutputGraphNames(), p.store, func(g storage.Graph, d []*triple.Triple) error { tracer.Trace(p.tracer, func() []string { return []string{"Inserting triples to graph \"" + g.ID(ctx) + "\""} }) return g.AddTriples(ctx, d) }) }
[ "func", "(", "p", "*", "insertPlan", ")", "Execute", "(", "ctx", "context", ".", "Context", ")", "(", "*", "table", ".", "Table", ",", "error", ")", "{", "t", ",", "err", ":=", "table", ".", "New", "(", "[", "]", "string", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "t", ",", "update", "(", "ctx", ",", "p", ".", "stm", ".", "Data", "(", ")", ",", "p", ".", "stm", ".", "OutputGraphNames", "(", ")", ",", "p", ".", "store", ",", "func", "(", "g", "storage", ".", "Graph", ",", "d", "[", "]", "*", "triple", ".", "Triple", ")", "error", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\\\"", "\"", "+", "g", ".", "ID", "(", "ctx", ")", "+", "\"", "\\\"", "\"", "}", "\n", "}", ")", "\n", "return", "g", ".", "AddTriples", "(", "ctx", ",", "d", ")", "\n", "}", ")", "\n", "}" ]
// Execute inserts the provided data into the indicated graphs.
[ "Execute", "inserts", "the", "provided", "data", "into", "the", "indicated", "graphs", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L180-L191
12,379
google/badwolf
bql/planner/planner.go
newQueryPlan
func newQueryPlan(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize int, w io.Writer) (*queryPlan, error) { bs := []string{} for _, b := range stm.Bindings() { bs = append(bs, b) } t, err := table.New([]string{}) if err != nil { return nil, err } return &queryPlan{ stm: stm, store: store, bndgs: bs, grfsNames: stm.InputGraphNames(), cls: stm.GraphPatternClauses(), tbl: t, chanSize: chanSize, tracer: w, }, nil }
go
func newQueryPlan(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize int, w io.Writer) (*queryPlan, error) { bs := []string{} for _, b := range stm.Bindings() { bs = append(bs, b) } t, err := table.New([]string{}) if err != nil { return nil, err } return &queryPlan{ stm: stm, store: store, bndgs: bs, grfsNames: stm.InputGraphNames(), cls: stm.GraphPatternClauses(), tbl: t, chanSize: chanSize, tracer: w, }, nil }
[ "func", "newQueryPlan", "(", "ctx", "context", ".", "Context", ",", "store", "storage", ".", "Store", ",", "stm", "*", "semantic", ".", "Statement", ",", "chanSize", "int", ",", "w", "io", ".", "Writer", ")", "(", "*", "queryPlan", ",", "error", ")", "{", "bs", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "b", ":=", "range", "stm", ".", "Bindings", "(", ")", "{", "bs", "=", "append", "(", "bs", ",", "b", ")", "\n", "}", "\n", "t", ",", "err", ":=", "table", ".", "New", "(", "[", "]", "string", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "queryPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "bndgs", ":", "bs", ",", "grfsNames", ":", "stm", ".", "InputGraphNames", "(", ")", ",", "cls", ":", "stm", ".", "GraphPatternClauses", "(", ")", ",", "tbl", ":", "t", ",", "chanSize", ":", "chanSize", ",", "tracer", ":", "w", ",", "}", ",", "nil", "\n", "}" ]
// newQueryPlan returns a new query plan ready to be executed.
[ "newQueryPlan", "returns", "a", "new", "query", "plan", "ready", "to", "be", "executed", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L272-L291
12,380
google/badwolf
bql/planner/planner.go
processClause
func (p *queryPlan) processClause(ctx context.Context, cls *semantic.GraphClause, lo *storage.LookupOptions) (bool, error) { // This method decides how to process the clause based on the current // list of bindings solved and data available. if cls.Specificity() == 3 { tracer.Trace(p.tracer, func() []string { return []string{"Clause is fully specified"} }) t, err := triple.New(cls.S, cls.P, cls.O) if err != nil { return false, err } b, tbl, err := simpleExist(ctx, p.grfs, cls, t) if err != nil { return false, err } if err := p.tbl.AppendTable(tbl); err != nil { return b, err } return b, nil } exist, total := 0, 0 var existing []string for _, b := range cls.Bindings() { total++ if p.tbl.HasBinding(b) { exist++ existing = append(existing, b) } } if exist == 0 { tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("None of the clause binding exist %v/%v", cls.Bindings(), existing)} }) // Data is new. stmLimit := int64(0) if len(p.stm.GraphPatternClauses()) == 1 && len(p.stm.GroupBy()) == 0 && len(p.stm.HavingExpression()) == 0 { stmLimit = p.stm.Limit() } tbl, err := simpleFetch(ctx, p.grfs, cls, lo, stmLimit, p.chanSize, p.tracer) if err != nil { return false, err } if len(p.tbl.Bindings()) > 0 { return false, p.tbl.DotProduct(tbl) } return false, p.tbl.AppendTable(tbl) } tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("Some clause binding exist %v/%v", cls.Bindings(), existing)} }) return false, p.specifyClauseWithTable(ctx, cls, lo) }
go
func (p *queryPlan) processClause(ctx context.Context, cls *semantic.GraphClause, lo *storage.LookupOptions) (bool, error) { // This method decides how to process the clause based on the current // list of bindings solved and data available. if cls.Specificity() == 3 { tracer.Trace(p.tracer, func() []string { return []string{"Clause is fully specified"} }) t, err := triple.New(cls.S, cls.P, cls.O) if err != nil { return false, err } b, tbl, err := simpleExist(ctx, p.grfs, cls, t) if err != nil { return false, err } if err := p.tbl.AppendTable(tbl); err != nil { return b, err } return b, nil } exist, total := 0, 0 var existing []string for _, b := range cls.Bindings() { total++ if p.tbl.HasBinding(b) { exist++ existing = append(existing, b) } } if exist == 0 { tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("None of the clause binding exist %v/%v", cls.Bindings(), existing)} }) // Data is new. stmLimit := int64(0) if len(p.stm.GraphPatternClauses()) == 1 && len(p.stm.GroupBy()) == 0 && len(p.stm.HavingExpression()) == 0 { stmLimit = p.stm.Limit() } tbl, err := simpleFetch(ctx, p.grfs, cls, lo, stmLimit, p.chanSize, p.tracer) if err != nil { return false, err } if len(p.tbl.Bindings()) > 0 { return false, p.tbl.DotProduct(tbl) } return false, p.tbl.AppendTable(tbl) } tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("Some clause binding exist %v/%v", cls.Bindings(), existing)} }) return false, p.specifyClauseWithTable(ctx, cls, lo) }
[ "func", "(", "p", "*", "queryPlan", ")", "processClause", "(", "ctx", "context", ".", "Context", ",", "cls", "*", "semantic", ".", "GraphClause", ",", "lo", "*", "storage", ".", "LookupOptions", ")", "(", "bool", ",", "error", ")", "{", "// This method decides how to process the clause based on the current", "// list of bindings solved and data available.", "if", "cls", ".", "Specificity", "(", ")", "==", "3", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", ")", "\n", "t", ",", "err", ":=", "triple", ".", "New", "(", "cls", ".", "S", ",", "cls", ".", "P", ",", "cls", ".", "O", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "b", ",", "tbl", ",", "err", ":=", "simpleExist", "(", "ctx", ",", "p", ".", "grfs", ",", "cls", ",", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "err", ":=", "p", ".", "tbl", ".", "AppendTable", "(", "tbl", ")", ";", "err", "!=", "nil", "{", "return", "b", ",", "err", "\n", "}", "\n", "return", "b", ",", "nil", "\n", "}", "\n\n", "exist", ",", "total", ":=", "0", ",", "0", "\n", "var", "existing", "[", "]", "string", "\n", "for", "_", ",", "b", ":=", "range", "cls", ".", "Bindings", "(", ")", "{", "total", "++", "\n", "if", "p", ".", "tbl", ".", "HasBinding", "(", "b", ")", "{", "exist", "++", "\n", "existing", "=", "append", "(", "existing", ",", "b", ")", "\n", "}", "\n", "}", "\n\n", "if", "exist", "==", "0", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cls", ".", "Bindings", "(", ")", ",", "existing", ")", "}", "\n", "}", ")", "\n", "// Data is new.", "stmLimit", ":=", "int64", "(", "0", ")", "\n", "if", "len", "(", "p", ".", "stm", ".", "GraphPatternClauses", "(", ")", ")", "==", "1", "&&", "len", "(", "p", ".", "stm", ".", "GroupBy", "(", ")", ")", "==", "0", "&&", "len", "(", "p", ".", "stm", ".", "HavingExpression", "(", ")", ")", "==", "0", "{", "stmLimit", "=", "p", ".", "stm", ".", "Limit", "(", ")", "\n", "}", "\n", "tbl", ",", "err", ":=", "simpleFetch", "(", "ctx", ",", "p", ".", "grfs", ",", "cls", ",", "lo", ",", "stmLimit", ",", "p", ".", "chanSize", ",", "p", ".", "tracer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "len", "(", "p", ".", "tbl", ".", "Bindings", "(", ")", ")", ">", "0", "{", "return", "false", ",", "p", ".", "tbl", ".", "DotProduct", "(", "tbl", ")", "\n", "}", "\n", "return", "false", ",", "p", ".", "tbl", ".", "AppendTable", "(", "tbl", ")", "\n", "}", "\n\n", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cls", ".", "Bindings", "(", ")", ",", "existing", ")", "}", "\n", "}", ")", "\n", "return", "false", ",", "p", ".", "specifyClauseWithTable", "(", "ctx", ",", "cls", ",", "lo", ")", "\n", "}" ]
// processClause retrieves the triples for the provided triple given the // information available.
[ "processClause", "retrieves", "the", "triples", "for", "the", "provided", "triple", "given", "the", "information", "available", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L295-L349
12,381
google/badwolf
bql/planner/planner.go
getBoundValueForComponent
func getBoundValueForComponent(r table.Row, bs []string) *table.Cell { var cs []*table.Cell for _, b := range bs { if v, ok := r[b]; ok { cs = append(cs, v) } } if len(cs) == 1 || len(cs) == 2 && reflect.DeepEqual(cs[0], cs[1]) { return cs[0] } return nil }
go
func getBoundValueForComponent(r table.Row, bs []string) *table.Cell { var cs []*table.Cell for _, b := range bs { if v, ok := r[b]; ok { cs = append(cs, v) } } if len(cs) == 1 || len(cs) == 2 && reflect.DeepEqual(cs[0], cs[1]) { return cs[0] } return nil }
[ "func", "getBoundValueForComponent", "(", "r", "table", ".", "Row", ",", "bs", "[", "]", "string", ")", "*", "table", ".", "Cell", "{", "var", "cs", "[", "]", "*", "table", ".", "Cell", "\n", "for", "_", ",", "b", ":=", "range", "bs", "{", "if", "v", ",", "ok", ":=", "r", "[", "b", "]", ";", "ok", "{", "cs", "=", "append", "(", "cs", ",", "v", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "cs", ")", "==", "1", "||", "len", "(", "cs", ")", "==", "2", "&&", "reflect", ".", "DeepEqual", "(", "cs", "[", "0", "]", ",", "cs", "[", "1", "]", ")", "{", "return", "cs", "[", "0", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getBoundValueForComponent return the unique bound value if available on // the provided row.
[ "getBoundValueForComponent", "return", "the", "unique", "bound", "value", "if", "available", "on", "the", "provided", "row", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L353-L364
12,382
google/badwolf
bql/planner/planner.go
specifyClauseWithTable
func (p *queryPlan) specifyClauseWithTable(ctx context.Context, cls *semantic.GraphClause, lo *storage.LookupOptions) error { rws := p.tbl.Rows() p.tbl.Truncate() var ( gErr error mu sync.Mutex wg sync.WaitGroup ) for _, tmpRow := range rws { wg.Add(1) go func(r table.Row) { defer wg.Done() var tmpCls = *cls // The table manipulations are now thread safe. if err := p.addSpecifiedData(ctx, r, &tmpCls, lo); err != nil { mu.Lock() gErr = err mu.Unlock() } }(tmpRow) } wg.Wait() return gErr }
go
func (p *queryPlan) specifyClauseWithTable(ctx context.Context, cls *semantic.GraphClause, lo *storage.LookupOptions) error { rws := p.tbl.Rows() p.tbl.Truncate() var ( gErr error mu sync.Mutex wg sync.WaitGroup ) for _, tmpRow := range rws { wg.Add(1) go func(r table.Row) { defer wg.Done() var tmpCls = *cls // The table manipulations are now thread safe. if err := p.addSpecifiedData(ctx, r, &tmpCls, lo); err != nil { mu.Lock() gErr = err mu.Unlock() } }(tmpRow) } wg.Wait() return gErr }
[ "func", "(", "p", "*", "queryPlan", ")", "specifyClauseWithTable", "(", "ctx", "context", ".", "Context", ",", "cls", "*", "semantic", ".", "GraphClause", ",", "lo", "*", "storage", ".", "LookupOptions", ")", "error", "{", "rws", ":=", "p", ".", "tbl", ".", "Rows", "(", ")", "\n", "p", ".", "tbl", ".", "Truncate", "(", ")", "\n", "var", "(", "gErr", "error", "\n", "mu", "sync", ".", "Mutex", "\n", "wg", "sync", ".", "WaitGroup", "\n", ")", "\n", "for", "_", ",", "tmpRow", ":=", "range", "rws", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "r", "table", ".", "Row", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "var", "tmpCls", "=", "*", "cls", "\n", "// The table manipulations are now thread safe.", "if", "err", ":=", "p", ".", "addSpecifiedData", "(", "ctx", ",", "r", ",", "&", "tmpCls", ",", "lo", ")", ";", "err", "!=", "nil", "{", "mu", ".", "Lock", "(", ")", "\n", "gErr", "=", "err", "\n", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "(", "tmpRow", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "gErr", "\n", "}" ]
// specifyClauseWithTable runs the clause, but it specifies it further based on // the current row being processed.
[ "specifyClauseWithTable", "runs", "the", "clause", "but", "it", "specifies", "it", "further", "based", "on", "the", "current", "row", "being", "processed", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L447-L470
12,383
google/badwolf
bql/planner/planner.go
cellToObject
func cellToObject(c *table.Cell) (*triple.Object, error) { if c == nil { return nil, errors.New("cannot create an object out of and empty cell") } if c.N != nil { return triple.NewNodeObject(c.N), nil } if c.P != nil { return triple.NewPredicateObject(c.P), nil } if c.L != nil { return triple.NewLiteralObject(c.L), nil } if c.S != nil { l, err := literal.DefaultBuilder().Parse(fmt.Sprintf(`"%s"^^type:string`, *c.S)) if err != nil { return nil, err } return triple.NewLiteralObject(l), nil } return nil, fmt.Errorf("invalid cell %v", c) }
go
func cellToObject(c *table.Cell) (*triple.Object, error) { if c == nil { return nil, errors.New("cannot create an object out of and empty cell") } if c.N != nil { return triple.NewNodeObject(c.N), nil } if c.P != nil { return triple.NewPredicateObject(c.P), nil } if c.L != nil { return triple.NewLiteralObject(c.L), nil } if c.S != nil { l, err := literal.DefaultBuilder().Parse(fmt.Sprintf(`"%s"^^type:string`, *c.S)) if err != nil { return nil, err } return triple.NewLiteralObject(l), nil } return nil, fmt.Errorf("invalid cell %v", c) }
[ "func", "cellToObject", "(", "c", "*", "table", ".", "Cell", ")", "(", "*", "triple", ".", "Object", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "N", "!=", "nil", "{", "return", "triple", ".", "NewNodeObject", "(", "c", ".", "N", ")", ",", "nil", "\n", "}", "\n", "if", "c", ".", "P", "!=", "nil", "{", "return", "triple", ".", "NewPredicateObject", "(", "c", ".", "P", ")", ",", "nil", "\n", "}", "\n", "if", "c", ".", "L", "!=", "nil", "{", "return", "triple", ".", "NewLiteralObject", "(", "c", ".", "L", ")", ",", "nil", "\n", "}", "\n", "if", "c", ".", "S", "!=", "nil", "{", "l", ",", "err", ":=", "literal", ".", "DefaultBuilder", "(", ")", ".", "Parse", "(", "fmt", ".", "Sprintf", "(", "`\"%s\"^^type:string`", ",", "*", "c", ".", "S", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "triple", ".", "NewLiteralObject", "(", "l", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ")", "\n", "}" ]
// cellToObject returns an object for the given cell.
[ "cellToObject", "returns", "an", "object", "for", "the", "given", "cell", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L473-L494
12,384
google/badwolf
bql/planner/planner.go
processGraphPattern
func (p *queryPlan) processGraphPattern(ctx context.Context, lo *storage.LookupOptions) error { tracer.Trace(p.tracer, func() []string { var res []string for i, cls := range p.cls { res = append(res, fmt.Sprintf("Clause %d to process: %v", i, cls)) } return res }) for i, c := range p.cls { i, cls := i, *c tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("Processing clause %d: %v", i, &cls)} }) // The current planner is based on naively executing clauses by // specificity. unresolvable, err := p.processClause(ctx, &cls, lo) if err != nil { return err } if unresolvable { p.tbl.Truncate() return nil } } return nil }
go
func (p *queryPlan) processGraphPattern(ctx context.Context, lo *storage.LookupOptions) error { tracer.Trace(p.tracer, func() []string { var res []string for i, cls := range p.cls { res = append(res, fmt.Sprintf("Clause %d to process: %v", i, cls)) } return res }) for i, c := range p.cls { i, cls := i, *c tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("Processing clause %d: %v", i, &cls)} }) // The current planner is based on naively executing clauses by // specificity. unresolvable, err := p.processClause(ctx, &cls, lo) if err != nil { return err } if unresolvable { p.tbl.Truncate() return nil } } return nil }
[ "func", "(", "p", "*", "queryPlan", ")", "processGraphPattern", "(", "ctx", "context", ".", "Context", ",", "lo", "*", "storage", ".", "LookupOptions", ")", "error", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "var", "res", "[", "]", "string", "\n", "for", "i", ",", "cls", ":=", "range", "p", ".", "cls", "{", "res", "=", "append", "(", "res", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ",", "cls", ")", ")", "\n", "}", "\n", "return", "res", "\n", "}", ")", "\n", "for", "i", ",", "c", ":=", "range", "p", ".", "cls", "{", "i", ",", "cls", ":=", "i", ",", "*", "c", "\n", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ",", "&", "cls", ")", "}", "\n", "}", ")", "\n", "// The current planner is based on naively executing clauses by", "// specificity.", "unresolvable", ",", "err", ":=", "p", ".", "processClause", "(", "ctx", ",", "&", "cls", ",", "lo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "unresolvable", "{", "p", ".", "tbl", ".", "Truncate", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processGraphPattern process the query graph pattern to retrieve the // data from the specified graphs.
[ "processGraphPattern", "process", "the", "query", "graph", "pattern", "to", "retrieve", "the", "data", "from", "the", "specified", "graphs", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L663-L688
12,385
google/badwolf
bql/planner/planner.go
orderBy
func (p *queryPlan) orderBy() { order := p.stm.OrderByConfig() if len(order) <= 0 { return } tracer.Trace(p.tracer, func() []string { return []string{"Ordering by " + order.String()} }) p.tbl.Sort(order) }
go
func (p *queryPlan) orderBy() { order := p.stm.OrderByConfig() if len(order) <= 0 { return } tracer.Trace(p.tracer, func() []string { return []string{"Ordering by " + order.String()} }) p.tbl.Sort(order) }
[ "func", "(", "p", "*", "queryPlan", ")", "orderBy", "(", ")", "{", "order", ":=", "p", ".", "stm", ".", "OrderByConfig", "(", ")", "\n", "if", "len", "(", "order", ")", "<=", "0", "{", "return", "\n", "}", "\n", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\"", "+", "order", ".", "String", "(", ")", "}", "\n", "}", ")", "\n", "p", ".", "tbl", ".", "Sort", "(", "order", ")", "\n", "}" ]
// orderBy takes the resulting table and sorts its contents according to the // specifications of the ORDER BY clause.
[ "orderBy", "takes", "the", "resulting", "table", "and", "sorts", "its", "contents", "according", "to", "the", "specifications", "of", "the", "ORDER", "BY", "clause", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L784-L793
12,386
google/badwolf
bql/planner/planner.go
having
func (p *queryPlan) having() error { if p.stm.HasHavingClause() { tracer.Trace(p.tracer, func() []string { return []string{"Having filtering"} }) eval := p.stm.HavingEvaluator() ok := true var eErr error p.tbl.Filter(func(r table.Row) bool { b, err := eval.Evaluate(r) if err != nil { ok, eErr = false, err } return !b }) if !ok { return eErr } } return nil }
go
func (p *queryPlan) having() error { if p.stm.HasHavingClause() { tracer.Trace(p.tracer, func() []string { return []string{"Having filtering"} }) eval := p.stm.HavingEvaluator() ok := true var eErr error p.tbl.Filter(func(r table.Row) bool { b, err := eval.Evaluate(r) if err != nil { ok, eErr = false, err } return !b }) if !ok { return eErr } } return nil }
[ "func", "(", "p", "*", "queryPlan", ")", "having", "(", ")", "error", "{", "if", "p", ".", "stm", ".", "HasHavingClause", "(", ")", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", ")", "\n", "eval", ":=", "p", ".", "stm", ".", "HavingEvaluator", "(", ")", "\n", "ok", ":=", "true", "\n", "var", "eErr", "error", "\n", "p", ".", "tbl", ".", "Filter", "(", "func", "(", "r", "table", ".", "Row", ")", "bool", "{", "b", ",", "err", ":=", "eval", ".", "Evaluate", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "ok", ",", "eErr", "=", "false", ",", "err", "\n", "}", "\n", "return", "!", "b", "\n", "}", ")", "\n", "if", "!", "ok", "{", "return", "eErr", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// having runs the filtering based on the having clause if needed.
[ "having", "runs", "the", "filtering", "based", "on", "the", "having", "clause", "if", "needed", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L796-L816
12,387
google/badwolf
bql/planner/planner.go
limit
func (p *queryPlan) limit() { if p.stm.IsLimitSet() { tracer.Trace(p.tracer, func() []string { return []string{"Limit results to " + strconv.Itoa(int(p.stm.Limit()))} }) p.tbl.Limit(p.stm.Limit()) } }
go
func (p *queryPlan) limit() { if p.stm.IsLimitSet() { tracer.Trace(p.tracer, func() []string { return []string{"Limit results to " + strconv.Itoa(int(p.stm.Limit()))} }) p.tbl.Limit(p.stm.Limit()) } }
[ "func", "(", "p", "*", "queryPlan", ")", "limit", "(", ")", "{", "if", "p", ".", "stm", ".", "IsLimitSet", "(", ")", "{", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "int", "(", "p", ".", "stm", ".", "Limit", "(", ")", ")", ")", "}", "\n", "}", ")", "\n", "p", ".", "tbl", ".", "Limit", "(", "p", ".", "stm", ".", "Limit", "(", ")", ")", "\n", "}", "\n", "}" ]
// limit truncates the table if the limit clause if available.
[ "limit", "truncates", "the", "table", "if", "the", "limit", "clause", "if", "available", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L819-L826
12,388
google/badwolf
bql/planner/planner.go
Execute
func (p *queryPlan) Execute(ctx context.Context) (*table.Table, error) { // Fetch and cache graph instances. tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("Caching graph instances for graphs %v", p.stm.InputGraphNames())} }) if err := p.stm.Init(ctx, p.store); err != nil { return nil, err } p.grfs = p.stm.InputGraphs() // Retrieve the data. lo := p.stm.GlobalLookupOptions() tracer.Trace(p.tracer, func() []string { return []string{"Setting global lookup options to " + lo.String()} }) if err := p.processGraphPattern(ctx, lo); err != nil { return nil, err } if err := p.projectAndGroupBy(); err != nil { return nil, err } p.orderBy() err := p.having() if err != nil { return nil, err } p.limit() if p.tbl.NumRows() == 0 { // Correct the bindings. t, err := table.New(p.stm.OutputBindings()) if err != nil { return nil, err } p.tbl = t } return p.tbl, nil }
go
func (p *queryPlan) Execute(ctx context.Context) (*table.Table, error) { // Fetch and cache graph instances. tracer.Trace(p.tracer, func() []string { return []string{fmt.Sprintf("Caching graph instances for graphs %v", p.stm.InputGraphNames())} }) if err := p.stm.Init(ctx, p.store); err != nil { return nil, err } p.grfs = p.stm.InputGraphs() // Retrieve the data. lo := p.stm.GlobalLookupOptions() tracer.Trace(p.tracer, func() []string { return []string{"Setting global lookup options to " + lo.String()} }) if err := p.processGraphPattern(ctx, lo); err != nil { return nil, err } if err := p.projectAndGroupBy(); err != nil { return nil, err } p.orderBy() err := p.having() if err != nil { return nil, err } p.limit() if p.tbl.NumRows() == 0 { // Correct the bindings. t, err := table.New(p.stm.OutputBindings()) if err != nil { return nil, err } p.tbl = t } return p.tbl, nil }
[ "func", "(", "p", "*", "queryPlan", ")", "Execute", "(", "ctx", "context", ".", "Context", ")", "(", "*", "table", ".", "Table", ",", "error", ")", "{", "// Fetch and cache graph instances.", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "stm", ".", "InputGraphNames", "(", ")", ")", "}", "\n", "}", ")", "\n", "if", "err", ":=", "p", ".", "stm", ".", "Init", "(", "ctx", ",", "p", ".", "store", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ".", "grfs", "=", "p", ".", "stm", ".", "InputGraphs", "(", ")", "\n", "// Retrieve the data.", "lo", ":=", "p", ".", "stm", ".", "GlobalLookupOptions", "(", ")", "\n", "tracer", ".", "Trace", "(", "p", ".", "tracer", ",", "func", "(", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\"", "+", "lo", ".", "String", "(", ")", "}", "\n", "}", ")", "\n", "if", "err", ":=", "p", ".", "processGraphPattern", "(", "ctx", ",", "lo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "p", ".", "projectAndGroupBy", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ".", "orderBy", "(", ")", "\n", "err", ":=", "p", ".", "having", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ".", "limit", "(", ")", "\n", "if", "p", ".", "tbl", ".", "NumRows", "(", ")", "==", "0", "{", "// Correct the bindings.", "t", ",", "err", ":=", "table", ".", "New", "(", "p", ".", "stm", ".", "OutputBindings", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ".", "tbl", "=", "t", "\n", "}", "\n", "return", "p", ".", "tbl", ",", "nil", "\n", "}" ]
// Execute queries the indicated graphs.
[ "Execute", "queries", "the", "indicated", "graphs", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L829-L864
12,389
google/badwolf
bql/planner/planner.go
Execute
func (p *showPlan) Execute(ctx context.Context) (*table.Table, error) { t, err := table.New([]string{"?graph_id"}) if err != nil { return nil, err } errs := make(chan error) names := make(chan string) go func() { errs <- p.store.GraphNames(ctx, names) close(errs) }() for name := range names { id := name t.AddRow(table.Row{ "?graph_id": &table.Cell{ S: &id, }, }) } if <-errs != nil { return nil, err } return t, nil }
go
func (p *showPlan) Execute(ctx context.Context) (*table.Table, error) { t, err := table.New([]string{"?graph_id"}) if err != nil { return nil, err } errs := make(chan error) names := make(chan string) go func() { errs <- p.store.GraphNames(ctx, names) close(errs) }() for name := range names { id := name t.AddRow(table.Row{ "?graph_id": &table.Cell{ S: &id, }, }) } if <-errs != nil { return nil, err } return t, nil }
[ "func", "(", "p", "*", "showPlan", ")", "Execute", "(", "ctx", "context", ".", "Context", ")", "(", "*", "table", ".", "Table", ",", "error", ")", "{", "t", ",", "err", ":=", "table", ".", "New", "(", "[", "]", "string", "{", "\"", "\"", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "errs", ":=", "make", "(", "chan", "error", ")", "\n", "names", ":=", "make", "(", "chan", "string", ")", "\n", "go", "func", "(", ")", "{", "errs", "<-", "p", ".", "store", ".", "GraphNames", "(", "ctx", ",", "names", ")", "\n", "close", "(", "errs", ")", "\n", "}", "(", ")", "\n\n", "for", "name", ":=", "range", "names", "{", "id", ":=", "name", "\n", "t", ".", "AddRow", "(", "table", ".", "Row", "{", "\"", "\"", ":", "&", "table", ".", "Cell", "{", "S", ":", "&", "id", ",", "}", ",", "}", ")", "\n", "}", "\n", "if", "<-", "errs", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}" ]
// Execute the show statement.
[ "Execute", "the", "show", "statement", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L1123-L1147
12,390
google/badwolf
bql/planner/planner.go
New
func New(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize, bulkSize int, w io.Writer) (Executor, error) { switch stm.Type() { case semantic.Query: return newQueryPlan(ctx, store, stm, chanSize, w) case semantic.Insert: return &insertPlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Delete: return &deletePlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Create: return &createPlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Drop: return &dropPlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Construct: qp, _ := newQueryPlan(ctx, store, stm, chanSize, w) return &constructPlan{ stm: stm, store: store, tracer: w, bulkSize: bulkSize, queryPlan: qp, construct: true, }, nil case semantic.Deconstruct: qp, _ := newQueryPlan(ctx, store, stm, chanSize, w) return &constructPlan{ stm: stm, store: store, tracer: w, bulkSize: bulkSize, queryPlan: qp, construct: false, }, nil case semantic.Show: return &showPlan{ stm: stm, store: store, tracer: w, }, nil default: return nil, fmt.Errorf("planner.New: unknown statement type in statement %v", stm) } }
go
func New(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize, bulkSize int, w io.Writer) (Executor, error) { switch stm.Type() { case semantic.Query: return newQueryPlan(ctx, store, stm, chanSize, w) case semantic.Insert: return &insertPlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Delete: return &deletePlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Create: return &createPlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Drop: return &dropPlan{ stm: stm, store: store, tracer: w, }, nil case semantic.Construct: qp, _ := newQueryPlan(ctx, store, stm, chanSize, w) return &constructPlan{ stm: stm, store: store, tracer: w, bulkSize: bulkSize, queryPlan: qp, construct: true, }, nil case semantic.Deconstruct: qp, _ := newQueryPlan(ctx, store, stm, chanSize, w) return &constructPlan{ stm: stm, store: store, tracer: w, bulkSize: bulkSize, queryPlan: qp, construct: false, }, nil case semantic.Show: return &showPlan{ stm: stm, store: store, tracer: w, }, nil default: return nil, fmt.Errorf("planner.New: unknown statement type in statement %v", stm) } }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "store", "storage", ".", "Store", ",", "stm", "*", "semantic", ".", "Statement", ",", "chanSize", ",", "bulkSize", "int", ",", "w", "io", ".", "Writer", ")", "(", "Executor", ",", "error", ")", "{", "switch", "stm", ".", "Type", "(", ")", "{", "case", "semantic", ".", "Query", ":", "return", "newQueryPlan", "(", "ctx", ",", "store", ",", "stm", ",", "chanSize", ",", "w", ")", "\n", "case", "semantic", ".", "Insert", ":", "return", "&", "insertPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "}", ",", "nil", "\n", "case", "semantic", ".", "Delete", ":", "return", "&", "deletePlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "}", ",", "nil", "\n", "case", "semantic", ".", "Create", ":", "return", "&", "createPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "}", ",", "nil", "\n", "case", "semantic", ".", "Drop", ":", "return", "&", "dropPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "}", ",", "nil", "\n", "case", "semantic", ".", "Construct", ":", "qp", ",", "_", ":=", "newQueryPlan", "(", "ctx", ",", "store", ",", "stm", ",", "chanSize", ",", "w", ")", "\n", "return", "&", "constructPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "bulkSize", ":", "bulkSize", ",", "queryPlan", ":", "qp", ",", "construct", ":", "true", ",", "}", ",", "nil", "\n", "case", "semantic", ".", "Deconstruct", ":", "qp", ",", "_", ":=", "newQueryPlan", "(", "ctx", ",", "store", ",", "stm", ",", "chanSize", ",", "w", ")", "\n", "return", "&", "constructPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "bulkSize", ":", "bulkSize", ",", "queryPlan", ":", "qp", ",", "construct", ":", "false", ",", "}", ",", "nil", "\n", "case", "semantic", ".", "Show", ":", "return", "&", "showPlan", "{", "stm", ":", "stm", ",", "store", ":", "store", ",", "tracer", ":", "w", ",", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "stm", ")", "\n", "}", "\n", "}" ]
// New create a new executable plan given a semantic BQL statement.
[ "New", "create", "a", "new", "executable", "plan", "given", "a", "semantic", "BQL", "statement", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/planner/planner.go#L1155-L1212
12,391
google/badwolf
bql/grammar/llk.go
NewLLk
func NewLLk(input string, k int) *LLk { c := lexer.New(input, 2*k) // +2 to keep a bit of buffer available. l := &LLk{ k: k, c: c, } for i := 0; i < k+1; i++ { appendNextToken(l) } return l }
go
func NewLLk(input string, k int) *LLk { c := lexer.New(input, 2*k) // +2 to keep a bit of buffer available. l := &LLk{ k: k, c: c, } for i := 0; i < k+1; i++ { appendNextToken(l) } return l }
[ "func", "NewLLk", "(", "input", "string", ",", "k", "int", ")", "*", "LLk", "{", "c", ":=", "lexer", ".", "New", "(", "input", ",", "2", "*", "k", ")", "// +2 to keep a bit of buffer available.", "\n", "l", ":=", "&", "LLk", "{", "k", ":", "k", ",", "c", ":", "c", ",", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "k", "+", "1", ";", "i", "++", "{", "appendNextToken", "(", "l", ")", "\n", "}", "\n", "return", "l", "\n", "}" ]
// NewLLk creates a LLk structure for the given string to parse and the // indicated k lookahead.
[ "NewLLk", "creates", "a", "LLk", "structure", "for", "the", "given", "string", "to", "parse", "and", "the", "indicated", "k", "lookahead", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/grammar/llk.go#L33-L43
12,392
google/badwolf
bql/grammar/llk.go
appendNextToken
func appendNextToken(l *LLk) { for t := range l.c { l.tkns = append(l.tkns, t) return } l.tkns = append(l.tkns, lexer.Token{Type: lexer.ItemEOF}) }
go
func appendNextToken(l *LLk) { for t := range l.c { l.tkns = append(l.tkns, t) return } l.tkns = append(l.tkns, lexer.Token{Type: lexer.ItemEOF}) }
[ "func", "appendNextToken", "(", "l", "*", "LLk", ")", "{", "for", "t", ":=", "range", "l", ".", "c", "{", "l", ".", "tkns", "=", "append", "(", "l", ".", "tkns", ",", "t", ")", "\n", "return", "\n", "}", "\n", "l", ".", "tkns", "=", "append", "(", "l", ".", "tkns", ",", "lexer", ".", "Token", "{", "Type", ":", "lexer", ".", "ItemEOF", "}", ")", "\n", "}" ]
// appendNextToken tries to append a new token. If not tokens are available // it appends ItemEOF token.
[ "appendNextToken", "tries", "to", "append", "a", "new", "token", ".", "If", "not", "tokens", "are", "available", "it", "appends", "ItemEOF", "token", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/grammar/llk.go#L47-L53
12,393
google/badwolf
bql/grammar/llk.go
Peek
func (l *LLk) Peek(k int) (*lexer.Token, error) { if k > l.k { return nil, fmt.Errorf("grammar.LLk: cannot look ahead %v beyond defined %v", k, l.k) } if k <= 0 { return nil, fmt.Errorf("grammar.LLk: invalid look ahead value %v", k) } return &l.tkns[k], nil }
go
func (l *LLk) Peek(k int) (*lexer.Token, error) { if k > l.k { return nil, fmt.Errorf("grammar.LLk: cannot look ahead %v beyond defined %v", k, l.k) } if k <= 0 { return nil, fmt.Errorf("grammar.LLk: invalid look ahead value %v", k) } return &l.tkns[k], nil }
[ "func", "(", "l", "*", "LLk", ")", "Peek", "(", "k", "int", ")", "(", "*", "lexer", ".", "Token", ",", "error", ")", "{", "if", "k", ">", "l", ".", "k", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "l", ".", "k", ")", "\n", "}", "\n", "if", "k", "<=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "return", "&", "l", ".", "tkns", "[", "k", "]", ",", "nil", "\n", "}" ]
// Peek returns the token for the k look ahead. It will return nil and failed // fail with an error if the provided k is bigger than the declared look ahead // on creation.
[ "Peek", "returns", "the", "token", "for", "the", "k", "look", "ahead", ".", "It", "will", "return", "nil", "and", "failed", "fail", "with", "an", "error", "if", "the", "provided", "k", "is", "bigger", "than", "the", "declared", "look", "ahead", "on", "creation", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/grammar/llk.go#L63-L71
12,394
google/badwolf
bql/grammar/llk.go
CanAccept
func (l *LLk) CanAccept(tt lexer.TokenType) bool { return l.tkns[0].Type == tt }
go
func (l *LLk) CanAccept(tt lexer.TokenType) bool { return l.tkns[0].Type == tt }
[ "func", "(", "l", "*", "LLk", ")", "CanAccept", "(", "tt", "lexer", ".", "TokenType", ")", "bool", "{", "return", "l", ".", "tkns", "[", "0", "]", ".", "Type", "==", "tt", "\n", "}" ]
// CanAccept returns true if the provided token matches the current on being // processed, false otherwise.
[ "CanAccept", "returns", "true", "if", "the", "provided", "token", "matches", "the", "current", "on", "being", "processed", "false", "otherwise", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/grammar/llk.go#L75-L77
12,395
google/badwolf
bql/grammar/llk.go
Consume
func (l *LLk) Consume(tt lexer.TokenType) bool { if l.tkns[0].Type != tt { return false } l.tkns = l.tkns[1:] appendNextToken(l) return true }
go
func (l *LLk) Consume(tt lexer.TokenType) bool { if l.tkns[0].Type != tt { return false } l.tkns = l.tkns[1:] appendNextToken(l) return true }
[ "func", "(", "l", "*", "LLk", ")", "Consume", "(", "tt", "lexer", ".", "TokenType", ")", "bool", "{", "if", "l", ".", "tkns", "[", "0", "]", ".", "Type", "!=", "tt", "{", "return", "false", "\n", "}", "\n", "l", ".", "tkns", "=", "l", ".", "tkns", "[", "1", ":", "]", "\n", "appendNextToken", "(", "l", ")", "\n", "return", "true", "\n", "}" ]
// Consume will consume the current token and move to the next one if it matches // the provided token, false otherwise.
[ "Consume", "will", "consume", "the", "current", "token", "and", "move", "to", "the", "next", "one", "if", "it", "matches", "the", "provided", "token", "false", "otherwise", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/bql/grammar/llk.go#L81-L88
12,396
google/badwolf
tools/benchmark/runtime/runtime.go
TrackDuration
func TrackDuration(f func() error) (time.Duration, error) { ts := timeNow() err := f() d := timeNow().Sub(ts) return d, err }
go
func TrackDuration(f func() error) (time.Duration, error) { ts := timeNow() err := f() d := timeNow().Sub(ts) return d, err }
[ "func", "TrackDuration", "(", "f", "func", "(", ")", "error", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "ts", ":=", "timeNow", "(", ")", "\n", "err", ":=", "f", "(", ")", "\n", "d", ":=", "timeNow", "(", ")", ".", "Sub", "(", "ts", ")", "\n", "return", "d", ",", "err", "\n", "}" ]
// TrackDuration measure the duration of the run time function using the // wall clock. You should not consider the returned duration in the presence // or an error since it will likely have shortcut the execution of the // function being executed.
[ "TrackDuration", "measure", "the", "duration", "of", "the", "run", "time", "function", "using", "the", "wall", "clock", ".", "You", "should", "not", "consider", "the", "returned", "duration", "in", "the", "presence", "or", "an", "error", "since", "it", "will", "likely", "have", "shortcut", "the", "execution", "of", "the", "function", "being", "executed", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/benchmark/runtime/runtime.go#L33-L38
12,397
google/badwolf
tools/benchmark/runtime/runtime.go
RepetitionDurationStats
func RepetitionDurationStats(reps int, setup, f, teardown func() error) (time.Duration, time.Duration, error) { if reps < 1 { return time.Duration(0), 0, fmt.Errorf("repetions need to be %d >= 1", reps) } if setup == nil { return time.Duration(0), 0, errors.New("setup function is required") } if f == nil { return time.Duration(0), 0, errors.New("benchmark function is required") } if teardown == nil { return time.Duration(0), 0, errors.New("teardown function is required") } var durations []time.Duration for i := 0; i < reps; i++ { if err := setup(); err != nil { return time.Duration(0), 0, err } d, err := TrackDuration(f) if err != nil { return 0, 0, err } durations = append(durations, d) if err := teardown(); err != nil { return time.Duration(0), 0, err } } mean := int64(0) for _, d := range durations { mean += int64(d) } mean /= int64(len(durations)) dev, expSquare := int64(0), mean*mean for _, d := range durations { dev = int64(d)*int64(d) - expSquare } dev = int64(math.Sqrt(math.Abs(float64(dev)))) return time.Duration(mean), time.Duration(dev), nil }
go
func RepetitionDurationStats(reps int, setup, f, teardown func() error) (time.Duration, time.Duration, error) { if reps < 1 { return time.Duration(0), 0, fmt.Errorf("repetions need to be %d >= 1", reps) } if setup == nil { return time.Duration(0), 0, errors.New("setup function is required") } if f == nil { return time.Duration(0), 0, errors.New("benchmark function is required") } if teardown == nil { return time.Duration(0), 0, errors.New("teardown function is required") } var durations []time.Duration for i := 0; i < reps; i++ { if err := setup(); err != nil { return time.Duration(0), 0, err } d, err := TrackDuration(f) if err != nil { return 0, 0, err } durations = append(durations, d) if err := teardown(); err != nil { return time.Duration(0), 0, err } } mean := int64(0) for _, d := range durations { mean += int64(d) } mean /= int64(len(durations)) dev, expSquare := int64(0), mean*mean for _, d := range durations { dev = int64(d)*int64(d) - expSquare } dev = int64(math.Sqrt(math.Abs(float64(dev)))) return time.Duration(mean), time.Duration(dev), nil }
[ "func", "RepetitionDurationStats", "(", "reps", "int", ",", "setup", ",", "f", ",", "teardown", "func", "(", ")", "error", ")", "(", "time", ".", "Duration", ",", "time", ".", "Duration", ",", "error", ")", "{", "if", "reps", "<", "1", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reps", ")", "\n", "}", "\n", "if", "setup", "==", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "f", "==", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "teardown", "==", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "durations", "[", "]", "time", ".", "Duration", "\n", "for", "i", ":=", "0", ";", "i", "<", "reps", ";", "i", "++", "{", "if", "err", ":=", "setup", "(", ")", ";", "err", "!=", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "0", ",", "err", "\n", "}", "\n", "d", ",", "err", ":=", "TrackDuration", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "durations", "=", "append", "(", "durations", ",", "d", ")", "\n", "if", "err", ":=", "teardown", "(", ")", ";", "err", "!=", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "0", ",", "err", "\n", "}", "\n", "}", "\n", "mean", ":=", "int64", "(", "0", ")", "\n", "for", "_", ",", "d", ":=", "range", "durations", "{", "mean", "+=", "int64", "(", "d", ")", "\n", "}", "\n", "mean", "/=", "int64", "(", "len", "(", "durations", ")", ")", "\n", "dev", ",", "expSquare", ":=", "int64", "(", "0", ")", ",", "mean", "*", "mean", "\n", "for", "_", ",", "d", ":=", "range", "durations", "{", "dev", "=", "int64", "(", "d", ")", "*", "int64", "(", "d", ")", "-", "expSquare", "\n", "}", "\n", "dev", "=", "int64", "(", "math", ".", "Sqrt", "(", "math", ".", "Abs", "(", "float64", "(", "dev", ")", ")", ")", ")", "\n", "return", "time", ".", "Duration", "(", "mean", ")", ",", "time", ".", "Duration", "(", "dev", ")", ",", "nil", "\n", "}" ]
// RepetitionDurationStats extracts some duration stats by repeatedly execution // and measuring runtime. Returns the mean and deviation of the run duration of // the provided function. If an error is return by the function it will shortcut // the execution and return just the error.
[ "RepetitionDurationStats", "extracts", "some", "duration", "stats", "by", "repeatedly", "execution", "and", "measuring", "runtime", ".", "Returns", "the", "mean", "and", "deviation", "of", "the", "run", "duration", "of", "the", "provided", "function", ".", "If", "an", "error", "is", "return", "by", "the", "function", "it", "will", "shortcut", "the", "execution", "and", "return", "just", "the", "error", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/benchmark/runtime/runtime.go#L44-L82
12,398
google/badwolf
tools/benchmark/runtime/runtime.go
RunBenchmarkBatterySequentially
func RunBenchmarkBatterySequentially(entries []*BenchEntry) []*BenchResult { var res []*BenchResult for _, entry := range entries { m, d, err := RepetitionDurationStats(entry.Reps, entry.Setup, entry.F, entry.TearDown) res = append(res, &BenchResult{ BatteryID: entry.BatteryID, ID: entry.ID, Triples: entry.Triples, Err: err, Mean: m, StdDev: d, }) } return res }
go
func RunBenchmarkBatterySequentially(entries []*BenchEntry) []*BenchResult { var res []*BenchResult for _, entry := range entries { m, d, err := RepetitionDurationStats(entry.Reps, entry.Setup, entry.F, entry.TearDown) res = append(res, &BenchResult{ BatteryID: entry.BatteryID, ID: entry.ID, Triples: entry.Triples, Err: err, Mean: m, StdDev: d, }) } return res }
[ "func", "RunBenchmarkBatterySequentially", "(", "entries", "[", "]", "*", "BenchEntry", ")", "[", "]", "*", "BenchResult", "{", "var", "res", "[", "]", "*", "BenchResult", "\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "m", ",", "d", ",", "err", ":=", "RepetitionDurationStats", "(", "entry", ".", "Reps", ",", "entry", ".", "Setup", ",", "entry", ".", "F", ",", "entry", ".", "TearDown", ")", "\n", "res", "=", "append", "(", "res", ",", "&", "BenchResult", "{", "BatteryID", ":", "entry", ".", "BatteryID", ",", "ID", ":", "entry", ".", "ID", ",", "Triples", ":", "entry", ".", "Triples", ",", "Err", ":", "err", ",", "Mean", ":", "m", ",", "StdDev", ":", "d", ",", "}", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// RunBenchmarkBatterySequentially runs all the bench entries and returns the // timing results.
[ "RunBenchmarkBatterySequentially", "runs", "all", "the", "bench", "entries", "and", "returns", "the", "timing", "results", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/benchmark/runtime/runtime.go#L108-L122
12,399
google/badwolf
tools/benchmark/runtime/runtime.go
RunBenchmarkBatteryConcurrently
func RunBenchmarkBatteryConcurrently(entries []*BenchEntry) []*BenchResult { var ( mu sync.Mutex wg sync.WaitGroup res []*BenchResult ) for _, entry := range entries { wg.Add(1) go func(entry *BenchEntry) { m, d, err := RepetitionDurationStats(entry.Reps, entry.Setup, entry.F, entry.TearDown) mu.Lock() defer mu.Unlock() defer wg.Done() res = append(res, &BenchResult{ BatteryID: entry.BatteryID, ID: entry.ID, Triples: entry.Triples, Err: err, Mean: m, StdDev: d, }) }(entry) } wg.Wait() return res }
go
func RunBenchmarkBatteryConcurrently(entries []*BenchEntry) []*BenchResult { var ( mu sync.Mutex wg sync.WaitGroup res []*BenchResult ) for _, entry := range entries { wg.Add(1) go func(entry *BenchEntry) { m, d, err := RepetitionDurationStats(entry.Reps, entry.Setup, entry.F, entry.TearDown) mu.Lock() defer mu.Unlock() defer wg.Done() res = append(res, &BenchResult{ BatteryID: entry.BatteryID, ID: entry.ID, Triples: entry.Triples, Err: err, Mean: m, StdDev: d, }) }(entry) } wg.Wait() return res }
[ "func", "RunBenchmarkBatteryConcurrently", "(", "entries", "[", "]", "*", "BenchEntry", ")", "[", "]", "*", "BenchResult", "{", "var", "(", "mu", "sync", ".", "Mutex", "\n", "wg", "sync", ".", "WaitGroup", "\n", "res", "[", "]", "*", "BenchResult", "\n", ")", "\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "entry", "*", "BenchEntry", ")", "{", "m", ",", "d", ",", "err", ":=", "RepetitionDurationStats", "(", "entry", ".", "Reps", ",", "entry", ".", "Setup", ",", "entry", ".", "F", ",", "entry", ".", "TearDown", ")", "\n", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "defer", "wg", ".", "Done", "(", ")", "\n", "res", "=", "append", "(", "res", ",", "&", "BenchResult", "{", "BatteryID", ":", "entry", ".", "BatteryID", ",", "ID", ":", "entry", ".", "ID", ",", "Triples", ":", "entry", ".", "Triples", ",", "Err", ":", "err", ",", "Mean", ":", "m", ",", "StdDev", ":", "d", ",", "}", ")", "\n", "}", "(", "entry", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "res", "\n", "}" ]
// RunBenchmarkBatteryConcurrently runs all the bench entries and returns the // timing results concurrently. The benchmarks will all be run concurrently.
[ "RunBenchmarkBatteryConcurrently", "runs", "all", "the", "bench", "entries", "and", "returns", "the", "timing", "results", "concurrently", ".", "The", "benchmarks", "will", "all", "be", "run", "concurrently", "." ]
f6c3103546450641440a719b2ed52cc74bae6237
https://github.com/google/badwolf/blob/f6c3103546450641440a719b2ed52cc74bae6237/tools/benchmark/runtime/runtime.go#L126-L151