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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
jolestar/go-commons-pool | collections/queue.go | Remove | func (iterator *LinkedBlockingDequeIterator) Remove() {
n := iterator.lastRet
if n == nil {
panic(errors.New("IllegalStateException"))
}
iterator.lastRet = nil
lock := iterator.q.lock
lock.Lock()
if n.item != nil {
iterator.q.unlink(n)
}
lock.Unlock()
} | go | func (iterator *LinkedBlockingDequeIterator) Remove() {
n := iterator.lastRet
if n == nil {
panic(errors.New("IllegalStateException"))
}
iterator.lastRet = nil
lock := iterator.q.lock
lock.Lock()
if n.item != nil {
iterator.q.unlink(n)
}
lock.Unlock()
} | [
"func",
"(",
"iterator",
"*",
"LinkedBlockingDequeIterator",
")",
"Remove",
"(",
")",
"{",
"n",
":=",
"iterator",
".",
"lastRet",
"\n",
"if",
"n",
"==",
"nil",
"{",
"panic",
"(",
"errors",
".",
"New",
"(",
"\"IllegalStateException\"",
")",
")",
"\n",
"}"... | // Remove current element from dequeue | [
"Remove",
"current",
"element",
"from",
"dequeue"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L558-L570 | train |
jolestar/go-commons-pool | config.go | NewDefaultPoolConfig | func NewDefaultPoolConfig() *ObjectPoolConfig {
return &ObjectPoolConfig{
LIFO: DefaultLIFO,
MaxTotal: DefaultMaxTotal,
MaxIdle: DefaultMaxIdle,
MinIdle: DefaultMinIdle,
MinEvictableIdleTime: DefaultMinEvictableIdleTime,
SoftMinEvictableIdleTime: DefaultSoftMinEvictableIdleTime,
NumTestsPerEvictionRun: DefaultNumTestsPerEvictionRun,
EvictionPolicyName: DefaultEvictionPolicyName,
EvitionContext: context.Background(),
TestOnCreate: DefaultTestOnCreate,
TestOnBorrow: DefaultTestOnBorrow,
TestOnReturn: DefaultTestOnReturn,
TestWhileIdle: DefaultTestWhileIdle,
TimeBetweenEvictionRuns: DefaultTimeBetweenEvictionRuns,
BlockWhenExhausted: DefaultBlockWhenExhausted}
} | go | func NewDefaultPoolConfig() *ObjectPoolConfig {
return &ObjectPoolConfig{
LIFO: DefaultLIFO,
MaxTotal: DefaultMaxTotal,
MaxIdle: DefaultMaxIdle,
MinIdle: DefaultMinIdle,
MinEvictableIdleTime: DefaultMinEvictableIdleTime,
SoftMinEvictableIdleTime: DefaultSoftMinEvictableIdleTime,
NumTestsPerEvictionRun: DefaultNumTestsPerEvictionRun,
EvictionPolicyName: DefaultEvictionPolicyName,
EvitionContext: context.Background(),
TestOnCreate: DefaultTestOnCreate,
TestOnBorrow: DefaultTestOnBorrow,
TestOnReturn: DefaultTestOnReturn,
TestWhileIdle: DefaultTestWhileIdle,
TimeBetweenEvictionRuns: DefaultTimeBetweenEvictionRuns,
BlockWhenExhausted: DefaultBlockWhenExhausted}
} | [
"func",
"NewDefaultPoolConfig",
"(",
")",
"*",
"ObjectPoolConfig",
"{",
"return",
"&",
"ObjectPoolConfig",
"{",
"LIFO",
":",
"DefaultLIFO",
",",
"MaxTotal",
":",
"DefaultMaxTotal",
",",
"MaxIdle",
":",
"DefaultMaxIdle",
",",
"MinIdle",
":",
"DefaultMinIdle",
",",
... | // NewDefaultPoolConfig return a ObjectPoolConfig instance init with default value. | [
"NewDefaultPoolConfig",
"return",
"a",
"ObjectPoolConfig",
"instance",
"init",
"with",
"default",
"value",
"."
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L192-L209 | train |
jolestar/go-commons-pool | config.go | NewDefaultAbandonedConfig | func NewDefaultAbandonedConfig() *AbandonedConfig {
return &AbandonedConfig{RemoveAbandonedOnBorrow: false, RemoveAbandonedOnMaintenance: false, RemoveAbandonedTimeout: 5 * time.Minute}
} | go | func NewDefaultAbandonedConfig() *AbandonedConfig {
return &AbandonedConfig{RemoveAbandonedOnBorrow: false, RemoveAbandonedOnMaintenance: false, RemoveAbandonedTimeout: 5 * time.Minute}
} | [
"func",
"NewDefaultAbandonedConfig",
"(",
")",
"*",
"AbandonedConfig",
"{",
"return",
"&",
"AbandonedConfig",
"{",
"RemoveAbandonedOnBorrow",
":",
"false",
",",
"RemoveAbandonedOnMaintenance",
":",
"false",
",",
"RemoveAbandonedTimeout",
":",
"5",
"*",
"time",
".",
... | // NewDefaultAbandonedConfig return a new AbandonedConfig instance init with default. | [
"NewDefaultAbandonedConfig",
"return",
"a",
"new",
"AbandonedConfig",
"instance",
"init",
"with",
"default",
"."
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L220-L222 | train |
jolestar/go-commons-pool | config.go | Evict | func (p *DefaultEvictionPolicy) Evict(config *EvictionConfig, underTest *PooledObject, idleCount int) bool {
idleTime := underTest.GetIdleTime()
if (config.IdleSoftEvictTime < idleTime &&
config.MinIdle < idleCount) ||
config.IdleEvictTime < idleTime {
return true
}
return false
} | go | func (p *DefaultEvictionPolicy) Evict(config *EvictionConfig, underTest *PooledObject, idleCount int) bool {
idleTime := underTest.GetIdleTime()
if (config.IdleSoftEvictTime < idleTime &&
config.MinIdle < idleCount) ||
config.IdleEvictTime < idleTime {
return true
}
return false
} | [
"func",
"(",
"p",
"*",
"DefaultEvictionPolicy",
")",
"Evict",
"(",
"config",
"*",
"EvictionConfig",
",",
"underTest",
"*",
"PooledObject",
",",
"idleCount",
"int",
")",
"bool",
"{",
"idleTime",
":=",
"underTest",
".",
"GetIdleTime",
"(",
")",
"\n",
"if",
"... | // Evict do evict by config | [
"Evict",
"do",
"evict",
"by",
"config"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L243-L252 | train |
jolestar/go-commons-pool | config.go | RegistryEvictionPolicy | func RegistryEvictionPolicy(name string, policy EvictionPolicy) {
if name == "" || policy == nil {
panic(errors.New("invalid argument"))
}
policiesMutex.Lock()
policies[name] = policy
policiesMutex.Unlock()
} | go | func RegistryEvictionPolicy(name string, policy EvictionPolicy) {
if name == "" || policy == nil {
panic(errors.New("invalid argument"))
}
policiesMutex.Lock()
policies[name] = policy
policiesMutex.Unlock()
} | [
"func",
"RegistryEvictionPolicy",
"(",
"name",
"string",
",",
"policy",
"EvictionPolicy",
")",
"{",
"if",
"name",
"==",
"\"\"",
"||",
"policy",
"==",
"nil",
"{",
"panic",
"(",
"errors",
".",
"New",
"(",
"\"invalid argument\"",
")",
")",
"\n",
"}",
"\n",
... | // RegistryEvictionPolicy registry a custom EvictionPolicy with gaven name. | [
"RegistryEvictionPolicy",
"registry",
"a",
"custom",
"EvictionPolicy",
"with",
"gaven",
"name",
"."
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L260-L267 | train |
jolestar/go-commons-pool | config.go | GetEvictionPolicy | func GetEvictionPolicy(name string) EvictionPolicy {
policiesMutex.Lock()
defer policiesMutex.Unlock()
return policies[name]
} | go | func GetEvictionPolicy(name string) EvictionPolicy {
policiesMutex.Lock()
defer policiesMutex.Unlock()
return policies[name]
} | [
"func",
"GetEvictionPolicy",
"(",
"name",
"string",
")",
"EvictionPolicy",
"{",
"policiesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"policiesMutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"policies",
"[",
"name",
"]",
"\n",
"}"
] | // GetEvictionPolicy return a EvictionPolicy by gaven name | [
"GetEvictionPolicy",
"return",
"a",
"EvictionPolicy",
"by",
"gaven",
"name"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L270-L275 | train |
jolestar/go-commons-pool | factory.go | NewPooledObjectFactorySimple | func NewPooledObjectFactorySimple(
create func(context.Context) (interface{}, error)) PooledObjectFactory {
return NewPooledObjectFactory(create, nil, nil, nil, nil)
} | go | func NewPooledObjectFactorySimple(
create func(context.Context) (interface{}, error)) PooledObjectFactory {
return NewPooledObjectFactory(create, nil, nil, nil, nil)
} | [
"func",
"NewPooledObjectFactorySimple",
"(",
"create",
"func",
"(",
"context",
".",
"Context",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
")",
"PooledObjectFactory",
"{",
"return",
"NewPooledObjectFactory",
"(",
"create",
",",
"nil",
",",
"nil",
",",
... | // NewPooledObjectFactorySimple return a DefaultPooledObjectFactory, only custom MakeObject func | [
"NewPooledObjectFactorySimple",
"return",
"a",
"DefaultPooledObjectFactory",
"only",
"custom",
"MakeObject",
"func"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L60-L63 | train |
jolestar/go-commons-pool | factory.go | NewPooledObjectFactory | func NewPooledObjectFactory(
create func(context.Context) (interface{}, error),
destroy func(ctx context.Context, object *PooledObject) error,
validate func(ctx context.Context, object *PooledObject) bool,
activate func(ctx context.Context, object *PooledObject) error,
passivate func(ctx context.Context, object *PooledObject) error) PooledObjectFactory {
if create == nil {
panic(errors.New("make function can not be nil"))
}
return &DefaultPooledObjectFactory{
make: func(ctx context.Context) (*PooledObject, error) {
o, err := create(ctx)
if err != nil {
return nil, err
}
return NewPooledObject(o), nil
},
destroy: destroy,
validate: validate,
activate: activate,
passivate: passivate}
} | go | func NewPooledObjectFactory(
create func(context.Context) (interface{}, error),
destroy func(ctx context.Context, object *PooledObject) error,
validate func(ctx context.Context, object *PooledObject) bool,
activate func(ctx context.Context, object *PooledObject) error,
passivate func(ctx context.Context, object *PooledObject) error) PooledObjectFactory {
if create == nil {
panic(errors.New("make function can not be nil"))
}
return &DefaultPooledObjectFactory{
make: func(ctx context.Context) (*PooledObject, error) {
o, err := create(ctx)
if err != nil {
return nil, err
}
return NewPooledObject(o), nil
},
destroy: destroy,
validate: validate,
activate: activate,
passivate: passivate}
} | [
"func",
"NewPooledObjectFactory",
"(",
"create",
"func",
"(",
"context",
".",
"Context",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
",",
"destroy",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"object",
"*",
"PooledObject",
")",
"error",
... | // NewPooledObjectFactory return a DefaultPooledObjectFactory, init with gaven func. | [
"NewPooledObjectFactory",
"return",
"a",
"DefaultPooledObjectFactory",
"init",
"with",
"gaven",
"func",
"."
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L66-L87 | train |
jolestar/go-commons-pool | factory.go | MakeObject | func (f *DefaultPooledObjectFactory) MakeObject(ctx context.Context) (*PooledObject, error) {
return f.make(ctx)
} | go | func (f *DefaultPooledObjectFactory) MakeObject(ctx context.Context) (*PooledObject, error) {
return f.make(ctx)
} | [
"func",
"(",
"f",
"*",
"DefaultPooledObjectFactory",
")",
"MakeObject",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"PooledObject",
",",
"error",
")",
"{",
"return",
"f",
".",
"make",
"(",
"ctx",
")",
"\n",
"}"
] | // MakeObject see PooledObjectFactory.MakeObject | [
"MakeObject",
"see",
"PooledObjectFactory",
".",
"MakeObject"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L90-L92 | train |
jolestar/go-commons-pool | factory.go | DestroyObject | func (f *DefaultPooledObjectFactory) DestroyObject(ctx context.Context, object *PooledObject) error {
if f.destroy != nil {
return f.destroy(ctx, object)
}
return nil
} | go | func (f *DefaultPooledObjectFactory) DestroyObject(ctx context.Context, object *PooledObject) error {
if f.destroy != nil {
return f.destroy(ctx, object)
}
return nil
} | [
"func",
"(",
"f",
"*",
"DefaultPooledObjectFactory",
")",
"DestroyObject",
"(",
"ctx",
"context",
".",
"Context",
",",
"object",
"*",
"PooledObject",
")",
"error",
"{",
"if",
"f",
".",
"destroy",
"!=",
"nil",
"{",
"return",
"f",
".",
"destroy",
"(",
"ctx... | // DestroyObject see PooledObjectFactory.DestroyObject | [
"DestroyObject",
"see",
"PooledObjectFactory",
".",
"DestroyObject"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L95-L100 | train |
jolestar/go-commons-pool | factory.go | ValidateObject | func (f *DefaultPooledObjectFactory) ValidateObject(ctx context.Context, object *PooledObject) bool {
if f.validate != nil {
return f.validate(ctx, object)
}
return true
} | go | func (f *DefaultPooledObjectFactory) ValidateObject(ctx context.Context, object *PooledObject) bool {
if f.validate != nil {
return f.validate(ctx, object)
}
return true
} | [
"func",
"(",
"f",
"*",
"DefaultPooledObjectFactory",
")",
"ValidateObject",
"(",
"ctx",
"context",
".",
"Context",
",",
"object",
"*",
"PooledObject",
")",
"bool",
"{",
"if",
"f",
".",
"validate",
"!=",
"nil",
"{",
"return",
"f",
".",
"validate",
"(",
"c... | // ValidateObject see PooledObjectFactory.ValidateObject | [
"ValidateObject",
"see",
"PooledObjectFactory",
".",
"ValidateObject"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L103-L108 | train |
jolestar/go-commons-pool | factory.go | ActivateObject | func (f *DefaultPooledObjectFactory) ActivateObject(ctx context.Context, object *PooledObject) error {
if f.activate != nil {
return f.activate(ctx, object)
}
return nil
} | go | func (f *DefaultPooledObjectFactory) ActivateObject(ctx context.Context, object *PooledObject) error {
if f.activate != nil {
return f.activate(ctx, object)
}
return nil
} | [
"func",
"(",
"f",
"*",
"DefaultPooledObjectFactory",
")",
"ActivateObject",
"(",
"ctx",
"context",
".",
"Context",
",",
"object",
"*",
"PooledObject",
")",
"error",
"{",
"if",
"f",
".",
"activate",
"!=",
"nil",
"{",
"return",
"f",
".",
"activate",
"(",
"... | // ActivateObject see PooledObjectFactory.ActivateObject | [
"ActivateObject",
"see",
"PooledObjectFactory",
".",
"ActivateObject"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L111-L116 | train |
jolestar/go-commons-pool | factory.go | PassivateObject | func (f *DefaultPooledObjectFactory) PassivateObject(ctx context.Context, object *PooledObject) error {
if f.passivate != nil {
return f.passivate(ctx, object)
}
return nil
} | go | func (f *DefaultPooledObjectFactory) PassivateObject(ctx context.Context, object *PooledObject) error {
if f.passivate != nil {
return f.passivate(ctx, object)
}
return nil
} | [
"func",
"(",
"f",
"*",
"DefaultPooledObjectFactory",
")",
"PassivateObject",
"(",
"ctx",
"context",
".",
"Context",
",",
"object",
"*",
"PooledObject",
")",
"error",
"{",
"if",
"f",
".",
"passivate",
"!=",
"nil",
"{",
"return",
"f",
".",
"passivate",
"(",
... | // PassivateObject see PooledObjectFactory.PassivateObject | [
"PassivateObject",
"see",
"PooledObjectFactory",
".",
"PassivateObject"
] | 5cc5d37d092a27de00a69e4501f50bb4ead1b304 | https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L119-L124 | train |
dgraph-io/dgo | x/error.go | Check | func Check(err error) {
if err != nil {
log.Fatalf("%+v", errors.WithStack(err))
}
} | go | func Check(err error) {
if err != nil {
log.Fatalf("%+v", errors.WithStack(err))
}
} | [
"func",
"Check",
"(",
"err",
"error",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"%+v\"",
",",
"errors",
".",
"WithStack",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Check logs fatal if err != nil. | [
"Check",
"logs",
"fatal",
"if",
"err",
"!",
"=",
"nil",
"."
] | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/x/error.go#L26-L30 | train |
dgraph-io/dgo | x/error.go | Checkf | func Checkf(err error, format string, args ...interface{}) {
if err != nil {
log.Fatalf("%+v", errors.Wrapf(err, format, args...))
}
} | go | func Checkf(err error, format string, args ...interface{}) {
if err != nil {
log.Fatalf("%+v", errors.Wrapf(err, format, args...))
}
} | [
"func",
"Checkf",
"(",
"err",
"error",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"%+v\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"format",
",",
... | // Checkf is Check with extra info. | [
"Checkf",
"is",
"Check",
"with",
"extra",
"info",
"."
] | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/x/error.go#L33-L37 | train |
dgraph-io/dgo | txn.go | BestEffort | func (txn *Txn) BestEffort() *Txn {
if !txn.readOnly {
panic("Best effort only works for read-only queries.")
}
txn.bestEffort = true
return txn
} | go | func (txn *Txn) BestEffort() *Txn {
if !txn.readOnly {
panic("Best effort only works for read-only queries.")
}
txn.bestEffort = true
return txn
} | [
"func",
"(",
"txn",
"*",
"Txn",
")",
"BestEffort",
"(",
")",
"*",
"Txn",
"{",
"if",
"!",
"txn",
".",
"readOnly",
"{",
"panic",
"(",
"\"Best effort only works for read-only queries.\"",
")",
"\n",
"}",
"\n",
"txn",
".",
"bestEffort",
"=",
"true",
"\n",
"r... | // BestEffort enables best effort in read-only queries. Using this flag will ask the
// Dgraph Alpha to try to get timestamps from memory in a best effort to reduce the number of
// outbound requests to Zero. This may yield improved latencies in read-bound datasets.
//
// This method will panic if the transaction is not read-only.
// Returns the transaction itself. | [
"BestEffort",
"enables",
"best",
"effort",
"in",
"read",
"-",
"only",
"queries",
".",
"Using",
"this",
"flag",
"will",
"ask",
"the",
"Dgraph",
"Alpha",
"to",
"try",
"to",
"get",
"timestamps",
"from",
"memory",
"in",
"a",
"best",
"effort",
"to",
"reduce",
... | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L68-L74 | train |
dgraph-io/dgo | txn.go | NewTxn | func (d *Dgraph) NewTxn() *Txn {
return &Txn{
dg: d,
dc: d.anyClient(),
context: &api.TxnContext{},
}
} | go | func (d *Dgraph) NewTxn() *Txn {
return &Txn{
dg: d,
dc: d.anyClient(),
context: &api.TxnContext{},
}
} | [
"func",
"(",
"d",
"*",
"Dgraph",
")",
"NewTxn",
"(",
")",
"*",
"Txn",
"{",
"return",
"&",
"Txn",
"{",
"dg",
":",
"d",
",",
"dc",
":",
"d",
".",
"anyClient",
"(",
")",
",",
"context",
":",
"&",
"api",
".",
"TxnContext",
"{",
"}",
",",
"}",
"... | // NewTxn creates a new transaction. | [
"NewTxn",
"creates",
"a",
"new",
"transaction",
"."
] | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L77-L83 | train |
dgraph-io/dgo | txn.go | QueryWithVars | func (txn *Txn) QueryWithVars(ctx context.Context, q string,
vars map[string]string) (*api.Response, error) {
if txn.finished {
return nil, ErrFinished
}
req := &api.Request{
Query: q,
Vars: vars,
StartTs: txn.context.StartTs,
ReadOnly: txn.readOnly,
BestEffort: txn.bestEffort,
}
ctx = txn.dg.getContext(ctx)
resp, err := txn.dc.Query(ctx, req)
if isJwtExpired(err) {
err = txn.dg.retryLogin(ctx)
if err != nil {
return nil, err
}
ctx = txn.dg.getContext(ctx)
resp, err = txn.dc.Query(ctx, req)
}
if err == nil {
if err := txn.mergeContext(resp.GetTxn()); err != nil {
return nil, err
}
}
return resp, err
} | go | func (txn *Txn) QueryWithVars(ctx context.Context, q string,
vars map[string]string) (*api.Response, error) {
if txn.finished {
return nil, ErrFinished
}
req := &api.Request{
Query: q,
Vars: vars,
StartTs: txn.context.StartTs,
ReadOnly: txn.readOnly,
BestEffort: txn.bestEffort,
}
ctx = txn.dg.getContext(ctx)
resp, err := txn.dc.Query(ctx, req)
if isJwtExpired(err) {
err = txn.dg.retryLogin(ctx)
if err != nil {
return nil, err
}
ctx = txn.dg.getContext(ctx)
resp, err = txn.dc.Query(ctx, req)
}
if err == nil {
if err := txn.mergeContext(resp.GetTxn()); err != nil {
return nil, err
}
}
return resp, err
} | [
"func",
"(",
"txn",
"*",
"Txn",
")",
"QueryWithVars",
"(",
"ctx",
"context",
".",
"Context",
",",
"q",
"string",
",",
"vars",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"api",
".",
"Response",
",",
"error",
")",
"{",
"if",
"txn",
".",
"f... | // QueryWithVars is like Query, but allows a variable map to be used. This can
// provide safety against injection attacks. | [
"QueryWithVars",
"is",
"like",
"Query",
"but",
"allows",
"a",
"variable",
"map",
"to",
"be",
"used",
".",
"This",
"can",
"provide",
"safety",
"against",
"injection",
"attacks",
"."
] | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L100-L129 | train |
dgraph-io/dgo | txn.go | Mutate | func (txn *Txn) Mutate(ctx context.Context, mu *api.Mutation) (*api.Assigned, error) {
switch {
case txn.readOnly:
return nil, ErrReadOnly
case txn.finished:
return nil, ErrFinished
}
txn.mutated = true
mu.StartTs = txn.context.StartTs
ctx = txn.dg.getContext(ctx)
ag, err := txn.dc.Mutate(ctx, mu)
if isJwtExpired(err) {
err = txn.dg.retryLogin(ctx)
if err != nil {
return nil, err
}
ctx = txn.dg.getContext(ctx)
ag, err = txn.dc.Mutate(ctx, mu)
}
if err != nil {
_ = txn.Discard(ctx) // Ignore error - user should see the original error.
return nil, err
}
if mu.CommitNow {
txn.finished = true
}
err = txn.mergeContext(ag.Context)
return ag, err
} | go | func (txn *Txn) Mutate(ctx context.Context, mu *api.Mutation) (*api.Assigned, error) {
switch {
case txn.readOnly:
return nil, ErrReadOnly
case txn.finished:
return nil, ErrFinished
}
txn.mutated = true
mu.StartTs = txn.context.StartTs
ctx = txn.dg.getContext(ctx)
ag, err := txn.dc.Mutate(ctx, mu)
if isJwtExpired(err) {
err = txn.dg.retryLogin(ctx)
if err != nil {
return nil, err
}
ctx = txn.dg.getContext(ctx)
ag, err = txn.dc.Mutate(ctx, mu)
}
if err != nil {
_ = txn.Discard(ctx) // Ignore error - user should see the original error.
return nil, err
}
if mu.CommitNow {
txn.finished = true
}
err = txn.mergeContext(ag.Context)
return ag, err
} | [
"func",
"(",
"txn",
"*",
"Txn",
")",
"Mutate",
"(",
"ctx",
"context",
".",
"Context",
",",
"mu",
"*",
"api",
".",
"Mutation",
")",
"(",
"*",
"api",
".",
"Assigned",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"txn",
".",
"readOnly",
":",
"retu... | // Mutate allows data stored on dgraph instances to be modified. The fields in
// api.Mutation come in pairs, set and delete. Mutations can either be
// encoded as JSON or as RDFs.
//
// If CommitNow is set, then this call will result in the transaction
// being committed. In this case, an explicit call to Commit doesn't need to
// subsequently be made.
//
// If the mutation fails, then the transaction is discarded and all future
// operations on it will fail. | [
"Mutate",
"allows",
"data",
"stored",
"on",
"dgraph",
"instances",
"to",
"be",
"modified",
".",
"The",
"fields",
"in",
"api",
".",
"Mutation",
"come",
"in",
"pairs",
"set",
"and",
"delete",
".",
"Mutations",
"can",
"either",
"be",
"encoded",
"as",
"JSON",
... | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L157-L188 | train |
dgraph-io/dgo | txn.go | Commit | func (txn *Txn) Commit(ctx context.Context) error {
switch {
case txn.readOnly:
return ErrReadOnly
case txn.finished:
return ErrFinished
}
err := txn.commitOrAbort(ctx)
if s, ok := status.FromError(err); ok && s.Code() == codes.Aborted {
err = y.ErrAborted
}
return err
} | go | func (txn *Txn) Commit(ctx context.Context) error {
switch {
case txn.readOnly:
return ErrReadOnly
case txn.finished:
return ErrFinished
}
err := txn.commitOrAbort(ctx)
if s, ok := status.FromError(err); ok && s.Code() == codes.Aborted {
err = y.ErrAborted
}
return err
} | [
"func",
"(",
"txn",
"*",
"Txn",
")",
"Commit",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"switch",
"{",
"case",
"txn",
".",
"readOnly",
":",
"return",
"ErrReadOnly",
"\n",
"case",
"txn",
".",
"finished",
":",
"return",
"ErrFinished",
"\... | // Commit commits any mutations that have been made in the transaction. Once
// Commit has been called, the lifespan of the transaction is complete.
//
// Errors could be returned for various reasons. Notably, ErrAborted could be
// returned if transactions that modify the same data are being run
// concurrently. It's up to the user to decide if they wish to retry. In this
// case, the user should create a new transaction. | [
"Commit",
"commits",
"any",
"mutations",
"that",
"have",
"been",
"made",
"in",
"the",
"transaction",
".",
"Once",
"Commit",
"has",
"been",
"called",
"the",
"lifespan",
"of",
"the",
"transaction",
"is",
"complete",
".",
"Errors",
"could",
"be",
"returned",
"f... | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L197-L210 | train |
dgraph-io/dgo | client.go | isJwtExpired | func isJwtExpired(err error) bool {
if err == nil {
return false
}
st, ok := status.FromError(err)
return ok && st.Code() == codes.Unauthenticated &&
strings.Contains(err.Error(), "Token is expired")
} | go | func isJwtExpired(err error) bool {
if err == nil {
return false
}
st, ok := status.FromError(err)
return ok && st.Code() == codes.Unauthenticated &&
strings.Contains(err.Error(), "Token is expired")
} | [
"func",
"isJwtExpired",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"st",
",",
"ok",
":=",
"status",
".",
"FromError",
"(",
"err",
")",
"\n",
"return",
"ok",
"&&",
"st",
".",
"Code",
"... | // isJwtExpired returns true if the error indicates that the jwt has expired | [
"isJwtExpired",
"returns",
"true",
"if",
"the",
"error",
"indicates",
"that",
"the",
"jwt",
"has",
"expired"
] | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/client.go#L132-L140 | train |
dgraph-io/dgo | client.go | DeleteEdges | func DeleteEdges(mu *api.Mutation, uid string, predicates ...string) {
for _, predicate := range predicates {
mu.Del = append(mu.Del, &api.NQuad{
Subject: uid,
Predicate: predicate,
// _STAR_ALL is defined as x.Star in x package.
ObjectValue: &api.Value{Val: &api.Value_DefaultVal{"_STAR_ALL"}},
})
}
} | go | func DeleteEdges(mu *api.Mutation, uid string, predicates ...string) {
for _, predicate := range predicates {
mu.Del = append(mu.Del, &api.NQuad{
Subject: uid,
Predicate: predicate,
// _STAR_ALL is defined as x.Star in x package.
ObjectValue: &api.Value{Val: &api.Value_DefaultVal{"_STAR_ALL"}},
})
}
} | [
"func",
"DeleteEdges",
"(",
"mu",
"*",
"api",
".",
"Mutation",
",",
"uid",
"string",
",",
"predicates",
"...",
"string",
")",
"{",
"for",
"_",
",",
"predicate",
":=",
"range",
"predicates",
"{",
"mu",
".",
"Del",
"=",
"append",
"(",
"mu",
".",
"Del",... | // DeleteEdges sets the edges corresponding to predicates on the node with the given uid
// for deletion.
// This helper function doesn't run the mutation on the server. It must be done by the user
// after the function returns. | [
"DeleteEdges",
"sets",
"the",
"edges",
"corresponding",
"to",
"predicates",
"on",
"the",
"node",
"with",
"the",
"given",
"uid",
"for",
"deletion",
".",
"This",
"helper",
"function",
"doesn",
"t",
"run",
"the",
"mutation",
"on",
"the",
"server",
".",
"It",
... | 7517ac021e22457b8b14c151a3476aa8c1e22a64 | https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/client.go#L150-L159 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | Analyze | func (a RPMAnalyzer) Analyze(image pkgutil.Image) (util.Result, error) {
analysis, err := singleVersionAnalysis(image, a)
return analysis, err
} | go | func (a RPMAnalyzer) Analyze(image pkgutil.Image) (util.Result, error) {
analysis, err := singleVersionAnalysis(image, a)
return analysis, err
} | [
"func",
"(",
"a",
"RPMAnalyzer",
")",
"Analyze",
"(",
"image",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"analysis",
",",
"err",
":=",
"singleVersionAnalysis",
"(",
"image",
",",
"a",
")",
"\n",
"return",
"analys... | // Analyze collects information of the installed rpm packages on image. | [
"Analyze",
"collects",
"information",
"of",
"the",
"installed",
"rpm",
"packages",
"on",
"image",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L79-L82 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | getPackages | func (a RPMAnalyzer) getPackages(image pkgutil.Image) (map[string]util.PackageInfo, error) {
path := image.FSPath
packages := make(map[string]util.PackageInfo)
if _, err := os.Stat(path); err != nil {
// invalid image directory path
return packages, err
}
// try to find the rpm binary in bin/ or usr/bin/
rpmBinary := filepath.Join(path, "bin/rpm")
if _, err := os.Stat(rpmBinary); err != nil {
rpmBinary = filepath.Join(path, "usr/bin/rpm")
if _, err = os.Stat(rpmBinary); err != nil {
logrus.Errorf("Could not detect RPM binary in unpacked image %s", image.Source)
return packages, nil
}
}
packages, err := rpmDataFromImageFS(image)
if err != nil {
logrus.Info("Couldn't retrieve RPM data from extracted filesystem; running query in container")
return rpmDataFromContainer(image.Image)
}
return packages, err
} | go | func (a RPMAnalyzer) getPackages(image pkgutil.Image) (map[string]util.PackageInfo, error) {
path := image.FSPath
packages := make(map[string]util.PackageInfo)
if _, err := os.Stat(path); err != nil {
// invalid image directory path
return packages, err
}
// try to find the rpm binary in bin/ or usr/bin/
rpmBinary := filepath.Join(path, "bin/rpm")
if _, err := os.Stat(rpmBinary); err != nil {
rpmBinary = filepath.Join(path, "usr/bin/rpm")
if _, err = os.Stat(rpmBinary); err != nil {
logrus.Errorf("Could not detect RPM binary in unpacked image %s", image.Source)
return packages, nil
}
}
packages, err := rpmDataFromImageFS(image)
if err != nil {
logrus.Info("Couldn't retrieve RPM data from extracted filesystem; running query in container")
return rpmDataFromContainer(image.Image)
}
return packages, err
} | [
"func",
"(",
"a",
"RPMAnalyzer",
")",
"getPackages",
"(",
"image",
"pkgutil",
".",
"Image",
")",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"path",
":=",
"image",
".",
"FSPath",
"\n",
"packages",
":=",
"make",
... | // getPackages returns a map of installed rpm package on image. | [
"getPackages",
"returns",
"a",
"map",
"of",
"installed",
"rpm",
"package",
"on",
"image",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L85-L109 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | rpmDataFromImageFS | func rpmDataFromImageFS(image pkgutil.Image) (map[string]util.PackageInfo, error) {
dbPath, err := rpmEnvCheck(image.FSPath)
if err != nil {
logrus.Warnf("Couldn't find RPM database: %s", err.Error())
return nil, err
}
return rpmDataFromFS(image.FSPath, dbPath)
} | go | func rpmDataFromImageFS(image pkgutil.Image) (map[string]util.PackageInfo, error) {
dbPath, err := rpmEnvCheck(image.FSPath)
if err != nil {
logrus.Warnf("Couldn't find RPM database: %s", err.Error())
return nil, err
}
return rpmDataFromFS(image.FSPath, dbPath)
} | [
"func",
"rpmDataFromImageFS",
"(",
"image",
"pkgutil",
".",
"Image",
")",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"dbPath",
",",
"err",
":=",
"rpmEnvCheck",
"(",
"image",
".",
"FSPath",
")",
"\n",
"if",
"err"... | // rpmDataFromImageFS runs a local rpm binary, if any, to query the image
// rpmdb and returns a map of installed packages. | [
"rpmDataFromImageFS",
"runs",
"a",
"local",
"rpm",
"binary",
"if",
"any",
"to",
"query",
"the",
"image",
"rpmdb",
"and",
"returns",
"a",
"map",
"of",
"installed",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L113-L120 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | rpmDataFromContainer | func rpmDataFromContainer(image v1.Image) (map[string]util.PackageInfo, error) {
packages := make(map[string]util.PackageInfo)
client, err := godocker.NewClientFromEnv()
if err != nil {
return packages, err
}
if err := lock(); err != nil {
return packages, err
}
imageName, err := loadImageToDaemon(image)
if err != nil {
return packages, fmt.Errorf("Error loading image: %s", err)
}
unlock()
defer client.RemoveImage(imageName)
defer logrus.Infof("Removing image %s", imageName)
contConf := godocker.Config{
Entrypoint: rpmCmd,
Image: imageName,
}
hostConf := godocker.HostConfig{
AutoRemove: true,
}
contOpts := godocker.CreateContainerOptions{Config: &contConf}
container, err := client.CreateContainer(contOpts)
if err != nil {
return packages, err
}
logrus.Infof("Created container %s", container.ID)
removeOpts := godocker.RemoveContainerOptions{
ID: container.ID,
}
defer client.RemoveContainer(removeOpts)
if err := client.StartContainer(container.ID, &hostConf); err != nil {
return packages, err
}
exitCode, err := client.WaitContainer(container.ID)
if err != nil {
return packages, err
}
outBuf := new(bytes.Buffer)
errBuf := new(bytes.Buffer)
logOpts := godocker.LogsOptions{
Context: context.Background(),
Container: container.ID,
Stdout: true,
Stderr: true,
OutputStream: outBuf,
ErrorStream: errBuf,
}
if err := client.Logs(logOpts); err != nil {
return packages, err
}
if exitCode != 0 {
return packages, fmt.Errorf("non-zero exit code %d: %s", exitCode, errBuf.String())
}
output := strings.Split(outBuf.String(), "\n")
return parsePackageData(output)
} | go | func rpmDataFromContainer(image v1.Image) (map[string]util.PackageInfo, error) {
packages := make(map[string]util.PackageInfo)
client, err := godocker.NewClientFromEnv()
if err != nil {
return packages, err
}
if err := lock(); err != nil {
return packages, err
}
imageName, err := loadImageToDaemon(image)
if err != nil {
return packages, fmt.Errorf("Error loading image: %s", err)
}
unlock()
defer client.RemoveImage(imageName)
defer logrus.Infof("Removing image %s", imageName)
contConf := godocker.Config{
Entrypoint: rpmCmd,
Image: imageName,
}
hostConf := godocker.HostConfig{
AutoRemove: true,
}
contOpts := godocker.CreateContainerOptions{Config: &contConf}
container, err := client.CreateContainer(contOpts)
if err != nil {
return packages, err
}
logrus.Infof("Created container %s", container.ID)
removeOpts := godocker.RemoveContainerOptions{
ID: container.ID,
}
defer client.RemoveContainer(removeOpts)
if err := client.StartContainer(container.ID, &hostConf); err != nil {
return packages, err
}
exitCode, err := client.WaitContainer(container.ID)
if err != nil {
return packages, err
}
outBuf := new(bytes.Buffer)
errBuf := new(bytes.Buffer)
logOpts := godocker.LogsOptions{
Context: context.Background(),
Container: container.ID,
Stdout: true,
Stderr: true,
OutputStream: outBuf,
ErrorStream: errBuf,
}
if err := client.Logs(logOpts); err != nil {
return packages, err
}
if exitCode != 0 {
return packages, fmt.Errorf("non-zero exit code %d: %s", exitCode, errBuf.String())
}
output := strings.Split(outBuf.String(), "\n")
return parsePackageData(output)
} | [
"func",
"rpmDataFromContainer",
"(",
"image",
"v1",
".",
"Image",
")",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"packages",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
")",
"\n",
... | // rpmDataFromContainer runs image in a container, queries the data of
// installed rpm packages and returns a map of packages. | [
"rpmDataFromContainer",
"runs",
"image",
"in",
"a",
"container",
"queries",
"the",
"data",
"of",
"installed",
"rpm",
"packages",
"and",
"returns",
"a",
"map",
"of",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L161-L233 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | parsePackageData | func parsePackageData(rpmOutput []string) (map[string]util.PackageInfo, error) {
packages := make(map[string]util.PackageInfo)
for _, output := range rpmOutput {
spl := strings.Split(output, "\t")
if len(spl) != 3 {
// ignore the empty (last) line
if output != "" {
logrus.Errorf("unexpected rpm-query output: '%s'", output)
}
continue
}
pkg := util.PackageInfo{}
var err error
pkg.Size, err = strconv.ParseInt(spl[2], 10, 64)
if err != nil {
return packages, fmt.Errorf("error converting package size: %s", spl[2])
}
pkg.Version = spl[1]
packages[spl[0]] = pkg
}
return packages, nil
} | go | func parsePackageData(rpmOutput []string) (map[string]util.PackageInfo, error) {
packages := make(map[string]util.PackageInfo)
for _, output := range rpmOutput {
spl := strings.Split(output, "\t")
if len(spl) != 3 {
// ignore the empty (last) line
if output != "" {
logrus.Errorf("unexpected rpm-query output: '%s'", output)
}
continue
}
pkg := util.PackageInfo{}
var err error
pkg.Size, err = strconv.ParseInt(spl[2], 10, 64)
if err != nil {
return packages, fmt.Errorf("error converting package size: %s", spl[2])
}
pkg.Version = spl[1]
packages[spl[0]] = pkg
}
return packages, nil
} | [
"func",
"parsePackageData",
"(",
"rpmOutput",
"[",
"]",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"packages",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
")",
"\n",
... | // parsePackageData parses the package data of each line in rpmOutput and
// returns a map of packages. | [
"parsePackageData",
"parses",
"the",
"package",
"data",
"of",
"each",
"line",
"in",
"rpmOutput",
"and",
"returns",
"a",
"map",
"of",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L237-L262 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | loadImageToDaemon | func loadImageToDaemon(img v1.Image) (string, error) {
tag := generateValidImageTag()
resp, err := daemon.Write(tag, img)
if err != nil {
return "", err
}
logrus.Infof("daemon response: %s", resp)
return tag.Name(), nil
} | go | func loadImageToDaemon(img v1.Image) (string, error) {
tag := generateValidImageTag()
resp, err := daemon.Write(tag, img)
if err != nil {
return "", err
}
logrus.Infof("daemon response: %s", resp)
return tag.Name(), nil
} | [
"func",
"loadImageToDaemon",
"(",
"img",
"v1",
".",
"Image",
")",
"(",
"string",
",",
"error",
")",
"{",
"tag",
":=",
"generateValidImageTag",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"daemon",
".",
"Write",
"(",
"tag",
",",
"img",
")",
"\n",
"if",
... | // loadImageToDaemon loads the image specified to the docker daemon. | [
"loadImageToDaemon",
"loads",
"the",
"image",
"specified",
"to",
"the",
"docker",
"daemon",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L265-L273 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | generateValidImageTag | func generateValidImageTag() name.Tag {
var tag name.Tag
var err error
var i int
b := make([]rune, 12)
for {
for i = 0; i < len(b); i++ {
b[i] = letters[rand.Intn(len(letters))]
}
tag, err = name.NewTag("rpm_test_image:"+string(b), name.WeakValidation)
if err != nil {
logrus.Warn(err.Error())
continue
}
img, _ := daemon.Image(tag)
if img == nil {
break
}
}
return tag
} | go | func generateValidImageTag() name.Tag {
var tag name.Tag
var err error
var i int
b := make([]rune, 12)
for {
for i = 0; i < len(b); i++ {
b[i] = letters[rand.Intn(len(letters))]
}
tag, err = name.NewTag("rpm_test_image:"+string(b), name.WeakValidation)
if err != nil {
logrus.Warn(err.Error())
continue
}
img, _ := daemon.Image(tag)
if img == nil {
break
}
}
return tag
} | [
"func",
"generateValidImageTag",
"(",
")",
"name",
".",
"Tag",
"{",
"var",
"tag",
"name",
".",
"Tag",
"\n",
"var",
"err",
"error",
"\n",
"var",
"i",
"int",
"\n",
"b",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"12",
")",
"\n",
"for",
"{",
"for",
... | // generate random image name until we find one that isn't in use | [
"generate",
"random",
"image",
"name",
"until",
"we",
"find",
"one",
"that",
"isn",
"t",
"in",
"use"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L276-L296 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | getLockfile | func getLockfile() (lockfile.Lockfile, error) {
lockPath := filepath.Join(os.TempDir(), ".containerdiff.lock")
lock, err := lockfile.New(lockPath)
if err != nil {
return lock, err
}
return lock, nil
} | go | func getLockfile() (lockfile.Lockfile, error) {
lockPath := filepath.Join(os.TempDir(), ".containerdiff.lock")
lock, err := lockfile.New(lockPath)
if err != nil {
return lock, err
}
return lock, nil
} | [
"func",
"getLockfile",
"(",
")",
"(",
"lockfile",
".",
"Lockfile",
",",
"error",
")",
"{",
"lockPath",
":=",
"filepath",
".",
"Join",
"(",
"os",
".",
"TempDir",
"(",
")",
",",
"\".containerdiff.lock\"",
")",
"\n",
"lock",
",",
"err",
":=",
"lockfile",
... | // unlock returns the containerdiff file-system lock. It is placed in the
// system's temporary directory to make sure it's accessible for all users in
// the system; no root required. | [
"unlock",
"returns",
"the",
"containerdiff",
"file",
"-",
"system",
"lock",
".",
"It",
"is",
"placed",
"in",
"the",
"system",
"s",
"temporary",
"directory",
"to",
"make",
"sure",
"it",
"s",
"accessible",
"for",
"all",
"users",
"in",
"the",
"system",
";",
... | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L301-L308 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | lock | func lock() error {
var err error
var lock lockfile.Lockfile
daemonMutex.Lock()
lock, err = getLockfile()
if err != nil {
daemonMutex.Unlock()
return fmt.Errorf("[lock] cannot init lockfile: %v", err)
}
// Try to acquire the lock and in case of a temporary error, sleep for
// two seconds until the next retry (at most 10 times). Return fatal
// errors immediately, as we can't recover.
for i := 0; i < 10; i++ {
if err = lock.TryLock(); err != nil {
switch err.(type) {
case lockfile.TemporaryError:
logrus.Debugf("[lock] busy: next retry in two seconds")
time.Sleep(2 * time.Second)
default:
daemonMutex.Unlock()
return fmt.Errorf("[lock] error acquiring lock: %s", err)
}
}
}
if err != nil {
daemonMutex.Unlock()
return fmt.Errorf("[lock] error acquiring lock: too many tries")
}
logrus.Debugf("[lock] lock acquired")
return nil
} | go | func lock() error {
var err error
var lock lockfile.Lockfile
daemonMutex.Lock()
lock, err = getLockfile()
if err != nil {
daemonMutex.Unlock()
return fmt.Errorf("[lock] cannot init lockfile: %v", err)
}
// Try to acquire the lock and in case of a temporary error, sleep for
// two seconds until the next retry (at most 10 times). Return fatal
// errors immediately, as we can't recover.
for i := 0; i < 10; i++ {
if err = lock.TryLock(); err != nil {
switch err.(type) {
case lockfile.TemporaryError:
logrus.Debugf("[lock] busy: next retry in two seconds")
time.Sleep(2 * time.Second)
default:
daemonMutex.Unlock()
return fmt.Errorf("[lock] error acquiring lock: %s", err)
}
}
}
if err != nil {
daemonMutex.Unlock()
return fmt.Errorf("[lock] error acquiring lock: too many tries")
}
logrus.Debugf("[lock] lock acquired")
return nil
} | [
"func",
"lock",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"var",
"lock",
"lockfile",
".",
"Lockfile",
"\n",
"daemonMutex",
".",
"Lock",
"(",
")",
"\n",
"lock",
",",
"err",
"=",
"getLockfile",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{"... | // lock acquires the containerdiff file-system lock. | [
"lock",
"acquires",
"the",
"containerdiff",
"file",
"-",
"system",
"lock",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L311-L344 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | unlock | func unlock() error {
lock, err := getLockfile()
if err != nil {
return fmt.Errorf("[unlock] cannot init lockfile: %v", err)
}
err = lock.Unlock()
if err != nil {
return fmt.Errorf("[unlock] error releasing lock: %s", err)
}
logrus.Debugf("[unlock] lock released")
daemonMutex.Unlock()
return nil
} | go | func unlock() error {
lock, err := getLockfile()
if err != nil {
return fmt.Errorf("[unlock] cannot init lockfile: %v", err)
}
err = lock.Unlock()
if err != nil {
return fmt.Errorf("[unlock] error releasing lock: %s", err)
}
logrus.Debugf("[unlock] lock released")
daemonMutex.Unlock()
return nil
} | [
"func",
"unlock",
"(",
")",
"error",
"{",
"lock",
",",
"err",
":=",
"getLockfile",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"[unlock] cannot init lockfile: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"="... | // unlock releases the containerdiff file-system lock. Note that errors can be
// ignored as there's no meaningful way to recover. | [
"unlock",
"releases",
"the",
"containerdiff",
"file",
"-",
"system",
"lock",
".",
"Note",
"that",
"errors",
"can",
"be",
"ignored",
"as",
"there",
"s",
"no",
"meaningful",
"way",
"to",
"recover",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L348-L360 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | getPackages | func (a RPMLayerAnalyzer) getPackages(image pkgutil.Image) ([]map[string]util.PackageInfo, error) {
path := image.FSPath
var packages []map[string]util.PackageInfo
if _, err := os.Stat(path); err != nil {
// invalid image directory path
return packages, err
}
// try to find the rpm binary in bin/ or usr/bin/
rpmBinary := filepath.Join(path, "bin/rpm")
if _, err := os.Stat(rpmBinary); err != nil {
rpmBinary = filepath.Join(path, "usr/bin/rpm")
if _, err = os.Stat(rpmBinary); err != nil {
logrus.Errorf("Could not detect RPM binary in unpacked image %s", image.Source)
return packages, nil
}
}
packages, err := rpmDataFromLayerFS(image)
if err != nil {
logrus.Info("Couldn't retrieve RPM data from extracted filesystem; running query in container")
return rpmDataFromLayeredContainers(image.Image)
}
return packages, err
} | go | func (a RPMLayerAnalyzer) getPackages(image pkgutil.Image) ([]map[string]util.PackageInfo, error) {
path := image.FSPath
var packages []map[string]util.PackageInfo
if _, err := os.Stat(path); err != nil {
// invalid image directory path
return packages, err
}
// try to find the rpm binary in bin/ or usr/bin/
rpmBinary := filepath.Join(path, "bin/rpm")
if _, err := os.Stat(rpmBinary); err != nil {
rpmBinary = filepath.Join(path, "usr/bin/rpm")
if _, err = os.Stat(rpmBinary); err != nil {
logrus.Errorf("Could not detect RPM binary in unpacked image %s", image.Source)
return packages, nil
}
}
packages, err := rpmDataFromLayerFS(image)
if err != nil {
logrus.Info("Couldn't retrieve RPM data from extracted filesystem; running query in container")
return rpmDataFromLayeredContainers(image.Image)
}
return packages, err
} | [
"func",
"(",
"a",
"RPMLayerAnalyzer",
")",
"getPackages",
"(",
"image",
"pkgutil",
".",
"Image",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"path",
":=",
"image",
".",
"FSPath",
"\n",
"var",
"pa... | // getPackages returns an array of maps of installed rpm packages on each layer | [
"getPackages",
"returns",
"an",
"array",
"of",
"maps",
"of",
"installed",
"rpm",
"packages",
"on",
"each",
"layer"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L383-L407 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | rpmDataFromLayerFS | func rpmDataFromLayerFS(image pkgutil.Image) ([]map[string]util.PackageInfo, error) {
var packages []map[string]util.PackageInfo
dbPath, err := rpmEnvCheck(image.FSPath)
if err != nil {
logrus.Warnf("Couldn't find RPM database: %s", err.Error())
return packages, err
}
for _, layer := range image.Layers {
layerPackages, err := rpmDataFromFS(layer.FSPath, dbPath)
if err != nil {
return packages, err
}
packages = append(packages, layerPackages)
}
return packages, nil
} | go | func rpmDataFromLayerFS(image pkgutil.Image) ([]map[string]util.PackageInfo, error) {
var packages []map[string]util.PackageInfo
dbPath, err := rpmEnvCheck(image.FSPath)
if err != nil {
logrus.Warnf("Couldn't find RPM database: %s", err.Error())
return packages, err
}
for _, layer := range image.Layers {
layerPackages, err := rpmDataFromFS(layer.FSPath, dbPath)
if err != nil {
return packages, err
}
packages = append(packages, layerPackages)
}
return packages, nil
} | [
"func",
"rpmDataFromLayerFS",
"(",
"image",
"pkgutil",
".",
"Image",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"var",
"packages",
"[",
"]",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
... | // rpmDataFromLayerFS runs a local rpm binary, if any, to query the layer
// rpmdb and returns an array of maps of installed packages. | [
"rpmDataFromLayerFS",
"runs",
"a",
"local",
"rpm",
"binary",
"if",
"any",
"to",
"query",
"the",
"layer",
"rpmdb",
"and",
"returns",
"an",
"array",
"of",
"maps",
"of",
"installed",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L411-L427 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | rpmDataFromFS | func rpmDataFromFS(fsPath string, dbPath string) (map[string]util.PackageInfo, error) {
packages := make(map[string]util.PackageInfo)
if _, err := os.Stat(filepath.Join(fsPath, dbPath)); err == nil {
cmdArgs := append([]string{"--root", fsPath, "--dbpath", dbPath}, rpmCmd[1:]...)
out, err := exec.Command(rpmCmd[0], cmdArgs...).Output()
if err != nil {
logrus.Warnf("RPM call failed: %s", err.Error())
return packages, err
}
output := strings.Split(string(out), "\n")
packages, err = parsePackageData(output)
if err != nil {
return packages, err
}
}
return packages, nil
} | go | func rpmDataFromFS(fsPath string, dbPath string) (map[string]util.PackageInfo, error) {
packages := make(map[string]util.PackageInfo)
if _, err := os.Stat(filepath.Join(fsPath, dbPath)); err == nil {
cmdArgs := append([]string{"--root", fsPath, "--dbpath", dbPath}, rpmCmd[1:]...)
out, err := exec.Command(rpmCmd[0], cmdArgs...).Output()
if err != nil {
logrus.Warnf("RPM call failed: %s", err.Error())
return packages, err
}
output := strings.Split(string(out), "\n")
packages, err = parsePackageData(output)
if err != nil {
return packages, err
}
}
return packages, nil
} | [
"func",
"rpmDataFromFS",
"(",
"fsPath",
"string",
",",
"dbPath",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"packages",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
")... | // rpmDataFromFS runs a local rpm binary to query the image
// rpmdb and returns a map of installed packages. | [
"rpmDataFromFS",
"runs",
"a",
"local",
"rpm",
"binary",
"to",
"query",
"the",
"image",
"rpmdb",
"and",
"returns",
"a",
"map",
"of",
"installed",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L431-L447 | train |
GoogleContainerTools/container-diff | differs/rpm_diff.go | rpmDataFromLayeredContainers | func rpmDataFromLayeredContainers(image v1.Image) ([]map[string]util.PackageInfo, error) {
var packages []map[string]util.PackageInfo
tmpImage, err := random.Image(0, 0)
if err != nil {
return packages, err
}
layers, err := image.Layers()
if err != nil {
return packages, err
}
// Append layers one by one to an empty image and query rpm
// database on each iteration
for _, layer := range layers {
tmpImage, err = mutate.AppendLayers(tmpImage, layer)
if err != nil {
return packages, err
}
layerPackages, err := rpmDataFromContainer(tmpImage)
if err != nil {
return packages, err
}
packages = append(packages, layerPackages)
}
return packages, nil
} | go | func rpmDataFromLayeredContainers(image v1.Image) ([]map[string]util.PackageInfo, error) {
var packages []map[string]util.PackageInfo
tmpImage, err := random.Image(0, 0)
if err != nil {
return packages, err
}
layers, err := image.Layers()
if err != nil {
return packages, err
}
// Append layers one by one to an empty image and query rpm
// database on each iteration
for _, layer := range layers {
tmpImage, err = mutate.AppendLayers(tmpImage, layer)
if err != nil {
return packages, err
}
layerPackages, err := rpmDataFromContainer(tmpImage)
if err != nil {
return packages, err
}
packages = append(packages, layerPackages)
}
return packages, nil
} | [
"func",
"rpmDataFromLayeredContainers",
"(",
"image",
"v1",
".",
"Image",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
",",
"error",
")",
"{",
"var",
"packages",
"[",
"]",
"map",
"[",
"string",
"]",
"util",
".",
"PackageIn... | // rpmDataFromLayeredContainers runs a tmp image in a container for each layer,
// queries the data of installed rpm packages and returns an array of maps of
// packages. | [
"rpmDataFromLayeredContainers",
"runs",
"a",
"tmp",
"image",
"in",
"a",
"container",
"for",
"each",
"layer",
"queries",
"the",
"data",
"of",
"installed",
"rpm",
"packages",
"and",
"returns",
"an",
"array",
"of",
"maps",
"of",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/rpm_diff.go#L452-L477 | train |
GoogleContainerTools/container-diff | cmd/util/output/output.go | PrintToStdErr | func PrintToStdErr(output string, vars ...interface{}) {
if !quiet {
fmt.Fprintf(os.Stderr, output, vars...)
}
} | go | func PrintToStdErr(output string, vars ...interface{}) {
if !quiet {
fmt.Fprintf(os.Stderr, output, vars...)
}
} | [
"func",
"PrintToStdErr",
"(",
"output",
"string",
",",
"vars",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"!",
"quiet",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"output",
",",
"vars",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // PrintToStdErr prints to stderr if quiet flag isn't enabled | [
"PrintToStdErr",
"prints",
"to",
"stderr",
"if",
"quiet",
"flag",
"isn",
"t",
"enabled"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/cmd/util/output/output.go#L28-L32 | train |
GoogleContainerTools/container-diff | differs/pip_diff.go | Diff | func (a PipAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff, err := multiVersionDiff(image1, image2, a)
return diff, err
} | go | func (a PipAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff, err := multiVersionDiff(image1, image2, a)
return diff, err
} | [
"func",
"(",
"a",
"PipAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"diff",
",",
"err",
":=",
"multiVersionDiff",
"(",
"image1",
",",
"image2",
",",
"a",
")",
... | // PipDiff compares pip-installed Python packages between layers of two different images. | [
"PipDiff",
"compares",
"pip",
"-",
"installed",
"Python",
"packages",
"between",
"layers",
"of",
"two",
"different",
"images",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/pip_diff.go#L40-L43 | train |
GoogleContainerTools/container-diff | util/package_diff_utils.go | GetMapDiff | func GetMapDiff(map1, map2 map[string]PackageInfo) PackageDiff {
diff := diffMaps(map1, map2)
diffVal := reflect.ValueOf(diff)
packDiff := diffVal.Interface().(PackageDiff)
return packDiff
} | go | func GetMapDiff(map1, map2 map[string]PackageInfo) PackageDiff {
diff := diffMaps(map1, map2)
diffVal := reflect.ValueOf(diff)
packDiff := diffVal.Interface().(PackageDiff)
return packDiff
} | [
"func",
"GetMapDiff",
"(",
"map1",
",",
"map2",
"map",
"[",
"string",
"]",
"PackageInfo",
")",
"PackageDiff",
"{",
"diff",
":=",
"diffMaps",
"(",
"map1",
",",
"map2",
")",
"\n",
"diffVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"diff",
")",
"\n",
"packD... | // GetMapDiff determines the differences between maps of package names to PackageInfo structs
// This getter supports only single version packages. | [
"GetMapDiff",
"determines",
"the",
"differences",
"between",
"maps",
"of",
"package",
"names",
"to",
"PackageInfo",
"structs",
"This",
"getter",
"supports",
"only",
"single",
"version",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/package_diff_utils.go#L118-L123 | train |
GoogleContainerTools/container-diff | util/package_diff_utils.go | GetMultiVersionMapDiff | func GetMultiVersionMapDiff(map1, map2 map[string]map[string]PackageInfo) MultiVersionPackageDiff {
diff := diffMaps(map1, map2)
diffVal := reflect.ValueOf(diff)
packDiff := diffVal.Interface().(MultiVersionPackageDiff)
return packDiff
} | go | func GetMultiVersionMapDiff(map1, map2 map[string]map[string]PackageInfo) MultiVersionPackageDiff {
diff := diffMaps(map1, map2)
diffVal := reflect.ValueOf(diff)
packDiff := diffVal.Interface().(MultiVersionPackageDiff)
return packDiff
} | [
"func",
"GetMultiVersionMapDiff",
"(",
"map1",
",",
"map2",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"PackageInfo",
")",
"MultiVersionPackageDiff",
"{",
"diff",
":=",
"diffMaps",
"(",
"map1",
",",
"map2",
")",
"\n",
"diffVal",
":=",
"reflect",
... | // GetMultiVersionMapDiff determines the differences between two image package maps with multi-version packages
// This getter supports multi version packages. | [
"GetMultiVersionMapDiff",
"determines",
"the",
"differences",
"between",
"two",
"image",
"package",
"maps",
"with",
"multi",
"-",
"version",
"packages",
"This",
"getter",
"supports",
"multi",
"version",
"packages",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/package_diff_utils.go#L127-L132 | train |
GoogleContainerTools/container-diff | util/package_diff_utils.go | BuildLayerTargets | func BuildLayerTargets(path, target string) ([]string, error) {
layerStems := []string{}
layers, err := ioutil.ReadDir(path)
if err != nil {
return layerStems, err
}
for _, layer := range layers {
if layer.IsDir() {
layerStems = append(layerStems, filepath.Join(path, layer.Name(), target))
}
}
return layerStems, nil
} | go | func BuildLayerTargets(path, target string) ([]string, error) {
layerStems := []string{}
layers, err := ioutil.ReadDir(path)
if err != nil {
return layerStems, err
}
for _, layer := range layers {
if layer.IsDir() {
layerStems = append(layerStems, filepath.Join(path, layer.Name(), target))
}
}
return layerStems, nil
} | [
"func",
"BuildLayerTargets",
"(",
"path",
",",
"target",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"layerStems",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"layers",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"path",
")",
... | // BuildLayerTargets creates a string slice of the layers found at path with the target concatenated. | [
"BuildLayerTargets",
"creates",
"a",
"string",
"slice",
"of",
"the",
"layers",
"found",
"at",
"path",
"with",
"the",
"target",
"concatenated",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/package_diff_utils.go#L197-L209 | train |
GoogleContainerTools/container-diff | cmd/diff.go | processImage | func processImage(imageName string, errChan chan<- error) *pkgutil.Image {
image, err := getImage(imageName)
if err != nil {
errChan <- fmt.Errorf("error retrieving image %s: %s", imageName, err)
}
return &image
} | go | func processImage(imageName string, errChan chan<- error) *pkgutil.Image {
image, err := getImage(imageName)
if err != nil {
errChan <- fmt.Errorf("error retrieving image %s: %s", imageName, err)
}
return &image
} | [
"func",
"processImage",
"(",
"imageName",
"string",
",",
"errChan",
"chan",
"<-",
"error",
")",
"*",
"pkgutil",
".",
"Image",
"{",
"image",
",",
"err",
":=",
"getImage",
"(",
"imageName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errChan",
"<-",
"fmt"... | // processImage is a concurrency-friendly wrapper around getImageForName | [
"processImage",
"is",
"a",
"concurrency",
"-",
"friendly",
"wrapper",
"around",
"getImageForName"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/cmd/diff.go#L74-L80 | train |
GoogleContainerTools/container-diff | cmd/diff.go | readErrorsFromChannel | func readErrorsFromChannel(c chan error) error {
errs := []string{}
for {
err, ok := <-c
if !ok {
break
}
errs = append(errs, err.Error())
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
} | go | func readErrorsFromChannel(c chan error) error {
errs := []string{}
for {
err, ok := <-c
if !ok {
break
}
errs = append(errs, err.Error())
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
} | [
"func",
"readErrorsFromChannel",
"(",
"c",
"chan",
"error",
")",
"error",
"{",
"errs",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"{",
"err",
",",
"ok",
":=",
"<-",
"c",
"\n",
"if",
"!",
"ok",
"{",
"break",
"\n",
"}",
"\n",
"errs",
"=",
"... | // collects errors from a channel and combines them
// assumes channel has already been closed | [
"collects",
"errors",
"from",
"a",
"channel",
"and",
"combines",
"them",
"assumes",
"channel",
"has",
"already",
"been",
"closed"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/cmd/diff.go#L84-L98 | train |
GoogleContainerTools/container-diff | differs/size_diff.go | Diff | func (a SizeAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff := []util.SizeDiff{}
size1 := pkgutil.GetSize(image1.FSPath)
size2 := pkgutil.GetSize(image2.FSPath)
if size1 != size2 {
diff = append(diff, util.SizeDiff{
Size1: size1,
Size2: size2,
})
}
return &util.SizeDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "Size",
Diff: diff,
}, nil
} | go | func (a SizeAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff := []util.SizeDiff{}
size1 := pkgutil.GetSize(image1.FSPath)
size2 := pkgutil.GetSize(image2.FSPath)
if size1 != size2 {
diff = append(diff, util.SizeDiff{
Size1: size1,
Size2: size2,
})
}
return &util.SizeDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "Size",
Diff: diff,
}, nil
} | [
"func",
"(",
"a",
"SizeAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"diff",
":=",
"[",
"]",
"util",
".",
"SizeDiff",
"{",
"}",
"\n",
"size1",
":=",
"pkgutil"... | // SizeDiff diffs two images and compares their size | [
"SizeDiff",
"diffs",
"two",
"images",
"and",
"compares",
"their",
"size"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/size_diff.go#L34-L52 | train |
GoogleContainerTools/container-diff | differs/size_diff.go | Diff | func (a SizeLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
var layerDiffs []util.SizeDiff
maxLayer := len(image1.Layers)
if len(image2.Layers) > maxLayer {
maxLayer = len(image2.Layers)
}
for index := 0; index < maxLayer; index++ {
var size1, size2 int64 = -1, -1
if index < len(image1.Layers) {
size1 = pkgutil.GetSize(image1.Layers[index].FSPath)
}
if index < len(image2.Layers) {
size2 = pkgutil.GetSize(image2.Layers[index].FSPath)
}
if size1 != size2 {
diff := util.SizeDiff{
Name: strconv.Itoa(index),
Size1: size1,
Size2: size2,
}
layerDiffs = append(layerDiffs, diff)
}
}
return &util.SizeLayerDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "SizeLayer",
Diff: layerDiffs,
}, nil
} | go | func (a SizeLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
var layerDiffs []util.SizeDiff
maxLayer := len(image1.Layers)
if len(image2.Layers) > maxLayer {
maxLayer = len(image2.Layers)
}
for index := 0; index < maxLayer; index++ {
var size1, size2 int64 = -1, -1
if index < len(image1.Layers) {
size1 = pkgutil.GetSize(image1.Layers[index].FSPath)
}
if index < len(image2.Layers) {
size2 = pkgutil.GetSize(image2.Layers[index].FSPath)
}
if size1 != size2 {
diff := util.SizeDiff{
Name: strconv.Itoa(index),
Size1: size1,
Size2: size2,
}
layerDiffs = append(layerDiffs, diff)
}
}
return &util.SizeLayerDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "SizeLayer",
Diff: layerDiffs,
}, nil
} | [
"func",
"(",
"a",
"SizeLayerAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"var",
"layerDiffs",
"[",
"]",
"util",
".",
"SizeDiff",
"\n",
"maxLayer",
":=",
"len",
... | // SizeLayerDiff diffs the layers of two images and compares their size | [
"SizeLayerDiff",
"diffs",
"the",
"layers",
"of",
"two",
"images",
"and",
"compares",
"their",
"size"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/size_diff.go#L78-L111 | train |
GoogleContainerTools/container-diff | differs/package_differs.go | singleVersionLayerDiff | func singleVersionLayerDiff(image1, image2 pkgutil.Image, differ SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerDiffResult, error) {
logrus.Warning("'diff' command for packages on layers is not supported, consider using 'analyze' on each image instead")
return &util.SingleVersionPackageLayerDiffResult{}, errors.New("Diff for packages on layers is not supported, only analysis is supported")
} | go | func singleVersionLayerDiff(image1, image2 pkgutil.Image, differ SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerDiffResult, error) {
logrus.Warning("'diff' command for packages on layers is not supported, consider using 'analyze' on each image instead")
return &util.SingleVersionPackageLayerDiffResult{}, errors.New("Diff for packages on layers is not supported, only analysis is supported")
} | [
"func",
"singleVersionLayerDiff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
",",
"differ",
"SingleVersionPackageLayerAnalyzer",
")",
"(",
"*",
"util",
".",
"SingleVersionPackageLayerDiffResult",
",",
"error",
")",
"{",
"logrus",
".",
"Warning",
"(",
"... | // singleVersionLayerDiff returns an error as this diff is not supported as
// it is far from obvious to define it in meaningful way | [
"singleVersionLayerDiff",
"returns",
"an",
"error",
"as",
"this",
"diff",
"is",
"not",
"supported",
"as",
"it",
"is",
"far",
"from",
"obvious",
"to",
"define",
"it",
"in",
"meaningful",
"way"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/package_differs.go#L83-L86 | train |
GoogleContainerTools/container-diff | differs/package_differs.go | singleVersionLayerAnalysis | func singleVersionLayerAnalysis(image pkgutil.Image, analyzer SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerAnalyzeResult, error) {
pack, err := analyzer.getPackages(image)
if err != nil {
return &util.SingleVersionPackageLayerAnalyzeResult{}, err
}
var pkgDiffs []util.PackageDiff
// Each layer with modified packages includes a complete list of packages
// in its package database. Thus we diff the current layer with the
// previous one that contains a package database. Layers that do not
// include a package database are omitted.
preInd := -1
for i := range pack {
var pkgDiff util.PackageDiff
if preInd < 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(make(map[string]util.PackageInfo), pack[i])
preInd = i
} else if preInd >= 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(pack[preInd], pack[i])
preInd = i
}
pkgDiffs = append(pkgDiffs, pkgDiff)
}
return &util.SingleVersionPackageLayerAnalyzeResult{
Image: image.Source,
AnalyzeType: strings.TrimSuffix(analyzer.Name(), "Analyzer"),
Analysis: util.PackageLayerDiff{
PackageDiffs: pkgDiffs,
},
}, nil
} | go | func singleVersionLayerAnalysis(image pkgutil.Image, analyzer SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerAnalyzeResult, error) {
pack, err := analyzer.getPackages(image)
if err != nil {
return &util.SingleVersionPackageLayerAnalyzeResult{}, err
}
var pkgDiffs []util.PackageDiff
// Each layer with modified packages includes a complete list of packages
// in its package database. Thus we diff the current layer with the
// previous one that contains a package database. Layers that do not
// include a package database are omitted.
preInd := -1
for i := range pack {
var pkgDiff util.PackageDiff
if preInd < 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(make(map[string]util.PackageInfo), pack[i])
preInd = i
} else if preInd >= 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(pack[preInd], pack[i])
preInd = i
}
pkgDiffs = append(pkgDiffs, pkgDiff)
}
return &util.SingleVersionPackageLayerAnalyzeResult{
Image: image.Source,
AnalyzeType: strings.TrimSuffix(analyzer.Name(), "Analyzer"),
Analysis: util.PackageLayerDiff{
PackageDiffs: pkgDiffs,
},
}, nil
} | [
"func",
"singleVersionLayerAnalysis",
"(",
"image",
"pkgutil",
".",
"Image",
",",
"analyzer",
"SingleVersionPackageLayerAnalyzer",
")",
"(",
"*",
"util",
".",
"SingleVersionPackageLayerAnalyzeResult",
",",
"error",
")",
"{",
"pack",
",",
"err",
":=",
"analyzer",
"."... | // singleVersionLayerAnalysis returns the packages included, deleted or
// updated in each layer | [
"singleVersionLayerAnalysis",
"returns",
"the",
"packages",
"included",
"deleted",
"or",
"updated",
"in",
"each",
"layer"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/package_differs.go#L118-L150 | train |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | GetFileSystemForLayer | func GetFileSystemForLayer(layer v1.Layer, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
contents, err := layer.Uncompressed()
if err != nil {
return err
}
return unpackTar(tar.NewReader(contents), root, whitelist)
} | go | func GetFileSystemForLayer(layer v1.Layer, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
contents, err := layer.Uncompressed()
if err != nil {
return err
}
return unpackTar(tar.NewReader(contents), root, whitelist)
} | [
"func",
"GetFileSystemForLayer",
"(",
"layer",
"v1",
".",
"Layer",
",",
"root",
"string",
",",
"whitelist",
"[",
"]",
"string",
")",
"error",
"{",
"empty",
",",
"err",
":=",
"DirIsEmpty",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",... | // GetFileSystemForLayer unpacks a layer to local disk | [
"GetFileSystemForLayer",
"unpacks",
"a",
"layer",
"to",
"local",
"disk"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L244-L258 | train |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | GetFileSystemForImage | func GetFileSystemForImage(image v1.Image, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
if err := unpackTar(tar.NewReader(mutate.Extract(image)), root, whitelist); err != nil {
return err
}
return nil
} | go | func GetFileSystemForImage(image v1.Image, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
if err := unpackTar(tar.NewReader(mutate.Extract(image)), root, whitelist); err != nil {
return err
}
return nil
} | [
"func",
"GetFileSystemForImage",
"(",
"image",
"v1",
".",
"Image",
",",
"root",
"string",
",",
"whitelist",
"[",
"]",
"string",
")",
"error",
"{",
"empty",
",",
"err",
":=",
"DirIsEmpty",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",... | // unpack image filesystem to local disk
// if provided directory is not empty, do nothing | [
"unpack",
"image",
"filesystem",
"to",
"local",
"disk",
"if",
"provided",
"directory",
"is",
"not",
"empty",
"do",
"nothing"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L262-L275 | train |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | HasTag | func HasTag(image string) bool {
tagRegex := regexp.MustCompile(tagRegexStr)
return tagRegex.MatchString(image)
} | go | func HasTag(image string) bool {
tagRegex := regexp.MustCompile(tagRegexStr)
return tagRegex.MatchString(image)
} | [
"func",
"HasTag",
"(",
"image",
"string",
")",
"bool",
"{",
"tagRegex",
":=",
"regexp",
".",
"MustCompile",
"(",
"tagRegexStr",
")",
"\n",
"return",
"tagRegex",
".",
"MatchString",
"(",
"image",
")",
"\n",
"}"
] | // checks to see if an image string contains a tag. | [
"checks",
"to",
"see",
"if",
"an",
"image",
"string",
"contains",
"a",
"tag",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L320-L323 | train |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | RemoveTag | func RemoveTag(image string) string {
if !HasTag(image) {
return image
}
tagRegex := regexp.MustCompile(tagRegexStr)
parts := tagRegex.FindStringSubmatch(image)
tag := parts[len(parts)-1]
return image[0 : len(image)-len(tag)-1]
} | go | func RemoveTag(image string) string {
if !HasTag(image) {
return image
}
tagRegex := regexp.MustCompile(tagRegexStr)
parts := tagRegex.FindStringSubmatch(image)
tag := parts[len(parts)-1]
return image[0 : len(image)-len(tag)-1]
} | [
"func",
"RemoveTag",
"(",
"image",
"string",
")",
"string",
"{",
"if",
"!",
"HasTag",
"(",
"image",
")",
"{",
"return",
"image",
"\n",
"}",
"\n",
"tagRegex",
":=",
"regexp",
".",
"MustCompile",
"(",
"tagRegexStr",
")",
"\n",
"parts",
":=",
"tagRegex",
... | // returns a raw image name with the tag removed | [
"returns",
"a",
"raw",
"image",
"name",
"with",
"the",
"tag",
"removed"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L326-L334 | train |
GoogleContainerTools/container-diff | util/diff_utils.go | GetAdditions | func GetAdditions(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
differences := matcher.GetGroupedOpCodes(0)
adds := []string{}
for _, group := range differences {
for _, opCode := range group {
j1, j2 := opCode.J1, opCode.J2
if opCode.Tag == 'r' || opCode.Tag == 'i' {
for _, line := range b[j1:j2] {
adds = append(adds, line)
}
}
}
}
return adds
} | go | func GetAdditions(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
differences := matcher.GetGroupedOpCodes(0)
adds := []string{}
for _, group := range differences {
for _, opCode := range group {
j1, j2 := opCode.J1, opCode.J2
if opCode.Tag == 'r' || opCode.Tag == 'i' {
for _, line := range b[j1:j2] {
adds = append(adds, line)
}
}
}
}
return adds
} | [
"func",
"GetAdditions",
"(",
"a",
",",
"b",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"matcher",
":=",
"difflib",
".",
"NewMatcher",
"(",
"a",
",",
"b",
")",
"\n",
"differences",
":=",
"matcher",
".",
"GetGroupedOpCodes",
"(",
"0",
")",
"\n",... | // Modification of difflib's unified differ | [
"Modification",
"of",
"difflib",
"s",
"unified",
"differ"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/diff_utils.go#L54-L70 | train |
GoogleContainerTools/container-diff | util/diff_utils.go | DiffDirectory | func DiffDirectory(d1, d2 pkgutil.Directory) (DirDiff, bool) {
adds := GetAddedEntries(d1, d2)
sort.Strings(adds)
addedEntries := pkgutil.CreateDirectoryEntries(d2.Root, adds)
dels := GetDeletedEntries(d1, d2)
sort.Strings(dels)
deletedEntries := pkgutil.CreateDirectoryEntries(d1.Root, dels)
mods := GetModifiedEntries(d1, d2)
sort.Strings(mods)
modifiedEntries := createEntryDiffs(d1.Root, d2.Root, mods)
var same bool
if len(adds) == 0 && len(dels) == 0 && len(mods) == 0 {
same = true
} else {
same = false
}
return DirDiff{addedEntries, deletedEntries, modifiedEntries}, same
} | go | func DiffDirectory(d1, d2 pkgutil.Directory) (DirDiff, bool) {
adds := GetAddedEntries(d1, d2)
sort.Strings(adds)
addedEntries := pkgutil.CreateDirectoryEntries(d2.Root, adds)
dels := GetDeletedEntries(d1, d2)
sort.Strings(dels)
deletedEntries := pkgutil.CreateDirectoryEntries(d1.Root, dels)
mods := GetModifiedEntries(d1, d2)
sort.Strings(mods)
modifiedEntries := createEntryDiffs(d1.Root, d2.Root, mods)
var same bool
if len(adds) == 0 && len(dels) == 0 && len(mods) == 0 {
same = true
} else {
same = false
}
return DirDiff{addedEntries, deletedEntries, modifiedEntries}, same
} | [
"func",
"DiffDirectory",
"(",
"d1",
",",
"d2",
"pkgutil",
".",
"Directory",
")",
"(",
"DirDiff",
",",
"bool",
")",
"{",
"adds",
":=",
"GetAddedEntries",
"(",
"d1",
",",
"d2",
")",
"\n",
"sort",
".",
"Strings",
"(",
"adds",
")",
"\n",
"addedEntries",
... | // DiffDirectory takes the diff of two directories, assuming both are completely unpacked | [
"DiffDirectory",
"takes",
"the",
"diff",
"of",
"two",
"directories",
"assuming",
"both",
"are",
"completely",
"unpacked"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/diff_utils.go#L108-L129 | train |
GoogleContainerTools/container-diff | util/diff_utils.go | GetModifiedEntries | func GetModifiedEntries(d1, d2 pkgutil.Directory) []string {
d1files := d1.Content
d2files := d2.Content
filematches := GetMatches(d1files, d2files)
modified := []string{}
for _, f := range filematches {
f1path := fmt.Sprintf("%s%s", d1.Root, f)
f2path := fmt.Sprintf("%s%s", d2.Root, f)
f1stat, err := os.Lstat(f1path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
f2stat, err := os.Lstat(f2path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
// If the directory entry is a symlink, make sure the symlinks point to the same place
if f1stat.Mode()&os.ModeSymlink != 0 && f2stat.Mode()&os.ModeSymlink != 0 {
same, err := pkgutil.CheckSameSymlink(f1path, f2path)
if err != nil {
logrus.Errorf("Error determining if symlink %s and %s are equivalent: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
continue
}
// If the directory entry in question is a tar, verify that the two have the same size
if pkgutil.IsTar(f1path) {
if f1stat.Size() != f2stat.Size() {
modified = append(modified, f)
}
continue
}
// If the directory entry is not a tar and not a directory, then it's a file so make sure the file contents are the same
// Note: We skip over directory entries because to compare directories, we compare their contents
if !f1stat.IsDir() {
same, err := pkgutil.CheckSameFile(f1path, f2path)
if err != nil {
logrus.Errorf("Error diffing contents of %s and %s: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
}
}
return modified
} | go | func GetModifiedEntries(d1, d2 pkgutil.Directory) []string {
d1files := d1.Content
d2files := d2.Content
filematches := GetMatches(d1files, d2files)
modified := []string{}
for _, f := range filematches {
f1path := fmt.Sprintf("%s%s", d1.Root, f)
f2path := fmt.Sprintf("%s%s", d2.Root, f)
f1stat, err := os.Lstat(f1path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
f2stat, err := os.Lstat(f2path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
// If the directory entry is a symlink, make sure the symlinks point to the same place
if f1stat.Mode()&os.ModeSymlink != 0 && f2stat.Mode()&os.ModeSymlink != 0 {
same, err := pkgutil.CheckSameSymlink(f1path, f2path)
if err != nil {
logrus.Errorf("Error determining if symlink %s and %s are equivalent: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
continue
}
// If the directory entry in question is a tar, verify that the two have the same size
if pkgutil.IsTar(f1path) {
if f1stat.Size() != f2stat.Size() {
modified = append(modified, f)
}
continue
}
// If the directory entry is not a tar and not a directory, then it's a file so make sure the file contents are the same
// Note: We skip over directory entries because to compare directories, we compare their contents
if !f1stat.IsDir() {
same, err := pkgutil.CheckSameFile(f1path, f2path)
if err != nil {
logrus.Errorf("Error diffing contents of %s and %s: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
}
}
return modified
} | [
"func",
"GetModifiedEntries",
"(",
"d1",
",",
"d2",
"pkgutil",
".",
"Directory",
")",
"[",
"]",
"string",
"{",
"d1files",
":=",
"d1",
".",
"Content",
"\n",
"d2files",
":=",
"d2",
".",
"Content",
"\n",
"filematches",
":=",
"GetMatches",
"(",
"d1files",
",... | // Checks for content differences between files of the same name from different directories | [
"Checks",
"for",
"content",
"differences",
"between",
"files",
"of",
"the",
"same",
"name",
"from",
"different",
"directories"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/diff_utils.go#L190-L247 | train |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | GetFileContents | func GetFileContents(path string) (*string, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
strContents := string(contents)
//If file is empty, return nil
if strContents == "" {
return nil, nil
}
return &strContents, nil
} | go | func GetFileContents(path string) (*string, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
strContents := string(contents)
//If file is empty, return nil
if strContents == "" {
return nil, nil
}
return &strContents, nil
} | [
"func",
"GetFileContents",
"(",
"path",
"string",
")",
"(",
"*",
"string",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"err",
... | //GetFileContents returns the contents of a file at the specified path | [
"GetFileContents",
"returns",
"the",
"contents",
"of",
"a",
"file",
"at",
"the",
"specified",
"path"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L58-L74 | train |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | GetDirectory | func GetDirectory(path string, deep bool) (Directory, error) {
var directory Directory
directory.Root = path
var err error
if deep {
walkFn := func(currPath string, info os.FileInfo, err error) error {
newContent := strings.TrimPrefix(currPath, directory.Root)
if newContent != "" {
directory.Content = append(directory.Content, newContent)
}
return nil
}
err = filepath.Walk(path, walkFn)
} else {
contents, err := ioutil.ReadDir(path)
if err != nil {
return directory, err
}
for _, file := range contents {
fileName := "/" + file.Name()
directory.Content = append(directory.Content, fileName)
}
}
return directory, err
} | go | func GetDirectory(path string, deep bool) (Directory, error) {
var directory Directory
directory.Root = path
var err error
if deep {
walkFn := func(currPath string, info os.FileInfo, err error) error {
newContent := strings.TrimPrefix(currPath, directory.Root)
if newContent != "" {
directory.Content = append(directory.Content, newContent)
}
return nil
}
err = filepath.Walk(path, walkFn)
} else {
contents, err := ioutil.ReadDir(path)
if err != nil {
return directory, err
}
for _, file := range contents {
fileName := "/" + file.Name()
directory.Content = append(directory.Content, fileName)
}
}
return directory, err
} | [
"func",
"GetDirectory",
"(",
"path",
"string",
",",
"deep",
"bool",
")",
"(",
"Directory",
",",
"error",
")",
"{",
"var",
"directory",
"Directory",
"\n",
"directory",
".",
"Root",
"=",
"path",
"\n",
"var",
"err",
"error",
"\n",
"if",
"deep",
"{",
"walk... | // GetDirectoryContents converts the directory starting at the provided path into a Directory struct. | [
"GetDirectoryContents",
"converts",
"the",
"directory",
"starting",
"at",
"the",
"provided",
"path",
"into",
"a",
"Directory",
"struct",
"."
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L88-L114 | train |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | HasFilepathPrefix | func HasFilepathPrefix(path, prefix string) bool {
path = filepath.Clean(path)
prefix = filepath.Clean(prefix)
pathArray := strings.Split(path, "/")
prefixArray := strings.Split(prefix, "/")
if len(pathArray) < len(prefixArray) {
return false
}
for index := range prefixArray {
if prefixArray[index] == pathArray[index] {
continue
}
return false
}
return true
} | go | func HasFilepathPrefix(path, prefix string) bool {
path = filepath.Clean(path)
prefix = filepath.Clean(prefix)
pathArray := strings.Split(path, "/")
prefixArray := strings.Split(prefix, "/")
if len(pathArray) < len(prefixArray) {
return false
}
for index := range prefixArray {
if prefixArray[index] == pathArray[index] {
continue
}
return false
}
return true
} | [
"func",
"HasFilepathPrefix",
"(",
"path",
",",
"prefix",
"string",
")",
"bool",
"{",
"path",
"=",
"filepath",
".",
"Clean",
"(",
"path",
")",
"\n",
"prefix",
"=",
"filepath",
".",
"Clean",
"(",
"prefix",
")",
"\n",
"pathArray",
":=",
"strings",
".",
"S... | // HasFilepathPrefix checks if the given file path begins with prefix | [
"HasFilepathPrefix",
"checks",
"if",
"the",
"given",
"file",
"path",
"begins",
"with",
"prefix"
] | a62c5163a8a12073631fddd972570e5559476e24 | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L178-L194 | train |
Unknwon/com | path.go | GetSrcPath | func GetSrcPath(importPath string) (appPath string, err error) {
paths := GetGOPATHs()
for _, p := range paths {
if IsExist(p + "/src/" + importPath + "/") {
appPath = p + "/src/" + importPath + "/"
break
}
}
if len(appPath) == 0 {
return "", errors.New("Unable to locate source folder path")
}
appPath = filepath.Dir(appPath) + "/"
if runtime.GOOS == "windows" {
// Replace all '\' to '/'.
appPath = strings.Replace(appPath, "\\", "/", -1)
}
return appPath, nil
} | go | func GetSrcPath(importPath string) (appPath string, err error) {
paths := GetGOPATHs()
for _, p := range paths {
if IsExist(p + "/src/" + importPath + "/") {
appPath = p + "/src/" + importPath + "/"
break
}
}
if len(appPath) == 0 {
return "", errors.New("Unable to locate source folder path")
}
appPath = filepath.Dir(appPath) + "/"
if runtime.GOOS == "windows" {
// Replace all '\' to '/'.
appPath = strings.Replace(appPath, "\\", "/", -1)
}
return appPath, nil
} | [
"func",
"GetSrcPath",
"(",
"importPath",
"string",
")",
"(",
"appPath",
"string",
",",
"err",
"error",
")",
"{",
"paths",
":=",
"GetGOPATHs",
"(",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"if",
"IsExist",
"(",
"p",
"+",
"\"/src/\... | // GetSrcPath returns app. source code path.
// It only works when you have src. folder in GOPATH,
// it returns error not able to locate source folder path. | [
"GetSrcPath",
"returns",
"app",
".",
"source",
"code",
"path",
".",
"It",
"only",
"works",
"when",
"you",
"have",
"src",
".",
"folder",
"in",
"GOPATH",
"it",
"returns",
"error",
"not",
"able",
"to",
"locate",
"source",
"folder",
"path",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/path.go#L41-L61 | train |
Unknwon/com | cmd.go | getColorLevel | func getColorLevel(level string) string {
level = strings.ToUpper(level)
switch level {
case "TRAC":
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case "ERRO":
return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
case "WARN":
return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
case "SUCC":
return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
default:
return level
}
} | go | func getColorLevel(level string) string {
level = strings.ToUpper(level)
switch level {
case "TRAC":
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case "ERRO":
return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
case "WARN":
return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
case "SUCC":
return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
default:
return level
}
} | [
"func",
"getColorLevel",
"(",
"level",
"string",
")",
"string",
"{",
"level",
"=",
"strings",
".",
"ToUpper",
"(",
"level",
")",
"\n",
"switch",
"level",
"{",
"case",
"\"TRAC\"",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"\\033[%dm%s\\033[0m\"",
",",
"\... | // getColorLevel returns colored level string by given level. | [
"getColorLevel",
"returns",
"colored",
"level",
"string",
"by",
"given",
"level",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/cmd.go#L82-L96 | train |
Unknwon/com | string.go | AESGCMEncrypt | func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
} | go | func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
} | [
"func",
"AESGCMEncrypt",
"(",
"key",
",",
"plaintext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil"... | // AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode. | [
"AESGCMEncrypt",
"encrypts",
"plaintext",
"with",
"the",
"given",
"key",
"using",
"AES",
"in",
"GCM",
"mode",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L32-L50 | train |
Unknwon/com | string.go | AESGCMDecrypt | func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
size := gcm.NonceSize()
if len(ciphertext)-size <= 0 {
return nil, errors.New("Ciphertext is empty")
}
nonce := ciphertext[:size]
ciphertext = ciphertext[size:]
plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plainText, nil
} | go | func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
size := gcm.NonceSize()
if len(ciphertext)-size <= 0 {
return nil, errors.New("Ciphertext is empty")
}
nonce := ciphertext[:size]
ciphertext = ciphertext[size:]
plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plainText, nil
} | [
"func",
"AESGCMDecrypt",
"(",
"key",
",",
"ciphertext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil... | // AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode. | [
"AESGCMDecrypt",
"decrypts",
"ciphertext",
"with",
"the",
"given",
"key",
"using",
"AES",
"in",
"GCM",
"mode",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L53-L78 | train |
Unknwon/com | string.go | IsLetter | func IsLetter(l uint8) bool {
n := (l | 0x20) - 'a'
if n >= 0 && n < 26 {
return true
}
return false
} | go | func IsLetter(l uint8) bool {
n := (l | 0x20) - 'a'
if n >= 0 && n < 26 {
return true
}
return false
} | [
"func",
"IsLetter",
"(",
"l",
"uint8",
")",
"bool",
"{",
"n",
":=",
"(",
"l",
"|",
"0x20",
")",
"-",
"'a'",
"\n",
"if",
"n",
">=",
"0",
"&&",
"n",
"<",
"26",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsLetter returns true if the 'l' is an English letter. | [
"IsLetter",
"returns",
"true",
"if",
"the",
"l",
"is",
"an",
"English",
"letter",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L81-L87 | train |
Unknwon/com | string.go | Reverse | func Reverse(s string) string {
n := len(s)
runes := make([]rune, n)
for _, rune := range s {
n--
runes[n] = rune
}
return string(runes[n:])
} | go | func Reverse(s string) string {
n := len(s)
runes := make([]rune, n)
for _, rune := range s {
n--
runes[n] = rune
}
return string(runes[n:])
} | [
"func",
"Reverse",
"(",
"s",
"string",
")",
"string",
"{",
"n",
":=",
"len",
"(",
"s",
")",
"\n",
"runes",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"n",
")",
"\n",
"for",
"_",
",",
"rune",
":=",
"range",
"s",
"{",
"n",
"--",
"\n",
"runes",
... | // Reverse s string, support unicode | [
"Reverse",
"s",
"string",
"support",
"unicode"
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L118-L126 | train |
Unknwon/com | time.go | Date | func Date(ti int64, format string) string {
t := time.Unix(int64(ti), 0)
return DateT(t, format)
} | go | func Date(ti int64, format string) string {
t := time.Unix(int64(ti), 0)
return DateT(t, format)
} | [
"func",
"Date",
"(",
"ti",
"int64",
",",
"format",
"string",
")",
"string",
"{",
"t",
":=",
"time",
".",
"Unix",
"(",
"int64",
"(",
"ti",
")",
",",
"0",
")",
"\n",
"return",
"DateT",
"(",
"t",
",",
"format",
")",
"\n",
"}"
] | // Format unix time int64 to string | [
"Format",
"unix",
"time",
"int64",
"to",
"string"
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L25-L28 | train |
Unknwon/com | time.go | DateS | func DateS(ts string, format string) string {
i, _ := strconv.ParseInt(ts, 10, 64)
return Date(i, format)
} | go | func DateS(ts string, format string) string {
i, _ := strconv.ParseInt(ts, 10, 64)
return Date(i, format)
} | [
"func",
"DateS",
"(",
"ts",
"string",
",",
"format",
"string",
")",
"string",
"{",
"i",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"ts",
",",
"10",
",",
"64",
")",
"\n",
"return",
"Date",
"(",
"i",
",",
"format",
")",
"\n",
"}"
] | // Format unix time string to string | [
"Format",
"unix",
"time",
"string",
"to",
"string"
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L31-L34 | train |
Unknwon/com | time.go | DateT | func DateT(t time.Time, format string) string {
res := strings.Replace(format, "MM", t.Format("01"), -1)
res = strings.Replace(res, "M", t.Format("1"), -1)
res = strings.Replace(res, "DD", t.Format("02"), -1)
res = strings.Replace(res, "D", t.Format("2"), -1)
res = strings.Replace(res, "YYYY", t.Format("2006"), -1)
res = strings.Replace(res, "YY", t.Format("06"), -1)
res = strings.Replace(res, "HH", fmt.Sprintf("%02d", t.Hour()), -1)
res = strings.Replace(res, "H", fmt.Sprintf("%d", t.Hour()), -1)
res = strings.Replace(res, "hh", t.Format("03"), -1)
res = strings.Replace(res, "h", t.Format("3"), -1)
res = strings.Replace(res, "mm", t.Format("04"), -1)
res = strings.Replace(res, "m", t.Format("4"), -1)
res = strings.Replace(res, "ss", t.Format("05"), -1)
res = strings.Replace(res, "s", t.Format("5"), -1)
return res
} | go | func DateT(t time.Time, format string) string {
res := strings.Replace(format, "MM", t.Format("01"), -1)
res = strings.Replace(res, "M", t.Format("1"), -1)
res = strings.Replace(res, "DD", t.Format("02"), -1)
res = strings.Replace(res, "D", t.Format("2"), -1)
res = strings.Replace(res, "YYYY", t.Format("2006"), -1)
res = strings.Replace(res, "YY", t.Format("06"), -1)
res = strings.Replace(res, "HH", fmt.Sprintf("%02d", t.Hour()), -1)
res = strings.Replace(res, "H", fmt.Sprintf("%d", t.Hour()), -1)
res = strings.Replace(res, "hh", t.Format("03"), -1)
res = strings.Replace(res, "h", t.Format("3"), -1)
res = strings.Replace(res, "mm", t.Format("04"), -1)
res = strings.Replace(res, "m", t.Format("4"), -1)
res = strings.Replace(res, "ss", t.Format("05"), -1)
res = strings.Replace(res, "s", t.Format("5"), -1)
return res
} | [
"func",
"DateT",
"(",
"t",
"time",
".",
"Time",
",",
"format",
"string",
")",
"string",
"{",
"res",
":=",
"strings",
".",
"Replace",
"(",
"format",
",",
"\"MM\"",
",",
"t",
".",
"Format",
"(",
"\"01\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
... | // Format time.Time struct to string
// MM - month - 01
// M - month - 1, single bit
// DD - day - 02
// D - day 2
// YYYY - year - 2006
// YY - year - 06
// HH - 24 hours - 03
// H - 24 hours - 3
// hh - 12 hours - 03
// h - 12 hours - 3
// mm - minute - 04
// m - minute - 4
// ss - second - 05
// s - second = 5 | [
"Format",
"time",
".",
"Time",
"struct",
"to",
"string",
"MM",
"-",
"month",
"-",
"01",
"M",
"-",
"month",
"-",
"1",
"single",
"bit",
"DD",
"-",
"day",
"-",
"02",
"D",
"-",
"day",
"2",
"YYYY",
"-",
"year",
"-",
"2006",
"YY",
"-",
"year",
"-",
... | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L51-L67 | train |
Unknwon/com | time.go | DateParse | func DateParse(dateString, format string) (time.Time, error) {
replacer := strings.NewReplacer(datePatterns...)
format = replacer.Replace(format)
return time.ParseInLocation(format, dateString, time.Local)
} | go | func DateParse(dateString, format string) (time.Time, error) {
replacer := strings.NewReplacer(datePatterns...)
format = replacer.Replace(format)
return time.ParseInLocation(format, dateString, time.Local)
} | [
"func",
"DateParse",
"(",
"dateString",
",",
"format",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"replacer",
":=",
"strings",
".",
"NewReplacer",
"(",
"datePatterns",
"...",
")",
"\n",
"format",
"=",
"replacer",
".",
"Replace",
"("... | // Parse Date use PHP time format. | [
"Parse",
"Date",
"use",
"PHP",
"time",
"format",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L111-L115 | train |
Unknwon/com | dir.go | GetAllSubDirs | func GetAllSubDirs(rootPath string) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
return statDir(rootPath, "", true, true, false)
} | go | func GetAllSubDirs(rootPath string) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
return statDir(rootPath, "", true, true, false)
} | [
"func",
"GetAllSubDirs",
"(",
"rootPath",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"IsDir",
"(",
"rootPath",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"not a directory or does not exist: \"",
"+",
"rootP... | // GetAllSubDirs returns all subdirectories of given root path.
// Slice does not include given path itself. | [
"GetAllSubDirs",
"returns",
"all",
"subdirectories",
"of",
"given",
"root",
"path",
".",
"Slice",
"does",
"not",
"include",
"given",
"path",
"itself",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/dir.go#L127-L132 | train |
Unknwon/com | dir.go | GetFileListBySuffix | func GetFileListBySuffix(dirPath, suffix string) ([]string, error) {
if !IsExist(dirPath) {
return nil, fmt.Errorf("given path does not exist: %s", dirPath)
} else if IsFile(dirPath) {
return []string{dirPath}, nil
}
// Given path is a directory.
dir, err := os.Open(dirPath)
if err != nil {
return nil, err
}
fis, err := dir.Readdir(0)
if err != nil {
return nil, err
}
files := make([]string, 0, len(fis))
for _, fi := range fis {
if strings.HasSuffix(fi.Name(), suffix) {
files = append(files, path.Join(dirPath, fi.Name()))
}
}
return files, nil
} | go | func GetFileListBySuffix(dirPath, suffix string) ([]string, error) {
if !IsExist(dirPath) {
return nil, fmt.Errorf("given path does not exist: %s", dirPath)
} else if IsFile(dirPath) {
return []string{dirPath}, nil
}
// Given path is a directory.
dir, err := os.Open(dirPath)
if err != nil {
return nil, err
}
fis, err := dir.Readdir(0)
if err != nil {
return nil, err
}
files := make([]string, 0, len(fis))
for _, fi := range fis {
if strings.HasSuffix(fi.Name(), suffix) {
files = append(files, path.Join(dirPath, fi.Name()))
}
}
return files, nil
} | [
"func",
"GetFileListBySuffix",
"(",
"dirPath",
",",
"suffix",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"IsExist",
"(",
"dirPath",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"given path does not exist: %s\... | // GetFileListBySuffix returns an ordered list of file paths.
// It recognize if given path is a file, and don't do recursive find. | [
"GetFileListBySuffix",
"returns",
"an",
"ordered",
"list",
"of",
"file",
"paths",
".",
"It",
"recognize",
"if",
"given",
"path",
"is",
"a",
"file",
"and",
"don",
"t",
"do",
"recursive",
"find",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/dir.go#L146-L172 | train |
Unknwon/com | slice.go | AppendStr | func AppendStr(strs []string, str string) []string {
for _, s := range strs {
if s == str {
return strs
}
}
return append(strs, str)
} | go | func AppendStr(strs []string, str string) []string {
for _, s := range strs {
if s == str {
return strs
}
}
return append(strs, str)
} | [
"func",
"AppendStr",
"(",
"strs",
"[",
"]",
"string",
",",
"str",
"string",
")",
"[",
"]",
"string",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"strs",
"{",
"if",
"s",
"==",
"str",
"{",
"return",
"strs",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ap... | // AppendStr appends string to slice with no duplicates. | [
"AppendStr",
"appends",
"string",
"to",
"slice",
"with",
"no",
"duplicates",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/slice.go#L22-L29 | train |
Unknwon/com | slice.go | CompareSliceStrU | func CompareSliceStrU(s1, s2 []string) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
for j := len(s2) - 1; j >= 0; j-- {
if s1[i] == s2[j] {
s2 = append(s2[:j], s2[j+1:]...)
break
}
}
}
if len(s2) > 0 {
return false
}
return true
} | go | func CompareSliceStrU(s1, s2 []string) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
for j := len(s2) - 1; j >= 0; j-- {
if s1[i] == s2[j] {
s2 = append(s2[:j], s2[j+1:]...)
break
}
}
}
if len(s2) > 0 {
return false
}
return true
} | [
"func",
"CompareSliceStrU",
"(",
"s1",
",",
"s2",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"s1",
")",
"!=",
"len",
"(",
"s2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"s1",
"{",
"for",
"j",
":=",
... | // CompareSliceStrU compares two 'string' type slices.
// It returns true if elements are the same, and ignores the order. | [
"CompareSliceStrU",
"compares",
"two",
"string",
"type",
"slices",
".",
"It",
"returns",
"true",
"if",
"elements",
"are",
"the",
"same",
"and",
"ignores",
"the",
"order",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/slice.go#L49-L66 | train |
Unknwon/com | slice.go | IsSliceContainsInt64 | func IsSliceContainsInt64(sl []int64, i int64) bool {
for _, s := range sl {
if s == i {
return true
}
}
return false
} | go | func IsSliceContainsInt64(sl []int64, i int64) bool {
for _, s := range sl {
if s == i {
return true
}
}
return false
} | [
"func",
"IsSliceContainsInt64",
"(",
"sl",
"[",
"]",
"int64",
",",
"i",
"int64",
")",
"bool",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"sl",
"{",
"if",
"s",
"==",
"i",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
... | // IsSliceContainsInt64 returns true if the int64 exists in given slice. | [
"IsSliceContainsInt64",
"returns",
"true",
"if",
"the",
"int64",
"exists",
"in",
"given",
"slice",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/slice.go#L80-L87 | train |
Unknwon/com | file.go | FileMTime | func FileMTime(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.ModTime().Unix(), nil
} | go | func FileMTime(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.ModTime().Unix(), nil
} | [
"func",
"FileMTime",
"(",
"file",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
... | // FileMTime returns file modified time and possible error. | [
"FileMTime",
"returns",
"file",
"modified",
"time",
"and",
"possible",
"error",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/file.go#L63-L69 | train |
Unknwon/com | file.go | FileSize | func FileSize(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.Size(), nil
} | go | func FileSize(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.Size(), nil
} | [
"func",
"FileSize",
"(",
"file",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
... | // FileSize returns file size in bytes and possible error. | [
"FileSize",
"returns",
"file",
"size",
"in",
"bytes",
"and",
"possible",
"error",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/file.go#L72-L78 | train |
Unknwon/com | file.go | WriteFile | func WriteFile(filename string, data []byte) error {
os.MkdirAll(path.Dir(filename), os.ModePerm)
return ioutil.WriteFile(filename, data, 0655)
} | go | func WriteFile(filename string, data []byte) error {
os.MkdirAll(path.Dir(filename), os.ModePerm)
return ioutil.WriteFile(filename, data, 0655)
} | [
"func",
"WriteFile",
"(",
"filename",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Dir",
"(",
"filename",
")",
",",
"os",
".",
"ModePerm",
")",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
... | // WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it
// and its upper level paths. | [
"WriteFile",
"writes",
"data",
"to",
"a",
"file",
"named",
"by",
"filename",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"WriteFile",
"creates",
"it",
"and",
"its",
"upper",
"level",
"paths",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/file.go#L125-L128 | train |
Unknwon/com | http.go | HttpPost | func HttpPost(client *http.Client, url string, header http.Header, body []byte) (io.ReadCloser, error) {
return HttpCall(client, "POST", url, header, bytes.NewBuffer(body))
} | go | func HttpPost(client *http.Client, url string, header http.Header, body []byte) (io.ReadCloser, error) {
return HttpCall(client, "POST", url, header, bytes.NewBuffer(body))
} | [
"func",
"HttpPost",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"header",
"http",
".",
"Header",
",",
"body",
"[",
"]",
"byte",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"return",
"HttpCall",
"(",
"client",
... | // HttpPost posts the specified resource.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpPost",
"posts",
"the",
"specified",
"resource",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L81-L83 | train |
Unknwon/com | http.go | HttpGetToFile | func HttpGetToFile(client *http.Client, url string, header http.Header, fileName string) error {
rc, err := HttpGet(client, url, header)
if err != nil {
return err
}
defer rc.Close()
os.MkdirAll(path.Dir(fileName), os.ModePerm)
f, err := os.Create(fileName)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, rc)
return err
} | go | func HttpGetToFile(client *http.Client, url string, header http.Header, fileName string) error {
rc, err := HttpGet(client, url, header)
if err != nil {
return err
}
defer rc.Close()
os.MkdirAll(path.Dir(fileName), os.ModePerm)
f, err := os.Create(fileName)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, rc)
return err
} | [
"func",
"HttpGetToFile",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"header",
"http",
".",
"Header",
",",
"fileName",
"string",
")",
"error",
"{",
"rc",
",",
"err",
":=",
"HttpGet",
"(",
"client",
",",
"url",
",",
"header",
... | // HttpGetToFile gets the specified resource and writes to file.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpGetToFile",
"gets",
"the",
"specified",
"resource",
"and",
"writes",
"to",
"file",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L87-L102 | train |
Unknwon/com | http.go | HttpPostJSON | func HttpPostJSON(client *http.Client, url string, body, v interface{}) error {
data, err := json.Marshal(body)
if err != nil {
return err
}
rc, err := HttpPost(client, url, http.Header{"content-type": []string{"application/json"}}, data)
if err != nil {
return err
}
defer rc.Close()
err = json.NewDecoder(rc).Decode(v)
if _, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("JSON syntax error at %s", url)
}
return nil
} | go | func HttpPostJSON(client *http.Client, url string, body, v interface{}) error {
data, err := json.Marshal(body)
if err != nil {
return err
}
rc, err := HttpPost(client, url, http.Header{"content-type": []string{"application/json"}}, data)
if err != nil {
return err
}
defer rc.Close()
err = json.NewDecoder(rc).Decode(v)
if _, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("JSON syntax error at %s", url)
}
return nil
} | [
"func",
"HttpPostJSON",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"body",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"body",
")",
"\n",
"if",
"err",
"!=",
... | // HttpPostJSON posts the specified resource with struct values,
// and maps results to struct.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpPostJSON",
"posts",
"the",
"specified",
"resource",
"with",
"struct",
"values",
"and",
"maps",
"results",
"to",
"struct",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L133-L148 | train |
Unknwon/com | http.go | FetchFiles | func FetchFiles(client *http.Client, files []RawFile, header http.Header) error {
ch := make(chan error, len(files))
for i := range files {
go func(i int) {
p, err := HttpGetBytes(client, files[i].RawUrl(), nil)
if err != nil {
ch <- err
return
}
files[i].SetData(p)
ch <- nil
}(i)
}
for _ = range files {
if err := <-ch; err != nil {
return err
}
}
return nil
} | go | func FetchFiles(client *http.Client, files []RawFile, header http.Header) error {
ch := make(chan error, len(files))
for i := range files {
go func(i int) {
p, err := HttpGetBytes(client, files[i].RawUrl(), nil)
if err != nil {
ch <- err
return
}
files[i].SetData(p)
ch <- nil
}(i)
}
for _ = range files {
if err := <-ch; err != nil {
return err
}
}
return nil
} | [
"func",
"FetchFiles",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"files",
"[",
"]",
"RawFile",
",",
"header",
"http",
".",
"Header",
")",
"error",
"{",
"ch",
":=",
"make",
"(",
"chan",
"error",
",",
"len",
"(",
"files",
")",
")",
"\n",
"for",
... | // FetchFiles fetches files specified by the rawURL field in parallel. | [
"FetchFiles",
"fetches",
"files",
"specified",
"by",
"the",
"rawURL",
"field",
"in",
"parallel",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L159-L178 | train |
Unknwon/com | convert.go | HexStr2int | func HexStr2int(hexStr string) (int, error) {
num := 0
length := len(hexStr)
for i := 0; i < length; i++ {
char := hexStr[length-i-1]
factor := -1
switch {
case char >= '0' && char <= '9':
factor = int(char) - '0'
case char >= 'a' && char <= 'f':
factor = int(char) - 'a' + 10
default:
return -1, fmt.Errorf("invalid hex: %s", string(char))
}
num += factor * PowInt(16, i)
}
return num, nil
} | go | func HexStr2int(hexStr string) (int, error) {
num := 0
length := len(hexStr)
for i := 0; i < length; i++ {
char := hexStr[length-i-1]
factor := -1
switch {
case char >= '0' && char <= '9':
factor = int(char) - '0'
case char >= 'a' && char <= 'f':
factor = int(char) - 'a' + 10
default:
return -1, fmt.Errorf("invalid hex: %s", string(char))
}
num += factor * PowInt(16, i)
}
return num, nil
} | [
"func",
"HexStr2int",
"(",
"hexStr",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"num",
":=",
"0",
"\n",
"length",
":=",
"len",
"(",
"hexStr",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
"{",
"char",
":=",
... | // HexStr2int converts hex format string to decimal number. | [
"HexStr2int",
"converts",
"hex",
"format",
"string",
"to",
"decimal",
"number",
"."
] | 0fed4efef7553eed2cd04624befccacda78bb8e2 | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/convert.go#L127-L146 | train |
HouzuoGuo/tiedot | data/partition.go | OpenPartition | func (conf *Config) OpenPartition(colPath, lookupPath string) (part *Partition, err error) {
part = conf.newPartition()
part.CalculateConfigConstants()
if part.col, err = conf.OpenCollection(colPath); err != nil {
return
} else if part.lookup, err = conf.OpenHashTable(lookupPath); err != nil {
return
}
return
} | go | func (conf *Config) OpenPartition(colPath, lookupPath string) (part *Partition, err error) {
part = conf.newPartition()
part.CalculateConfigConstants()
if part.col, err = conf.OpenCollection(colPath); err != nil {
return
} else if part.lookup, err = conf.OpenHashTable(lookupPath); err != nil {
return
}
return
} | [
"func",
"(",
"conf",
"*",
"Config",
")",
"OpenPartition",
"(",
"colPath",
",",
"lookupPath",
"string",
")",
"(",
"part",
"*",
"Partition",
",",
"err",
"error",
")",
"{",
"part",
"=",
"conf",
".",
"newPartition",
"(",
")",
"\n",
"part",
".",
"CalculateC... | // Open a collection partition. | [
"Open",
"a",
"collection",
"partition",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L37-L46 | train |
HouzuoGuo/tiedot | data/partition.go | LockUpdate | func (part *Partition) LockUpdate(id int) {
for {
part.exclUpdateLock.Lock()
ch, ok := part.exclUpdate[id]
if !ok {
part.exclUpdate[id] = make(chan struct{})
}
part.exclUpdateLock.Unlock()
if ok {
<-ch
} else {
break
}
}
} | go | func (part *Partition) LockUpdate(id int) {
for {
part.exclUpdateLock.Lock()
ch, ok := part.exclUpdate[id]
if !ok {
part.exclUpdate[id] = make(chan struct{})
}
part.exclUpdateLock.Unlock()
if ok {
<-ch
} else {
break
}
}
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"LockUpdate",
"(",
"id",
"int",
")",
"{",
"for",
"{",
"part",
".",
"exclUpdateLock",
".",
"Lock",
"(",
")",
"\n",
"ch",
",",
"ok",
":=",
"part",
".",
"exclUpdate",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",... | // Lock a document for exclusive update. | [
"Lock",
"a",
"document",
"for",
"exclusive",
"update",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L93-L107 | train |
HouzuoGuo/tiedot | data/partition.go | UnlockUpdate | func (part *Partition) UnlockUpdate(id int) {
part.exclUpdateLock.Lock()
ch := part.exclUpdate[id]
delete(part.exclUpdate, id)
part.exclUpdateLock.Unlock()
close(ch)
} | go | func (part *Partition) UnlockUpdate(id int) {
part.exclUpdateLock.Lock()
ch := part.exclUpdate[id]
delete(part.exclUpdate, id)
part.exclUpdateLock.Unlock()
close(ch)
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"UnlockUpdate",
"(",
"id",
"int",
")",
"{",
"part",
".",
"exclUpdateLock",
".",
"Lock",
"(",
")",
"\n",
"ch",
":=",
"part",
".",
"exclUpdate",
"[",
"id",
"]",
"\n",
"delete",
"(",
"part",
".",
"exclUpdate",... | // Unlock a document to make it ready for the next update. | [
"Unlock",
"a",
"document",
"to",
"make",
"it",
"ready",
"for",
"the",
"next",
"update",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L110-L116 | train |
HouzuoGuo/tiedot | data/partition.go | ForEachDoc | func (part *Partition) ForEachDoc(partNum, totalPart int, fun func(id int, doc []byte) bool) (moveOn bool) {
ids, physIDs := part.lookup.GetPartition(partNum, totalPart)
for i, id := range ids {
data := part.col.Read(physIDs[i])
if data != nil {
if !fun(id, data) {
return false
}
}
}
return true
} | go | func (part *Partition) ForEachDoc(partNum, totalPart int, fun func(id int, doc []byte) bool) (moveOn bool) {
ids, physIDs := part.lookup.GetPartition(partNum, totalPart)
for i, id := range ids {
data := part.col.Read(physIDs[i])
if data != nil {
if !fun(id, data) {
return false
}
}
}
return true
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"ForEachDoc",
"(",
"partNum",
",",
"totalPart",
"int",
",",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
")",
"(",
"moveOn",
"bool",
")",
"{",
"ids",
",",
"physIDs",
":=",
... | // Partition documents into roughly equally sized portions, and run the function on every document in the portion. | [
"Partition",
"documents",
"into",
"roughly",
"equally",
"sized",
"portions",
"and",
"run",
"the",
"function",
"on",
"every",
"document",
"in",
"the",
"portion",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L130-L141 | train |
HouzuoGuo/tiedot | data/partition.go | ApproxDocCount | func (part *Partition) ApproxDocCount() int {
totalPart := 24 // not magic; a larger number makes estimation less accurate, but improves performance
for {
keys, _ := part.lookup.GetPartition(0, totalPart)
if len(keys) == 0 {
if totalPart < 8 {
return 0 // the hash table is really really empty
}
// Try a larger partition size
totalPart = totalPart / 2
} else {
return int(float64(len(keys)) * float64(totalPart))
}
}
} | go | func (part *Partition) ApproxDocCount() int {
totalPart := 24 // not magic; a larger number makes estimation less accurate, but improves performance
for {
keys, _ := part.lookup.GetPartition(0, totalPart)
if len(keys) == 0 {
if totalPart < 8 {
return 0 // the hash table is really really empty
}
// Try a larger partition size
totalPart = totalPart / 2
} else {
return int(float64(len(keys)) * float64(totalPart))
}
}
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"ApproxDocCount",
"(",
")",
"int",
"{",
"totalPart",
":=",
"24",
"\n",
"for",
"{",
"keys",
",",
"_",
":=",
"part",
".",
"lookup",
".",
"GetPartition",
"(",
"0",
",",
"totalPart",
")",
"\n",
"if",
"len",
"... | // Return approximate number of documents in the partition. | [
"Return",
"approximate",
"number",
"of",
"documents",
"in",
"the",
"partition",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L144-L158 | train |
HouzuoGuo/tiedot | data/partition.go | Close | func (part *Partition) Close() error {
var err error
if e := part.col.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.col.Path, e)
err = dberr.New(dberr.ErrorIO)
}
if e := part.lookup.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.lookup.Path, e)
err = dberr.New(dberr.ErrorIO)
}
return err
} | go | func (part *Partition) Close() error {
var err error
if e := part.col.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.col.Path, e)
err = dberr.New(dberr.ErrorIO)
}
if e := part.lookup.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.lookup.Path, e)
err = dberr.New(dberr.ErrorIO)
}
return err
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"if",
"e",
":=",
"part",
".",
"col",
".",
"Close",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"Failed to close... | // Close all file handles. | [
"Close",
"all",
"file",
"handles",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L181-L194 | train |
HouzuoGuo/tiedot | gommap/mmap.go | Map | func Map(f *os.File) (MMap, error) {
fd := uintptr(f.Fd())
fi, err := f.Stat()
if err != nil {
return nil, err
}
length := int(fi.Size())
if int64(length) != fi.Size() {
return nil, errors.New("memory map file length overflow")
}
return mmap(length, fd)
} | go | func Map(f *os.File) (MMap, error) {
fd := uintptr(f.Fd())
fi, err := f.Stat()
if err != nil {
return nil, err
}
length := int(fi.Size())
if int64(length) != fi.Size() {
return nil, errors.New("memory map file length overflow")
}
return mmap(length, fd)
} | [
"func",
"Map",
"(",
"f",
"*",
"os",
".",
"File",
")",
"(",
"MMap",
",",
"error",
")",
"{",
"fd",
":=",
"uintptr",
"(",
"f",
".",
"Fd",
"(",
")",
")",
"\n",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil"... | // Map maps an entire file into memory.
// Note that because of runtime limitations, no file larger than about 2GB can
// be completely mapped into memory. | [
"Map",
"maps",
"an",
"entire",
"file",
"into",
"memory",
".",
"Note",
"that",
"because",
"of",
"runtime",
"limitations",
"no",
"file",
"larger",
"than",
"about",
"2GB",
"can",
"be",
"completely",
"mapped",
"into",
"memory",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/gommap/mmap.go#L30-L41 | train |
HouzuoGuo/tiedot | httpapi/query.go | Query | func Query(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
// Evaluate the query
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
// Construct array of result
resultDocs := make(map[string]interface{}, len(queryResult))
counter := 0
for docID := range queryResult {
doc, _ := dbcol.Read(docID)
if doc != nil {
resultDocs[strconv.Itoa(docID)] = doc
counter++
}
}
// Serialize the array
resp, err := json.Marshal(resultDocs)
if err != nil {
http.Error(w, fmt.Sprintf("Server error: query returned invalid structure"), 500)
return
}
w.Write([]byte(string(resp)))
} | go | func Query(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
// Evaluate the query
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
// Construct array of result
resultDocs := make(map[string]interface{}, len(queryResult))
counter := 0
for docID := range queryResult {
doc, _ := dbcol.Read(docID)
if doc != nil {
resultDocs[strconv.Itoa(docID)] = doc
counter++
}
}
// Serialize the array
resp, err := json.Marshal(resultDocs)
if err != nil {
http.Error(w, fmt.Sprintf("Server error: query returned invalid structure"), 500)
return
}
w.Write([]byte(string(resp)))
} | [
"func",
"Query",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Cache-Control\"",
",",
"\"must-revalidate\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
... | // Execute a query and return documents from the result. | [
"Execute",
"a",
"query",
"and",
"return",
"documents",
"from",
"the",
"result",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/query.go#L15-L60 | train |
HouzuoGuo/tiedot | httpapi/query.go | Count | func Count(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.Write([]byte(strconv.Itoa(len(queryResult))))
} | go | func Count(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.Write([]byte(strconv.Itoa(len(queryResult))))
} | [
"func",
"Count",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Cache-Control\"",
",",
"\"must-revalidate\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
... | // Execute a query and return number of documents from the result. | [
"Execute",
"a",
"query",
"and",
"return",
"number",
"of",
"documents",
"from",
"the",
"result",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/query.go#L63-L91 | train |
HouzuoGuo/tiedot | db/col.go | OpenCol | func OpenCol(db *DB, name string) (*Col, error) {
col := &Col{db: db, name: name}
return col, col.load()
} | go | func OpenCol(db *DB, name string) (*Col, error) {
col := &Col{db: db, name: name}
return col, col.load()
} | [
"func",
"OpenCol",
"(",
"db",
"*",
"DB",
",",
"name",
"string",
")",
"(",
"*",
"Col",
",",
"error",
")",
"{",
"col",
":=",
"&",
"Col",
"{",
"db",
":",
"db",
",",
"name",
":",
"name",
"}",
"\n",
"return",
"col",
",",
"col",
".",
"load",
"(",
... | // Open a collection and load all indexes. | [
"Open",
"a",
"collection",
"and",
"load",
"all",
"indexes",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L33-L36 | train |
HouzuoGuo/tiedot | db/col.go | load | func (col *Col) load() error {
if err := os.MkdirAll(path.Join(col.db.path, col.name), 0700); err != nil {
return err
}
col.parts = make([]*data.Partition, col.db.numParts)
col.hts = make([]map[string]*data.HashTable, col.db.numParts)
for i := 0; i < col.db.numParts; i++ {
col.hts[i] = make(map[string]*data.HashTable)
}
col.indexPaths = make(map[string][]string)
// Open collection document partitions
for i := 0; i < col.db.numParts; i++ {
var err error
if col.parts[i], err = col.db.Config.OpenPartition(
path.Join(col.db.path, col.name, DOC_DATA_FILE+strconv.Itoa(i)),
path.Join(col.db.path, col.name, DOC_LOOKUP_FILE+strconv.Itoa(i))); err != nil {
return err
}
}
// Look for index directories
colDirContent, err := ioutil.ReadDir(path.Join(col.db.path, col.name))
if err != nil {
return err
}
for _, htDir := range colDirContent {
if !htDir.IsDir() {
continue
}
// Open index partitions
idxName := htDir.Name()
idxPath := strings.Split(idxName, INDEX_PATH_SEP)
col.indexPaths[idxName] = idxPath
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(
path.Join(col.db.path, col.name, idxName, strconv.Itoa(i))); err != nil {
return err
}
}
}
return nil
} | go | func (col *Col) load() error {
if err := os.MkdirAll(path.Join(col.db.path, col.name), 0700); err != nil {
return err
}
col.parts = make([]*data.Partition, col.db.numParts)
col.hts = make([]map[string]*data.HashTable, col.db.numParts)
for i := 0; i < col.db.numParts; i++ {
col.hts[i] = make(map[string]*data.HashTable)
}
col.indexPaths = make(map[string][]string)
// Open collection document partitions
for i := 0; i < col.db.numParts; i++ {
var err error
if col.parts[i], err = col.db.Config.OpenPartition(
path.Join(col.db.path, col.name, DOC_DATA_FILE+strconv.Itoa(i)),
path.Join(col.db.path, col.name, DOC_LOOKUP_FILE+strconv.Itoa(i))); err != nil {
return err
}
}
// Look for index directories
colDirContent, err := ioutil.ReadDir(path.Join(col.db.path, col.name))
if err != nil {
return err
}
for _, htDir := range colDirContent {
if !htDir.IsDir() {
continue
}
// Open index partitions
idxName := htDir.Name()
idxPath := strings.Split(idxName, INDEX_PATH_SEP)
col.indexPaths[idxName] = idxPath
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(
path.Join(col.db.path, col.name, idxName, strconv.Itoa(i))); err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"load",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
")",
",",
"0700",
")",
";",
"err",
"!=",
"... | // Load collection schema including index schema. | [
"Load",
"collection",
"schema",
"including",
"index",
"schema",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L39-L79 | train |
HouzuoGuo/tiedot | db/col.go | close | func (col *Col) close() error {
errs := make([]error, 0, 0)
for i := 0; i < col.db.numParts; i++ {
col.parts[i].DataLock.Lock()
if err := col.parts[i].Close(); err != nil {
errs = append(errs, err)
}
for _, ht := range col.hts[i] {
if err := ht.Close(); err != nil {
errs = append(errs, err)
}
}
col.parts[i].DataLock.Unlock()
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
} | go | func (col *Col) close() error {
errs := make([]error, 0, 0)
for i := 0; i < col.db.numParts; i++ {
col.parts[i].DataLock.Lock()
if err := col.parts[i].Close(); err != nil {
errs = append(errs, err)
}
for _, ht := range col.hts[i] {
if err := ht.Close(); err != nil {
errs = append(errs, err)
}
}
col.parts[i].DataLock.Unlock()
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"close",
"(",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
",",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{... | // Close all collection files. Do not use the collection afterwards! | [
"Close",
"all",
"collection",
"files",
".",
"Do",
"not",
"use",
"the",
"collection",
"afterwards!"
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L82-L100 | train |
HouzuoGuo/tiedot | db/col.go | ForEachDoc | func (col *Col) ForEachDoc(fun func(id int, doc []byte) (moveOn bool)) {
col.forEachDoc(fun, true)
} | go | func (col *Col) ForEachDoc(fun func(id int, doc []byte) (moveOn bool)) {
col.forEachDoc(fun, true)
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"ForEachDoc",
"(",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"(",
"moveOn",
"bool",
")",
")",
"{",
"col",
".",
"forEachDoc",
"(",
"fun",
",",
"true",
")",
"\n",
"}"
] | // Do fun for all documents in the collection. | [
"Do",
"fun",
"for",
"all",
"documents",
"in",
"the",
"collection",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L126-L128 | train |
HouzuoGuo/tiedot | db/col.go | Index | func (col *Col) Index(idxPath []string) (err error) {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; exists {
return fmt.Errorf("Path %v is already indexed", idxPath)
}
col.indexPaths[idxName] = idxPath
idxDir := path.Join(col.db.path, col.name, idxName)
if err = os.MkdirAll(idxDir, 0700); err != nil {
return err
}
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(path.Join(idxDir, strconv.Itoa(i))); err != nil {
return err
}
}
// Put all documents on the new index
col.forEachDoc(func(id int, doc []byte) (moveOn bool) {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err != nil {
// Skip corrupted document
return true
}
for _, idxVal := range GetIn(docObj, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
col.hts[hashKey%col.db.numParts][idxName].Put(hashKey, id)
}
}
return true
}, false)
return
} | go | func (col *Col) Index(idxPath []string) (err error) {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; exists {
return fmt.Errorf("Path %v is already indexed", idxPath)
}
col.indexPaths[idxName] = idxPath
idxDir := path.Join(col.db.path, col.name, idxName)
if err = os.MkdirAll(idxDir, 0700); err != nil {
return err
}
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(path.Join(idxDir, strconv.Itoa(i))); err != nil {
return err
}
}
// Put all documents on the new index
col.forEachDoc(func(id int, doc []byte) (moveOn bool) {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err != nil {
// Skip corrupted document
return true
}
for _, idxVal := range GetIn(docObj, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
col.hts[hashKey%col.db.numParts][idxName].Put(hashKey, id)
}
}
return true
}, false)
return
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Index",
"(",
"idxPath",
"[",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"col",
".",
"db",
".",
"schemaLock",
".",
"Unlock",
... | // Create an index on the path. | [
"Create",
"an",
"index",
"on",
"the",
"path",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L131-L164 | train |
HouzuoGuo/tiedot | db/col.go | Unindex | func (col *Col) Unindex(idxPath []string) error {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; !exists {
return fmt.Errorf("Path %v is not indexed", idxPath)
}
delete(col.indexPaths, idxName)
for i := 0; i < col.db.numParts; i++ {
col.hts[i][idxName].Close()
delete(col.hts[i], idxName)
}
if err := os.RemoveAll(path.Join(col.db.path, col.name, idxName)); err != nil {
return err
}
return nil
} | go | func (col *Col) Unindex(idxPath []string) error {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; !exists {
return fmt.Errorf("Path %v is not indexed", idxPath)
}
delete(col.indexPaths, idxName)
for i := 0; i < col.db.numParts; i++ {
col.hts[i][idxName].Close()
delete(col.hts[i], idxName)
}
if err := os.RemoveAll(path.Join(col.db.path, col.name, idxName)); err != nil {
return err
}
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Unindex",
"(",
"idxPath",
"[",
"]",
"string",
")",
"error",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"col",
".",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
... | // Remove an index. | [
"Remove",
"an",
"index",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L182-L198 | train |
HouzuoGuo/tiedot | db/col.go | ForEachDocInPage | func (col *Col) ForEachDocInPage(page, total int, fun func(id int, doc []byte) bool) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
for iteratePart := 0; iteratePart < col.db.numParts; iteratePart++ {
part := col.parts[iteratePart]
part.DataLock.RLock()
if !part.ForEachDoc(page, total, fun) {
part.DataLock.RUnlock()
return
}
part.DataLock.RUnlock()
}
} | go | func (col *Col) ForEachDocInPage(page, total int, fun func(id int, doc []byte) bool) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
for iteratePart := 0; iteratePart < col.db.numParts; iteratePart++ {
part := col.parts[iteratePart]
part.DataLock.RLock()
if !part.ForEachDoc(page, total, fun) {
part.DataLock.RUnlock()
return
}
part.DataLock.RUnlock()
}
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"ForEachDocInPage",
"(",
"page",
",",
"total",
"int",
",",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
")",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"... | // Divide the collection into roughly equally sized pages, and do fun on all documents in the specified page. | [
"Divide",
"the",
"collection",
"into",
"roughly",
"equally",
"sized",
"pages",
"and",
"do",
"fun",
"on",
"all",
"documents",
"in",
"the",
"specified",
"page",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L220-L232 | train |
HouzuoGuo/tiedot | db/doc.go | StrHash | func StrHash(str string) int {
var hash int
for _, c := range str {
hash = int(c) + (hash << 6) + (hash << 16) - hash
}
if hash < 0 {
return -hash
}
return hash
} | go | func StrHash(str string) int {
var hash int
for _, c := range str {
hash = int(c) + (hash << 6) + (hash << 16) - hash
}
if hash < 0 {
return -hash
}
return hash
} | [
"func",
"StrHash",
"(",
"str",
"string",
")",
"int",
"{",
"var",
"hash",
"int",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"str",
"{",
"hash",
"=",
"int",
"(",
"c",
")",
"+",
"(",
"hash",
"<<",
"6",
")",
"+",
"(",
"hash",
"<<",
"16",
")",
"... | // Hash a string using sdbm algorithm. | [
"Hash",
"a",
"string",
"using",
"sdbm",
"algorithm",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L42-L51 | train |
HouzuoGuo/tiedot | db/doc.go | indexDoc | func (col *Col) indexDoc(id int, doc map[string]interface{}) {
for idxName, idxPath := range col.indexPaths {
for _, idxVal := range GetIn(doc, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
partNum := hashKey % col.db.numParts
ht := col.hts[partNum][idxName]
ht.Lock.Lock()
ht.Put(hashKey, id)
ht.Lock.Unlock()
}
}
}
} | go | func (col *Col) indexDoc(id int, doc map[string]interface{}) {
for idxName, idxPath := range col.indexPaths {
for _, idxVal := range GetIn(doc, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
partNum := hashKey % col.db.numParts
ht := col.hts[partNum][idxName]
ht.Lock.Lock()
ht.Put(hashKey, id)
ht.Lock.Unlock()
}
}
}
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"indexDoc",
"(",
"id",
"int",
",",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"for",
"idxName",
",",
"idxPath",
":=",
"range",
"col",
".",
"indexPaths",
"{",
"for",
"_",
",",
"idxVal",
... | // Put a document on all user-created indexes. | [
"Put",
"a",
"document",
"on",
"all",
"user",
"-",
"created",
"indexes",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L54-L67 | train |
HouzuoGuo/tiedot | db/doc.go | Insert | func (col *Col) Insert(doc map[string]interface{}) (id int, err error) {
docJS, err := json.Marshal(doc)
if err != nil {
return
}
id = rand.Int()
partNum := id % col.db.numParts
col.db.schemaLock.RLock()
part := col.parts[partNum]
// Put document data into collection
part.DataLock.Lock()
_, err = part.Insert(id, []byte(docJS))
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return
}
part.LockUpdate(id)
// Index the document
col.indexDoc(id, doc)
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return
} | go | func (col *Col) Insert(doc map[string]interface{}) (id int, err error) {
docJS, err := json.Marshal(doc)
if err != nil {
return
}
id = rand.Int()
partNum := id % col.db.numParts
col.db.schemaLock.RLock()
part := col.parts[partNum]
// Put document data into collection
part.DataLock.Lock()
_, err = part.Insert(id, []byte(docJS))
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return
}
part.LockUpdate(id)
// Index the document
col.indexDoc(id, doc)
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Insert",
"(",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"id",
"int",
",",
"err",
"error",
")",
"{",
"docJS",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"doc",
")",
"\n",
"if",
... | // Insert a document into the collection. | [
"Insert",
"a",
"document",
"into",
"the",
"collection",
"."
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L103-L129 | train |
HouzuoGuo/tiedot | tdlog/tdlog.go | CritNoRepeat | func CritNoRepeat(template string, params ...interface{}) {
msg := fmt.Sprintf(template, params...)
critLock.Lock()
if _, exists := critHistory[msg]; !exists {
log.Print(msg)
critHistory[msg] = struct{}{}
}
if len(critHistory) > limitCritHistory {
critHistory = make(map[string]struct{})
}
critLock.Unlock()
} | go | func CritNoRepeat(template string, params ...interface{}) {
msg := fmt.Sprintf(template, params...)
critLock.Lock()
if _, exists := critHistory[msg]; !exists {
log.Print(msg)
critHistory[msg] = struct{}{}
}
if len(critHistory) > limitCritHistory {
critHistory = make(map[string]struct{})
}
critLock.Unlock()
} | [
"func",
"CritNoRepeat",
"(",
"template",
"string",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"template",
",",
"params",
"...",
")",
"\n",
"critLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
... | // LVL 2 - will not repeat a message twice over the past 100 distinct crit messages | [
"LVL",
"2",
"-",
"will",
"not",
"repeat",
"a",
"message",
"twice",
"over",
"the",
"past",
"100",
"distinct",
"crit",
"messages"
] | be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39 | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/tdlog/tdlog.go#L41-L52 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.