repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
256dpi/fire
|
flame/tools.go
|
EnsureFirstUser
|
func EnsureFirstUser(store *coal.Store, name, email, password string) error {
// copy store
s := store.Copy()
defer s.Close()
// check existence
n, err := s.C(&User{}).Count()
if err != nil {
return err
} else if n > 0 {
return nil
}
// user is missing
// create user
user := coal.Init(&User{}).(*User)
user.Name = name
user.Email = email
user.Password = password
// set key and secret
err = user.Validate()
if err != nil {
return err
}
// save user
err = s.C(user).Insert(user)
if err != nil {
return err
}
return nil
}
|
go
|
func EnsureFirstUser(store *coal.Store, name, email, password string) error {
// copy store
s := store.Copy()
defer s.Close()
// check existence
n, err := s.C(&User{}).Count()
if err != nil {
return err
} else if n > 0 {
return nil
}
// user is missing
// create user
user := coal.Init(&User{}).(*User)
user.Name = name
user.Email = email
user.Password = password
// set key and secret
err = user.Validate()
if err != nil {
return err
}
// save user
err = s.C(user).Insert(user)
if err != nil {
return err
}
return nil
}
|
[
"func",
"EnsureFirstUser",
"(",
"store",
"*",
"coal",
".",
"Store",
",",
"name",
",",
"email",
",",
"password",
"string",
")",
"error",
"{",
"s",
":=",
"store",
".",
"Copy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"n",
",",
"err",
":=",
"s",
".",
"C",
"(",
"&",
"User",
"{",
"}",
")",
".",
"Count",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"n",
">",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"user",
":=",
"coal",
".",
"Init",
"(",
"&",
"User",
"{",
"}",
")",
".",
"(",
"*",
"User",
")",
"\n",
"user",
".",
"Name",
"=",
"name",
"\n",
"user",
".",
"Email",
"=",
"email",
"\n",
"user",
".",
"Password",
"=",
"password",
"\n",
"err",
"=",
"user",
".",
"Validate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"C",
"(",
"user",
")",
".",
"Insert",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// EnsureFirstUser ensures the existence of a first user if no other has been
// created.
|
[
"EnsureFirstUser",
"ensures",
"the",
"existence",
"of",
"a",
"first",
"user",
"if",
"no",
"other",
"has",
"been",
"created",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/tools.go#L93-L127
|
test
|
256dpi/fire
|
ash/strategy.go
|
Callback
|
func (s *Strategy) Callback() *fire.Callback {
// enforce defaults
if s.CollectionAction == nil {
s.CollectionAction = make(map[string][]*Authorizer)
}
if s.ResourceAction == nil {
s.ResourceAction = make(map[string][]*Authorizer)
}
// construct and return callback
return fire.C("ash/Strategy.Callback", fire.All(), func(ctx *fire.Context) (err error) {
switch ctx.Operation {
case fire.List:
err = s.call(ctx, s.List, s.Read, s.All)
case fire.Find:
err = s.call(ctx, s.Find, s.Read, s.All)
case fire.Create:
err = s.call(ctx, s.Create, s.Write, s.All)
case fire.Update:
err = s.call(ctx, s.Update, s.Write, s.All)
case fire.Delete:
err = s.call(ctx, s.Delete, s.Write, s.All)
case fire.CollectionAction:
err = s.call(ctx, s.CollectionAction[ctx.JSONAPIRequest.CollectionAction], s.CollectionActions, s.Actions, s.All)
case fire.ResourceAction:
err = s.call(ctx, s.ResourceAction[ctx.JSONAPIRequest.ResourceAction], s.ResourceActions, s.Actions, s.All)
}
return err
})
}
|
go
|
func (s *Strategy) Callback() *fire.Callback {
// enforce defaults
if s.CollectionAction == nil {
s.CollectionAction = make(map[string][]*Authorizer)
}
if s.ResourceAction == nil {
s.ResourceAction = make(map[string][]*Authorizer)
}
// construct and return callback
return fire.C("ash/Strategy.Callback", fire.All(), func(ctx *fire.Context) (err error) {
switch ctx.Operation {
case fire.List:
err = s.call(ctx, s.List, s.Read, s.All)
case fire.Find:
err = s.call(ctx, s.Find, s.Read, s.All)
case fire.Create:
err = s.call(ctx, s.Create, s.Write, s.All)
case fire.Update:
err = s.call(ctx, s.Update, s.Write, s.All)
case fire.Delete:
err = s.call(ctx, s.Delete, s.Write, s.All)
case fire.CollectionAction:
err = s.call(ctx, s.CollectionAction[ctx.JSONAPIRequest.CollectionAction], s.CollectionActions, s.Actions, s.All)
case fire.ResourceAction:
err = s.call(ctx, s.ResourceAction[ctx.JSONAPIRequest.ResourceAction], s.ResourceActions, s.Actions, s.All)
}
return err
})
}
|
[
"func",
"(",
"s",
"*",
"Strategy",
")",
"Callback",
"(",
")",
"*",
"fire",
".",
"Callback",
"{",
"if",
"s",
".",
"CollectionAction",
"==",
"nil",
"{",
"s",
".",
"CollectionAction",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"Authorizer",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"ResourceAction",
"==",
"nil",
"{",
"s",
".",
"ResourceAction",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"Authorizer",
")",
"\n",
"}",
"\n",
"return",
"fire",
".",
"C",
"(",
"\"ash/Strategy.Callback\"",
",",
"fire",
".",
"All",
"(",
")",
",",
"func",
"(",
"ctx",
"*",
"fire",
".",
"Context",
")",
"(",
"err",
"error",
")",
"{",
"switch",
"ctx",
".",
"Operation",
"{",
"case",
"fire",
".",
"List",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"List",
",",
"s",
".",
"Read",
",",
"s",
".",
"All",
")",
"\n",
"case",
"fire",
".",
"Find",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"Find",
",",
"s",
".",
"Read",
",",
"s",
".",
"All",
")",
"\n",
"case",
"fire",
".",
"Create",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"Create",
",",
"s",
".",
"Write",
",",
"s",
".",
"All",
")",
"\n",
"case",
"fire",
".",
"Update",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"Update",
",",
"s",
".",
"Write",
",",
"s",
".",
"All",
")",
"\n",
"case",
"fire",
".",
"Delete",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"Delete",
",",
"s",
".",
"Write",
",",
"s",
".",
"All",
")",
"\n",
"case",
"fire",
".",
"CollectionAction",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"CollectionAction",
"[",
"ctx",
".",
"JSONAPIRequest",
".",
"CollectionAction",
"]",
",",
"s",
".",
"CollectionActions",
",",
"s",
".",
"Actions",
",",
"s",
".",
"All",
")",
"\n",
"case",
"fire",
".",
"ResourceAction",
":",
"err",
"=",
"s",
".",
"call",
"(",
"ctx",
",",
"s",
".",
"ResourceAction",
"[",
"ctx",
".",
"JSONAPIRequest",
".",
"ResourceAction",
"]",
",",
"s",
".",
"ResourceActions",
",",
"s",
".",
"Actions",
",",
"s",
".",
"All",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] |
// Callback will return a callback that authorizes operations using the strategy.
|
[
"Callback",
"will",
"return",
"a",
"callback",
"that",
"authorizes",
"operations",
"using",
"the",
"strategy",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/strategy.go#L49-L79
|
test
|
256dpi/fire
|
coal/stream.go
|
OpenStream
|
func OpenStream(store *Store, model Model, token []byte, receiver Receiver, opened func(), manager func(error) bool) *Stream {
// prepare resume token
var resumeToken *bson.Raw
// create resume token if available
if token != nil {
resumeToken = &bson.Raw{
Kind: bson.ElementDocument,
Data: token,
}
}
// create stream
s := &Stream{
store: store,
model: model,
token: resumeToken,
receiver: receiver,
opened: opened,
manager: manager,
}
// open stream
go s.open()
return s
}
|
go
|
func OpenStream(store *Store, model Model, token []byte, receiver Receiver, opened func(), manager func(error) bool) *Stream {
// prepare resume token
var resumeToken *bson.Raw
// create resume token if available
if token != nil {
resumeToken = &bson.Raw{
Kind: bson.ElementDocument,
Data: token,
}
}
// create stream
s := &Stream{
store: store,
model: model,
token: resumeToken,
receiver: receiver,
opened: opened,
manager: manager,
}
// open stream
go s.open()
return s
}
|
[
"func",
"OpenStream",
"(",
"store",
"*",
"Store",
",",
"model",
"Model",
",",
"token",
"[",
"]",
"byte",
",",
"receiver",
"Receiver",
",",
"opened",
"func",
"(",
")",
",",
"manager",
"func",
"(",
"error",
")",
"bool",
")",
"*",
"Stream",
"{",
"var",
"resumeToken",
"*",
"bson",
".",
"Raw",
"\n",
"if",
"token",
"!=",
"nil",
"{",
"resumeToken",
"=",
"&",
"bson",
".",
"Raw",
"{",
"Kind",
":",
"bson",
".",
"ElementDocument",
",",
"Data",
":",
"token",
",",
"}",
"\n",
"}",
"\n",
"s",
":=",
"&",
"Stream",
"{",
"store",
":",
"store",
",",
"model",
":",
"model",
",",
"token",
":",
"resumeToken",
",",
"receiver",
":",
"receiver",
",",
"opened",
":",
"opened",
",",
"manager",
":",
"manager",
",",
"}",
"\n",
"go",
"s",
".",
"open",
"(",
")",
"\n",
"return",
"s",
"\n",
"}"
] |
// OpenStream will open a stream and continuously forward events to the specified
// receiver until the stream is closed. If a token is present it will be used to
// resume the stream. The provided opened function is called when the stream has
// been opened the first time. The passed manager is called with errors returned
// by the underlying change stream. The managers result is used to determine if
// the stream should be opened again.
//
// The stream automatically resumes on errors using an internally stored resume
// token. Applications that need more control should store the token externally
// and reopen the stream manually to resume from a specific position.
|
[
"OpenStream",
"will",
"open",
"a",
"stream",
"and",
"continuously",
"forward",
"events",
"to",
"the",
"specified",
"receiver",
"until",
"the",
"stream",
"is",
"closed",
".",
"If",
"a",
"token",
"is",
"present",
"it",
"will",
"be",
"used",
"to",
"resume",
"the",
"stream",
".",
"The",
"provided",
"opened",
"function",
"is",
"called",
"when",
"the",
"stream",
"has",
"been",
"opened",
"the",
"first",
"time",
".",
"The",
"passed",
"manager",
"is",
"called",
"with",
"errors",
"returned",
"by",
"the",
"underlying",
"change",
"stream",
".",
"The",
"managers",
"result",
"is",
"used",
"to",
"determine",
"if",
"the",
"stream",
"should",
"be",
"opened",
"again",
".",
"The",
"stream",
"automatically",
"resumes",
"on",
"errors",
"using",
"an",
"internally",
"stored",
"resume",
"token",
".",
"Applications",
"that",
"need",
"more",
"control",
"should",
"store",
"the",
"token",
"externally",
"and",
"reopen",
"the",
"stream",
"manually",
"to",
"resume",
"from",
"a",
"specific",
"position",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/stream.go#L52-L78
|
test
|
256dpi/fire
|
coal/stream.go
|
Close
|
func (s *Stream) Close() {
// get mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// set flag
s.closed = true
// close active change stream
if s.current != nil {
_ = s.current.Close()
}
}
|
go
|
func (s *Stream) Close() {
// get mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// set flag
s.closed = true
// close active change stream
if s.current != nil {
_ = s.current.Close()
}
}
|
[
"func",
"(",
"s",
"*",
"Stream",
")",
"Close",
"(",
")",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"closed",
"=",
"true",
"\n",
"if",
"s",
".",
"current",
"!=",
"nil",
"{",
"_",
"=",
"s",
".",
"current",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Close will close the stream.
|
[
"Close",
"will",
"close",
"the",
"stream",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/stream.go#L81-L93
|
test
|
256dpi/fire
|
flame/models.go
|
AddTokenIndexes
|
func AddTokenIndexes(i *coal.Indexer, autoExpire bool) {
i.Add(&Token{}, false, 0, "Type")
i.Add(&Token{}, false, 0, "Application")
i.Add(&Token{}, false, 0, "User")
if autoExpire {
i.Add(&Token{}, false, time.Minute, "ExpiresAt")
}
}
|
go
|
func AddTokenIndexes(i *coal.Indexer, autoExpire bool) {
i.Add(&Token{}, false, 0, "Type")
i.Add(&Token{}, false, 0, "Application")
i.Add(&Token{}, false, 0, "User")
if autoExpire {
i.Add(&Token{}, false, time.Minute, "ExpiresAt")
}
}
|
[
"func",
"AddTokenIndexes",
"(",
"i",
"*",
"coal",
".",
"Indexer",
",",
"autoExpire",
"bool",
")",
"{",
"i",
".",
"Add",
"(",
"&",
"Token",
"{",
"}",
",",
"false",
",",
"0",
",",
"\"Type\"",
")",
"\n",
"i",
".",
"Add",
"(",
"&",
"Token",
"{",
"}",
",",
"false",
",",
"0",
",",
"\"Application\"",
")",
"\n",
"i",
".",
"Add",
"(",
"&",
"Token",
"{",
"}",
",",
"false",
",",
"0",
",",
"\"User\"",
")",
"\n",
"if",
"autoExpire",
"{",
"i",
".",
"Add",
"(",
"&",
"Token",
"{",
"}",
",",
"false",
",",
"time",
".",
"Minute",
",",
"\"ExpiresAt\"",
")",
"\n",
"}",
"\n",
"}"
] |
// AddTokenIndexes will add access token indexes to the specified indexer.
|
[
"AddTokenIndexes",
"will",
"add",
"access",
"token",
"indexes",
"to",
"the",
"specified",
"indexer",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L47-L55
|
test
|
256dpi/fire
|
flame/models.go
|
GetTokenData
|
func (t *Token) GetTokenData() (TokenType, []string, time.Time, bson.ObjectId, *bson.ObjectId) {
return t.Type, t.Scope, t.ExpiresAt, t.Application, t.User
}
|
go
|
func (t *Token) GetTokenData() (TokenType, []string, time.Time, bson.ObjectId, *bson.ObjectId) {
return t.Type, t.Scope, t.ExpiresAt, t.Application, t.User
}
|
[
"func",
"(",
"t",
"*",
"Token",
")",
"GetTokenData",
"(",
")",
"(",
"TokenType",
",",
"[",
"]",
"string",
",",
"time",
".",
"Time",
",",
"bson",
".",
"ObjectId",
",",
"*",
"bson",
".",
"ObjectId",
")",
"{",
"return",
"t",
".",
"Type",
",",
"t",
".",
"Scope",
",",
"t",
".",
"ExpiresAt",
",",
"t",
".",
"Application",
",",
"t",
".",
"User",
"\n",
"}"
] |
// GetTokenData implements the flame.GenericToken interface.
|
[
"GetTokenData",
"implements",
"the",
"flame",
".",
"GenericToken",
"interface",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L58-L60
|
test
|
256dpi/fire
|
flame/models.go
|
SetTokenData
|
func (t *Token) SetTokenData(typ TokenType, scope []string, expiresAt time.Time, client Client, resourceOwner ResourceOwner) {
t.Type = typ
t.Scope = scope
t.ExpiresAt = expiresAt
t.Application = client.ID()
if resourceOwner != nil {
t.User = coal.P(resourceOwner.ID())
}
}
|
go
|
func (t *Token) SetTokenData(typ TokenType, scope []string, expiresAt time.Time, client Client, resourceOwner ResourceOwner) {
t.Type = typ
t.Scope = scope
t.ExpiresAt = expiresAt
t.Application = client.ID()
if resourceOwner != nil {
t.User = coal.P(resourceOwner.ID())
}
}
|
[
"func",
"(",
"t",
"*",
"Token",
")",
"SetTokenData",
"(",
"typ",
"TokenType",
",",
"scope",
"[",
"]",
"string",
",",
"expiresAt",
"time",
".",
"Time",
",",
"client",
"Client",
",",
"resourceOwner",
"ResourceOwner",
")",
"{",
"t",
".",
"Type",
"=",
"typ",
"\n",
"t",
".",
"Scope",
"=",
"scope",
"\n",
"t",
".",
"ExpiresAt",
"=",
"expiresAt",
"\n",
"t",
".",
"Application",
"=",
"client",
".",
"ID",
"(",
")",
"\n",
"if",
"resourceOwner",
"!=",
"nil",
"{",
"t",
".",
"User",
"=",
"coal",
".",
"P",
"(",
"resourceOwner",
".",
"ID",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// SetTokenData implements the flame.GenericToken interface.
|
[
"SetTokenData",
"implements",
"the",
"flame",
".",
"GenericToken",
"interface",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L63-L71
|
test
|
256dpi/fire
|
flame/models.go
|
ValidSecret
|
func (a *Application) ValidSecret(secret string) bool {
return bcrypt.CompareHashAndPassword(a.SecretHash, []byte(secret)) == nil
}
|
go
|
func (a *Application) ValidSecret(secret string) bool {
return bcrypt.CompareHashAndPassword(a.SecretHash, []byte(secret)) == nil
}
|
[
"func",
"(",
"a",
"*",
"Application",
")",
"ValidSecret",
"(",
"secret",
"string",
")",
"bool",
"{",
"return",
"bcrypt",
".",
"CompareHashAndPassword",
"(",
"a",
".",
"SecretHash",
",",
"[",
"]",
"byte",
"(",
"secret",
")",
")",
"==",
"nil",
"\n",
"}"
] |
// ValidSecret implements the flame.Client interface.
|
[
"ValidSecret",
"implements",
"the",
"flame",
".",
"Client",
"interface",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L126-L128
|
test
|
256dpi/fire
|
flame/models.go
|
HashSecret
|
func (a *Application) HashSecret() error {
// check length
if len(a.Secret) == 0 {
return nil
}
// generate hash from password
hash, err := bcrypt.GenerateFromPassword([]byte(a.Secret), bcrypt.DefaultCost)
if err != nil {
return err
}
// save hash
a.SecretHash = hash
// clear password
a.Secret = ""
return nil
}
|
go
|
func (a *Application) HashSecret() error {
// check length
if len(a.Secret) == 0 {
return nil
}
// generate hash from password
hash, err := bcrypt.GenerateFromPassword([]byte(a.Secret), bcrypt.DefaultCost)
if err != nil {
return err
}
// save hash
a.SecretHash = hash
// clear password
a.Secret = ""
return nil
}
|
[
"func",
"(",
"a",
"*",
"Application",
")",
"HashSecret",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"a",
".",
"Secret",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"hash",
",",
"err",
":=",
"bcrypt",
".",
"GenerateFromPassword",
"(",
"[",
"]",
"byte",
"(",
"a",
".",
"Secret",
")",
",",
"bcrypt",
".",
"DefaultCost",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"a",
".",
"SecretHash",
"=",
"hash",
"\n",
"a",
".",
"Secret",
"=",
"\"\"",
"\n",
"return",
"nil",
"\n",
"}"
] |
// HashSecret will hash Secret and set SecretHash.
|
[
"HashSecret",
"will",
"hash",
"Secret",
"and",
"set",
"SecretHash",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L167-L186
|
test
|
256dpi/fire
|
flame/models.go
|
ValidPassword
|
func (u *User) ValidPassword(password string) bool {
return bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(password)) == nil
}
|
go
|
func (u *User) ValidPassword(password string) bool {
return bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(password)) == nil
}
|
[
"func",
"(",
"u",
"*",
"User",
")",
"ValidPassword",
"(",
"password",
"string",
")",
"bool",
"{",
"return",
"bcrypt",
".",
"CompareHashAndPassword",
"(",
"u",
".",
"PasswordHash",
",",
"[",
"]",
"byte",
"(",
"password",
")",
")",
"==",
"nil",
"\n",
"}"
] |
// ValidPassword implements the flame.ResourceOwner interface.
|
[
"ValidPassword",
"implements",
"the",
"flame",
".",
"ResourceOwner",
"interface",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L214-L216
|
test
|
256dpi/fire
|
flame/models.go
|
HashPassword
|
func (u *User) HashPassword() error {
// check length
if len(u.Password) == 0 {
return nil
}
// generate hash from password
hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
// save hash
u.PasswordHash = hash
// clear password
u.Password = ""
return nil
}
|
go
|
func (u *User) HashPassword() error {
// check length
if len(u.Password) == 0 {
return nil
}
// generate hash from password
hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
// save hash
u.PasswordHash = hash
// clear password
u.Password = ""
return nil
}
|
[
"func",
"(",
"u",
"*",
"User",
")",
"HashPassword",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"u",
".",
"Password",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"hash",
",",
"err",
":=",
"bcrypt",
".",
"GenerateFromPassword",
"(",
"[",
"]",
"byte",
"(",
"u",
".",
"Password",
")",
",",
"bcrypt",
".",
"DefaultCost",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"u",
".",
"PasswordHash",
"=",
"hash",
"\n",
"u",
".",
"Password",
"=",
"\"\"",
"\n",
"return",
"nil",
"\n",
"}"
] |
// HashPassword will hash Password and set PasswordHash.
|
[
"HashPassword",
"will",
"hash",
"Password",
"and",
"set",
"PasswordHash",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L250-L269
|
test
|
256dpi/fire
|
coal/store.go
|
MustCreateStore
|
func MustCreateStore(uri string) *Store {
store, err := CreateStore(uri)
if err != nil {
panic(err)
}
return store
}
|
go
|
func MustCreateStore(uri string) *Store {
store, err := CreateStore(uri)
if err != nil {
panic(err)
}
return store
}
|
[
"func",
"MustCreateStore",
"(",
"uri",
"string",
")",
"*",
"Store",
"{",
"store",
",",
"err",
":=",
"CreateStore",
"(",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"store",
"\n",
"}"
] |
// MustCreateStore will dial the passed database and return a new store. It will
// panic if the initial connection failed.
|
[
"MustCreateStore",
"will",
"dial",
"the",
"passed",
"database",
"and",
"return",
"a",
"new",
"store",
".",
"It",
"will",
"panic",
"if",
"the",
"initial",
"connection",
"failed",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/store.go#L7-L14
|
test
|
256dpi/fire
|
coal/store.go
|
CreateStore
|
func CreateStore(uri string) (*Store, error) {
session, err := mgo.Dial(uri)
if err != nil {
return nil, err
}
return NewStore(session), nil
}
|
go
|
func CreateStore(uri string) (*Store, error) {
session, err := mgo.Dial(uri)
if err != nil {
return nil, err
}
return NewStore(session), nil
}
|
[
"func",
"CreateStore",
"(",
"uri",
"string",
")",
"(",
"*",
"Store",
",",
"error",
")",
"{",
"session",
",",
"err",
":=",
"mgo",
".",
"Dial",
"(",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewStore",
"(",
"session",
")",
",",
"nil",
"\n",
"}"
] |
// CreateStore will dial the passed database and return a new store. It will
// return an error if the initial connection failed
|
[
"CreateStore",
"will",
"dial",
"the",
"passed",
"database",
"and",
"return",
"a",
"new",
"store",
".",
"It",
"will",
"return",
"an",
"error",
"if",
"the",
"initial",
"connection",
"failed"
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/store.go#L18-L25
|
test
|
256dpi/fire
|
coal/store.go
|
C
|
func (s *SubStore) C(model Model) *mgo.Collection {
return s.DB().C(C(model))
}
|
go
|
func (s *SubStore) C(model Model) *mgo.Collection {
return s.DB().C(C(model))
}
|
[
"func",
"(",
"s",
"*",
"SubStore",
")",
"C",
"(",
"model",
"Model",
")",
"*",
"mgo",
".",
"Collection",
"{",
"return",
"s",
".",
"DB",
"(",
")",
".",
"C",
"(",
"C",
"(",
"model",
")",
")",
"\n",
"}"
] |
// C will return the collection associated to the passed model.
|
[
"C",
"will",
"return",
"the",
"collection",
"associated",
"to",
"the",
"passed",
"model",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/store.go#L68-L70
|
test
|
256dpi/fire
|
wood/asset_server.go
|
NewAssetServer
|
func NewAssetServer(prefix, directory string) http.Handler {
// ensure prefix
prefix = "/" + strings.Trim(prefix, "/")
// create dir server
dir := http.Dir(directory)
// create file server
fs := http.FileServer(dir)
h := func(w http.ResponseWriter, r *http.Request) {
// pre-check if file does exist
f, err := dir.Open(r.URL.Path)
if err != nil {
r.URL.Path = "/"
} else if f != nil {
_ = f.Close()
}
// serve file
fs.ServeHTTP(w, r)
}
return http.StripPrefix(prefix, http.HandlerFunc(h))
}
|
go
|
func NewAssetServer(prefix, directory string) http.Handler {
// ensure prefix
prefix = "/" + strings.Trim(prefix, "/")
// create dir server
dir := http.Dir(directory)
// create file server
fs := http.FileServer(dir)
h := func(w http.ResponseWriter, r *http.Request) {
// pre-check if file does exist
f, err := dir.Open(r.URL.Path)
if err != nil {
r.URL.Path = "/"
} else if f != nil {
_ = f.Close()
}
// serve file
fs.ServeHTTP(w, r)
}
return http.StripPrefix(prefix, http.HandlerFunc(h))
}
|
[
"func",
"NewAssetServer",
"(",
"prefix",
",",
"directory",
"string",
")",
"http",
".",
"Handler",
"{",
"prefix",
"=",
"\"/\"",
"+",
"strings",
".",
"Trim",
"(",
"prefix",
",",
"\"/\"",
")",
"\n",
"dir",
":=",
"http",
".",
"Dir",
"(",
"directory",
")",
"\n",
"fs",
":=",
"http",
".",
"FileServer",
"(",
"dir",
")",
"\n",
"h",
":=",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"f",
",",
"err",
":=",
"dir",
".",
"Open",
"(",
"r",
".",
"URL",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r",
".",
"URL",
".",
"Path",
"=",
"\"/\"",
"\n",
"}",
"else",
"if",
"f",
"!=",
"nil",
"{",
"_",
"=",
"f",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"fs",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"return",
"http",
".",
"StripPrefix",
"(",
"prefix",
",",
"http",
".",
"HandlerFunc",
"(",
"h",
")",
")",
"\n",
"}"
] |
// NewAssetServer constructs an asset server handler that serves an asset
// directory on a specified path and serves the index file for not found paths
// which is needed to run single page applications like Ember.
|
[
"NewAssetServer",
"constructs",
"an",
"asset",
"server",
"handler",
"that",
"serves",
"an",
"asset",
"directory",
"on",
"a",
"specified",
"path",
"and",
"serves",
"the",
"index",
"file",
"for",
"not",
"found",
"paths",
"which",
"is",
"needed",
"to",
"run",
"single",
"page",
"applications",
"like",
"Ember",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/wood/asset_server.go#L17-L41
|
test
|
256dpi/fire
|
flame/policy.go
|
DefaultGrantStrategy
|
func DefaultGrantStrategy(scope oauth2.Scope, _ Client, _ ResourceOwner) (oauth2.Scope, error) {
// check scope
if !scope.Empty() {
return nil, ErrInvalidScope
}
return scope, nil
}
|
go
|
func DefaultGrantStrategy(scope oauth2.Scope, _ Client, _ ResourceOwner) (oauth2.Scope, error) {
// check scope
if !scope.Empty() {
return nil, ErrInvalidScope
}
return scope, nil
}
|
[
"func",
"DefaultGrantStrategy",
"(",
"scope",
"oauth2",
".",
"Scope",
",",
"_",
"Client",
",",
"_",
"ResourceOwner",
")",
"(",
"oauth2",
".",
"Scope",
",",
"error",
")",
"{",
"if",
"!",
"scope",
".",
"Empty",
"(",
")",
"{",
"return",
"nil",
",",
"ErrInvalidScope",
"\n",
"}",
"\n",
"return",
"scope",
",",
"nil",
"\n",
"}"
] |
// DefaultGrantStrategy grants only empty scopes.
|
[
"DefaultGrantStrategy",
"grants",
"only",
"empty",
"scopes",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L84-L91
|
test
|
256dpi/fire
|
flame/policy.go
|
DefaultTokenData
|
func DefaultTokenData(_ Client, ro ResourceOwner, _ GenericToken) map[string]interface{} {
if ro != nil {
return map[string]interface{}{
"user": ro.ID(),
}
}
return nil
}
|
go
|
func DefaultTokenData(_ Client, ro ResourceOwner, _ GenericToken) map[string]interface{} {
if ro != nil {
return map[string]interface{}{
"user": ro.ID(),
}
}
return nil
}
|
[
"func",
"DefaultTokenData",
"(",
"_",
"Client",
",",
"ro",
"ResourceOwner",
",",
"_",
"GenericToken",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"if",
"ro",
"!=",
"nil",
"{",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"user\"",
":",
"ro",
".",
"ID",
"(",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DefaultTokenData adds the user's id to the token data claim.
|
[
"DefaultTokenData",
"adds",
"the",
"user",
"s",
"id",
"to",
"the",
"token",
"data",
"claim",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L94-L102
|
test
|
256dpi/fire
|
flame/policy.go
|
GenerateToken
|
func (p *Policy) GenerateToken(id bson.ObjectId, issuedAt, expiresAt time.Time, client Client, resourceOwner ResourceOwner, token GenericToken) (string, error) {
// prepare claims
claims := &TokenClaims{}
claims.Id = id.Hex()
claims.IssuedAt = issuedAt.Unix()
claims.ExpiresAt = expiresAt.Unix()
// set user data
if p.TokenData != nil {
claims.Data = p.TokenData(client, resourceOwner, token)
}
// create token
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// sign token
str, err := tkn.SignedString(p.Secret)
if err != nil {
return "", nil
}
return str, nil
}
|
go
|
func (p *Policy) GenerateToken(id bson.ObjectId, issuedAt, expiresAt time.Time, client Client, resourceOwner ResourceOwner, token GenericToken) (string, error) {
// prepare claims
claims := &TokenClaims{}
claims.Id = id.Hex()
claims.IssuedAt = issuedAt.Unix()
claims.ExpiresAt = expiresAt.Unix()
// set user data
if p.TokenData != nil {
claims.Data = p.TokenData(client, resourceOwner, token)
}
// create token
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// sign token
str, err := tkn.SignedString(p.Secret)
if err != nil {
return "", nil
}
return str, nil
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"GenerateToken",
"(",
"id",
"bson",
".",
"ObjectId",
",",
"issuedAt",
",",
"expiresAt",
"time",
".",
"Time",
",",
"client",
"Client",
",",
"resourceOwner",
"ResourceOwner",
",",
"token",
"GenericToken",
")",
"(",
"string",
",",
"error",
")",
"{",
"claims",
":=",
"&",
"TokenClaims",
"{",
"}",
"\n",
"claims",
".",
"Id",
"=",
"id",
".",
"Hex",
"(",
")",
"\n",
"claims",
".",
"IssuedAt",
"=",
"issuedAt",
".",
"Unix",
"(",
")",
"\n",
"claims",
".",
"ExpiresAt",
"=",
"expiresAt",
".",
"Unix",
"(",
")",
"\n",
"if",
"p",
".",
"TokenData",
"!=",
"nil",
"{",
"claims",
".",
"Data",
"=",
"p",
".",
"TokenData",
"(",
"client",
",",
"resourceOwner",
",",
"token",
")",
"\n",
"}",
"\n",
"tkn",
":=",
"jwt",
".",
"NewWithClaims",
"(",
"jwt",
".",
"SigningMethodHS256",
",",
"claims",
")",
"\n",
"str",
",",
"err",
":=",
"tkn",
".",
"SignedString",
"(",
"p",
".",
"Secret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"str",
",",
"nil",
"\n",
"}"
] |
// GenerateToken returns a new token for the provided information.
|
[
"GenerateToken",
"returns",
"a",
"new",
"token",
"for",
"the",
"provided",
"information",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L124-L146
|
test
|
256dpi/fire
|
flame/policy.go
|
ParseToken
|
func (p *Policy) ParseToken(str string) (*TokenClaims, bool, error) {
// parse token and check id
var claims TokenClaims
_, err := jwt.ParseWithClaims(str, &claims, func(_ *jwt.Token) (interface{}, error) {
return p.Secret, nil
})
if valErr, ok := err.(*jwt.ValidationError); ok && valErr.Errors == jwt.ValidationErrorExpired {
return nil, true, err
} else if err != nil {
return nil, false, err
} else if !bson.IsObjectIdHex(claims.Id) {
return nil, false, errors.New("invalid id")
}
return &claims, false, nil
}
|
go
|
func (p *Policy) ParseToken(str string) (*TokenClaims, bool, error) {
// parse token and check id
var claims TokenClaims
_, err := jwt.ParseWithClaims(str, &claims, func(_ *jwt.Token) (interface{}, error) {
return p.Secret, nil
})
if valErr, ok := err.(*jwt.ValidationError); ok && valErr.Errors == jwt.ValidationErrorExpired {
return nil, true, err
} else if err != nil {
return nil, false, err
} else if !bson.IsObjectIdHex(claims.Id) {
return nil, false, errors.New("invalid id")
}
return &claims, false, nil
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"ParseToken",
"(",
"str",
"string",
")",
"(",
"*",
"TokenClaims",
",",
"bool",
",",
"error",
")",
"{",
"var",
"claims",
"TokenClaims",
"\n",
"_",
",",
"err",
":=",
"jwt",
".",
"ParseWithClaims",
"(",
"str",
",",
"&",
"claims",
",",
"func",
"(",
"_",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"p",
".",
"Secret",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"valErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"jwt",
".",
"ValidationError",
")",
";",
"ok",
"&&",
"valErr",
".",
"Errors",
"==",
"jwt",
".",
"ValidationErrorExpired",
"{",
"return",
"nil",
",",
"true",
",",
"err",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"else",
"if",
"!",
"bson",
".",
"IsObjectIdHex",
"(",
"claims",
".",
"Id",
")",
"{",
"return",
"nil",
",",
"false",
",",
"errors",
".",
"New",
"(",
"\"invalid id\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"claims",
",",
"false",
",",
"nil",
"\n",
"}"
] |
// ParseToken will parse the presented token and return its claims, if it is
// expired and eventual errors.
|
[
"ParseToken",
"will",
"parse",
"the",
"presented",
"token",
"and",
"return",
"its",
"claims",
"if",
"it",
"is",
"expired",
"and",
"eventual",
"errors",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L150-L165
|
test
|
256dpi/fire
|
ash/enforcer.go
|
E
|
func E(name string, m fire.Matcher, h fire.Handler) *Enforcer {
return fire.C(name, m, h)
}
|
go
|
func E(name string, m fire.Matcher, h fire.Handler) *Enforcer {
return fire.C(name, m, h)
}
|
[
"func",
"E",
"(",
"name",
"string",
",",
"m",
"fire",
".",
"Matcher",
",",
"h",
"fire",
".",
"Handler",
")",
"*",
"Enforcer",
"{",
"return",
"fire",
".",
"C",
"(",
"name",
",",
"m",
",",
"h",
")",
"\n",
"}"
] |
// E is a short-hand function to create an enforcer.
|
[
"E",
"is",
"a",
"short",
"-",
"hand",
"function",
"to",
"create",
"an",
"enforcer",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/enforcer.go#L10-L12
|
test
|
256dpi/fire
|
coal/model.go
|
MustGet
|
func (b *Base) MustGet(name string) interface{} {
// find field
field := b.meta.Fields[name]
if field == nil {
panic(fmt.Sprintf(`coal: field "%s" not found on "%s"`, name, b.meta.Name))
}
// read value from model struct
structField := reflect.ValueOf(b.model).Elem().Field(field.index)
return structField.Interface()
}
|
go
|
func (b *Base) MustGet(name string) interface{} {
// find field
field := b.meta.Fields[name]
if field == nil {
panic(fmt.Sprintf(`coal: field "%s" not found on "%s"`, name, b.meta.Name))
}
// read value from model struct
structField := reflect.ValueOf(b.model).Elem().Field(field.index)
return structField.Interface()
}
|
[
"func",
"(",
"b",
"*",
"Base",
")",
"MustGet",
"(",
"name",
"string",
")",
"interface",
"{",
"}",
"{",
"field",
":=",
"b",
".",
"meta",
".",
"Fields",
"[",
"name",
"]",
"\n",
"if",
"field",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`coal: field \"%s\" not found on \"%s\"`",
",",
"name",
",",
"b",
".",
"meta",
".",
"Name",
")",
")",
"\n",
"}",
"\n",
"structField",
":=",
"reflect",
".",
"ValueOf",
"(",
"b",
".",
"model",
")",
".",
"Elem",
"(",
")",
".",
"Field",
"(",
"field",
".",
"index",
")",
"\n",
"return",
"structField",
".",
"Interface",
"(",
")",
"\n",
"}"
] |
// MustGet returns the value of the given field. MustGet will panic if no field
// has been found.
|
[
"MustGet",
"returns",
"the",
"value",
"of",
"the",
"given",
"field",
".",
"MustGet",
"will",
"panic",
"if",
"no",
"field",
"has",
"been",
"found",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/model.go#L62-L72
|
test
|
256dpi/fire
|
coal/model.go
|
MustSet
|
func (b *Base) MustSet(name string, value interface{}) {
// find field
field := b.meta.Fields[name]
if field == nil {
panic(fmt.Sprintf(`coal: field "%s" not found on "%s"`, name, b.meta.Name))
}
// set the value on model struct
reflect.ValueOf(b.model).Elem().Field(field.index).Set(reflect.ValueOf(value))
}
|
go
|
func (b *Base) MustSet(name string, value interface{}) {
// find field
field := b.meta.Fields[name]
if field == nil {
panic(fmt.Sprintf(`coal: field "%s" not found on "%s"`, name, b.meta.Name))
}
// set the value on model struct
reflect.ValueOf(b.model).Elem().Field(field.index).Set(reflect.ValueOf(value))
}
|
[
"func",
"(",
"b",
"*",
"Base",
")",
"MustSet",
"(",
"name",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"field",
":=",
"b",
".",
"meta",
".",
"Fields",
"[",
"name",
"]",
"\n",
"if",
"field",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`coal: field \"%s\" not found on \"%s\"`",
",",
"name",
",",
"b",
".",
"meta",
".",
"Name",
")",
")",
"\n",
"}",
"\n",
"reflect",
".",
"ValueOf",
"(",
"b",
".",
"model",
")",
".",
"Elem",
"(",
")",
".",
"Field",
"(",
"field",
".",
"index",
")",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
")",
"\n",
"}"
] |
// MustSet will set the given field to the the passed valued. MustSet will panic
// if no field has been found.
|
[
"MustSet",
"will",
"set",
"the",
"given",
"field",
"to",
"the",
"the",
"passed",
"valued",
".",
"MustSet",
"will",
"panic",
"if",
"no",
"field",
"has",
"been",
"found",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/model.go#L76-L85
|
test
|
256dpi/fire
|
group.go
|
NewGroup
|
func NewGroup() *Group {
return &Group{
controllers: make(map[string]*Controller),
actions: make(map[string]*GroupAction),
}
}
|
go
|
func NewGroup() *Group {
return &Group{
controllers: make(map[string]*Controller),
actions: make(map[string]*GroupAction),
}
}
|
[
"func",
"NewGroup",
"(",
")",
"*",
"Group",
"{",
"return",
"&",
"Group",
"{",
"controllers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Controller",
")",
",",
"actions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"GroupAction",
")",
",",
"}",
"\n",
"}"
] |
// NewGroup creates and returns a new group.
|
[
"NewGroup",
"creates",
"and",
"returns",
"a",
"new",
"group",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/group.go#L35-L40
|
test
|
256dpi/fire
|
group.go
|
Add
|
func (g *Group) Add(controllers ...*Controller) {
for _, controller := range controllers {
// prepare controller
controller.prepare()
// get name
name := controller.Model.Meta().PluralName
// check existence
if g.controllers[name] != nil {
panic(fmt.Sprintf(`fire: controller with name "%s" already exists`, name))
}
// create entry in controller map
g.controllers[name] = controller
}
}
|
go
|
func (g *Group) Add(controllers ...*Controller) {
for _, controller := range controllers {
// prepare controller
controller.prepare()
// get name
name := controller.Model.Meta().PluralName
// check existence
if g.controllers[name] != nil {
panic(fmt.Sprintf(`fire: controller with name "%s" already exists`, name))
}
// create entry in controller map
g.controllers[name] = controller
}
}
|
[
"func",
"(",
"g",
"*",
"Group",
")",
"Add",
"(",
"controllers",
"...",
"*",
"Controller",
")",
"{",
"for",
"_",
",",
"controller",
":=",
"range",
"controllers",
"{",
"controller",
".",
"prepare",
"(",
")",
"\n",
"name",
":=",
"controller",
".",
"Model",
".",
"Meta",
"(",
")",
".",
"PluralName",
"\n",
"if",
"g",
".",
"controllers",
"[",
"name",
"]",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`fire: controller with name \"%s\" already exists`",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"g",
".",
"controllers",
"[",
"name",
"]",
"=",
"controller",
"\n",
"}",
"\n",
"}"
] |
// Add will add a controller to the group.
|
[
"Add",
"will",
"add",
"a",
"controller",
"to",
"the",
"group",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/group.go#L43-L59
|
test
|
256dpi/fire
|
group.go
|
Endpoint
|
func (g *Group) Endpoint(prefix string) http.Handler {
// trim prefix
prefix = strings.Trim(prefix, "/")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// create tracer
tracer := NewTracerFromRequest(r, "fire/Group.Endpoint")
defer tracer.Finish(true)
// continue any previous aborts
defer stack.Resume(func(err error) {
// directly write jsonapi errors
if jsonapiError, ok := err.(*jsonapi.Error); ok {
_ = jsonapi.WriteError(w, jsonapiError)
return
}
// set critical error on last span
tracer.Tag("error", true)
tracer.Log("error", err.Error())
tracer.Log("stack", stack.Trace())
// report critical errors if possible
if g.Reporter != nil {
g.Reporter(err)
}
// ignore errors caused by writing critical errors
_ = jsonapi.WriteError(w, jsonapi.InternalServerError(""))
})
// trim path
path := strings.Trim(r.URL.Path, "/")
path = strings.TrimPrefix(path, prefix)
path = strings.Trim(path, "/")
// check path
if path == "" {
stack.Abort(jsonapi.NotFound("resource not found"))
}
// split path
s := strings.Split(path, "/")
// prepare context
ctx := &Context{
Data: Map{},
HTTPRequest: r,
ResponseWriter: w,
Group: g,
Tracer: tracer,
}
// get controller
controller, ok := g.controllers[s[0]]
if ok {
// set controller
ctx.Controller = controller
// call controller with context
controller.generalHandler(prefix, ctx)
return
}
// get action
action, ok := g.actions[s[0]]
if ok {
// check if action is allowed
if Contains(action.Action.Methods, r.Method) {
// check if action matches the context
if action.Action.Callback.Matcher(ctx) {
// run authorizers and handle errors
for _, cb := range action.Authorizers {
// check if callback should be run
if !cb.Matcher(ctx) {
continue
}
// call callback
err := cb.Handler(ctx)
if IsSafe(err) {
stack.Abort(&jsonapi.Error{
Status: http.StatusUnauthorized,
Detail: err.Error(),
})
} else if err != nil {
stack.Abort(err)
}
}
// limit request body size
LimitBody(ctx.ResponseWriter, ctx.HTTPRequest, int64(action.Action.BodyLimit))
// call action with context
stack.AbortIf(action.Action.Callback.Handler(ctx))
return
}
}
}
// otherwise return error
stack.Abort(jsonapi.NotFound("resource not found"))
})
}
|
go
|
func (g *Group) Endpoint(prefix string) http.Handler {
// trim prefix
prefix = strings.Trim(prefix, "/")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// create tracer
tracer := NewTracerFromRequest(r, "fire/Group.Endpoint")
defer tracer.Finish(true)
// continue any previous aborts
defer stack.Resume(func(err error) {
// directly write jsonapi errors
if jsonapiError, ok := err.(*jsonapi.Error); ok {
_ = jsonapi.WriteError(w, jsonapiError)
return
}
// set critical error on last span
tracer.Tag("error", true)
tracer.Log("error", err.Error())
tracer.Log("stack", stack.Trace())
// report critical errors if possible
if g.Reporter != nil {
g.Reporter(err)
}
// ignore errors caused by writing critical errors
_ = jsonapi.WriteError(w, jsonapi.InternalServerError(""))
})
// trim path
path := strings.Trim(r.URL.Path, "/")
path = strings.TrimPrefix(path, prefix)
path = strings.Trim(path, "/")
// check path
if path == "" {
stack.Abort(jsonapi.NotFound("resource not found"))
}
// split path
s := strings.Split(path, "/")
// prepare context
ctx := &Context{
Data: Map{},
HTTPRequest: r,
ResponseWriter: w,
Group: g,
Tracer: tracer,
}
// get controller
controller, ok := g.controllers[s[0]]
if ok {
// set controller
ctx.Controller = controller
// call controller with context
controller.generalHandler(prefix, ctx)
return
}
// get action
action, ok := g.actions[s[0]]
if ok {
// check if action is allowed
if Contains(action.Action.Methods, r.Method) {
// check if action matches the context
if action.Action.Callback.Matcher(ctx) {
// run authorizers and handle errors
for _, cb := range action.Authorizers {
// check if callback should be run
if !cb.Matcher(ctx) {
continue
}
// call callback
err := cb.Handler(ctx)
if IsSafe(err) {
stack.Abort(&jsonapi.Error{
Status: http.StatusUnauthorized,
Detail: err.Error(),
})
} else if err != nil {
stack.Abort(err)
}
}
// limit request body size
LimitBody(ctx.ResponseWriter, ctx.HTTPRequest, int64(action.Action.BodyLimit))
// call action with context
stack.AbortIf(action.Action.Callback.Handler(ctx))
return
}
}
}
// otherwise return error
stack.Abort(jsonapi.NotFound("resource not found"))
})
}
|
[
"func",
"(",
"g",
"*",
"Group",
")",
"Endpoint",
"(",
"prefix",
"string",
")",
"http",
".",
"Handler",
"{",
"prefix",
"=",
"strings",
".",
"Trim",
"(",
"prefix",
",",
"\"/\"",
")",
"\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"tracer",
":=",
"NewTracerFromRequest",
"(",
"r",
",",
"\"fire/Group.Endpoint\"",
")",
"\n",
"defer",
"tracer",
".",
"Finish",
"(",
"true",
")",
"\n",
"defer",
"stack",
".",
"Resume",
"(",
"func",
"(",
"err",
"error",
")",
"{",
"if",
"jsonapiError",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"jsonapi",
".",
"Error",
")",
";",
"ok",
"{",
"_",
"=",
"jsonapi",
".",
"WriteError",
"(",
"w",
",",
"jsonapiError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"tracer",
".",
"Tag",
"(",
"\"error\"",
",",
"true",
")",
"\n",
"tracer",
".",
"Log",
"(",
"\"error\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"tracer",
".",
"Log",
"(",
"\"stack\"",
",",
"stack",
".",
"Trace",
"(",
")",
")",
"\n",
"if",
"g",
".",
"Reporter",
"!=",
"nil",
"{",
"g",
".",
"Reporter",
"(",
"err",
")",
"\n",
"}",
"\n",
"_",
"=",
"jsonapi",
".",
"WriteError",
"(",
"w",
",",
"jsonapi",
".",
"InternalServerError",
"(",
"\"\"",
")",
")",
"\n",
"}",
")",
"\n",
"path",
":=",
"strings",
".",
"Trim",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"/\"",
")",
"\n",
"path",
"=",
"strings",
".",
"TrimPrefix",
"(",
"path",
",",
"prefix",
")",
"\n",
"path",
"=",
"strings",
".",
"Trim",
"(",
"path",
",",
"\"/\"",
")",
"\n",
"if",
"path",
"==",
"\"\"",
"{",
"stack",
".",
"Abort",
"(",
"jsonapi",
".",
"NotFound",
"(",
"\"resource not found\"",
")",
")",
"\n",
"}",
"\n",
"s",
":=",
"strings",
".",
"Split",
"(",
"path",
",",
"\"/\"",
")",
"\n",
"ctx",
":=",
"&",
"Context",
"{",
"Data",
":",
"Map",
"{",
"}",
",",
"HTTPRequest",
":",
"r",
",",
"ResponseWriter",
":",
"w",
",",
"Group",
":",
"g",
",",
"Tracer",
":",
"tracer",
",",
"}",
"\n",
"controller",
",",
"ok",
":=",
"g",
".",
"controllers",
"[",
"s",
"[",
"0",
"]",
"]",
"\n",
"if",
"ok",
"{",
"ctx",
".",
"Controller",
"=",
"controller",
"\n",
"controller",
".",
"generalHandler",
"(",
"prefix",
",",
"ctx",
")",
"\n",
"return",
"\n",
"}",
"\n",
"action",
",",
"ok",
":=",
"g",
".",
"actions",
"[",
"s",
"[",
"0",
"]",
"]",
"\n",
"if",
"ok",
"{",
"if",
"Contains",
"(",
"action",
".",
"Action",
".",
"Methods",
",",
"r",
".",
"Method",
")",
"{",
"if",
"action",
".",
"Action",
".",
"Callback",
".",
"Matcher",
"(",
"ctx",
")",
"{",
"for",
"_",
",",
"cb",
":=",
"range",
"action",
".",
"Authorizers",
"{",
"if",
"!",
"cb",
".",
"Matcher",
"(",
"ctx",
")",
"{",
"continue",
"\n",
"}",
"\n",
"err",
":=",
"cb",
".",
"Handler",
"(",
"ctx",
")",
"\n",
"if",
"IsSafe",
"(",
"err",
")",
"{",
"stack",
".",
"Abort",
"(",
"&",
"jsonapi",
".",
"Error",
"{",
"Status",
":",
"http",
".",
"StatusUnauthorized",
",",
"Detail",
":",
"err",
".",
"Error",
"(",
")",
",",
"}",
")",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"stack",
".",
"Abort",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"LimitBody",
"(",
"ctx",
".",
"ResponseWriter",
",",
"ctx",
".",
"HTTPRequest",
",",
"int64",
"(",
"action",
".",
"Action",
".",
"BodyLimit",
")",
")",
"\n",
"stack",
".",
"AbortIf",
"(",
"action",
".",
"Action",
".",
"Callback",
".",
"Handler",
"(",
"ctx",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"stack",
".",
"Abort",
"(",
"jsonapi",
".",
"NotFound",
"(",
"\"resource not found\"",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Endpoint will return an http handler that serves requests for this group. The
// specified prefix is used to parse the requests and generate urls for the
// resources.
|
[
"Endpoint",
"will",
"return",
"an",
"http",
"handler",
"that",
"serves",
"requests",
"for",
"this",
"group",
".",
"The",
"specified",
"prefix",
"is",
"used",
"to",
"parse",
"the",
"requests",
"and",
"generate",
"urls",
"for",
"the",
"resources",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/group.go#L87-L192
|
test
|
256dpi/fire
|
coal/indexer.go
|
Add
|
func (i *Indexer) Add(model Model, unique bool, expireAfter time.Duration, fields ...string) {
// construct key from fields
var key []string
for _, f := range fields {
key = append(key, F(model, f))
}
// add index
i.AddRaw(C(model), mgo.Index{
Key: key,
Unique: unique,
ExpireAfter: expireAfter,
Background: true,
})
}
|
go
|
func (i *Indexer) Add(model Model, unique bool, expireAfter time.Duration, fields ...string) {
// construct key from fields
var key []string
for _, f := range fields {
key = append(key, F(model, f))
}
// add index
i.AddRaw(C(model), mgo.Index{
Key: key,
Unique: unique,
ExpireAfter: expireAfter,
Background: true,
})
}
|
[
"func",
"(",
"i",
"*",
"Indexer",
")",
"Add",
"(",
"model",
"Model",
",",
"unique",
"bool",
",",
"expireAfter",
"time",
".",
"Duration",
",",
"fields",
"...",
"string",
")",
"{",
"var",
"key",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"fields",
"{",
"key",
"=",
"append",
"(",
"key",
",",
"F",
"(",
"model",
",",
"f",
")",
")",
"\n",
"}",
"\n",
"i",
".",
"AddRaw",
"(",
"C",
"(",
"model",
")",
",",
"mgo",
".",
"Index",
"{",
"Key",
":",
"key",
",",
"Unique",
":",
"unique",
",",
"ExpireAfter",
":",
"expireAfter",
",",
"Background",
":",
"true",
",",
"}",
")",
"\n",
"}"
] |
// Add will add an index to the internal index list. Fields that are prefixed
// with a dash will result in an descending index. See the MongoDB documentation
// for more details.
|
[
"Add",
"will",
"add",
"an",
"index",
"to",
"the",
"internal",
"index",
"list",
".",
"Fields",
"that",
"are",
"prefixed",
"with",
"a",
"dash",
"will",
"result",
"in",
"an",
"descending",
"index",
".",
"See",
"the",
"MongoDB",
"documentation",
"for",
"more",
"details",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/indexer.go#L28-L42
|
test
|
256dpi/fire
|
coal/indexer.go
|
AddRaw
|
func (i *Indexer) AddRaw(coll string, idx mgo.Index) {
i.indexes = append(i.indexes, index{
coll: coll,
index: idx,
})
}
|
go
|
func (i *Indexer) AddRaw(coll string, idx mgo.Index) {
i.indexes = append(i.indexes, index{
coll: coll,
index: idx,
})
}
|
[
"func",
"(",
"i",
"*",
"Indexer",
")",
"AddRaw",
"(",
"coll",
"string",
",",
"idx",
"mgo",
".",
"Index",
")",
"{",
"i",
".",
"indexes",
"=",
"append",
"(",
"i",
".",
"indexes",
",",
"index",
"{",
"coll",
":",
"coll",
",",
"index",
":",
"idx",
",",
"}",
")",
"\n",
"}"
] |
// AddRaw will add a raw mgo.Index to the internal index list.
|
[
"AddRaw",
"will",
"add",
"a",
"raw",
"mgo",
".",
"Index",
"to",
"the",
"internal",
"index",
"list",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/indexer.go#L63-L68
|
test
|
256dpi/fire
|
coal/indexer.go
|
Ensure
|
func (i *Indexer) Ensure(store *Store) error {
// copy store
s := store.Copy()
defer s.Close()
// go through all raw indexes
for _, i := range i.indexes {
// ensure single index
err := s.DB().C(i.coll).EnsureIndex(i.index)
if err != nil {
return err
}
}
return nil
}
|
go
|
func (i *Indexer) Ensure(store *Store) error {
// copy store
s := store.Copy()
defer s.Close()
// go through all raw indexes
for _, i := range i.indexes {
// ensure single index
err := s.DB().C(i.coll).EnsureIndex(i.index)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"i",
"*",
"Indexer",
")",
"Ensure",
"(",
"store",
"*",
"Store",
")",
"error",
"{",
"s",
":=",
"store",
".",
"Copy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"i",
".",
"indexes",
"{",
"err",
":=",
"s",
".",
"DB",
"(",
")",
".",
"C",
"(",
"i",
".",
"coll",
")",
".",
"EnsureIndex",
"(",
"i",
".",
"index",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Ensure will ensure that the required indexes exist. It may fail early if some
// of the indexes are already existing and do not match the supplied index.
|
[
"Ensure",
"will",
"ensure",
"that",
"the",
"required",
"indexes",
"exist",
".",
"It",
"may",
"fail",
"early",
"if",
"some",
"of",
"the",
"indexes",
"are",
"already",
"existing",
"and",
"do",
"not",
"match",
"the",
"supplied",
"index",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/indexer.go#L72-L87
|
test
|
256dpi/fire
|
coal/catalog.go
|
NewCatalog
|
func NewCatalog(models ...Model) *Catalog {
// create catalog
c := &Catalog{
models: make(map[string]Model),
}
// add models
c.Add(models...)
return c
}
|
go
|
func NewCatalog(models ...Model) *Catalog {
// create catalog
c := &Catalog{
models: make(map[string]Model),
}
// add models
c.Add(models...)
return c
}
|
[
"func",
"NewCatalog",
"(",
"models",
"...",
"Model",
")",
"*",
"Catalog",
"{",
"c",
":=",
"&",
"Catalog",
"{",
"models",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Model",
")",
",",
"}",
"\n",
"c",
".",
"Add",
"(",
"models",
"...",
")",
"\n",
"return",
"c",
"\n",
"}"
] |
// NewCatalog will create a new catalog.
|
[
"NewCatalog",
"will",
"create",
"a",
"new",
"catalog",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/catalog.go#L15-L25
|
test
|
256dpi/fire
|
coal/catalog.go
|
Add
|
func (c *Catalog) Add(models ...Model) {
for _, model := range models {
// get name
name := Init(model).Meta().PluralName
// check existence
if c.models[name] != nil {
panic(fmt.Sprintf(`coal: model with name "%s" already exists in catalog`, name))
}
// add model
c.models[name] = model
}
}
|
go
|
func (c *Catalog) Add(models ...Model) {
for _, model := range models {
// get name
name := Init(model).Meta().PluralName
// check existence
if c.models[name] != nil {
panic(fmt.Sprintf(`coal: model with name "%s" already exists in catalog`, name))
}
// add model
c.models[name] = model
}
}
|
[
"func",
"(",
"c",
"*",
"Catalog",
")",
"Add",
"(",
"models",
"...",
"Model",
")",
"{",
"for",
"_",
",",
"model",
":=",
"range",
"models",
"{",
"name",
":=",
"Init",
"(",
"model",
")",
".",
"Meta",
"(",
")",
".",
"PluralName",
"\n",
"if",
"c",
".",
"models",
"[",
"name",
"]",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`coal: model with name \"%s\" already exists in catalog`",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"models",
"[",
"name",
"]",
"=",
"model",
"\n",
"}",
"\n",
"}"
] |
// Add will add the specified models to the catalog.
|
[
"Add",
"will",
"add",
"the",
"specified",
"models",
"to",
"the",
"catalog",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/catalog.go#L28-L41
|
test
|
256dpi/fire
|
coal/catalog.go
|
All
|
func (c *Catalog) All() []Model {
// prepare models
models := make([]Model, 0, len(c.models))
// add models
for _, model := range c.models {
models = append(models, model)
}
return models
}
|
go
|
func (c *Catalog) All() []Model {
// prepare models
models := make([]Model, 0, len(c.models))
// add models
for _, model := range c.models {
models = append(models, model)
}
return models
}
|
[
"func",
"(",
"c",
"*",
"Catalog",
")",
"All",
"(",
")",
"[",
"]",
"Model",
"{",
"models",
":=",
"make",
"(",
"[",
"]",
"Model",
",",
"0",
",",
"len",
"(",
"c",
".",
"models",
")",
")",
"\n",
"for",
"_",
",",
"model",
":=",
"range",
"c",
".",
"models",
"{",
"models",
"=",
"append",
"(",
"models",
",",
"model",
")",
"\n",
"}",
"\n",
"return",
"models",
"\n",
"}"
] |
// All returns a list of all registered models.
|
[
"All",
"returns",
"a",
"list",
"of",
"all",
"registered",
"models",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/catalog.go#L49-L59
|
test
|
256dpi/fire
|
coal/catalog.go
|
Visualize
|
func (c *Catalog) Visualize(title string) string {
// prepare buffer
var out bytes.Buffer
// start graph
out.WriteString("graph G {\n")
out.WriteString(" rankdir=\"LR\";\n")
out.WriteString(" sep=\"0.3\";\n")
out.WriteString(" ranksep=\"0.5\";\n")
out.WriteString(" nodesep=\"0.4\";\n")
out.WriteString(" pad=\"0.4,0.4\";\n")
out.WriteString(" margin=\"0,0\";\n")
out.WriteString(" labelloc=\"t\";\n")
out.WriteString(" fontsize=\"13\";\n")
out.WriteString(" fontname=\"Arial BoldMT\";\n")
out.WriteString(" splines=\"spline\";\n")
out.WriteString(" overlap=\"voronoi\";\n")
out.WriteString(" outputorder=\"edgesfirst\";\n")
out.WriteString(" edge[headclip=true, tailclip=false];\n")
out.WriteString(" label=\"" + title + "\";\n")
// get a sorted list of model names and lookup table
var names []string
lookup := make(map[string]string)
for name, model := range c.models {
names = append(names, name)
lookup[name] = model.Meta().Name
}
sort.Strings(names)
// add model nodes
for _, name := range names {
// get model
model := c.models[name]
// write begin of node
out.WriteString(fmt.Sprintf(` "%s" [ style=filled, fillcolor=white, label=`, lookup[name]))
// write head table
out.WriteString(fmt.Sprintf(`<<table border="0" align="center" cellspacing="0.5" cellpadding="0" width="134"><tr><td align="center" valign="bottom" width="130"><font face="Arial BoldMT" point-size="11">%s</font></td></tr></table>|`, lookup[name]))
// write begin of tail table
out.WriteString(fmt.Sprintf(`<table border="0" align="left" cellspacing="2" cellpadding="0" width="134">`))
// write attributes
for _, field := range model.Meta().OrderedFields {
out.WriteString(fmt.Sprintf(`<tr><td align="left" width="130" port="%s">%s<font face="Arial ItalicMT" color="grey60"> %s</font></td></tr>`, field.Name, field.Name, field.Type.String()))
}
// write end of tail table
out.WriteString(fmt.Sprintf(`</table>>`))
// write end of node
out.WriteString(`, shape=Mrecord, fontsize=10, fontname="ArialMT", margin="0.07,0.05", penwidth="1.0" ];` + "\n")
}
// define temporary struct
type rel struct {
from, to string
srcMany bool
dstMany bool
hasInverse bool
}
// prepare list
list := make(map[string]*rel)
var relNames []string
// prepare relationships
for _, name := range names {
// get model
model := c.models[name]
// add all direct relationships
for _, field := range model.Meta().OrderedFields {
if field.RelName != "" && (field.ToOne || field.ToMany) {
list[name+"-"+field.RelName] = &rel{
from: name,
to: field.RelType,
srcMany: field.ToMany,
}
relNames = append(relNames, name+"-"+field.RelName)
}
}
}
// update relationships
for _, name := range names {
// get model
model := c.models[name]
// add all indirect relationships
for _, field := range model.Meta().OrderedFields {
if field.RelName != "" && (field.HasOne || field.HasMany) {
r := list[field.RelType+"-"+field.RelInverse]
r.dstMany = field.HasMany
r.hasInverse = true
}
}
}
// sort relationship names
sort.Strings(relNames)
// add relationships
for _, name := range relNames {
// get relationship
r := list[name]
// get style
style := "solid"
if !r.hasInverse {
style = "dotted"
}
// get color
color := "black"
if r.srcMany {
color = "black:white:black"
}
// write edge
out.WriteString(fmt.Sprintf(` "%s"--"%s"[ fontname="ArialMT", fontsize=7, dir=both, arrowsize="0.9", penwidth="0.9", labelangle=32, labeldistance="1.8", style=%s, color="%s", arrowhead=%s, arrowtail=%s ];`, lookup[r.from], lookup[r.to], style, color, "normal", "none") + "\n")
}
// end graph
out.WriteString("}\n")
return out.String()
}
|
go
|
func (c *Catalog) Visualize(title string) string {
// prepare buffer
var out bytes.Buffer
// start graph
out.WriteString("graph G {\n")
out.WriteString(" rankdir=\"LR\";\n")
out.WriteString(" sep=\"0.3\";\n")
out.WriteString(" ranksep=\"0.5\";\n")
out.WriteString(" nodesep=\"0.4\";\n")
out.WriteString(" pad=\"0.4,0.4\";\n")
out.WriteString(" margin=\"0,0\";\n")
out.WriteString(" labelloc=\"t\";\n")
out.WriteString(" fontsize=\"13\";\n")
out.WriteString(" fontname=\"Arial BoldMT\";\n")
out.WriteString(" splines=\"spline\";\n")
out.WriteString(" overlap=\"voronoi\";\n")
out.WriteString(" outputorder=\"edgesfirst\";\n")
out.WriteString(" edge[headclip=true, tailclip=false];\n")
out.WriteString(" label=\"" + title + "\";\n")
// get a sorted list of model names and lookup table
var names []string
lookup := make(map[string]string)
for name, model := range c.models {
names = append(names, name)
lookup[name] = model.Meta().Name
}
sort.Strings(names)
// add model nodes
for _, name := range names {
// get model
model := c.models[name]
// write begin of node
out.WriteString(fmt.Sprintf(` "%s" [ style=filled, fillcolor=white, label=`, lookup[name]))
// write head table
out.WriteString(fmt.Sprintf(`<<table border="0" align="center" cellspacing="0.5" cellpadding="0" width="134"><tr><td align="center" valign="bottom" width="130"><font face="Arial BoldMT" point-size="11">%s</font></td></tr></table>|`, lookup[name]))
// write begin of tail table
out.WriteString(fmt.Sprintf(`<table border="0" align="left" cellspacing="2" cellpadding="0" width="134">`))
// write attributes
for _, field := range model.Meta().OrderedFields {
out.WriteString(fmt.Sprintf(`<tr><td align="left" width="130" port="%s">%s<font face="Arial ItalicMT" color="grey60"> %s</font></td></tr>`, field.Name, field.Name, field.Type.String()))
}
// write end of tail table
out.WriteString(fmt.Sprintf(`</table>>`))
// write end of node
out.WriteString(`, shape=Mrecord, fontsize=10, fontname="ArialMT", margin="0.07,0.05", penwidth="1.0" ];` + "\n")
}
// define temporary struct
type rel struct {
from, to string
srcMany bool
dstMany bool
hasInverse bool
}
// prepare list
list := make(map[string]*rel)
var relNames []string
// prepare relationships
for _, name := range names {
// get model
model := c.models[name]
// add all direct relationships
for _, field := range model.Meta().OrderedFields {
if field.RelName != "" && (field.ToOne || field.ToMany) {
list[name+"-"+field.RelName] = &rel{
from: name,
to: field.RelType,
srcMany: field.ToMany,
}
relNames = append(relNames, name+"-"+field.RelName)
}
}
}
// update relationships
for _, name := range names {
// get model
model := c.models[name]
// add all indirect relationships
for _, field := range model.Meta().OrderedFields {
if field.RelName != "" && (field.HasOne || field.HasMany) {
r := list[field.RelType+"-"+field.RelInverse]
r.dstMany = field.HasMany
r.hasInverse = true
}
}
}
// sort relationship names
sort.Strings(relNames)
// add relationships
for _, name := range relNames {
// get relationship
r := list[name]
// get style
style := "solid"
if !r.hasInverse {
style = "dotted"
}
// get color
color := "black"
if r.srcMany {
color = "black:white:black"
}
// write edge
out.WriteString(fmt.Sprintf(` "%s"--"%s"[ fontname="ArialMT", fontsize=7, dir=both, arrowsize="0.9", penwidth="0.9", labelangle=32, labeldistance="1.8", style=%s, color="%s", arrowhead=%s, arrowtail=%s ];`, lookup[r.from], lookup[r.to], style, color, "normal", "none") + "\n")
}
// end graph
out.WriteString("}\n")
return out.String()
}
|
[
"func",
"(",
"c",
"*",
"Catalog",
")",
"Visualize",
"(",
"title",
"string",
")",
"string",
"{",
"var",
"out",
"bytes",
".",
"Buffer",
"\n",
"out",
".",
"WriteString",
"(",
"\"graph G {\\n\"",
")",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" rankdir=\\\"LR\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" sep=\\\"0.3\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" ranksep=\\\"0.5\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" nodesep=\\\"0.4\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" pad=\\\"0.4,0.4\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" margin=\\\"0,0\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\n",
"\n",
"out",
".",
"WriteString",
"(",
"\" labelloc=\\\"t\\\";\\n\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"}"
] |
// Visualize emits a string in dot format which when rendered with graphviz
// visualizes the models and their relationships.
|
[
"Visualize",
"emits",
"a",
"string",
"in",
"dot",
"format",
"which",
"when",
"rendered",
"with",
"graphviz",
"visualizes",
"the",
"models",
"and",
"their",
"relationships",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/catalog.go#L63-L193
|
test
|
256dpi/fire
|
wood/error_reporter.go
|
NewErrorReporter
|
func NewErrorReporter(out io.Writer) func(error) {
return func(err error) {
_, _ = fmt.Fprintf(out, "===> Begin Error: %s\n", err.Error())
_, _ = out.Write(debug.Stack())
_, _ = fmt.Fprintln(out, "<=== End Error")
}
}
|
go
|
func NewErrorReporter(out io.Writer) func(error) {
return func(err error) {
_, _ = fmt.Fprintf(out, "===> Begin Error: %s\n", err.Error())
_, _ = out.Write(debug.Stack())
_, _ = fmt.Fprintln(out, "<=== End Error")
}
}
|
[
"func",
"NewErrorReporter",
"(",
"out",
"io",
".",
"Writer",
")",
"func",
"(",
"error",
")",
"{",
"return",
"func",
"(",
"err",
"error",
")",
"{",
"_",
",",
"_",
"=",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"===> Begin Error: %s\\n\"",
",",
"\\n",
")",
"\n",
"err",
".",
"Error",
"(",
")",
"\n",
"_",
",",
"_",
"=",
"out",
".",
"Write",
"(",
"debug",
".",
"Stack",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// NewErrorReporter returns a very basic reporter that writes errors and stack
// traces to the specified writer.
|
[
"NewErrorReporter",
"returns",
"a",
"very",
"basic",
"reporter",
"that",
"writes",
"errors",
"and",
"stack",
"traces",
"to",
"the",
"specified",
"writer",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/wood/error_reporter.go#L17-L23
|
test
|
256dpi/fire
|
example/models.go
|
EnsureIndexes
|
func EnsureIndexes(store *coal.Store) error {
// ensure model indexes
err := indexer.Ensure(store)
if err != nil {
return err
}
return nil
}
|
go
|
func EnsureIndexes(store *coal.Store) error {
// ensure model indexes
err := indexer.Ensure(store)
if err != nil {
return err
}
return nil
}
|
[
"func",
"EnsureIndexes",
"(",
"store",
"*",
"coal",
".",
"Store",
")",
"error",
"{",
"err",
":=",
"indexer",
".",
"Ensure",
"(",
"store",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// EnsureIndexes will ensure that the required indexes exist.
|
[
"EnsureIndexes",
"will",
"ensure",
"that",
"the",
"required",
"indexes",
"exist",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/example/models.go#L36-L44
|
test
|
256dpi/fire
|
helpers.go
|
E
|
func E(format string, a ...interface{}) error {
return Safe(fmt.Errorf(format, a...))
}
|
go
|
func E(format string, a ...interface{}) error {
return Safe(fmt.Errorf(format, a...))
}
|
[
"func",
"E",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Safe",
"(",
"fmt",
".",
"Errorf",
"(",
"format",
",",
"a",
"...",
")",
")",
"\n",
"}"
] |
// E is a short-hand function to construct a safe error.
|
[
"E",
"is",
"a",
"short",
"-",
"hand",
"function",
"to",
"construct",
"a",
"safe",
"error",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/helpers.go#L17-L19
|
test
|
256dpi/fire
|
helpers.go
|
Compose
|
func Compose(chain ...interface{}) http.Handler {
// check length
if len(chain) < 2 {
panic("fire: expected chain to have at least two items")
}
// get handler
h, ok := chain[len(chain)-1].(http.Handler)
if !ok {
panic(`fire: expected last chain item to be a "http.Handler"`)
}
// chain all middleware
for i := len(chain) - 2; i >= 0; i-- {
// get middleware
m, ok := chain[i].(func(http.Handler) http.Handler)
if !ok {
panic(`fire: expected intermediary chain item to be a "func(http.handler) http.Handler"`)
}
// chain
h = m(h)
}
return h
}
|
go
|
func Compose(chain ...interface{}) http.Handler {
// check length
if len(chain) < 2 {
panic("fire: expected chain to have at least two items")
}
// get handler
h, ok := chain[len(chain)-1].(http.Handler)
if !ok {
panic(`fire: expected last chain item to be a "http.Handler"`)
}
// chain all middleware
for i := len(chain) - 2; i >= 0; i-- {
// get middleware
m, ok := chain[i].(func(http.Handler) http.Handler)
if !ok {
panic(`fire: expected intermediary chain item to be a "func(http.handler) http.Handler"`)
}
// chain
h = m(h)
}
return h
}
|
[
"func",
"Compose",
"(",
"chain",
"...",
"interface",
"{",
"}",
")",
"http",
".",
"Handler",
"{",
"if",
"len",
"(",
"chain",
")",
"<",
"2",
"{",
"panic",
"(",
"\"fire: expected chain to have at least two items\"",
")",
"\n",
"}",
"\n",
"h",
",",
"ok",
":=",
"chain",
"[",
"len",
"(",
"chain",
")",
"-",
"1",
"]",
".",
"(",
"http",
".",
"Handler",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"`fire: expected last chain item to be a \"http.Handler\"`",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"len",
"(",
"chain",
")",
"-",
"2",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"m",
",",
"ok",
":=",
"chain",
"[",
"i",
"]",
".",
"(",
"func",
"(",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"`fire: expected intermediary chain item to be a \"func(http.handler) http.Handler\"`",
")",
"\n",
"}",
"\n",
"h",
"=",
"m",
"(",
"h",
")",
"\n",
"}",
"\n",
"return",
"h",
"\n",
"}"
] |
// Compose is a short-hand for chaining the specified middleware and handler
// together.
|
[
"Compose",
"is",
"a",
"short",
"-",
"hand",
"for",
"chaining",
"the",
"specified",
"middleware",
"and",
"handler",
"together",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/helpers.go#L41-L66
|
test
|
256dpi/fire
|
helpers.go
|
Includes
|
func Includes(all, subset []string) bool {
for _, item := range subset {
if !Contains(all, item) {
return false
}
}
return true
}
|
go
|
func Includes(all, subset []string) bool {
for _, item := range subset {
if !Contains(all, item) {
return false
}
}
return true
}
|
[
"func",
"Includes",
"(",
"all",
",",
"subset",
"[",
"]",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"item",
":=",
"range",
"subset",
"{",
"if",
"!",
"Contains",
"(",
"all",
",",
"item",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Includes returns true if a list of strings includes another list of strings.
|
[
"Includes",
"returns",
"true",
"if",
"a",
"list",
"of",
"strings",
"includes",
"another",
"list",
"of",
"strings",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/helpers.go#L112-L120
|
test
|
256dpi/fire
|
helpers.go
|
Intersect
|
func Intersect(listA, listB []string) []string {
// prepare new list
list := make([]string, 0, len(listA))
// add items that are part of both lists
for _, item := range listA {
if Contains(listB, item) {
list = append(list, item)
}
}
return list
}
|
go
|
func Intersect(listA, listB []string) []string {
// prepare new list
list := make([]string, 0, len(listA))
// add items that are part of both lists
for _, item := range listA {
if Contains(listB, item) {
list = append(list, item)
}
}
return list
}
|
[
"func",
"Intersect",
"(",
"listA",
",",
"listB",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"list",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"listA",
")",
")",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"listA",
"{",
"if",
"Contains",
"(",
"listB",
",",
"item",
")",
"{",
"list",
"=",
"append",
"(",
"list",
",",
"item",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"list",
"\n",
"}"
] |
// Intersect will return the intersection of both lists.
|
[
"Intersect",
"will",
"return",
"the",
"intersection",
"of",
"both",
"lists",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/helpers.go#L123-L135
|
test
|
256dpi/fire
|
axe/task.go
|
E
|
func E(reason string, retry bool) *Error {
return &Error{
Reason: reason,
Retry: retry,
}
}
|
go
|
func E(reason string, retry bool) *Error {
return &Error{
Reason: reason,
Retry: retry,
}
}
|
[
"func",
"E",
"(",
"reason",
"string",
",",
"retry",
"bool",
")",
"*",
"Error",
"{",
"return",
"&",
"Error",
"{",
"Reason",
":",
"reason",
",",
"Retry",
":",
"retry",
",",
"}",
"\n",
"}"
] |
// E is a short-hand to construct an error.
|
[
"E",
"is",
"a",
"short",
"-",
"hand",
"to",
"construct",
"an",
"error",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/task.go#L22-L27
|
test
|
256dpi/fire
|
tracer.go
|
RootTracer
|
func RootTracer() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// split url
segments := strings.Split(r.URL.Path, "/")
// replace ids
for i, s := range segments {
if bson.IsObjectIdHex(s) {
segments[i] = ":id"
}
}
// construct name
path := strings.Join(segments, "/")
name := fmt.Sprintf("%s %s", r.Method, path)
// create root span from request
tracer := NewTracerFromRequest(r, name)
tracer.Tag("peer.address", r.RemoteAddr)
tracer.Tag("http.proto", r.Proto)
tracer.Tag("http.method", r.Method)
tracer.Tag("http.host", r.Host)
tracer.Log("http.url", r.URL.String())
tracer.Log("http.length", r.ContentLength)
tracer.Log("http.header", r.Header)
r = r.WithContext(tracer.Context(r.Context()))
defer tracer.Finish(true)
// call next handler
next.ServeHTTP(w, r)
})
}
}
|
go
|
func RootTracer() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// split url
segments := strings.Split(r.URL.Path, "/")
// replace ids
for i, s := range segments {
if bson.IsObjectIdHex(s) {
segments[i] = ":id"
}
}
// construct name
path := strings.Join(segments, "/")
name := fmt.Sprintf("%s %s", r.Method, path)
// create root span from request
tracer := NewTracerFromRequest(r, name)
tracer.Tag("peer.address", r.RemoteAddr)
tracer.Tag("http.proto", r.Proto)
tracer.Tag("http.method", r.Method)
tracer.Tag("http.host", r.Host)
tracer.Log("http.url", r.URL.String())
tracer.Log("http.length", r.ContentLength)
tracer.Log("http.header", r.Header)
r = r.WithContext(tracer.Context(r.Context()))
defer tracer.Finish(true)
// call next handler
next.ServeHTTP(w, r)
})
}
}
|
[
"func",
"RootTracer",
"(",
")",
"func",
"(",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"func",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"segments",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"/\"",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"segments",
"{",
"if",
"bson",
".",
"IsObjectIdHex",
"(",
"s",
")",
"{",
"segments",
"[",
"i",
"]",
"=",
"\":id\"",
"\n",
"}",
"\n",
"}",
"\n",
"path",
":=",
"strings",
".",
"Join",
"(",
"segments",
",",
"\"/\"",
")",
"\n",
"name",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s %s\"",
",",
"r",
".",
"Method",
",",
"path",
")",
"\n",
"tracer",
":=",
"NewTracerFromRequest",
"(",
"r",
",",
"name",
")",
"\n",
"tracer",
".",
"Tag",
"(",
"\"peer.address\"",
",",
"r",
".",
"RemoteAddr",
")",
"\n",
"tracer",
".",
"Tag",
"(",
"\"http.proto\"",
",",
"r",
".",
"Proto",
")",
"\n",
"tracer",
".",
"Tag",
"(",
"\"http.method\"",
",",
"r",
".",
"Method",
")",
"\n",
"tracer",
".",
"Tag",
"(",
"\"http.host\"",
",",
"r",
".",
"Host",
")",
"\n",
"tracer",
".",
"Log",
"(",
"\"http.url\"",
",",
"r",
".",
"URL",
".",
"String",
"(",
")",
")",
"\n",
"tracer",
".",
"Log",
"(",
"\"http.length\"",
",",
"r",
".",
"ContentLength",
")",
"\n",
"tracer",
".",
"Log",
"(",
"\"http.header\"",
",",
"r",
".",
"Header",
")",
"\n",
"r",
"=",
"r",
".",
"WithContext",
"(",
"tracer",
".",
"Context",
"(",
"r",
".",
"Context",
"(",
")",
")",
")",
"\n",
"defer",
"tracer",
".",
"Finish",
"(",
"true",
")",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// RootTracer is a middleware that can be used to create root trace span for an
// incoming request.
|
[
"RootTracer",
"is",
"a",
"middleware",
"that",
"can",
"be",
"used",
"to",
"create",
"root",
"trace",
"span",
"for",
"an",
"incoming",
"request",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L15-L48
|
test
|
256dpi/fire
|
tracer.go
|
NewTracerFromRequest
|
func NewTracerFromRequest(r *http.Request, name string) *Tracer {
span, _ := opentracing.StartSpanFromContext(r.Context(), name)
return NewTracer(span)
}
|
go
|
func NewTracerFromRequest(r *http.Request, name string) *Tracer {
span, _ := opentracing.StartSpanFromContext(r.Context(), name)
return NewTracer(span)
}
|
[
"func",
"NewTracerFromRequest",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"name",
"string",
")",
"*",
"Tracer",
"{",
"span",
",",
"_",
":=",
"opentracing",
".",
"StartSpanFromContext",
"(",
"r",
".",
"Context",
"(",
")",
",",
"name",
")",
"\n",
"return",
"NewTracer",
"(",
"span",
")",
"\n",
"}"
] |
// NewTracerFromRequest returns a new tracer that has a root span derived from
// the specified request. A span previously added to the request context using
// Context is automatically used as the parent.
|
[
"NewTracerFromRequest",
"returns",
"a",
"new",
"tracer",
"that",
"has",
"a",
"root",
"span",
"derived",
"from",
"the",
"specified",
"request",
".",
"A",
"span",
"previously",
"added",
"to",
"the",
"request",
"context",
"using",
"Context",
"is",
"automatically",
"used",
"as",
"the",
"parent",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L60-L63
|
test
|
256dpi/fire
|
tracer.go
|
NewTracer
|
func NewTracer(root opentracing.Span) *Tracer {
return &Tracer{
root: root,
spans: make([]opentracing.Span, 0, 32),
}
}
|
go
|
func NewTracer(root opentracing.Span) *Tracer {
return &Tracer{
root: root,
spans: make([]opentracing.Span, 0, 32),
}
}
|
[
"func",
"NewTracer",
"(",
"root",
"opentracing",
".",
"Span",
")",
"*",
"Tracer",
"{",
"return",
"&",
"Tracer",
"{",
"root",
":",
"root",
",",
"spans",
":",
"make",
"(",
"[",
"]",
"opentracing",
".",
"Span",
",",
"0",
",",
"32",
")",
",",
"}",
"\n",
"}"
] |
// NewTracer returns a new tracer with the specified root span.
|
[
"NewTracer",
"returns",
"a",
"new",
"tracer",
"with",
"the",
"specified",
"root",
"span",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L72-L77
|
test
|
256dpi/fire
|
tracer.go
|
Push
|
func (t *Tracer) Push(name string) {
// get context
var ctx opentracing.SpanContext
if len(t.spans) > 0 {
ctx = t.Last().Context()
} else {
ctx = t.root.Context()
}
// create new span
span := opentracing.StartSpan(name, opentracing.ChildOf(ctx))
// push span
t.spans = append(t.spans, span)
}
|
go
|
func (t *Tracer) Push(name string) {
// get context
var ctx opentracing.SpanContext
if len(t.spans) > 0 {
ctx = t.Last().Context()
} else {
ctx = t.root.Context()
}
// create new span
span := opentracing.StartSpan(name, opentracing.ChildOf(ctx))
// push span
t.spans = append(t.spans, span)
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Push",
"(",
"name",
"string",
")",
"{",
"var",
"ctx",
"opentracing",
".",
"SpanContext",
"\n",
"if",
"len",
"(",
"t",
".",
"spans",
")",
">",
"0",
"{",
"ctx",
"=",
"t",
".",
"Last",
"(",
")",
".",
"Context",
"(",
")",
"\n",
"}",
"else",
"{",
"ctx",
"=",
"t",
".",
"root",
".",
"Context",
"(",
")",
"\n",
"}",
"\n",
"span",
":=",
"opentracing",
".",
"StartSpan",
"(",
"name",
",",
"opentracing",
".",
"ChildOf",
"(",
"ctx",
")",
")",
"\n",
"t",
".",
"spans",
"=",
"append",
"(",
"t",
".",
"spans",
",",
"span",
")",
"\n",
"}"
] |
// Push will add a new span on to the stack. Successful spans must be finished by
// calling Pop. If the code panics or an error is returned the last pushed span
// will be flagged with the error and a leftover spans are popped.
|
[
"Push",
"will",
"add",
"a",
"new",
"span",
"on",
"to",
"the",
"stack",
".",
"Successful",
"spans",
"must",
"be",
"finished",
"by",
"calling",
"Pop",
".",
"If",
"the",
"code",
"panics",
"or",
"an",
"error",
"is",
"returned",
"the",
"last",
"pushed",
"span",
"will",
"be",
"flagged",
"with",
"the",
"error",
"and",
"a",
"leftover",
"spans",
"are",
"popped",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L82-L96
|
test
|
256dpi/fire
|
tracer.go
|
Last
|
func (t *Tracer) Last() opentracing.Span {
// return root if empty
if len(t.spans) == 0 {
return t.root
}
return t.spans[len(t.spans)-1]
}
|
go
|
func (t *Tracer) Last() opentracing.Span {
// return root if empty
if len(t.spans) == 0 {
return t.root
}
return t.spans[len(t.spans)-1]
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Last",
"(",
")",
"opentracing",
".",
"Span",
"{",
"if",
"len",
"(",
"t",
".",
"spans",
")",
"==",
"0",
"{",
"return",
"t",
".",
"root",
"\n",
"}",
"\n",
"return",
"t",
".",
"spans",
"[",
"len",
"(",
"t",
".",
"spans",
")",
"-",
"1",
"]",
"\n",
"}"
] |
// Last returns the last pushed span or the root span.
|
[
"Last",
"returns",
"the",
"last",
"pushed",
"span",
"or",
"the",
"root",
"span",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L99-L106
|
test
|
256dpi/fire
|
tracer.go
|
Tag
|
func (t *Tracer) Tag(key string, value interface{}) {
t.Last().SetTag(key, value)
}
|
go
|
func (t *Tracer) Tag(key string, value interface{}) {
t.Last().SetTag(key, value)
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Tag",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"Last",
"(",
")",
".",
"SetTag",
"(",
"key",
",",
"value",
")",
"\n",
"}"
] |
// Tag adds a tag to the last pushed span.
|
[
"Tag",
"adds",
"a",
"tag",
"to",
"the",
"last",
"pushed",
"span",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L109-L111
|
test
|
256dpi/fire
|
tracer.go
|
Log
|
func (t *Tracer) Log(key string, value interface{}) {
t.Last().LogKV(key, value)
}
|
go
|
func (t *Tracer) Log(key string, value interface{}) {
t.Last().LogKV(key, value)
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Log",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"Last",
"(",
")",
".",
"LogKV",
"(",
"key",
",",
"value",
")",
"\n",
"}"
] |
// Log adds a log to the last pushed span.
|
[
"Log",
"adds",
"a",
"log",
"to",
"the",
"last",
"pushed",
"span",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L114-L116
|
test
|
256dpi/fire
|
tracer.go
|
Context
|
func (t *Tracer) Context(ctx context.Context) context.Context {
return opentracing.ContextWithSpan(ctx, t.Last())
}
|
go
|
func (t *Tracer) Context(ctx context.Context) context.Context {
return opentracing.ContextWithSpan(ctx, t.Last())
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Context",
"(",
"ctx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"return",
"opentracing",
".",
"ContextWithSpan",
"(",
"ctx",
",",
"t",
".",
"Last",
"(",
")",
")",
"\n",
"}"
] |
// Context returns a new context with the latest span stored as a reference for
// handlers that will call NewTracerFromRequest or similar.
|
[
"Context",
"returns",
"a",
"new",
"context",
"with",
"the",
"latest",
"span",
"stored",
"as",
"a",
"reference",
"for",
"handlers",
"that",
"will",
"call",
"NewTracerFromRequest",
"or",
"similar",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L120-L122
|
test
|
256dpi/fire
|
tracer.go
|
Pop
|
func (t *Tracer) Pop() {
// check list
if len(t.spans) == 0 {
return
}
// finish last span
t.Last().Finish()
// resize slice
t.spans = t.spans[:len(t.spans)-1]
}
|
go
|
func (t *Tracer) Pop() {
// check list
if len(t.spans) == 0 {
return
}
// finish last span
t.Last().Finish()
// resize slice
t.spans = t.spans[:len(t.spans)-1]
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Pop",
"(",
")",
"{",
"if",
"len",
"(",
"t",
".",
"spans",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"t",
".",
"Last",
"(",
")",
".",
"Finish",
"(",
")",
"\n",
"t",
".",
"spans",
"=",
"t",
".",
"spans",
"[",
":",
"len",
"(",
"t",
".",
"spans",
")",
"-",
"1",
"]",
"\n",
"}"
] |
// Pop finishes and removes the last pushed span.
|
[
"Pop",
"finishes",
"and",
"removes",
"the",
"last",
"pushed",
"span",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L125-L136
|
test
|
256dpi/fire
|
tracer.go
|
Finish
|
func (t *Tracer) Finish(root bool) {
for _, span := range t.spans {
span.Finish()
}
if root {
t.root.Finish()
}
}
|
go
|
func (t *Tracer) Finish(root bool) {
for _, span := range t.spans {
span.Finish()
}
if root {
t.root.Finish()
}
}
|
[
"func",
"(",
"t",
"*",
"Tracer",
")",
"Finish",
"(",
"root",
"bool",
")",
"{",
"for",
"_",
",",
"span",
":=",
"range",
"t",
".",
"spans",
"{",
"span",
".",
"Finish",
"(",
")",
"\n",
"}",
"\n",
"if",
"root",
"{",
"t",
".",
"root",
".",
"Finish",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Finish will finish all leftover spans and the root span if requested.
|
[
"Finish",
"will",
"finish",
"all",
"leftover",
"spans",
"and",
"the",
"root",
"span",
"if",
"requested",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L139-L147
|
test
|
256dpi/fire
|
axe/pool.go
|
NewPool
|
func NewPool() *Pool {
return &Pool{
tasks: make(map[string]*Task),
queues: make(map[*Queue]bool),
closed: make(chan struct{}),
}
}
|
go
|
func NewPool() *Pool {
return &Pool{
tasks: make(map[string]*Task),
queues: make(map[*Queue]bool),
closed: make(chan struct{}),
}
}
|
[
"func",
"NewPool",
"(",
")",
"*",
"Pool",
"{",
"return",
"&",
"Pool",
"{",
"tasks",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Task",
")",
",",
"queues",
":",
"make",
"(",
"map",
"[",
"*",
"Queue",
"]",
"bool",
")",
",",
"closed",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] |
// NewPool creates and returns a new pool.
|
[
"NewPool",
"creates",
"and",
"returns",
"a",
"new",
"pool",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/pool.go#L18-L24
|
test
|
256dpi/fire
|
axe/pool.go
|
Add
|
func (p *Pool) Add(task *Task) {
// check existence
if p.tasks[task.Name] != nil {
panic(fmt.Sprintf(`axe: task with name "%s" already exists`, task.Name))
}
// save task
p.tasks[task.Name] = task
// add task to queue
task.Queue.tasks = append(task.Queue.tasks, task.Name)
// save queue
p.queues[task.Queue] = true
}
|
go
|
func (p *Pool) Add(task *Task) {
// check existence
if p.tasks[task.Name] != nil {
panic(fmt.Sprintf(`axe: task with name "%s" already exists`, task.Name))
}
// save task
p.tasks[task.Name] = task
// add task to queue
task.Queue.tasks = append(task.Queue.tasks, task.Name)
// save queue
p.queues[task.Queue] = true
}
|
[
"func",
"(",
"p",
"*",
"Pool",
")",
"Add",
"(",
"task",
"*",
"Task",
")",
"{",
"if",
"p",
".",
"tasks",
"[",
"task",
".",
"Name",
"]",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`axe: task with name \"%s\" already exists`",
",",
"task",
".",
"Name",
")",
")",
"\n",
"}",
"\n",
"p",
".",
"tasks",
"[",
"task",
".",
"Name",
"]",
"=",
"task",
"\n",
"task",
".",
"Queue",
".",
"tasks",
"=",
"append",
"(",
"task",
".",
"Queue",
".",
"tasks",
",",
"task",
".",
"Name",
")",
"\n",
"p",
".",
"queues",
"[",
"task",
".",
"Queue",
"]",
"=",
"true",
"\n",
"}"
] |
// Add will add the specified task and its queue to the pool.
|
[
"Add",
"will",
"add",
"the",
"specified",
"task",
"and",
"its",
"queue",
"to",
"the",
"pool",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/pool.go#L27-L41
|
test
|
256dpi/fire
|
axe/pool.go
|
Run
|
func (p *Pool) Run() {
// start all queues
for queue := range p.queues {
queue.start(p)
}
// start all tasks
for _, task := range p.tasks {
task.start(p)
}
}
|
go
|
func (p *Pool) Run() {
// start all queues
for queue := range p.queues {
queue.start(p)
}
// start all tasks
for _, task := range p.tasks {
task.start(p)
}
}
|
[
"func",
"(",
"p",
"*",
"Pool",
")",
"Run",
"(",
")",
"{",
"for",
"queue",
":=",
"range",
"p",
".",
"queues",
"{",
"queue",
".",
"start",
"(",
"p",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"task",
":=",
"range",
"p",
".",
"tasks",
"{",
"task",
".",
"start",
"(",
"p",
")",
"\n",
"}",
"\n",
"}"
] |
// Run will launch the queue watchers and task workers in the background.
|
[
"Run",
"will",
"launch",
"the",
"queue",
"watchers",
"and",
"task",
"workers",
"in",
"the",
"background",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/pool.go#L44-L54
|
test
|
256dpi/fire
|
body_limiter.go
|
NewBodyLimiter
|
func NewBodyLimiter(w http.ResponseWriter, r *http.Request, n int64) *BodyLimiter {
return &BodyLimiter{
Original: r.Body,
ReadCloser: http.MaxBytesReader(w, r.Body, n),
}
}
|
go
|
func NewBodyLimiter(w http.ResponseWriter, r *http.Request, n int64) *BodyLimiter {
return &BodyLimiter{
Original: r.Body,
ReadCloser: http.MaxBytesReader(w, r.Body, n),
}
}
|
[
"func",
"NewBodyLimiter",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"n",
"int64",
")",
"*",
"BodyLimiter",
"{",
"return",
"&",
"BodyLimiter",
"{",
"Original",
":",
"r",
".",
"Body",
",",
"ReadCloser",
":",
"http",
".",
"MaxBytesReader",
"(",
"w",
",",
"r",
".",
"Body",
",",
"n",
")",
",",
"}",
"\n",
"}"
] |
// NewBodyLimiter returns a new body limiter for the specified request.
|
[
"NewBodyLimiter",
"returns",
"a",
"new",
"body",
"limiter",
"for",
"the",
"specified",
"request",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/body_limiter.go#L17-L22
|
test
|
256dpi/fire
|
body_limiter.go
|
LimitBody
|
func LimitBody(w http.ResponseWriter, r *http.Request, n int64) {
// get original body from existing limiter
if bl, ok := r.Body.(*BodyLimiter); ok {
r.Body = bl.Original
}
// set new limiter
r.Body = NewBodyLimiter(w, r, n)
}
|
go
|
func LimitBody(w http.ResponseWriter, r *http.Request, n int64) {
// get original body from existing limiter
if bl, ok := r.Body.(*BodyLimiter); ok {
r.Body = bl.Original
}
// set new limiter
r.Body = NewBodyLimiter(w, r, n)
}
|
[
"func",
"LimitBody",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"n",
"int64",
")",
"{",
"if",
"bl",
",",
"ok",
":=",
"r",
".",
"Body",
".",
"(",
"*",
"BodyLimiter",
")",
";",
"ok",
"{",
"r",
".",
"Body",
"=",
"bl",
".",
"Original",
"\n",
"}",
"\n",
"r",
".",
"Body",
"=",
"NewBodyLimiter",
"(",
"w",
",",
"r",
",",
"n",
")",
"\n",
"}"
] |
// LimitBody will limit reading from the body of the supplied request to the
// specified amount of bytes. Earlier calls to LimitBody will be overwritten
// which essentially allows callers to increase the limit from a default limit.
|
[
"LimitBody",
"will",
"limit",
"reading",
"from",
"the",
"body",
"of",
"the",
"supplied",
"request",
"to",
"the",
"specified",
"amount",
"of",
"bytes",
".",
"Earlier",
"calls",
"to",
"LimitBody",
"will",
"be",
"overwritten",
"which",
"essentially",
"allows",
"callers",
"to",
"increase",
"the",
"limit",
"from",
"a",
"default",
"limit",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/body_limiter.go#L27-L35
|
test
|
256dpi/fire
|
callbacks.go
|
C
|
func C(name string, m Matcher, h Handler) *Callback {
// panic if matcher or handler is not set
if m == nil || h == nil {
panic("fire: missing matcher or handler")
}
return &Callback{
Matcher: m,
Handler: func(ctx *Context) error {
// begin trace
ctx.Tracer.Push(name)
// call handler
err := h(ctx)
if err != nil {
return err
}
// finish trace
ctx.Tracer.Pop()
return nil
},
}
}
|
go
|
func C(name string, m Matcher, h Handler) *Callback {
// panic if matcher or handler is not set
if m == nil || h == nil {
panic("fire: missing matcher or handler")
}
return &Callback{
Matcher: m,
Handler: func(ctx *Context) error {
// begin trace
ctx.Tracer.Push(name)
// call handler
err := h(ctx)
if err != nil {
return err
}
// finish trace
ctx.Tracer.Pop()
return nil
},
}
}
|
[
"func",
"C",
"(",
"name",
"string",
",",
"m",
"Matcher",
",",
"h",
"Handler",
")",
"*",
"Callback",
"{",
"if",
"m",
"==",
"nil",
"||",
"h",
"==",
"nil",
"{",
"panic",
"(",
"\"fire: missing matcher or handler\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"Callback",
"{",
"Matcher",
":",
"m",
",",
"Handler",
":",
"func",
"(",
"ctx",
"*",
"Context",
")",
"error",
"{",
"ctx",
".",
"Tracer",
".",
"Push",
"(",
"name",
")",
"\n",
"err",
":=",
"h",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ctx",
".",
"Tracer",
".",
"Pop",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
",",
"}",
"\n",
"}"
] |
// C is a short-hand function to construct a callback. It will also add tracing
// code around the execution of the callback.
|
[
"C",
"is",
"a",
"short",
"-",
"hand",
"function",
"to",
"construct",
"a",
"callback",
".",
"It",
"will",
"also",
"add",
"tracing",
"code",
"around",
"the",
"execution",
"of",
"the",
"callback",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L17-L41
|
test
|
256dpi/fire
|
callbacks.go
|
Only
|
func Only(ops ...Operation) Matcher {
return func(ctx *Context) bool {
// allow if operation is listed
for _, op := range ops {
if op == ctx.Operation {
return true
}
}
return false
}
}
|
go
|
func Only(ops ...Operation) Matcher {
return func(ctx *Context) bool {
// allow if operation is listed
for _, op := range ops {
if op == ctx.Operation {
return true
}
}
return false
}
}
|
[
"func",
"Only",
"(",
"ops",
"...",
"Operation",
")",
"Matcher",
"{",
"return",
"func",
"(",
"ctx",
"*",
"Context",
")",
"bool",
"{",
"for",
"_",
",",
"op",
":=",
"range",
"ops",
"{",
"if",
"op",
"==",
"ctx",
".",
"Operation",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] |
// Only will match if the operation is present in the provided list.
|
[
"Only",
"will",
"match",
"if",
"the",
"operation",
"is",
"present",
"in",
"the",
"provided",
"list",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L59-L70
|
test
|
256dpi/fire
|
callbacks.go
|
BasicAuthorizer
|
func BasicAuthorizer(credentials map[string]string) *Callback {
return C("fire/BasicAuthorizer", All(), func(ctx *Context) error {
// check for credentials
user, password, ok := ctx.HTTPRequest.BasicAuth()
if !ok {
return ErrAccessDenied
}
// check if credentials match
if val, ok := credentials[user]; !ok || val != password {
return ErrAccessDenied
}
return nil
})
}
|
go
|
func BasicAuthorizer(credentials map[string]string) *Callback {
return C("fire/BasicAuthorizer", All(), func(ctx *Context) error {
// check for credentials
user, password, ok := ctx.HTTPRequest.BasicAuth()
if !ok {
return ErrAccessDenied
}
// check if credentials match
if val, ok := credentials[user]; !ok || val != password {
return ErrAccessDenied
}
return nil
})
}
|
[
"func",
"BasicAuthorizer",
"(",
"credentials",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"Callback",
"{",
"return",
"C",
"(",
"\"fire/BasicAuthorizer\"",
",",
"All",
"(",
")",
",",
"func",
"(",
"ctx",
"*",
"Context",
")",
"error",
"{",
"user",
",",
"password",
",",
"ok",
":=",
"ctx",
".",
"HTTPRequest",
".",
"BasicAuth",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrAccessDenied",
"\n",
"}",
"\n",
"if",
"val",
",",
"ok",
":=",
"credentials",
"[",
"user",
"]",
";",
"!",
"ok",
"||",
"val",
"!=",
"password",
"{",
"return",
"ErrAccessDenied",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// BasicAuthorizer authorizes requests based on a simple credentials list.
|
[
"BasicAuthorizer",
"authorizes",
"requests",
"based",
"on",
"a",
"simple",
"credentials",
"list",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L106-L121
|
test
|
256dpi/fire
|
callbacks.go
|
ModelValidator
|
func ModelValidator() *Callback {
return C("fire/ModelValidator", Only(Create, Update), func(ctx *Context) error {
// check model
m, ok := ctx.Model.(ValidatableModel)
if !ok {
return fmt.Errorf("model is not validatable")
}
// validate model
err := m.Validate()
if err != nil {
return err
}
return nil
})
}
|
go
|
func ModelValidator() *Callback {
return C("fire/ModelValidator", Only(Create, Update), func(ctx *Context) error {
// check model
m, ok := ctx.Model.(ValidatableModel)
if !ok {
return fmt.Errorf("model is not validatable")
}
// validate model
err := m.Validate()
if err != nil {
return err
}
return nil
})
}
|
[
"func",
"ModelValidator",
"(",
")",
"*",
"Callback",
"{",
"return",
"C",
"(",
"\"fire/ModelValidator\"",
",",
"Only",
"(",
"Create",
",",
"Update",
")",
",",
"func",
"(",
"ctx",
"*",
"Context",
")",
"error",
"{",
"m",
",",
"ok",
":=",
"ctx",
".",
"Model",
".",
"(",
"ValidatableModel",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"model is not validatable\"",
")",
"\n",
"}",
"\n",
"err",
":=",
"m",
".",
"Validate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// ModelValidator performs a validation of the model using the Validate method.
|
[
"ModelValidator",
"performs",
"a",
"validation",
"of",
"the",
"model",
"using",
"the",
"Validate",
"method",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L133-L149
|
test
|
256dpi/fire
|
callbacks.go
|
TimestampValidator
|
func TimestampValidator() *Callback {
return C("fire/TimestampValidator", Only(Create, Update), func(ctx *Context) error {
// get time
now := time.Now()
// get timestamp fields
ctf := coal.L(ctx.Model, "fire-created-timestamp", false)
utf := coal.L(ctx.Model, "fire-updated-timestamp", false)
// set created timestamp on creation and set missing create timestamps
// to the timestamp inferred from the model id
if ctf != "" {
if ctx.Operation == Create {
ctx.Model.MustSet(ctf, now)
} else if t := ctx.Model.MustGet(ctf).(time.Time); t.IsZero() {
ctx.Model.MustSet(ctf, ctx.Model.ID().Time())
}
}
// always set updated timestamp
if utf != "" {
ctx.Model.MustSet(utf, now)
}
return nil
})
}
|
go
|
func TimestampValidator() *Callback {
return C("fire/TimestampValidator", Only(Create, Update), func(ctx *Context) error {
// get time
now := time.Now()
// get timestamp fields
ctf := coal.L(ctx.Model, "fire-created-timestamp", false)
utf := coal.L(ctx.Model, "fire-updated-timestamp", false)
// set created timestamp on creation and set missing create timestamps
// to the timestamp inferred from the model id
if ctf != "" {
if ctx.Operation == Create {
ctx.Model.MustSet(ctf, now)
} else if t := ctx.Model.MustGet(ctf).(time.Time); t.IsZero() {
ctx.Model.MustSet(ctf, ctx.Model.ID().Time())
}
}
// always set updated timestamp
if utf != "" {
ctx.Model.MustSet(utf, now)
}
return nil
})
}
|
[
"func",
"TimestampValidator",
"(",
")",
"*",
"Callback",
"{",
"return",
"C",
"(",
"\"fire/TimestampValidator\"",
",",
"Only",
"(",
"Create",
",",
"Update",
")",
",",
"func",
"(",
"ctx",
"*",
"Context",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"ctf",
":=",
"coal",
".",
"L",
"(",
"ctx",
".",
"Model",
",",
"\"fire-created-timestamp\"",
",",
"false",
")",
"\n",
"utf",
":=",
"coal",
".",
"L",
"(",
"ctx",
".",
"Model",
",",
"\"fire-updated-timestamp\"",
",",
"false",
")",
"\n",
"if",
"ctf",
"!=",
"\"\"",
"{",
"if",
"ctx",
".",
"Operation",
"==",
"Create",
"{",
"ctx",
".",
"Model",
".",
"MustSet",
"(",
"ctf",
",",
"now",
")",
"\n",
"}",
"else",
"if",
"t",
":=",
"ctx",
".",
"Model",
".",
"MustGet",
"(",
"ctf",
")",
".",
"(",
"time",
".",
"Time",
")",
";",
"t",
".",
"IsZero",
"(",
")",
"{",
"ctx",
".",
"Model",
".",
"MustSet",
"(",
"ctf",
",",
"ctx",
".",
"Model",
".",
"ID",
"(",
")",
".",
"Time",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"utf",
"!=",
"\"\"",
"{",
"ctx",
".",
"Model",
".",
"MustSet",
"(",
"utf",
",",
"now",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// TimestampValidator will set timestamp fields on create and update operations.
// The fields are inferred from the model using the "fire-created-timestamp" and
// "fire-updated-timestamp" flags. Missing created timestamps are retroactively
// set using the timestamp encoded in the model id.
|
[
"TimestampValidator",
"will",
"set",
"timestamp",
"fields",
"on",
"create",
"and",
"update",
"operations",
".",
"The",
"fields",
"are",
"inferred",
"from",
"the",
"model",
"using",
"the",
"fire",
"-",
"created",
"-",
"timestamp",
"and",
"fire",
"-",
"updated",
"-",
"timestamp",
"flags",
".",
"Missing",
"created",
"timestamps",
"are",
"retroactively",
"set",
"using",
"the",
"timestamp",
"encoded",
"in",
"the",
"model",
"id",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L155-L181
|
test
|
256dpi/fire
|
callbacks.go
|
RelationshipValidator
|
func RelationshipValidator(model coal.Model, catalog *coal.Catalog, excludedFields ...string) *Callback {
// prepare lists
dependentResources := make(map[coal.Model]string)
references := make(map[string]coal.Model)
// iterate through all fields
for _, field := range coal.Init(model).Meta().Relationships {
// exclude field if requested
if Contains(excludedFields, field.Name) {
continue
}
// handle has-one and has-many relationships
if field.HasOne || field.HasMany {
// get related model
relatedModel := catalog.Find(field.RelType)
if relatedModel == nil {
panic(fmt.Sprintf(`fire: missing model in catalog: "%s"`, field.RelType))
}
// get related bson field
bsonField := ""
for _, relatedField := range relatedModel.Meta().Relationships {
if relatedField.RelName == field.RelInverse {
bsonField = relatedField.Name
}
}
if bsonField == "" {
panic(fmt.Sprintf(`fire: missing field for inverse relationship: "%s"`, field.RelInverse))
}
// add relationship
dependentResources[relatedModel] = bsonField
}
// handle to-one and to-many relationships
if field.ToOne || field.ToMany {
// get related model
relatedModel := catalog.Find(field.RelType)
if relatedModel == nil {
panic(fmt.Sprintf(`fire: missing model in catalog: "%s"`, field.RelType))
}
// add relationship
references[field.Name] = relatedModel
}
}
// create callbacks
cb1 := DependentResourcesValidator(dependentResources)
cb2 := VerifyReferencesValidator(references)
return C("RelationshipValidator", func(ctx *Context) bool {
return cb1.Matcher(ctx) || cb2.Matcher(ctx)
}, func(ctx *Context) error {
// run dependent resources validator
if cb1.Matcher(ctx) {
err := cb1.Handler(ctx)
if err != nil {
return err
}
}
// run dependent resources validator
if cb2.Matcher(ctx) {
err := cb2.Handler(ctx)
if err != nil {
return err
}
}
return nil
})
}
|
go
|
func RelationshipValidator(model coal.Model, catalog *coal.Catalog, excludedFields ...string) *Callback {
// prepare lists
dependentResources := make(map[coal.Model]string)
references := make(map[string]coal.Model)
// iterate through all fields
for _, field := range coal.Init(model).Meta().Relationships {
// exclude field if requested
if Contains(excludedFields, field.Name) {
continue
}
// handle has-one and has-many relationships
if field.HasOne || field.HasMany {
// get related model
relatedModel := catalog.Find(field.RelType)
if relatedModel == nil {
panic(fmt.Sprintf(`fire: missing model in catalog: "%s"`, field.RelType))
}
// get related bson field
bsonField := ""
for _, relatedField := range relatedModel.Meta().Relationships {
if relatedField.RelName == field.RelInverse {
bsonField = relatedField.Name
}
}
if bsonField == "" {
panic(fmt.Sprintf(`fire: missing field for inverse relationship: "%s"`, field.RelInverse))
}
// add relationship
dependentResources[relatedModel] = bsonField
}
// handle to-one and to-many relationships
if field.ToOne || field.ToMany {
// get related model
relatedModel := catalog.Find(field.RelType)
if relatedModel == nil {
panic(fmt.Sprintf(`fire: missing model in catalog: "%s"`, field.RelType))
}
// add relationship
references[field.Name] = relatedModel
}
}
// create callbacks
cb1 := DependentResourcesValidator(dependentResources)
cb2 := VerifyReferencesValidator(references)
return C("RelationshipValidator", func(ctx *Context) bool {
return cb1.Matcher(ctx) || cb2.Matcher(ctx)
}, func(ctx *Context) error {
// run dependent resources validator
if cb1.Matcher(ctx) {
err := cb1.Handler(ctx)
if err != nil {
return err
}
}
// run dependent resources validator
if cb2.Matcher(ctx) {
err := cb2.Handler(ctx)
if err != nil {
return err
}
}
return nil
})
}
|
[
"func",
"RelationshipValidator",
"(",
"model",
"coal",
".",
"Model",
",",
"catalog",
"*",
"coal",
".",
"Catalog",
",",
"excludedFields",
"...",
"string",
")",
"*",
"Callback",
"{",
"dependentResources",
":=",
"make",
"(",
"map",
"[",
"coal",
".",
"Model",
"]",
"string",
")",
"\n",
"references",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"coal",
".",
"Model",
")",
"\n",
"for",
"_",
",",
"field",
":=",
"range",
"coal",
".",
"Init",
"(",
"model",
")",
".",
"Meta",
"(",
")",
".",
"Relationships",
"{",
"if",
"Contains",
"(",
"excludedFields",
",",
"field",
".",
"Name",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"field",
".",
"HasOne",
"||",
"field",
".",
"HasMany",
"{",
"relatedModel",
":=",
"catalog",
".",
"Find",
"(",
"field",
".",
"RelType",
")",
"\n",
"if",
"relatedModel",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`fire: missing model in catalog: \"%s\"`",
",",
"field",
".",
"RelType",
")",
")",
"\n",
"}",
"\n",
"bsonField",
":=",
"\"\"",
"\n",
"for",
"_",
",",
"relatedField",
":=",
"range",
"relatedModel",
".",
"Meta",
"(",
")",
".",
"Relationships",
"{",
"if",
"relatedField",
".",
"RelName",
"==",
"field",
".",
"RelInverse",
"{",
"bsonField",
"=",
"relatedField",
".",
"Name",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"bsonField",
"==",
"\"\"",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`fire: missing field for inverse relationship: \"%s\"`",
",",
"field",
".",
"RelInverse",
")",
")",
"\n",
"}",
"\n",
"dependentResources",
"[",
"relatedModel",
"]",
"=",
"bsonField",
"\n",
"}",
"\n",
"if",
"field",
".",
"ToOne",
"||",
"field",
".",
"ToMany",
"{",
"relatedModel",
":=",
"catalog",
".",
"Find",
"(",
"field",
".",
"RelType",
")",
"\n",
"if",
"relatedModel",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"`fire: missing model in catalog: \"%s\"`",
",",
"field",
".",
"RelType",
")",
")",
"\n",
"}",
"\n",
"references",
"[",
"field",
".",
"Name",
"]",
"=",
"relatedModel",
"\n",
"}",
"\n",
"}",
"\n",
"cb1",
":=",
"DependentResourcesValidator",
"(",
"dependentResources",
")",
"\n",
"cb2",
":=",
"VerifyReferencesValidator",
"(",
"references",
")",
"\n",
"return",
"C",
"(",
"\"RelationshipValidator\"",
",",
"func",
"(",
"ctx",
"*",
"Context",
")",
"bool",
"{",
"return",
"cb1",
".",
"Matcher",
"(",
"ctx",
")",
"||",
"cb2",
".",
"Matcher",
"(",
"ctx",
")",
"\n",
"}",
",",
"func",
"(",
"ctx",
"*",
"Context",
")",
"error",
"{",
"if",
"cb1",
".",
"Matcher",
"(",
"ctx",
")",
"{",
"err",
":=",
"cb1",
".",
"Handler",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cb2",
".",
"Matcher",
"(",
"ctx",
")",
"{",
"err",
":=",
"cb2",
".",
"Handler",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// RelationshipValidator makes sure all relationships of a model are correct and
// in place. It does so by combining a DependentResourcesValidator and a
// VerifyReferencesValidator based on the specified model and catalog.
|
[
"RelationshipValidator",
"makes",
"sure",
"all",
"relationships",
"of",
"a",
"model",
"are",
"correct",
"and",
"in",
"place",
".",
"It",
"does",
"so",
"by",
"combining",
"a",
"DependentResourcesValidator",
"and",
"a",
"VerifyReferencesValidator",
"based",
"on",
"the",
"specified",
"model",
"and",
"catalog",
"."
] |
fa66e74352b30b9a4c730f7b8dc773302941b0fb
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L362-L435
|
test
|
apuigsech/seekret
|
inspect.go
|
Inspect
|
func (s *Seekret) Inspect(Nworkers int) {
jobs := make(chan workerJob)
results := make(chan workerResult)
for w := 1; w <= Nworkers; w++ {
go inspect_worker(w, jobs, results)
}
objectGroupMap := s.GroupObjectsByPrimaryKeyHash()
go func() {
for _, objectGroup := range objectGroupMap {
jobs <- workerJob{
objectGroup: objectGroup,
ruleList: s.ruleList,
exceptionList: s.exceptionList,
}
}
close(jobs)
}()
for i := 0; i < len(objectGroupMap); i++ {
result := <-results
s.secretList = append(s.secretList, result.secretList...)
}
}
|
go
|
func (s *Seekret) Inspect(Nworkers int) {
jobs := make(chan workerJob)
results := make(chan workerResult)
for w := 1; w <= Nworkers; w++ {
go inspect_worker(w, jobs, results)
}
objectGroupMap := s.GroupObjectsByPrimaryKeyHash()
go func() {
for _, objectGroup := range objectGroupMap {
jobs <- workerJob{
objectGroup: objectGroup,
ruleList: s.ruleList,
exceptionList: s.exceptionList,
}
}
close(jobs)
}()
for i := 0; i < len(objectGroupMap); i++ {
result := <-results
s.secretList = append(s.secretList, result.secretList...)
}
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"Inspect",
"(",
"Nworkers",
"int",
")",
"{",
"jobs",
":=",
"make",
"(",
"chan",
"workerJob",
")",
"\n",
"results",
":=",
"make",
"(",
"chan",
"workerResult",
")",
"\n",
"for",
"w",
":=",
"1",
";",
"w",
"<=",
"Nworkers",
";",
"w",
"++",
"{",
"go",
"inspect_worker",
"(",
"w",
",",
"jobs",
",",
"results",
")",
"\n",
"}",
"\n",
"objectGroupMap",
":=",
"s",
".",
"GroupObjectsByPrimaryKeyHash",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"_",
",",
"objectGroup",
":=",
"range",
"objectGroupMap",
"{",
"jobs",
"<-",
"workerJob",
"{",
"objectGroup",
":",
"objectGroup",
",",
"ruleList",
":",
"s",
".",
"ruleList",
",",
"exceptionList",
":",
"s",
".",
"exceptionList",
",",
"}",
"\n",
"}",
"\n",
"close",
"(",
"jobs",
")",
"\n",
"}",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"objectGroupMap",
")",
";",
"i",
"++",
"{",
"result",
":=",
"<-",
"results",
"\n",
"s",
".",
"secretList",
"=",
"append",
"(",
"s",
".",
"secretList",
",",
"result",
".",
"secretList",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// Inspect executes the inspection into all loaded objects, by checking all
// rules and exceptions loaded.
|
[
"Inspect",
"executes",
"the",
"inspection",
"into",
"all",
"loaded",
"objects",
"by",
"checking",
"all",
"rules",
"and",
"exceptions",
"loaded",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/inspect.go#L27-L52
|
test
|
apuigsech/seekret
|
models/rule.go
|
NewRule
|
func NewRule(name string, match string) (*Rule, error) {
matchRegexp, err := regexp.Compile("(?i)" + match)
if err != nil {
return nil, err
}
if err != nil {
fmt.Println(err)
}
r := &Rule{
Enabled: false,
Name: name,
Match: matchRegexp,
}
return r, nil
}
|
go
|
func NewRule(name string, match string) (*Rule, error) {
matchRegexp, err := regexp.Compile("(?i)" + match)
if err != nil {
return nil, err
}
if err != nil {
fmt.Println(err)
}
r := &Rule{
Enabled: false,
Name: name,
Match: matchRegexp,
}
return r, nil
}
|
[
"func",
"NewRule",
"(",
"name",
"string",
",",
"match",
"string",
")",
"(",
"*",
"Rule",
",",
"error",
")",
"{",
"matchRegexp",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"\"(?i)\"",
"+",
"match",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"err",
")",
"\n",
"}",
"\n",
"r",
":=",
"&",
"Rule",
"{",
"Enabled",
":",
"false",
",",
"Name",
":",
"name",
",",
"Match",
":",
"matchRegexp",
",",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] |
// NewRule creates a new rule.
|
[
"NewRule",
"creates",
"a",
"new",
"rule",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/rule.go#L37-L52
|
test
|
apuigsech/seekret
|
models/rule.go
|
AddUnmatch
|
func (r *Rule) AddUnmatch(unmatch string) error {
unmatchRegexp, err := regexp.Compile("(?i)" + unmatch)
if err != nil {
return err
}
r.Unmatch = append(r.Unmatch, unmatchRegexp)
return nil
}
|
go
|
func (r *Rule) AddUnmatch(unmatch string) error {
unmatchRegexp, err := regexp.Compile("(?i)" + unmatch)
if err != nil {
return err
}
r.Unmatch = append(r.Unmatch, unmatchRegexp)
return nil
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"AddUnmatch",
"(",
"unmatch",
"string",
")",
"error",
"{",
"unmatchRegexp",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"\"(?i)\"",
"+",
"unmatch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"r",
".",
"Unmatch",
"=",
"append",
"(",
"r",
".",
"Unmatch",
",",
"unmatchRegexp",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddUnmatch adds a refular expression into the unmatch list.
|
[
"AddUnmatch",
"adds",
"a",
"refular",
"expression",
"into",
"the",
"unmatch",
"list",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/rule.go#L65-L74
|
test
|
apuigsech/seekret
|
models/rule.go
|
Run
|
func (r *Rule) Run(content []byte) []RunResult {
var results []RunResult
b := bufio.NewScanner(bytes.NewReader(content))
nLine := 0
for b.Scan() {
nLine = nLine + 1
line := b.Text()
if r.Match.MatchString(line) {
unmatch := false
for _, Unmatch := range r.Unmatch {
if Unmatch.MatchString(line) {
unmatch = true
}
}
if !unmatch {
results = append(results, RunResult{
Line: line,
Nline: nLine,
})
}
}
}
return results
}
|
go
|
func (r *Rule) Run(content []byte) []RunResult {
var results []RunResult
b := bufio.NewScanner(bytes.NewReader(content))
nLine := 0
for b.Scan() {
nLine = nLine + 1
line := b.Text()
if r.Match.MatchString(line) {
unmatch := false
for _, Unmatch := range r.Unmatch {
if Unmatch.MatchString(line) {
unmatch = true
}
}
if !unmatch {
results = append(results, RunResult{
Line: line,
Nline: nLine,
})
}
}
}
return results
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"Run",
"(",
"content",
"[",
"]",
"byte",
")",
"[",
"]",
"RunResult",
"{",
"var",
"results",
"[",
"]",
"RunResult",
"\n",
"b",
":=",
"bufio",
".",
"NewScanner",
"(",
"bytes",
".",
"NewReader",
"(",
"content",
")",
")",
"\n",
"nLine",
":=",
"0",
"\n",
"for",
"b",
".",
"Scan",
"(",
")",
"{",
"nLine",
"=",
"nLine",
"+",
"1",
"\n",
"line",
":=",
"b",
".",
"Text",
"(",
")",
"\n",
"if",
"r",
".",
"Match",
".",
"MatchString",
"(",
"line",
")",
"{",
"unmatch",
":=",
"false",
"\n",
"for",
"_",
",",
"Unmatch",
":=",
"range",
"r",
".",
"Unmatch",
"{",
"if",
"Unmatch",
".",
"MatchString",
"(",
"line",
")",
"{",
"unmatch",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"unmatch",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"RunResult",
"{",
"Line",
":",
"line",
",",
"Nline",
":",
"nLine",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"results",
"\n",
"}"
] |
// Run executes the rule into a content to find all lines that matches it.
|
[
"Run",
"executes",
"the",
"rule",
"into",
"a",
"content",
"to",
"find",
"all",
"lines",
"that",
"matches",
"it",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/rule.go#L77-L105
|
test
|
apuigsech/seekret
|
models/secret.go
|
NewSecret
|
func NewSecret(object *Object, rule *Rule, nLine int, line string) *Secret {
s := &Secret{
Object: object,
Rule: rule,
Nline: nLine,
Line: line,
}
return s
}
|
go
|
func NewSecret(object *Object, rule *Rule, nLine int, line string) *Secret {
s := &Secret{
Object: object,
Rule: rule,
Nline: nLine,
Line: line,
}
return s
}
|
[
"func",
"NewSecret",
"(",
"object",
"*",
"Object",
",",
"rule",
"*",
"Rule",
",",
"nLine",
"int",
",",
"line",
"string",
")",
"*",
"Secret",
"{",
"s",
":=",
"&",
"Secret",
"{",
"Object",
":",
"object",
",",
"Rule",
":",
"rule",
",",
"Nline",
":",
"nLine",
",",
"Line",
":",
"line",
",",
"}",
"\n",
"return",
"s",
"\n",
"}"
] |
// NewSecret creates a new secret.
|
[
"NewSecret",
"creates",
"a",
"new",
"secret",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/secret.go#L27-L35
|
test
|
apuigsech/seekret
|
models/object.go
|
NewObject
|
func NewObject(name string, t string, st string, content []byte) *Object {
if len(content) > MaxObjectContentLen {
content = content[:MaxObjectContentLen]
}
o := &Object{
Type: t,
SubType: st,
Name: name,
Content: content,
Metadata: make(map[string]MetadataData),
PrimaryKeyHash: nil,
}
return o
}
|
go
|
func NewObject(name string, t string, st string, content []byte) *Object {
if len(content) > MaxObjectContentLen {
content = content[:MaxObjectContentLen]
}
o := &Object{
Type: t,
SubType: st,
Name: name,
Content: content,
Metadata: make(map[string]MetadataData),
PrimaryKeyHash: nil,
}
return o
}
|
[
"func",
"NewObject",
"(",
"name",
"string",
",",
"t",
"string",
",",
"st",
"string",
",",
"content",
"[",
"]",
"byte",
")",
"*",
"Object",
"{",
"if",
"len",
"(",
"content",
")",
">",
"MaxObjectContentLen",
"{",
"content",
"=",
"content",
"[",
":",
"MaxObjectContentLen",
"]",
"\n",
"}",
"\n",
"o",
":=",
"&",
"Object",
"{",
"Type",
":",
"t",
",",
"SubType",
":",
"st",
",",
"Name",
":",
"name",
",",
"Content",
":",
"content",
",",
"Metadata",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"MetadataData",
")",
",",
"PrimaryKeyHash",
":",
"nil",
",",
"}",
"\n",
"return",
"o",
"\n",
"}"
] |
// NewObject creates a new object.
|
[
"NewObject",
"creates",
"a",
"new",
"object",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L46-L61
|
test
|
apuigsech/seekret
|
models/object.go
|
SetMetadata
|
func (o *Object) SetMetadata(key string, value string, attr MetadataAttributes) error {
o.Metadata[key] = MetadataData{
value: value,
attr: attr,
}
if attr.PrimaryKey {
o.updatePrimaryKeyHash()
}
return nil
}
|
go
|
func (o *Object) SetMetadata(key string, value string, attr MetadataAttributes) error {
o.Metadata[key] = MetadataData{
value: value,
attr: attr,
}
if attr.PrimaryKey {
o.updatePrimaryKeyHash()
}
return nil
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"SetMetadata",
"(",
"key",
"string",
",",
"value",
"string",
",",
"attr",
"MetadataAttributes",
")",
"error",
"{",
"o",
".",
"Metadata",
"[",
"key",
"]",
"=",
"MetadataData",
"{",
"value",
":",
"value",
",",
"attr",
":",
"attr",
",",
"}",
"\n",
"if",
"attr",
".",
"PrimaryKey",
"{",
"o",
".",
"updatePrimaryKeyHash",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetMetadata sets a metadata value for the object.
|
[
"SetMetadata",
"sets",
"a",
"metadata",
"value",
"for",
"the",
"object",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L64-L75
|
test
|
apuigsech/seekret
|
models/object.go
|
GetMetadata
|
func (o *Object) GetMetadata(key string) (string, error) {
data, ok := o.Metadata[key]
if !ok {
return "", fmt.Errorf("%s unexistent key", key)
}
return data.value, nil
}
|
go
|
func (o *Object) GetMetadata(key string) (string, error) {
data, ok := o.Metadata[key]
if !ok {
return "", fmt.Errorf("%s unexistent key", key)
}
return data.value, nil
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"GetMetadata",
"(",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"data",
",",
"ok",
":=",
"o",
".",
"Metadata",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s unexistent key\"",
",",
"key",
")",
"\n",
"}",
"\n",
"return",
"data",
".",
"value",
",",
"nil",
"\n",
"}"
] |
// SetMetadata gets a metadata value from the object.
|
[
"SetMetadata",
"gets",
"a",
"metadata",
"value",
"from",
"the",
"object",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L78-L85
|
test
|
apuigsech/seekret
|
models/object.go
|
GetMetadataAll
|
func (o *Object) GetMetadataAll(attr bool) map[string]string {
metadataAll := make(map[string]string)
for k, v := range o.Metadata {
metadataAll[k] = v.value
}
return metadataAll
}
|
go
|
func (o *Object) GetMetadataAll(attr bool) map[string]string {
metadataAll := make(map[string]string)
for k, v := range o.Metadata {
metadataAll[k] = v.value
}
return metadataAll
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"GetMetadataAll",
"(",
"attr",
"bool",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"metadataAll",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"o",
".",
"Metadata",
"{",
"metadataAll",
"[",
"k",
"]",
"=",
"v",
".",
"value",
"\n",
"}",
"\n",
"return",
"metadataAll",
"\n",
"}"
] |
// GetMetadataAll gets a map that contains all metadata of the object.
|
[
"GetMetadataAll",
"gets",
"a",
"map",
"that",
"contains",
"all",
"metadata",
"of",
"the",
"object",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L88-L94
|
test
|
apuigsech/seekret
|
models/exception.go
|
SetRule
|
func (x *Exception) SetRule(rule string) error {
ruleRegexp, err := regexp.Compile("(?i)" + rule)
if err != nil {
return err
}
x.Rule = ruleRegexp
return nil
}
|
go
|
func (x *Exception) SetRule(rule string) error {
ruleRegexp, err := regexp.Compile("(?i)" + rule)
if err != nil {
return err
}
x.Rule = ruleRegexp
return nil
}
|
[
"func",
"(",
"x",
"*",
"Exception",
")",
"SetRule",
"(",
"rule",
"string",
")",
"error",
"{",
"ruleRegexp",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"\"(?i)\"",
"+",
"rule",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"x",
".",
"Rule",
"=",
"ruleRegexp",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetRule sets the regular expresion that should match the name of the rule.
|
[
"SetRule",
"sets",
"the",
"regular",
"expresion",
"that",
"should",
"match",
"the",
"name",
"of",
"the",
"rule",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L40-L47
|
test
|
apuigsech/seekret
|
models/exception.go
|
SetObject
|
func (x *Exception) SetObject(object string) error {
objectRegexp, err := regexp.Compile("(?i)" + object)
if err != nil {
return err
}
x.Object = objectRegexp
return nil
}
|
go
|
func (x *Exception) SetObject(object string) error {
objectRegexp, err := regexp.Compile("(?i)" + object)
if err != nil {
return err
}
x.Object = objectRegexp
return nil
}
|
[
"func",
"(",
"x",
"*",
"Exception",
")",
"SetObject",
"(",
"object",
"string",
")",
"error",
"{",
"objectRegexp",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"\"(?i)\"",
"+",
"object",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"x",
".",
"Object",
"=",
"objectRegexp",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetObject sets the regular expresion that should match the name of the
// object.
|
[
"SetObject",
"sets",
"the",
"regular",
"expresion",
"that",
"should",
"match",
"the",
"name",
"of",
"the",
"object",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L51-L58
|
test
|
apuigsech/seekret
|
models/exception.go
|
SetNline
|
func (x *Exception) SetNline(nLine int) error {
x.Nline = &nLine
return nil
}
|
go
|
func (x *Exception) SetNline(nLine int) error {
x.Nline = &nLine
return nil
}
|
[
"func",
"(",
"x",
"*",
"Exception",
")",
"SetNline",
"(",
"nLine",
"int",
")",
"error",
"{",
"x",
".",
"Nline",
"=",
"&",
"nLine",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetNline sets the number of line where secret should be found.
|
[
"SetNline",
"sets",
"the",
"number",
"of",
"line",
"where",
"secret",
"should",
"be",
"found",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L61-L64
|
test
|
apuigsech/seekret
|
models/exception.go
|
SetContent
|
func (x *Exception) SetContent(content string) error {
contentRegexp, err := regexp.Compile("(?i)" + content)
if err != nil {
return err
}
x.Content = contentRegexp
return nil
}
|
go
|
func (x *Exception) SetContent(content string) error {
contentRegexp, err := regexp.Compile("(?i)" + content)
if err != nil {
return err
}
x.Content = contentRegexp
return nil
}
|
[
"func",
"(",
"x",
"*",
"Exception",
")",
"SetContent",
"(",
"content",
"string",
")",
"error",
"{",
"contentRegexp",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"\"(?i)\"",
"+",
"content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"x",
".",
"Content",
"=",
"contentRegexp",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetContent sets the regular expresion that should match the content of the
// object.
|
[
"SetContent",
"sets",
"the",
"regular",
"expresion",
"that",
"should",
"match",
"the",
"content",
"of",
"the",
"object",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L68-L75
|
test
|
apuigsech/seekret
|
models/exception.go
|
Run
|
func (x *Exception) Run(s *Secret) bool {
match := true
if match && x.Rule != nil && !x.Rule.MatchString(s.Rule.Name) {
match = false
}
if match && x.Object != nil && !x.Object.MatchString(s.Object.Name) {
match = false
}
if match && x.Nline != nil && *x.Nline != s.Nline {
match = false
}
if match && x.Content != nil && !x.Content.MatchString(s.Line) {
match = false
}
return match
}
|
go
|
func (x *Exception) Run(s *Secret) bool {
match := true
if match && x.Rule != nil && !x.Rule.MatchString(s.Rule.Name) {
match = false
}
if match && x.Object != nil && !x.Object.MatchString(s.Object.Name) {
match = false
}
if match && x.Nline != nil && *x.Nline != s.Nline {
match = false
}
if match && x.Content != nil && !x.Content.MatchString(s.Line) {
match = false
}
return match
}
|
[
"func",
"(",
"x",
"*",
"Exception",
")",
"Run",
"(",
"s",
"*",
"Secret",
")",
"bool",
"{",
"match",
":=",
"true",
"\n",
"if",
"match",
"&&",
"x",
".",
"Rule",
"!=",
"nil",
"&&",
"!",
"x",
".",
"Rule",
".",
"MatchString",
"(",
"s",
".",
"Rule",
".",
"Name",
")",
"{",
"match",
"=",
"false",
"\n",
"}",
"\n",
"if",
"match",
"&&",
"x",
".",
"Object",
"!=",
"nil",
"&&",
"!",
"x",
".",
"Object",
".",
"MatchString",
"(",
"s",
".",
"Object",
".",
"Name",
")",
"{",
"match",
"=",
"false",
"\n",
"}",
"\n",
"if",
"match",
"&&",
"x",
".",
"Nline",
"!=",
"nil",
"&&",
"*",
"x",
".",
"Nline",
"!=",
"s",
".",
"Nline",
"{",
"match",
"=",
"false",
"\n",
"}",
"\n",
"if",
"match",
"&&",
"x",
".",
"Content",
"!=",
"nil",
"&&",
"!",
"x",
".",
"Content",
".",
"MatchString",
"(",
"s",
".",
"Line",
")",
"{",
"match",
"=",
"false",
"\n",
"}",
"\n",
"return",
"match",
"\n",
"}"
] |
// Run executes the exception into a secret to determine if it's an exception
// or not.
|
[
"Run",
"executes",
"the",
"exception",
"into",
"a",
"secret",
"to",
"determine",
"if",
"it",
"s",
"an",
"exception",
"or",
"not",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L79-L99
|
test
|
apuigsech/seekret
|
seekret.go
|
AddRule
|
func (s *Seekret) AddRule(rule models.Rule, enabled bool) {
if enabled {
rule.Enable()
}
s.ruleList = append(s.ruleList, rule)
}
|
go
|
func (s *Seekret) AddRule(rule models.Rule, enabled bool) {
if enabled {
rule.Enable()
}
s.ruleList = append(s.ruleList, rule)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"AddRule",
"(",
"rule",
"models",
".",
"Rule",
",",
"enabled",
"bool",
")",
"{",
"if",
"enabled",
"{",
"rule",
".",
"Enable",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"ruleList",
"=",
"append",
"(",
"s",
".",
"ruleList",
",",
"rule",
")",
"\n",
"}"
] |
// AddRule adds a new rule into the context.
|
[
"AddRule",
"adds",
"a",
"new",
"rule",
"into",
"the",
"context",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L41-L46
|
test
|
apuigsech/seekret
|
seekret.go
|
LoadRulesFromFile
|
func (s *Seekret) LoadRulesFromFile(file string, defaulEnabled bool) error {
var ruleYamlMap map[string]ruleYaml
if file == "" {
return nil
}
filename, _ := filepath.Abs(file)
ruleBase := filepath.Base(filename)
if filepath.Ext(ruleBase) == ".rule" {
ruleBase = ruleBase[0 : len(ruleBase)-5]
}
yamlData, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = yaml.Unmarshal(yamlData, &ruleYamlMap)
if err != nil {
return err
}
for k, v := range ruleYamlMap {
rule, err := models.NewRule(ruleBase+"."+k, v.Match)
if err != nil {
return err
}
for _, e := range v.Unmatch {
rule.AddUnmatch(e)
}
s.AddRule(*rule, defaulEnabled)
}
return nil
}
|
go
|
func (s *Seekret) LoadRulesFromFile(file string, defaulEnabled bool) error {
var ruleYamlMap map[string]ruleYaml
if file == "" {
return nil
}
filename, _ := filepath.Abs(file)
ruleBase := filepath.Base(filename)
if filepath.Ext(ruleBase) == ".rule" {
ruleBase = ruleBase[0 : len(ruleBase)-5]
}
yamlData, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = yaml.Unmarshal(yamlData, &ruleYamlMap)
if err != nil {
return err
}
for k, v := range ruleYamlMap {
rule, err := models.NewRule(ruleBase+"."+k, v.Match)
if err != nil {
return err
}
for _, e := range v.Unmatch {
rule.AddUnmatch(e)
}
s.AddRule(*rule, defaulEnabled)
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"LoadRulesFromFile",
"(",
"file",
"string",
",",
"defaulEnabled",
"bool",
")",
"error",
"{",
"var",
"ruleYamlMap",
"map",
"[",
"string",
"]",
"ruleYaml",
"\n",
"if",
"file",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"filename",
",",
"_",
":=",
"filepath",
".",
"Abs",
"(",
"file",
")",
"\n",
"ruleBase",
":=",
"filepath",
".",
"Base",
"(",
"filename",
")",
"\n",
"if",
"filepath",
".",
"Ext",
"(",
"ruleBase",
")",
"==",
"\".rule\"",
"{",
"ruleBase",
"=",
"ruleBase",
"[",
"0",
":",
"len",
"(",
"ruleBase",
")",
"-",
"5",
"]",
"\n",
"}",
"\n",
"yamlData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"yaml",
".",
"Unmarshal",
"(",
"yamlData",
",",
"&",
"ruleYamlMap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"ruleYamlMap",
"{",
"rule",
",",
"err",
":=",
"models",
".",
"NewRule",
"(",
"ruleBase",
"+",
"\".\"",
"+",
"k",
",",
"v",
".",
"Match",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"v",
".",
"Unmatch",
"{",
"rule",
".",
"AddUnmatch",
"(",
"e",
")",
"\n",
"}",
"\n",
"s",
".",
"AddRule",
"(",
"*",
"rule",
",",
"defaulEnabled",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// LoadRulesFromFile loads rules from a YAML file.
|
[
"LoadRulesFromFile",
"loads",
"rules",
"from",
"a",
"YAML",
"file",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L55-L92
|
test
|
apuigsech/seekret
|
seekret.go
|
LoadRulesFromDir
|
func (s *Seekret) LoadRulesFromDir(dir string, defaulEnabled bool) error {
fi, err := os.Stat(dir)
if err != nil {
return err
}
if !fi.IsDir() {
err := fmt.Errorf("%s is not a directory", dir)
return err
}
fileList, err := filepath.Glob(dir + "/*")
if err != nil {
return err
}
for _, file := range fileList {
if strings.HasSuffix(file, ".rule") {
err := s.LoadRulesFromFile(file, defaulEnabled)
if err != nil {
return err
}
}
}
return nil
}
|
go
|
func (s *Seekret) LoadRulesFromDir(dir string, defaulEnabled bool) error {
fi, err := os.Stat(dir)
if err != nil {
return err
}
if !fi.IsDir() {
err := fmt.Errorf("%s is not a directory", dir)
return err
}
fileList, err := filepath.Glob(dir + "/*")
if err != nil {
return err
}
for _, file := range fileList {
if strings.HasSuffix(file, ".rule") {
err := s.LoadRulesFromFile(file, defaulEnabled)
if err != nil {
return err
}
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"LoadRulesFromDir",
"(",
"dir",
"string",
",",
"defaulEnabled",
"bool",
")",
"error",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"%s is not a directory\"",
",",
"dir",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"fileList",
",",
"err",
":=",
"filepath",
".",
"Glob",
"(",
"dir",
"+",
"\"/*\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"fileList",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"file",
",",
"\".rule\"",
")",
"{",
"err",
":=",
"s",
".",
"LoadRulesFromFile",
"(",
"file",
",",
"defaulEnabled",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// LoadRulesFromFile loads rules from all YAML files inside a directory.
|
[
"LoadRulesFromFile",
"loads",
"rules",
"from",
"all",
"YAML",
"files",
"inside",
"a",
"directory",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L95-L119
|
test
|
apuigsech/seekret
|
seekret.go
|
DefaultRulesPath
|
func DefaultRulesPath() string {
rulesPath := os.Getenv("SEEKRET_RULES_PATH")
if rulesPath == "" {
rulesPath = os.ExpandEnv(defaultRulesDir)
}
return rulesPath
}
|
go
|
func DefaultRulesPath() string {
rulesPath := os.Getenv("SEEKRET_RULES_PATH")
if rulesPath == "" {
rulesPath = os.ExpandEnv(defaultRulesDir)
}
return rulesPath
}
|
[
"func",
"DefaultRulesPath",
"(",
")",
"string",
"{",
"rulesPath",
":=",
"os",
".",
"Getenv",
"(",
"\"SEEKRET_RULES_PATH\"",
")",
"\n",
"if",
"rulesPath",
"==",
"\"\"",
"{",
"rulesPath",
"=",
"os",
".",
"ExpandEnv",
"(",
"defaultRulesDir",
")",
"\n",
"}",
"\n",
"return",
"rulesPath",
"\n",
"}"
] |
// DefaultRulesPath return the default PATH that contains rules.
|
[
"DefaultRulesPath",
"return",
"the",
"default",
"PATH",
"that",
"contains",
"rules",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L140-L146
|
test
|
apuigsech/seekret
|
seekret.go
|
EnableRule
|
func (s *Seekret) EnableRule(name string) error {
return setRuleEnabled(s.ruleList, name, true)
}
|
go
|
func (s *Seekret) EnableRule(name string) error {
return setRuleEnabled(s.ruleList, name, true)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"EnableRule",
"(",
"name",
"string",
")",
"error",
"{",
"return",
"setRuleEnabled",
"(",
"s",
".",
"ruleList",
",",
"name",
",",
"true",
")",
"\n",
"}"
] |
// EnableRule enables specific rule.
|
[
"EnableRule",
"enables",
"specific",
"rule",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L154-L156
|
test
|
apuigsech/seekret
|
seekret.go
|
DisableRule
|
func (s *Seekret) DisableRule(name string) error {
return setRuleEnabled(s.ruleList, name, false)
}
|
go
|
func (s *Seekret) DisableRule(name string) error {
return setRuleEnabled(s.ruleList, name, false)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"DisableRule",
"(",
"name",
"string",
")",
"error",
"{",
"return",
"setRuleEnabled",
"(",
"s",
".",
"ruleList",
",",
"name",
",",
"false",
")",
"\n",
"}"
] |
// DisableRule disables specific rule.
|
[
"DisableRule",
"disables",
"specific",
"rule",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L159-L161
|
test
|
apuigsech/seekret
|
seekret.go
|
EnableRuleByRegexp
|
func (s *Seekret) EnableRuleByRegexp(name string) int {
return setRuleEnabledByRegexp(s.ruleList, name, true)
}
|
go
|
func (s *Seekret) EnableRuleByRegexp(name string) int {
return setRuleEnabledByRegexp(s.ruleList, name, true)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"EnableRuleByRegexp",
"(",
"name",
"string",
")",
"int",
"{",
"return",
"setRuleEnabledByRegexp",
"(",
"s",
".",
"ruleList",
",",
"name",
",",
"true",
")",
"\n",
"}"
] |
// EnableRule enables rules that match with a regular expression.
|
[
"EnableRule",
"enables",
"rules",
"that",
"match",
"with",
"a",
"regular",
"expression",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L164-L166
|
test
|
apuigsech/seekret
|
seekret.go
|
DisableRuleByRegexp
|
func (s *Seekret) DisableRuleByRegexp(name string) int {
return setRuleEnabledByRegexp(s.ruleList, name, false)
}
|
go
|
func (s *Seekret) DisableRuleByRegexp(name string) int {
return setRuleEnabledByRegexp(s.ruleList, name, false)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"DisableRuleByRegexp",
"(",
"name",
"string",
")",
"int",
"{",
"return",
"setRuleEnabledByRegexp",
"(",
"s",
".",
"ruleList",
",",
"name",
",",
"false",
")",
"\n",
"}"
] |
// DisableRule disables rules that match with a regular expression.
|
[
"DisableRule",
"disables",
"rules",
"that",
"match",
"with",
"a",
"regular",
"expression",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L169-L171
|
test
|
apuigsech/seekret
|
seekret.go
|
LoadObjects
|
func (s *Seekret) LoadObjects(st SourceType, source string, opt LoadOptions) error {
objectList, err := st.LoadObjects(source, opt)
if err != nil {
return err
}
s.objectList = append(s.objectList, objectList...)
return nil
}
|
go
|
func (s *Seekret) LoadObjects(st SourceType, source string, opt LoadOptions) error {
objectList, err := st.LoadObjects(source, opt)
if err != nil {
return err
}
s.objectList = append(s.objectList, objectList...)
return nil
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"LoadObjects",
"(",
"st",
"SourceType",
",",
"source",
"string",
",",
"opt",
"LoadOptions",
")",
"error",
"{",
"objectList",
",",
"err",
":=",
"st",
".",
"LoadObjects",
"(",
"source",
",",
"opt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"objectList",
"=",
"append",
"(",
"s",
".",
"objectList",
",",
"objectList",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// LoadObjects loads objects form an specific source. It can load objects from
// different source types, that are implemented following the SourceType
// interface.
|
[
"LoadObjects",
"loads",
"objects",
"form",
"an",
"specific",
"source",
".",
"It",
"can",
"load",
"objects",
"from",
"different",
"source",
"types",
"that",
"are",
"implemented",
"following",
"the",
"SourceType",
"interface",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L208-L215
|
test
|
apuigsech/seekret
|
seekret.go
|
GroupObjectsByMetadata
|
func (s *Seekret) GroupObjectsByMetadata(k string) map[string][]models.Object {
return models.GroupObjectsByMetadata(s.objectList, k)
}
|
go
|
func (s *Seekret) GroupObjectsByMetadata(k string) map[string][]models.Object {
return models.GroupObjectsByMetadata(s.objectList, k)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"GroupObjectsByMetadata",
"(",
"k",
"string",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"models",
".",
"Object",
"{",
"return",
"models",
".",
"GroupObjectsByMetadata",
"(",
"s",
".",
"objectList",
",",
"k",
")",
"\n",
"}"
] |
// GroupObjectsByMetadata returns a map with all objects grouped by specific
// metadata key.
|
[
"GroupObjectsByMetadata",
"returns",
"a",
"map",
"with",
"all",
"objects",
"grouped",
"by",
"specific",
"metadata",
"key",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L219-L221
|
test
|
apuigsech/seekret
|
seekret.go
|
GroupObjectsByPrimaryKeyHash
|
func (s *Seekret) GroupObjectsByPrimaryKeyHash() map[string][]models.Object {
return models.GroupObjectsByPrimaryKeyHash(s.objectList)
}
|
go
|
func (s *Seekret) GroupObjectsByPrimaryKeyHash() map[string][]models.Object {
return models.GroupObjectsByPrimaryKeyHash(s.objectList)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"GroupObjectsByPrimaryKeyHash",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"models",
".",
"Object",
"{",
"return",
"models",
".",
"GroupObjectsByPrimaryKeyHash",
"(",
"s",
".",
"objectList",
")",
"\n",
"}"
] |
// GroupObjectsByPrimaryKeyHash returns a map with all objects grouped by
// the primary key hash, that is calculated from all metadata keys with the
// primary attribute.
// All returned objects could have the same content, even if are not the same.
|
[
"GroupObjectsByPrimaryKeyHash",
"returns",
"a",
"map",
"with",
"all",
"objects",
"grouped",
"by",
"the",
"primary",
"key",
"hash",
"that",
"is",
"calculated",
"from",
"all",
"metadata",
"keys",
"with",
"the",
"primary",
"attribute",
".",
"All",
"returned",
"objects",
"could",
"have",
"the",
"same",
"content",
"even",
"if",
"are",
"not",
"the",
"same",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L227-L229
|
test
|
apuigsech/seekret
|
seekret.go
|
AddException
|
func (s *Seekret) AddException(exception models.Exception) {
s.exceptionList = append(s.exceptionList, exception)
}
|
go
|
func (s *Seekret) AddException(exception models.Exception) {
s.exceptionList = append(s.exceptionList, exception)
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"AddException",
"(",
"exception",
"models",
".",
"Exception",
")",
"{",
"s",
".",
"exceptionList",
"=",
"append",
"(",
"s",
".",
"exceptionList",
",",
"exception",
")",
"\n",
"}"
] |
// AddException adds a new exception into the context.
|
[
"AddException",
"adds",
"a",
"new",
"exception",
"into",
"the",
"context",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L239-L241
|
test
|
apuigsech/seekret
|
seekret.go
|
LoadExceptionsFromFile
|
func (s *Seekret) LoadExceptionsFromFile(file string) error {
var exceptionYamlList []exceptionYaml
if file == "" {
return nil
}
filename, _ := filepath.Abs(file)
yamlData, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = yaml.Unmarshal(yamlData, &exceptionYamlList)
if err != nil {
return err
}
for _, v := range exceptionYamlList {
x := models.NewException()
if v.Rule != nil {
err := x.SetRule(*v.Rule)
if err != nil {
return err
}
}
if v.Object != nil {
err := x.SetObject(*v.Object)
if err != nil {
return err
}
}
if v.Line != nil {
err := x.SetNline(*v.Line)
if err != nil {
return err
}
}
if v.Content != nil {
err := x.SetContent(*v.Content)
if err != nil {
return err
}
}
s.AddException(*x)
}
return nil
}
|
go
|
func (s *Seekret) LoadExceptionsFromFile(file string) error {
var exceptionYamlList []exceptionYaml
if file == "" {
return nil
}
filename, _ := filepath.Abs(file)
yamlData, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = yaml.Unmarshal(yamlData, &exceptionYamlList)
if err != nil {
return err
}
for _, v := range exceptionYamlList {
x := models.NewException()
if v.Rule != nil {
err := x.SetRule(*v.Rule)
if err != nil {
return err
}
}
if v.Object != nil {
err := x.SetObject(*v.Object)
if err != nil {
return err
}
}
if v.Line != nil {
err := x.SetNline(*v.Line)
if err != nil {
return err
}
}
if v.Content != nil {
err := x.SetContent(*v.Content)
if err != nil {
return err
}
}
s.AddException(*x)
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Seekret",
")",
"LoadExceptionsFromFile",
"(",
"file",
"string",
")",
"error",
"{",
"var",
"exceptionYamlList",
"[",
"]",
"exceptionYaml",
"\n",
"if",
"file",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"filename",
",",
"_",
":=",
"filepath",
".",
"Abs",
"(",
"file",
")",
"\n",
"yamlData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"yaml",
".",
"Unmarshal",
"(",
"yamlData",
",",
"&",
"exceptionYamlList",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"exceptionYamlList",
"{",
"x",
":=",
"models",
".",
"NewException",
"(",
")",
"\n",
"if",
"v",
".",
"Rule",
"!=",
"nil",
"{",
"err",
":=",
"x",
".",
"SetRule",
"(",
"*",
"v",
".",
"Rule",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
".",
"Object",
"!=",
"nil",
"{",
"err",
":=",
"x",
".",
"SetObject",
"(",
"*",
"v",
".",
"Object",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
".",
"Line",
"!=",
"nil",
"{",
"err",
":=",
"x",
".",
"SetNline",
"(",
"*",
"v",
".",
"Line",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
".",
"Content",
"!=",
"nil",
"{",
"err",
":=",
"x",
".",
"SetContent",
"(",
"*",
"v",
".",
"Content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"AddException",
"(",
"*",
"x",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// LoadExceptionsFromFile loads exceptions from a YAML file.
|
[
"LoadExceptionsFromFile",
"loads",
"exceptions",
"from",
"a",
"YAML",
"file",
"."
] |
9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L244-L297
|
test
|
justinfx/gofileseq
|
cmd/seqinfo/seqinfo.go
|
printPlainResults
|
func printPlainResults(results Results) error {
for _, res := range results {
// Explicitely start with the string and error output
fmt.Printf("Source = %s\n", res.origString)
fmt.Printf(" String = %s\n", res.String)
if res.Error != "" {
fmt.Printf(" Error = %s\n", res.Error)
continue
}
// Dynamically loop over the rest of the fields
typ := reflect.TypeOf(*res)
val := reflect.ValueOf(*res)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.Name == "Error" || field.Name == "String" {
continue
}
if field.PkgPath != "" {
// ignore unexported fields
continue
}
fmt.Printf(" %s = %v\n", field.Name, val.Field(i).Interface())
}
fmt.Print("\n")
}
return nil
}
|
go
|
func printPlainResults(results Results) error {
for _, res := range results {
// Explicitely start with the string and error output
fmt.Printf("Source = %s\n", res.origString)
fmt.Printf(" String = %s\n", res.String)
if res.Error != "" {
fmt.Printf(" Error = %s\n", res.Error)
continue
}
// Dynamically loop over the rest of the fields
typ := reflect.TypeOf(*res)
val := reflect.ValueOf(*res)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.Name == "Error" || field.Name == "String" {
continue
}
if field.PkgPath != "" {
// ignore unexported fields
continue
}
fmt.Printf(" %s = %v\n", field.Name, val.Field(i).Interface())
}
fmt.Print("\n")
}
return nil
}
|
[
"func",
"printPlainResults",
"(",
"results",
"Results",
")",
"error",
"{",
"for",
"_",
",",
"res",
":=",
"range",
"results",
"{",
"fmt",
".",
"Printf",
"(",
"\"Source = %s\\n\"",
",",
"\\n",
")",
"\n",
"res",
".",
"origString",
"\n",
"fmt",
".",
"Printf",
"(",
"\" String = %s\\n\"",
",",
"\\n",
")",
"\n",
"res",
".",
"String",
"\n",
"if",
"res",
".",
"Error",
"!=",
"\"\"",
"{",
"fmt",
".",
"Printf",
"(",
"\" Error = %s\\n\"",
",",
"\\n",
")",
"\n",
"res",
".",
"Error",
"\n",
"}",
"\n",
"continue",
"\n",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"*",
"res",
")",
"\n",
"}",
"\n",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"*",
"res",
")",
"\n",
"}"
] |
// printPlainResults prints plain-text output for results
|
[
"printPlainResults",
"prints",
"plain",
"-",
"text",
"output",
"for",
"results"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqinfo/seqinfo.go#L155-L185
|
test
|
justinfx/gofileseq
|
cmd/seqinfo/seqinfo.go
|
printJsonResults
|
func printJsonResults(results Results) error {
data, err := json.MarshalIndent(results, "", " ")
if err != nil {
return fmt.Errorf("Failed to convert results to JSON: %s", err.Error())
}
if _, err = io.Copy(os.Stdout, bytes.NewReader(data)); err != nil {
return fmt.Errorf("Failed to write json output: %s", err.Error())
}
fmt.Print("\n")
return nil
}
|
go
|
func printJsonResults(results Results) error {
data, err := json.MarshalIndent(results, "", " ")
if err != nil {
return fmt.Errorf("Failed to convert results to JSON: %s", err.Error())
}
if _, err = io.Copy(os.Stdout, bytes.NewReader(data)); err != nil {
return fmt.Errorf("Failed to write json output: %s", err.Error())
}
fmt.Print("\n")
return nil
}
|
[
"func",
"printJsonResults",
"(",
"results",
"Results",
")",
"error",
"{",
"data",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"results",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to convert results to JSON: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"os",
".",
"Stdout",
",",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to write json output: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Print",
"(",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"}"
] |
// printJsonResults prints json-formatted output for results
|
[
"printJsonResults",
"prints",
"json",
"-",
"formatted",
"output",
"for",
"results"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqinfo/seqinfo.go#L188-L200
|
test
|
justinfx/gofileseq
|
exp/cpp/export/uuid.go
|
NewXor64Source
|
func NewXor64Source(seed int64) *Xor64Source {
var s Xor64Source
s.Seed(seed)
return &s
}
|
go
|
func NewXor64Source(seed int64) *Xor64Source {
var s Xor64Source
s.Seed(seed)
return &s
}
|
[
"func",
"NewXor64Source",
"(",
"seed",
"int64",
")",
"*",
"Xor64Source",
"{",
"var",
"s",
"Xor64Source",
"\n",
"s",
".",
"Seed",
"(",
"seed",
")",
"\n",
"return",
"&",
"s",
"\n",
"}"
] |
// NewXor64Source returns a pointer to a new Xor64Source seeded with the given
// value.
|
[
"NewXor64Source",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Xor64Source",
"seeded",
"with",
"the",
"given",
"value",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/uuid.go#L56-L60
|
test
|
justinfx/gofileseq
|
exp/cpp/export/uuid.go
|
xor64
|
func xor64(x uint64) uint64 {
x ^= x << 13
x ^= x >> 7
x ^= x << 17
return x
}
|
go
|
func xor64(x uint64) uint64 {
x ^= x << 13
x ^= x >> 7
x ^= x << 17
return x
}
|
[
"func",
"xor64",
"(",
"x",
"uint64",
")",
"uint64",
"{",
"x",
"^=",
"x",
"<<",
"13",
"\n",
"x",
"^=",
"x",
">>",
"7",
"\n",
"x",
"^=",
"x",
"<<",
"17",
"\n",
"return",
"x",
"\n",
"}"
] |
// xor64 generates the next value of a pseudo-random sequence given a current
// state x.
|
[
"xor64",
"generates",
"the",
"next",
"value",
"of",
"a",
"pseudo",
"-",
"random",
"sequence",
"given",
"a",
"current",
"state",
"x",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/uuid.go#L64-L69
|
test
|
justinfx/gofileseq
|
exp/cpp/export/uuid.go
|
next
|
func (s *Xor64Source) next() uint64 {
x := xor64(uint64(*s))
*s = Xor64Source(x)
return x
}
|
go
|
func (s *Xor64Source) next() uint64 {
x := xor64(uint64(*s))
*s = Xor64Source(x)
return x
}
|
[
"func",
"(",
"s",
"*",
"Xor64Source",
")",
"next",
"(",
")",
"uint64",
"{",
"x",
":=",
"xor64",
"(",
"uint64",
"(",
"*",
"s",
")",
")",
"\n",
"*",
"s",
"=",
"Xor64Source",
"(",
"x",
")",
"\n",
"return",
"x",
"\n",
"}"
] |
// next advances the generators internal state to the next value and returns
// this value as an uint64.
|
[
"next",
"advances",
"the",
"generators",
"internal",
"state",
"to",
"the",
"next",
"value",
"and",
"returns",
"this",
"value",
"as",
"an",
"uint64",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/uuid.go#L73-L77
|
test
|
justinfx/gofileseq
|
exp/cpp/export/uuid.go
|
Seed
|
func (s *Xor64Source) Seed(seed int64) {
if seed == 0 {
seed = seed0
}
*s = Xor64Source(seed)
}
|
go
|
func (s *Xor64Source) Seed(seed int64) {
if seed == 0 {
seed = seed0
}
*s = Xor64Source(seed)
}
|
[
"func",
"(",
"s",
"*",
"Xor64Source",
")",
"Seed",
"(",
"seed",
"int64",
")",
"{",
"if",
"seed",
"==",
"0",
"{",
"seed",
"=",
"seed0",
"\n",
"}",
"\n",
"*",
"s",
"=",
"Xor64Source",
"(",
"seed",
")",
"\n",
"}"
] |
// Seed uses the given value to initialize the generator. If this value is 0, a
// pre-defined seed is used instead, since the xorshift algorithm requires at
// least one bit of the internal state to be set.
|
[
"Seed",
"uses",
"the",
"given",
"value",
"to",
"initialize",
"the",
"generator",
".",
"If",
"this",
"value",
"is",
"0",
"a",
"pre",
"-",
"defined",
"seed",
"is",
"used",
"instead",
"since",
"the",
"xorshift",
"algorithm",
"requires",
"at",
"least",
"one",
"bit",
"of",
"the",
"internal",
"state",
"to",
"be",
"set",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/uuid.go#L92-L97
|
test
|
justinfx/gofileseq
|
frameset.go
|
NewFrameSet
|
func NewFrameSet(frange string) (*FrameSet, error) {
// Process the frame range and get a slice of match slices
matches, err := frameRangeMatches(frange)
if err != nil {
return nil, err
}
frameSet := &FrameSet{frange, &ranges.InclusiveRanges{}}
// Process each slice match and add it to the frame set
for _, match := range matches {
if err = frameSet.handleMatch(match); err != nil {
return nil, err
}
}
return frameSet, nil
}
|
go
|
func NewFrameSet(frange string) (*FrameSet, error) {
// Process the frame range and get a slice of match slices
matches, err := frameRangeMatches(frange)
if err != nil {
return nil, err
}
frameSet := &FrameSet{frange, &ranges.InclusiveRanges{}}
// Process each slice match and add it to the frame set
for _, match := range matches {
if err = frameSet.handleMatch(match); err != nil {
return nil, err
}
}
return frameSet, nil
}
|
[
"func",
"NewFrameSet",
"(",
"frange",
"string",
")",
"(",
"*",
"FrameSet",
",",
"error",
")",
"{",
"matches",
",",
"err",
":=",
"frameRangeMatches",
"(",
"frange",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"frameSet",
":=",
"&",
"FrameSet",
"{",
"frange",
",",
"&",
"ranges",
".",
"InclusiveRanges",
"{",
"}",
"}",
"\n",
"for",
"_",
",",
"match",
":=",
"range",
"matches",
"{",
"if",
"err",
"=",
"frameSet",
".",
"handleMatch",
"(",
"match",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"frameSet",
",",
"nil",
"\n",
"}"
] |
// Create a new FrameSet from a given frame range string
// Returns an error if the frame range could not be parsed.
|
[
"Create",
"a",
"new",
"FrameSet",
"from",
"a",
"given",
"frame",
"range",
"string",
"Returns",
"an",
"error",
"if",
"the",
"frame",
"range",
"could",
"not",
"be",
"parsed",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L19-L36
|
test
|
justinfx/gofileseq
|
frameset.go
|
handleMatch
|
func (s *FrameSet) handleMatch(match []string) error {
switch len(match) {
// Single frame match
case 1:
f, err := parseInt(match[0])
if err != nil {
return err
}
s.rangePtr.AppendUnique(f, f, 1)
// Simple frame range
case 2:
start, err := parseInt(match[0])
if err != nil {
return err
}
end, err := parseInt(match[1])
if err != nil {
return err
}
// Handle descending frame ranges, like 10-1
var inc int
if start > end {
inc = -1
} else {
inc = 1
}
s.rangePtr.AppendUnique(start, end, inc)
// Complex frame range
case 4:
var (
err error
mod string
start, end, chunk int
)
chunk, err = parseInt(match[3])
if err != nil {
return err
}
if chunk == 0 {
return fmt.Errorf("Failed to parse part of range %v. "+
"Encountered invalid 0 value", match[3])
}
if start, err = parseInt(match[0]); err != nil {
return err
}
if end, err = parseInt(match[1]); err != nil {
return err
}
if mod = match[2]; !isModifier(mod) {
return fmt.Errorf("%q is not one of the valid modifier 'xy:'", mod)
}
switch mod {
case `x`:
s.rangePtr.AppendUnique(start, end, chunk)
case `y`:
// TODO: Add proper support for adding inverse of range.
// This approach will add excessive amounts of singe
// range elements. They could be compressed into chunks
skip := start
aRange := ranges.NewInclusiveRange(start, end, 1)
var val int
for it := aRange.IterValues(); !it.IsDone(); {
val = it.Next()
if val == skip {
skip += chunk
continue
}
s.rangePtr.AppendUnique(val, val, 1)
}
case `:`:
for ; chunk > 0; chunk-- {
s.rangePtr.AppendUnique(start, end, chunk)
}
}
default:
return fmt.Errorf("Unexpected match []string size: %v", match)
}
return nil
}
|
go
|
func (s *FrameSet) handleMatch(match []string) error {
switch len(match) {
// Single frame match
case 1:
f, err := parseInt(match[0])
if err != nil {
return err
}
s.rangePtr.AppendUnique(f, f, 1)
// Simple frame range
case 2:
start, err := parseInt(match[0])
if err != nil {
return err
}
end, err := parseInt(match[1])
if err != nil {
return err
}
// Handle descending frame ranges, like 10-1
var inc int
if start > end {
inc = -1
} else {
inc = 1
}
s.rangePtr.AppendUnique(start, end, inc)
// Complex frame range
case 4:
var (
err error
mod string
start, end, chunk int
)
chunk, err = parseInt(match[3])
if err != nil {
return err
}
if chunk == 0 {
return fmt.Errorf("Failed to parse part of range %v. "+
"Encountered invalid 0 value", match[3])
}
if start, err = parseInt(match[0]); err != nil {
return err
}
if end, err = parseInt(match[1]); err != nil {
return err
}
if mod = match[2]; !isModifier(mod) {
return fmt.Errorf("%q is not one of the valid modifier 'xy:'", mod)
}
switch mod {
case `x`:
s.rangePtr.AppendUnique(start, end, chunk)
case `y`:
// TODO: Add proper support for adding inverse of range.
// This approach will add excessive amounts of singe
// range elements. They could be compressed into chunks
skip := start
aRange := ranges.NewInclusiveRange(start, end, 1)
var val int
for it := aRange.IterValues(); !it.IsDone(); {
val = it.Next()
if val == skip {
skip += chunk
continue
}
s.rangePtr.AppendUnique(val, val, 1)
}
case `:`:
for ; chunk > 0; chunk-- {
s.rangePtr.AppendUnique(start, end, chunk)
}
}
default:
return fmt.Errorf("Unexpected match []string size: %v", match)
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"FrameSet",
")",
"handleMatch",
"(",
"match",
"[",
"]",
"string",
")",
"error",
"{",
"switch",
"len",
"(",
"match",
")",
"{",
"case",
"1",
":",
"f",
",",
"err",
":=",
"parseInt",
"(",
"match",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"rangePtr",
".",
"AppendUnique",
"(",
"f",
",",
"f",
",",
"1",
")",
"\n",
"case",
"2",
":",
"start",
",",
"err",
":=",
"parseInt",
"(",
"match",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"end",
",",
"err",
":=",
"parseInt",
"(",
"match",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"inc",
"int",
"\n",
"if",
"start",
">",
"end",
"{",
"inc",
"=",
"-",
"1",
"\n",
"}",
"else",
"{",
"inc",
"=",
"1",
"\n",
"}",
"\n",
"s",
".",
"rangePtr",
".",
"AppendUnique",
"(",
"start",
",",
"end",
",",
"inc",
")",
"\n",
"case",
"4",
":",
"var",
"(",
"err",
"error",
"\n",
"mod",
"string",
"\n",
"start",
",",
"end",
",",
"chunk",
"int",
"\n",
")",
"\n",
"chunk",
",",
"err",
"=",
"parseInt",
"(",
"match",
"[",
"3",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"chunk",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to parse part of range %v. \"",
"+",
"\"Encountered invalid 0 value\"",
",",
"match",
"[",
"3",
"]",
")",
"\n",
"}",
"\n",
"if",
"start",
",",
"err",
"=",
"parseInt",
"(",
"match",
"[",
"0",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"end",
",",
"err",
"=",
"parseInt",
"(",
"match",
"[",
"1",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"mod",
"=",
"match",
"[",
"2",
"]",
";",
"!",
"isModifier",
"(",
"mod",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%q is not one of the valid modifier 'xy:'\"",
",",
"mod",
")",
"\n",
"}",
"\n",
"switch",
"mod",
"{",
"case",
"`x`",
":",
"s",
".",
"rangePtr",
".",
"AppendUnique",
"(",
"start",
",",
"end",
",",
"chunk",
")",
"\n",
"case",
"`y`",
":",
"skip",
":=",
"start",
"\n",
"aRange",
":=",
"ranges",
".",
"NewInclusiveRange",
"(",
"start",
",",
"end",
",",
"1",
")",
"\n",
"var",
"val",
"int",
"\n",
"for",
"it",
":=",
"aRange",
".",
"IterValues",
"(",
")",
";",
"!",
"it",
".",
"IsDone",
"(",
")",
";",
"{",
"val",
"=",
"it",
".",
"Next",
"(",
")",
"\n",
"if",
"val",
"==",
"skip",
"{",
"skip",
"+=",
"chunk",
"\n",
"continue",
"\n",
"}",
"\n",
"s",
".",
"rangePtr",
".",
"AppendUnique",
"(",
"val",
",",
"val",
",",
"1",
")",
"\n",
"}",
"\n",
"case",
"`:`",
":",
"for",
";",
"chunk",
">",
"0",
";",
"chunk",
"--",
"{",
"s",
".",
"rangePtr",
".",
"AppendUnique",
"(",
"start",
",",
"end",
",",
"chunk",
")",
"\n",
"}",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Unexpected match []string size: %v\"",
",",
"match",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Process a rangePattern match group
|
[
"Process",
"a",
"rangePattern",
"match",
"group"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L39-L127
|
test
|
justinfx/gofileseq
|
frameset.go
|
Index
|
func (s *FrameSet) Index(frame int) int {
return s.rangePtr.Index(frame)
}
|
go
|
func (s *FrameSet) Index(frame int) int {
return s.rangePtr.Index(frame)
}
|
[
"func",
"(",
"s",
"*",
"FrameSet",
")",
"Index",
"(",
"frame",
"int",
")",
"int",
"{",
"return",
"s",
".",
"rangePtr",
".",
"Index",
"(",
"frame",
")",
"\n",
"}"
] |
// Index returns the index position of the frame value
// within the frame set.
// If the given frame does not exist, then return -1
|
[
"Index",
"returns",
"the",
"index",
"position",
"of",
"the",
"frame",
"value",
"within",
"the",
"frame",
"set",
".",
"If",
"the",
"given",
"frame",
"does",
"not",
"exist",
"then",
"return",
"-",
"1"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L144-L146
|
test
|
justinfx/gofileseq
|
frameset.go
|
Frame
|
func (s *FrameSet) Frame(index int) (int, error) {
return s.rangePtr.Value(index)
}
|
go
|
func (s *FrameSet) Frame(index int) (int, error) {
return s.rangePtr.Value(index)
}
|
[
"func",
"(",
"s",
"*",
"FrameSet",
")",
"Frame",
"(",
"index",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"s",
".",
"rangePtr",
".",
"Value",
"(",
"index",
")",
"\n",
"}"
] |
// Frame returns the frame number value for a given index into
// the frame set.
// If the index is outside the bounds of the frame set range,
// then an error is returned.
|
[
"Frame",
"returns",
"the",
"frame",
"number",
"value",
"for",
"a",
"given",
"index",
"into",
"the",
"frame",
"set",
".",
"If",
"the",
"index",
"is",
"outside",
"the",
"bounds",
"of",
"the",
"frame",
"set",
"range",
"then",
"an",
"error",
"is",
"returned",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L152-L154
|
test
|
justinfx/gofileseq
|
frameset.go
|
HasFrame
|
func (s *FrameSet) HasFrame(frame int) bool {
return s.rangePtr.Contains(frame)
}
|
go
|
func (s *FrameSet) HasFrame(frame int) bool {
return s.rangePtr.Contains(frame)
}
|
[
"func",
"(",
"s",
"*",
"FrameSet",
")",
"HasFrame",
"(",
"frame",
"int",
")",
"bool",
"{",
"return",
"s",
".",
"rangePtr",
".",
"Contains",
"(",
"frame",
")",
"\n",
"}"
] |
// HasFrame returns true if the frameset contains the given
// frame value.
|
[
"HasFrame",
"returns",
"true",
"if",
"the",
"frameset",
"contains",
"the",
"given",
"frame",
"value",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L175-L177
|
test
|
justinfx/gofileseq
|
frameset.go
|
FrameRangePadded
|
func (s *FrameSet) FrameRangePadded(pad int) string {
return PadFrameRange(s.frange, pad)
}
|
go
|
func (s *FrameSet) FrameRangePadded(pad int) string {
return PadFrameRange(s.frange, pad)
}
|
[
"func",
"(",
"s",
"*",
"FrameSet",
")",
"FrameRangePadded",
"(",
"pad",
"int",
")",
"string",
"{",
"return",
"PadFrameRange",
"(",
"s",
".",
"frange",
",",
"pad",
")",
"\n",
"}"
] |
// FrameRangePadded returns the range string that was used
// to initialize the FrameSet, with each number padded out
// with zeros to a given width
|
[
"FrameRangePadded",
"returns",
"the",
"range",
"string",
"that",
"was",
"used",
"to",
"initialize",
"the",
"FrameSet",
"with",
"each",
"number",
"padded",
"out",
"with",
"zeros",
"to",
"a",
"given",
"width"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L198-L200
|
test
|
justinfx/gofileseq
|
frameset.go
|
Normalize
|
func (s *FrameSet) Normalize() *FrameSet {
ptr := s.rangePtr.Normalized()
return &FrameSet{ptr.String(), ptr}
}
|
go
|
func (s *FrameSet) Normalize() *FrameSet {
ptr := s.rangePtr.Normalized()
return &FrameSet{ptr.String(), ptr}
}
|
[
"func",
"(",
"s",
"*",
"FrameSet",
")",
"Normalize",
"(",
")",
"*",
"FrameSet",
"{",
"ptr",
":=",
"s",
".",
"rangePtr",
".",
"Normalized",
"(",
")",
"\n",
"return",
"&",
"FrameSet",
"{",
"ptr",
".",
"String",
"(",
")",
",",
"ptr",
"}",
"\n",
"}"
] |
// Normalize returns a new sorted and compacted FrameSet
|
[
"Normalize",
"returns",
"a",
"new",
"sorted",
"and",
"compacted",
"FrameSet"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L222-L225
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.