repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
lestrrat-go/xslate
vm/ops.go
txMarkRaw
func txMarkRaw(st *State) { if reflect.ValueOf(st.sa).Type() != rawStringType { st.sa = rawString(interfaceToString(st.sa)) } st.Advance() }
go
func txMarkRaw(st *State) { if reflect.ValueOf(st.sa).Type() != rawStringType { st.sa = rawString(interfaceToString(st.sa)) } st.Advance() }
[ "func", "txMarkRaw", "(", "st", "*", "State", ")", "{", "if", "reflect", ".", "ValueOf", "(", "st", ".", "sa", ")", ".", "Type", "(", ")", "!=", "rawStringType", "{", "st", ".", "sa", "=", "rawString", "(", "interfaceToString", "(", "st", ".", "sa", ")", ")", "\n", "}", "\n", "st", ".", "Advance", "(", ")", "\n", "}" ]
// Wraps the contents of register sa with a "raw string" mark // Note that this effectively stringifies the contents of register sa
[ "Wraps", "the", "contents", "of", "register", "sa", "with", "a", "raw", "string", "mark", "Note", "that", "this", "effectively", "stringifies", "the", "contents", "of", "register", "sa" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L320-L325
test
lestrrat-go/xslate
vm/ops.go
txUnmarkRaw
func txUnmarkRaw(st *State) { if reflect.ValueOf(st.sa).Type() == rawStringType { st.sa = string(interfaceToString(st.sa)) } st.Advance() }
go
func txUnmarkRaw(st *State) { if reflect.ValueOf(st.sa).Type() == rawStringType { st.sa = string(interfaceToString(st.sa)) } st.Advance() }
[ "func", "txUnmarkRaw", "(", "st", "*", "State", ")", "{", "if", "reflect", ".", "ValueOf", "(", "st", ".", "sa", ")", ".", "Type", "(", ")", "==", "rawStringType", "{", "st", ".", "sa", "=", "string", "(", "interfaceToString", "(", "st", ".", "sa", ")", ")", "\n", "}", "\n", "st", ".", "Advance", "(", ")", "\n", "}" ]
// Sets the contents of register sa to a regular string, and removes // the "raw string" mark, forcing html escapes to be applied when printing. // Note that this effectively stringifies the contents of register sa
[ "Sets", "the", "contents", "of", "register", "sa", "to", "a", "regular", "string", "and", "removes", "the", "raw", "string", "mark", "forcing", "html", "escapes", "to", "be", "applied", "when", "printing", ".", "Note", "that", "this", "effectively", "stringifies", "the", "contents", "of", "register", "sa" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L330-L335
test
lestrrat-go/xslate
vm/ops.go
txPrint
func txPrint(st *State) { arg := st.sa if arg == nil { st.Warnf("Use of nil to print\n") } else if reflect.ValueOf(st.sa).Type() != rawStringType { st.AppendOutputString(html.EscapeString(interfaceToString(arg))) } else { st.AppendOutputString(interfaceToString(arg)) } st.Advance() }
go
func txPrint(st *State) { arg := st.sa if arg == nil { st.Warnf("Use of nil to print\n") } else if reflect.ValueOf(st.sa).Type() != rawStringType { st.AppendOutputString(html.EscapeString(interfaceToString(arg))) } else { st.AppendOutputString(interfaceToString(arg)) } st.Advance() }
[ "func", "txPrint", "(", "st", "*", "State", ")", "{", "arg", ":=", "st", ".", "sa", "\n", "if", "arg", "==", "nil", "{", "st", ".", "Warnf", "(", "\"Use of nil to print\\n\"", ")", "\n", "}", "else", "\\n", "\n", "if", "reflect", ".", "ValueOf", "(", "st", ".", "sa", ")", ".", "Type", "(", ")", "!=", "rawStringType", "{", "st", ".", "AppendOutputString", "(", "html", ".", "EscapeString", "(", "interfaceToString", "(", "arg", ")", ")", ")", "\n", "}", "else", "{", "st", ".", "AppendOutputString", "(", "interfaceToString", "(", "arg", ")", ")", "\n", "}", "\n", "}" ]
// Prints the contents of register sa to Output. // Forcefully applies html escaping unless the variable in sa is marked "raw"
[ "Prints", "the", "contents", "of", "register", "sa", "to", "Output", ".", "Forcefully", "applies", "html", "escaping", "unless", "the", "variable", "in", "sa", "is", "marked", "raw" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L339-L349
test
lestrrat-go/xslate
vm/ops.go
txPrintRaw
func txPrintRaw(st *State) { // XXX TODO: mark_raw handling arg := st.sa if arg == nil { st.Warnf("Use of nil to print\n") } else { st.AppendOutputString(interfaceToString(arg)) } st.Advance() }
go
func txPrintRaw(st *State) { // XXX TODO: mark_raw handling arg := st.sa if arg == nil { st.Warnf("Use of nil to print\n") } else { st.AppendOutputString(interfaceToString(arg)) } st.Advance() }
[ "func", "txPrintRaw", "(", "st", "*", "State", ")", "{", "arg", ":=", "st", ".", "sa", "\n", "if", "arg", "==", "nil", "{", "st", ".", "Warnf", "(", "\"Use of nil to print\\n\"", ")", "\n", "}", "else", "\\n", "\n", "{", "st", ".", "AppendOutputString", "(", "interfaceToString", "(", "arg", ")", ")", "\n", "}", "\n", "}" ]
// Prints the contents of register sa, forcing raw string semantics
[ "Prints", "the", "contents", "of", "register", "sa", "forcing", "raw", "string", "semantics" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L357-L366
test
lestrrat-go/xslate
vm/ops.go
NewLoopVar
func NewLoopVar(idx int, array reflect.Value) *LoopVar { lv := &LoopVar{ Index: idx, Count: idx + 1, Body: array, Size: array.Len(), MaxIndex: array.Len() - 1, PeekNext: nil, PeekPrev: nil, IsFirst: false, IsLast: false, } return lv }
go
func NewLoopVar(idx int, array reflect.Value) *LoopVar { lv := &LoopVar{ Index: idx, Count: idx + 1, Body: array, Size: array.Len(), MaxIndex: array.Len() - 1, PeekNext: nil, PeekPrev: nil, IsFirst: false, IsLast: false, } return lv }
[ "func", "NewLoopVar", "(", "idx", "int", ",", "array", "reflect", ".", "Value", ")", "*", "LoopVar", "{", "lv", ":=", "&", "LoopVar", "{", "Index", ":", "idx", ",", "Count", ":", "idx", "+", "1", ",", "Body", ":", "array", ",", "Size", ":", "array", ".", "Len", "(", ")", ",", "MaxIndex", ":", "array", ".", "Len", "(", ")", "-", "1", ",", "PeekNext", ":", "nil", ",", "PeekPrev", ":", "nil", ",", "IsFirst", ":", "false", ",", "IsLast", ":", "false", ",", "}", "\n", "return", "lv", "\n", "}" ]
// NewLoopVar creates the loop variable
[ "NewLoopVar", "creates", "the", "loop", "variable" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L461-L474
test
lestrrat-go/xslate
vm/ops.go
txMakeArray
func txMakeArray(st *State) { start := st.CurrentMark() // start end := st.StackTip() // end if end <= start { panic(fmt.Sprintf("MakeArray: list start (%d) >= end (%d)", start, end)) } list := make([]interface{}, end-start+1) for i := end; i >= start; i-- { list[i-start] = st.StackPop() } st.sa = list st.Advance() }
go
func txMakeArray(st *State) { start := st.CurrentMark() // start end := st.StackTip() // end if end <= start { panic(fmt.Sprintf("MakeArray: list start (%d) >= end (%d)", start, end)) } list := make([]interface{}, end-start+1) for i := end; i >= start; i-- { list[i-start] = st.StackPop() } st.sa = list st.Advance() }
[ "func", "txMakeArray", "(", "st", "*", "State", ")", "{", "start", ":=", "st", ".", "CurrentMark", "(", ")", "\n", "end", ":=", "st", ".", "StackTip", "(", ")", "\n", "if", "end", "<=", "start", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"MakeArray: list start (%d) >= end (%d)\"", ",", "start", ",", "end", ")", ")", "\n", "}", "\n", "list", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "end", "-", "start", "+", "1", ")", "\n", "for", "i", ":=", "end", ";", "i", ">=", "start", ";", "i", "--", "{", "list", "[", "i", "-", "start", "]", "=", "st", ".", "StackPop", "(", ")", "\n", "}", "\n", "st", ".", "sa", "=", "list", "\n", "st", ".", "Advance", "(", ")", "\n", "}" ]
// Grab every thing from current mark up to the tip of the stack, // and make it a list
[ "Grab", "every", "thing", "from", "current", "mark", "up", "to", "the", "tip", "of", "the", "stack", "and", "make", "it", "a", "list" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L857-L871
test
lestrrat-go/xslate
vm/ops.go
txFunCallOmni
func txFunCallOmni(st *State) { t := reflect.ValueOf(st.sa) switch t.Kind() { case reflect.Int: // If it's an int, assume that it's a MACRO, which points to // the location in the bytecode that contains the macro code txMacroCall(st) case reflect.Func: txFunCall(st) default: st.Warnf("Unknown variable as function call: %s\n", st.sa) st.sa = nil st.Advance() } }
go
func txFunCallOmni(st *State) { t := reflect.ValueOf(st.sa) switch t.Kind() { case reflect.Int: // If it's an int, assume that it's a MACRO, which points to // the location in the bytecode that contains the macro code txMacroCall(st) case reflect.Func: txFunCall(st) default: st.Warnf("Unknown variable as function call: %s\n", st.sa) st.sa = nil st.Advance() } }
[ "func", "txFunCallOmni", "(", "st", "*", "State", ")", "{", "t", ":=", "reflect", ".", "ValueOf", "(", "st", ".", "sa", ")", "\n", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ":", "txMacroCall", "(", "st", ")", "\n", "case", "reflect", ".", "Func", ":", "txFunCall", "(", "st", ")", "\n", "default", ":", "st", ".", "Warnf", "(", "\"Unknown variable as function call: %s\\n\"", ",", "\\n", ")", "\n", "st", ".", "sa", "\n", "st", ".", "sa", "=", "nil", "\n", "}", "\n", "}" ]
// Executes what's in st.sa
[ "Executes", "what", "s", "in", "st", ".", "sa" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L991-L1005
test
lestrrat-go/xslate
loader/loader.go
DumpAST
func (f *Flags) DumpAST(b bool) { if b { f.flags |= MaskDumpAST } else { f.flags &= ^MaskDumpAST } }
go
func (f *Flags) DumpAST(b bool) { if b { f.flags |= MaskDumpAST } else { f.flags &= ^MaskDumpAST } }
[ "func", "(", "f", "*", "Flags", ")", "DumpAST", "(", "b", "bool", ")", "{", "if", "b", "{", "f", ".", "flags", "|=", "MaskDumpAST", "\n", "}", "else", "{", "f", ".", "flags", "&=", "^", "MaskDumpAST", "\n", "}", "\n", "}" ]
// DumpAST sets the bitmask for DumpAST debug flag
[ "DumpAST", "sets", "the", "bitmask", "for", "DumpAST", "debug", "flag" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/loader.go#L13-L19
test
lestrrat-go/xslate
loader/loader.go
DumpByteCode
func (f *Flags) DumpByteCode(b bool) { if b { f.flags |= MaskDumpByteCode } else { f.flags &= ^MaskDumpByteCode } }
go
func (f *Flags) DumpByteCode(b bool) { if b { f.flags |= MaskDumpByteCode } else { f.flags &= ^MaskDumpByteCode } }
[ "func", "(", "f", "*", "Flags", ")", "DumpByteCode", "(", "b", "bool", ")", "{", "if", "b", "{", "f", ".", "flags", "|=", "MaskDumpByteCode", "\n", "}", "else", "{", "f", ".", "flags", "&=", "^", "MaskDumpByteCode", "\n", "}", "\n", "}" ]
// DumpByteCode sets the bitmask for DumpByteCode debug flag
[ "DumpByteCode", "sets", "the", "bitmask", "for", "DumpByteCode", "debug", "flag" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/loader.go#L22-L28
test
lestrrat-go/xslate
compiler/optimizer.go
Optimize
func (o *NaiveOptimizer) Optimize(bc *vm.ByteCode) error { for i := 0; i < bc.Len(); i++ { op := bc.Get(i) if op == nil { return errors.New("failed to fetch op '" + op.String() + "'") } switch op.Type() { case vm.TXOPLiteral: if i+1 < bc.Len() && bc.Get(i+1).Type() == vm.TXOPPrintRaw { bc.OpList[i] = vm.NewOp(vm.TXOPPrintRawConst, op.ArgString()) bc.OpList[i+1] = vm.NewOp(vm.TXOPNoop) i++ } } } return nil }
go
func (o *NaiveOptimizer) Optimize(bc *vm.ByteCode) error { for i := 0; i < bc.Len(); i++ { op := bc.Get(i) if op == nil { return errors.New("failed to fetch op '" + op.String() + "'") } switch op.Type() { case vm.TXOPLiteral: if i+1 < bc.Len() && bc.Get(i+1).Type() == vm.TXOPPrintRaw { bc.OpList[i] = vm.NewOp(vm.TXOPPrintRawConst, op.ArgString()) bc.OpList[i+1] = vm.NewOp(vm.TXOPNoop) i++ } } } return nil }
[ "func", "(", "o", "*", "NaiveOptimizer", ")", "Optimize", "(", "bc", "*", "vm", ".", "ByteCode", ")", "error", "{", "for", "i", ":=", "0", ";", "i", "<", "bc", ".", "Len", "(", ")", ";", "i", "++", "{", "op", ":=", "bc", ".", "Get", "(", "i", ")", "\n", "if", "op", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"failed to fetch op '\"", "+", "op", ".", "String", "(", ")", "+", "\"'\"", ")", "\n", "}", "\n", "switch", "op", ".", "Type", "(", ")", "{", "case", "vm", ".", "TXOPLiteral", ":", "if", "i", "+", "1", "<", "bc", ".", "Len", "(", ")", "&&", "bc", ".", "Get", "(", "i", "+", "1", ")", ".", "Type", "(", ")", "==", "vm", ".", "TXOPPrintRaw", "{", "bc", ".", "OpList", "[", "i", "]", "=", "vm", ".", "NewOp", "(", "vm", ".", "TXOPPrintRawConst", ",", "op", ".", "ArgString", "(", ")", ")", "\n", "bc", ".", "OpList", "[", "i", "+", "1", "]", "=", "vm", ".", "NewOp", "(", "vm", ".", "TXOPNoop", ")", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Optimize modifies the ByteCode in place to an optimized version
[ "Optimize", "modifies", "the", "ByteCode", "in", "place", "to", "an", "optimized", "version" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/compiler/optimizer.go#L10-L26
test
lestrrat-go/xslate
functions/depot.go
NewFuncDepot
func NewFuncDepot(namespace string) *FuncDepot { return &FuncDepot{namespace, make(map[string]reflect.Value)} }
go
func NewFuncDepot(namespace string) *FuncDepot { return &FuncDepot{namespace, make(map[string]reflect.Value)} }
[ "func", "NewFuncDepot", "(", "namespace", "string", ")", "*", "FuncDepot", "{", "return", "&", "FuncDepot", "{", "namespace", ",", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", "}", "\n", "}" ]
// NewFuncDepot creates a new FuncDepot under the given `namespace`
[ "NewFuncDepot", "creates", "a", "new", "FuncDepot", "under", "the", "given", "namespace" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/functions/depot.go#L15-L17
test
lestrrat-go/xslate
functions/depot.go
Get
func (fc *FuncDepot) Get(key string) (reflect.Value, bool) { f, ok := fc.depot[key] return f, ok }
go
func (fc *FuncDepot) Get(key string) (reflect.Value, bool) { f, ok := fc.depot[key] return f, ok }
[ "func", "(", "fc", "*", "FuncDepot", ")", "Get", "(", "key", "string", ")", "(", "reflect", ".", "Value", ",", "bool", ")", "{", "f", ",", "ok", ":=", "fc", ".", "depot", "[", "key", "]", "\n", "return", "f", ",", "ok", "\n", "}" ]
// Get returns the function associated with the given key. The function // is wrapped as reflect.Value so reflection can be used to determine // attributes about this function
[ "Get", "returns", "the", "function", "associated", "with", "the", "given", "key", ".", "The", "function", "is", "wrapped", "as", "reflect", ".", "Value", "so", "reflection", "can", "be", "used", "to", "determine", "attributes", "about", "this", "function" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/functions/depot.go#L27-L30
test
lestrrat-go/xslate
functions/depot.go
Set
func (fc *FuncDepot) Set(key string, v interface{}) { fc.depot[key] = reflect.ValueOf(v) }
go
func (fc *FuncDepot) Set(key string, v interface{}) { fc.depot[key] = reflect.ValueOf(v) }
[ "func", "(", "fc", "*", "FuncDepot", ")", "Set", "(", "key", "string", ",", "v", "interface", "{", "}", ")", "{", "fc", ".", "depot", "[", "key", "]", "=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "}" ]
// Set stores the function under the name `key`
[ "Set", "stores", "the", "function", "under", "the", "name", "key" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/functions/depot.go#L33-L35
test
lestrrat-go/xslate
loader/file.go
NewFileTemplateFetcher
func NewFileTemplateFetcher(paths []string) (*FileTemplateFetcher, error) { l := &FileTemplateFetcher{ Paths: make([]string, len(paths)), } for k, v := range paths { abs, err := filepath.Abs(v) if err != nil { return nil, err } l.Paths[k] = abs } return l, nil }
go
func NewFileTemplateFetcher(paths []string) (*FileTemplateFetcher, error) { l := &FileTemplateFetcher{ Paths: make([]string, len(paths)), } for k, v := range paths { abs, err := filepath.Abs(v) if err != nil { return nil, err } l.Paths[k] = abs } return l, nil }
[ "func", "NewFileTemplateFetcher", "(", "paths", "[", "]", "string", ")", "(", "*", "FileTemplateFetcher", ",", "error", ")", "{", "l", ":=", "&", "FileTemplateFetcher", "{", "Paths", ":", "make", "(", "[", "]", "string", ",", "len", "(", "paths", ")", ")", ",", "}", "\n", "for", "k", ",", "v", ":=", "range", "paths", "{", "abs", ",", "err", ":=", "filepath", ".", "Abs", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "l", ".", "Paths", "[", "k", "]", "=", "abs", "\n", "}", "\n", "return", "l", ",", "nil", "\n", "}" ]
// NewFileTemplateFetcher creates a new struct. `paths` must give us the // directories for us to look the templates in
[ "NewFileTemplateFetcher", "creates", "a", "new", "struct", ".", "paths", "must", "give", "us", "the", "directories", "for", "us", "to", "look", "the", "templates", "in" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L19-L31
test
lestrrat-go/xslate
loader/file.go
LastModified
func (s *FileSource) LastModified() (time.Time, error) { // Calling os.Stat() for *every* Render of the same source is a waste // Only call os.Stat() if we haven't done so in the last 1 second if time.Since(s.LastStat) < time.Second { // A-ha! it's not that long ago we calculated this value, just return // the same thing as our last call return s.LastStatResult.ModTime(), nil } // If we got here, our previous check was too old or this is the first // time we're checking for os.Stat() fi, err := os.Stat(s.Path) if err != nil { return time.Time{}, err } // Save these for later... s.LastStat = time.Now() s.LastStatResult = fi return s.LastStatResult.ModTime(), nil }
go
func (s *FileSource) LastModified() (time.Time, error) { // Calling os.Stat() for *every* Render of the same source is a waste // Only call os.Stat() if we haven't done so in the last 1 second if time.Since(s.LastStat) < time.Second { // A-ha! it's not that long ago we calculated this value, just return // the same thing as our last call return s.LastStatResult.ModTime(), nil } // If we got here, our previous check was too old or this is the first // time we're checking for os.Stat() fi, err := os.Stat(s.Path) if err != nil { return time.Time{}, err } // Save these for later... s.LastStat = time.Now() s.LastStatResult = fi return s.LastStatResult.ModTime(), nil }
[ "func", "(", "s", "*", "FileSource", ")", "LastModified", "(", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "if", "time", ".", "Since", "(", "s", ".", "LastStat", ")", "<", "time", ".", "Second", "{", "return", "s", ".", "LastStatResult", ".", "ModTime", "(", ")", ",", "nil", "\n", "}", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "s", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "time", ".", "Time", "{", "}", ",", "err", "\n", "}", "\n", "s", ".", "LastStat", "=", "time", ".", "Now", "(", ")", "\n", "s", ".", "LastStatResult", "=", "fi", "\n", "return", "s", ".", "LastStatResult", ".", "ModTime", "(", ")", ",", "nil", "\n", "}" ]
// LastModified returns time when the target template file was last modified
[ "LastModified", "returns", "time", "when", "the", "target", "template", "file", "was", "last", "modified" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L54-L75
test
lestrrat-go/xslate
loader/file.go
Reader
func (s *FileSource) Reader() (io.Reader, error) { fh, err := os.Open(s.Path) if err != nil { return nil, err } return fh, nil }
go
func (s *FileSource) Reader() (io.Reader, error) { fh, err := os.Open(s.Path) if err != nil { return nil, err } return fh, nil }
[ "func", "(", "s", "*", "FileSource", ")", "Reader", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "fh", ",", "err", ":=", "os", ".", "Open", "(", "s", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "fh", ",", "nil", "\n", "}" ]
// Reader returns the io.Reader instance for the file source
[ "Reader", "returns", "the", "io", ".", "Reader", "instance", "for", "the", "file", "source" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L78-L84
test
lestrrat-go/xslate
loader/file.go
Bytes
func (s *FileSource) Bytes() ([]byte, error) { rdr, err := s.Reader() if err != nil { return nil, err } return ioutil.ReadAll(rdr) }
go
func (s *FileSource) Bytes() ([]byte, error) { rdr, err := s.Reader() if err != nil { return nil, err } return ioutil.ReadAll(rdr) }
[ "func", "(", "s", "*", "FileSource", ")", "Bytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "rdr", ",", "err", ":=", "s", ".", "Reader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ioutil", ".", "ReadAll", "(", "rdr", ")", "\n", "}" ]
// Bytes returns the bytes in teh template file
[ "Bytes", "returns", "the", "bytes", "in", "teh", "template", "file" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L87-L93
test
lestrrat-go/xslate
vm/state.go
NewState
func NewState() *State { st := &State{ opidx: 0, pc: NewByteCode(), stack: stack.New(5), markstack: stack.New(5), framestack: stack.New(5), frames: stack.New(5), vars: make(Vars), warn: os.Stderr, MaxLoopCount: 1000, } st.Pushmark() st.PushFrame() return st }
go
func NewState() *State { st := &State{ opidx: 0, pc: NewByteCode(), stack: stack.New(5), markstack: stack.New(5), framestack: stack.New(5), frames: stack.New(5), vars: make(Vars), warn: os.Stderr, MaxLoopCount: 1000, } st.Pushmark() st.PushFrame() return st }
[ "func", "NewState", "(", ")", "*", "State", "{", "st", ":=", "&", "State", "{", "opidx", ":", "0", ",", "pc", ":", "NewByteCode", "(", ")", ",", "stack", ":", "stack", ".", "New", "(", "5", ")", ",", "markstack", ":", "stack", ".", "New", "(", "5", ")", ",", "framestack", ":", "stack", ".", "New", "(", "5", ")", ",", "frames", ":", "stack", ".", "New", "(", "5", ")", ",", "vars", ":", "make", "(", "Vars", ")", ",", "warn", ":", "os", ".", "Stderr", ",", "MaxLoopCount", ":", "1000", ",", "}", "\n", "st", ".", "Pushmark", "(", ")", "\n", "st", ".", "PushFrame", "(", ")", "\n", "return", "st", "\n", "}" ]
// NewState creates a new State struct
[ "NewState", "creates", "a", "new", "State", "struct" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L12-L28
test
lestrrat-go/xslate
vm/state.go
PushFrame
func (st *State) PushFrame() *frame.Frame { f := frame.New(st.framestack) st.frames.Push(f) f.SetMark(st.frames.Size()) return f }
go
func (st *State) PushFrame() *frame.Frame { f := frame.New(st.framestack) st.frames.Push(f) f.SetMark(st.frames.Size()) return f }
[ "func", "(", "st", "*", "State", ")", "PushFrame", "(", ")", "*", "frame", ".", "Frame", "{", "f", ":=", "frame", ".", "New", "(", "st", ".", "framestack", ")", "\n", "st", ".", "frames", ".", "Push", "(", "f", ")", "\n", "f", ".", "SetMark", "(", "st", ".", "frames", ".", "Size", "(", ")", ")", "\n", "return", "f", "\n", "}" ]
// PushFrame pushes a new frame to the frame stack
[ "PushFrame", "pushes", "a", "new", "frame", "to", "the", "frame", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L61-L66
test
lestrrat-go/xslate
vm/state.go
PopFrame
func (st *State) PopFrame() *frame.Frame { x := st.frames.Pop() if x == nil { return nil } f := x.(*frame.Frame) for i := st.framestack.Size(); i > f.Mark(); i-- { st.framestack.Pop() } return f }
go
func (st *State) PopFrame() *frame.Frame { x := st.frames.Pop() if x == nil { return nil } f := x.(*frame.Frame) for i := st.framestack.Size(); i > f.Mark(); i-- { st.framestack.Pop() } return f }
[ "func", "(", "st", "*", "State", ")", "PopFrame", "(", ")", "*", "frame", ".", "Frame", "{", "x", ":=", "st", ".", "frames", ".", "Pop", "(", ")", "\n", "if", "x", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "f", ":=", "x", ".", "(", "*", "frame", ".", "Frame", ")", "\n", "for", "i", ":=", "st", ".", "framestack", ".", "Size", "(", ")", ";", "i", ">", "f", ".", "Mark", "(", ")", ";", "i", "--", "{", "st", ".", "framestack", ".", "Pop", "(", ")", "\n", "}", "\n", "return", "f", "\n", "}" ]
// PopFrame pops the frame from the top of the frame stack
[ "PopFrame", "pops", "the", "frame", "from", "the", "top", "of", "the", "frame", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L69-L79
test
lestrrat-go/xslate
vm/state.go
CurrentFrame
func (st *State) CurrentFrame() *frame.Frame { x, err := st.frames.Top() if err != nil { return nil } return x.(*frame.Frame) }
go
func (st *State) CurrentFrame() *frame.Frame { x, err := st.frames.Top() if err != nil { return nil } return x.(*frame.Frame) }
[ "func", "(", "st", "*", "State", ")", "CurrentFrame", "(", ")", "*", "frame", ".", "Frame", "{", "x", ",", "err", ":=", "st", ".", "frames", ".", "Top", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "x", ".", "(", "*", "frame", ".", "Frame", ")", "\n", "}" ]
// CurrentFrame returns the frame currently at the top of the frame stack
[ "CurrentFrame", "returns", "the", "frame", "currently", "at", "the", "top", "of", "the", "frame", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L82-L88
test
lestrrat-go/xslate
vm/state.go
Warnf
func (st *State) Warnf(format string, args ...interface{}) { st.warn.Write([]byte(fmt.Sprintf(format, args...))) }
go
func (st *State) Warnf(format string, args ...interface{}) { st.warn.Write([]byte(fmt.Sprintf(format, args...))) }
[ "func", "(", "st", "*", "State", ")", "Warnf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "st", ".", "warn", ".", "Write", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ")", ")", "\n", "}" ]
// Warnf is used to generate warnings during virtual machine execution
[ "Warnf", "is", "used", "to", "generate", "warnings", "during", "virtual", "machine", "execution" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L91-L93
test
lestrrat-go/xslate
vm/state.go
AppendOutputString
func (st *State) AppendOutputString(o string) { st.output.Write([]byte(o)) }
go
func (st *State) AppendOutputString(o string) { st.output.Write([]byte(o)) }
[ "func", "(", "st", "*", "State", ")", "AppendOutputString", "(", "o", "string", ")", "{", "st", ".", "output", ".", "Write", "(", "[", "]", "byte", "(", "o", ")", ")", "\n", "}" ]
// AppendOutputString is the same as AppendOutput, but uses a string
[ "AppendOutputString", "is", "the", "same", "as", "AppendOutput", "but", "uses", "a", "string" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L102-L104
test
lestrrat-go/xslate
vm/state.go
Popmark
func (st *State) Popmark() int { x := st.markstack.Pop() return x.(int) }
go
func (st *State) Popmark() int { x := st.markstack.Pop() return x.(int) }
[ "func", "(", "st", "*", "State", ")", "Popmark", "(", ")", "int", "{", "x", ":=", "st", ".", "markstack", ".", "Pop", "(", ")", "\n", "return", "x", ".", "(", "int", ")", "\n", "}" ]
// Popmark pops the mark stored at the top of the mark stack
[ "Popmark", "pops", "the", "mark", "stored", "at", "the", "top", "of", "the", "mark", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L113-L116
test
lestrrat-go/xslate
vm/state.go
CurrentMark
func (st *State) CurrentMark() int { x, err := st.markstack.Top() if err != nil { x = 0 } return x.(int) }
go
func (st *State) CurrentMark() int { x, err := st.markstack.Top() if err != nil { x = 0 } return x.(int) }
[ "func", "(", "st", "*", "State", ")", "CurrentMark", "(", ")", "int", "{", "x", ",", "err", ":=", "st", ".", "markstack", ".", "Top", "(", ")", "\n", "if", "err", "!=", "nil", "{", "x", "=", "0", "\n", "}", "\n", "return", "x", ".", "(", "int", ")", "\n", "}" ]
// CurrentMark returns the mark stored at the top of the mark stack
[ "CurrentMark", "returns", "the", "mark", "stored", "at", "the", "top", "of", "the", "mark", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L119-L125
test
lestrrat-go/xslate
vm/state.go
LoadByteCode
func (st *State) LoadByteCode(key string) (*ByteCode, error) { return st.Loader.Load(key) }
go
func (st *State) LoadByteCode(key string) (*ByteCode, error) { return st.Loader.Load(key) }
[ "func", "(", "st", "*", "State", ")", "LoadByteCode", "(", "key", "string", ")", "(", "*", "ByteCode", ",", "error", ")", "{", "return", "st", ".", "Loader", ".", "Load", "(", "key", ")", "\n", "}" ]
// LoadByteCode loads a new ByteCode. This is used for op codes that // call to external templates such as `include`
[ "LoadByteCode", "loads", "a", "new", "ByteCode", ".", "This", "is", "used", "for", "op", "codes", "that", "call", "to", "external", "templates", "such", "as", "include" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L144-L146
test
lestrrat-go/xslate
vm/state.go
Reset
func (st *State) Reset() { st.opidx = 0 st.sa = nil st.sb = nil st.stack.Reset() st.markstack.Reset() st.frames.Reset() st.framestack.Reset() st.Pushmark() st.PushFrame() }
go
func (st *State) Reset() { st.opidx = 0 st.sa = nil st.sb = nil st.stack.Reset() st.markstack.Reset() st.frames.Reset() st.framestack.Reset() st.Pushmark() st.PushFrame() }
[ "func", "(", "st", "*", "State", ")", "Reset", "(", ")", "{", "st", ".", "opidx", "=", "0", "\n", "st", ".", "sa", "=", "nil", "\n", "st", ".", "sb", "=", "nil", "\n", "st", ".", "stack", ".", "Reset", "(", ")", "\n", "st", ".", "markstack", ".", "Reset", "(", ")", "\n", "st", ".", "frames", ".", "Reset", "(", ")", "\n", "st", ".", "framestack", ".", "Reset", "(", ")", "\n", "st", ".", "Pushmark", "(", ")", "\n", "st", ".", "PushFrame", "(", ")", "\n", "}" ]
// Reset resets the whole State object
[ "Reset", "resets", "the", "whole", "State", "object" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L149-L160
test
lestrrat-go/xslate
internal/frame/frame.go
DeclareVar
func (f *Frame) DeclareVar(v interface{}) int { f.stack.Push(v) return f.stack.Size() - 1 }
go
func (f *Frame) DeclareVar(v interface{}) int { f.stack.Push(v) return f.stack.Size() - 1 }
[ "func", "(", "f", "*", "Frame", ")", "DeclareVar", "(", "v", "interface", "{", "}", ")", "int", "{", "f", ".", "stack", ".", "Push", "(", "v", ")", "\n", "return", "f", ".", "stack", ".", "Size", "(", ")", "-", "1", "\n", "}" ]
// DeclareVar puts a new variable in the stack, and returns the // index where it now resides
[ "DeclareVar", "puts", "a", "new", "variable", "in", "the", "stack", "and", "returns", "the", "index", "where", "it", "now", "resides" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/frame/frame.go#L42-L45
test
lestrrat-go/xslate
internal/frame/frame.go
GetLvar
func (f *Frame) GetLvar(i int) (interface{}, error) { v, err := f.stack.Get(i) if err != nil { return nil, errors.Wrap(err, "failed to get local variable at "+strconv.Itoa(i+f.mark)) } return v, nil }
go
func (f *Frame) GetLvar(i int) (interface{}, error) { v, err := f.stack.Get(i) if err != nil { return nil, errors.Wrap(err, "failed to get local variable at "+strconv.Itoa(i+f.mark)) } return v, nil }
[ "func", "(", "f", "*", "Frame", ")", "GetLvar", "(", "i", "int", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "v", ",", "err", ":=", "f", ".", "stack", ".", "Get", "(", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to get local variable at \"", "+", "strconv", ".", "Itoa", "(", "i", "+", "f", ".", "mark", ")", ")", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// GetLvar gets the frame local variable at position i
[ "GetLvar", "gets", "the", "frame", "local", "variable", "at", "position", "i" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/frame/frame.go#L48-L54
test
lestrrat-go/xslate
internal/frame/frame.go
SetLvar
func (f *Frame) SetLvar(i int, v interface{}) { f.stack.Set(i, v) }
go
func (f *Frame) SetLvar(i int, v interface{}) { f.stack.Set(i, v) }
[ "func", "(", "f", "*", "Frame", ")", "SetLvar", "(", "i", "int", ",", "v", "interface", "{", "}", ")", "{", "f", ".", "stack", ".", "Set", "(", "i", ",", "v", ")", "\n", "}" ]
// SetLvar sets the frame local variable at position i
[ "SetLvar", "sets", "the", "frame", "local", "variable", "at", "position", "i" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/frame/frame.go#L57-L59
test
lestrrat-go/xslate
vm/bytecode.go
NewByteCode
func NewByteCode() *ByteCode { return &ByteCode{ GeneratedOn: time.Now(), Name: "", OpList: nil, Version: 1.0, } }
go
func NewByteCode() *ByteCode { return &ByteCode{ GeneratedOn: time.Now(), Name: "", OpList: nil, Version: 1.0, } }
[ "func", "NewByteCode", "(", ")", "*", "ByteCode", "{", "return", "&", "ByteCode", "{", "GeneratedOn", ":", "time", ".", "Now", "(", ")", ",", "Name", ":", "\"\"", ",", "OpList", ":", "nil", ",", "Version", ":", "1.0", ",", "}", "\n", "}" ]
// NewByteCode creates an empty ByteCode instance.
[ "NewByteCode", "creates", "an", "empty", "ByteCode", "instance", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L11-L18
test
lestrrat-go/xslate
vm/bytecode.go
Append
func (b *ByteCode) Append(op Op) { b.OpList = append(b.OpList, op) }
go
func (b *ByteCode) Append(op Op) { b.OpList = append(b.OpList, op) }
[ "func", "(", "b", "*", "ByteCode", ")", "Append", "(", "op", "Op", ")", "{", "b", ".", "OpList", "=", "append", "(", "b", ".", "OpList", ",", "op", ")", "\n", "}" ]
// Append appends an op code to the current list of op codes.
[ "Append", "appends", "an", "op", "code", "to", "the", "current", "list", "of", "op", "codes", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L32-L34
test
lestrrat-go/xslate
vm/bytecode.go
AppendOp
func (b *ByteCode) AppendOp(o OpType, args ...interface{}) Op { x := NewOp(o, args...) b.Append(x) return x }
go
func (b *ByteCode) AppendOp(o OpType, args ...interface{}) Op { x := NewOp(o, args...) b.Append(x) return x }
[ "func", "(", "b", "*", "ByteCode", ")", "AppendOp", "(", "o", "OpType", ",", "args", "...", "interface", "{", "}", ")", "Op", "{", "x", ":=", "NewOp", "(", "o", ",", "args", "...", ")", "\n", "b", ".", "Append", "(", "x", ")", "\n", "return", "x", "\n", "}" ]
// AppendOp is an utility method to create AND append a new op code to the // current list of op codes
[ "AppendOp", "is", "an", "utility", "method", "to", "create", "AND", "append", "a", "new", "op", "code", "to", "the", "current", "list", "of", "op", "codes" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L38-L42
test
lestrrat-go/xslate
vm/bytecode.go
String
func (b *ByteCode) String() string { buf := rbpool.Get() defer rbpool.Release(buf) fmt.Fprintf(buf, "// Bytecode for '%s'\n// Generated On: %s\n", b.Name, b.GeneratedOn, ) for k, v := range b.OpList { fmt.Fprintf(buf, "%03d. %s\n", k+1, v) } return buf.String() }
go
func (b *ByteCode) String() string { buf := rbpool.Get() defer rbpool.Release(buf) fmt.Fprintf(buf, "// Bytecode for '%s'\n// Generated On: %s\n", b.Name, b.GeneratedOn, ) for k, v := range b.OpList { fmt.Fprintf(buf, "%03d. %s\n", k+1, v) } return buf.String() }
[ "func", "(", "b", "*", "ByteCode", ")", "String", "(", ")", "string", "{", "buf", ":=", "rbpool", ".", "Get", "(", ")", "\n", "defer", "rbpool", ".", "Release", "(", "buf", ")", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"// Bytecode for '%s'\\n// Generated On: %s\\n\"", ",", "\\n", ",", "\\n", ",", ")", "\n", "b", ".", "Name", "\n", "b", ".", "GeneratedOn", "\n", "}" ]
// String returns the textual representation of this ByteCode
[ "String", "returns", "the", "textual", "representation", "of", "this", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L45-L58
test
lestrrat-go/xslate
loader/cache.go
NewCachedByteCodeLoader
func NewCachedByteCodeLoader( cache Cache, cacheLevel CacheStrategy, fetcher TemplateFetcher, parser parser.Parser, compiler compiler.Compiler, ) *CachedByteCodeLoader { return &CachedByteCodeLoader{ NewStringByteCodeLoader(parser, compiler), NewReaderByteCodeLoader(parser, compiler), fetcher, []Cache{MemoryCache{}, cache}, cacheLevel, } }
go
func NewCachedByteCodeLoader( cache Cache, cacheLevel CacheStrategy, fetcher TemplateFetcher, parser parser.Parser, compiler compiler.Compiler, ) *CachedByteCodeLoader { return &CachedByteCodeLoader{ NewStringByteCodeLoader(parser, compiler), NewReaderByteCodeLoader(parser, compiler), fetcher, []Cache{MemoryCache{}, cache}, cacheLevel, } }
[ "func", "NewCachedByteCodeLoader", "(", "cache", "Cache", ",", "cacheLevel", "CacheStrategy", ",", "fetcher", "TemplateFetcher", ",", "parser", "parser", ".", "Parser", ",", "compiler", "compiler", ".", "Compiler", ",", ")", "*", "CachedByteCodeLoader", "{", "return", "&", "CachedByteCodeLoader", "{", "NewStringByteCodeLoader", "(", "parser", ",", "compiler", ")", ",", "NewReaderByteCodeLoader", "(", "parser", ",", "compiler", ")", ",", "fetcher", ",", "[", "]", "Cache", "{", "MemoryCache", "{", "}", ",", "cache", "}", ",", "cacheLevel", ",", "}", "\n", "}" ]
// NewCachedByteCodeLoader creates a new CachedByteCodeLoader
[ "NewCachedByteCodeLoader", "creates", "a", "new", "CachedByteCodeLoader" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L18-L32
test
lestrrat-go/xslate
loader/cache.go
Load
func (l *CachedByteCodeLoader) Load(key string) (bc *vm.ByteCode, err error) { defer func() { if bc != nil && err == nil && l.ShouldDumpByteCode() { fmt.Fprintf(os.Stderr, "%s\n", bc.String()) } }() var source TemplateSource if l.CacheLevel > CacheNone { var entity *CacheEntity for _, cache := range l.Caches { entity, err = cache.Get(key) if err == nil { break } } if err == nil { if l.CacheLevel == CacheNoVerify { return entity.ByteCode, nil } t, err := entity.Source.LastModified() if err != nil { return nil, errors.Wrap(err, "failed to get last-modified from source") } if t.Before(entity.ByteCode.GeneratedOn) { return entity.ByteCode, nil } // ByteCode validation failed, but we can still re-use source source = entity.Source } } if source == nil { source, err = l.Fetcher.FetchTemplate(key) if err != nil { return nil, errors.Wrap(err, "failed to fetch template") } } rdr, err := source.Reader() if err != nil { return nil, errors.Wrap(err, "failed to get the reader") } bc, err = l.LoadReader(key, rdr) if err != nil { return nil, errors.Wrap(err, "failed to read byte code") } entity := &CacheEntity{bc, source} for _, cache := range l.Caches { cache.Set(key, entity) } return bc, nil }
go
func (l *CachedByteCodeLoader) Load(key string) (bc *vm.ByteCode, err error) { defer func() { if bc != nil && err == nil && l.ShouldDumpByteCode() { fmt.Fprintf(os.Stderr, "%s\n", bc.String()) } }() var source TemplateSource if l.CacheLevel > CacheNone { var entity *CacheEntity for _, cache := range l.Caches { entity, err = cache.Get(key) if err == nil { break } } if err == nil { if l.CacheLevel == CacheNoVerify { return entity.ByteCode, nil } t, err := entity.Source.LastModified() if err != nil { return nil, errors.Wrap(err, "failed to get last-modified from source") } if t.Before(entity.ByteCode.GeneratedOn) { return entity.ByteCode, nil } // ByteCode validation failed, but we can still re-use source source = entity.Source } } if source == nil { source, err = l.Fetcher.FetchTemplate(key) if err != nil { return nil, errors.Wrap(err, "failed to fetch template") } } rdr, err := source.Reader() if err != nil { return nil, errors.Wrap(err, "failed to get the reader") } bc, err = l.LoadReader(key, rdr) if err != nil { return nil, errors.Wrap(err, "failed to read byte code") } entity := &CacheEntity{bc, source} for _, cache := range l.Caches { cache.Set(key, entity) } return bc, nil }
[ "func", "(", "l", "*", "CachedByteCodeLoader", ")", "Load", "(", "key", "string", ")", "(", "bc", "*", "vm", ".", "ByteCode", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "bc", "!=", "nil", "&&", "err", "==", "nil", "&&", "l", ".", "ShouldDumpByteCode", "(", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"%s\\n\"", ",", "\\n", ")", "\n", "}", "\n", "}", "bc", ".", "String", "(", ")", "\n", "(", ")", "\n", "var", "source", "TemplateSource", "\n", "if", "l", ".", "CacheLevel", ">", "CacheNone", "{", "var", "entity", "*", "CacheEntity", "\n", "for", "_", ",", "cache", ":=", "range", "l", ".", "Caches", "{", "entity", ",", "err", "=", "cache", ".", "Get", "(", "key", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "if", "err", "==", "nil", "{", "if", "l", ".", "CacheLevel", "==", "CacheNoVerify", "{", "return", "entity", ".", "ByteCode", ",", "nil", "\n", "}", "\n", "t", ",", "err", ":=", "entity", ".", "Source", ".", "LastModified", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to get last-modified from source\"", ")", "\n", "}", "\n", "if", "t", ".", "Before", "(", "entity", ".", "ByteCode", ".", "GeneratedOn", ")", "{", "return", "entity", ".", "ByteCode", ",", "nil", "\n", "}", "\n", "source", "=", "entity", ".", "Source", "\n", "}", "\n", "}", "\n", "if", "source", "==", "nil", "{", "source", ",", "err", "=", "l", ".", "Fetcher", ".", "FetchTemplate", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to fetch template\"", ")", "\n", "}", "\n", "}", "\n", "rdr", ",", "err", ":=", "source", ".", "Reader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to get the reader\"", ")", "\n", "}", "\n", "bc", ",", "err", "=", "l", ".", "LoadReader", "(", "key", ",", "rdr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to read byte code\"", ")", "\n", "}", "\n", "entity", ":=", "&", "CacheEntity", "{", "bc", ",", "source", "}", "\n", "for", "_", ",", "cache", ":=", "range", "l", ".", "Caches", "{", "cache", ".", "Set", "(", "key", ",", "entity", ")", "\n", "}", "\n", "}" ]
// Load loads the ByteCode for template specified by `key`, which, for this // ByteCodeLoader, is the path to the template we want. // If cached vm.ByteCode struct is found, it is loaded and its last modified // time is compared against that of the template file. If the template is // newer, it's compiled. Otherwise the cached version is used, saving us the // time to parse and compile the template.
[ "Load", "loads", "the", "ByteCode", "for", "template", "specified", "by", "key", "which", "for", "this", "ByteCodeLoader", "is", "the", "path", "to", "the", "template", "we", "want", ".", "If", "cached", "vm", ".", "ByteCode", "struct", "is", "found", "it", "is", "loaded", "and", "its", "last", "modified", "time", "is", "compared", "against", "that", "of", "the", "template", "file", ".", "If", "the", "template", "is", "newer", "it", "s", "compiled", ".", "Otherwise", "the", "cached", "version", "is", "used", "saving", "us", "the", "time", "to", "parse", "and", "compile", "the", "template", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L58-L117
test
lestrrat-go/xslate
loader/cache.go
NewFileCache
func NewFileCache(dir string) (*FileCache, error) { f := &FileCache{dir} return f, nil }
go
func NewFileCache(dir string) (*FileCache, error) { f := &FileCache{dir} return f, nil }
[ "func", "NewFileCache", "(", "dir", "string", ")", "(", "*", "FileCache", ",", "error", ")", "{", "f", ":=", "&", "FileCache", "{", "dir", "}", "\n", "return", "f", ",", "nil", "\n", "}" ]
// NewFileCache creates a new FileCache which stores caches underneath // the directory specified by `dir`
[ "NewFileCache", "creates", "a", "new", "FileCache", "which", "stores", "caches", "underneath", "the", "directory", "specified", "by", "dir" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L121-L124
test
lestrrat-go/xslate
loader/cache.go
GetCachePath
func (c *FileCache) GetCachePath(key string) string { // What's the best, portable way to remove make an absolute path into // a relative path? key = filepath.Clean(key) key = strings.TrimPrefix(key, "/") return filepath.Join(c.Dir, key) }
go
func (c *FileCache) GetCachePath(key string) string { // What's the best, portable way to remove make an absolute path into // a relative path? key = filepath.Clean(key) key = strings.TrimPrefix(key, "/") return filepath.Join(c.Dir, key) }
[ "func", "(", "c", "*", "FileCache", ")", "GetCachePath", "(", "key", "string", ")", "string", "{", "key", "=", "filepath", ".", "Clean", "(", "key", ")", "\n", "key", "=", "strings", ".", "TrimPrefix", "(", "key", ",", "\"/\"", ")", "\n", "return", "filepath", ".", "Join", "(", "c", ".", "Dir", ",", "key", ")", "\n", "}" ]
// GetCachePath creates a string describing where a given template key // would be cached in the file system
[ "GetCachePath", "creates", "a", "string", "describing", "where", "a", "given", "template", "key", "would", "be", "cached", "in", "the", "file", "system" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L128-L134
test
lestrrat-go/xslate
loader/cache.go
Get
func (c *FileCache) Get(key string) (*CacheEntity, error) { path := c.GetCachePath(key) // Need to avoid race condition file, err := os.Open(path) if err != nil { return nil, errors.Wrap(err, "failed to open cache file '"+path+"'") } defer file.Close() var entity CacheEntity dec := gob.NewDecoder(file) if err = dec.Decode(&entity); err != nil { return nil, errors.Wrap(err, "failed to gob decode from cache file '"+path+"'") } return &entity, nil }
go
func (c *FileCache) Get(key string) (*CacheEntity, error) { path := c.GetCachePath(key) // Need to avoid race condition file, err := os.Open(path) if err != nil { return nil, errors.Wrap(err, "failed to open cache file '"+path+"'") } defer file.Close() var entity CacheEntity dec := gob.NewDecoder(file) if err = dec.Decode(&entity); err != nil { return nil, errors.Wrap(err, "failed to gob decode from cache file '"+path+"'") } return &entity, nil }
[ "func", "(", "c", "*", "FileCache", ")", "Get", "(", "key", "string", ")", "(", "*", "CacheEntity", ",", "error", ")", "{", "path", ":=", "c", ".", "GetCachePath", "(", "key", ")", "\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to open cache file '\"", "+", "path", "+", "\"'\"", ")", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "var", "entity", "CacheEntity", "\n", "dec", ":=", "gob", ".", "NewDecoder", "(", "file", ")", "\n", "if", "err", "=", "dec", ".", "Decode", "(", "&", "entity", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to gob decode from cache file '\"", "+", "path", "+", "\"'\"", ")", "\n", "}", "\n", "return", "&", "entity", ",", "nil", "\n", "}" ]
// Get returns the cached vm.ByteCode, if available
[ "Get", "returns", "the", "cached", "vm", ".", "ByteCode", "if", "available" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L137-L154
test
lestrrat-go/xslate
loader/cache.go
Set
func (c *FileCache) Set(key string, entity *CacheEntity) error { path := c.GetCachePath(key) if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil { return errors.Wrap(err, "failed to create directory for cache file") } // Need to avoid race condition file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { return errors.Wrap(err, "failed to open/create a cache file") } defer file.Close() f := bufio.NewWriter(file) defer f.Flush() enc := gob.NewEncoder(f) if err = enc.Encode(entity); err != nil { return errors.Wrap(err, "failed to encode Entity via gob") } return nil }
go
func (c *FileCache) Set(key string, entity *CacheEntity) error { path := c.GetCachePath(key) if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil { return errors.Wrap(err, "failed to create directory for cache file") } // Need to avoid race condition file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { return errors.Wrap(err, "failed to open/create a cache file") } defer file.Close() f := bufio.NewWriter(file) defer f.Flush() enc := gob.NewEncoder(f) if err = enc.Encode(entity); err != nil { return errors.Wrap(err, "failed to encode Entity via gob") } return nil }
[ "func", "(", "c", "*", "FileCache", ")", "Set", "(", "key", "string", ",", "entity", "*", "CacheEntity", ")", "error", "{", "path", ":=", "c", ".", "GetCachePath", "(", "key", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "path", ")", ",", "0777", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to create directory for cache file\"", ")", "\n", "}", "\n", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to open/create a cache file\"", ")", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "f", ":=", "bufio", ".", "NewWriter", "(", "file", ")", "\n", "defer", "f", ".", "Flush", "(", ")", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "f", ")", "\n", "if", "err", "=", "enc", ".", "Encode", "(", "entity", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to encode Entity via gob\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Set creates a new cache file to store the ByteCode.
[ "Set", "creates", "a", "new", "cache", "file", "to", "store", "the", "ByteCode", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L157-L178
test
lestrrat-go/xslate
loader/cache.go
Delete
func (c *FileCache) Delete(key string) error { return errors.Wrap(os.Remove(c.GetCachePath(key)), "failed to remove file cache file") }
go
func (c *FileCache) Delete(key string) error { return errors.Wrap(os.Remove(c.GetCachePath(key)), "failed to remove file cache file") }
[ "func", "(", "c", "*", "FileCache", ")", "Delete", "(", "key", "string", ")", "error", "{", "return", "errors", ".", "Wrap", "(", "os", ".", "Remove", "(", "c", ".", "GetCachePath", "(", "key", ")", ")", ",", "\"failed to remove file cache file\"", ")", "\n", "}" ]
// Delete deletes the cache
[ "Delete", "deletes", "the", "cache" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L181-L183
test
lestrrat-go/xslate
loader/cache.go
Get
func (c MemoryCache) Get(key string) (*CacheEntity, error) { bc, ok := c[key] if !ok { return nil, errors.New("cache miss") } return bc, nil }
go
func (c MemoryCache) Get(key string) (*CacheEntity, error) { bc, ok := c[key] if !ok { return nil, errors.New("cache miss") } return bc, nil }
[ "func", "(", "c", "MemoryCache", ")", "Get", "(", "key", "string", ")", "(", "*", "CacheEntity", ",", "error", ")", "{", "bc", ",", "ok", ":=", "c", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"cache miss\"", ")", "\n", "}", "\n", "return", "bc", ",", "nil", "\n", "}" ]
// Get returns the cached ByteCode
[ "Get", "returns", "the", "cached", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L186-L192
test
lestrrat-go/xslate
loader/cache.go
Set
func (c MemoryCache) Set(key string, bc *CacheEntity) error { c[key] = bc return nil }
go
func (c MemoryCache) Set(key string, bc *CacheEntity) error { c[key] = bc return nil }
[ "func", "(", "c", "MemoryCache", ")", "Set", "(", "key", "string", ",", "bc", "*", "CacheEntity", ")", "error", "{", "c", "[", "key", "]", "=", "bc", "\n", "return", "nil", "\n", "}" ]
// Set stores the ByteCode
[ "Set", "stores", "the", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L195-L198
test
lestrrat-go/xslate
loader/cache.go
Delete
func (c MemoryCache) Delete(key string) error { delete(c, key) return nil }
go
func (c MemoryCache) Delete(key string) error { delete(c, key) return nil }
[ "func", "(", "c", "MemoryCache", ")", "Delete", "(", "key", "string", ")", "error", "{", "delete", "(", "c", ",", "key", ")", "\n", "return", "nil", "\n", "}" ]
// Delete deletes the ByteCode
[ "Delete", "deletes", "the", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L201-L204
test
lestrrat-go/xslate
parser/tterse/tterse.go
NewStringLexer
func NewStringLexer(template string) *parser.Lexer { l := parser.NewStringLexer(template, SymbolSet) l.SetTagStart("[%") l.SetTagEnd("%]") return l }
go
func NewStringLexer(template string) *parser.Lexer { l := parser.NewStringLexer(template, SymbolSet) l.SetTagStart("[%") l.SetTagEnd("%]") return l }
[ "func", "NewStringLexer", "(", "template", "string", ")", "*", "parser", ".", "Lexer", "{", "l", ":=", "parser", ".", "NewStringLexer", "(", "template", ",", "SymbolSet", ")", "\n", "l", ".", "SetTagStart", "(", "\"[%\"", ")", "\n", "l", ".", "SetTagEnd", "(", "\"%]\"", ")", "\n", "return", "l", "\n", "}" ]
// NewStringLexer creates a new lexer
[ "NewStringLexer", "creates", "a", "new", "lexer" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/tterse/tterse.go#L36-L42
test
lestrrat-go/xslate
parser/tterse/tterse.go
NewReaderLexer
func NewReaderLexer(rdr io.Reader) *parser.Lexer { l := parser.NewReaderLexer(rdr, SymbolSet) l.SetTagStart("[%") l.SetTagEnd("%]") return l }
go
func NewReaderLexer(rdr io.Reader) *parser.Lexer { l := parser.NewReaderLexer(rdr, SymbolSet) l.SetTagStart("[%") l.SetTagEnd("%]") return l }
[ "func", "NewReaderLexer", "(", "rdr", "io", ".", "Reader", ")", "*", "parser", ".", "Lexer", "{", "l", ":=", "parser", ".", "NewReaderLexer", "(", "rdr", ",", "SymbolSet", ")", "\n", "l", ".", "SetTagStart", "(", "\"[%\"", ")", "\n", "l", ".", "SetTagEnd", "(", "\"%]\"", ")", "\n", "return", "l", "\n", "}" ]
// NewReaderLexer creates a new lexer
[ "NewReaderLexer", "creates", "a", "new", "lexer" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/tterse/tterse.go#L45-L51
test
fgrid/uuid
v4.go
NewV4
func NewV4() *UUID { buf := make([]byte, 16) rand.Read(buf) buf[6] = (buf[6] & 0x0f) | 0x40 var uuid UUID copy(uuid[:], buf[:]) uuid.variantRFC4122() return &uuid }
go
func NewV4() *UUID { buf := make([]byte, 16) rand.Read(buf) buf[6] = (buf[6] & 0x0f) | 0x40 var uuid UUID copy(uuid[:], buf[:]) uuid.variantRFC4122() return &uuid }
[ "func", "NewV4", "(", ")", "*", "UUID", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "16", ")", "\n", "rand", ".", "Read", "(", "buf", ")", "\n", "buf", "[", "6", "]", "=", "(", "buf", "[", "6", "]", "&", "0x0f", ")", "|", "0x40", "\n", "var", "uuid", "UUID", "\n", "copy", "(", "uuid", "[", ":", "]", ",", "buf", "[", ":", "]", ")", "\n", "uuid", ".", "variantRFC4122", "(", ")", "\n", "return", "&", "uuid", "\n", "}" ]
// NewV4 creates a new UUID with variant 4 as described in RFC 4122. Variant 4 based on pure random bytes.
[ "NewV4", "creates", "a", "new", "UUID", "with", "variant", "4", "as", "described", "in", "RFC", "4122", ".", "Variant", "4", "based", "on", "pure", "random", "bytes", "." ]
6f72a2d331c927473b9b19f590d43ccb5018c844
https://github.com/fgrid/uuid/blob/6f72a2d331c927473b9b19f590d43ccb5018c844/v4.go#L6-L14
test
lestrrat-go/xslate
parser/kolonish/kolonish.go
Parse
func (p *Kolonish) Parse(name string, template []byte) (*parser.AST, error) { return p.ParseString(name, string(template)) }
go
func (p *Kolonish) Parse(name string, template []byte) (*parser.AST, error) { return p.ParseString(name, string(template)) }
[ "func", "(", "p", "*", "Kolonish", ")", "Parse", "(", "name", "string", ",", "template", "[", "]", "byte", ")", "(", "*", "parser", ".", "AST", ",", "error", ")", "{", "return", "p", ".", "ParseString", "(", "name", ",", "string", "(", "template", ")", ")", "\n", "}" ]
// Parse parses the given template and creates an AST
[ "Parse", "parses", "the", "given", "template", "and", "creates", "an", "AST" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/kolonish/kolonish.go#L54-L56
test
lestrrat-go/xslate
parser/kolonish/kolonish.go
ParseReader
func (p *Kolonish) ParseReader(name string, rdr io.Reader) (*parser.AST, error) { b := parser.NewBuilder() lex := NewReaderLexer(rdr) return b.Parse(name, lex) }
go
func (p *Kolonish) ParseReader(name string, rdr io.Reader) (*parser.AST, error) { b := parser.NewBuilder() lex := NewReaderLexer(rdr) return b.Parse(name, lex) }
[ "func", "(", "p", "*", "Kolonish", ")", "ParseReader", "(", "name", "string", ",", "rdr", "io", ".", "Reader", ")", "(", "*", "parser", ".", "AST", ",", "error", ")", "{", "b", ":=", "parser", ".", "NewBuilder", "(", ")", "\n", "lex", ":=", "NewReaderLexer", "(", "rdr", ")", "\n", "return", "b", ".", "Parse", "(", "name", ",", "lex", ")", "\n", "}" ]
// ParseReader gets the template content from an io.Reader type
[ "ParseReader", "gets", "the", "template", "content", "from", "an", "io", ".", "Reader", "type" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/kolonish/kolonish.go#L66-L70
test
lestrrat-go/xslate
parser/ast.go
Visit
func (ast *AST) Visit() <-chan node.Node { c := make(chan node.Node) go func() { defer close(c) ast.Root.Visit(c) }() return c }
go
func (ast *AST) Visit() <-chan node.Node { c := make(chan node.Node) go func() { defer close(c) ast.Root.Visit(c) }() return c }
[ "func", "(", "ast", "*", "AST", ")", "Visit", "(", ")", "<-", "chan", "node", ".", "Node", "{", "c", ":=", "make", "(", "chan", "node", ".", "Node", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "ast", ".", "Root", ".", "Visit", "(", "c", ")", "\n", "}", "(", ")", "\n", "return", "c", "\n", "}" ]
// Visit returns a channel which you can receive Node structs in order that // that they would be processed
[ "Visit", "returns", "a", "channel", "which", "you", "can", "receive", "Node", "structs", "in", "order", "that", "that", "they", "would", "be", "processed" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/ast.go#L12-L19
test
lestrrat-go/xslate
parser/ast.go
String
func (ast *AST) String() string { buf := rbpool.Get() defer rbpool.Release(buf) c := ast.Visit() k := 0 for v := range c { k++ fmt.Fprintf(buf, "%03d. %s\n", k, v) } return buf.String() }
go
func (ast *AST) String() string { buf := rbpool.Get() defer rbpool.Release(buf) c := ast.Visit() k := 0 for v := range c { k++ fmt.Fprintf(buf, "%03d. %s\n", k, v) } return buf.String() }
[ "func", "(", "ast", "*", "AST", ")", "String", "(", ")", "string", "{", "buf", ":=", "rbpool", ".", "Get", "(", ")", "\n", "defer", "rbpool", ".", "Release", "(", "buf", ")", "\n", "c", ":=", "ast", ".", "Visit", "(", ")", "\n", "k", ":=", "0", "\n", "for", "v", ":=", "range", "c", "{", "k", "++", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"%03d. %s\\n\"", ",", "\\n", ",", "k", ")", "\n", "}", "\n", "v", "\n", "}" ]
// String returns the textual representation of this AST
[ "String", "returns", "the", "textual", "representation", "of", "this", "AST" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/ast.go#L22-L33
test
lestrrat-go/xslate
vm/vm.go
Run
func (vm *VM) Run(bc *ByteCode, vars Vars, output io.Writer) { if !vm.IsSupportedByteCodeVersion(bc) { panic(fmt.Sprintf( "error: ByteCode version %f no supported", bc.Version, )) } st := vm.st if _, ok := output.(*bufio.Writer); !ok { output = bufio.NewWriter(output) defer output.(*bufio.Writer).Flush() } st.Reset() st.pc = bc st.output = output newvars := Vars(rvpool.Get()) defer rvpool.Release(newvars) defer newvars.Reset() st.vars = newvars if fc := vm.functions; fc != nil { for k, v := range vm.functions { st.vars[k] = v } } if vars != nil { for k, v := range vars { st.vars[k] = v } } st.Loader = vm.Loader // This is the main loop for op := st.CurrentOp(); op.Type() != TXOPEnd; op = st.CurrentOp() { op.Call(st) } }
go
func (vm *VM) Run(bc *ByteCode, vars Vars, output io.Writer) { if !vm.IsSupportedByteCodeVersion(bc) { panic(fmt.Sprintf( "error: ByteCode version %f no supported", bc.Version, )) } st := vm.st if _, ok := output.(*bufio.Writer); !ok { output = bufio.NewWriter(output) defer output.(*bufio.Writer).Flush() } st.Reset() st.pc = bc st.output = output newvars := Vars(rvpool.Get()) defer rvpool.Release(newvars) defer newvars.Reset() st.vars = newvars if fc := vm.functions; fc != nil { for k, v := range vm.functions { st.vars[k] = v } } if vars != nil { for k, v := range vars { st.vars[k] = v } } st.Loader = vm.Loader // This is the main loop for op := st.CurrentOp(); op.Type() != TXOPEnd; op = st.CurrentOp() { op.Call(st) } }
[ "func", "(", "vm", "*", "VM", ")", "Run", "(", "bc", "*", "ByteCode", ",", "vars", "Vars", ",", "output", "io", ".", "Writer", ")", "{", "if", "!", "vm", ".", "IsSupportedByteCodeVersion", "(", "bc", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"error: ByteCode version %f no supported\"", ",", "bc", ".", "Version", ",", ")", ")", "\n", "}", "\n", "st", ":=", "vm", ".", "st", "\n", "if", "_", ",", "ok", ":=", "output", ".", "(", "*", "bufio", ".", "Writer", ")", ";", "!", "ok", "{", "output", "=", "bufio", ".", "NewWriter", "(", "output", ")", "\n", "defer", "output", ".", "(", "*", "bufio", ".", "Writer", ")", ".", "Flush", "(", ")", "\n", "}", "\n", "st", ".", "Reset", "(", ")", "\n", "st", ".", "pc", "=", "bc", "\n", "st", ".", "output", "=", "output", "\n", "newvars", ":=", "Vars", "(", "rvpool", ".", "Get", "(", ")", ")", "\n", "defer", "rvpool", ".", "Release", "(", "newvars", ")", "\n", "defer", "newvars", ".", "Reset", "(", ")", "\n", "st", ".", "vars", "=", "newvars", "\n", "if", "fc", ":=", "vm", ".", "functions", ";", "fc", "!=", "nil", "{", "for", "k", ",", "v", ":=", "range", "vm", ".", "functions", "{", "st", ".", "vars", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "if", "vars", "!=", "nil", "{", "for", "k", ",", "v", ":=", "range", "vars", "{", "st", ".", "vars", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "st", ".", "Loader", "=", "vm", ".", "Loader", "\n", "for", "op", ":=", "st", ".", "CurrentOp", "(", ")", ";", "op", ".", "Type", "(", ")", "!=", "TXOPEnd", ";", "op", "=", "st", ".", "CurrentOp", "(", ")", "{", "op", ".", "Call", "(", "st", ")", "\n", "}", "\n", "}" ]
// Run executes the given vm.ByteCode using the given variables. For historical // reasons, it also allows re-executing the previous bytecode instructions // given to a virtual machine, but this will probably be removed in the future
[ "Run", "executes", "the", "given", "vm", ".", "ByteCode", "using", "the", "given", "variables", ".", "For", "historical", "reasons", "it", "also", "allows", "re", "-", "executing", "the", "previous", "bytecode", "instructions", "given", "to", "a", "virtual", "machine", "but", "this", "will", "probably", "be", "removed", "in", "the", "future" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/vm.go#L52-L91
test
lestrrat-go/xslate
xslate.go
DefaultParser
func DefaultParser(tx *Xslate, args Args) error { syntax, ok := args.Get("Syntax") if !ok { syntax = "TTerse" } switch syntax { case "TTerse": tx.Parser = tterse.New() case "Kolon", "Kolonish": tx.Parser = kolonish.New() default: return errors.New("sytanx '" + syntax.(string) + "' is not available") } return nil }
go
func DefaultParser(tx *Xslate, args Args) error { syntax, ok := args.Get("Syntax") if !ok { syntax = "TTerse" } switch syntax { case "TTerse": tx.Parser = tterse.New() case "Kolon", "Kolonish": tx.Parser = kolonish.New() default: return errors.New("sytanx '" + syntax.(string) + "' is not available") } return nil }
[ "func", "DefaultParser", "(", "tx", "*", "Xslate", ",", "args", "Args", ")", "error", "{", "syntax", ",", "ok", ":=", "args", ".", "Get", "(", "\"Syntax\"", ")", "\n", "if", "!", "ok", "{", "syntax", "=", "\"TTerse\"", "\n", "}", "\n", "switch", "syntax", "{", "case", "\"TTerse\"", ":", "tx", ".", "Parser", "=", "tterse", ".", "New", "(", ")", "\n", "case", "\"Kolon\"", ",", "\"Kolonish\"", ":", "tx", ".", "Parser", "=", "kolonish", ".", "New", "(", ")", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"sytanx '\"", "+", "syntax", ".", "(", "string", ")", "+", "\"' is not available\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DefaultParser sets up and assigns the default parser to be used by Xslate.
[ "DefaultParser", "sets", "up", "and", "assigns", "the", "default", "parser", "to", "be", "used", "by", "Xslate", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L114-L129
test
lestrrat-go/xslate
xslate.go
DefaultLoader
func DefaultLoader(tx *Xslate, args Args) error { var tmp interface{} tmp, ok := args.Get("CacheDir") if !ok { tmp, _ = ioutil.TempDir("", "go-xslate-cache-") } cacheDir := tmp.(string) tmp, ok = args.Get("LoadPaths") if !ok { cwd, _ := os.Getwd() tmp = []string{cwd} } paths := tmp.([]string) cache, err := loader.NewFileCache(cacheDir) if err != nil { return err } fetcher, err := loader.NewFileTemplateFetcher(paths) if err != nil { return err } tmp, ok = args.Get("CacheLevel") if !ok { tmp = 1 } cacheLevel := tmp.(int) tx.Loader = loader.NewCachedByteCodeLoader(cache, loader.CacheStrategy(cacheLevel), fetcher, tx.Parser, tx.Compiler) return nil }
go
func DefaultLoader(tx *Xslate, args Args) error { var tmp interface{} tmp, ok := args.Get("CacheDir") if !ok { tmp, _ = ioutil.TempDir("", "go-xslate-cache-") } cacheDir := tmp.(string) tmp, ok = args.Get("LoadPaths") if !ok { cwd, _ := os.Getwd() tmp = []string{cwd} } paths := tmp.([]string) cache, err := loader.NewFileCache(cacheDir) if err != nil { return err } fetcher, err := loader.NewFileTemplateFetcher(paths) if err != nil { return err } tmp, ok = args.Get("CacheLevel") if !ok { tmp = 1 } cacheLevel := tmp.(int) tx.Loader = loader.NewCachedByteCodeLoader(cache, loader.CacheStrategy(cacheLevel), fetcher, tx.Parser, tx.Compiler) return nil }
[ "func", "DefaultLoader", "(", "tx", "*", "Xslate", ",", "args", "Args", ")", "error", "{", "var", "tmp", "interface", "{", "}", "\n", "tmp", ",", "ok", ":=", "args", ".", "Get", "(", "\"CacheDir\"", ")", "\n", "if", "!", "ok", "{", "tmp", ",", "_", "=", "ioutil", ".", "TempDir", "(", "\"\"", ",", "\"go-xslate-cache-\"", ")", "\n", "}", "\n", "cacheDir", ":=", "tmp", ".", "(", "string", ")", "\n", "tmp", ",", "ok", "=", "args", ".", "Get", "(", "\"LoadPaths\"", ")", "\n", "if", "!", "ok", "{", "cwd", ",", "_", ":=", "os", ".", "Getwd", "(", ")", "\n", "tmp", "=", "[", "]", "string", "{", "cwd", "}", "\n", "}", "\n", "paths", ":=", "tmp", ".", "(", "[", "]", "string", ")", "\n", "cache", ",", "err", ":=", "loader", ".", "NewFileCache", "(", "cacheDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fetcher", ",", "err", ":=", "loader", ".", "NewFileTemplateFetcher", "(", "paths", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tmp", ",", "ok", "=", "args", ".", "Get", "(", "\"CacheLevel\"", ")", "\n", "if", "!", "ok", "{", "tmp", "=", "1", "\n", "}", "\n", "cacheLevel", ":=", "tmp", ".", "(", "int", ")", "\n", "tx", ".", "Loader", "=", "loader", ".", "NewCachedByteCodeLoader", "(", "cache", ",", "loader", ".", "CacheStrategy", "(", "cacheLevel", ")", ",", "fetcher", ",", "tx", ".", "Parser", ",", "tx", ".", "Compiler", ")", "\n", "return", "nil", "\n", "}" ]
// DefaultLoader sets up and assigns the default loader to be used by Xslate.
[ "DefaultLoader", "sets", "up", "and", "assigns", "the", "default", "loader", "to", "be", "used", "by", "Xslate", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L132-L165
test
lestrrat-go/xslate
xslate.go
DefaultVM
func DefaultVM(tx *Xslate, args Args) error { dvm := vm.NewVM() dvm.Loader = tx.Loader tx.VM = dvm return nil }
go
func DefaultVM(tx *Xslate, args Args) error { dvm := vm.NewVM() dvm.Loader = tx.Loader tx.VM = dvm return nil }
[ "func", "DefaultVM", "(", "tx", "*", "Xslate", ",", "args", "Args", ")", "error", "{", "dvm", ":=", "vm", ".", "NewVM", "(", ")", "\n", "dvm", ".", "Loader", "=", "tx", ".", "Loader", "\n", "tx", ".", "VM", "=", "dvm", "\n", "return", "nil", "\n", "}" ]
// DefaultVM sets up and assigns the default VM to be used by Xslate
[ "DefaultVM", "sets", "up", "and", "assigns", "the", "default", "VM", "to", "be", "used", "by", "Xslate" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L168-L173
test
lestrrat-go/xslate
xslate.go
Get
func (args Args) Get(key string) (interface{}, bool) { ret, ok := args[key] return ret, ok }
go
func (args Args) Get(key string) (interface{}, bool) { ret, ok := args[key] return ret, ok }
[ "func", "(", "args", "Args", ")", "Get", "(", "key", "string", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "ret", ",", "ok", ":=", "args", "[", "key", "]", "\n", "return", "ret", ",", "ok", "\n", "}" ]
// Get retrieves the value assigned to `key`
[ "Get", "retrieves", "the", "value", "assigned", "to", "key" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L176-L179
test
lestrrat-go/xslate
loader/http.go
NewHTTPSource
func NewHTTPSource(r *http.Response) (*HTTPSource, error) { body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } s := &HTTPSource{ bytes.NewBuffer(body), time.Time{}, } if lastmodStr := r.Header.Get("Last-Modified"); lastmodStr != "" { t, err := time.Parse(http.TimeFormat, lastmodStr) if err != nil { fmt.Printf("failed to parse: %s\n", err) t = time.Now() } s.LastModifiedTime = t } else { s.LastModifiedTime = time.Now() } return s, nil }
go
func NewHTTPSource(r *http.Response) (*HTTPSource, error) { body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } s := &HTTPSource{ bytes.NewBuffer(body), time.Time{}, } if lastmodStr := r.Header.Get("Last-Modified"); lastmodStr != "" { t, err := time.Parse(http.TimeFormat, lastmodStr) if err != nil { fmt.Printf("failed to parse: %s\n", err) t = time.Now() } s.LastModifiedTime = t } else { s.LastModifiedTime = time.Now() } return s, nil }
[ "func", "NewHTTPSource", "(", "r", "*", "http", ".", "Response", ")", "(", "*", "HTTPSource", ",", "error", ")", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "s", ":=", "&", "HTTPSource", "{", "bytes", ".", "NewBuffer", "(", "body", ")", ",", "time", ".", "Time", "{", "}", ",", "}", "\n", "if", "lastmodStr", ":=", "r", ".", "Header", ".", "Get", "(", "\"Last-Modified\"", ")", ";", "lastmodStr", "!=", "\"\"", "{", "t", ",", "err", ":=", "time", ".", "Parse", "(", "http", ".", "TimeFormat", ",", "lastmodStr", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"failed to parse: %s\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "t", "=", "time", ".", "Now", "(", ")", "\n", "}", "else", "s", ".", "LastModifiedTime", "=", "t", "\n", "{", "s", ".", "LastModifiedTime", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n", "}" ]
// NewHTTPSource creates a new HTTPSource instance
[ "NewHTTPSource", "creates", "a", "new", "HTTPSource", "instance" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/http.go#L60-L83
test
lestrrat-go/xslate
loader/string.go
NewStringByteCodeLoader
func NewStringByteCodeLoader(p parser.Parser, c compiler.Compiler) *StringByteCodeLoader { return &StringByteCodeLoader{NewFlags(), p, c} }
go
func NewStringByteCodeLoader(p parser.Parser, c compiler.Compiler) *StringByteCodeLoader { return &StringByteCodeLoader{NewFlags(), p, c} }
[ "func", "NewStringByteCodeLoader", "(", "p", "parser", ".", "Parser", ",", "c", "compiler", ".", "Compiler", ")", "*", "StringByteCodeLoader", "{", "return", "&", "StringByteCodeLoader", "{", "NewFlags", "(", ")", ",", "p", ",", "c", "}", "\n", "}" ]
// NewStringByteCodeLoader creates a new object
[ "NewStringByteCodeLoader", "creates", "a", "new", "object" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/string.go#L12-L14
test
lestrrat-go/xslate
loader/string.go
LoadString
func (l *StringByteCodeLoader) LoadString(name string, template string) (*vm.ByteCode, error) { ast, err := l.Parser.ParseString(name, template) if err != nil { return nil, err } if l.ShouldDumpAST() { fmt.Fprintf(os.Stderr, "AST:\n%s\n", ast) } bc, err := l.Compiler.Compile(ast) if err != nil { return nil, err } if l.ShouldDumpByteCode() { fmt.Fprintf(os.Stderr, "ByteCode:\n%s\n", bc) } return bc, nil }
go
func (l *StringByteCodeLoader) LoadString(name string, template string) (*vm.ByteCode, error) { ast, err := l.Parser.ParseString(name, template) if err != nil { return nil, err } if l.ShouldDumpAST() { fmt.Fprintf(os.Stderr, "AST:\n%s\n", ast) } bc, err := l.Compiler.Compile(ast) if err != nil { return nil, err } if l.ShouldDumpByteCode() { fmt.Fprintf(os.Stderr, "ByteCode:\n%s\n", bc) } return bc, nil }
[ "func", "(", "l", "*", "StringByteCodeLoader", ")", "LoadString", "(", "name", "string", ",", "template", "string", ")", "(", "*", "vm", ".", "ByteCode", ",", "error", ")", "{", "ast", ",", "err", ":=", "l", ".", "Parser", ".", "ParseString", "(", "name", ",", "template", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "l", ".", "ShouldDumpAST", "(", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"AST:\\n%s\\n\"", ",", "\\n", ")", "\n", "}", "\n", "\\n", "\n", "ast", "\n", "bc", ",", "err", ":=", "l", ".", "Compiler", ".", "Compile", "(", "ast", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// LoadString takes a template string and compiles it into vm.ByteCode
[ "LoadString", "takes", "a", "template", "string", "and", "compiles", "it", "into", "vm", ".", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/string.go#L17-L37
test
lestrrat-go/xslate
vm/vars.go
Get
func (v Vars) Get(k interface{}) (interface{}, bool) { key, ok := k.(string) if !ok { key = fmt.Sprintf("%s", k) } x, ok := v[key] return x, ok }
go
func (v Vars) Get(k interface{}) (interface{}, bool) { key, ok := k.(string) if !ok { key = fmt.Sprintf("%s", k) } x, ok := v[key] return x, ok }
[ "func", "(", "v", "Vars", ")", "Get", "(", "k", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "key", ",", "ok", ":=", "k", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "key", "=", "fmt", ".", "Sprintf", "(", "\"%s\"", ",", "k", ")", "\n", "}", "\n", "x", ",", "ok", ":=", "v", "[", "key", "]", "\n", "return", "x", ",", "ok", "\n", "}" ]
// Get returns the variable stored in slot `x`
[ "Get", "returns", "the", "variable", "stored", "in", "slot", "x" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/vars.go#L13-L20
test
lestrrat-go/xslate
vm/op.go
NewOp
func NewOp(o OpType, args ...interface{}) Op { h := optypeToHandler(o) var arg interface{} if len(args) > 0 { arg = args[0] } return &op{ OpType: o, OpHandler: h, uArg: arg, } }
go
func NewOp(o OpType, args ...interface{}) Op { h := optypeToHandler(o) var arg interface{} if len(args) > 0 { arg = args[0] } return &op{ OpType: o, OpHandler: h, uArg: arg, } }
[ "func", "NewOp", "(", "o", "OpType", ",", "args", "...", "interface", "{", "}", ")", "Op", "{", "h", ":=", "optypeToHandler", "(", "o", ")", "\n", "var", "arg", "interface", "{", "}", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "arg", "=", "args", "[", "0", "]", "\n", "}", "\n", "return", "&", "op", "{", "OpType", ":", "o", ",", "OpHandler", ":", "h", ",", "uArg", ":", "arg", ",", "}", "\n", "}" ]
// NewOp creates a new Op.
[ "NewOp", "creates", "a", "new", "Op", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L27-L40
test
lestrrat-go/xslate
vm/op.go
MarshalBinary
func (o op) MarshalBinary() ([]byte, error) { buf := rbpool.Get() defer rbpool.Release(buf) // Write the code/opcode if err := binary.Write(buf, binary.LittleEndian, int64(o.OpType)); err != nil { return nil, errors.Wrap(err, "failed to marshal op to binary") } // If this has args, we need to encode the args tArg := reflect.TypeOf(o.uArg) hasArg := tArg != nil if hasArg { binary.Write(buf, binary.LittleEndian, int8(1)) } else { binary.Write(buf, binary.LittleEndian, int8(0)) } if hasArg { switch tArg.Kind() { case reflect.Int: binary.Write(buf, binary.LittleEndian, int64(2)) binary.Write(buf, binary.LittleEndian, int64(o.uArg.(int))) case reflect.Int64: binary.Write(buf, binary.LittleEndian, int64(2)) binary.Write(buf, binary.LittleEndian, int64(o.uArg.(int64))) case reflect.Slice: if tArg.Elem().Kind() != reflect.Uint8 { panic("Slice of what?") } binary.Write(buf, binary.LittleEndian, int64(5)) binary.Write(buf, binary.LittleEndian, int64(len(o.uArg.([]byte)))) for _, v := range o.uArg.([]byte) { binary.Write(buf, binary.LittleEndian, v) } case reflect.String: binary.Write(buf, binary.LittleEndian, int64(6)) binary.Write(buf, binary.LittleEndian, int64(len(o.uArg.(string)))) for _, v := range []byte(o.uArg.(string)) { binary.Write(buf, binary.LittleEndian, v) } default: panic("Unknown type " + tArg.String()) } } v := o.comment hasComment := v != "" if hasComment { binary.Write(buf, binary.LittleEndian, int8(1)) binary.Write(buf, binary.LittleEndian, v) } else { binary.Write(buf, binary.LittleEndian, int8(0)) } return buf.Bytes(), nil }
go
func (o op) MarshalBinary() ([]byte, error) { buf := rbpool.Get() defer rbpool.Release(buf) // Write the code/opcode if err := binary.Write(buf, binary.LittleEndian, int64(o.OpType)); err != nil { return nil, errors.Wrap(err, "failed to marshal op to binary") } // If this has args, we need to encode the args tArg := reflect.TypeOf(o.uArg) hasArg := tArg != nil if hasArg { binary.Write(buf, binary.LittleEndian, int8(1)) } else { binary.Write(buf, binary.LittleEndian, int8(0)) } if hasArg { switch tArg.Kind() { case reflect.Int: binary.Write(buf, binary.LittleEndian, int64(2)) binary.Write(buf, binary.LittleEndian, int64(o.uArg.(int))) case reflect.Int64: binary.Write(buf, binary.LittleEndian, int64(2)) binary.Write(buf, binary.LittleEndian, int64(o.uArg.(int64))) case reflect.Slice: if tArg.Elem().Kind() != reflect.Uint8 { panic("Slice of what?") } binary.Write(buf, binary.LittleEndian, int64(5)) binary.Write(buf, binary.LittleEndian, int64(len(o.uArg.([]byte)))) for _, v := range o.uArg.([]byte) { binary.Write(buf, binary.LittleEndian, v) } case reflect.String: binary.Write(buf, binary.LittleEndian, int64(6)) binary.Write(buf, binary.LittleEndian, int64(len(o.uArg.(string)))) for _, v := range []byte(o.uArg.(string)) { binary.Write(buf, binary.LittleEndian, v) } default: panic("Unknown type " + tArg.String()) } } v := o.comment hasComment := v != "" if hasComment { binary.Write(buf, binary.LittleEndian, int8(1)) binary.Write(buf, binary.LittleEndian, v) } else { binary.Write(buf, binary.LittleEndian, int8(0)) } return buf.Bytes(), nil }
[ "func", "(", "o", "op", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "rbpool", ".", "Get", "(", ")", "\n", "defer", "rbpool", ".", "Release", "(", "buf", ")", "\n", "if", "err", ":=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "o", ".", "OpType", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"failed to marshal op to binary\"", ")", "\n", "}", "\n", "tArg", ":=", "reflect", ".", "TypeOf", "(", "o", ".", "uArg", ")", "\n", "hasArg", ":=", "tArg", "!=", "nil", "\n", "if", "hasArg", "{", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int8", "(", "1", ")", ")", "\n", "}", "else", "{", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int8", "(", "0", ")", ")", "\n", "}", "\n", "if", "hasArg", "{", "switch", "tArg", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ":", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "2", ")", ")", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "o", ".", "uArg", ".", "(", "int", ")", ")", ")", "\n", "case", "reflect", ".", "Int64", ":", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "2", ")", ")", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "o", ".", "uArg", ".", "(", "int64", ")", ")", ")", "\n", "case", "reflect", ".", "Slice", ":", "if", "tArg", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Uint8", "{", "panic", "(", "\"Slice of what?\"", ")", "\n", "}", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "5", ")", ")", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "len", "(", "o", ".", "uArg", ".", "(", "[", "]", "byte", ")", ")", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "o", ".", "uArg", ".", "(", "[", "]", "byte", ")", "{", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "v", ")", "\n", "}", "\n", "case", "reflect", ".", "String", ":", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "6", ")", ")", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int64", "(", "len", "(", "o", ".", "uArg", ".", "(", "string", ")", ")", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "[", "]", "byte", "(", "o", ".", "uArg", ".", "(", "string", ")", ")", "{", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "v", ")", "\n", "}", "\n", "default", ":", "panic", "(", "\"Unknown type \"", "+", "tArg", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n", "v", ":=", "o", ".", "comment", "\n", "hasComment", ":=", "v", "!=", "\"\"", "\n", "if", "hasComment", "{", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int8", "(", "1", ")", ")", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "v", ")", "\n", "}", "else", "{", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "int8", "(", "0", ")", ")", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalBinary is used to serialize an Op into a binary form. This // is used to cache the ByteCode
[ "MarshalBinary", "is", "used", "to", "serialize", "an", "Op", "into", "a", "binary", "form", ".", "This", "is", "used", "to", "cache", "the", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L52-L108
test
lestrrat-go/xslate
vm/op.go
UnmarshalBinary
func (o *op) UnmarshalBinary(data []byte) error { buf := bytes.NewReader(data) var t int64 if err := binary.Read(buf, binary.LittleEndian, &t); err != nil { return errors.Wrap(err, "optype check failed during UnmarshalBinary") } o.OpType = OpType(t) o.OpHandler = optypeToHandler(o.OpType) var hasArg int8 if err := binary.Read(buf, binary.LittleEndian, &hasArg); err != nil { return errors.Wrap(err, "hasArg check failed during UnmarshalBinary") } if hasArg == 1 { var tArg int64 if err := binary.Read(buf, binary.LittleEndian, &tArg); err != nil { return errors.Wrap(err, "failed to read argument from buffer during UnmarshalBinary") } switch tArg { case 2: var i int64 if err := binary.Read(buf, binary.LittleEndian, &i); err != nil { return errors.Wrap(err, "failed to read integer argument during UnmarshalBinary") } o.uArg = i case 5: var l int64 if err := binary.Read(buf, binary.LittleEndian, &l); err != nil { return errors.Wrap(err, "failed to read length argument during UnmarshalBinary") } b := make([]byte, l) for i := int64(0); i < l; i++ { if err := binary.Read(buf, binary.LittleEndian, &b[i]); err != nil { return errors.Wrap(err, "failed to read bytes from buffer during UnmarshalBinary") } } o.uArg = b default: panic(fmt.Sprintf("Unknown tArg: %d", tArg)) } } var hasComment int8 if err := binary.Read(buf, binary.LittleEndian, &hasComment); err != nil { return errors.Wrap(err, "hasComment check failed during UnmarshalBinary") } if hasComment == 1 { if err := binary.Read(buf, binary.LittleEndian, &o.comment); err != nil { return errors.Wrap(err, "failed to read comment bytes during UnmarshalBinary") } } return nil }
go
func (o *op) UnmarshalBinary(data []byte) error { buf := bytes.NewReader(data) var t int64 if err := binary.Read(buf, binary.LittleEndian, &t); err != nil { return errors.Wrap(err, "optype check failed during UnmarshalBinary") } o.OpType = OpType(t) o.OpHandler = optypeToHandler(o.OpType) var hasArg int8 if err := binary.Read(buf, binary.LittleEndian, &hasArg); err != nil { return errors.Wrap(err, "hasArg check failed during UnmarshalBinary") } if hasArg == 1 { var tArg int64 if err := binary.Read(buf, binary.LittleEndian, &tArg); err != nil { return errors.Wrap(err, "failed to read argument from buffer during UnmarshalBinary") } switch tArg { case 2: var i int64 if err := binary.Read(buf, binary.LittleEndian, &i); err != nil { return errors.Wrap(err, "failed to read integer argument during UnmarshalBinary") } o.uArg = i case 5: var l int64 if err := binary.Read(buf, binary.LittleEndian, &l); err != nil { return errors.Wrap(err, "failed to read length argument during UnmarshalBinary") } b := make([]byte, l) for i := int64(0); i < l; i++ { if err := binary.Read(buf, binary.LittleEndian, &b[i]); err != nil { return errors.Wrap(err, "failed to read bytes from buffer during UnmarshalBinary") } } o.uArg = b default: panic(fmt.Sprintf("Unknown tArg: %d", tArg)) } } var hasComment int8 if err := binary.Read(buf, binary.LittleEndian, &hasComment); err != nil { return errors.Wrap(err, "hasComment check failed during UnmarshalBinary") } if hasComment == 1 { if err := binary.Read(buf, binary.LittleEndian, &o.comment); err != nil { return errors.Wrap(err, "failed to read comment bytes during UnmarshalBinary") } } return nil }
[ "func", "(", "o", "*", "op", ")", "UnmarshalBinary", "(", "data", "[", "]", "byte", ")", "error", "{", "buf", ":=", "bytes", ".", "NewReader", "(", "data", ")", "\n", "var", "t", "int64", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "t", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"optype check failed during UnmarshalBinary\"", ")", "\n", "}", "\n", "o", ".", "OpType", "=", "OpType", "(", "t", ")", "\n", "o", ".", "OpHandler", "=", "optypeToHandler", "(", "o", ".", "OpType", ")", "\n", "var", "hasArg", "int8", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "hasArg", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"hasArg check failed during UnmarshalBinary\"", ")", "\n", "}", "\n", "if", "hasArg", "==", "1", "{", "var", "tArg", "int64", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "tArg", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to read argument from buffer during UnmarshalBinary\"", ")", "\n", "}", "\n", "switch", "tArg", "{", "case", "2", ":", "var", "i", "int64", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "i", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to read integer argument during UnmarshalBinary\"", ")", "\n", "}", "\n", "o", ".", "uArg", "=", "i", "\n", "case", "5", ":", "var", "l", "int64", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "l", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to read length argument during UnmarshalBinary\"", ")", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "l", ")", "\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "l", ";", "i", "++", "{", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "b", "[", "i", "]", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to read bytes from buffer during UnmarshalBinary\"", ")", "\n", "}", "\n", "}", "\n", "o", ".", "uArg", "=", "b", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"Unknown tArg: %d\"", ",", "tArg", ")", ")", "\n", "}", "\n", "}", "\n", "var", "hasComment", "int8", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "hasComment", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"hasComment check failed during UnmarshalBinary\"", ")", "\n", "}", "\n", "if", "hasComment", "==", "1", "{", "if", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "o", ".", "comment", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to read comment bytes during UnmarshalBinary\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary is used to deserialize an Op from binary form.
[ "UnmarshalBinary", "is", "used", "to", "deserialize", "an", "Op", "from", "binary", "form", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L111-L170
test
lestrrat-go/xslate
vm/op.go
ArgInt
func (o op) ArgInt() int { v := interfaceToNumeric(o.uArg) return int(v.Int()) }
go
func (o op) ArgInt() int { v := interfaceToNumeric(o.uArg) return int(v.Int()) }
[ "func", "(", "o", "op", ")", "ArgInt", "(", ")", "int", "{", "v", ":=", "interfaceToNumeric", "(", "o", ".", "uArg", ")", "\n", "return", "int", "(", "v", ".", "Int", "(", ")", ")", "\n", "}" ]
// ArgInt returns the integer representation of the argument
[ "ArgInt", "returns", "the", "integer", "representation", "of", "the", "argument" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L192-L195
test
lestrrat-go/xslate
vm/op.go
ArgString
func (o op) ArgString() string { // In most cases we do this because it's a sring if v, ok := o.uArg.(string); ok { return v } return interfaceToString(o.uArg) }
go
func (o op) ArgString() string { // In most cases we do this because it's a sring if v, ok := o.uArg.(string); ok { return v } return interfaceToString(o.uArg) }
[ "func", "(", "o", "op", ")", "ArgString", "(", ")", "string", "{", "if", "v", ",", "ok", ":=", "o", ".", "uArg", ".", "(", "string", ")", ";", "ok", "{", "return", "v", "\n", "}", "\n", "return", "interfaceToString", "(", "o", ".", "uArg", ")", "\n", "}" ]
// ArgString returns the string representatin of the argument
[ "ArgString", "returns", "the", "string", "representatin", "of", "the", "argument" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L198-L204
test
lestrrat-go/xslate
compiler/compiler.go
AppendOp
func (ctx *context) AppendOp(o vm.OpType, args ...interface{}) vm.Op { return ctx.ByteCode.AppendOp(o, args...) }
go
func (ctx *context) AppendOp(o vm.OpType, args ...interface{}) vm.Op { return ctx.ByteCode.AppendOp(o, args...) }
[ "func", "(", "ctx", "*", "context", ")", "AppendOp", "(", "o", "vm", ".", "OpType", ",", "args", "...", "interface", "{", "}", ")", "vm", ".", "Op", "{", "return", "ctx", ".", "ByteCode", ".", "AppendOp", "(", "o", ",", "args", "...", ")", "\n", "}" ]
// AppendOp creates and appends a new op to the current set of ByteCode
[ "AppendOp", "creates", "and", "appends", "a", "new", "op", "to", "the", "current", "set", "of", "ByteCode" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/compiler/compiler.go#L13-L15
test
lestrrat-go/xslate
compiler/compiler.go
Compile
func (c *BasicCompiler) Compile(ast *parser.AST) (*vm.ByteCode, error) { ctx := &context{ ByteCode: vm.NewByteCode(), } for _, n := range ast.Root.Nodes { compile(ctx, n) } // When we're done compiling, always append an END op ctx.ByteCode.AppendOp(vm.TXOPEnd) opt := &NaiveOptimizer{} opt.Optimize(ctx.ByteCode) ctx.ByteCode.Name = ast.Name return ctx.ByteCode, nil }
go
func (c *BasicCompiler) Compile(ast *parser.AST) (*vm.ByteCode, error) { ctx := &context{ ByteCode: vm.NewByteCode(), } for _, n := range ast.Root.Nodes { compile(ctx, n) } // When we're done compiling, always append an END op ctx.ByteCode.AppendOp(vm.TXOPEnd) opt := &NaiveOptimizer{} opt.Optimize(ctx.ByteCode) ctx.ByteCode.Name = ast.Name return ctx.ByteCode, nil }
[ "func", "(", "c", "*", "BasicCompiler", ")", "Compile", "(", "ast", "*", "parser", ".", "AST", ")", "(", "*", "vm", ".", "ByteCode", ",", "error", ")", "{", "ctx", ":=", "&", "context", "{", "ByteCode", ":", "vm", ".", "NewByteCode", "(", ")", ",", "}", "\n", "for", "_", ",", "n", ":=", "range", "ast", ".", "Root", ".", "Nodes", "{", "compile", "(", "ctx", ",", "n", ")", "\n", "}", "\n", "ctx", ".", "ByteCode", ".", "AppendOp", "(", "vm", ".", "TXOPEnd", ")", "\n", "opt", ":=", "&", "NaiveOptimizer", "{", "}", "\n", "opt", ".", "Optimize", "(", "ctx", ".", "ByteCode", ")", "\n", "ctx", ".", "ByteCode", ".", "Name", "=", "ast", ".", "Name", "\n", "return", "ctx", ".", "ByteCode", ",", "nil", "\n", "}" ]
// Compile satisfies the compiler.Compiler interface. It accepts an AST // created by parser.Parser, and returns vm.ByteCode or an error
[ "Compile", "satisfies", "the", "compiler", ".", "Compiler", "interface", ".", "It", "accepts", "an", "AST", "created", "by", "parser", ".", "Parser", "and", "returns", "vm", ".", "ByteCode", "or", "an", "error" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/compiler/compiler.go#L24-L40
test
fgrid/uuid
v5.go
NewV5
func NewV5(namespaceUUID *UUID, name []byte) *UUID { uuid := newByHash(sha1.New(), namespaceUUID, name) uuid[6] = (uuid[6] & 0x0f) | 0x50 return uuid }
go
func NewV5(namespaceUUID *UUID, name []byte) *UUID { uuid := newByHash(sha1.New(), namespaceUUID, name) uuid[6] = (uuid[6] & 0x0f) | 0x50 return uuid }
[ "func", "NewV5", "(", "namespaceUUID", "*", "UUID", ",", "name", "[", "]", "byte", ")", "*", "UUID", "{", "uuid", ":=", "newByHash", "(", "sha1", ".", "New", "(", ")", ",", "namespaceUUID", ",", "name", ")", "\n", "uuid", "[", "6", "]", "=", "(", "uuid", "[", "6", "]", "&", "0x0f", ")", "|", "0x50", "\n", "return", "uuid", "\n", "}" ]
// NewV5 creates a new UUID with variant 5 as described in RFC 4122. // Variant 5 based namespace-uuid and name and SHA-1 hash calculation.
[ "NewV5", "creates", "a", "new", "UUID", "with", "variant", "5", "as", "described", "in", "RFC", "4122", ".", "Variant", "5", "based", "namespace", "-", "uuid", "and", "name", "and", "SHA", "-", "1", "hash", "calculation", "." ]
6f72a2d331c927473b9b19f590d43ccb5018c844
https://github.com/fgrid/uuid/blob/6f72a2d331c927473b9b19f590d43ccb5018c844/v5.go#L7-L11
test
lestrrat-go/xslate
parser/symbols.go
Sort
func (list LexSymbolList) Sort() LexSymbolList { sorter := LexSymbolSorter{ list: list, } sort.Sort(sorter) return sorter.list }
go
func (list LexSymbolList) Sort() LexSymbolList { sorter := LexSymbolSorter{ list: list, } sort.Sort(sorter) return sorter.list }
[ "func", "(", "list", "LexSymbolList", ")", "Sort", "(", ")", "LexSymbolList", "{", "sorter", ":=", "LexSymbolSorter", "{", "list", ":", "list", ",", "}", "\n", "sort", ".", "Sort", "(", "sorter", ")", "\n", "return", "sorter", ".", "list", "\n", "}" ]
// Sort returns a sorted list of LexSymbols, sorted by Priority
[ "Sort", "returns", "a", "sorted", "list", "of", "LexSymbols", "sorted", "by", "Priority" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L39-L45
test
lestrrat-go/xslate
parser/symbols.go
Less
func (s LexSymbolSorter) Less(i, j int) bool { return s.list[i].Priority > s.list[j].Priority }
go
func (s LexSymbolSorter) Less(i, j int) bool { return s.list[i].Priority > s.list[j].Priority }
[ "func", "(", "s", "LexSymbolSorter", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "s", ".", "list", "[", "i", "]", ".", "Priority", ">", "s", ".", "list", "[", "j", "]", ".", "Priority", "\n", "}" ]
// Less returns true if the i-th element's Priority is less than the j-th element
[ "Less", "returns", "true", "if", "the", "i", "-", "th", "element", "s", "Priority", "is", "less", "than", "the", "j", "-", "th", "element" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L53-L55
test
lestrrat-go/xslate
parser/symbols.go
Swap
func (s LexSymbolSorter) Swap(i, j int) { s.list[i], s.list[j] = s.list[j], s.list[i] }
go
func (s LexSymbolSorter) Swap(i, j int) { s.list[i], s.list[j] = s.list[j], s.list[i] }
[ "func", "(", "s", "LexSymbolSorter", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "s", ".", "list", "[", "i", "]", ",", "s", ".", "list", "[", "j", "]", "=", "s", ".", "list", "[", "j", "]", ",", "s", ".", "list", "[", "i", "]", "\n", "}" ]
// Swap swaps the elements at i and j
[ "Swap", "swaps", "the", "elements", "at", "i", "and", "j" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L58-L60
test
lestrrat-go/xslate
parser/symbols.go
Copy
func (l *LexSymbolSet) Copy() *LexSymbolSet { c := NewLexSymbolSet() for k, v := range l.Map { c.Map[k] = LexSymbol{v.Name, v.Type, v.Priority} } return c }
go
func (l *LexSymbolSet) Copy() *LexSymbolSet { c := NewLexSymbolSet() for k, v := range l.Map { c.Map[k] = LexSymbol{v.Name, v.Type, v.Priority} } return c }
[ "func", "(", "l", "*", "LexSymbolSet", ")", "Copy", "(", ")", "*", "LexSymbolSet", "{", "c", ":=", "NewLexSymbolSet", "(", ")", "\n", "for", "k", ",", "v", ":=", "range", "l", ".", "Map", "{", "c", ".", "Map", "[", "k", "]", "=", "LexSymbol", "{", "v", ".", "Name", ",", "v", ".", "Type", ",", "v", ".", "Priority", "}", "\n", "}", "\n", "return", "c", "\n", "}" ]
// Copy creates a new copy of the given LexSymbolSet
[ "Copy", "creates", "a", "new", "copy", "of", "the", "given", "LexSymbolSet" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L71-L77
test
lestrrat-go/xslate
parser/symbols.go
Set
func (l *LexSymbolSet) Set(name string, typ lex.ItemType, prio ...float32) { var x float32 if len(prio) < 1 { x = 1.0 } else { x = prio[0] } l.Map[name] = LexSymbol{name, typ, x} l.SortedList = nil // reset }
go
func (l *LexSymbolSet) Set(name string, typ lex.ItemType, prio ...float32) { var x float32 if len(prio) < 1 { x = 1.0 } else { x = prio[0] } l.Map[name] = LexSymbol{name, typ, x} l.SortedList = nil // reset }
[ "func", "(", "l", "*", "LexSymbolSet", ")", "Set", "(", "name", "string", ",", "typ", "lex", ".", "ItemType", ",", "prio", "...", "float32", ")", "{", "var", "x", "float32", "\n", "if", "len", "(", "prio", ")", "<", "1", "{", "x", "=", "1.0", "\n", "}", "else", "{", "x", "=", "prio", "[", "0", "]", "\n", "}", "\n", "l", ".", "Map", "[", "name", "]", "=", "LexSymbol", "{", "name", ",", "typ", ",", "x", "}", "\n", "l", ".", "SortedList", "=", "nil", "\n", "}" ]
// Set creates and sets a new LexItem to `name`
[ "Set", "creates", "and", "sets", "a", "new", "LexItem", "to", "name" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L90-L99
test
lestrrat-go/xslate
parser/symbols.go
GetSortedList
func (l *LexSymbolSet) GetSortedList() LexSymbolList { // Because symbols are parsed automatically in a loop, we need to make // sure that we search starting with the longest term (e.g., "INCLUDE" // must come before "IN") // However, simply sorting the symbols using alphabetical sort then // max-length forces us to make more comparisons than necessary. // To get the best of both world, we allow passing a floating point // "priority" parameter to sort the symbols if l.SortedList != nil { return l.SortedList } num := len(l.Map) list := make(LexSymbolList, num) i := 0 for _, v := range l.Map { list[i] = v i++ } l.SortedList = list.Sort() return l.SortedList }
go
func (l *LexSymbolSet) GetSortedList() LexSymbolList { // Because symbols are parsed automatically in a loop, we need to make // sure that we search starting with the longest term (e.g., "INCLUDE" // must come before "IN") // However, simply sorting the symbols using alphabetical sort then // max-length forces us to make more comparisons than necessary. // To get the best of both world, we allow passing a floating point // "priority" parameter to sort the symbols if l.SortedList != nil { return l.SortedList } num := len(l.Map) list := make(LexSymbolList, num) i := 0 for _, v := range l.Map { list[i] = v i++ } l.SortedList = list.Sort() return l.SortedList }
[ "func", "(", "l", "*", "LexSymbolSet", ")", "GetSortedList", "(", ")", "LexSymbolList", "{", "if", "l", ".", "SortedList", "!=", "nil", "{", "return", "l", ".", "SortedList", "\n", "}", "\n", "num", ":=", "len", "(", "l", ".", "Map", ")", "\n", "list", ":=", "make", "(", "LexSymbolList", ",", "num", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "v", ":=", "range", "l", ".", "Map", "{", "list", "[", "i", "]", "=", "v", "\n", "i", "++", "\n", "}", "\n", "l", ".", "SortedList", "=", "list", ".", "Sort", "(", ")", "\n", "return", "l", ".", "SortedList", "\n", "}" ]
// GetSortedList returns the lsit of LexSymbols in order that they should // be searched for in the tempalte
[ "GetSortedList", "returns", "the", "lsit", "of", "LexSymbols", "in", "order", "that", "they", "should", "be", "searched", "for", "in", "the", "tempalte" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L103-L125
test
lestrrat-go/xslate
internal/stack/stack.go
Top
func (s *Stack) Top() (interface{}, error) { if len(*s) == 0 { return nil, errors.New("nothing on stack") } return (*s)[len(*s)-1], nil }
go
func (s *Stack) Top() (interface{}, error) { if len(*s) == 0 { return nil, errors.New("nothing on stack") } return (*s)[len(*s)-1], nil }
[ "func", "(", "s", "*", "Stack", ")", "Top", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "len", "(", "*", "s", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"nothing on stack\"", ")", "\n", "}", "\n", "return", "(", "*", "s", ")", "[", "len", "(", "*", "s", ")", "-", "1", "]", ",", "nil", "\n", "}" ]
// Top returns the element at the top of the stack or an error if stack is empty
[ "Top", "returns", "the", "element", "at", "the", "top", "of", "the", "stack", "or", "an", "error", "if", "stack", "is", "empty" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L32-L37
test
lestrrat-go/xslate
internal/stack/stack.go
Resize
func (s *Stack) Resize(size int) { newl := make([]interface{}, len(*s), size) copy(newl, *s) *s = newl }
go
func (s *Stack) Resize(size int) { newl := make([]interface{}, len(*s), size) copy(newl, *s) *s = newl }
[ "func", "(", "s", "*", "Stack", ")", "Resize", "(", "size", "int", ")", "{", "newl", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "*", "s", ")", ",", "size", ")", "\n", "copy", "(", "newl", ",", "*", "s", ")", "\n", "*", "s", "=", "newl", "\n", "}" ]
// Resize changes the size of the underlying buffer
[ "Resize", "changes", "the", "size", "of", "the", "underlying", "buffer" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L50-L54
test
lestrrat-go/xslate
internal/stack/stack.go
Extend
func (s *Stack) Extend(extendBy int) { s.Resize(s.Size() + extendBy) }
go
func (s *Stack) Extend(extendBy int) { s.Resize(s.Size() + extendBy) }
[ "func", "(", "s", "*", "Stack", ")", "Extend", "(", "extendBy", "int", ")", "{", "s", ".", "Resize", "(", "s", ".", "Size", "(", ")", "+", "extendBy", ")", "\n", "}" ]
// Extend changes the size of the underlying buffer, extending it by `extendBy`
[ "Extend", "changes", "the", "size", "of", "the", "underlying", "buffer", "extending", "it", "by", "extendBy" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L57-L59
test
lestrrat-go/xslate
internal/stack/stack.go
Grow
func (s *Stack) Grow(min int) { // Automatically grow the stack to some long-enough length if min <= s.BufferSize() { // we have enough return } s.Resize(calcNewSize(min)) }
go
func (s *Stack) Grow(min int) { // Automatically grow the stack to some long-enough length if min <= s.BufferSize() { // we have enough return } s.Resize(calcNewSize(min)) }
[ "func", "(", "s", "*", "Stack", ")", "Grow", "(", "min", "int", ")", "{", "if", "min", "<=", "s", ".", "BufferSize", "(", ")", "{", "return", "\n", "}", "\n", "s", ".", "Resize", "(", "calcNewSize", "(", "min", ")", ")", "\n", "}" ]
// Grow automatically grows the underlying buffer so that it can hold at // least `min` elements
[ "Grow", "automatically", "grows", "the", "underlying", "buffer", "so", "that", "it", "can", "hold", "at", "least", "min", "elements" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L63-L71
test
lestrrat-go/xslate
internal/stack/stack.go
Get
func (s *Stack) Get(i int) (interface{}, error) { if i < 0 || i >= len(*s) { return nil, errors.New(strconv.Itoa(i) + " is out of range") } return (*s)[i], nil }
go
func (s *Stack) Get(i int) (interface{}, error) { if i < 0 || i >= len(*s) { return nil, errors.New(strconv.Itoa(i) + " is out of range") } return (*s)[i], nil }
[ "func", "(", "s", "*", "Stack", ")", "Get", "(", "i", "int", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "i", "<", "0", "||", "i", ">=", "len", "(", "*", "s", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "strconv", ".", "Itoa", "(", "i", ")", "+", "\" is out of range\"", ")", "\n", "}", "\n", "return", "(", "*", "s", ")", "[", "i", "]", ",", "nil", "\n", "}" ]
// Get returns the element at position `i`
[ "Get", "returns", "the", "element", "at", "position", "i" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L74-L80
test
lestrrat-go/xslate
internal/stack/stack.go
Set
func (s *Stack) Set(i int, v interface{}) error { if i < 0 { return errors.New("invalid index into stack") } if i >= s.BufferSize() { s.Resize(calcNewSize(i)) } for len(*s) < i + 1 { *s = append(*s, nil) } (*s)[i] = v return nil }
go
func (s *Stack) Set(i int, v interface{}) error { if i < 0 { return errors.New("invalid index into stack") } if i >= s.BufferSize() { s.Resize(calcNewSize(i)) } for len(*s) < i + 1 { *s = append(*s, nil) } (*s)[i] = v return nil }
[ "func", "(", "s", "*", "Stack", ")", "Set", "(", "i", "int", ",", "v", "interface", "{", "}", ")", "error", "{", "if", "i", "<", "0", "{", "return", "errors", ".", "New", "(", "\"invalid index into stack\"", ")", "\n", "}", "\n", "if", "i", ">=", "s", ".", "BufferSize", "(", ")", "{", "s", ".", "Resize", "(", "calcNewSize", "(", "i", ")", ")", "\n", "}", "\n", "for", "len", "(", "*", "s", ")", "<", "i", "+", "1", "{", "*", "s", "=", "append", "(", "*", "s", ",", "nil", ")", "\n", "}", "\n", "(", "*", "s", ")", "[", "i", "]", "=", "v", "\n", "return", "nil", "\n", "}" ]
// Set sets the element at position `i` to `v`. The stack size is automatically // adjusted.
[ "Set", "sets", "the", "element", "at", "position", "i", "to", "v", ".", "The", "stack", "size", "is", "automatically", "adjusted", "." ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L84-L99
test
lestrrat-go/xslate
internal/stack/stack.go
Push
func (s *Stack) Push(v interface{}) { if len(*s) >= s.BufferSize() { s.Resize(calcNewSize(cap(*s))) } *s = append(*s, v) }
go
func (s *Stack) Push(v interface{}) { if len(*s) >= s.BufferSize() { s.Resize(calcNewSize(cap(*s))) } *s = append(*s, v) }
[ "func", "(", "s", "*", "Stack", ")", "Push", "(", "v", "interface", "{", "}", ")", "{", "if", "len", "(", "*", "s", ")", ">=", "s", ".", "BufferSize", "(", ")", "{", "s", ".", "Resize", "(", "calcNewSize", "(", "cap", "(", "*", "s", ")", ")", ")", "\n", "}", "\n", "*", "s", "=", "append", "(", "*", "s", ",", "v", ")", "\n", "}" ]
// Push adds an element at the end of the stack
[ "Push", "adds", "an", "element", "at", "the", "end", "of", "the", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L102-L108
test
lestrrat-go/xslate
internal/stack/stack.go
Pop
func (s *Stack) Pop() interface{} { l := len(*s) if l == 0 { return nil } v := (*s)[l-1] *s = (*s)[:l-1] return v }
go
func (s *Stack) Pop() interface{} { l := len(*s) if l == 0 { return nil } v := (*s)[l-1] *s = (*s)[:l-1] return v }
[ "func", "(", "s", "*", "Stack", ")", "Pop", "(", ")", "interface", "{", "}", "{", "l", ":=", "len", "(", "*", "s", ")", "\n", "if", "l", "==", "0", "{", "return", "nil", "\n", "}", "\n", "v", ":=", "(", "*", "s", ")", "[", "l", "-", "1", "]", "\n", "*", "s", "=", "(", "*", "s", ")", "[", ":", "l", "-", "1", "]", "\n", "return", "v", "\n", "}" ]
// Pop removes and returns the item at the end of the stack
[ "Pop", "removes", "and", "returns", "the", "item", "at", "the", "end", "of", "the", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L111-L120
test
lestrrat-go/xslate
internal/stack/stack.go
String
func (s *Stack) String() string { buf := bytes.Buffer{} for k, v := range *s { fmt.Fprintf(&buf, "%03d: %q\n", k, v) } return buf.String() }
go
func (s *Stack) String() string { buf := bytes.Buffer{} for k, v := range *s { fmt.Fprintf(&buf, "%03d: %q\n", k, v) } return buf.String() }
[ "func", "(", "s", "*", "Stack", ")", "String", "(", ")", "string", "{", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "*", "s", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"%03d: %q\\n\"", ",", "\\n", ",", "k", ")", "\n", "}", "\n", "v", "\n", "}" ]
// String returns the textual representation of the stack
[ "String", "returns", "the", "textual", "representation", "of", "the", "stack" ]
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L123-L129
test
mailgun/iptools
ip.go
GetHostIPs
func GetHostIPs() ([]net.IP, error) { ifaces, err := net.Interfaces() if err != nil { return nil, err } var ips []net.IP for _, iface := range ifaces { if strings.HasPrefix(iface.Name, "docker") { continue } addrs, err := iface.Addrs() if err != nil { continue } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok { ips = append(ips, ipnet.IP) } } } return ips, nil }
go
func GetHostIPs() ([]net.IP, error) { ifaces, err := net.Interfaces() if err != nil { return nil, err } var ips []net.IP for _, iface := range ifaces { if strings.HasPrefix(iface.Name, "docker") { continue } addrs, err := iface.Addrs() if err != nil { continue } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok { ips = append(ips, ipnet.IP) } } } return ips, nil }
[ "func", "GetHostIPs", "(", ")", "(", "[", "]", "net", ".", "IP", ",", "error", ")", "{", "ifaces", ",", "err", ":=", "net", ".", "Interfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "ips", "[", "]", "net", ".", "IP", "\n", "for", "_", ",", "iface", ":=", "range", "ifaces", "{", "if", "strings", ".", "HasPrefix", "(", "iface", ".", "Name", ",", "\"docker\"", ")", "{", "continue", "\n", "}", "\n", "addrs", ",", "err", ":=", "iface", ".", "Addrs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "if", "ipnet", ",", "ok", ":=", "addr", ".", "(", "*", "net", ".", "IPNet", ")", ";", "ok", "{", "ips", "=", "append", "(", "ips", ",", "ipnet", ".", "IP", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ips", ",", "nil", "\n", "}" ]
// GetHostIPs returns a list of IP addresses of all host's interfaces.
[ "GetHostIPs", "returns", "a", "list", "of", "IP", "addresses", "of", "all", "host", "s", "interfaces", "." ]
ba8d5743f6788db9906c07c292a033f194849563
https://github.com/mailgun/iptools/blob/ba8d5743f6788db9906c07c292a033f194849563/ip.go#L32-L55
test
mailgun/iptools
ip.go
GetPrivateHostIPs
func GetPrivateHostIPs() ([]net.IP, error) { ips, err := GetHostIPs() if err != nil { return nil, err } var privateIPs []net.IP for _, ip := range ips { // skip loopback, non-IPv4 and non-private addresses if ip.IsLoopback() || ip.To4() == nil || !IsPrivate(ip) { continue } privateIPs = append(privateIPs, ip) } return privateIPs, nil }
go
func GetPrivateHostIPs() ([]net.IP, error) { ips, err := GetHostIPs() if err != nil { return nil, err } var privateIPs []net.IP for _, ip := range ips { // skip loopback, non-IPv4 and non-private addresses if ip.IsLoopback() || ip.To4() == nil || !IsPrivate(ip) { continue } privateIPs = append(privateIPs, ip) } return privateIPs, nil }
[ "func", "GetPrivateHostIPs", "(", ")", "(", "[", "]", "net", ".", "IP", ",", "error", ")", "{", "ips", ",", "err", ":=", "GetHostIPs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "privateIPs", "[", "]", "net", ".", "IP", "\n", "for", "_", ",", "ip", ":=", "range", "ips", "{", "if", "ip", ".", "IsLoopback", "(", ")", "||", "ip", ".", "To4", "(", ")", "==", "nil", "||", "!", "IsPrivate", "(", "ip", ")", "{", "continue", "\n", "}", "\n", "privateIPs", "=", "append", "(", "privateIPs", ",", "ip", ")", "\n", "}", "\n", "return", "privateIPs", ",", "nil", "\n", "}" ]
// GetPrivateHostIPs returns a list of host's private IP addresses.
[ "GetPrivateHostIPs", "returns", "a", "list", "of", "host", "s", "private", "IP", "addresses", "." ]
ba8d5743f6788db9906c07c292a033f194849563
https://github.com/mailgun/iptools/blob/ba8d5743f6788db9906c07c292a033f194849563/ip.go#L58-L74
test
mailgun/iptools
ip.go
IsPrivate
func IsPrivate(ip net.IP) bool { for _, ipnet := range privateNets { if ipnet.Contains(ip) { return true } } return false }
go
func IsPrivate(ip net.IP) bool { for _, ipnet := range privateNets { if ipnet.Contains(ip) { return true } } return false }
[ "func", "IsPrivate", "(", "ip", "net", ".", "IP", ")", "bool", "{", "for", "_", ",", "ipnet", ":=", "range", "privateNets", "{", "if", "ipnet", ".", "Contains", "(", "ip", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsPrivate determines whether a passed IP address is from one of private blocks or not.
[ "IsPrivate", "determines", "whether", "a", "passed", "IP", "address", "is", "from", "one", "of", "private", "blocks", "or", "not", "." ]
ba8d5743f6788db9906c07c292a033f194849563
https://github.com/mailgun/iptools/blob/ba8d5743f6788db9906c07c292a033f194849563/ip.go#L77-L84
test
danott/envflag
envflag.go
Environ
func Environ() []string { s := make([]string, 0) FlagSet.VisitAll(func(f *flag.Flag) { if value, ok := getenv(f.Name); ok { s = append(s, flagAsEnv(f.Name)+"="+value) } }) return s }
go
func Environ() []string { s := make([]string, 0) FlagSet.VisitAll(func(f *flag.Flag) { if value, ok := getenv(f.Name); ok { s = append(s, flagAsEnv(f.Name)+"="+value) } }) return s }
[ "func", "Environ", "(", ")", "[", "]", "string", "{", "s", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "FlagSet", ".", "VisitAll", "(", "func", "(", "f", "*", "flag", ".", "Flag", ")", "{", "if", "value", ",", "ok", ":=", "getenv", "(", "f", ".", "Name", ")", ";", "ok", "{", "s", "=", "append", "(", "s", ",", "flagAsEnv", "(", "f", ".", "Name", ")", "+", "\"=\"", "+", "value", ")", "\n", "}", "\n", "}", ")", "\n", "return", "s", "\n", "}" ]
// Identical to os.Environ, but limited to the environment variable equivalents // for the flags your program cares about.
[ "Identical", "to", "os", ".", "Environ", "but", "limited", "to", "the", "environment", "variable", "equivalents", "for", "the", "flags", "your", "program", "cares", "about", "." ]
14c5f9aaa227ddb49f3206fe06432edfc27735a5
https://github.com/danott/envflag/blob/14c5f9aaa227ddb49f3206fe06432edfc27735a5/envflag.go#L59-L69
test
danott/envflag
envflag.go
getenv
func getenv(name string) (s string, ok bool) { m := make(map[string]bool) for _, keyVal := range os.Environ() { split := strings.Split(keyVal, "=") m[split[0]] = true } name = flagAsEnv(name) if _, ok = m[name]; ok { s = os.Getenv(name) } return }
go
func getenv(name string) (s string, ok bool) { m := make(map[string]bool) for _, keyVal := range os.Environ() { split := strings.Split(keyVal, "=") m[split[0]] = true } name = flagAsEnv(name) if _, ok = m[name]; ok { s = os.Getenv(name) } return }
[ "func", "getenv", "(", "name", "string", ")", "(", "s", "string", ",", "ok", "bool", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "keyVal", ":=", "range", "os", ".", "Environ", "(", ")", "{", "split", ":=", "strings", ".", "Split", "(", "keyVal", ",", "\"=\"", ")", "\n", "m", "[", "split", "[", "0", "]", "]", "=", "true", "\n", "}", "\n", "name", "=", "flagAsEnv", "(", "name", ")", "\n", "if", "_", ",", "ok", "=", "m", "[", "name", "]", ";", "ok", "{", "s", "=", "os", ".", "Getenv", "(", "name", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Just like os.Getenv, but with a second return value; a boolean specifying // if name was actually set in the environment.
[ "Just", "like", "os", ".", "Getenv", "but", "with", "a", "second", "return", "value", ";", "a", "boolean", "specifying", "if", "name", "was", "actually", "set", "in", "the", "environment", "." ]
14c5f9aaa227ddb49f3206fe06432edfc27735a5
https://github.com/danott/envflag/blob/14c5f9aaa227ddb49f3206fe06432edfc27735a5/envflag.go#L96-L110
test
danott/envflag
envflag.go
flagAsEnv
func flagAsEnv(name string) string { name = strings.ToUpper(EnvPrefix + name) name = strings.Replace(name, ".", "_", -1) name = strings.Replace(name, "-", "_", -1) return name }
go
func flagAsEnv(name string) string { name = strings.ToUpper(EnvPrefix + name) name = strings.Replace(name, ".", "_", -1) name = strings.Replace(name, "-", "_", -1) return name }
[ "func", "flagAsEnv", "(", "name", "string", ")", "string", "{", "name", "=", "strings", ".", "ToUpper", "(", "EnvPrefix", "+", "name", ")", "\n", "name", "=", "strings", ".", "Replace", "(", "name", ",", "\".\"", ",", "\"_\"", ",", "-", "1", ")", "\n", "name", "=", "strings", ".", "Replace", "(", "name", ",", "\"-\"", ",", "\"_\"", ",", "-", "1", ")", "\n", "return", "name", "\n", "}" ]
// To be unix'y, we translate flagnames to their uppercase equivalents.
[ "To", "be", "unix", "y", "we", "translate", "flagnames", "to", "their", "uppercase", "equivalents", "." ]
14c5f9aaa227ddb49f3206fe06432edfc27735a5
https://github.com/danott/envflag/blob/14c5f9aaa227ddb49f3206fe06432edfc27735a5/envflag.go#L113-L118
test
sayanarijit/gopassgen
gopassgen.go
NewPolicy
func NewPolicy() Policy { p := Policy{ MinLength: 6, MaxLength: 16, MinLowers: 0, MinUppers: 0, MinDigits: 0, MinSpclChars: 0, LowerPool: "abcdefghijklmnopqrstuvwxyz", UpperPool: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", DigitPool: "0123456789", SpclCharPool: "!@#$%^&*()-_=+,.?/:;{}[]~", } return p }
go
func NewPolicy() Policy { p := Policy{ MinLength: 6, MaxLength: 16, MinLowers: 0, MinUppers: 0, MinDigits: 0, MinSpclChars: 0, LowerPool: "abcdefghijklmnopqrstuvwxyz", UpperPool: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", DigitPool: "0123456789", SpclCharPool: "!@#$%^&*()-_=+,.?/:;{}[]~", } return p }
[ "func", "NewPolicy", "(", ")", "Policy", "{", "p", ":=", "Policy", "{", "MinLength", ":", "6", ",", "MaxLength", ":", "16", ",", "MinLowers", ":", "0", ",", "MinUppers", ":", "0", ",", "MinDigits", ":", "0", ",", "MinSpclChars", ":", "0", ",", "LowerPool", ":", "\"abcdefghijklmnopqrstuvwxyz\"", ",", "UpperPool", ":", "\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ",", "DigitPool", ":", "\"0123456789\"", ",", "SpclCharPool", ":", "\"!@#$%^&*()-_=+,.?/:;{}[]~\"", ",", "}", "\n", "return", "p", "\n", "}" ]
// NewPolicy returns a default password policy which can be modified
[ "NewPolicy", "returns", "a", "default", "password", "policy", "which", "can", "be", "modified" ]
cf555de90ad6031f567a55be7d7c90f2fbe8389a
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L49-L63
test
sayanarijit/gopassgen
gopassgen.go
CreateRandom
func CreateRandom(bs []byte, length int) []byte { filled := make([]byte, length) max := len(bs) for i := 0; i < length; i++ { Shuffle(bs) filled[i] = bs[random(0, max)] } return filled }
go
func CreateRandom(bs []byte, length int) []byte { filled := make([]byte, length) max := len(bs) for i := 0; i < length; i++ { Shuffle(bs) filled[i] = bs[random(0, max)] } return filled }
[ "func", "CreateRandom", "(", "bs", "[", "]", "byte", ",", "length", "int", ")", "[", "]", "byte", "{", "filled", ":=", "make", "(", "[", "]", "byte", ",", "length", ")", "\n", "max", ":=", "len", "(", "bs", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "length", ";", "i", "++", "{", "Shuffle", "(", "bs", ")", "\n", "filled", "[", "i", "]", "=", "bs", "[", "random", "(", "0", ",", "max", ")", "]", "\n", "}", "\n", "return", "filled", "\n", "}" ]
// CreateRandom returns a random byte string of given length from given byte string
[ "CreateRandom", "returns", "a", "random", "byte", "string", "of", "given", "length", "from", "given", "byte", "string" ]
cf555de90ad6031f567a55be7d7c90f2fbe8389a
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L74-L84
test
sayanarijit/gopassgen
gopassgen.go
Shuffle
func Shuffle(bs []byte) { n := len(bs) for i := n - 1; i > 0; i-- { rand.Seed(time.Now().UnixNano()) j := rand.Intn(i + 1) bs[i], bs[j] = bs[j], bs[i] } }
go
func Shuffle(bs []byte) { n := len(bs) for i := n - 1; i > 0; i-- { rand.Seed(time.Now().UnixNano()) j := rand.Intn(i + 1) bs[i], bs[j] = bs[j], bs[i] } }
[ "func", "Shuffle", "(", "bs", "[", "]", "byte", ")", "{", "n", ":=", "len", "(", "bs", ")", "\n", "for", "i", ":=", "n", "-", "1", ";", "i", ">", "0", ";", "i", "--", "{", "rand", ".", "Seed", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "j", ":=", "rand", ".", "Intn", "(", "i", "+", "1", ")", "\n", "bs", "[", "i", "]", ",", "bs", "[", "j", "]", "=", "bs", "[", "j", "]", ",", "bs", "[", "i", "]", "\n", "}", "\n", "}" ]
// Shuffle the given byte string
[ "Shuffle", "the", "given", "byte", "string" ]
cf555de90ad6031f567a55be7d7c90f2fbe8389a
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L87-L94
test
sayanarijit/gopassgen
gopassgen.go
Generate
func Generate(p Policy) (string, error) { // Character length based policies should not be negative if p.MinLength < 0 || p.MaxLength < 0 || p.MinUppers < 0 || p.MinLowers < 0 || p.MinDigits < 0 || p.MinSpclChars < 0 { return "", ErrNegativeLengthNotAllowed } collectiveMinLength := p.MinUppers + p.MinLowers + p.MinDigits + p.MinSpclChars // Min length is the collective min length if collectiveMinLength > p.MinLength { p.MinLength = collectiveMinLength } // Max length should be greater than collective minimun length if p.MinLength > p.MaxLength { return "", ErrMaxLengthExceeded } if p.MaxLength == 0 { return "", nil } capsAlpha := []byte(p.UpperPool) smallAlpha := []byte(p.LowerPool) digits := []byte(p.DigitPool) spclChars := []byte(p.SpclCharPool) allChars := []byte(p.UpperPool + p.LowerPool + p.DigitPool + p.SpclCharPool) passwd := CreateRandom(capsAlpha, p.MinUppers) passwd = append(passwd, CreateRandom(smallAlpha, p.MinLowers)...) passwd = append(passwd, CreateRandom(digits, p.MinDigits)...) passwd = append(passwd, CreateRandom(spclChars, p.MinSpclChars)...) passLen := len(passwd) if passLen < p.MaxLength { randLength := random(p.MinLength, p.MaxLength) passwd = append(passwd, CreateRandom(allChars, randLength-passLen)...) } Shuffle(passwd) return string(passwd), nil }
go
func Generate(p Policy) (string, error) { // Character length based policies should not be negative if p.MinLength < 0 || p.MaxLength < 0 || p.MinUppers < 0 || p.MinLowers < 0 || p.MinDigits < 0 || p.MinSpclChars < 0 { return "", ErrNegativeLengthNotAllowed } collectiveMinLength := p.MinUppers + p.MinLowers + p.MinDigits + p.MinSpclChars // Min length is the collective min length if collectiveMinLength > p.MinLength { p.MinLength = collectiveMinLength } // Max length should be greater than collective minimun length if p.MinLength > p.MaxLength { return "", ErrMaxLengthExceeded } if p.MaxLength == 0 { return "", nil } capsAlpha := []byte(p.UpperPool) smallAlpha := []byte(p.LowerPool) digits := []byte(p.DigitPool) spclChars := []byte(p.SpclCharPool) allChars := []byte(p.UpperPool + p.LowerPool + p.DigitPool + p.SpclCharPool) passwd := CreateRandom(capsAlpha, p.MinUppers) passwd = append(passwd, CreateRandom(smallAlpha, p.MinLowers)...) passwd = append(passwd, CreateRandom(digits, p.MinDigits)...) passwd = append(passwd, CreateRandom(spclChars, p.MinSpclChars)...) passLen := len(passwd) if passLen < p.MaxLength { randLength := random(p.MinLength, p.MaxLength) passwd = append(passwd, CreateRandom(allChars, randLength-passLen)...) } Shuffle(passwd) return string(passwd), nil }
[ "func", "Generate", "(", "p", "Policy", ")", "(", "string", ",", "error", ")", "{", "if", "p", ".", "MinLength", "<", "0", "||", "p", ".", "MaxLength", "<", "0", "||", "p", ".", "MinUppers", "<", "0", "||", "p", ".", "MinLowers", "<", "0", "||", "p", ".", "MinDigits", "<", "0", "||", "p", ".", "MinSpclChars", "<", "0", "{", "return", "\"\"", ",", "ErrNegativeLengthNotAllowed", "\n", "}", "\n", "collectiveMinLength", ":=", "p", ".", "MinUppers", "+", "p", ".", "MinLowers", "+", "p", ".", "MinDigits", "+", "p", ".", "MinSpclChars", "\n", "if", "collectiveMinLength", ">", "p", ".", "MinLength", "{", "p", ".", "MinLength", "=", "collectiveMinLength", "\n", "}", "\n", "if", "p", ".", "MinLength", ">", "p", ".", "MaxLength", "{", "return", "\"\"", ",", "ErrMaxLengthExceeded", "\n", "}", "\n", "if", "p", ".", "MaxLength", "==", "0", "{", "return", "\"\"", ",", "nil", "\n", "}", "\n", "capsAlpha", ":=", "[", "]", "byte", "(", "p", ".", "UpperPool", ")", "\n", "smallAlpha", ":=", "[", "]", "byte", "(", "p", ".", "LowerPool", ")", "\n", "digits", ":=", "[", "]", "byte", "(", "p", ".", "DigitPool", ")", "\n", "spclChars", ":=", "[", "]", "byte", "(", "p", ".", "SpclCharPool", ")", "\n", "allChars", ":=", "[", "]", "byte", "(", "p", ".", "UpperPool", "+", "p", ".", "LowerPool", "+", "p", ".", "DigitPool", "+", "p", ".", "SpclCharPool", ")", "\n", "passwd", ":=", "CreateRandom", "(", "capsAlpha", ",", "p", ".", "MinUppers", ")", "\n", "passwd", "=", "append", "(", "passwd", ",", "CreateRandom", "(", "smallAlpha", ",", "p", ".", "MinLowers", ")", "...", ")", "\n", "passwd", "=", "append", "(", "passwd", ",", "CreateRandom", "(", "digits", ",", "p", ".", "MinDigits", ")", "...", ")", "\n", "passwd", "=", "append", "(", "passwd", ",", "CreateRandom", "(", "spclChars", ",", "p", ".", "MinSpclChars", ")", "...", ")", "\n", "passLen", ":=", "len", "(", "passwd", ")", "\n", "if", "passLen", "<", "p", ".", "MaxLength", "{", "randLength", ":=", "random", "(", "p", ".", "MinLength", ",", "p", ".", "MaxLength", ")", "\n", "passwd", "=", "append", "(", "passwd", ",", "CreateRandom", "(", "allChars", ",", "randLength", "-", "passLen", ")", "...", ")", "\n", "}", "\n", "Shuffle", "(", "passwd", ")", "\n", "return", "string", "(", "passwd", ")", ",", "nil", "\n", "}" ]
// Generate a new password based on given policy
[ "Generate", "a", "new", "password", "based", "on", "given", "policy" ]
cf555de90ad6031f567a55be7d7c90f2fbe8389a
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L97-L143
test
mitchellh/osext
osext.go
ExecutableFolder
func ExecutableFolder() (string, error) { p, err := Executable() if err != nil { return "", err } folder, _ := filepath.Split(p) return folder, nil }
go
func ExecutableFolder() (string, error) { p, err := Executable() if err != nil { return "", err } folder, _ := filepath.Split(p) return folder, nil }
[ "func", "ExecutableFolder", "(", ")", "(", "string", ",", "error", ")", "{", "p", ",", "err", ":=", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "folder", ",", "_", ":=", "filepath", ".", "Split", "(", "p", ")", "\n", "return", "folder", ",", "nil", "\n", "}" ]
// Returns same path as Executable, returns just the folder // path. Excludes the executable name.
[ "Returns", "same", "path", "as", "Executable", "returns", "just", "the", "folder", "path", ".", "Excludes", "the", "executable", "name", "." ]
5e2d6d41470f99c881826dedd8c526728b783c9c
https://github.com/mitchellh/osext/blob/5e2d6d41470f99c881826dedd8c526728b783c9c/osext.go#L20-L27
test
brankas/sentinel
opts.go
Ignore
func Ignore(ignore ...func(error) bool) Option { return func(s *Sentinel) error { s.Lock() defer s.Unlock() if s.started { return ErrAlreadyStarted } s.ignoreErrors = append(s.ignoreErrors, ignore...) return nil } }
go
func Ignore(ignore ...func(error) bool) Option { return func(s *Sentinel) error { s.Lock() defer s.Unlock() if s.started { return ErrAlreadyStarted } s.ignoreErrors = append(s.ignoreErrors, ignore...) return nil } }
[ "func", "Ignore", "(", "ignore", "...", "func", "(", "error", ")", "bool", ")", "Option", "{", "return", "func", "(", "s", "*", "Sentinel", ")", "error", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "started", "{", "return", "ErrAlreadyStarted", "\n", "}", "\n", "s", ".", "ignoreErrors", "=", "append", "(", "s", ".", "ignoreErrors", ",", "ignore", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Ignore is a sentinel option to add ignore error handlers.
[ "Ignore", "is", "a", "sentinel", "option", "to", "add", "ignore", "error", "handlers", "." ]
0ff081867c31a45cb71f5976ea6144fd06a557b5
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L68-L80
test
brankas/sentinel
opts.go
Sigs
func Sigs(sigs ...os.Signal) Option { return func(s *Sentinel) error { s.Lock() defer s.Unlock() if s.started { return ErrAlreadyStarted } s.shutdownSigs = sigs return nil } }
go
func Sigs(sigs ...os.Signal) Option { return func(s *Sentinel) error { s.Lock() defer s.Unlock() if s.started { return ErrAlreadyStarted } s.shutdownSigs = sigs return nil } }
[ "func", "Sigs", "(", "sigs", "...", "os", ".", "Signal", ")", "Option", "{", "return", "func", "(", "s", "*", "Sentinel", ")", "error", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "started", "{", "return", "ErrAlreadyStarted", "\n", "}", "\n", "s", ".", "shutdownSigs", "=", "sigs", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Sigs is a sentinel option to set the specified signals for shutdown.
[ "Sigs", "is", "a", "sentinel", "option", "to", "set", "the", "specified", "signals", "for", "shutdown", "." ]
0ff081867c31a45cb71f5976ea6144fd06a557b5
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L83-L95
test
brankas/sentinel
opts.go
Logf
func Logf(f func(string, ...interface{})) Option { return func(s *Sentinel) error { s.logf = f return nil } }
go
func Logf(f func(string, ...interface{})) Option { return func(s *Sentinel) error { s.logf = f return nil } }
[ "func", "Logf", "(", "f", "func", "(", "string", ",", "...", "interface", "{", "}", ")", ")", "Option", "{", "return", "func", "(", "s", "*", "Sentinel", ")", "error", "{", "s", ".", "logf", "=", "f", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Logf is a sentinel option to set a logger.
[ "Logf", "is", "a", "sentinel", "option", "to", "set", "a", "logger", "." ]
0ff081867c31a45cb71f5976ea6144fd06a557b5
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L98-L103
test
brankas/sentinel
opts.go
Errorf
func Errorf(f func(string, ...interface{})) Option { return func(s *Sentinel) error { s.errf = f return nil } }
go
func Errorf(f func(string, ...interface{})) Option { return func(s *Sentinel) error { s.errf = f return nil } }
[ "func", "Errorf", "(", "f", "func", "(", "string", ",", "...", "interface", "{", "}", ")", ")", "Option", "{", "return", "func", "(", "s", "*", "Sentinel", ")", "error", "{", "s", ".", "errf", "=", "f", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Errorf is a sentinel option to set a error logger.
[ "Errorf", "is", "a", "sentinel", "option", "to", "set", "a", "error", "logger", "." ]
0ff081867c31a45cb71f5976ea6144fd06a557b5
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L106-L111
test
brankas/sentinel
sentinel.go
New
func New(opts ...Option) (*Sentinel, error) { s := &Sentinel{ shutdownDuration: DefaultShutdownDuration, logf: func(string, ...interface{}) {}, } var err error // apply options for _, o := range opts { if err = o(s); err != nil { return nil, err } } // ensure sigs set if s.shutdownSigs == nil { s.shutdownSigs = []os.Signal{os.Interrupt} } // ensure errf set if s.errf == nil { s.errf = func(str string, v ...interface{}) { s.logf("ERROR: "+str, v...) } } return s, nil }
go
func New(opts ...Option) (*Sentinel, error) { s := &Sentinel{ shutdownDuration: DefaultShutdownDuration, logf: func(string, ...interface{}) {}, } var err error // apply options for _, o := range opts { if err = o(s); err != nil { return nil, err } } // ensure sigs set if s.shutdownSigs == nil { s.shutdownSigs = []os.Signal{os.Interrupt} } // ensure errf set if s.errf == nil { s.errf = func(str string, v ...interface{}) { s.logf("ERROR: "+str, v...) } } return s, nil }
[ "func", "New", "(", "opts", "...", "Option", ")", "(", "*", "Sentinel", ",", "error", ")", "{", "s", ":=", "&", "Sentinel", "{", "shutdownDuration", ":", "DefaultShutdownDuration", ",", "logf", ":", "func", "(", "string", ",", "...", "interface", "{", "}", ")", "{", "}", ",", "}", "\n", "var", "err", "error", "\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "if", "err", "=", "o", "(", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "s", ".", "shutdownSigs", "==", "nil", "{", "s", ".", "shutdownSigs", "=", "[", "]", "os", ".", "Signal", "{", "os", ".", "Interrupt", "}", "\n", "}", "\n", "if", "s", ".", "errf", "==", "nil", "{", "s", ".", "errf", "=", "func", "(", "str", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "s", ".", "logf", "(", "\"ERROR: \"", "+", "str", ",", "v", "...", ")", "\n", "}", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// New creates a new sentinel server group.
[ "New", "creates", "a", "new", "sentinel", "server", "group", "." ]
0ff081867c31a45cb71f5976ea6144fd06a557b5
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L38-L66
test
brankas/sentinel
sentinel.go
Run
func (s *Sentinel) Run(ctxt context.Context) error { s.Lock() if s.started { defer s.Unlock() return ErrAlreadyStarted } s.started = true s.Unlock() eg, ctxt := errgroup.WithContext(ctxt) // add servers for _, f := range s.serverFuncs { eg.Go(func(f func(context.Context) error) func() error { return func() error { return f(ctxt) } }(f)) } // add shutdown eg.Go(func() func() error { s.sig = make(chan os.Signal, 1) signal.Notify(s.sig, s.shutdownSigs...) return func() error { s.logf("received signal: %v", <-s.sig) return s.Shutdown() } }()) if err := eg.Wait(); err != nil && !s.ShutdownIgnore(err) { return err } return nil }
go
func (s *Sentinel) Run(ctxt context.Context) error { s.Lock() if s.started { defer s.Unlock() return ErrAlreadyStarted } s.started = true s.Unlock() eg, ctxt := errgroup.WithContext(ctxt) // add servers for _, f := range s.serverFuncs { eg.Go(func(f func(context.Context) error) func() error { return func() error { return f(ctxt) } }(f)) } // add shutdown eg.Go(func() func() error { s.sig = make(chan os.Signal, 1) signal.Notify(s.sig, s.shutdownSigs...) return func() error { s.logf("received signal: %v", <-s.sig) return s.Shutdown() } }()) if err := eg.Wait(); err != nil && !s.ShutdownIgnore(err) { return err } return nil }
[ "func", "(", "s", "*", "Sentinel", ")", "Run", "(", "ctxt", "context", ".", "Context", ")", "error", "{", "s", ".", "Lock", "(", ")", "\n", "if", "s", ".", "started", "{", "defer", "s", ".", "Unlock", "(", ")", "\n", "return", "ErrAlreadyStarted", "\n", "}", "\n", "s", ".", "started", "=", "true", "\n", "s", ".", "Unlock", "(", ")", "\n", "eg", ",", "ctxt", ":=", "errgroup", ".", "WithContext", "(", "ctxt", ")", "\n", "for", "_", ",", "f", ":=", "range", "s", ".", "serverFuncs", "{", "eg", ".", "Go", "(", "func", "(", "f", "func", "(", "context", ".", "Context", ")", "error", ")", "func", "(", ")", "error", "{", "return", "func", "(", ")", "error", "{", "return", "f", "(", "ctxt", ")", "\n", "}", "\n", "}", "(", "f", ")", ")", "\n", "}", "\n", "eg", ".", "Go", "(", "func", "(", ")", "func", "(", ")", "error", "{", "s", ".", "sig", "=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "s", ".", "sig", ",", "s", ".", "shutdownSigs", "...", ")", "\n", "return", "func", "(", ")", "error", "{", "s", ".", "logf", "(", "\"received signal: %v\"", ",", "<-", "s", ".", "sig", ")", "\n", "return", "s", ".", "Shutdown", "(", ")", "\n", "}", "\n", "}", "(", ")", ")", "\n", "if", "err", ":=", "eg", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "&&", "!", "s", ".", "ShutdownIgnore", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run starts the server group, returning the first encountered error upon // shutdown.
[ "Run", "starts", "the", "server", "group", "returning", "the", "first", "encountered", "error", "upon", "shutdown", "." ]
0ff081867c31a45cb71f5976ea6144fd06a557b5
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L70-L105
test