id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
13,000
0xrawsec/golang-utils
datastructs/sortedslice.go
NewSortedSlice
func NewSortedSlice(opts ...int) (ss SortedSlice) { l, c := 0, 0 if len(opts) >= 1 { l = opts[0] } if len(opts) >= 2 { c = opts[1] } ss.s = make([]Sortable, l, c) return }
go
func NewSortedSlice(opts ...int) (ss SortedSlice) { l, c := 0, 0 if len(opts) >= 1 { l = opts[0] } if len(opts) >= 2 { c = opts[1] } ss.s = make([]Sortable, l, c) return }
[ "func", "NewSortedSlice", "(", "opts", "...", "int", ")", "(", "ss", "SortedSlice", ")", "{", "l", ",", "c", ":=", "0", ",", "0", "\n", "if", "len", "(", "opts", ")", ">=", "1", "{", "l", "=", "opts", "[", "0", "]", "\n", "}", "\n", "if", "...
// NewSortedSlice returns an empty initialized slice. Opts takes len and cap in // order to initialize the underlying slice
[ "NewSortedSlice", "returns", "an", "empty", "initialized", "slice", ".", "Opts", "takes", "len", "and", "cap", "in", "order", "to", "initialize", "the", "underlying", "slice" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/sortedslice.go#L21-L31
13,001
0xrawsec/golang-utils
datastructs/sortedslice.go
searchLessThan
func (ss *SortedSlice) searchLessThan(e *Sortable, i, j int) int { pivot := ((j + 1 - i) / 2) + i if j-i == 1 { if ss.s[i].Less(e) { return i } return j } if ss.s[pivot].Less(e) { return ss.searchLessThan(e, i, pivot) } return ss.searchLessThan(e, pivot, j) }
go
func (ss *SortedSlice) searchLessThan(e *Sortable, i, j int) int { pivot := ((j + 1 - i) / 2) + i if j-i == 1 { if ss.s[i].Less(e) { return i } return j } if ss.s[pivot].Less(e) { return ss.searchLessThan(e, i, pivot) } return ss.searchLessThan(e, pivot, j) }
[ "func", "(", "ss", "*", "SortedSlice", ")", "searchLessThan", "(", "e", "*", "Sortable", ",", "i", ",", "j", "int", ")", "int", "{", "pivot", ":=", "(", "(", "j", "+", "1", "-", "i", ")", "/", "2", ")", "+", "i", "\n", "if", "j", "-", "i", ...
// Recursive function to search for the next index less than Sortable
[ "Recursive", "function", "to", "search", "for", "the", "next", "index", "less", "than", "Sortable" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/sortedslice.go#L34-L46
13,002
0xrawsec/golang-utils
datastructs/sortedslice.go
RangeLessThan
func (ss *SortedSlice) RangeLessThan(e Sortable) (int, int) { i := ss.searchLessThan(&e, 0, len(ss.s)-1) return i, len(ss.s) - 1 }
go
func (ss *SortedSlice) RangeLessThan(e Sortable) (int, int) { i := ss.searchLessThan(&e, 0, len(ss.s)-1) return i, len(ss.s) - 1 }
[ "func", "(", "ss", "*", "SortedSlice", ")", "RangeLessThan", "(", "e", "Sortable", ")", "(", "int", ",", "int", ")", "{", "i", ":=", "ss", ".", "searchLessThan", "(", "&", "e", ",", "0", ",", "len", "(", "ss", ".", "s", ")", "-", "1", ")", "\...
// RangeLessThan returns the indexes of the objects Less than Sortable
[ "RangeLessThan", "returns", "the", "indexes", "of", "the", "objects", "Less", "than", "Sortable" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/sortedslice.go#L49-L52
13,003
0xrawsec/golang-utils
datastructs/sortedslice.go
Insert
func (ss *SortedSlice) Insert(e Sortable) { switch { // Particular cases case len(ss.s) == 0, !ss.s[len(ss.s)-1].Less(&e): ss.s = append(ss.s, e) case len(ss.s) == 1 && ss.s[0].Less(&e): ss.s = append(ss.s, e) ss.s[1] = ss.s[0] ss.s[0] = e default: //log.Printf("want to insert v=%v into %v", e, ss.s) i := ss.searchLessThan(&e, 0, len(ss.s)-1) //log.Printf("insert v=%v @ i=%d in ss=%v", e, i, ss.s) // Avoid creating intermediary slices ss.s = append(ss.s, e) copy(ss.s[i+1:], ss.s[i:]) ss.s[i] = e } }
go
func (ss *SortedSlice) Insert(e Sortable) { switch { // Particular cases case len(ss.s) == 0, !ss.s[len(ss.s)-1].Less(&e): ss.s = append(ss.s, e) case len(ss.s) == 1 && ss.s[0].Less(&e): ss.s = append(ss.s, e) ss.s[1] = ss.s[0] ss.s[0] = e default: //log.Printf("want to insert v=%v into %v", e, ss.s) i := ss.searchLessThan(&e, 0, len(ss.s)-1) //log.Printf("insert v=%v @ i=%d in ss=%v", e, i, ss.s) // Avoid creating intermediary slices ss.s = append(ss.s, e) copy(ss.s[i+1:], ss.s[i:]) ss.s[i] = e } }
[ "func", "(", "ss", "*", "SortedSlice", ")", "Insert", "(", "e", "Sortable", ")", "{", "switch", "{", "// Particular cases", "case", "len", "(", "ss", ".", "s", ")", "==", "0", ",", "!", "ss", ".", "s", "[", "len", "(", "ss", ".", "s", ")", "-",...
// Insertion method in the slice for a structure implementing Sortable
[ "Insertion", "method", "in", "the", "slice", "for", "a", "structure", "implementing", "Sortable" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/sortedslice.go#L55-L73
13,004
0xrawsec/golang-utils
datastructs/sortedslice.go
ReversedIter
func (ss *SortedSlice) ReversedIter(idx ...int) (c chan Sortable) { c = make(chan Sortable) i, j := 0, len(ss.s)-1 if len(idx) >= 1 { i = idx[0] } if len(idx) >= 2 { j = idx[1] } if i < len(ss.s) && j < len(ss.s) && i <= j && i >= 0 { go func() { defer close(c) for k := len(ss.s) - 1 - i; k >= len(ss.s)-1-j; k-- { v := ss.s[k] c <- v } }() } else { close(c) } return c }
go
func (ss *SortedSlice) ReversedIter(idx ...int) (c chan Sortable) { c = make(chan Sortable) i, j := 0, len(ss.s)-1 if len(idx) >= 1 { i = idx[0] } if len(idx) >= 2 { j = idx[1] } if i < len(ss.s) && j < len(ss.s) && i <= j && i >= 0 { go func() { defer close(c) for k := len(ss.s) - 1 - i; k >= len(ss.s)-1-j; k-- { v := ss.s[k] c <- v } }() } else { close(c) } return c }
[ "func", "(", "ss", "*", "SortedSlice", ")", "ReversedIter", "(", "idx", "...", "int", ")", "(", "c", "chan", "Sortable", ")", "{", "c", "=", "make", "(", "chan", "Sortable", ")", "\n", "i", ",", "j", ":=", "0", ",", "len", "(", "ss", ".", "s", ...
// Iter returns a chan of Sortable in the slice but in reverse order. Start and // Stop indexes can be specified via optional parameters
[ "Iter", "returns", "a", "chan", "of", "Sortable", "in", "the", "slice", "but", "in", "reverse", "order", ".", "Start", "and", "Stop", "indexes", "can", "be", "specified", "via", "optional", "parameters" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/sortedslice.go#L103-L124
13,005
0xrawsec/golang-utils
datastructs/sortedslice.go
Control
func (ss *SortedSlice) Control() bool { v := ss.s[0] for _, tv := range ss.s { if !reflect.DeepEqual(v, tv) && !tv.Less(&v) { return false } } return true }
go
func (ss *SortedSlice) Control() bool { v := ss.s[0] for _, tv := range ss.s { if !reflect.DeepEqual(v, tv) && !tv.Less(&v) { return false } } return true }
[ "func", "(", "ss", "*", "SortedSlice", ")", "Control", "(", ")", "bool", "{", "v", ":=", "ss", ".", "s", "[", "0", "]", "\n", "for", "_", ",", "tv", ":=", "range", "ss", ".", "s", "{", "if", "!", "reflect", ".", "DeepEqual", "(", "v", ",", ...
// Control controls if the slice has been properly ordered. A return value of // true means it is in good order
[ "Control", "controls", "if", "the", "slice", "has", "been", "properly", "ordered", ".", "A", "return", "value", "of", "true", "means", "it", "is", "in", "good", "order" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/sortedslice.go#L133-L141
13,006
0xrawsec/golang-utils
fsutil/logfile/logfile.go
OpenFile
func OpenFile(path string, perm os.FileMode, size int64) (*LogFile, error) { l := LogFile{} l.path = path l.perm = perm l.size = size l.rate = DefaultRotationRate // Search for the first available path err := l.searchFirstAvPath() if err != nil { return nil, err } // Open the file descriptor f, err := os.OpenFile(l.Path(), os.O_APPEND|os.O_CREATE|os.O_RDWR, l.perm) if err != nil { return nil, err } l.file = f l.writer = gzip.NewWriter(f) // We start the rotate routine l.rotateRoutine() return &l, nil }
go
func OpenFile(path string, perm os.FileMode, size int64) (*LogFile, error) { l := LogFile{} l.path = path l.perm = perm l.size = size l.rate = DefaultRotationRate // Search for the first available path err := l.searchFirstAvPath() if err != nil { return nil, err } // Open the file descriptor f, err := os.OpenFile(l.Path(), os.O_APPEND|os.O_CREATE|os.O_RDWR, l.perm) if err != nil { return nil, err } l.file = f l.writer = gzip.NewWriter(f) // We start the rotate routine l.rotateRoutine() return &l, nil }
[ "func", "OpenFile", "(", "path", "string", ",", "perm", "os", ".", "FileMode", ",", "size", "int64", ")", "(", "*", "LogFile", ",", "error", ")", "{", "l", ":=", "LogFile", "{", "}", "\n", "l", ".", "path", "=", "path", "\n", "l", ".", "perm", ...
// OpenFile opens a new file for logging
[ "OpenFile", "opens", "a", "new", "file", "for", "logging" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L42-L64
13,007
0xrawsec/golang-utils
fsutil/logfile/logfile.go
Path
func (l *LogFile) Path() string { if l.idx == 0 { return l.path } return fmt.Sprintf("%s.%d", l.path, l.idx) }
go
func (l *LogFile) Path() string { if l.idx == 0 { return l.path } return fmt.Sprintf("%s.%d", l.path, l.idx) }
[ "func", "(", "l", "*", "LogFile", ")", "Path", "(", ")", "string", "{", "if", "l", ".", "idx", "==", "0", "{", "return", "l", ".", "path", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "l", ".", "path", ",", "l", "...
// Path returns the path of the LogFile
[ "Path", "returns", "the", "path", "of", "the", "LogFile" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L67-L72
13,008
0xrawsec/golang-utils
fsutil/logfile/logfile.go
searchFirstAvPath
func (l *LogFile) searchFirstAvPath() error { for { if fsutil.Exists(l.Path()) { stats, err := os.Stat(l.Path()) if err != nil { return err } if stats.Size() >= l.size { l.idx++ } else { return nil } } else { return nil } } }
go
func (l *LogFile) searchFirstAvPath() error { for { if fsutil.Exists(l.Path()) { stats, err := os.Stat(l.Path()) if err != nil { return err } if stats.Size() >= l.size { l.idx++ } else { return nil } } else { return nil } } }
[ "func", "(", "l", "*", "LogFile", ")", "searchFirstAvPath", "(", ")", "error", "{", "for", "{", "if", "fsutil", ".", "Exists", "(", "l", ".", "Path", "(", ")", ")", "{", "stats", ",", "err", ":=", "os", ".", "Stat", "(", "l", ".", "Path", "(", ...
// helper function to retrieve the first available file for writing
[ "helper", "function", "to", "retrieve", "the", "first", "available", "file", "for", "writing" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L75-L91
13,009
0xrawsec/golang-utils
fsutil/logfile/logfile.go
rotateRoutine
func (l *LogFile) rotateRoutine() { go func() { for { if stats, err := os.Stat(l.Path()); err == nil { if stats.Size() >= l.size { l.Rotate() } } time.Sleep(l.rate) } }() }
go
func (l *LogFile) rotateRoutine() { go func() { for { if stats, err := os.Stat(l.Path()); err == nil { if stats.Size() >= l.size { l.Rotate() } } time.Sleep(l.rate) } }() }
[ "func", "(", "l", "*", "LogFile", ")", "rotateRoutine", "(", ")", "{", "go", "func", "(", ")", "{", "for", "{", "if", "stats", ",", "err", ":=", "os", ".", "Stat", "(", "l", ".", "Path", "(", ")", ")", ";", "err", "==", "nil", "{", "if", "s...
// helper function which rotate the logfile when needed
[ "helper", "function", "which", "rotate", "the", "logfile", "when", "needed" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L94-L105
13,010
0xrawsec/golang-utils
fsutil/logfile/logfile.go
Rotate
func (l *LogFile) Rotate() error { l.Lock() defer l.Unlock() // We close everything first l.Close() if err := l.searchFirstAvPath(); err != nil { return err } f, err := os.OpenFile(l.Path(), os.O_APPEND|os.O_CREATE|os.O_RDWR, l.perm) if err != nil { return err } l.file = f l.writer = gzip.NewWriter(l.file) return nil }
go
func (l *LogFile) Rotate() error { l.Lock() defer l.Unlock() // We close everything first l.Close() if err := l.searchFirstAvPath(); err != nil { return err } f, err := os.OpenFile(l.Path(), os.O_APPEND|os.O_CREATE|os.O_RDWR, l.perm) if err != nil { return err } l.file = f l.writer = gzip.NewWriter(l.file) return nil }
[ "func", "(", "l", "*", "LogFile", ")", "Rotate", "(", ")", "error", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "// We close everything first", "l", ".", "Close", "(", ")", "\n", "if", "err", ":=", "l", "."...
// Rotate rotates the current LogFile
[ "Rotate", "rotates", "the", "current", "LogFile" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L114-L129
13,011
0xrawsec/golang-utils
fsutil/logfile/logfile.go
Close
func (l *LogFile) Close() error { l.writer.Flush() l.writer.Close() return l.file.Close() }
go
func (l *LogFile) Close() error { l.writer.Flush() l.writer.Close() return l.file.Close() }
[ "func", "(", "l", "*", "LogFile", ")", "Close", "(", ")", "error", "{", "l", ".", "writer", ".", "Flush", "(", ")", "\n", "l", ".", "writer", ".", "Close", "(", ")", "\n", "return", "l", ".", "file", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the LogFile properly
[ "Close", "closes", "the", "LogFile", "properly" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L132-L136
13,012
0xrawsec/golang-utils
fsutil/logfile/logfile.go
WriteString
func (l *LogFile) WriteString(s string) (int, error) { l.Lock() defer l.Unlock() return l.writer.Write([]byte(s)) }
go
func (l *LogFile) WriteString(s string) (int, error) { l.Lock() defer l.Unlock() return l.writer.Write([]byte(s)) }
[ "func", "(", "l", "*", "LogFile", ")", "WriteString", "(", "s", "string", ")", "(", "int", ",", "error", ")", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "writer", ".", "Write", "(", ...
// WriteString writes a string into the LogFile
[ "WriteString", "writes", "a", "string", "into", "the", "LogFile" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L139-L143
13,013
0xrawsec/golang-utils
fsutil/logfile/logfile.go
Write
func (l *LogFile) Write(b []byte) (int, error) { l.Lock() defer l.Unlock() return l.writer.Write(b) }
go
func (l *LogFile) Write(b []byte) (int, error) { l.Lock() defer l.Unlock() return l.writer.Write(b) }
[ "func", "(", "l", "*", "LogFile", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "writer", ".", "Write", ...
// Write writes bytes into the LogFile
[ "Write", "writes", "bytes", "into", "the", "LogFile" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/logfile/logfile.go#L146-L150
13,014
0xrawsec/golang-utils
log/log.go
InitLogger
func InitLogger(logLevel int) { SetLogLevel(logLevel) if logLevel <= LDebug { log.SetFlags(log.LstdFlags | log.Lshortfile) } }
go
func InitLogger(logLevel int) { SetLogLevel(logLevel) if logLevel <= LDebug { log.SetFlags(log.LstdFlags | log.Lshortfile) } }
[ "func", "InitLogger", "(", "logLevel", "int", ")", "{", "SetLogLevel", "(", "logLevel", ")", "\n", "if", "logLevel", "<=", "LDebug", "{", "log", ".", "SetFlags", "(", "log", ".", "LstdFlags", "|", "log", ".", "Lshortfile", ")", "\n", "}", "\n", "}" ]
// InitLogger Initialize the global logger
[ "InitLogger", "Initialize", "the", "global", "logger" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L34-L39
13,015
0xrawsec/golang-utils
log/log.go
SetLogfile
func SetLogfile(logfilePath string, opts ...os.FileMode) { var err error mode := os.FileMode(defaultFileMode) // We open the file in append mode if len(opts) > 0 { mode = opts[0] } gLogFile, err := os.OpenFile(logfilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, mode) if err != nil { panic(err) } if _, err := gLogFile.Seek(0, os.SEEK_END); err != nil { panic(err) } log.SetOutput(gLogFile) }
go
func SetLogfile(logfilePath string, opts ...os.FileMode) { var err error mode := os.FileMode(defaultFileMode) // We open the file in append mode if len(opts) > 0 { mode = opts[0] } gLogFile, err := os.OpenFile(logfilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, mode) if err != nil { panic(err) } if _, err := gLogFile.Seek(0, os.SEEK_END); err != nil { panic(err) } log.SetOutput(gLogFile) }
[ "func", "SetLogfile", "(", "logfilePath", "string", ",", "opts", "...", "os", ".", "FileMode", ")", "{", "var", "err", "error", "\n", "mode", ":=", "os", ".", "FileMode", "(", "defaultFileMode", ")", "\n", "// We open the file in append mode", "if", "len", "...
// SetLogfile sets output file to put logging messages
[ "SetLogfile", "sets", "output", "file", "to", "put", "logging", "messages" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L42-L57
13,016
0xrawsec/golang-utils
log/log.go
SetLogLevel
func SetLogLevel(logLevel int) { gLogLevelBackup = gLogLevel switch logLevel { case LInfo: gLogLevel = logLevel case LDebug: gLogLevel = logLevel case LCritical: gLogLevel = logLevel case LError: gLogLevel = logLevel default: gLogLevel = LInfo } }
go
func SetLogLevel(logLevel int) { gLogLevelBackup = gLogLevel switch logLevel { case LInfo: gLogLevel = logLevel case LDebug: gLogLevel = logLevel case LCritical: gLogLevel = logLevel case LError: gLogLevel = logLevel default: gLogLevel = LInfo } }
[ "func", "SetLogLevel", "(", "logLevel", "int", ")", "{", "gLogLevelBackup", "=", "gLogLevel", "\n", "switch", "logLevel", "{", "case", "LInfo", ":", "gLogLevel", "=", "logLevel", "\n", "case", "LDebug", ":", "gLogLevel", "=", "logLevel", "\n", "case", "LCrit...
// SetLogLevel backup gLoglevel and set gLogLevel to logLevel
[ "SetLogLevel", "backup", "gLoglevel", "and", "set", "gLogLevel", "to", "logLevel" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L60-L74
13,017
0xrawsec/golang-utils
log/log.go
Infof
func Infof(format string, i ...interface{}) { if gLogLevel <= LInfo { logMessage("INFO - ", fmt.Sprintf(format, i...)) } }
go
func Infof(format string, i ...interface{}) { if gLogLevel <= LInfo { logMessage("INFO - ", fmt.Sprintf(format, i...)) } }
[ "func", "Infof", "(", "format", "string", ",", "i", "...", "interface", "{", "}", ")", "{", "if", "gLogLevel", "<=", "LInfo", "{", "logMessage", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "format", ",", "i", "...", ")", ")", "\n", "}", "\n...
// Infof log message with format if gLogLevel <= LInfo
[ "Infof", "log", "message", "with", "format", "if", "gLogLevel", "<", "=", "LInfo" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L95-L99
13,018
0xrawsec/golang-utils
log/log.go
Debugf
func Debugf(format string, i ...interface{}) { if gLogLevel <= LDebug { logMessage("DEBUG - ", fmt.Sprintf(format, i...)) } }
go
func Debugf(format string, i ...interface{}) { if gLogLevel <= LDebug { logMessage("DEBUG - ", fmt.Sprintf(format, i...)) } }
[ "func", "Debugf", "(", "format", "string", ",", "i", "...", "interface", "{", "}", ")", "{", "if", "gLogLevel", "<=", "LDebug", "{", "logMessage", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "format", ",", "i", "...", ")", ")", "\n", "}", "...
// Debugf log message with format if gLogLevel <= LDebug
[ "Debugf", "log", "message", "with", "format", "if", "gLogLevel", "<", "=", "LDebug" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L123-L127
13,019
0xrawsec/golang-utils
log/log.go
Errorf
func Errorf(format string, i ...interface{}) { if gLogLevel <= LError { logMessage("ERROR - ", fmt.Sprintf(format, i...)) } }
go
func Errorf(format string, i ...interface{}) { if gLogLevel <= LError { logMessage("ERROR - ", fmt.Sprintf(format, i...)) } }
[ "func", "Errorf", "(", "format", "string", ",", "i", "...", "interface", "{", "}", ")", "{", "if", "gLogLevel", "<=", "LError", "{", "logMessage", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "format", ",", "i", "...", ")", ")", "\n", "}", "...
// Errorf log message with format if gLogLevel <= LError
[ "Errorf", "log", "message", "with", "format", "if", "gLogLevel", "<", "=", "LError" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L137-L141
13,020
0xrawsec/golang-utils
log/log.go
LogErrorAndExit
func LogErrorAndExit(err error, opts ...int) { var rc int if len(opts) > 0 { rc = opts[0] } if gLogLevel <= LError { logMessage("ERROR - ", err.Error()) } os.Exit(rc) }
go
func LogErrorAndExit(err error, opts ...int) { var rc int if len(opts) > 0 { rc = opts[0] } if gLogLevel <= LError { logMessage("ERROR - ", err.Error()) } os.Exit(rc) }
[ "func", "LogErrorAndExit", "(", "err", "error", ",", "opts", "...", "int", ")", "{", "var", "rc", "int", "\n", "if", "len", "(", "opts", ")", ">", "0", "{", "rc", "=", "opts", "[", "0", "]", "\n", "}", "\n", "if", "gLogLevel", "<=", "LError", "...
// LogErrorAndExit logs an error and exit with an optional return code
[ "LogErrorAndExit", "logs", "an", "error", "and", "exit", "with", "an", "optional", "return", "code" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L151-L160
13,021
0xrawsec/golang-utils
log/log.go
Criticalf
func Criticalf(format string, i ...interface{}) { if gLogLevel <= LCritical { logMessage("CRITICAL - ", fmt.Sprintf(format, i...)) } }
go
func Criticalf(format string, i ...interface{}) { if gLogLevel <= LCritical { logMessage("CRITICAL - ", fmt.Sprintf(format, i...)) } }
[ "func", "Criticalf", "(", "format", "string", ",", "i", "...", "interface", "{", "}", ")", "{", "if", "gLogLevel", "<=", "LCritical", "{", "logMessage", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "format", ",", "i", "...", ")", ")", "\n", "}...
// Criticalf log message with format if gLogLevel <= LCritical
[ "Criticalf", "log", "message", "with", "format", "if", "gLogLevel", "<", "=", "LCritical" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L170-L174
13,022
0xrawsec/golang-utils
log/log.go
DontPanic
func DontPanic(i interface{}) { msg := fmt.Sprintf("%v\n %s", i, debug.Stack()) logMessage("PANIC - ", msg) }
go
func DontPanic(i interface{}) { msg := fmt.Sprintf("%v\n %s", i, debug.Stack()) logMessage("PANIC - ", msg) }
[ "func", "DontPanic", "(", "i", "interface", "{", "}", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "i", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "logMessage", "(", "\"", "\"", ",", "msg", ")", "\n", "}" ]
// DontPanic only prints panic information but don't panic
[ "DontPanic", "only", "prints", "panic", "information", "but", "don", "t", "panic" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L177-L180
13,023
0xrawsec/golang-utils
log/log.go
DebugDontPanic
func DebugDontPanic(i interface{}) { if gLogLevel <= LDebug { msg := fmt.Sprintf("%v\n %s", i, debug.Stack()) logMessage("PANIC - ", msg) } }
go
func DebugDontPanic(i interface{}) { if gLogLevel <= LDebug { msg := fmt.Sprintf("%v\n %s", i, debug.Stack()) logMessage("PANIC - ", msg) } }
[ "func", "DebugDontPanic", "(", "i", "interface", "{", "}", ")", "{", "if", "gLogLevel", "<=", "LDebug", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "i", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "logMessage", "(", ...
// DebugDontPanic only prints panic information but don't panic
[ "DebugDontPanic", "only", "prints", "panic", "information", "but", "don", "t", "panic" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L183-L188
13,024
0xrawsec/golang-utils
log/log.go
DontPanicf
func DontPanicf(format string, i ...interface{}) { msg := fmt.Sprintf("%v\n %s", fmt.Sprintf(format, i...), debug.Stack()) logMessage("PANIC - ", msg) }
go
func DontPanicf(format string, i ...interface{}) { msg := fmt.Sprintf("%v\n %s", fmt.Sprintf(format, i...), debug.Stack()) logMessage("PANIC - ", msg) }
[ "func", "DontPanicf", "(", "format", "string", ",", "i", "...", "interface", "{", "}", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "fmt", ".", "Sprintf", "(", "format", ",", "i", "...", ")", ",", "debug", ".", "Stac...
// DontPanicf only prints panic information but don't panic
[ "DontPanicf", "only", "prints", "panic", "information", "but", "don", "t", "panic" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L191-L194
13,025
0xrawsec/golang-utils
log/log.go
DebugDontPanicf
func DebugDontPanicf(format string, i ...interface{}) { if gLogLevel <= LDebug { msg := fmt.Sprintf("%v\n %s", fmt.Sprintf(format, i...), debug.Stack()) logMessage("PANIC - ", msg) } }
go
func DebugDontPanicf(format string, i ...interface{}) { if gLogLevel <= LDebug { msg := fmt.Sprintf("%v\n %s", fmt.Sprintf(format, i...), debug.Stack()) logMessage("PANIC - ", msg) } }
[ "func", "DebugDontPanicf", "(", "format", "string", ",", "i", "...", "interface", "{", "}", ")", "{", "if", "gLogLevel", "<=", "LDebug", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "fmt", ".", "Sprintf", "(", "format", ",", ...
// DebugDontPanicf only prints panic information but don't panic
[ "DebugDontPanicf", "only", "prints", "panic", "information", "but", "don", "t", "panic" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L197-L202
13,026
0xrawsec/golang-utils
log/log.go
Panic
func Panic(i interface{}) { msg := fmt.Sprintf("%v\n %s", i, debug.Stack()) logMessage("PANIC - ", msg) panic(i) }
go
func Panic(i interface{}) { msg := fmt.Sprintf("%v\n %s", i, debug.Stack()) logMessage("PANIC - ", msg) panic(i) }
[ "func", "Panic", "(", "i", "interface", "{", "}", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "i", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "logMessage", "(", "\"", "\"", ",", "msg", ")", "\n", "panic", ...
// Panic prints panic information and call panic
[ "Panic", "prints", "panic", "information", "and", "call", "panic" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/log/log.go#L205-L209
13,027
0xrawsec/golang-utils
args/dateargs.go
Set
func (da *DateVar) Set(input string) error { t, err := dateutil.Parse(input) (*da) = DateVar(t) return err }
go
func (da *DateVar) Set(input string) error { t, err := dateutil.Parse(input) (*da) = DateVar(t) return err }
[ "func", "(", "da", "*", "DateVar", ")", "Set", "(", "input", "string", ")", "error", "{", "t", ",", "err", ":=", "dateutil", ".", "Parse", "(", "input", ")", "\n", "(", "*", "da", ")", "=", "DateVar", "(", "t", ")", "\n", "return", "err", "\n",...
// Set argument implementation
[ "Set", "argument", "implementation" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/args/dateargs.go#L18-L22
13,028
0xrawsec/golang-utils
ngram/ngram.go
NewNgram
func NewNgram(buf []byte) Ngram { ngram := make(Ngram, len(buf)) copy(ngram, buf) return ngram }
go
func NewNgram(buf []byte) Ngram { ngram := make(Ngram, len(buf)) copy(ngram, buf) return ngram }
[ "func", "NewNgram", "(", "buf", "[", "]", "byte", ")", "Ngram", "{", "ngram", ":=", "make", "(", "Ngram", ",", "len", "(", "buf", ")", ")", "\n", "copy", "(", "ngram", ",", "buf", ")", "\n", "return", "ngram", "\n", "}" ]
// New new ngram from buffer
[ "New", "new", "ngram", "from", "buffer" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/ngram/ngram.go#L22-L26
13,029
0xrawsec/golang-utils
ngram/ngram.go
Hash
func (ngram *Ngram) Hash() uint64 { h := fnv.New64a() h.Write((*ngram)[:]) return h.Sum64() }
go
func (ngram *Ngram) Hash() uint64 { h := fnv.New64a() h.Write((*ngram)[:]) return h.Sum64() }
[ "func", "(", "ngram", "*", "Ngram", ")", "Hash", "(", ")", "uint64", "{", "h", ":=", "fnv", ".", "New64a", "(", ")", "\n", "h", ".", "Write", "(", "(", "*", "ngram", ")", "[", ":", "]", ")", "\n", "return", "h", ".", "Sum64", "(", ")", "\n"...
// Hash hashes a ngram
[ "Hash", "hashes", "a", "ngram" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/ngram/ngram.go#L29-L33
13,030
0xrawsec/golang-utils
ngram/ngram.go
Generator
func Generator(reader io.Reader, sNgram int) chan Ngram { if sNgram <= 0 { panic(ErrBadNgramSize) } yield := make(chan Ngram) go func() { feed(yield, reader, sNgram) }() return yield }
go
func Generator(reader io.Reader, sNgram int) chan Ngram { if sNgram <= 0 { panic(ErrBadNgramSize) } yield := make(chan Ngram) go func() { feed(yield, reader, sNgram) }() return yield }
[ "func", "Generator", "(", "reader", "io", ".", "Reader", ",", "sNgram", "int", ")", "chan", "Ngram", "{", "if", "sNgram", "<=", "0", "{", "panic", "(", "ErrBadNgramSize", ")", "\n", "}", "\n", "yield", ":=", "make", "(", "chan", "Ngram", ")", "\n\n",...
// Generator generates Ngrams of size sNgram from a file
[ "Generator", "generates", "Ngrams", "of", "size", "sNgram", "from", "a", "file" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/ngram/ngram.go#L36-L47
13,031
0xrawsec/golang-utils
scanner/scanner.go
New
func New(r io.Reader) (s *Scanner) { s = &Scanner{} s.r = bufio.NewReader(r) s.Whitespace = datastructs.NewBitSet(256) s.Error = func(err error) { fmt.Fprintf(os.Stderr, "Scanner error: %s\n", err) } // initialize default with Whitespace variable s.InitWhitespace(Whitespace) s.token = make([]rune, MaxTokenLen) s.tokenIdx = 0 return }
go
func New(r io.Reader) (s *Scanner) { s = &Scanner{} s.r = bufio.NewReader(r) s.Whitespace = datastructs.NewBitSet(256) s.Error = func(err error) { fmt.Fprintf(os.Stderr, "Scanner error: %s\n", err) } // initialize default with Whitespace variable s.InitWhitespace(Whitespace) s.token = make([]rune, MaxTokenLen) s.tokenIdx = 0 return }
[ "func", "New", "(", "r", "io", ".", "Reader", ")", "(", "s", "*", "Scanner", ")", "{", "s", "=", "&", "Scanner", "{", "}", "\n", "s", ".", "r", "=", "bufio", ".", "NewReader", "(", "r", ")", "\n", "s", ".", "Whitespace", "=", "datastructs", "...
// New creates a new scanner from reader
[ "New", "creates", "a", "new", "scanner", "from", "reader" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/scanner/scanner.go#L36-L48
13,032
0xrawsec/golang-utils
scanner/scanner.go
InitWhitespace
func (s *Scanner) InitWhitespace(w string) { s.Whitespace = datastructs.NewBitSet(256) for _, c := range w { s.Whitespace.Set(int(c)) } }
go
func (s *Scanner) InitWhitespace(w string) { s.Whitespace = datastructs.NewBitSet(256) for _, c := range w { s.Whitespace.Set(int(c)) } }
[ "func", "(", "s", "*", "Scanner", ")", "InitWhitespace", "(", "w", "string", ")", "{", "s", ".", "Whitespace", "=", "datastructs", ".", "NewBitSet", "(", "256", ")", "\n", "for", "_", ",", "c", ":=", "range", "w", "{", "s", ".", "Whitespace", ".", ...
// InitWhitespace initialised an new set of whitespaces for the scanner
[ "InitWhitespace", "initialised", "an", "new", "set", "of", "whitespaces", "for", "the", "scanner" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/scanner/scanner.go#L51-L56
13,033
0xrawsec/golang-utils
scanner/scanner.go
Scan
func (s *Scanner) Scan() (r rune) { s.tokenIdx = 0 r, _, err := s.r.ReadRune() prevRune := r if s.Whitespace.Get(int(r)) { s.token[s.tokenIdx] = r s.tokenIdx++ return r } for ; !s.Whitespace.Get(int(r)); r, _, err = s.r.ReadRune() { switch err { case nil: break case io.EOF: return EOF default: s.Error(err) return EOF } s.token[s.tokenIdx] = r s.tokenIdx++ prevRune = r } // We have to UnreadRune because we went too far of one rune err = s.r.UnreadRune() if err != nil { s.Error(err) } return prevRune }
go
func (s *Scanner) Scan() (r rune) { s.tokenIdx = 0 r, _, err := s.r.ReadRune() prevRune := r if s.Whitespace.Get(int(r)) { s.token[s.tokenIdx] = r s.tokenIdx++ return r } for ; !s.Whitespace.Get(int(r)); r, _, err = s.r.ReadRune() { switch err { case nil: break case io.EOF: return EOF default: s.Error(err) return EOF } s.token[s.tokenIdx] = r s.tokenIdx++ prevRune = r } // We have to UnreadRune because we went too far of one rune err = s.r.UnreadRune() if err != nil { s.Error(err) } return prevRune }
[ "func", "(", "s", "*", "Scanner", ")", "Scan", "(", ")", "(", "r", "rune", ")", "{", "s", ".", "tokenIdx", "=", "0", "\n", "r", ",", "_", ",", "err", ":=", "s", ".", "r", ".", "ReadRune", "(", ")", "\n", "prevRune", ":=", "r", "\n\n", "if",...
// Scan scans until we reach a whitespace token
[ "Scan", "scans", "until", "we", "reach", "a", "whitespace", "token" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/scanner/scanner.go#L59-L92
13,034
0xrawsec/golang-utils
scanner/scanner.go
Tokenize
func (s *Scanner) Tokenize() (cs chan string) { cs = make(chan string) go func() { defer close(cs) for r := s.Scan(); r != EOF; r = s.Scan() { cs <- s.TokenText() } cs <- s.TokenText() }() return }
go
func (s *Scanner) Tokenize() (cs chan string) { cs = make(chan string) go func() { defer close(cs) for r := s.Scan(); r != EOF; r = s.Scan() { cs <- s.TokenText() } cs <- s.TokenText() }() return }
[ "func", "(", "s", "*", "Scanner", ")", "Tokenize", "(", ")", "(", "cs", "chan", "string", ")", "{", "cs", "=", "make", "(", "chan", "string", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "cs", ")", "\n", "for", "r", ":=", "s...
// Tokenize returns a chan of tokens found in scanner until exhaustion
[ "Tokenize", "returns", "a", "chan", "of", "tokens", "found", "in", "scanner", "until", "exhaustion" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/scanner/scanner.go#L100-L110
13,035
0xrawsec/golang-utils
fsutil/shred/shred.go
Shred
func Shred(fpath string) error { stat, err := os.Stat(fpath) if err != nil { return err } file, err := os.OpenFile(fpath, os.O_RDWR, 0) if err != nil { return err } defer file.Close() b := make([]byte, stat.Size()) rand.Read(b) _, err = file.Write(b) err = os.Remove(fpath) if err != nil { return err } return err }
go
func Shred(fpath string) error { stat, err := os.Stat(fpath) if err != nil { return err } file, err := os.OpenFile(fpath, os.O_RDWR, 0) if err != nil { return err } defer file.Close() b := make([]byte, stat.Size()) rand.Read(b) _, err = file.Write(b) err = os.Remove(fpath) if err != nil { return err } return err }
[ "func", "Shred", "(", "fpath", "string", ")", "error", "{", "stat", ",", "err", ":=", "os", ".", "Stat", "(", "fpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "file", ",", "err", ":=", "os", ".", "OpenFile", ...
// Shred a file
[ "Shred", "a", "file" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/shred/shred.go#L9-L31
13,036
0xrawsec/golang-utils
datastructs/hashmap.go
NewSyncedHashMap
func NewSyncedHashMap() (hm SyncedHashMap) { hm.keys = make(map[string]Hashable) hm.values = make(map[string]interface{}) return hm }
go
func NewSyncedHashMap() (hm SyncedHashMap) { hm.keys = make(map[string]Hashable) hm.values = make(map[string]interface{}) return hm }
[ "func", "NewSyncedHashMap", "(", ")", "(", "hm", "SyncedHashMap", ")", "{", "hm", ".", "keys", "=", "make", "(", "map", "[", "string", "]", "Hashable", ")", "\n", "hm", ".", "values", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "...
// NewSyncedHashMap SyncedHashMap constructor
[ "NewSyncedHashMap", "SyncedHashMap", "constructor" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/hashmap.go#L98-L102
13,037
0xrawsec/golang-utils
datastructs/hashmap.go
Len
func (hm *SyncedHashMap) Len() int { hm.RLock() defer hm.RUnlock() return len(hm.keys) }
go
func (hm *SyncedHashMap) Len() int { hm.RLock() defer hm.RUnlock() return len(hm.keys) }
[ "func", "(", "hm", "*", "SyncedHashMap", ")", "Len", "(", ")", "int", "{", "hm", ".", "RLock", "(", ")", "\n", "defer", "hm", ".", "RUnlock", "(", ")", "\n", "return", "len", "(", "hm", ".", "keys", ")", "\n", "}" ]
// Len returns the length of the HashMap
[ "Len", "returns", "the", "length", "of", "the", "HashMap" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/hashmap.go#L184-L188
13,038
0xrawsec/golang-utils
datastructs/bitset.go
NewBitSet
func NewBitSet(size int) (bs *BitSet) { bs = &BitSet{} bs.size = size if size%8 == 0 { bs.set = make([]uint8, size/8) } else { bs.set = make([]uint8, (size/8)+1) } return }
go
func NewBitSet(size int) (bs *BitSet) { bs = &BitSet{} bs.size = size if size%8 == 0 { bs.set = make([]uint8, size/8) } else { bs.set = make([]uint8, (size/8)+1) } return }
[ "func", "NewBitSet", "(", "size", "int", ")", "(", "bs", "*", "BitSet", ")", "{", "bs", "=", "&", "BitSet", "{", "}", "\n", "bs", ".", "size", "=", "size", "\n", "if", "size", "%", "8", "==", "0", "{", "bs", ".", "set", "=", "make", "(", "[...
// NewBitSet creates a new bitset
[ "NewBitSet", "creates", "a", "new", "bitset" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/bitset.go#L10-L19
13,039
0xrawsec/golang-utils
datastructs/bitset.go
Set
func (b *BitSet) Set(o int) { bucketID := o / 8 oInBucket := uint8(o % 8) if o >= b.size { return } b.set[bucketID] = (b.set[bucketID] | 0x1<<oInBucket) }
go
func (b *BitSet) Set(o int) { bucketID := o / 8 oInBucket := uint8(o % 8) if o >= b.size { return } b.set[bucketID] = (b.set[bucketID] | 0x1<<oInBucket) }
[ "func", "(", "b", "*", "BitSet", ")", "Set", "(", "o", "int", ")", "{", "bucketID", ":=", "o", "/", "8", "\n", "oInBucket", ":=", "uint8", "(", "o", "%", "8", ")", "\n", "if", "o", ">=", "b", ".", "size", "{", "return", "\n", "}", "\n", "b"...
// Set bit at offset o
[ "Set", "bit", "at", "offset", "o" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/bitset.go#L22-L29
13,040
0xrawsec/golang-utils
datastructs/bitset.go
Get
func (b *BitSet) Get(o int) bool { bucketID := o / 8 oInBucket := uint8(o % 8) if o >= b.size { return false } return (b.set[bucketID]&(0x1<<oInBucket))>>oInBucket == 0x1 }
go
func (b *BitSet) Get(o int) bool { bucketID := o / 8 oInBucket := uint8(o % 8) if o >= b.size { return false } return (b.set[bucketID]&(0x1<<oInBucket))>>oInBucket == 0x1 }
[ "func", "(", "b", "*", "BitSet", ")", "Get", "(", "o", "int", ")", "bool", "{", "bucketID", ":=", "o", "/", "8", "\n", "oInBucket", ":=", "uint8", "(", "o", "%", "8", ")", "\n", "if", "o", ">=", "b", ".", "size", "{", "return", "false", "\n",...
// Get the value of bit at offset o
[ "Get", "the", "value", "of", "bit", "at", "offset", "o" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/datastructs/bitset.go#L32-L39
13,041
0xrawsec/golang-utils
dateutil/parser.go
Parse
func Parse(value string) (time.Time, error) { for _, ds := range allDateStrings { if ds.Match(value) { return ds.Parse(value) } } return time.Time{}, &UnknownDateFormatError{value} }
go
func Parse(value string) (time.Time, error) { for _, ds := range allDateStrings { if ds.Match(value) { return ds.Parse(value) } } return time.Time{}, &UnknownDateFormatError{value} }
[ "func", "Parse", "(", "value", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "for", "_", ",", "ds", ":=", "range", "allDateStrings", "{", "if", "ds", ".", "Match", "(", "value", ")", "{", "return", "ds", ".", "Parse", "(", "val...
// Parse attempts to parse a time string with all the knowns DateStrings
[ "Parse", "attempts", "to", "parse", "a", "time", "string", "with", "all", "the", "knowns", "DateStrings" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/dateutil/parser.go#L107-L114
13,042
0xrawsec/golang-utils
dateutil/parser.go
NewDateString
func NewDateString(dateRe, layout string) DateString { return DateString{regexp.MustCompile(dateRe), layout} }
go
func NewDateString(dateRe, layout string) DateString { return DateString{regexp.MustCompile(dateRe), layout} }
[ "func", "NewDateString", "(", "dateRe", ",", "layout", "string", ")", "DateString", "{", "return", "DateString", "{", "regexp", ".", "MustCompile", "(", "dateRe", ")", ",", "layout", "}", "\n", "}" ]
// NewDateString creates a DateString structure
[ "NewDateString", "creates", "a", "DateString", "structure" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/dateutil/parser.go#L117-L119
13,043
0xrawsec/golang-utils
dateutil/parser.go
Match
func (d *DateString) Match(value string) bool { return d.Regexp.Match([]byte(value)) }
go
func (d *DateString) Match(value string) bool { return d.Regexp.Match([]byte(value)) }
[ "func", "(", "d", "*", "DateString", ")", "Match", "(", "value", "string", ")", "bool", "{", "return", "d", ".", "Regexp", ".", "Match", "(", "[", "]", "byte", "(", "value", ")", ")", "\n", "}" ]
// Match returns true if the DateString Regexp matches b
[ "Match", "returns", "true", "if", "the", "DateString", "Regexp", "matches", "b" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/dateutil/parser.go#L122-L124
13,044
0xrawsec/golang-utils
dateutil/parser.go
Parse
func (d *DateString) Parse(value string) (time.Time, error) { return time.Parse(d.Layout, value) }
go
func (d *DateString) Parse(value string) (time.Time, error) { return time.Parse(d.Layout, value) }
[ "func", "(", "d", "*", "DateString", ")", "Parse", "(", "value", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "return", "time", ".", "Parse", "(", "d", ".", "Layout", ",", "value", ")", "\n", "}" ]
// Parse parses value and returns the corresponding time.Time
[ "Parse", "parses", "value", "and", "returns", "the", "corresponding", "time", ".", "Time" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/dateutil/parser.go#L127-L129
13,045
0xrawsec/golang-utils
fsutil/fswalker/fswalker.go
NormalizePath
func NormalizePath(path string) string { pointer, err := filepath.EvalSymlinks(path) if err != nil { return path } abs, err := filepath.Abs(pointer) if err != nil { return pointer } return abs }
go
func NormalizePath(path string) string { pointer, err := filepath.EvalSymlinks(path) if err != nil { return path } abs, err := filepath.Abs(pointer) if err != nil { return pointer } return abs }
[ "func", "NormalizePath", "(", "path", "string", ")", "string", "{", "pointer", ",", "err", ":=", "filepath", ".", "EvalSymlinks", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "path", "\n", "}", "\n", "abs", ",", "err", ":=", "file...
// NormalizePath normalizes a given path
[ "NormalizePath", "normalizes", "a", "given", "path" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/fswalker/fswalker.go#L37-L47
13,046
0xrawsec/golang-utils
progress/sprogress.go
New
func New(optionals ...int) Progress { if len(optionals) > 0 { if optionals[0] < 0 { panic(ErrBadSize) } return Progress{pre: "Progress", state: "|", sOutput: optionals[0]} } return Progress{pre: "Progress", state: "|"} }
go
func New(optionals ...int) Progress { if len(optionals) > 0 { if optionals[0] < 0 { panic(ErrBadSize) } return Progress{pre: "Progress", state: "|", sOutput: optionals[0]} } return Progress{pre: "Progress", state: "|"} }
[ "func", "New", "(", "optionals", "...", "int", ")", "Progress", "{", "if", "len", "(", "optionals", ")", ">", "0", "{", "if", "optionals", "[", "0", "]", "<", "0", "{", "panic", "(", "ErrBadSize", ")", "\n", "}", "\n", "return", "Progress", "{", ...
// New Progress structure
[ "New", "Progress", "structure" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/progress/sprogress.go#L25-L33
13,047
0xrawsec/golang-utils
progress/sprogress.go
Update
func (p *Progress) Update(message string) { switch p.state { case "|": p.state = "/" case "/": p.state = "-" case "-": p.state = "\\" case "\\": p.state = "|" } if message != "" { p.message = message } }
go
func (p *Progress) Update(message string) { switch p.state { case "|": p.state = "/" case "/": p.state = "-" case "-": p.state = "\\" case "\\": p.state = "|" } if message != "" { p.message = message } }
[ "func", "(", "p", "*", "Progress", ")", "Update", "(", "message", "string", ")", "{", "switch", "p", ".", "state", "{", "case", "\"", "\"", ":", "p", ".", "state", "=", "\"", "\"", "\n", "case", "\"", "\"", ":", "p", ".", "state", "=", "\"", ...
//Update the status of the Progress
[ "Update", "the", "status", "of", "the", "Progress" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/progress/sprogress.go#L41-L55
13,048
0xrawsec/golang-utils
progress/sprogress.go
Print
func (p *Progress) Print(optionals ...bool) { stream := os.Stderr if len(optionals) > 0 { if optionals[0] { stream = os.Stdout } } f := bufio.NewWriter(stream) defer f.Flush() f.WriteString(fmt.Sprintf("% *s\r", p.sOutput, "")) f.WriteString(p.String() + "\r") }
go
func (p *Progress) Print(optionals ...bool) { stream := os.Stderr if len(optionals) > 0 { if optionals[0] { stream = os.Stdout } } f := bufio.NewWriter(stream) defer f.Flush() f.WriteString(fmt.Sprintf("% *s\r", p.sOutput, "")) f.WriteString(p.String() + "\r") }
[ "func", "(", "p", "*", "Progress", ")", "Print", "(", "optionals", "...", "bool", ")", "{", "stream", ":=", "os", ".", "Stderr", "\n", "if", "len", "(", "optionals", ")", ">", "0", "{", "if", "optionals", "[", "0", "]", "{", "stream", "=", "os", ...
// Print Progress structure on stderr or stdout if the first optional argument // is true
[ "Print", "Progress", "structure", "on", "stderr", "or", "stdout", "if", "the", "first", "optional", "argument", "is", "true" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/progress/sprogress.go#L76-L87
13,049
0xrawsec/golang-utils
fsutil/fsutil.go
IsLink
func IsLink(path string) bool { s, err := os.Stat(path) if err != nil { return false } return (s.Mode()&os.ModeSymlink == os.ModeSymlink) }
go
func IsLink(path string) bool { s, err := os.Stat(path) if err != nil { return false } return (s.Mode()&os.ModeSymlink == os.ModeSymlink) }
[ "func", "IsLink", "(", "path", "string", ")", "bool", "{", "s", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "(", "s", ".", "Mode", "(", ")", "&", "o...
// IsLink returns true if path is a Symlink
[ "IsLink", "returns", "true", "if", "path", "is", "a", "Symlink" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/fsutil.go#L95-L101
13,050
0xrawsec/golang-utils
fsutil/fsutil.go
ResolveLink
func ResolveLink(path string) (string, error) { if IsLink(path) { return os.Readlink(path) } return path, nil }
go
func ResolveLink(path string) (string, error) { if IsLink(path) { return os.Readlink(path) } return path, nil }
[ "func", "ResolveLink", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "if", "IsLink", "(", "path", ")", "{", "return", "os", ".", "Readlink", "(", "path", ")", "\n", "}", "\n", "return", "path", ",", "nil", "\n", "}" ]
// ResolveLink resolves the link if it is a Link or return the original path
[ "ResolveLink", "resolves", "the", "link", "if", "it", "is", "a", "Link", "or", "return", "the", "original", "path" ]
817f34752728629396193de0249e187c6ab1c5cb
https://github.com/0xrawsec/golang-utils/blob/817f34752728629396193de0249e187c6ab1c5cb/fsutil/fsutil.go#L114-L119
13,051
abiosoft/semaphore
semaphore.go
New
func New(permits int) *Semaphore { if permits < 1 { panic("Invalid number of permits. Less than 1") } // fill channel buffer channel := make(chan struct{}, permits) for i := 0; i < permits; i++ { channel <- struct{}{} } return &Semaphore{ permits: permits, avail: permits, channel: channel, } }
go
func New(permits int) *Semaphore { if permits < 1 { panic("Invalid number of permits. Less than 1") } // fill channel buffer channel := make(chan struct{}, permits) for i := 0; i < permits; i++ { channel <- struct{}{} } return &Semaphore{ permits: permits, avail: permits, channel: channel, } }
[ "func", "New", "(", "permits", "int", ")", "*", "Semaphore", "{", "if", "permits", "<", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// fill channel buffer", "channel", ":=", "make", "(", "chan", "struct", "{", "}", ",", "permits", ")...
// New creates a new Semaphore with specified number of permits.
[ "New", "creates", "a", "new", "Semaphore", "with", "specified", "number", "of", "permits", "." ]
cb737ff681bd644054d04b9e420135e01179114d
https://github.com/abiosoft/semaphore/blob/cb737ff681bd644054d04b9e420135e01179114d/semaphore.go#L20-L36
13,052
abiosoft/semaphore
semaphore.go
Acquire
func (s *Semaphore) Acquire() { s.aMutex.Lock() defer s.aMutex.Unlock() s.pMutex.Lock() s.avail-- s.pMutex.Unlock() <-s.channel }
go
func (s *Semaphore) Acquire() { s.aMutex.Lock() defer s.aMutex.Unlock() s.pMutex.Lock() s.avail-- s.pMutex.Unlock() <-s.channel }
[ "func", "(", "s", "*", "Semaphore", ")", "Acquire", "(", ")", "{", "s", ".", "aMutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "aMutex", ".", "Unlock", "(", ")", "\n\n", "s", ".", "pMutex", ".", "Lock", "(", ")", "\n", "s", ".", "avai...
// Acquire acquires one permit. If it is not available, the goroutine will block until it is available.
[ "Acquire", "acquires", "one", "permit", ".", "If", "it", "is", "not", "available", "the", "goroutine", "will", "block", "until", "it", "is", "available", "." ]
cb737ff681bd644054d04b9e420135e01179114d
https://github.com/abiosoft/semaphore/blob/cb737ff681bd644054d04b9e420135e01179114d/semaphore.go#L39-L48
13,053
abiosoft/semaphore
semaphore.go
Release
func (s *Semaphore) Release() { s.rMutex.Lock() defer s.rMutex.Unlock() s.channel <- struct{}{} s.pMutex.Lock() s.avail++ s.pMutex.Unlock() }
go
func (s *Semaphore) Release() { s.rMutex.Lock() defer s.rMutex.Unlock() s.channel <- struct{}{} s.pMutex.Lock() s.avail++ s.pMutex.Unlock() }
[ "func", "(", "s", "*", "Semaphore", ")", "Release", "(", ")", "{", "s", ".", "rMutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "rMutex", ".", "Unlock", "(", ")", "\n\n", "s", ".", "channel", "<-", "struct", "{", "}", "{", "}", "\n\n", ...
// Release releases one permit.
[ "Release", "releases", "one", "permit", "." ]
cb737ff681bd644054d04b9e420135e01179114d
https://github.com/abiosoft/semaphore/blob/cb737ff681bd644054d04b9e420135e01179114d/semaphore.go#L99-L108
13,054
abiosoft/semaphore
semaphore.go
AvailablePermits
func (s *Semaphore) AvailablePermits() int { s.pMutex.RLock() defer s.pMutex.RUnlock() if s.avail < 0 { return 0 } return s.avail }
go
func (s *Semaphore) AvailablePermits() int { s.pMutex.RLock() defer s.pMutex.RUnlock() if s.avail < 0 { return 0 } return s.avail }
[ "func", "(", "s", "*", "Semaphore", ")", "AvailablePermits", "(", ")", "int", "{", "s", ".", "pMutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "pMutex", ".", "RUnlock", "(", ")", "\n\n", "if", "s", ".", "avail", "<", "0", "{", "return", ...
// AvailablePermits gives number of available unacquired permits.
[ "AvailablePermits", "gives", "number", "of", "available", "unacquired", "permits", "." ]
cb737ff681bd644054d04b9e420135e01179114d
https://github.com/abiosoft/semaphore/blob/cb737ff681bd644054d04b9e420135e01179114d/semaphore.go#L125-L133
13,055
abiosoft/semaphore
semaphore.go
DrainPermits
func (s *Semaphore) DrainPermits() int { n := s.AvailablePermits() if n > 0 { s.AcquireMany(n) } return n }
go
func (s *Semaphore) DrainPermits() int { n := s.AvailablePermits() if n > 0 { s.AcquireMany(n) } return n }
[ "func", "(", "s", "*", "Semaphore", ")", "DrainPermits", "(", ")", "int", "{", "n", ":=", "s", ".", "AvailablePermits", "(", ")", "\n", "if", "n", ">", "0", "{", "s", ".", "AcquireMany", "(", "n", ")", "\n", "}", "\n", "return", "n", "\n", "}" ...
// DrainPermits acquires all available permits and return the number of permits acquired.
[ "DrainPermits", "acquires", "all", "available", "permits", "and", "return", "the", "number", "of", "permits", "acquired", "." ]
cb737ff681bd644054d04b9e420135e01179114d
https://github.com/abiosoft/semaphore/blob/cb737ff681bd644054d04b9e420135e01179114d/semaphore.go#L136-L142
13,056
hopkinsth/go-ruler
ruler.go
NewRulerWithJson
func NewRulerWithJson(jsonstr []byte) (*Ruler, error) { var rules []*Rule err := json.Unmarshal(jsonstr, &rules) if err != nil { return nil, err } return NewRuler(rules), nil }
go
func NewRulerWithJson(jsonstr []byte) (*Ruler, error) { var rules []*Rule err := json.Unmarshal(jsonstr, &rules) if err != nil { return nil, err } return NewRuler(rules), nil }
[ "func", "NewRulerWithJson", "(", "jsonstr", "[", "]", "byte", ")", "(", "*", "Ruler", ",", "error", ")", "{", "var", "rules", "[", "]", "*", "Rule", "\n\n", "err", ":=", "json", ".", "Unmarshal", "(", "jsonstr", ",", "&", "rules", ")", "\n", "if", ...
// returns a new ruler with filters parsed from JSON data // expects JSON as a slice of bytes and will parse your JSON for you!
[ "returns", "a", "new", "ruler", "with", "filters", "parsed", "from", "JSON", "data", "expects", "JSON", "as", "a", "slice", "of", "bytes", "and", "will", "parse", "your", "JSON", "for", "you!" ]
6e651a652de80d6923a6b7fa6de1666d7b470559
https://github.com/hopkinsth/go-ruler/blob/6e651a652de80d6923a6b7fa6de1666d7b470559/ruler.go#L50-L59
13,057
hopkinsth/go-ruler
ruler.go
Rule
func (r *Ruler) Rule(path string) *RulerRule { rule := &Rule{ "", path, nil, } r.rules = append(r.rules, rule) return &RulerRule{ r, rule, } }
go
func (r *Ruler) Rule(path string) *RulerRule { rule := &Rule{ "", path, nil, } r.rules = append(r.rules, rule) return &RulerRule{ r, rule, } }
[ "func", "(", "r", "*", "Ruler", ")", "Rule", "(", "path", "string", ")", "*", "RulerRule", "{", "rule", ":=", "&", "Rule", "{", "\"", "\"", ",", "path", ",", "nil", ",", "}", "\n\n", "r", ".", "rules", "=", "append", "(", "r", ".", "rules", "...
// adds a new rule for the property at `path` // returns a RulerFilter that you can use to add conditions // and more filters
[ "adds", "a", "new", "rule", "for", "the", "property", "at", "path", "returns", "a", "RulerFilter", "that", "you", "can", "use", "to", "add", "conditions", "and", "more", "filters" ]
6e651a652de80d6923a6b7fa6de1666d7b470559
https://github.com/hopkinsth/go-ruler/blob/6e651a652de80d6923a6b7fa6de1666d7b470559/ruler.go#L64-L77
13,058
hopkinsth/go-ruler
ruler.go
compare
func (r *Ruler) compare(f *Rule, actual interface{}) bool { ruleDebug("beginning comparison") expected := f.Value switch f.Comparator { case "eq": return actual == expected case "neq": return actual != expected case "gt": return r.inequality(gt, actual, expected) case "gte": return r.inequality(gte, actual, expected) case "lt": return r.inequality(lt, actual, expected) case "lte": return r.inequality(lte, actual, expected) case "exists": // not sure this makes complete sense return actual != nil case "nexists": return actual == nil case "regex": fallthrough case "contains": fallthrough case "matches": return r.regexp(actual, expected) case "ncontains": return !r.regexp(actual, expected) default: //should probably return an error or something //but this is good for now //if comparator is not implemented, return false ruleDebug("unknown comparator %s", f.Comparator) return false } }
go
func (r *Ruler) compare(f *Rule, actual interface{}) bool { ruleDebug("beginning comparison") expected := f.Value switch f.Comparator { case "eq": return actual == expected case "neq": return actual != expected case "gt": return r.inequality(gt, actual, expected) case "gte": return r.inequality(gte, actual, expected) case "lt": return r.inequality(lt, actual, expected) case "lte": return r.inequality(lte, actual, expected) case "exists": // not sure this makes complete sense return actual != nil case "nexists": return actual == nil case "regex": fallthrough case "contains": fallthrough case "matches": return r.regexp(actual, expected) case "ncontains": return !r.regexp(actual, expected) default: //should probably return an error or something //but this is good for now //if comparator is not implemented, return false ruleDebug("unknown comparator %s", f.Comparator) return false } }
[ "func", "(", "r", "*", "Ruler", ")", "compare", "(", "f", "*", "Rule", ",", "actual", "interface", "{", "}", ")", "bool", "{", "ruleDebug", "(", "\"", "\"", ")", "\n", "expected", ":=", "f", ".", "Value", "\n", "switch", "f", ".", "Comparator", "...
// compares real v. actual values
[ "compares", "real", "v", ".", "actual", "values" ]
6e651a652de80d6923a6b7fa6de1666d7b470559
https://github.com/hopkinsth/go-ruler/blob/6e651a652de80d6923a6b7fa6de1666d7b470559/ruler.go#L114-L159
13,059
hopkinsth/go-ruler
ruler.go
inequality
func (r *Ruler) inequality(op int, actual, expected interface{}) bool { // need some variables for these deals ruleDebug("entered inequality comparison") var cmpStr [2]string var cmpUint [2]uint64 var cmpInt [2]int64 var cmpFloat [2]float64 for idx, i := range []interface{}{actual, expected} { switch t := i.(type) { case uint8: cmpUint[idx] = uint64(t) case uint16: cmpUint[idx] = uint64(t) case uint32: cmpUint[idx] = uint64(t) case uint64: cmpUint[idx] = t case uint: cmpUint[idx] = uint64(t) case int8: cmpInt[idx] = int64(t) case int16: cmpInt[idx] = int64(t) case int32: cmpInt[idx] = int64(t) case int64: cmpInt[idx] = t case int: cmpInt[idx] = int64(t) case float32: cmpFloat[idx] = float64(t) case float64: cmpFloat[idx] = t case string: cmpStr[idx] = t default: ruleDebug("invalid type for inequality comparison") return false } } // whichever of these works, we're happy with // but if you're trying to compare a string to an int, oh well! switch op { case gt: return cmpStr[0] > cmpStr[1] || cmpUint[0] > cmpUint[1] || cmpInt[0] > cmpInt[1] || cmpFloat[0] > cmpFloat[1] case gte: return cmpStr[0] >= cmpStr[1] || cmpUint[0] >= cmpUint[1] || cmpInt[0] >= cmpInt[1] || cmpFloat[0] >= cmpFloat[1] case lt: return cmpStr[0] < cmpStr[1] || cmpUint[0] < cmpUint[1] || cmpInt[0] < cmpInt[1] || cmpFloat[0] < cmpFloat[1] case lte: return cmpStr[0] <= cmpStr[1] || cmpUint[0] <= cmpUint[1] || cmpInt[0] <= cmpInt[1] || cmpFloat[0] <= cmpFloat[1] } return false }
go
func (r *Ruler) inequality(op int, actual, expected interface{}) bool { // need some variables for these deals ruleDebug("entered inequality comparison") var cmpStr [2]string var cmpUint [2]uint64 var cmpInt [2]int64 var cmpFloat [2]float64 for idx, i := range []interface{}{actual, expected} { switch t := i.(type) { case uint8: cmpUint[idx] = uint64(t) case uint16: cmpUint[idx] = uint64(t) case uint32: cmpUint[idx] = uint64(t) case uint64: cmpUint[idx] = t case uint: cmpUint[idx] = uint64(t) case int8: cmpInt[idx] = int64(t) case int16: cmpInt[idx] = int64(t) case int32: cmpInt[idx] = int64(t) case int64: cmpInt[idx] = t case int: cmpInt[idx] = int64(t) case float32: cmpFloat[idx] = float64(t) case float64: cmpFloat[idx] = t case string: cmpStr[idx] = t default: ruleDebug("invalid type for inequality comparison") return false } } // whichever of these works, we're happy with // but if you're trying to compare a string to an int, oh well! switch op { case gt: return cmpStr[0] > cmpStr[1] || cmpUint[0] > cmpUint[1] || cmpInt[0] > cmpInt[1] || cmpFloat[0] > cmpFloat[1] case gte: return cmpStr[0] >= cmpStr[1] || cmpUint[0] >= cmpUint[1] || cmpInt[0] >= cmpInt[1] || cmpFloat[0] >= cmpFloat[1] case lt: return cmpStr[0] < cmpStr[1] || cmpUint[0] < cmpUint[1] || cmpInt[0] < cmpInt[1] || cmpFloat[0] < cmpFloat[1] case lte: return cmpStr[0] <= cmpStr[1] || cmpUint[0] <= cmpUint[1] || cmpInt[0] <= cmpInt[1] || cmpFloat[0] <= cmpFloat[1] } return false }
[ "func", "(", "r", "*", "Ruler", ")", "inequality", "(", "op", "int", ",", "actual", ",", "expected", "interface", "{", "}", ")", "bool", "{", "// need some variables for these deals", "ruleDebug", "(", "\"", "\"", ")", "\n", "var", "cmpStr", "[", "2", "]...
// runs equality comparison // separated in a different function because // we need to do another type assertion here // and some other acrobatics
[ "runs", "equality", "comparison", "separated", "in", "a", "different", "function", "because", "we", "need", "to", "do", "another", "type", "assertion", "here", "and", "some", "other", "acrobatics" ]
6e651a652de80d6923a6b7fa6de1666d7b470559
https://github.com/hopkinsth/go-ruler/blob/6e651a652de80d6923a6b7fa6de1666d7b470559/ruler.go#L165-L233
13,060
hopkinsth/go-ruler
rule.go
compare
func (rf *RulerRule) compare(comp int, value interface{}) *RulerRule { var comparator string switch comp { case eq: comparator = "eq" case neq: comparator = "neq" case lt: comparator = "lt" case lte: comparator = "lte" case gt: comparator = "gt" case gte: comparator = "gte" case contains: comparator = "contains" case matches: comparator = "matches" case ncontains: comparator = "ncontains" } // if this thing has a comparator already, we need to make a new ruler filter if rf.Comparator != "" { rf = &RulerRule{ rf.Ruler, &Rule{ comparator, rf.Path, value, }, } // attach the new filter to the ruler rf.Ruler.rules = append(rf.Ruler.rules, rf.Rule) } else { //if there is no comparator, we can just set things on the current filter rf.Comparator = comparator rf.Value = value } return rf }
go
func (rf *RulerRule) compare(comp int, value interface{}) *RulerRule { var comparator string switch comp { case eq: comparator = "eq" case neq: comparator = "neq" case lt: comparator = "lt" case lte: comparator = "lte" case gt: comparator = "gt" case gte: comparator = "gte" case contains: comparator = "contains" case matches: comparator = "matches" case ncontains: comparator = "ncontains" } // if this thing has a comparator already, we need to make a new ruler filter if rf.Comparator != "" { rf = &RulerRule{ rf.Ruler, &Rule{ comparator, rf.Path, value, }, } // attach the new filter to the ruler rf.Ruler.rules = append(rf.Ruler.rules, rf.Rule) } else { //if there is no comparator, we can just set things on the current filter rf.Comparator = comparator rf.Value = value } return rf }
[ "func", "(", "rf", "*", "RulerRule", ")", "compare", "(", "comp", "int", ",", "value", "interface", "{", "}", ")", "*", "RulerRule", "{", "var", "comparator", "string", "\n", "switch", "comp", "{", "case", "eq", ":", "comparator", "=", "\"", "\"", "\...
// comparator will either create a new ruler filter and add its filter
[ "comparator", "will", "either", "create", "a", "new", "ruler", "filter", "and", "add", "its", "filter" ]
6e651a652de80d6923a6b7fa6de1666d7b470559
https://github.com/hopkinsth/go-ruler/blob/6e651a652de80d6923a6b7fa6de1666d7b470559/rule.go#L80-L122
13,061
fabric8-services/fabric8-wit
controller/work_item_events.go
NewEventsController
func NewEventsController(service *goa.Service, db application.DB, config EventsControllerConfig) *EventsController { return &EventsController{ Controller: service.NewController("EventsController"), db: db, config: config} }
go
func NewEventsController(service *goa.Service, db application.DB, config EventsControllerConfig) *EventsController { return &EventsController{ Controller: service.NewController("EventsController"), db: db, config: config} }
[ "func", "NewEventsController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "EventsControllerConfig", ")", "*", "EventsController", "{", "return", "&", "EventsController", "{", "Controller", ":", "service", ".",...
// NewEventsController creates a work_item_events controller.
[ "NewEventsController", "creates", "a", "work_item_events", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_events.go#L32-L37
13,062
fabric8-services/fabric8-wit
controller/work_item_events.go
ConvertEvents
func ConvertEvents(ctx context.Context, appl application.Application, request *http.Request, eventList []event.Event, wiID uuid.UUID) ([]*app.Event, error) { var ls = []*app.Event{} for _, i := range eventList { converted, err := ConvertEvent(ctx, appl, request, i, wiID) if err != nil { return nil, errs.Wrapf(err, "failed to convert event: %+v", i) } ls = append(ls, converted) } return ls, nil }
go
func ConvertEvents(ctx context.Context, appl application.Application, request *http.Request, eventList []event.Event, wiID uuid.UUID) ([]*app.Event, error) { var ls = []*app.Event{} for _, i := range eventList { converted, err := ConvertEvent(ctx, appl, request, i, wiID) if err != nil { return nil, errs.Wrapf(err, "failed to convert event: %+v", i) } ls = append(ls, converted) } return ls, nil }
[ "func", "ConvertEvents", "(", "ctx", "context", ".", "Context", ",", "appl", "application", ".", "Application", ",", "request", "*", "http", ".", "Request", ",", "eventList", "[", "]", "event", ".", "Event", ",", "wiID", "uuid", ".", "UUID", ")", "(", ...
// ConvertEvents from internal to external REST representation
[ "ConvertEvents", "from", "internal", "to", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_events.go#L71-L81
13,063
fabric8-services/fabric8-wit
notification/notification.go
NewWorkItemCreated
func NewWorkItemCreated(workitemID string, revisionID uuid.UUID) Message { return Message{ MessageID: uuid.NewV4(), MessageType: "workitem.create", TargetID: workitemID, Custom: map[string]interface{}{"revision_id": revisionID}, } }
go
func NewWorkItemCreated(workitemID string, revisionID uuid.UUID) Message { return Message{ MessageID: uuid.NewV4(), MessageType: "workitem.create", TargetID: workitemID, Custom: map[string]interface{}{"revision_id": revisionID}, } }
[ "func", "NewWorkItemCreated", "(", "workitemID", "string", ",", "revisionID", "uuid", ".", "UUID", ")", "Message", "{", "return", "Message", "{", "MessageID", ":", "uuid", ".", "NewV4", "(", ")", ",", "MessageType", ":", "\"", "\"", ",", "TargetID", ":", ...
// NewWorkItemCreated creates a new message instance for the newly created WorkItemID
[ "NewWorkItemCreated", "creates", "a", "new", "message", "instance", "for", "the", "newly", "created", "WorkItemID" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/notification/notification.go#L40-L47
13,064
fabric8-services/fabric8-wit
notification/notification.go
NewCommentCreated
func NewCommentCreated(commentID string) Message { return Message{MessageID: uuid.NewV4(), MessageType: "comment.create", TargetID: commentID} }
go
func NewCommentCreated(commentID string) Message { return Message{MessageID: uuid.NewV4(), MessageType: "comment.create", TargetID: commentID} }
[ "func", "NewCommentCreated", "(", "commentID", "string", ")", "Message", "{", "return", "Message", "{", "MessageID", ":", "uuid", ".", "NewV4", "(", ")", ",", "MessageType", ":", "\"", "\"", ",", "TargetID", ":", "commentID", "}", "\n", "}" ]
// NewCommentCreated creates a new message instance for the newly created CommentID
[ "NewCommentCreated", "creates", "a", "new", "message", "instance", "for", "the", "newly", "created", "CommentID" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/notification/notification.go#L60-L62
13,065
fabric8-services/fabric8-wit
notification/notification.go
NewServiceChannel
func NewServiceChannel(config ServiceConfiguration) (Channel, error) { err := validateConfig(config) if err != nil { return nil, err } return &Service{config: config}, nil }
go
func NewServiceChannel(config ServiceConfiguration) (Channel, error) { err := validateConfig(config) if err != nil { return nil, err } return &Service{config: config}, nil }
[ "func", "NewServiceChannel", "(", "config", "ServiceConfiguration", ")", "(", "Channel", ",", "error", ")", "{", "err", ":=", "validateConfig", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return...
// NewServiceChannel sends notification messages to the fabric8-notification service
[ "NewServiceChannel", "sends", "notification", "messages", "to", "the", "fabric8", "-", "notification", "service" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/notification/notification.go#L102-L108
13,066
fabric8-services/fabric8-wit
notification/notification.go
Send
func (s *Service) Send(ctx context.Context, msg Message) { go func(ctx context.Context, msg Message) { setCurrentIdentity(ctx, &msg) u, err := url.Parse(s.config.GetNotificationServiceURL()) if err != nil { log.Error(ctx, map[string]interface{}{ "url": s.config.GetNotificationServiceURL(), "err": err, }, "unable to parse GetNotificationServiceURL") } cl := client.New(goaclient.HTTPClientDoer(http.DefaultClient)) cl.Host = u.Host cl.Scheme = u.Scheme cl.SetJWTSigner(goasupport.NewForwardSigner(ctx)) msgID := goauuid.UUID(msg.MessageID) resp, err := cl.SendNotify( goasupport.ForwardContextRequestID(ctx), client.SendNotifyPath(), &client.SendNotifyPayload{ Data: &client.Notification{ Type: "notifications", ID: &msgID, Attributes: &client.NotificationAttributes{ Type: msg.MessageType, ID: msg.TargetID, Custom: msg.Custom, }, }, }, ) if err != nil { log.Error(ctx, map[string]interface{}{ "message_id": msg.MessageID, "type": msg.MessageType, "target_id": msg.TargetID, "err": err, }, "unable to send notification") } else if resp.StatusCode >= 400 { log.Error(ctx, map[string]interface{}{ "status": resp.StatusCode, "message_id": msg.MessageID, "type": msg.MessageType, "target_id": msg.TargetID, "err": err, }, "unexpected response code") } defer rest.CloseResponse(resp) }(ctx, msg) }
go
func (s *Service) Send(ctx context.Context, msg Message) { go func(ctx context.Context, msg Message) { setCurrentIdentity(ctx, &msg) u, err := url.Parse(s.config.GetNotificationServiceURL()) if err != nil { log.Error(ctx, map[string]interface{}{ "url": s.config.GetNotificationServiceURL(), "err": err, }, "unable to parse GetNotificationServiceURL") } cl := client.New(goaclient.HTTPClientDoer(http.DefaultClient)) cl.Host = u.Host cl.Scheme = u.Scheme cl.SetJWTSigner(goasupport.NewForwardSigner(ctx)) msgID := goauuid.UUID(msg.MessageID) resp, err := cl.SendNotify( goasupport.ForwardContextRequestID(ctx), client.SendNotifyPath(), &client.SendNotifyPayload{ Data: &client.Notification{ Type: "notifications", ID: &msgID, Attributes: &client.NotificationAttributes{ Type: msg.MessageType, ID: msg.TargetID, Custom: msg.Custom, }, }, }, ) if err != nil { log.Error(ctx, map[string]interface{}{ "message_id": msg.MessageID, "type": msg.MessageType, "target_id": msg.TargetID, "err": err, }, "unable to send notification") } else if resp.StatusCode >= 400 { log.Error(ctx, map[string]interface{}{ "status": resp.StatusCode, "message_id": msg.MessageID, "type": msg.MessageType, "target_id": msg.TargetID, "err": err, }, "unexpected response code") } defer rest.CloseResponse(resp) }(ctx, msg) }
[ "func", "(", "s", "*", "Service", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "msg", "Message", ")", "{", "go", "func", "(", "ctx", "context", ".", "Context", ",", "msg", "Message", ")", "{", "setCurrentIdentity", "(", "ctx", ",", "&", ...
// Send invokes the fabric8-notification API
[ "Send", "invokes", "the", "fabric8", "-", "notification", "API" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/notification/notification.go#L111-L164
13,067
fabric8-services/fabric8-wit
workitem/link/type.go
Equal
func (t WorkItemLinkType) Equal(u convert.Equaler) bool { other, ok := u.(WorkItemLinkType) if !ok { return false } if t.ID != other.ID { return false } if t.Name != other.Name { return false } if t.Version != other.Version { return false } if !convert.CascadeEqual(t.Lifecycle, other.Lifecycle) { return false } if !reflect.DeepEqual(t.Description, other.Description) { return false } if !reflect.DeepEqual(t.ForwardDescription, other.ForwardDescription) { return false } if !reflect.DeepEqual(t.ReverseDescription, other.ReverseDescription) { return false } if t.Topology != other.Topology { return false } if t.ForwardName != other.ForwardName { return false } if t.ReverseName != other.ReverseName { return false } if t.SpaceTemplateID != other.SpaceTemplateID { return false } return true }
go
func (t WorkItemLinkType) Equal(u convert.Equaler) bool { other, ok := u.(WorkItemLinkType) if !ok { return false } if t.ID != other.ID { return false } if t.Name != other.Name { return false } if t.Version != other.Version { return false } if !convert.CascadeEqual(t.Lifecycle, other.Lifecycle) { return false } if !reflect.DeepEqual(t.Description, other.Description) { return false } if !reflect.DeepEqual(t.ForwardDescription, other.ForwardDescription) { return false } if !reflect.DeepEqual(t.ReverseDescription, other.ReverseDescription) { return false } if t.Topology != other.Topology { return false } if t.ForwardName != other.ForwardName { return false } if t.ReverseName != other.ReverseName { return false } if t.SpaceTemplateID != other.SpaceTemplateID { return false } return true }
[ "func", "(", "t", "WorkItemLinkType", ")", "Equal", "(", "u", "convert", ".", "Equaler", ")", "bool", "{", "other", ",", "ok", ":=", "u", ".", "(", "WorkItemLinkType", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", "t", ...
// Equal returns true if two WorkItemLinkType objects are equal; otherwise false is returned.
[ "Equal", "returns", "true", "if", "two", "WorkItemLinkType", "objects", "are", "equal", ";", "otherwise", "false", "is", "returned", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/link/type.go#L43-L82
13,068
fabric8-services/fabric8-wit
workitem/link/type.go
CheckValidForCreation
func (t *WorkItemLinkType) CheckValidForCreation() error { if t.Name == "" { return errors.NewBadParameterError("name", t.Name) } if t.ForwardName == "" { return errors.NewBadParameterError("forward_name", t.ForwardName) } if t.ReverseName == "" { return errors.NewBadParameterError("reverse_name", t.ReverseName) } if err := t.Topology.CheckValid(); err != nil { return errs.WithStack(err) } if t.SpaceTemplateID == uuid.Nil { return errors.NewBadParameterError("space_template_id", t.SpaceTemplateID) } return nil }
go
func (t *WorkItemLinkType) CheckValidForCreation() error { if t.Name == "" { return errors.NewBadParameterError("name", t.Name) } if t.ForwardName == "" { return errors.NewBadParameterError("forward_name", t.ForwardName) } if t.ReverseName == "" { return errors.NewBadParameterError("reverse_name", t.ReverseName) } if err := t.Topology.CheckValid(); err != nil { return errs.WithStack(err) } if t.SpaceTemplateID == uuid.Nil { return errors.NewBadParameterError("space_template_id", t.SpaceTemplateID) } return nil }
[ "func", "(", "t", "*", "WorkItemLinkType", ")", "CheckValidForCreation", "(", ")", "error", "{", "if", "t", ".", "Name", "==", "\"", "\"", "{", "return", "errors", ".", "NewBadParameterError", "(", "\"", "\"", ",", "t", ".", "Name", ")", "\n", "}", "...
// CheckValidForCreation returns an error if the work item link type cannot be // used for the creation of a new work item link type.
[ "CheckValidForCreation", "returns", "an", "error", "if", "the", "work", "item", "link", "type", "cannot", "be", "used", "for", "the", "creation", "of", "a", "new", "work", "item", "link", "type", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/link/type.go#L97-L114
13,069
fabric8-services/fabric8-wit
controller/codebase.go
NewCodebaseController
func NewCodebaseController(service *goa.Service, db application.DB, config codebaseConfiguration) *CodebaseController { return &CodebaseController{ Controller: service.NewController("CodebaseController"), db: db, config: config, } }
go
func NewCodebaseController(service *goa.Service, db application.DB, config codebaseConfiguration) *CodebaseController { return &CodebaseController{ Controller: service.NewController("CodebaseController"), db: db, config: config, } }
[ "func", "NewCodebaseController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "codebaseConfiguration", ")", "*", "CodebaseController", "{", "return", "&", "CodebaseController", "{", "Controller", ":", "service", ...
// NewCodebaseController creates a codebase controller.
[ "NewCodebaseController", "creates", "a", "codebase", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L51-L57
13,070
fabric8-services/fabric8-wit
controller/codebase.go
Update
func (c *CodebaseController) Update(ctx *app.UpdateCodebaseContext) error { codebaseID, err := uuid.FromString(ctx.CodebaseID) if err != nil { return err } // see if the user is allowed to update this codebase cb, err := c.verifyCodebaseOwner(ctx, codebaseID) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } // set only allowed fields reqAttributes := ctx.Payload.Data.Attributes if reqAttributes.CveScan != nil { cb.CVEScan = *reqAttributes.CveScan } if reqAttributes.StackID != nil { cb.StackID = reqAttributes.StackID } if reqAttributes.Type != nil { cb.Type = *reqAttributes.Type } var updatedCb *codebase.Codebase // now save the object back into the database err = application.Transactional(c.db, func(appl application.Application) error { updatedCb, err = appl.Codebases().Save(ctx, cb) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } res := &app.CodebaseSingle{ Data: ConvertCodebase(ctx.Request, *updatedCb), } ctx.ResponseData.Header().Set("Location", rest.AbsoluteURL(ctx.Request, app.CodebaseHref(res.Data.ID))) return ctx.OK(res) }
go
func (c *CodebaseController) Update(ctx *app.UpdateCodebaseContext) error { codebaseID, err := uuid.FromString(ctx.CodebaseID) if err != nil { return err } // see if the user is allowed to update this codebase cb, err := c.verifyCodebaseOwner(ctx, codebaseID) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } // set only allowed fields reqAttributes := ctx.Payload.Data.Attributes if reqAttributes.CveScan != nil { cb.CVEScan = *reqAttributes.CveScan } if reqAttributes.StackID != nil { cb.StackID = reqAttributes.StackID } if reqAttributes.Type != nil { cb.Type = *reqAttributes.Type } var updatedCb *codebase.Codebase // now save the object back into the database err = application.Transactional(c.db, func(appl application.Application) error { updatedCb, err = appl.Codebases().Save(ctx, cb) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } res := &app.CodebaseSingle{ Data: ConvertCodebase(ctx.Request, *updatedCb), } ctx.ResponseData.Header().Set("Location", rest.AbsoluteURL(ctx.Request, app.CodebaseHref(res.Data.ID))) return ctx.OK(res) }
[ "func", "(", "c", "*", "CodebaseController", ")", "Update", "(", "ctx", "*", "app", ".", "UpdateCodebaseContext", ")", "error", "{", "codebaseID", ",", "err", ":=", "uuid", ".", "FromString", "(", "ctx", ".", "CodebaseID", ")", "\n", "if", "err", "!=", ...
// Update can be used to update the codebase entries to change things like // the cve-scan, stackID, codebase type, rest of the attributes of codebase // will remain same
[ "Update", "can", "be", "used", "to", "update", "the", "codebase", "entries", "to", "change", "things", "like", "the", "cve", "-", "scan", "stackID", "codebase", "type", "rest", "of", "the", "attributes", "of", "codebase", "will", "remain", "same" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L79-L118
13,071
fabric8-services/fabric8-wit
controller/codebase.go
verifyCodebaseOwner
func (c *CodebaseController) verifyCodebaseOwner(ctx context.Context, codebaseID uuid.UUID) (*codebase.Codebase, error) { currentUser, err := login.ContextIdentity(ctx) if err != nil { return nil, goa.ErrUnauthorized(err.Error()) } var cb *codebase.Codebase var cbSpace *space.Space err = application.Transactional(c.db, func(appl application.Application) error { cb, err = appl.Codebases().Load(ctx, codebaseID) if err != nil { return err } cbSpace, err = appl.Spaces().Load(ctx, cb.SpaceID) return err }) if err != nil { return nil, err } if !uuid.Equal(*currentUser, cbSpace.OwnerID) { log.Warn(ctx, map[string]interface{}{ "codebase_id": codebaseID, "space_id": cbSpace.ID, "space_owner": cbSpace.OwnerID, "current_user": *currentUser, }, "user is not the space owner") return nil, errors.NewForbiddenError("user is not the space owner") } return cb, nil }
go
func (c *CodebaseController) verifyCodebaseOwner(ctx context.Context, codebaseID uuid.UUID) (*codebase.Codebase, error) { currentUser, err := login.ContextIdentity(ctx) if err != nil { return nil, goa.ErrUnauthorized(err.Error()) } var cb *codebase.Codebase var cbSpace *space.Space err = application.Transactional(c.db, func(appl application.Application) error { cb, err = appl.Codebases().Load(ctx, codebaseID) if err != nil { return err } cbSpace, err = appl.Spaces().Load(ctx, cb.SpaceID) return err }) if err != nil { return nil, err } if !uuid.Equal(*currentUser, cbSpace.OwnerID) { log.Warn(ctx, map[string]interface{}{ "codebase_id": codebaseID, "space_id": cbSpace.ID, "space_owner": cbSpace.OwnerID, "current_user": *currentUser, }, "user is not the space owner") return nil, errors.NewForbiddenError("user is not the space owner") } return cb, nil }
[ "func", "(", "c", "*", "CodebaseController", ")", "verifyCodebaseOwner", "(", "ctx", "context", ".", "Context", ",", "codebaseID", "uuid", ".", "UUID", ")", "(", "*", "codebase", ".", "Codebase", ",", "error", ")", "{", "currentUser", ",", "err", ":=", "...
// verifyCodebaseOwner makes sure that the users making changes are the ones who own it // this can be called in the update and delete to verify that, if the verification is successful // this function also returns the codebase object corresponding to the codebase id that was passed
[ "verifyCodebaseOwner", "makes", "sure", "that", "the", "users", "making", "changes", "are", "the", "ones", "who", "own", "it", "this", "can", "be", "called", "in", "the", "update", "and", "delete", "to", "verify", "that", "if", "the", "verification", "is", ...
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L203-L231
13,072
fabric8-services/fabric8-wit
controller/codebase.go
Delete
func (c *CodebaseController) Delete(ctx *app.DeleteCodebaseContext) error { // see if the user is allowed to delete this codebase cb, err := c.verifyCodebaseOwner(ctx, ctx.CodebaseID) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } // attempt to remotely delete the Che workspaces ns, err := c.getCheNamespace(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheClient, err := c.NewCheClient(ctx, ns) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } workspaces, err := cheClient.ListWorkspaces(ctx, cb.URL) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } log.Info(ctx, nil, "Found %d workspaces to delete", len(workspaces)) for _, workspace := range workspaces { log.Info(ctx, map[string]interface{}{"codebase_url": cb.URL, "che_namespace": ns, "workspace": workspace.Config.Name, }, "About to delete Che workspace") err = cheClient.DeleteWorkspace(ctx.Context, workspace.Config.Name) if err != nil { log.Error(ctx, map[string]interface{}{ "codebase_url": cb.URL, "che_namespace": ns, "workspace": workspace.Config.Name}, "failed to delete Che workspace: %s", err.Error(), ) } } // delete the local codebase data err = application.Transactional(c.db, func(appl application.Application) error { return appl.Codebases().Delete(ctx, ctx.CodebaseID) }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.NoContent() }
go
func (c *CodebaseController) Delete(ctx *app.DeleteCodebaseContext) error { // see if the user is allowed to delete this codebase cb, err := c.verifyCodebaseOwner(ctx, ctx.CodebaseID) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } // attempt to remotely delete the Che workspaces ns, err := c.getCheNamespace(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheClient, err := c.NewCheClient(ctx, ns) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } workspaces, err := cheClient.ListWorkspaces(ctx, cb.URL) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } log.Info(ctx, nil, "Found %d workspaces to delete", len(workspaces)) for _, workspace := range workspaces { log.Info(ctx, map[string]interface{}{"codebase_url": cb.URL, "che_namespace": ns, "workspace": workspace.Config.Name, }, "About to delete Che workspace") err = cheClient.DeleteWorkspace(ctx.Context, workspace.Config.Name) if err != nil { log.Error(ctx, map[string]interface{}{ "codebase_url": cb.URL, "che_namespace": ns, "workspace": workspace.Config.Name}, "failed to delete Che workspace: %s", err.Error(), ) } } // delete the local codebase data err = application.Transactional(c.db, func(appl application.Application) error { return appl.Codebases().Delete(ctx, ctx.CodebaseID) }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.NoContent() }
[ "func", "(", "c", "*", "CodebaseController", ")", "Delete", "(", "ctx", "*", "app", ".", "DeleteCodebaseContext", ")", "error", "{", "// see if the user is allowed to delete this codebase", "cb", ",", "err", ":=", "c", ".", "verifyCodebaseOwner", "(", "ctx", ",", ...
// Delete deletes the given codebase if the user is authenticated and authorized
[ "Delete", "deletes", "the", "given", "codebase", "if", "the", "user", "is", "authenticated", "and", "authorized" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L234-L281
13,073
fabric8-services/fabric8-wit
controller/codebase.go
Open
func (c *CodebaseController) Open(ctx *app.OpenCodebaseContext) error { _, err := login.ContextIdentity(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error())) } var cb *codebase.Codebase err = application.Transactional(c.db, func(appl application.Application) error { cb, err = appl.Codebases().Load(ctx, ctx.CodebaseID) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } ns, err := c.getCheNamespace(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheClient, err := c.NewCheClient(ctx, ns) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } workspaceResp, err := cheClient.StartExistingWorkspace(ctx, ctx.WorkspaceID) if err != nil { log.Error(ctx, map[string]interface{}{ "codebase_id": cb.ID, "stack_id": cb.StackID, "err": err, }, "unable to open workspaces") if werr, ok := err.(*che.StarterError); ok { log.Error(ctx, map[string]interface{}{ "codebase_id": cb.ID, "stack_id": cb.StackID, "err": err, }, "unable to open workspaces: %s", werr.String()) } return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } err = application.Transactional(c.db, func(appl application.Application) error { cb.LastUsedWorkspace = ctx.WorkspaceID _, err := appl.Codebases().Save(ctx, cb) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } ideURL := workspaceResp.GetHrefByRelOfWorkspaceLink(che.IdeUrlRel) resp := &app.WorkspaceOpen{ Links: &app.WorkspaceOpenLinks{ Open: &ideURL, }, } return ctx.OK(resp) }
go
func (c *CodebaseController) Open(ctx *app.OpenCodebaseContext) error { _, err := login.ContextIdentity(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error())) } var cb *codebase.Codebase err = application.Transactional(c.db, func(appl application.Application) error { cb, err = appl.Codebases().Load(ctx, ctx.CodebaseID) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } ns, err := c.getCheNamespace(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheClient, err := c.NewCheClient(ctx, ns) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } workspaceResp, err := cheClient.StartExistingWorkspace(ctx, ctx.WorkspaceID) if err != nil { log.Error(ctx, map[string]interface{}{ "codebase_id": cb.ID, "stack_id": cb.StackID, "err": err, }, "unable to open workspaces") if werr, ok := err.(*che.StarterError); ok { log.Error(ctx, map[string]interface{}{ "codebase_id": cb.ID, "stack_id": cb.StackID, "err": err, }, "unable to open workspaces: %s", werr.String()) } return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } err = application.Transactional(c.db, func(appl application.Application) error { cb.LastUsedWorkspace = ctx.WorkspaceID _, err := appl.Codebases().Save(ctx, cb) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } ideURL := workspaceResp.GetHrefByRelOfWorkspaceLink(che.IdeUrlRel) resp := &app.WorkspaceOpen{ Links: &app.WorkspaceOpenLinks{ Open: &ideURL, }, } return ctx.OK(resp) }
[ "func", "(", "c", "*", "CodebaseController", ")", "Open", "(", "ctx", "*", "app", ".", "OpenCodebaseContext", ")", "error", "{", "_", ",", "err", ":=", "login", ".", "ContextIdentity", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "...
// Open runs the open action.
[ "Open", "runs", "the", "open", "action", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L351-L405
13,074
fabric8-services/fabric8-wit
controller/codebase.go
ConvertCodebases
func ConvertCodebases(request *http.Request, codebases []codebase.Codebase, options ...CodebaseConvertFunc) []*app.Codebase { result := make([]*app.Codebase, len(codebases)) for i, c := range codebases { result[i] = ConvertCodebase(request, c, options...) } return result }
go
func ConvertCodebases(request *http.Request, codebases []codebase.Codebase, options ...CodebaseConvertFunc) []*app.Codebase { result := make([]*app.Codebase, len(codebases)) for i, c := range codebases { result[i] = ConvertCodebase(request, c, options...) } return result }
[ "func", "ConvertCodebases", "(", "request", "*", "http", ".", "Request", ",", "codebases", "[", "]", "codebase", ".", "Codebase", ",", "options", "...", "CodebaseConvertFunc", ")", "[", "]", "*", "app", ".", "Codebase", "{", "result", ":=", "make", "(", ...
// ConvertCodebases converts between internal and external REST representation
[ "ConvertCodebases", "converts", "between", "internal", "and", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L412-L418
13,075
fabric8-services/fabric8-wit
controller/codebase.go
getBranch
func getBranch(projects []che.WorkspaceProject, codebaseURL string) string { for _, p := range projects { if p.Source.Location == codebaseURL { return p.Source.Parameters.Branch } } return "" }
go
func getBranch(projects []che.WorkspaceProject, codebaseURL string) string { for _, p := range projects { if p.Source.Location == codebaseURL { return p.Source.Parameters.Branch } } return "" }
[ "func", "getBranch", "(", "projects", "[", "]", "che", ".", "WorkspaceProject", ",", "codebaseURL", "string", ")", "string", "{", "for", "_", ",", "p", ":=", "range", "projects", "{", "if", "p", ".", "Source", ".", "Location", "==", "codebaseURL", "{", ...
// GetBranch return branch of the Che project which location matches codebase URL
[ "GetBranch", "return", "branch", "of", "the", "Che", "project", "which", "location", "matches", "codebase", "URL" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L421-L428
13,076
fabric8-services/fabric8-wit
controller/codebase.go
ConvertCodebaseSimple
func ConvertCodebaseSimple(request *http.Request, id interface{}) (*app.GenericData, *app.GenericLinks) { i := fmt.Sprint(id) data := &app.GenericData{ Type: ptr.String(APIStringTypeCodebase), ID: &i, } relatedURL := rest.AbsoluteURL(request, app.CodebaseHref(i)) links := &app.GenericLinks{ Self: &relatedURL, Related: &relatedURL, } return data, links }
go
func ConvertCodebaseSimple(request *http.Request, id interface{}) (*app.GenericData, *app.GenericLinks) { i := fmt.Sprint(id) data := &app.GenericData{ Type: ptr.String(APIStringTypeCodebase), ID: &i, } relatedURL := rest.AbsoluteURL(request, app.CodebaseHref(i)) links := &app.GenericLinks{ Self: &relatedURL, Related: &relatedURL, } return data, links }
[ "func", "ConvertCodebaseSimple", "(", "request", "*", "http", ".", "Request", ",", "id", "interface", "{", "}", ")", "(", "*", "app", ".", "GenericData", ",", "*", "app", ".", "GenericLinks", ")", "{", "i", ":=", "fmt", ".", "Sprint", "(", "id", ")",...
// ConvertCodebaseSimple converts a simple codebase ID into a Generic Relationship
[ "ConvertCodebaseSimple", "converts", "a", "simple", "codebase", "ID", "into", "a", "Generic", "Relationship" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L431-L443
13,077
fabric8-services/fabric8-wit
controller/codebase.go
ConvertCodebase
func ConvertCodebase(request *http.Request, codebase codebase.Codebase, options ...CodebaseConvertFunc) *app.Codebase { relatedURL := rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)) spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(codebase.SpaceID)) workspacesRelatedURL := rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)+"/workspaces") result := &app.Codebase{ Type: APIStringTypeCodebase, ID: &codebase.ID, Attributes: &app.CodebaseAttributes{ CreatedAt: &codebase.CreatedAt, Type: &codebase.Type, URL: &codebase.URL, StackID: codebase.StackID, LastUsedWorkspace: &codebase.LastUsedWorkspace, CveScan: &codebase.CVEScan, }, Relationships: &app.CodebaseRelations{ Space: &app.RelationGeneric{ Data: &app.GenericData{ Type: ptr.String(APIStringTypeSpace), ID: ptr.String(codebase.SpaceID.String()), }, Links: &app.GenericLinks{ Self: &spaceRelatedURL, Related: &spaceRelatedURL, }, }, Workspaces: &app.RelationGeneric{ Links: &app.GenericLinks{ Self: &workspacesRelatedURL, Related: &workspacesRelatedURL, }, }, }, Links: &app.CodebaseLinks{ Self: &relatedURL, Related: &relatedURL, // Deprecated: use 'Workspaces' links instead Edit: ptr.String(rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)+"/edit")), }, } for _, option := range options { option(request, codebase, result) } return result }
go
func ConvertCodebase(request *http.Request, codebase codebase.Codebase, options ...CodebaseConvertFunc) *app.Codebase { relatedURL := rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)) spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(codebase.SpaceID)) workspacesRelatedURL := rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)+"/workspaces") result := &app.Codebase{ Type: APIStringTypeCodebase, ID: &codebase.ID, Attributes: &app.CodebaseAttributes{ CreatedAt: &codebase.CreatedAt, Type: &codebase.Type, URL: &codebase.URL, StackID: codebase.StackID, LastUsedWorkspace: &codebase.LastUsedWorkspace, CveScan: &codebase.CVEScan, }, Relationships: &app.CodebaseRelations{ Space: &app.RelationGeneric{ Data: &app.GenericData{ Type: ptr.String(APIStringTypeSpace), ID: ptr.String(codebase.SpaceID.String()), }, Links: &app.GenericLinks{ Self: &spaceRelatedURL, Related: &spaceRelatedURL, }, }, Workspaces: &app.RelationGeneric{ Links: &app.GenericLinks{ Self: &workspacesRelatedURL, Related: &workspacesRelatedURL, }, }, }, Links: &app.CodebaseLinks{ Self: &relatedURL, Related: &relatedURL, // Deprecated: use 'Workspaces' links instead Edit: ptr.String(rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)+"/edit")), }, } for _, option := range options { option(request, codebase, result) } return result }
[ "func", "ConvertCodebase", "(", "request", "*", "http", ".", "Request", ",", "codebase", "codebase", ".", "Codebase", ",", "options", "...", "CodebaseConvertFunc", ")", "*", "app", ".", "Codebase", "{", "relatedURL", ":=", "rest", ".", "AbsoluteURL", "(", "r...
// ConvertCodebase converts between internal and external REST representation
[ "ConvertCodebase", "converts", "between", "internal", "and", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L446-L491
13,078
fabric8-services/fabric8-wit
controller/codebase.go
CheState
func (c *CodebaseController) CheState(ctx *app.CheStateCodebaseContext) error { ns, err := c.getCheNamespace(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheClient, err := c.NewCheClient(ctx, ns) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheState, err := cheClient.GetCheServerState(ctx) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err, }, "unable to get che server state") if werr, ok := err.(*che.StarterError); ok { log.Error(ctx, map[string]interface{}{ "err": err, }, "unable to get che server state: %s", werr.String()) } return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } isRunning := cheState.Running isMultiTenant := cheState.MultiTenant isClusterFull := cheState.ClusterFull state := app.CheServerState{ Running: &isRunning, MultiTenant: &isMultiTenant, ClusterFull: &isClusterFull, } return ctx.OK(&state) }
go
func (c *CodebaseController) CheState(ctx *app.CheStateCodebaseContext) error { ns, err := c.getCheNamespace(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheClient, err := c.NewCheClient(ctx, ns) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } cheState, err := cheClient.GetCheServerState(ctx) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err, }, "unable to get che server state") if werr, ok := err.(*che.StarterError); ok { log.Error(ctx, map[string]interface{}{ "err": err, }, "unable to get che server state: %s", werr.String()) } return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error())) } isRunning := cheState.Running isMultiTenant := cheState.MultiTenant isClusterFull := cheState.ClusterFull state := app.CheServerState{ Running: &isRunning, MultiTenant: &isMultiTenant, ClusterFull: &isClusterFull, } return ctx.OK(&state) }
[ "func", "(", "c", "*", "CodebaseController", ")", "CheState", "(", "ctx", "*", "app", ".", "CheStateCodebaseContext", ")", "error", "{", "ns", ",", "err", ":=", "c", ".", "getCheNamespace", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return"...
// CheState gets che server state.
[ "CheState", "gets", "che", "server", "state", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L494-L527
13,079
fabric8-services/fabric8-wit
controller/codebase.go
NewDefaultCheClient
func NewDefaultCheClient(config codebaseConfiguration) CodebaseCheClientProvider { return func(ctx context.Context, ns string) (che.Client, error) { cheClient := che.NewStarterClient(config.GetCheStarterURL(), config.GetOpenshiftTenantMasterURL(), ns, http.DefaultClient) return cheClient, nil } }
go
func NewDefaultCheClient(config codebaseConfiguration) CodebaseCheClientProvider { return func(ctx context.Context, ns string) (che.Client, error) { cheClient := che.NewStarterClient(config.GetCheStarterURL(), config.GetOpenshiftTenantMasterURL(), ns, http.DefaultClient) return cheClient, nil } }
[ "func", "NewDefaultCheClient", "(", "config", "codebaseConfiguration", ")", "CodebaseCheClientProvider", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "ns", "string", ")", "(", "che", ".", "Client", ",", "error", ")", "{", "cheClient", ":=...
// NewDefaultCheClient returns the default function to initialize a new Che client with a "regular" http client
[ "NewDefaultCheClient", "returns", "the", "default", "function", "to", "initialize", "a", "new", "Che", "client", "with", "a", "regular", "http", "client" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/codebase.go#L589-L594
13,080
fabric8-services/fabric8-wit
label/label.go
Create
func (m *GormLabelRepository) Create(ctx context.Context, u *Label) error { defer goa.MeasureSince([]string{"goa", "db", "label", "create"}, time.Now()) u.ID = uuid.NewV4() if strings.TrimSpace(u.Name) == "" { return errors.NewBadParameterError("label name cannot be empty string", u.Name).Expected("non empty string") } err := m.db.Create(u).Error if err != nil { // combination of name and space ID should be unique if gormsupport.IsUniqueViolation(err, "labels_name_space_id_unique_idx") { log.Error(ctx, map[string]interface{}{ "err": err, "name": u.Name, "space_id": u.SpaceID, }, "unable to create label because a label with same already exists in the space") return errors.NewDataConflictError(fmt.Sprintf("label already exists with name = %s , space_id = %s", u.Name, u.SpaceID.String())) } log.Error(ctx, map[string]interface{}{}, "error adding Label: %s", err.Error()) return err } return nil }
go
func (m *GormLabelRepository) Create(ctx context.Context, u *Label) error { defer goa.MeasureSince([]string{"goa", "db", "label", "create"}, time.Now()) u.ID = uuid.NewV4() if strings.TrimSpace(u.Name) == "" { return errors.NewBadParameterError("label name cannot be empty string", u.Name).Expected("non empty string") } err := m.db.Create(u).Error if err != nil { // combination of name and space ID should be unique if gormsupport.IsUniqueViolation(err, "labels_name_space_id_unique_idx") { log.Error(ctx, map[string]interface{}{ "err": err, "name": u.Name, "space_id": u.SpaceID, }, "unable to create label because a label with same already exists in the space") return errors.NewDataConflictError(fmt.Sprintf("label already exists with name = %s , space_id = %s", u.Name, u.SpaceID.String())) } log.Error(ctx, map[string]interface{}{}, "error adding Label: %s", err.Error()) return err } return nil }
[ "func", "(", "m", "*", "GormLabelRepository", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "u", "*", "Label", ")", "error", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\""...
// Create a new label
[ "Create", "a", "new", "label" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/label/label.go#L73-L94
13,081
fabric8-services/fabric8-wit
label/label.go
Save
func (m *GormLabelRepository) Save(ctx context.Context, l Label) (*Label, error) { defer goa.MeasureSince([]string{"goa", "db", "label", "save"}, time.Now()) if strings.TrimSpace(l.Name) == "" { return nil, errors.NewBadParameterError("label name cannot be empty string", l.Name).Expected("non empty string") } lbl := Label{} tx := m.db.Where("id = ?", l.ID).First(&lbl) oldVersion := l.Version l.Version = lbl.Version + 1 if tx.RecordNotFound() { log.Error(ctx, map[string]interface{}{ "label_id": l.ID, }, "label cannot be found") return nil, errors.NewNotFoundError("label", l.ID.String()) } if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "label_id": l.ID, "err": err, }, "unknown error happened when searching the label") return nil, errors.NewInternalError(ctx, err) } tx = tx.Where("Version = ?", oldVersion).Save(&l) if err := tx.Error; err != nil { // combination of name and space ID should be unique if gormsupport.IsUniqueViolation(err, "labels_name_space_id_unique_idx") { log.Error(ctx, map[string]interface{}{ "err": err, "name": l.Name, "space_id": l.SpaceID, }, "unable to create label because a label with same already exists in the space") return nil, errors.NewDataConflictError(fmt.Sprintf("label already exists with name = %s , space_id = %s", l.Name, l.SpaceID.String())) } log.Error(ctx, map[string]interface{}{ "label_id": l.ID, "err": err, }, "unable to save the label") return nil, errors.NewInternalError(ctx, err) } if tx.RowsAffected == 0 { return nil, errors.NewVersionConflictError("version conflict") } log.Debug(ctx, map[string]interface{}{ "label_id": l.ID, }, "label updated successfully") return &l, nil }
go
func (m *GormLabelRepository) Save(ctx context.Context, l Label) (*Label, error) { defer goa.MeasureSince([]string{"goa", "db", "label", "save"}, time.Now()) if strings.TrimSpace(l.Name) == "" { return nil, errors.NewBadParameterError("label name cannot be empty string", l.Name).Expected("non empty string") } lbl := Label{} tx := m.db.Where("id = ?", l.ID).First(&lbl) oldVersion := l.Version l.Version = lbl.Version + 1 if tx.RecordNotFound() { log.Error(ctx, map[string]interface{}{ "label_id": l.ID, }, "label cannot be found") return nil, errors.NewNotFoundError("label", l.ID.String()) } if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "label_id": l.ID, "err": err, }, "unknown error happened when searching the label") return nil, errors.NewInternalError(ctx, err) } tx = tx.Where("Version = ?", oldVersion).Save(&l) if err := tx.Error; err != nil { // combination of name and space ID should be unique if gormsupport.IsUniqueViolation(err, "labels_name_space_id_unique_idx") { log.Error(ctx, map[string]interface{}{ "err": err, "name": l.Name, "space_id": l.SpaceID, }, "unable to create label because a label with same already exists in the space") return nil, errors.NewDataConflictError(fmt.Sprintf("label already exists with name = %s , space_id = %s", l.Name, l.SpaceID.String())) } log.Error(ctx, map[string]interface{}{ "label_id": l.ID, "err": err, }, "unable to save the label") return nil, errors.NewInternalError(ctx, err) } if tx.RowsAffected == 0 { return nil, errors.NewVersionConflictError("version conflict") } log.Debug(ctx, map[string]interface{}{ "label_id": l.ID, }, "label updated successfully") return &l, nil }
[ "func", "(", "m", "*", "GormLabelRepository", ")", "Save", "(", "ctx", "context", ".", "Context", ",", "l", "Label", ")", "(", "*", "Label", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\"", ",",...
// Save update the given label
[ "Save", "update", "the", "given", "label" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/label/label.go#L97-L144
13,082
fabric8-services/fabric8-wit
label/label.go
List
func (m *GormLabelRepository) List(ctx context.Context, spaceID uuid.UUID) ([]Label, error) { defer goa.MeasureSince([]string{"goa", "db", "label", "query"}, time.Now()) var objs []Label err := m.db.Where("space_id = ?", spaceID).Find(&objs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } return objs, nil }
go
func (m *GormLabelRepository) List(ctx context.Context, spaceID uuid.UUID) ([]Label, error) { defer goa.MeasureSince([]string{"goa", "db", "label", "query"}, time.Now()) var objs []Label err := m.db.Where("space_id = ?", spaceID).Find(&objs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } return objs, nil }
[ "func", "(", "m", "*", "GormLabelRepository", ")", "List", "(", "ctx", "context", ".", "Context", ",", "spaceID", "uuid", ".", "UUID", ")", "(", "[", "]", "Label", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", ...
// List all labels in a space
[ "List", "all", "labels", "in", "a", "space" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/label/label.go#L147-L155
13,083
fabric8-services/fabric8-wit
label/label.go
Load
func (m *GormLabelRepository) Load(ctx context.Context, ID uuid.UUID) (*Label, error) { defer goa.MeasureSince([]string{"goa", "db", "label", "show"}, time.Now()) lbl := Label{} tx := m.db.Where("id = ?", ID).First(&lbl) if tx.RecordNotFound() { log.Error(ctx, map[string]interface{}{ "label_id": ID.String(), }, "state or known referer was empty") return nil, errors.NewNotFoundError("label", ID.String()) } if tx.Error != nil { log.Error(ctx, map[string]interface{}{ "err": tx.Error, "label_id": ID.String(), }, "unable to load the label by ID") return nil, errors.NewInternalError(ctx, tx.Error) } return &lbl, nil }
go
func (m *GormLabelRepository) Load(ctx context.Context, ID uuid.UUID) (*Label, error) { defer goa.MeasureSince([]string{"goa", "db", "label", "show"}, time.Now()) lbl := Label{} tx := m.db.Where("id = ?", ID).First(&lbl) if tx.RecordNotFound() { log.Error(ctx, map[string]interface{}{ "label_id": ID.String(), }, "state or known referer was empty") return nil, errors.NewNotFoundError("label", ID.String()) } if tx.Error != nil { log.Error(ctx, map[string]interface{}{ "err": tx.Error, "label_id": ID.String(), }, "unable to load the label by ID") return nil, errors.NewInternalError(ctx, tx.Error) } return &lbl, nil }
[ "func", "(", "m", "*", "GormLabelRepository", ")", "Load", "(", "ctx", "context", ".", "Context", ",", "ID", "uuid", ".", "UUID", ")", "(", "*", "Label", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"...
// Load label in a space
[ "Load", "label", "in", "a", "space" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/label/label.go#L163-L181
13,084
fabric8-services/fabric8-wit
gormsupport/postgres.go
IsCheckViolation
func IsCheckViolation(err error, constraintName string) bool { if err == nil { return false } pqError, ok := err.(*pq.Error) if !ok { return false } return pqError.Code == errCheckViolation && pqError.Constraint == constraintName }
go
func IsCheckViolation(err error, constraintName string) bool { if err == nil { return false } pqError, ok := err.(*pq.Error) if !ok { return false } return pqError.Code == errCheckViolation && pqError.Constraint == constraintName }
[ "func", "IsCheckViolation", "(", "err", "error", ",", "constraintName", "string", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n", "pqError", ",", "ok", ":=", "err", ".", "(", "*", "pq", ".", "Error", ")", "\n", ...
// IsCheckViolation returns true if the error is a violation of the given check
[ "IsCheckViolation", "returns", "true", "if", "the", "error", "is", "a", "violation", "of", "the", "given", "check" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/gormsupport/postgres.go#L14-L23
13,085
fabric8-services/fabric8-wit
gormsupport/postgres.go
IsUniqueViolation
func IsUniqueViolation(err error, indexName string) bool { if err == nil { return false } pqError, ok := err.(*pq.Error) if !ok { return false } return pqError.Code == errUniqueViolation && pqError.Constraint == indexName }
go
func IsUniqueViolation(err error, indexName string) bool { if err == nil { return false } pqError, ok := err.(*pq.Error) if !ok { return false } return pqError.Code == errUniqueViolation && pqError.Constraint == indexName }
[ "func", "IsUniqueViolation", "(", "err", "error", ",", "indexName", "string", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n", "pqError", ",", "ok", ":=", "err", ".", "(", "*", "pq", ".", "Error", ")", "\n", "if"...
// IsUniqueViolation returns true if the error is a violation of the given unique index
[ "IsUniqueViolation", "returns", "true", "if", "the", "error", "is", "a", "violation", "of", "the", "given", "unique", "index" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/gormsupport/postgres.go#L50-L59
13,086
fabric8-services/fabric8-wit
gormsupport/postgres.go
IsForeignKeyViolation
func IsForeignKeyViolation(err error, indexName string) bool { if err == nil { return false } pqError, ok := err.(*pq.Error) if !ok { return false } return pqError.Code == errForeignKeyViolation && pqError.Constraint == indexName }
go
func IsForeignKeyViolation(err error, indexName string) bool { if err == nil { return false } pqError, ok := err.(*pq.Error) if !ok { return false } return pqError.Code == errForeignKeyViolation && pqError.Constraint == indexName }
[ "func", "IsForeignKeyViolation", "(", "err", "error", ",", "indexName", "string", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n", "pqError", ",", "ok", ":=", "err", ".", "(", "*", "pq", ".", "Error", ")", "\n", ...
// IsForeignKeyViolation returns true if the error is a violation of the given foreign key index
[ "IsForeignKeyViolation", "returns", "true", "if", "the", "error", "is", "a", "violation", "of", "the", "given", "foreign", "key", "index" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/gormsupport/postgres.go#L62-L71
13,087
fabric8-services/fabric8-wit
rest/proxy/proxy.go
RouteHTTPToPath
func RouteHTTPToPath(ctx jsonapi.InternalServerErrorContext, targetHost string, targetPath string) error { return route(ctx, targetHost, &targetPath) }
go
func RouteHTTPToPath(ctx jsonapi.InternalServerErrorContext, targetHost string, targetPath string) error { return route(ctx, targetHost, &targetPath) }
[ "func", "RouteHTTPToPath", "(", "ctx", "jsonapi", ".", "InternalServerErrorContext", ",", "targetHost", "string", ",", "targetPath", "string", ")", "error", "{", "return", "route", "(", "ctx", ",", "targetHost", ",", "&", "targetPath", ")", "\n", "}" ]
// RouteHTTPToPath uses a reverse proxy to route the http request to the scheme, host provided in targetHost // and path provided in targetPath.
[ "RouteHTTPToPath", "uses", "a", "reverse", "proxy", "to", "route", "the", "http", "request", "to", "the", "scheme", "host", "provided", "in", "targetHost", "and", "path", "provided", "in", "targetPath", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/rest/proxy/proxy.go#L22-L24
13,088
fabric8-services/fabric8-wit
controller/work_item_board.go
NewWorkItemBoardController
func NewWorkItemBoardController(service *goa.Service, db application.DB) *WorkItemBoardController { return &WorkItemBoardController{ Controller: service.NewController("WorkItemBoardController"), db: db, } }
go
func NewWorkItemBoardController(service *goa.Service, db application.DB) *WorkItemBoardController { return &WorkItemBoardController{ Controller: service.NewController("WorkItemBoardController"), db: db, } }
[ "func", "NewWorkItemBoardController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ")", "*", "WorkItemBoardController", "{", "return", "&", "WorkItemBoardController", "{", "Controller", ":", "service", ".", "NewController", "(",...
// NewWorkItemBoardController creates a work_item_board controller.
[ "NewWorkItemBoardController", "creates", "a", "work_item_board", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_board.go#L32-L37
13,089
fabric8-services/fabric8-wit
controller/work_item_board.go
ConvertColumnsFromModel
func ConvertColumnsFromModel(request *http.Request, column workitem.BoardColumn) *app.WorkItemBoardColumnData { return &app.WorkItemBoardColumnData{ ID: column.ID, Type: APIBoardColumns, Attributes: &app.WorkItemBoardColumnAttributes{ Name: column.Name, Order: &column.Order, }, } }
go
func ConvertColumnsFromModel(request *http.Request, column workitem.BoardColumn) *app.WorkItemBoardColumnData { return &app.WorkItemBoardColumnData{ ID: column.ID, Type: APIBoardColumns, Attributes: &app.WorkItemBoardColumnAttributes{ Name: column.Name, Order: &column.Order, }, } }
[ "func", "ConvertColumnsFromModel", "(", "request", "*", "http", ".", "Request", ",", "column", "workitem", ".", "BoardColumn", ")", "*", "app", ".", "WorkItemBoardColumnData", "{", "return", "&", "app", ".", "WorkItemBoardColumnData", "{", "ID", ":", "column", ...
// ConvertColumnsFromModel converts WorkitemTypeBoard model to a response // resource object for jsonapi.org specification
[ "ConvertColumnsFromModel", "converts", "WorkitemTypeBoard", "model", "to", "a", "response", "resource", "object", "for", "jsonapi", ".", "org", "specification" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_board.go#L64-L73
13,090
fabric8-services/fabric8-wit
controller/work_item_board.go
ConvertBoardFromModel
func ConvertBoardFromModel(request *http.Request, b workitem.Board) *app.WorkItemBoardData { res := &app.WorkItemBoardData{ ID: &b.ID, Type: APIWorkItemBoards, Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.WorkItemBoardHref(b.ID))), }, Attributes: &app.WorkItemBoardAttributes{ Context: b.Context, ContextType: b.ContextType, Name: b.Name, CreatedAt: ptr.Time(b.CreatedAt.UTC()), UpdatedAt: ptr.Time(b.UpdatedAt.UTC()), }, Relationships: &app.WorkItemBoardRelationships{ Columns: &app.RelationGenericList{ Data: make([]*app.GenericData, len(b.Columns)), }, SpaceTemplate: &app.RelationGeneric{ Data: &app.GenericData{ ID: ptr.String(b.SpaceTemplateID.String()), Type: &APISpaceTemplates, }, }, }, } // iterate over the columns and attach them as an // included relationship for i, column := range b.Columns { res.Relationships.Columns.Data[i] = &app.GenericData{ ID: ptr.String(column.ID.String()), Type: ptr.String(APIBoardColumns), } } return res }
go
func ConvertBoardFromModel(request *http.Request, b workitem.Board) *app.WorkItemBoardData { res := &app.WorkItemBoardData{ ID: &b.ID, Type: APIWorkItemBoards, Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.WorkItemBoardHref(b.ID))), }, Attributes: &app.WorkItemBoardAttributes{ Context: b.Context, ContextType: b.ContextType, Name: b.Name, CreatedAt: ptr.Time(b.CreatedAt.UTC()), UpdatedAt: ptr.Time(b.UpdatedAt.UTC()), }, Relationships: &app.WorkItemBoardRelationships{ Columns: &app.RelationGenericList{ Data: make([]*app.GenericData, len(b.Columns)), }, SpaceTemplate: &app.RelationGeneric{ Data: &app.GenericData{ ID: ptr.String(b.SpaceTemplateID.String()), Type: &APISpaceTemplates, }, }, }, } // iterate over the columns and attach them as an // included relationship for i, column := range b.Columns { res.Relationships.Columns.Data[i] = &app.GenericData{ ID: ptr.String(column.ID.String()), Type: ptr.String(APIBoardColumns), } } return res }
[ "func", "ConvertBoardFromModel", "(", "request", "*", "http", ".", "Request", ",", "b", "workitem", ".", "Board", ")", "*", "app", ".", "WorkItemBoardData", "{", "res", ":=", "&", "app", ".", "WorkItemBoardData", "{", "ID", ":", "&", "b", ".", "ID", ",...
// ConvertBoardFromModel converts WorkitemTypeBoard model to a response resource // object for jsonapi.org specification
[ "ConvertBoardFromModel", "converts", "WorkitemTypeBoard", "model", "to", "a", "response", "resource", "object", "for", "jsonapi", ".", "org", "specification" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_board.go#L77-L114
13,091
fabric8-services/fabric8-wit
controller/work_item_board.go
ConvertBoardColumnsSimple
func ConvertBoardColumnsSimple(request *http.Request, labelIDs []interface{}) []*app.GenericData { ops := make([]*app.GenericData, 0, len(labelIDs)) for _, labelID := range labelIDs { ops = append(ops, ConvertBoardColumnSimple(request, labelID)) } return ops }
go
func ConvertBoardColumnsSimple(request *http.Request, labelIDs []interface{}) []*app.GenericData { ops := make([]*app.GenericData, 0, len(labelIDs)) for _, labelID := range labelIDs { ops = append(ops, ConvertBoardColumnSimple(request, labelID)) } return ops }
[ "func", "ConvertBoardColumnsSimple", "(", "request", "*", "http", ".", "Request", ",", "labelIDs", "[", "]", "interface", "{", "}", ")", "[", "]", "*", "app", ".", "GenericData", "{", "ops", ":=", "make", "(", "[", "]", "*", "app", ".", "GenericData", ...
// ConvertBoardColumnsSimple converts an array of board column IDs into a // Generic Relationship List
[ "ConvertBoardColumnsSimple", "converts", "an", "array", "of", "board", "column", "IDs", "into", "a", "Generic", "Relationship", "List" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_board.go#L118-L124
13,092
fabric8-services/fabric8-wit
controller/work_item_board.go
ConvertBoardColumnSimple
func ConvertBoardColumnSimple(request *http.Request, labelID interface{}) *app.GenericData { t := APIBoardColumns i := fmt.Sprint(labelID) return &app.GenericData{ Type: &t, ID: &i, } }
go
func ConvertBoardColumnSimple(request *http.Request, labelID interface{}) *app.GenericData { t := APIBoardColumns i := fmt.Sprint(labelID) return &app.GenericData{ Type: &t, ID: &i, } }
[ "func", "ConvertBoardColumnSimple", "(", "request", "*", "http", ".", "Request", ",", "labelID", "interface", "{", "}", ")", "*", "app", ".", "GenericData", "{", "t", ":=", "APIBoardColumns", "\n", "i", ":=", "fmt", ".", "Sprint", "(", "labelID", ")", "\...
// ConvertBoardColumnSimple converts a board column ID into a Generic // Relationship
[ "ConvertBoardColumnSimple", "converts", "a", "board", "column", "ID", "into", "a", "Generic", "Relationship" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_board.go#L128-L135
13,093
fabric8-services/fabric8-wit
controller/space.go
ConvertSpaceToModel
func ConvertSpaceToModel(appSpace app.Space) space.Space { modelSpace := space.Space{} if appSpace.ID != nil { modelSpace.ID = *appSpace.ID } if appSpace.Attributes != nil { if appSpace.Attributes.CreatedAt != nil { modelSpace.CreatedAt = *appSpace.Attributes.CreatedAt } if appSpace.Attributes.UpdatedAt != nil { modelSpace.UpdatedAt = *appSpace.Attributes.UpdatedAt } if appSpace.Attributes.Version != nil { modelSpace.Version = *appSpace.Attributes.Version } if appSpace.Attributes.Name != nil { modelSpace.Name = *appSpace.Attributes.Name } if appSpace.Attributes.Description != nil { modelSpace.Description = *appSpace.Attributes.Description } } if appSpace.Relationships != nil && appSpace.Relationships.OwnedBy != nil && appSpace.Relationships.OwnedBy.Data != nil && appSpace.Relationships.OwnedBy.Data.ID != nil { modelSpace.OwnerID = *appSpace.Relationships.OwnedBy.Data.ID } if appSpace.Relationships != nil && appSpace.Relationships.SpaceTemplate != nil && appSpace.Relationships.SpaceTemplate.Data != nil { modelSpace.SpaceTemplateID = appSpace.Relationships.SpaceTemplate.Data.ID } return modelSpace }
go
func ConvertSpaceToModel(appSpace app.Space) space.Space { modelSpace := space.Space{} if appSpace.ID != nil { modelSpace.ID = *appSpace.ID } if appSpace.Attributes != nil { if appSpace.Attributes.CreatedAt != nil { modelSpace.CreatedAt = *appSpace.Attributes.CreatedAt } if appSpace.Attributes.UpdatedAt != nil { modelSpace.UpdatedAt = *appSpace.Attributes.UpdatedAt } if appSpace.Attributes.Version != nil { modelSpace.Version = *appSpace.Attributes.Version } if appSpace.Attributes.Name != nil { modelSpace.Name = *appSpace.Attributes.Name } if appSpace.Attributes.Description != nil { modelSpace.Description = *appSpace.Attributes.Description } } if appSpace.Relationships != nil && appSpace.Relationships.OwnedBy != nil && appSpace.Relationships.OwnedBy.Data != nil && appSpace.Relationships.OwnedBy.Data.ID != nil { modelSpace.OwnerID = *appSpace.Relationships.OwnedBy.Data.ID } if appSpace.Relationships != nil && appSpace.Relationships.SpaceTemplate != nil && appSpace.Relationships.SpaceTemplate.Data != nil { modelSpace.SpaceTemplateID = appSpace.Relationships.SpaceTemplate.Data.ID } return modelSpace }
[ "func", "ConvertSpaceToModel", "(", "appSpace", "app", ".", "Space", ")", "space", ".", "Space", "{", "modelSpace", ":=", "space", ".", "Space", "{", "}", "\n\n", "if", "appSpace", ".", "ID", "!=", "nil", "{", "modelSpace", ".", "ID", "=", "*", "appSpa...
// ConvertSpaceToModel converts an `app.Space` to a `space.Space`
[ "ConvertSpaceToModel", "converts", "an", "app", ".", "Space", "to", "a", "space", ".", "Space" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space.go#L609-L641
13,094
fabric8-services/fabric8-wit
controller/space.go
IncludeBacklogTotalCount
func IncludeBacklogTotalCount(ctx context.Context, db application.DB) SpaceConvertFunc { return func(req *http.Request, modelSpace *space.Space, appSpace *app.Space) error { count, err := countBacklogItems(ctx, db, modelSpace.ID) if err != nil { return errs.Wrap(err, "unable to count backlog items") } appSpace.Links.Backlog.Meta = &app.BacklogLinkMeta{TotalCount: count} // TODO (xcoulon) remove that part appSpace.Relationships.Backlog.Meta = map[string]interface{}{"totalCount": count} return nil } }
go
func IncludeBacklogTotalCount(ctx context.Context, db application.DB) SpaceConvertFunc { return func(req *http.Request, modelSpace *space.Space, appSpace *app.Space) error { count, err := countBacklogItems(ctx, db, modelSpace.ID) if err != nil { return errs.Wrap(err, "unable to count backlog items") } appSpace.Links.Backlog.Meta = &app.BacklogLinkMeta{TotalCount: count} // TODO (xcoulon) remove that part appSpace.Relationships.Backlog.Meta = map[string]interface{}{"totalCount": count} return nil } }
[ "func", "IncludeBacklogTotalCount", "(", "ctx", "context", ".", "Context", ",", "db", "application", ".", "DB", ")", "SpaceConvertFunc", "{", "return", "func", "(", "req", "*", "http", ".", "Request", ",", "modelSpace", "*", "space", ".", "Space", ",", "ap...
// IncludeBacklog returns a SpaceConvertFunc that includes the a link to the backlog // along with the total count of items in the backlog of the current space
[ "IncludeBacklog", "returns", "a", "SpaceConvertFunc", "that", "includes", "the", "a", "link", "to", "the", "backlog", "along", "with", "the", "total", "count", "of", "items", "in", "the", "backlog", "of", "the", "current", "space" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space.go#L649-L659
13,095
fabric8-services/fabric8-wit
controller/space.go
ConvertSpacesFromModel
func ConvertSpacesFromModel(request *http.Request, spaces []space.Space, additional ...SpaceConvertFunc) ([]*app.Space, error) { var result = make([]*app.Space, len(spaces)) for i, p := range spaces { spaceData, err := ConvertSpaceFromModel(request, p, additional...) if err != nil { return nil, err } result[i] = spaceData } return result, nil }
go
func ConvertSpacesFromModel(request *http.Request, spaces []space.Space, additional ...SpaceConvertFunc) ([]*app.Space, error) { var result = make([]*app.Space, len(spaces)) for i, p := range spaces { spaceData, err := ConvertSpaceFromModel(request, p, additional...) if err != nil { return nil, err } result[i] = spaceData } return result, nil }
[ "func", "ConvertSpacesFromModel", "(", "request", "*", "http", ".", "Request", ",", "spaces", "[", "]", "space", ".", "Space", ",", "additional", "...", "SpaceConvertFunc", ")", "(", "[", "]", "*", "app", ".", "Space", ",", "error", ")", "{", "var", "r...
// ConvertSpacesFromModel converts between internal and external REST representation
[ "ConvertSpacesFromModel", "converts", "between", "internal", "and", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space.go#L662-L672
13,096
fabric8-services/fabric8-wit
workitem/link/topology.go
CheckValid
func (t Topology) CheckValid() error { switch t { case TopologyNetwork, TopologyDirectedNetwork, TopologyDependency, TopologyTree: return nil default: return errors.NewBadParameterError("topolgy", t).Expected(TopologyNetwork + "|" + TopologyDirectedNetwork + "|" + TopologyDependency + "|" + TopologyTree) } }
go
func (t Topology) CheckValid() error { switch t { case TopologyNetwork, TopologyDirectedNetwork, TopologyDependency, TopologyTree: return nil default: return errors.NewBadParameterError("topolgy", t).Expected(TopologyNetwork + "|" + TopologyDirectedNetwork + "|" + TopologyDependency + "|" + TopologyTree) } }
[ "func", "(", "t", "Topology", ")", "CheckValid", "(", ")", "error", "{", "switch", "t", "{", "case", "TopologyNetwork", ",", "TopologyDirectedNetwork", ",", "TopologyDependency", ",", "TopologyTree", ":", "return", "nil", "\n", "default", ":", "return", "error...
// CheckValid returns nil if the given topology is valid; otherwise a // BadParameterError is returned.
[ "CheckValid", "returns", "nil", "if", "the", "given", "topology", "is", "valid", ";", "otherwise", "a", "BadParameterError", "is", "returned", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/link/topology.go#L50-L57
13,097
fabric8-services/fabric8-wit
controller/deployments_osioclient.go
ReadResponse
func (r *IOResponseReader) ReadResponse(resp *http.Response) ([]byte, error) { defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }
go
func (r *IOResponseReader) ReadResponse(resp *http.Response) ([]byte, error) { defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }
[ "func", "(", "r", "*", "IOResponseReader", ")", "ReadResponse", "(", "resp", "*", "http", ".", "Response", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "return", "ioutil", ".", "Rea...
// ReadResponse implementation for ResponseReader
[ "ReadResponse", "implementation", "for", "ResponseReader" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/deployments_osioclient.go#L29-L32
13,098
fabric8-services/fabric8-wit
controller/deployments_osioclient.go
NewOSIOClient
func NewOSIOClient(ctx context.Context, scheme string, host string) OpenshiftIOClient { wc := witclient.New(goaclient.HTTPClientDoer(http.DefaultClient)) wc.Host = host wc.Scheme = scheme wc.SetJWTSigner(goasupport.NewForwardSigner(ctx)) return CreateOSIOClient(wc, &IOResponseReader{}) }
go
func NewOSIOClient(ctx context.Context, scheme string, host string) OpenshiftIOClient { wc := witclient.New(goaclient.HTTPClientDoer(http.DefaultClient)) wc.Host = host wc.Scheme = scheme wc.SetJWTSigner(goasupport.NewForwardSigner(ctx)) return CreateOSIOClient(wc, &IOResponseReader{}) }
[ "func", "NewOSIOClient", "(", "ctx", "context", ".", "Context", ",", "scheme", "string", ",", "host", "string", ")", "OpenshiftIOClient", "{", "wc", ":=", "witclient", ".", "New", "(", "goaclient", ".", "HTTPClientDoer", "(", "http", ".", "DefaultClient", ")...
// NewOSIOClient creates an openshift IO client given an http request context
[ "NewOSIOClient", "creates", "an", "openshift", "IO", "client", "given", "an", "http", "request", "context" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/deployments_osioclient.go#L63-L69
13,099
fabric8-services/fabric8-wit
controller/deployments_osioclient.go
CreateOSIOClient
func CreateOSIOClient(witclient WitClient, responseReader ResponseReader) OpenshiftIOClient { client := new(OSIOClient) client.wc = witclient client.responseReader = responseReader return client }
go
func CreateOSIOClient(witclient WitClient, responseReader ResponseReader) OpenshiftIOClient { client := new(OSIOClient) client.wc = witclient client.responseReader = responseReader return client }
[ "func", "CreateOSIOClient", "(", "witclient", "WitClient", ",", "responseReader", "ResponseReader", ")", "OpenshiftIOClient", "{", "client", ":=", "new", "(", "OSIOClient", ")", "\n", "client", ".", "wc", "=", "witclient", "\n", "client", ".", "responseReader", ...
// CreateOSIOClient factory method replaced during unit testing
[ "CreateOSIOClient", "factory", "method", "replaced", "during", "unit", "testing" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/deployments_osioclient.go#L72-L77