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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
rkt/rkt
|
pkg/flag/optionlist.go
|
NewOptionList
|
func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) {
permissible := make(map[string]struct{})
ol := &OptionList{
allOptions: permissibleOptions,
permissible: permissible,
typeName: "OptionList",
}
for _, o := range permissibleOptions {
ol.permissible[o] = struct{}{}
}
if err := ol.Set(defaultOptions); err != nil {
return nil, errwrap.Wrap(errors.New("problem setting defaults"), err)
}
return ol, nil
}
|
go
|
func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) {
permissible := make(map[string]struct{})
ol := &OptionList{
allOptions: permissibleOptions,
permissible: permissible,
typeName: "OptionList",
}
for _, o := range permissibleOptions {
ol.permissible[o] = struct{}{}
}
if err := ol.Set(defaultOptions); err != nil {
return nil, errwrap.Wrap(errors.New("problem setting defaults"), err)
}
return ol, nil
}
|
[
"func",
"NewOptionList",
"(",
"permissibleOptions",
"[",
"]",
"string",
",",
"defaultOptions",
"string",
")",
"(",
"*",
"OptionList",
",",
"error",
")",
"{",
"permissible",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"ol",
":=",
"&",
"OptionList",
"{",
"allOptions",
":",
"permissibleOptions",
",",
"permissible",
":",
"permissible",
",",
"typeName",
":",
"\"OptionList\"",
",",
"}",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"permissibleOptions",
"{",
"ol",
".",
"permissible",
"[",
"o",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ol",
".",
"Set",
"(",
"defaultOptions",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"problem setting defaults\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"ol",
",",
"nil",
"\n",
"}"
] |
// NewOptionList initializes an OptionList. PermissibleOptions is the complete
// set of allowable options. It will set all options specified in defaultOptions
// as provided; they will all be cleared if this flag is passed in the CLI
|
[
"NewOptionList",
"initializes",
"an",
"OptionList",
".",
"PermissibleOptions",
"is",
"the",
"complete",
"set",
"of",
"allowable",
"options",
".",
"It",
"will",
"set",
"all",
"options",
"specified",
"in",
"defaultOptions",
"as",
"provided",
";",
"they",
"will",
"all",
"be",
"cleared",
"if",
"this",
"flag",
"is",
"passed",
"in",
"the",
"CLI"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/flag/optionlist.go#L38-L55
|
train
|
rkt/rkt
|
rkt/image_gc.go
|
gcTreeStore
|
func gcTreeStore(ts *treestore.Store) error {
// Take an exclusive lock to block other pods being created.
// This is needed to avoid races between the below steps (getting the
// list of referenced treeStoreIDs, getting the list of treeStoreIDs
// from the store, removal of unreferenced treeStoreIDs) and new
// pods/treeStores being created/referenced
keyLock, err := lock.ExclusiveKeyLock(lockDir(), common.PrepareLock)
if err != nil {
return errwrap.Wrap(errors.New("cannot get exclusive prepare lock"), err)
}
defer keyLock.Close()
referencedTreeStoreIDs, err := getReferencedTreeStoreIDs()
if err != nil {
return errwrap.Wrap(errors.New("cannot get referenced treestoreIDs"), err)
}
treeStoreIDs, err := ts.GetIDs()
if err != nil {
return errwrap.Wrap(errors.New("cannot get treestoreIDs from the store"), err)
}
for _, treeStoreID := range treeStoreIDs {
if _, ok := referencedTreeStoreIDs[treeStoreID]; !ok {
if err := ts.Remove(treeStoreID); err != nil {
stderr.PrintE(fmt.Sprintf("error removing treestore %q", treeStoreID), err)
} else {
stderr.Printf("removed treestore %q", treeStoreID)
}
}
}
return nil
}
|
go
|
func gcTreeStore(ts *treestore.Store) error {
// Take an exclusive lock to block other pods being created.
// This is needed to avoid races between the below steps (getting the
// list of referenced treeStoreIDs, getting the list of treeStoreIDs
// from the store, removal of unreferenced treeStoreIDs) and new
// pods/treeStores being created/referenced
keyLock, err := lock.ExclusiveKeyLock(lockDir(), common.PrepareLock)
if err != nil {
return errwrap.Wrap(errors.New("cannot get exclusive prepare lock"), err)
}
defer keyLock.Close()
referencedTreeStoreIDs, err := getReferencedTreeStoreIDs()
if err != nil {
return errwrap.Wrap(errors.New("cannot get referenced treestoreIDs"), err)
}
treeStoreIDs, err := ts.GetIDs()
if err != nil {
return errwrap.Wrap(errors.New("cannot get treestoreIDs from the store"), err)
}
for _, treeStoreID := range treeStoreIDs {
if _, ok := referencedTreeStoreIDs[treeStoreID]; !ok {
if err := ts.Remove(treeStoreID); err != nil {
stderr.PrintE(fmt.Sprintf("error removing treestore %q", treeStoreID), err)
} else {
stderr.Printf("removed treestore %q", treeStoreID)
}
}
}
return nil
}
|
[
"func",
"gcTreeStore",
"(",
"ts",
"*",
"treestore",
".",
"Store",
")",
"error",
"{",
"keyLock",
",",
"err",
":=",
"lock",
".",
"ExclusiveKeyLock",
"(",
"lockDir",
"(",
")",
",",
"common",
".",
"PrepareLock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot get exclusive prepare lock\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"keyLock",
".",
"Close",
"(",
")",
"\n",
"referencedTreeStoreIDs",
",",
"err",
":=",
"getReferencedTreeStoreIDs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot get referenced treestoreIDs\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"treeStoreIDs",
",",
"err",
":=",
"ts",
".",
"GetIDs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot get treestoreIDs from the store\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"treeStoreID",
":=",
"range",
"treeStoreIDs",
"{",
"if",
"_",
",",
"ok",
":=",
"referencedTreeStoreIDs",
"[",
"treeStoreID",
"]",
";",
"!",
"ok",
"{",
"if",
"err",
":=",
"ts",
".",
"Remove",
"(",
"treeStoreID",
")",
";",
"err",
"!=",
"nil",
"{",
"stderr",
".",
"PrintE",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"error removing treestore %q\"",
",",
"treeStoreID",
")",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"stderr",
".",
"Printf",
"(",
"\"removed treestore %q\"",
",",
"treeStoreID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// gcTreeStore removes all treeStoreIDs not referenced by any non garbage
// collected pod from the store.
|
[
"gcTreeStore",
"removes",
"all",
"treeStoreIDs",
"not",
"referenced",
"by",
"any",
"non",
"garbage",
"collected",
"pod",
"from",
"the",
"store",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image_gc.go#L82-L111
|
train
|
rkt/rkt
|
rkt/image_gc.go
|
getRunningImages
|
func getRunningImages() ([]string, error) {
var runningImages []string
var errors []error
err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeMostDirs, func(p *pkgPod.Pod) {
var pm schema.PodManifest
if p.State() != pkgPod.Running {
return
}
if !p.PodManifestAvailable() {
return
}
_, manifest, err := p.PodManifest()
if err != nil {
errors = append(errors, newPodListReadError(p, err))
return
}
pm = *manifest
for _, app := range pm.Apps {
runningImages = append(runningImages, app.Image.ID.String())
}
})
if err != nil {
return nil, err
}
if len(errors) > 0 {
return nil, errors[0]
}
return runningImages, nil
}
|
go
|
func getRunningImages() ([]string, error) {
var runningImages []string
var errors []error
err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeMostDirs, func(p *pkgPod.Pod) {
var pm schema.PodManifest
if p.State() != pkgPod.Running {
return
}
if !p.PodManifestAvailable() {
return
}
_, manifest, err := p.PodManifest()
if err != nil {
errors = append(errors, newPodListReadError(p, err))
return
}
pm = *manifest
for _, app := range pm.Apps {
runningImages = append(runningImages, app.Image.ID.String())
}
})
if err != nil {
return nil, err
}
if len(errors) > 0 {
return nil, errors[0]
}
return runningImages, nil
}
|
[
"func",
"getRunningImages",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"runningImages",
"[",
"]",
"string",
"\n",
"var",
"errors",
"[",
"]",
"error",
"\n",
"err",
":=",
"pkgPod",
".",
"WalkPods",
"(",
"getDataDir",
"(",
")",
",",
"pkgPod",
".",
"IncludeMostDirs",
",",
"func",
"(",
"p",
"*",
"pkgPod",
".",
"Pod",
")",
"{",
"var",
"pm",
"schema",
".",
"PodManifest",
"\n",
"if",
"p",
".",
"State",
"(",
")",
"!=",
"pkgPod",
".",
"Running",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"p",
".",
"PodManifestAvailable",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"_",
",",
"manifest",
",",
"err",
":=",
"p",
".",
"PodManifest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"newPodListReadError",
"(",
"p",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"pm",
"=",
"*",
"manifest",
"\n",
"for",
"_",
",",
"app",
":=",
"range",
"pm",
".",
"Apps",
"{",
"runningImages",
"=",
"append",
"(",
"runningImages",
",",
"app",
".",
"Image",
".",
"ID",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errors",
")",
">",
"0",
"{",
"return",
"nil",
",",
"errors",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"runningImages",
",",
"nil",
"\n",
"}"
] |
// getRunningImages will return the image IDs used to create any of the
// currently running pods
|
[
"getRunningImages",
"will",
"return",
"the",
"image",
"IDs",
"used",
"to",
"create",
"any",
"of",
"the",
"currently",
"running",
"pods"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image_gc.go#L167-L195
|
train
|
rkt/rkt
|
stage0/run.go
|
deduplicateMPs
|
func deduplicateMPs(mounts []schema.Mount) []schema.Mount {
var res []schema.Mount
seen := make(map[string]struct{})
for _, m := range mounts {
cleanPath := path.Clean(m.Path)
if _, ok := seen[cleanPath]; !ok {
res = append(res, m)
seen[cleanPath] = struct{}{}
}
}
return res
}
|
go
|
func deduplicateMPs(mounts []schema.Mount) []schema.Mount {
var res []schema.Mount
seen := make(map[string]struct{})
for _, m := range mounts {
cleanPath := path.Clean(m.Path)
if _, ok := seen[cleanPath]; !ok {
res = append(res, m)
seen[cleanPath] = struct{}{}
}
}
return res
}
|
[
"func",
"deduplicateMPs",
"(",
"mounts",
"[",
"]",
"schema",
".",
"Mount",
")",
"[",
"]",
"schema",
".",
"Mount",
"{",
"var",
"res",
"[",
"]",
"schema",
".",
"Mount",
"\n",
"seen",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"mounts",
"{",
"cleanPath",
":=",
"path",
".",
"Clean",
"(",
"m",
".",
"Path",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"seen",
"[",
"cleanPath",
"]",
";",
"!",
"ok",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"m",
")",
"\n",
"seen",
"[",
"cleanPath",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] |
// deduplicateMPs removes Mounts with duplicated paths. If there's more than
// one Mount with the same path, it keeps the first one encountered.
|
[
"deduplicateMPs",
"removes",
"Mounts",
"with",
"duplicated",
"paths",
".",
"If",
"there",
"s",
"more",
"than",
"one",
"Mount",
"with",
"the",
"same",
"path",
"it",
"keeps",
"the",
"first",
"one",
"encountered",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L161-L172
|
train
|
rkt/rkt
|
stage0/run.go
|
MergeMounts
|
func MergeMounts(mounts []schema.Mount, appMounts []schema.Mount) []schema.Mount {
ml := append(appMounts, mounts...)
return deduplicateMPs(ml)
}
|
go
|
func MergeMounts(mounts []schema.Mount, appMounts []schema.Mount) []schema.Mount {
ml := append(appMounts, mounts...)
return deduplicateMPs(ml)
}
|
[
"func",
"MergeMounts",
"(",
"mounts",
"[",
"]",
"schema",
".",
"Mount",
",",
"appMounts",
"[",
"]",
"schema",
".",
"Mount",
")",
"[",
"]",
"schema",
".",
"Mount",
"{",
"ml",
":=",
"append",
"(",
"appMounts",
",",
"mounts",
"...",
")",
"\n",
"return",
"deduplicateMPs",
"(",
"ml",
")",
"\n",
"}"
] |
// MergeMounts combines the global and per-app mount slices
|
[
"MergeMounts",
"combines",
"the",
"global",
"and",
"per",
"-",
"app",
"mount",
"slices"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L175-L178
|
train
|
rkt/rkt
|
stage0/run.go
|
Prepare
|
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error {
if err := os.MkdirAll(common.AppsInfoPath(dir), common.DefaultRegularDirPerm); err != nil {
return errwrap.Wrap(errors.New("error creating apps info directory"), err)
}
debug("Preparing stage1")
if err := prepareStage1Image(cfg, dir); err != nil {
return errwrap.Wrap(errors.New("error preparing stage1"), err)
}
var pmb []byte
var err error
if len(cfg.PodManifest) > 0 {
pmb, err = validatePodManifest(cfg, dir)
} else {
pmb, err = generatePodManifest(cfg, dir)
}
if err != nil {
return err
}
cfg.CommonConfig.ManifestData = string(pmb)
// create pod lock file for app add/rm operations.
f, err := os.OpenFile(common.PodManifestLockPath(dir), os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
f.Close()
debug("Writing pod manifest")
fn := common.PodManifestPath(dir)
if err := ioutil.WriteFile(fn, pmb, common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing pod manifest"), err)
}
f, err = os.OpenFile(common.PodCreatedPath(dir), os.O_CREATE|os.O_RDWR, common.DefaultRegularFilePerm)
if err != nil {
return err
}
f.Close()
if cfg.UseOverlay {
// mark the pod as prepared with overlay
f, err := os.Create(filepath.Join(dir, common.OverlayPreparedFilename))
if err != nil {
return errwrap.Wrap(errors.New("error writing overlay marker file"), err)
}
defer f.Close()
}
if cfg.PrivateUsers.Shift > 0 {
// mark the pod as prepared for user namespaces
uidrangeBytes := cfg.PrivateUsers.Serialize()
if err := ioutil.WriteFile(filepath.Join(dir, common.PrivateUsersPreparedFilename), uidrangeBytes, common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing userns marker file"), err)
}
}
return nil
}
|
go
|
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error {
if err := os.MkdirAll(common.AppsInfoPath(dir), common.DefaultRegularDirPerm); err != nil {
return errwrap.Wrap(errors.New("error creating apps info directory"), err)
}
debug("Preparing stage1")
if err := prepareStage1Image(cfg, dir); err != nil {
return errwrap.Wrap(errors.New("error preparing stage1"), err)
}
var pmb []byte
var err error
if len(cfg.PodManifest) > 0 {
pmb, err = validatePodManifest(cfg, dir)
} else {
pmb, err = generatePodManifest(cfg, dir)
}
if err != nil {
return err
}
cfg.CommonConfig.ManifestData = string(pmb)
// create pod lock file for app add/rm operations.
f, err := os.OpenFile(common.PodManifestLockPath(dir), os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
f.Close()
debug("Writing pod manifest")
fn := common.PodManifestPath(dir)
if err := ioutil.WriteFile(fn, pmb, common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing pod manifest"), err)
}
f, err = os.OpenFile(common.PodCreatedPath(dir), os.O_CREATE|os.O_RDWR, common.DefaultRegularFilePerm)
if err != nil {
return err
}
f.Close()
if cfg.UseOverlay {
// mark the pod as prepared with overlay
f, err := os.Create(filepath.Join(dir, common.OverlayPreparedFilename))
if err != nil {
return errwrap.Wrap(errors.New("error writing overlay marker file"), err)
}
defer f.Close()
}
if cfg.PrivateUsers.Shift > 0 {
// mark the pod as prepared for user namespaces
uidrangeBytes := cfg.PrivateUsers.Serialize()
if err := ioutil.WriteFile(filepath.Join(dir, common.PrivateUsersPreparedFilename), uidrangeBytes, common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing userns marker file"), err)
}
}
return nil
}
|
[
"func",
"Prepare",
"(",
"cfg",
"PrepareConfig",
",",
"dir",
"string",
",",
"uuid",
"*",
"types",
".",
"UUID",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"common",
".",
"AppsInfoPath",
"(",
"dir",
")",
",",
"common",
".",
"DefaultRegularDirPerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error creating apps info directory\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"debug",
"(",
"\"Preparing stage1\"",
")",
"\n",
"if",
"err",
":=",
"prepareStage1Image",
"(",
"cfg",
",",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error preparing stage1\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"var",
"pmb",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"if",
"len",
"(",
"cfg",
".",
"PodManifest",
")",
">",
"0",
"{",
"pmb",
",",
"err",
"=",
"validatePodManifest",
"(",
"cfg",
",",
"dir",
")",
"\n",
"}",
"else",
"{",
"pmb",
",",
"err",
"=",
"generatePodManifest",
"(",
"cfg",
",",
"dir",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cfg",
".",
"CommonConfig",
".",
"ManifestData",
"=",
"string",
"(",
"pmb",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"common",
".",
"PodManifestLockPath",
"(",
"dir",
")",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_RDWR",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
".",
"Close",
"(",
")",
"\n",
"debug",
"(",
"\"Writing pod manifest\"",
")",
"\n",
"fn",
":=",
"common",
".",
"PodManifestPath",
"(",
"dir",
")",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"fn",
",",
"pmb",
",",
"common",
".",
"DefaultRegularFilePerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error writing pod manifest\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"f",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"common",
".",
"PodCreatedPath",
"(",
"dir",
")",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_RDWR",
",",
"common",
".",
"DefaultRegularFilePerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
".",
"Close",
"(",
")",
"\n",
"if",
"cfg",
".",
"UseOverlay",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"common",
".",
"OverlayPreparedFilename",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error writing overlay marker file\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"PrivateUsers",
".",
"Shift",
">",
"0",
"{",
"uidrangeBytes",
":=",
"cfg",
".",
"PrivateUsers",
".",
"Serialize",
"(",
")",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"common",
".",
"PrivateUsersPreparedFilename",
")",
",",
"uidrangeBytes",
",",
"common",
".",
"DefaultRegularFilePerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error writing userns marker file\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Prepare sets up a pod based on the given config.
|
[
"Prepare",
"sets",
"up",
"a",
"pod",
"based",
"on",
"the",
"given",
"config",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L408-L468
|
train
|
rkt/rkt
|
stage0/run.go
|
setupAppImage
|
func setupAppImage(cfg RunConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) error {
ad := common.AppPath(cdir, appName)
if useOverlay {
err := os.MkdirAll(ad, common.DefaultRegularDirPerm)
if err != nil {
return errwrap.Wrap(errors.New("error creating image directory"), err)
}
treeStoreID, err := ioutil.ReadFile(common.AppTreeStoreIDPath(cdir, appName))
if err != nil {
return err
}
if err := copyAppManifest(cdir, appName, ad); err != nil {
return err
}
if err := overlayRender(cfg, string(treeStoreID), cdir, ad, appName.String()); err != nil {
return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err)
}
}
return ensureMtabExists(filepath.Join(ad, "rootfs"))
}
|
go
|
func setupAppImage(cfg RunConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) error {
ad := common.AppPath(cdir, appName)
if useOverlay {
err := os.MkdirAll(ad, common.DefaultRegularDirPerm)
if err != nil {
return errwrap.Wrap(errors.New("error creating image directory"), err)
}
treeStoreID, err := ioutil.ReadFile(common.AppTreeStoreIDPath(cdir, appName))
if err != nil {
return err
}
if err := copyAppManifest(cdir, appName, ad); err != nil {
return err
}
if err := overlayRender(cfg, string(treeStoreID), cdir, ad, appName.String()); err != nil {
return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err)
}
}
return ensureMtabExists(filepath.Join(ad, "rootfs"))
}
|
[
"func",
"setupAppImage",
"(",
"cfg",
"RunConfig",
",",
"appName",
"types",
".",
"ACName",
",",
"img",
"types",
".",
"Hash",
",",
"cdir",
"string",
",",
"useOverlay",
"bool",
")",
"error",
"{",
"ad",
":=",
"common",
".",
"AppPath",
"(",
"cdir",
",",
"appName",
")",
"\n",
"if",
"useOverlay",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"ad",
",",
"common",
".",
"DefaultRegularDirPerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error creating image directory\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"treeStoreID",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"common",
".",
"AppTreeStoreIDPath",
"(",
"cdir",
",",
"appName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"copyAppManifest",
"(",
"cdir",
",",
"appName",
",",
"ad",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"overlayRender",
"(",
"cfg",
",",
"string",
"(",
"treeStoreID",
")",
",",
"cdir",
",",
"ad",
",",
"appName",
".",
"String",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error rendering overlay filesystem\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ensureMtabExists",
"(",
"filepath",
".",
"Join",
"(",
"ad",
",",
"\"rootfs\"",
")",
")",
"\n",
"}"
] |
// setupAppImage mounts the overlay filesystem for the app image that
// corresponds to the given hash if useOverlay is true.
// It also creates an mtab file in the application's rootfs if one is not
// present.
|
[
"setupAppImage",
"mounts",
"the",
"overlay",
"filesystem",
"for",
"the",
"app",
"image",
"that",
"corresponds",
"to",
"the",
"given",
"hash",
"if",
"useOverlay",
"is",
"true",
".",
"It",
"also",
"creates",
"an",
"mtab",
"file",
"in",
"the",
"application",
"s",
"rootfs",
"if",
"one",
"is",
"not",
"present",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L773-L792
|
train
|
rkt/rkt
|
stage0/run.go
|
prepareStage1Image
|
func prepareStage1Image(cfg PrepareConfig, cdir string) error {
s1 := common.Stage1ImagePath(cdir)
if err := os.MkdirAll(s1, common.DefaultRegularDirPerm); err != nil {
return errwrap.Wrap(errors.New("error creating stage1 directory"), err)
}
treeStoreID, _, err := cfg.TreeStore.Render(cfg.Stage1Image.String(), false)
if err != nil {
return errwrap.Wrap(errors.New("error rendering tree image"), err)
}
if err := writeManifest(*cfg.CommonConfig, cfg.Stage1Image, s1); err != nil {
return errwrap.Wrap(errors.New("error writing manifest"), err)
}
if !cfg.UseOverlay {
destRootfs := filepath.Join(s1, "rootfs")
cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID)
if err := fileutil.CopyTree(cachedTreePath, destRootfs, cfg.PrivateUsers); err != nil {
return errwrap.Wrap(errors.New("error rendering ACI"), err)
}
}
fn := path.Join(cdir, common.Stage1TreeStoreIDFilename)
if err := ioutil.WriteFile(fn, []byte(treeStoreID), common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing stage1 treeStoreID"), err)
}
return nil
}
|
go
|
func prepareStage1Image(cfg PrepareConfig, cdir string) error {
s1 := common.Stage1ImagePath(cdir)
if err := os.MkdirAll(s1, common.DefaultRegularDirPerm); err != nil {
return errwrap.Wrap(errors.New("error creating stage1 directory"), err)
}
treeStoreID, _, err := cfg.TreeStore.Render(cfg.Stage1Image.String(), false)
if err != nil {
return errwrap.Wrap(errors.New("error rendering tree image"), err)
}
if err := writeManifest(*cfg.CommonConfig, cfg.Stage1Image, s1); err != nil {
return errwrap.Wrap(errors.New("error writing manifest"), err)
}
if !cfg.UseOverlay {
destRootfs := filepath.Join(s1, "rootfs")
cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID)
if err := fileutil.CopyTree(cachedTreePath, destRootfs, cfg.PrivateUsers); err != nil {
return errwrap.Wrap(errors.New("error rendering ACI"), err)
}
}
fn := path.Join(cdir, common.Stage1TreeStoreIDFilename)
if err := ioutil.WriteFile(fn, []byte(treeStoreID), common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing stage1 treeStoreID"), err)
}
return nil
}
|
[
"func",
"prepareStage1Image",
"(",
"cfg",
"PrepareConfig",
",",
"cdir",
"string",
")",
"error",
"{",
"s1",
":=",
"common",
".",
"Stage1ImagePath",
"(",
"cdir",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"s1",
",",
"common",
".",
"DefaultRegularDirPerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error creating stage1 directory\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"treeStoreID",
",",
"_",
",",
"err",
":=",
"cfg",
".",
"TreeStore",
".",
"Render",
"(",
"cfg",
".",
"Stage1Image",
".",
"String",
"(",
")",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error rendering tree image\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"writeManifest",
"(",
"*",
"cfg",
".",
"CommonConfig",
",",
"cfg",
".",
"Stage1Image",
",",
"s1",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error writing manifest\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"cfg",
".",
"UseOverlay",
"{",
"destRootfs",
":=",
"filepath",
".",
"Join",
"(",
"s1",
",",
"\"rootfs\"",
")",
"\n",
"cachedTreePath",
":=",
"cfg",
".",
"TreeStore",
".",
"GetRootFS",
"(",
"treeStoreID",
")",
"\n",
"if",
"err",
":=",
"fileutil",
".",
"CopyTree",
"(",
"cachedTreePath",
",",
"destRootfs",
",",
"cfg",
".",
"PrivateUsers",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error rendering ACI\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fn",
":=",
"path",
".",
"Join",
"(",
"cdir",
",",
"common",
".",
"Stage1TreeStoreIDFilename",
")",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"fn",
",",
"[",
"]",
"byte",
"(",
"treeStoreID",
")",
",",
"common",
".",
"DefaultRegularFilePerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error writing stage1 treeStoreID\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// prepareStage1Image renders and verifies tree cache of the given hash
// when using overlay.
// When useOverlay is false, it attempts to render and expand the stage1.
|
[
"prepareStage1Image",
"renders",
"and",
"verifies",
"tree",
"cache",
"of",
"the",
"given",
"hash",
"when",
"using",
"overlay",
".",
"When",
"useOverlay",
"is",
"false",
"it",
"attempts",
"to",
"render",
"and",
"expand",
"the",
"stage1",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L830-L858
|
train
|
rkt/rkt
|
stage0/run.go
|
setupStage1Image
|
func setupStage1Image(cfg RunConfig, cdir string, useOverlay bool) error {
s1 := common.Stage1ImagePath(cdir)
if useOverlay {
treeStoreID, err := ioutil.ReadFile(filepath.Join(cdir, common.Stage1TreeStoreIDFilename))
if err != nil {
return err
}
// pass an empty appName
if err := overlayRender(cfg, string(treeStoreID), cdir, s1, ""); err != nil {
return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err)
}
// we will later read the status from the upper layer of the overlay fs
// force the status directory to be there by touching it
statusPath := filepath.Join(s1, "rootfs", "rkt", "status")
if err := os.Chtimes(statusPath, time.Now(), time.Now()); err != nil {
return errwrap.Wrap(errors.New("error touching status dir"), err)
}
}
return nil
}
|
go
|
func setupStage1Image(cfg RunConfig, cdir string, useOverlay bool) error {
s1 := common.Stage1ImagePath(cdir)
if useOverlay {
treeStoreID, err := ioutil.ReadFile(filepath.Join(cdir, common.Stage1TreeStoreIDFilename))
if err != nil {
return err
}
// pass an empty appName
if err := overlayRender(cfg, string(treeStoreID), cdir, s1, ""); err != nil {
return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err)
}
// we will later read the status from the upper layer of the overlay fs
// force the status directory to be there by touching it
statusPath := filepath.Join(s1, "rootfs", "rkt", "status")
if err := os.Chtimes(statusPath, time.Now(), time.Now()); err != nil {
return errwrap.Wrap(errors.New("error touching status dir"), err)
}
}
return nil
}
|
[
"func",
"setupStage1Image",
"(",
"cfg",
"RunConfig",
",",
"cdir",
"string",
",",
"useOverlay",
"bool",
")",
"error",
"{",
"s1",
":=",
"common",
".",
"Stage1ImagePath",
"(",
"cdir",
")",
"\n",
"if",
"useOverlay",
"{",
"treeStoreID",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"cdir",
",",
"common",
".",
"Stage1TreeStoreIDFilename",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"overlayRender",
"(",
"cfg",
",",
"string",
"(",
"treeStoreID",
")",
",",
"cdir",
",",
"s1",
",",
"\"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error rendering overlay filesystem\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"statusPath",
":=",
"filepath",
".",
"Join",
"(",
"s1",
",",
"\"rootfs\"",
",",
"\"rkt\"",
",",
"\"status\"",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"Chtimes",
"(",
"statusPath",
",",
"time",
".",
"Now",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error touching status dir\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// setupStage1Image mounts the overlay filesystem for stage1.
// When useOverlay is false it is a noop
|
[
"setupStage1Image",
"mounts",
"the",
"overlay",
"filesystem",
"for",
"stage1",
".",
"When",
"useOverlay",
"is",
"false",
"it",
"is",
"a",
"noop"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L862-L884
|
train
|
rkt/rkt
|
stage0/run.go
|
writeManifest
|
func writeManifest(cfg CommonConfig, img types.Hash, dest string) error {
mb, err := cfg.Store.GetImageManifestJSON(img.String())
if err != nil {
return err
}
debug("Writing image manifest")
if err := ioutil.WriteFile(filepath.Join(dest, "manifest"), mb, common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing image manifest"), err)
}
return nil
}
|
go
|
func writeManifest(cfg CommonConfig, img types.Hash, dest string) error {
mb, err := cfg.Store.GetImageManifestJSON(img.String())
if err != nil {
return err
}
debug("Writing image manifest")
if err := ioutil.WriteFile(filepath.Join(dest, "manifest"), mb, common.DefaultRegularFilePerm); err != nil {
return errwrap.Wrap(errors.New("error writing image manifest"), err)
}
return nil
}
|
[
"func",
"writeManifest",
"(",
"cfg",
"CommonConfig",
",",
"img",
"types",
".",
"Hash",
",",
"dest",
"string",
")",
"error",
"{",
"mb",
",",
"err",
":=",
"cfg",
".",
"Store",
".",
"GetImageManifestJSON",
"(",
"img",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"debug",
"(",
"\"Writing image manifest\"",
")",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"dest",
",",
"\"manifest\"",
")",
",",
"mb",
",",
"common",
".",
"DefaultRegularFilePerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error writing image manifest\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// writeManifest takes an img ID and writes the corresponding manifest in dest
|
[
"writeManifest",
"takes",
"an",
"img",
"ID",
"and",
"writes",
"the",
"corresponding",
"manifest",
"in",
"dest"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L887-L899
|
train
|
rkt/rkt
|
stage0/run.go
|
copyAppManifest
|
func copyAppManifest(cdir string, appName types.ACName, dest string) error {
appInfoDir := common.AppInfoPath(cdir, appName)
sourceFn := filepath.Join(appInfoDir, "manifest")
destFn := filepath.Join(dest, "manifest")
if err := fileutil.CopyRegularFile(sourceFn, destFn); err != nil {
return errwrap.Wrap(errors.New("error copying image manifest"), err)
}
return nil
}
|
go
|
func copyAppManifest(cdir string, appName types.ACName, dest string) error {
appInfoDir := common.AppInfoPath(cdir, appName)
sourceFn := filepath.Join(appInfoDir, "manifest")
destFn := filepath.Join(dest, "manifest")
if err := fileutil.CopyRegularFile(sourceFn, destFn); err != nil {
return errwrap.Wrap(errors.New("error copying image manifest"), err)
}
return nil
}
|
[
"func",
"copyAppManifest",
"(",
"cdir",
"string",
",",
"appName",
"types",
".",
"ACName",
",",
"dest",
"string",
")",
"error",
"{",
"appInfoDir",
":=",
"common",
".",
"AppInfoPath",
"(",
"cdir",
",",
"appName",
")",
"\n",
"sourceFn",
":=",
"filepath",
".",
"Join",
"(",
"appInfoDir",
",",
"\"manifest\"",
")",
"\n",
"destFn",
":=",
"filepath",
".",
"Join",
"(",
"dest",
",",
"\"manifest\"",
")",
"\n",
"if",
"err",
":=",
"fileutil",
".",
"CopyRegularFile",
"(",
"sourceFn",
",",
"destFn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error copying image manifest\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// copyAppManifest copies to saved image manifest for the given appName and
// writes it in the dest directory.
|
[
"copyAppManifest",
"copies",
"to",
"saved",
"image",
"manifest",
"for",
"the",
"given",
"appName",
"and",
"writes",
"it",
"in",
"the",
"dest",
"directory",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L903-L911
|
train
|
rkt/rkt
|
stage0/run.go
|
overlayRender
|
func overlayRender(cfg RunConfig, treeStoreID string, cdir string, dest string, appName string) error {
cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID)
mc, err := prepareOverlay(cachedTreePath, treeStoreID, cdir, dest, appName, cfg.MountLabel,
cfg.RktGid, common.DefaultRegularDirPerm)
if err != nil {
return errwrap.Wrap(errors.New("problem preparing overlay directories"), err)
}
if err = overlay.Mount(mc); err != nil {
return errwrap.Wrap(errors.New("problem mounting overlay filesystem"), err)
}
return nil
}
|
go
|
func overlayRender(cfg RunConfig, treeStoreID string, cdir string, dest string, appName string) error {
cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID)
mc, err := prepareOverlay(cachedTreePath, treeStoreID, cdir, dest, appName, cfg.MountLabel,
cfg.RktGid, common.DefaultRegularDirPerm)
if err != nil {
return errwrap.Wrap(errors.New("problem preparing overlay directories"), err)
}
if err = overlay.Mount(mc); err != nil {
return errwrap.Wrap(errors.New("problem mounting overlay filesystem"), err)
}
return nil
}
|
[
"func",
"overlayRender",
"(",
"cfg",
"RunConfig",
",",
"treeStoreID",
"string",
",",
"cdir",
"string",
",",
"dest",
"string",
",",
"appName",
"string",
")",
"error",
"{",
"cachedTreePath",
":=",
"cfg",
".",
"TreeStore",
".",
"GetRootFS",
"(",
"treeStoreID",
")",
"\n",
"mc",
",",
"err",
":=",
"prepareOverlay",
"(",
"cachedTreePath",
",",
"treeStoreID",
",",
"cdir",
",",
"dest",
",",
"appName",
",",
"cfg",
".",
"MountLabel",
",",
"cfg",
".",
"RktGid",
",",
"common",
".",
"DefaultRegularDirPerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"problem preparing overlay directories\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"overlay",
".",
"Mount",
"(",
"mc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"problem mounting overlay filesystem\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// overlayRender renders the image that corresponds to the given hash using the
// overlay filesystem. It mounts an overlay filesystem from the cached tree of
// the image as rootfs.
|
[
"overlayRender",
"renders",
"the",
"image",
"that",
"corresponds",
"to",
"the",
"given",
"hash",
"using",
"the",
"overlay",
"filesystem",
".",
"It",
"mounts",
"an",
"overlay",
"filesystem",
"from",
"the",
"cached",
"tree",
"of",
"the",
"image",
"as",
"rootfs",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L916-L928
|
train
|
rkt/rkt
|
stage0/run.go
|
prepareOverlay
|
func prepareOverlay(lower, treeStoreID, cdir, dest, appName, lbl string,
gid int, fm os.FileMode) (*overlay.MountCfg, error) {
fi, err := os.Stat(lower)
if err != nil {
return nil, err
}
imgMode := fi.Mode()
dst := path.Join(dest, "rootfs")
if err := os.MkdirAll(dst, imgMode); err != nil {
return nil, err
}
overlayDir := path.Join(cdir, "overlay")
if err := os.MkdirAll(overlayDir, fm); err != nil {
return nil, err
}
// Since the parent directory (rkt/pods/$STATE/$POD_UUID) has the 'S_ISGID' bit, here
// we need to explicitly turn the bit off when creating this overlay
// directory so that it won't inherit the bit. Otherwise the files
// created by users within the pod will inherit the 'S_ISGID' bit
// as well.
if err := os.Chmod(overlayDir, fm); err != nil {
return nil, err
}
imgDir := path.Join(overlayDir, treeStoreID)
if err := os.MkdirAll(imgDir, fm); err != nil {
return nil, err
}
// Also make 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID' to be readable by 'rkt' group
// As 'rkt' status will read the 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID/upper/rkt/status/$APP'
// to get exgid
if err := os.Chown(imgDir, -1, gid); err != nil {
return nil, err
}
upper := path.Join(imgDir, "upper", appName)
if err := os.MkdirAll(upper, imgMode); err != nil {
return nil, err
}
if err := label.SetFileLabel(upper, lbl); err != nil {
return nil, err
}
work := path.Join(imgDir, "work", appName)
if err := os.MkdirAll(work, fm); err != nil {
return nil, err
}
if err := label.SetFileLabel(work, lbl); err != nil {
return nil, err
}
return &overlay.MountCfg{lower, upper, work, dst, lbl}, nil
}
|
go
|
func prepareOverlay(lower, treeStoreID, cdir, dest, appName, lbl string,
gid int, fm os.FileMode) (*overlay.MountCfg, error) {
fi, err := os.Stat(lower)
if err != nil {
return nil, err
}
imgMode := fi.Mode()
dst := path.Join(dest, "rootfs")
if err := os.MkdirAll(dst, imgMode); err != nil {
return nil, err
}
overlayDir := path.Join(cdir, "overlay")
if err := os.MkdirAll(overlayDir, fm); err != nil {
return nil, err
}
// Since the parent directory (rkt/pods/$STATE/$POD_UUID) has the 'S_ISGID' bit, here
// we need to explicitly turn the bit off when creating this overlay
// directory so that it won't inherit the bit. Otherwise the files
// created by users within the pod will inherit the 'S_ISGID' bit
// as well.
if err := os.Chmod(overlayDir, fm); err != nil {
return nil, err
}
imgDir := path.Join(overlayDir, treeStoreID)
if err := os.MkdirAll(imgDir, fm); err != nil {
return nil, err
}
// Also make 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID' to be readable by 'rkt' group
// As 'rkt' status will read the 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID/upper/rkt/status/$APP'
// to get exgid
if err := os.Chown(imgDir, -1, gid); err != nil {
return nil, err
}
upper := path.Join(imgDir, "upper", appName)
if err := os.MkdirAll(upper, imgMode); err != nil {
return nil, err
}
if err := label.SetFileLabel(upper, lbl); err != nil {
return nil, err
}
work := path.Join(imgDir, "work", appName)
if err := os.MkdirAll(work, fm); err != nil {
return nil, err
}
if err := label.SetFileLabel(work, lbl); err != nil {
return nil, err
}
return &overlay.MountCfg{lower, upper, work, dst, lbl}, nil
}
|
[
"func",
"prepareOverlay",
"(",
"lower",
",",
"treeStoreID",
",",
"cdir",
",",
"dest",
",",
"appName",
",",
"lbl",
"string",
",",
"gid",
"int",
",",
"fm",
"os",
".",
"FileMode",
")",
"(",
"*",
"overlay",
".",
"MountCfg",
",",
"error",
")",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"lower",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"imgMode",
":=",
"fi",
".",
"Mode",
"(",
")",
"\n",
"dst",
":=",
"path",
".",
"Join",
"(",
"dest",
",",
"\"rootfs\"",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dst",
",",
"imgMode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"overlayDir",
":=",
"path",
".",
"Join",
"(",
"cdir",
",",
"\"overlay\"",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"overlayDir",
",",
"fm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Chmod",
"(",
"overlayDir",
",",
"fm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"imgDir",
":=",
"path",
".",
"Join",
"(",
"overlayDir",
",",
"treeStoreID",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"imgDir",
",",
"fm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Chown",
"(",
"imgDir",
",",
"-",
"1",
",",
"gid",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"upper",
":=",
"path",
".",
"Join",
"(",
"imgDir",
",",
"\"upper\"",
",",
"appName",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"upper",
",",
"imgMode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"label",
".",
"SetFileLabel",
"(",
"upper",
",",
"lbl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"work",
":=",
"path",
".",
"Join",
"(",
"imgDir",
",",
"\"work\"",
",",
"appName",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"work",
",",
"fm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"label",
".",
"SetFileLabel",
"(",
"work",
",",
"lbl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"overlay",
".",
"MountCfg",
"{",
"lower",
",",
"upper",
",",
"work",
",",
"dst",
",",
"lbl",
"}",
",",
"nil",
"\n",
"}"
] |
// prepateOverlay sets up the needed directories, files and permissions for the
// overlay-rendered pods
|
[
"prepateOverlay",
"sets",
"up",
"the",
"needed",
"directories",
"files",
"and",
"permissions",
"for",
"the",
"overlay",
"-",
"rendered",
"pods"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L932-L987
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
NewStore
|
func NewStore(dir string, store *imagestore.Store) (*Store, error) {
// TODO(sgotti) backward compatibility with the current tree store paths. Needs a migration path to better paths.
ts := &Store{dir: filepath.Join(dir, "tree"), store: store}
ts.lockDir = filepath.Join(dir, "treestorelocks")
if err := os.MkdirAll(ts.lockDir, 0755); err != nil {
return nil, err
}
return ts, nil
}
|
go
|
func NewStore(dir string, store *imagestore.Store) (*Store, error) {
// TODO(sgotti) backward compatibility with the current tree store paths. Needs a migration path to better paths.
ts := &Store{dir: filepath.Join(dir, "tree"), store: store}
ts.lockDir = filepath.Join(dir, "treestorelocks")
if err := os.MkdirAll(ts.lockDir, 0755); err != nil {
return nil, err
}
return ts, nil
}
|
[
"func",
"NewStore",
"(",
"dir",
"string",
",",
"store",
"*",
"imagestore",
".",
"Store",
")",
"(",
"*",
"Store",
",",
"error",
")",
"{",
"ts",
":=",
"&",
"Store",
"{",
"dir",
":",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"tree\"",
")",
",",
"store",
":",
"store",
"}",
"\n",
"ts",
".",
"lockDir",
"=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"treestorelocks\"",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"ts",
".",
"lockDir",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"ts",
",",
"nil",
"\n",
"}"
] |
// NewStore creates a Store for managing filesystem trees, including the dependency graph resolution of the underlying image layers.
|
[
"NewStore",
"creates",
"a",
"Store",
"for",
"managing",
"filesystem",
"trees",
"including",
"the",
"dependency",
"graph",
"resolution",
"of",
"the",
"underlying",
"image",
"layers",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L73-L82
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
GetID
|
func (ts *Store) GetID(key string) (string, error) {
hash, err := types.NewHash(key)
if err != nil {
return "", err
}
images, err := acirenderer.CreateDepListFromImageID(*hash, ts.store)
if err != nil {
return "", err
}
var keys []string
for _, image := range images {
keys = append(keys, image.Key)
}
imagesString := strings.Join(keys, ",")
h := sha512.New()
h.Write([]byte(imagesString))
return "deps-" + hashToKey(h), nil
}
|
go
|
func (ts *Store) GetID(key string) (string, error) {
hash, err := types.NewHash(key)
if err != nil {
return "", err
}
images, err := acirenderer.CreateDepListFromImageID(*hash, ts.store)
if err != nil {
return "", err
}
var keys []string
for _, image := range images {
keys = append(keys, image.Key)
}
imagesString := strings.Join(keys, ",")
h := sha512.New()
h.Write([]byte(imagesString))
return "deps-" + hashToKey(h), nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"GetID",
"(",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"hash",
",",
"err",
":=",
"types",
".",
"NewHash",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"images",
",",
"err",
":=",
"acirenderer",
".",
"CreateDepListFromImageID",
"(",
"*",
"hash",
",",
"ts",
".",
"store",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"var",
"keys",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"image",
":=",
"range",
"images",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"image",
".",
"Key",
")",
"\n",
"}",
"\n",
"imagesString",
":=",
"strings",
".",
"Join",
"(",
"keys",
",",
"\",\"",
")",
"\n",
"h",
":=",
"sha512",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"imagesString",
")",
")",
"\n",
"return",
"\"deps-\"",
"+",
"hashToKey",
"(",
"h",
")",
",",
"nil",
"\n",
"}"
] |
// GetID calculates the treestore ID for the given image key.
// The treeStoreID is computed as an hash of the flattened dependency tree
// image keys. In this way the ID may change for the same key if the image's
// dependencies change.
|
[
"GetID",
"calculates",
"the",
"treestore",
"ID",
"for",
"the",
"given",
"image",
"key",
".",
"The",
"treeStoreID",
"is",
"computed",
"as",
"an",
"hash",
"of",
"the",
"flattened",
"dependency",
"tree",
"image",
"keys",
".",
"In",
"this",
"way",
"the",
"ID",
"may",
"change",
"for",
"the",
"same",
"key",
"if",
"the",
"image",
"s",
"dependencies",
"change",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L88-L106
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
Render
|
func (ts *Store) Render(key string, rebuild bool) (id string, hash string, err error) {
id, err = ts.GetID(key)
if err != nil {
return "", "", errwrap.Wrap(errors.New("cannot calculate treestore id"), err)
}
// this lock references the treestore dir for the specified id.
treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id)
if err != nil {
return "", "", errwrap.Wrap(errors.New("error locking tree store"), err)
}
defer treeStoreKeyLock.Close()
if !rebuild {
rendered, err := ts.IsRendered(id)
if err != nil {
return "", "", errwrap.Wrap(errors.New("cannot determine if tree is already rendered"), err)
}
if rendered {
return id, "", nil
}
}
// Firstly remove a possible partial treestore if existing.
// This is needed as a previous ACI removal operation could have failed
// cleaning the tree store leaving some stale files.
if err := ts.remove(id); err != nil {
return "", "", err
}
if hash, err = ts.render(id, key); err != nil {
return "", "", err
}
return id, hash, nil
}
|
go
|
func (ts *Store) Render(key string, rebuild bool) (id string, hash string, err error) {
id, err = ts.GetID(key)
if err != nil {
return "", "", errwrap.Wrap(errors.New("cannot calculate treestore id"), err)
}
// this lock references the treestore dir for the specified id.
treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id)
if err != nil {
return "", "", errwrap.Wrap(errors.New("error locking tree store"), err)
}
defer treeStoreKeyLock.Close()
if !rebuild {
rendered, err := ts.IsRendered(id)
if err != nil {
return "", "", errwrap.Wrap(errors.New("cannot determine if tree is already rendered"), err)
}
if rendered {
return id, "", nil
}
}
// Firstly remove a possible partial treestore if existing.
// This is needed as a previous ACI removal operation could have failed
// cleaning the tree store leaving some stale files.
if err := ts.remove(id); err != nil {
return "", "", err
}
if hash, err = ts.render(id, key); err != nil {
return "", "", err
}
return id, hash, nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"Render",
"(",
"key",
"string",
",",
"rebuild",
"bool",
")",
"(",
"id",
"string",
",",
"hash",
"string",
",",
"err",
"error",
")",
"{",
"id",
",",
"err",
"=",
"ts",
".",
"GetID",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot calculate treestore id\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"treeStoreKeyLock",
",",
"err",
":=",
"lock",
".",
"ExclusiveKeyLock",
"(",
"ts",
".",
"lockDir",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error locking tree store\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"treeStoreKeyLock",
".",
"Close",
"(",
")",
"\n",
"if",
"!",
"rebuild",
"{",
"rendered",
",",
"err",
":=",
"ts",
".",
"IsRendered",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot determine if tree is already rendered\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"rendered",
"{",
"return",
"id",
",",
"\"\"",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ts",
".",
"remove",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"hash",
",",
"err",
"=",
"ts",
".",
"render",
"(",
"id",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"id",
",",
"hash",
",",
"nil",
"\n",
"}"
] |
// Render renders a treestore for the given image key if it's not
// already fully rendered.
// Users of treestore should call s.Render before using it to ensure
// that the treestore is completely rendered.
// Returns the id and hash of the rendered treestore if it is newly rendered,
// and only the id if it is already rendered.
|
[
"Render",
"renders",
"a",
"treestore",
"for",
"the",
"given",
"image",
"key",
"if",
"it",
"s",
"not",
"already",
"fully",
"rendered",
".",
"Users",
"of",
"treestore",
"should",
"call",
"s",
".",
"Render",
"before",
"using",
"it",
"to",
"ensure",
"that",
"the",
"treestore",
"is",
"completely",
"rendered",
".",
"Returns",
"the",
"id",
"and",
"hash",
"of",
"the",
"rendered",
"treestore",
"if",
"it",
"is",
"newly",
"rendered",
"and",
"only",
"the",
"id",
"if",
"it",
"is",
"already",
"rendered",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L114-L147
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
Check
|
func (ts *Store) Check(id string) (string, error) {
treeStoreKeyLock, err := lock.SharedKeyLock(ts.lockDir, id)
if err != nil {
return "", errwrap.Wrap(errors.New("error locking tree store"), err)
}
defer treeStoreKeyLock.Close()
return ts.check(id)
}
|
go
|
func (ts *Store) Check(id string) (string, error) {
treeStoreKeyLock, err := lock.SharedKeyLock(ts.lockDir, id)
if err != nil {
return "", errwrap.Wrap(errors.New("error locking tree store"), err)
}
defer treeStoreKeyLock.Close()
return ts.check(id)
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"Check",
"(",
"id",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"treeStoreKeyLock",
",",
"err",
":=",
"lock",
".",
"SharedKeyLock",
"(",
"ts",
".",
"lockDir",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error locking tree store\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"treeStoreKeyLock",
".",
"Close",
"(",
")",
"\n",
"return",
"ts",
".",
"check",
"(",
"id",
")",
"\n",
"}"
] |
// Check verifies the treestore consistency for the specified id.
|
[
"Check",
"verifies",
"the",
"treestore",
"consistency",
"for",
"the",
"specified",
"id",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L150-L158
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
Remove
|
func (ts *Store) Remove(id string) error {
treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id)
if err != nil {
return errwrap.Wrap(errors.New("error locking tree store"), err)
}
defer treeStoreKeyLock.Close()
if err := ts.remove(id); err != nil {
return errwrap.Wrap(errors.New("error removing the tree store"), err)
}
return nil
}
|
go
|
func (ts *Store) Remove(id string) error {
treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id)
if err != nil {
return errwrap.Wrap(errors.New("error locking tree store"), err)
}
defer treeStoreKeyLock.Close()
if err := ts.remove(id); err != nil {
return errwrap.Wrap(errors.New("error removing the tree store"), err)
}
return nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"Remove",
"(",
"id",
"string",
")",
"error",
"{",
"treeStoreKeyLock",
",",
"err",
":=",
"lock",
".",
"ExclusiveKeyLock",
"(",
"ts",
".",
"lockDir",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error locking tree store\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"treeStoreKeyLock",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
":=",
"ts",
".",
"remove",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error removing the tree store\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Remove removes the rendered image in tree store with the given id.
|
[
"Remove",
"removes",
"the",
"rendered",
"image",
"in",
"tree",
"store",
"with",
"the",
"given",
"id",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L161-L173
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
remove
|
func (ts *Store) remove(id string) error {
treepath := ts.GetPath(id)
// If tree path doesn't exist we're done
_, err := os.Stat(treepath)
if err != nil && os.IsNotExist(err) {
return nil
}
if err != nil {
return errwrap.Wrap(errors.New("failed to open tree store directory"), err)
}
renderedFilePath := filepath.Join(treepath, renderedfilename)
// The "rendered" flag file should be the firstly removed file. So if
// the removal ends with some error leaving some stale files IsRendered()
// will return false.
_, err = os.Stat(renderedFilePath)
if err != nil && !os.IsNotExist(err) {
return err
}
if !os.IsNotExist(err) {
err := os.Remove(renderedFilePath)
// Ensure that the treepath directory is fsynced after removing the
// "rendered" flag file
f, err := os.Open(treepath)
if err != nil {
return errwrap.Wrap(errors.New("failed to open tree store directory"), err)
}
defer f.Close()
err = f.Sync()
if err != nil {
return errwrap.Wrap(errors.New("failed to sync tree store directory"), err)
}
}
// Ignore error retrieving image hash
key, _ := ts.GetImageHash(id)
if err := os.RemoveAll(treepath); err != nil {
return err
}
if key != "" {
return ts.store.UpdateTreeStoreSize(key, 0)
}
return nil
}
|
go
|
func (ts *Store) remove(id string) error {
treepath := ts.GetPath(id)
// If tree path doesn't exist we're done
_, err := os.Stat(treepath)
if err != nil && os.IsNotExist(err) {
return nil
}
if err != nil {
return errwrap.Wrap(errors.New("failed to open tree store directory"), err)
}
renderedFilePath := filepath.Join(treepath, renderedfilename)
// The "rendered" flag file should be the firstly removed file. So if
// the removal ends with some error leaving some stale files IsRendered()
// will return false.
_, err = os.Stat(renderedFilePath)
if err != nil && !os.IsNotExist(err) {
return err
}
if !os.IsNotExist(err) {
err := os.Remove(renderedFilePath)
// Ensure that the treepath directory is fsynced after removing the
// "rendered" flag file
f, err := os.Open(treepath)
if err != nil {
return errwrap.Wrap(errors.New("failed to open tree store directory"), err)
}
defer f.Close()
err = f.Sync()
if err != nil {
return errwrap.Wrap(errors.New("failed to sync tree store directory"), err)
}
}
// Ignore error retrieving image hash
key, _ := ts.GetImageHash(id)
if err := os.RemoveAll(treepath); err != nil {
return err
}
if key != "" {
return ts.store.UpdateTreeStoreSize(key, 0)
}
return nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"remove",
"(",
"id",
"string",
")",
"error",
"{",
"treepath",
":=",
"ts",
".",
"GetPath",
"(",
"id",
")",
"\n",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"treepath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"failed to open tree store directory\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"renderedFilePath",
":=",
"filepath",
".",
"Join",
"(",
"treepath",
",",
"renderedfilename",
")",
"\n",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"renderedFilePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"err",
":=",
"os",
".",
"Remove",
"(",
"renderedFilePath",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"treepath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"failed to open tree store directory\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"f",
".",
"Sync",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"failed to sync tree store directory\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"key",
",",
"_",
":=",
"ts",
".",
"GetImageHash",
"(",
"id",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"treepath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"key",
"!=",
"\"\"",
"{",
"return",
"ts",
".",
"store",
".",
"UpdateTreeStoreSize",
"(",
"key",
",",
"0",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// remove cleans the directory for the provided id
|
[
"remove",
"cleans",
"the",
"directory",
"for",
"the",
"provided",
"id"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L270-L316
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
IsRendered
|
func (ts *Store) IsRendered(id string) (bool, error) {
// if the "rendered" flag file exists, assume that the store is already
// fully rendered.
treepath := ts.GetPath(id)
_, err := os.Stat(filepath.Join(treepath, renderedfilename))
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
|
go
|
func (ts *Store) IsRendered(id string) (bool, error) {
// if the "rendered" flag file exists, assume that the store is already
// fully rendered.
treepath := ts.GetPath(id)
_, err := os.Stat(filepath.Join(treepath, renderedfilename))
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"IsRendered",
"(",
"id",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"treepath",
":=",
"ts",
".",
"GetPath",
"(",
"id",
")",
"\n",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"filepath",
".",
"Join",
"(",
"treepath",
",",
"renderedfilename",
")",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// IsRendered checks if the tree store with the provided id is fully rendered
|
[
"IsRendered",
"checks",
"if",
"the",
"tree",
"store",
"with",
"the",
"provided",
"id",
"is",
"fully",
"rendered"
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L319-L331
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
Hash
|
func (ts *Store) Hash(id string) (string, error) {
treepath := ts.GetPath(id)
hash := sha512.New()
iw := newHashWriter(hash)
err := filepath.Walk(treepath, buildWalker(treepath, iw))
if err != nil {
return "", errwrap.Wrap(errors.New("error walking rootfs"), err)
}
hashstring := hashToKey(hash)
return hashstring, nil
}
|
go
|
func (ts *Store) Hash(id string) (string, error) {
treepath := ts.GetPath(id)
hash := sha512.New()
iw := newHashWriter(hash)
err := filepath.Walk(treepath, buildWalker(treepath, iw))
if err != nil {
return "", errwrap.Wrap(errors.New("error walking rootfs"), err)
}
hashstring := hashToKey(hash)
return hashstring, nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"Hash",
"(",
"id",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"treepath",
":=",
"ts",
".",
"GetPath",
"(",
"id",
")",
"\n",
"hash",
":=",
"sha512",
".",
"New",
"(",
")",
"\n",
"iw",
":=",
"newHashWriter",
"(",
"hash",
")",
"\n",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"treepath",
",",
"buildWalker",
"(",
"treepath",
",",
"iw",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error walking rootfs\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"hashstring",
":=",
"hashToKey",
"(",
"hash",
")",
"\n",
"return",
"hashstring",
",",
"nil",
"\n",
"}"
] |
// Hash calculates an hash of the rendered ACI. It uses the same functions
// used to create a tar but instead of writing the full archive is just
// computes the sha512 sum of the file infos and contents.
|
[
"Hash",
"calculates",
"an",
"hash",
"of",
"the",
"rendered",
"ACI",
".",
"It",
"uses",
"the",
"same",
"functions",
"used",
"to",
"create",
"a",
"tar",
"but",
"instead",
"of",
"writing",
"the",
"full",
"archive",
"is",
"just",
"computes",
"the",
"sha512",
"sum",
"of",
"the",
"file",
"infos",
"and",
"contents",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L350-L363
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
check
|
func (ts *Store) check(id string) (string, error) {
treepath := ts.GetPath(id)
hash, err := ioutil.ReadFile(filepath.Join(treepath, hashfilename))
if err != nil {
return "", errwrap.Wrap(ErrReadHashfile, err)
}
curhash, err := ts.Hash(id)
if err != nil {
return "", errwrap.Wrap(errors.New("cannot calculate tree hash"), err)
}
if curhash != string(hash) {
return "", fmt.Errorf("wrong tree hash: %s, expected: %s", curhash, hash)
}
return curhash, nil
}
|
go
|
func (ts *Store) check(id string) (string, error) {
treepath := ts.GetPath(id)
hash, err := ioutil.ReadFile(filepath.Join(treepath, hashfilename))
if err != nil {
return "", errwrap.Wrap(ErrReadHashfile, err)
}
curhash, err := ts.Hash(id)
if err != nil {
return "", errwrap.Wrap(errors.New("cannot calculate tree hash"), err)
}
if curhash != string(hash) {
return "", fmt.Errorf("wrong tree hash: %s, expected: %s", curhash, hash)
}
return curhash, nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"check",
"(",
"id",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"treepath",
":=",
"ts",
".",
"GetPath",
"(",
"id",
")",
"\n",
"hash",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"treepath",
",",
"hashfilename",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"ErrReadHashfile",
",",
"err",
")",
"\n",
"}",
"\n",
"curhash",
",",
"err",
":=",
"ts",
".",
"Hash",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot calculate tree hash\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"curhash",
"!=",
"string",
"(",
"hash",
")",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"wrong tree hash: %s, expected: %s\"",
",",
"curhash",
",",
"hash",
")",
"\n",
"}",
"\n",
"return",
"curhash",
",",
"nil",
"\n",
"}"
] |
// check calculates the actual rendered ACI's hash and verifies that it matches
// the saved value. Returns the calculated hash.
|
[
"check",
"calculates",
"the",
"actual",
"rendered",
"ACI",
"s",
"hash",
"and",
"verifies",
"that",
"it",
"matches",
"the",
"saved",
"value",
".",
"Returns",
"the",
"calculated",
"hash",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L367-L381
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
Size
|
func (ts *Store) Size(id string) (int64, error) {
sz, err := fileutil.DirSize(ts.GetPath(id))
if err != nil {
return -1, errwrap.Wrap(errors.New("error calculating size"), err)
}
return sz, nil
}
|
go
|
func (ts *Store) Size(id string) (int64, error) {
sz, err := fileutil.DirSize(ts.GetPath(id))
if err != nil {
return -1, errwrap.Wrap(errors.New("error calculating size"), err)
}
return sz, nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"Size",
"(",
"id",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"sz",
",",
"err",
":=",
"fileutil",
".",
"DirSize",
"(",
"ts",
".",
"GetPath",
"(",
"id",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"error calculating size\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"sz",
",",
"nil",
"\n",
"}"
] |
// Size returns the size of the rootfs for the provided id. It is a relatively
// expensive operation, it goes through all the files and adds up their size.
|
[
"Size",
"returns",
"the",
"size",
"of",
"the",
"rootfs",
"for",
"the",
"provided",
"id",
".",
"It",
"is",
"a",
"relatively",
"expensive",
"operation",
"it",
"goes",
"through",
"all",
"the",
"files",
"and",
"adds",
"up",
"their",
"size",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L385-L391
|
train
|
rkt/rkt
|
store/treestore/tree.go
|
GetImageHash
|
func (ts *Store) GetImageHash(id string) (string, error) {
treepath := ts.GetPath(id)
imgHash, err := ioutil.ReadFile(filepath.Join(treepath, imagefilename))
if err != nil {
return "", errwrap.Wrap(errors.New("cannot read image file"), err)
}
return string(imgHash), nil
}
|
go
|
func (ts *Store) GetImageHash(id string) (string, error) {
treepath := ts.GetPath(id)
imgHash, err := ioutil.ReadFile(filepath.Join(treepath, imagefilename))
if err != nil {
return "", errwrap.Wrap(errors.New("cannot read image file"), err)
}
return string(imgHash), nil
}
|
[
"func",
"(",
"ts",
"*",
"Store",
")",
"GetImageHash",
"(",
"id",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"treepath",
":=",
"ts",
".",
"GetPath",
"(",
"id",
")",
"\n",
"imgHash",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"treepath",
",",
"imagefilename",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errwrap",
".",
"Wrap",
"(",
"errors",
".",
"New",
"(",
"\"cannot read image file\"",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"imgHash",
")",
",",
"nil",
"\n",
"}"
] |
// GetImageHash returns the hash of the image that uses the tree store
// identified by id.
|
[
"GetImageHash",
"returns",
"the",
"hash",
"of",
"the",
"image",
"that",
"uses",
"the",
"tree",
"store",
"identified",
"by",
"id",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L395-L404
|
train
|
rkt/rkt
|
pkg/mountinfo/mountinfo.go
|
HasPrefix
|
func HasPrefix(p string) FilterFunc {
return FilterFunc(func(m *Mount) bool {
return strings.HasPrefix(m.MountPoint, p)
})
}
|
go
|
func HasPrefix(p string) FilterFunc {
return FilterFunc(func(m *Mount) bool {
return strings.HasPrefix(m.MountPoint, p)
})
}
|
[
"func",
"HasPrefix",
"(",
"p",
"string",
")",
"FilterFunc",
"{",
"return",
"FilterFunc",
"(",
"func",
"(",
"m",
"*",
"Mount",
")",
"bool",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"m",
".",
"MountPoint",
",",
"p",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// HasPrefix returns a FilterFunc which returns true if
// the mountpoint of a given mount has prefix p, else false.
|
[
"HasPrefix",
"returns",
"a",
"FilterFunc",
"which",
"returns",
"true",
"if",
"the",
"mountpoint",
"of",
"a",
"given",
"mount",
"has",
"prefix",
"p",
"else",
"false",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L32-L36
|
train
|
rkt/rkt
|
pkg/mountinfo/mountinfo.go
|
ParseMounts
|
func ParseMounts(pid uint) (Mounts, error) {
var procPath string
if pid == 0 {
procPath = "/proc/self/mountinfo"
} else {
procPath = fmt.Sprintf("/proc/%d/mountinfo", pid)
}
mi, err := os.Open(procPath)
if err != nil {
return nil, err
}
defer mi.Close()
return parseMountinfo(mi)
}
|
go
|
func ParseMounts(pid uint) (Mounts, error) {
var procPath string
if pid == 0 {
procPath = "/proc/self/mountinfo"
} else {
procPath = fmt.Sprintf("/proc/%d/mountinfo", pid)
}
mi, err := os.Open(procPath)
if err != nil {
return nil, err
}
defer mi.Close()
return parseMountinfo(mi)
}
|
[
"func",
"ParseMounts",
"(",
"pid",
"uint",
")",
"(",
"Mounts",
",",
"error",
")",
"{",
"var",
"procPath",
"string",
"\n",
"if",
"pid",
"==",
"0",
"{",
"procPath",
"=",
"\"/proc/self/mountinfo\"",
"\n",
"}",
"else",
"{",
"procPath",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"/proc/%d/mountinfo\"",
",",
"pid",
")",
"\n",
"}",
"\n",
"mi",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"procPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"mi",
".",
"Close",
"(",
")",
"\n",
"return",
"parseMountinfo",
"(",
"mi",
")",
"\n",
"}"
] |
// ParseMounts returns all mountpoints associated with a process mount namespace.
// The special value 0 as pid argument is used to specify the current process.
|
[
"ParseMounts",
"returns",
"all",
"mountpoints",
"associated",
"with",
"a",
"process",
"mount",
"namespace",
".",
"The",
"special",
"value",
"0",
"as",
"pid",
"argument",
"is",
"used",
"to",
"specify",
"the",
"current",
"process",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L40-L55
|
train
|
rkt/rkt
|
stage1/init/kvm/resources.go
|
findResources
|
func findResources(isolators types.Isolators) (mem, cpus int64) {
for _, i := range isolators {
switch v := i.Value().(type) {
case *types.ResourceMemory:
mem = v.Limit().Value()
// Convert bytes into megabytes
mem /= 1024 * 1024
case *types.ResourceCPU:
cpus = v.Limit().Value()
}
}
return mem, cpus
}
|
go
|
func findResources(isolators types.Isolators) (mem, cpus int64) {
for _, i := range isolators {
switch v := i.Value().(type) {
case *types.ResourceMemory:
mem = v.Limit().Value()
// Convert bytes into megabytes
mem /= 1024 * 1024
case *types.ResourceCPU:
cpus = v.Limit().Value()
}
}
return mem, cpus
}
|
[
"func",
"findResources",
"(",
"isolators",
"types",
".",
"Isolators",
")",
"(",
"mem",
",",
"cpus",
"int64",
")",
"{",
"for",
"_",
",",
"i",
":=",
"range",
"isolators",
"{",
"switch",
"v",
":=",
"i",
".",
"Value",
"(",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"types",
".",
"ResourceMemory",
":",
"mem",
"=",
"v",
".",
"Limit",
"(",
")",
".",
"Value",
"(",
")",
"\n",
"mem",
"/=",
"1024",
"*",
"1024",
"\n",
"case",
"*",
"types",
".",
"ResourceCPU",
":",
"cpus",
"=",
"v",
".",
"Limit",
"(",
")",
".",
"Value",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"mem",
",",
"cpus",
"\n",
"}"
] |
// findResources finds value of last isolator for particular type.
|
[
"findResources",
"finds",
"value",
"of",
"last",
"isolator",
"for",
"particular",
"type",
"."
] |
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
|
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/resources.go#L42-L54
|
train
|
go-playground/validator
|
struct_level.go
|
wrapStructLevelFunc
|
func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx {
return func(ctx context.Context, sl StructLevel) {
fn(sl)
}
}
|
go
|
func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx {
return func(ctx context.Context, sl StructLevel) {
fn(sl)
}
}
|
[
"func",
"wrapStructLevelFunc",
"(",
"fn",
"StructLevelFunc",
")",
"StructLevelFuncCtx",
"{",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"sl",
"StructLevel",
")",
"{",
"fn",
"(",
"sl",
")",
"\n",
"}",
"\n",
"}"
] |
// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx
|
[
"wrapStructLevelFunc",
"wraps",
"normal",
"StructLevelFunc",
"makes",
"it",
"compatible",
"with",
"StructLevelFuncCtx"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L16-L20
|
train
|
go-playground/validator
|
struct_level.go
|
ExtractType
|
func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) {
return v.extractTypeInternal(field, false)
}
|
go
|
func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) {
return v.extractTypeInternal(field, false)
}
|
[
"func",
"(",
"v",
"*",
"validate",
")",
"ExtractType",
"(",
"field",
"reflect",
".",
"Value",
")",
"(",
"reflect",
".",
"Value",
",",
"reflect",
".",
"Kind",
",",
"bool",
")",
"{",
"return",
"v",
".",
"extractTypeInternal",
"(",
"field",
",",
"false",
")",
"\n",
"}"
] |
// ExtractType gets the actual underlying type of field value.
|
[
"ExtractType",
"gets",
"the",
"actual",
"underlying",
"type",
"of",
"field",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L104-L106
|
train
|
go-playground/validator
|
struct_level.go
|
ReportError
|
func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) {
fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false)
if len(structFieldName) == 0 {
structFieldName = fieldName
}
v.str1 = string(append(v.ns, fieldName...))
if v.v.hasTagNameFunc || fieldName != structFieldName {
v.str2 = string(append(v.actualNs, structFieldName...))
} else {
v.str2 = v.str1
}
if kind == reflect.Invalid {
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: tag,
actualTag: tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(fieldName)),
structfieldLen: uint8(len(structFieldName)),
param: param,
kind: kind,
},
)
return
}
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: tag,
actualTag: tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(fieldName)),
structfieldLen: uint8(len(structFieldName)),
value: fv.Interface(),
param: param,
kind: kind,
typ: fv.Type(),
},
)
}
|
go
|
func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) {
fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false)
if len(structFieldName) == 0 {
structFieldName = fieldName
}
v.str1 = string(append(v.ns, fieldName...))
if v.v.hasTagNameFunc || fieldName != structFieldName {
v.str2 = string(append(v.actualNs, structFieldName...))
} else {
v.str2 = v.str1
}
if kind == reflect.Invalid {
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: tag,
actualTag: tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(fieldName)),
structfieldLen: uint8(len(structFieldName)),
param: param,
kind: kind,
},
)
return
}
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: tag,
actualTag: tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(fieldName)),
structfieldLen: uint8(len(structFieldName)),
value: fv.Interface(),
param: param,
kind: kind,
typ: fv.Type(),
},
)
}
|
[
"func",
"(",
"v",
"*",
"validate",
")",
"ReportError",
"(",
"field",
"interface",
"{",
"}",
",",
"fieldName",
",",
"structFieldName",
",",
"tag",
",",
"param",
"string",
")",
"{",
"fv",
",",
"kind",
",",
"_",
":=",
"v",
".",
"extractTypeInternal",
"(",
"reflect",
".",
"ValueOf",
"(",
"field",
")",
",",
"false",
")",
"\n",
"if",
"len",
"(",
"structFieldName",
")",
"==",
"0",
"{",
"structFieldName",
"=",
"fieldName",
"\n",
"}",
"\n",
"v",
".",
"str1",
"=",
"string",
"(",
"append",
"(",
"v",
".",
"ns",
",",
"fieldName",
"...",
")",
")",
"\n",
"if",
"v",
".",
"v",
".",
"hasTagNameFunc",
"||",
"fieldName",
"!=",
"structFieldName",
"{",
"v",
".",
"str2",
"=",
"string",
"(",
"append",
"(",
"v",
".",
"actualNs",
",",
"structFieldName",
"...",
")",
")",
"\n",
"}",
"else",
"{",
"v",
".",
"str2",
"=",
"v",
".",
"str1",
"\n",
"}",
"\n",
"if",
"kind",
"==",
"reflect",
".",
"Invalid",
"{",
"v",
".",
"errs",
"=",
"append",
"(",
"v",
".",
"errs",
",",
"&",
"fieldError",
"{",
"v",
":",
"v",
".",
"v",
",",
"tag",
":",
"tag",
",",
"actualTag",
":",
"tag",
",",
"ns",
":",
"v",
".",
"str1",
",",
"structNs",
":",
"v",
".",
"str2",
",",
"fieldLen",
":",
"uint8",
"(",
"len",
"(",
"fieldName",
")",
")",
",",
"structfieldLen",
":",
"uint8",
"(",
"len",
"(",
"structFieldName",
")",
")",
",",
"param",
":",
"param",
",",
"kind",
":",
"kind",
",",
"}",
",",
")",
"\n",
"return",
"\n",
"}",
"\n",
"v",
".",
"errs",
"=",
"append",
"(",
"v",
".",
"errs",
",",
"&",
"fieldError",
"{",
"v",
":",
"v",
".",
"v",
",",
"tag",
":",
"tag",
",",
"actualTag",
":",
"tag",
",",
"ns",
":",
"v",
".",
"str1",
",",
"structNs",
":",
"v",
".",
"str2",
",",
"fieldLen",
":",
"uint8",
"(",
"len",
"(",
"fieldName",
")",
")",
",",
"structfieldLen",
":",
"uint8",
"(",
"len",
"(",
"structFieldName",
")",
")",
",",
"value",
":",
"fv",
".",
"Interface",
"(",
")",
",",
"param",
":",
"param",
",",
"kind",
":",
"kind",
",",
"typ",
":",
"fv",
".",
"Type",
"(",
")",
",",
"}",
",",
")",
"\n",
"}"
] |
// ReportError reports an error just by passing the field and tag information
|
[
"ReportError",
"reports",
"an",
"error",
"just",
"by",
"passing",
"the",
"field",
"and",
"tag",
"information"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L109-L158
|
train
|
go-playground/validator
|
_examples/custom/main.go
|
ValidateValuer
|
func ValidateValuer(field reflect.Value) interface{} {
if valuer, ok := field.Interface().(driver.Valuer); ok {
val, err := valuer.Value()
if err == nil {
return val
}
// handle the error how you want
}
return nil
}
|
go
|
func ValidateValuer(field reflect.Value) interface{} {
if valuer, ok := field.Interface().(driver.Valuer); ok {
val, err := valuer.Value()
if err == nil {
return val
}
// handle the error how you want
}
return nil
}
|
[
"func",
"ValidateValuer",
"(",
"field",
"reflect",
".",
"Value",
")",
"interface",
"{",
"}",
"{",
"if",
"valuer",
",",
"ok",
":=",
"field",
".",
"Interface",
"(",
")",
".",
"(",
"driver",
".",
"Valuer",
")",
";",
"ok",
"{",
"val",
",",
"err",
":=",
"valuer",
".",
"Value",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"val",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ValidateValuer implements validator.CustomTypeFunc
|
[
"ValidateValuer",
"implements",
"validator",
".",
"CustomTypeFunc"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/_examples/custom/main.go#L39-L51
|
train
|
go-playground/validator
|
errors.go
|
Error
|
func (e *InvalidValidationError) Error() string {
if e.Type == nil {
return "validator: (nil)"
}
return "validator: (nil " + e.Type.String() + ")"
}
|
go
|
func (e *InvalidValidationError) Error() string {
if e.Type == nil {
return "validator: (nil)"
}
return "validator: (nil " + e.Type.String() + ")"
}
|
[
"func",
"(",
"e",
"*",
"InvalidValidationError",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"e",
".",
"Type",
"==",
"nil",
"{",
"return",
"\"validator: (nil)\"",
"\n",
"}",
"\n",
"return",
"\"validator: (nil \"",
"+",
"e",
".",
"Type",
".",
"String",
"(",
")",
"+",
"\")\"",
"\n",
"}"
] |
// Error returns InvalidValidationError message
|
[
"Error",
"returns",
"InvalidValidationError",
"message"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L26-L33
|
train
|
go-playground/validator
|
errors.go
|
Error
|
func (ve ValidationErrors) Error() string {
buff := bytes.NewBufferString("")
var fe *fieldError
for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError)
buff.WriteString(fe.Error())
buff.WriteString("\n")
}
return strings.TrimSpace(buff.String())
}
|
go
|
func (ve ValidationErrors) Error() string {
buff := bytes.NewBufferString("")
var fe *fieldError
for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError)
buff.WriteString(fe.Error())
buff.WriteString("\n")
}
return strings.TrimSpace(buff.String())
}
|
[
"func",
"(",
"ve",
"ValidationErrors",
")",
"Error",
"(",
")",
"string",
"{",
"buff",
":=",
"bytes",
".",
"NewBufferString",
"(",
"\"\"",
")",
"\n",
"var",
"fe",
"*",
"fieldError",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ve",
")",
";",
"i",
"++",
"{",
"fe",
"=",
"ve",
"[",
"i",
"]",
".",
"(",
"*",
"fieldError",
")",
"\n",
"buff",
".",
"WriteString",
"(",
"fe",
".",
"Error",
"(",
")",
")",
"\n",
"buff",
".",
"WriteString",
"(",
"\"\\n\"",
")",
"\n",
"}",
"\n",
"\\n",
"\n",
"}"
] |
// Error is intended for use in development + debugging and not intended to be a production error message.
// It allows ValidationErrors to subscribe to the Error interface.
// All information to create an error message specific to your application is contained within
// the FieldError found within the ValidationErrors array
|
[
"Error",
"is",
"intended",
"for",
"use",
"in",
"development",
"+",
"debugging",
"and",
"not",
"intended",
"to",
"be",
"a",
"production",
"error",
"message",
".",
"It",
"allows",
"ValidationErrors",
"to",
"subscribe",
"to",
"the",
"Error",
"interface",
".",
"All",
"information",
"to",
"create",
"an",
"error",
"message",
"specific",
"to",
"your",
"application",
"is",
"contained",
"within",
"the",
"FieldError",
"found",
"within",
"the",
"ValidationErrors",
"array"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L43-L57
|
train
|
go-playground/validator
|
errors.go
|
Translate
|
func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations {
trans := make(ValidationErrorsTranslations)
var fe *fieldError
for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError)
// // in case an Anonymous struct was used, ensure that the key
// // would be 'Username' instead of ".Username"
// if len(fe.ns) > 0 && fe.ns[:1] == "." {
// trans[fe.ns[1:]] = fe.Translate(ut)
// continue
// }
trans[fe.ns] = fe.Translate(ut)
}
return trans
}
|
go
|
func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations {
trans := make(ValidationErrorsTranslations)
var fe *fieldError
for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError)
// // in case an Anonymous struct was used, ensure that the key
// // would be 'Username' instead of ".Username"
// if len(fe.ns) > 0 && fe.ns[:1] == "." {
// trans[fe.ns[1:]] = fe.Translate(ut)
// continue
// }
trans[fe.ns] = fe.Translate(ut)
}
return trans
}
|
[
"func",
"(",
"ve",
"ValidationErrors",
")",
"Translate",
"(",
"ut",
"ut",
".",
"Translator",
")",
"ValidationErrorsTranslations",
"{",
"trans",
":=",
"make",
"(",
"ValidationErrorsTranslations",
")",
"\n",
"var",
"fe",
"*",
"fieldError",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ve",
")",
";",
"i",
"++",
"{",
"fe",
"=",
"ve",
"[",
"i",
"]",
".",
"(",
"*",
"fieldError",
")",
"\n",
"trans",
"[",
"fe",
".",
"ns",
"]",
"=",
"fe",
".",
"Translate",
"(",
"ut",
")",
"\n",
"}",
"\n",
"return",
"trans",
"\n",
"}"
] |
// Translate translates all of the ValidationErrors
|
[
"Translate",
"translates",
"all",
"of",
"the",
"ValidationErrors"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L60-L80
|
train
|
go-playground/validator
|
errors.go
|
Field
|
func (fe *fieldError) Field() string {
return fe.ns[len(fe.ns)-int(fe.fieldLen):]
// // return fe.field
// fld := fe.ns[len(fe.ns)-int(fe.fieldLen):]
// log.Println("FLD:", fld)
// if len(fld) > 0 && fld[:1] == "." {
// return fld[1:]
// }
// return fld
}
|
go
|
func (fe *fieldError) Field() string {
return fe.ns[len(fe.ns)-int(fe.fieldLen):]
// // return fe.field
// fld := fe.ns[len(fe.ns)-int(fe.fieldLen):]
// log.Println("FLD:", fld)
// if len(fld) > 0 && fld[:1] == "." {
// return fld[1:]
// }
// return fld
}
|
[
"func",
"(",
"fe",
"*",
"fieldError",
")",
"Field",
"(",
")",
"string",
"{",
"return",
"fe",
".",
"ns",
"[",
"len",
"(",
"fe",
".",
"ns",
")",
"-",
"int",
"(",
"fe",
".",
"fieldLen",
")",
":",
"]",
"\n",
"}"
] |
// Field returns the fields name with the tag name taking precedence over the
// fields actual name.
|
[
"Field",
"returns",
"the",
"fields",
"name",
"with",
"the",
"tag",
"name",
"taking",
"precedence",
"over",
"the",
"fields",
"actual",
"name",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L206-L219
|
train
|
go-playground/validator
|
errors.go
|
StructField
|
func (fe *fieldError) StructField() string {
// return fe.structField
return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):]
}
|
go
|
func (fe *fieldError) StructField() string {
// return fe.structField
return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):]
}
|
[
"func",
"(",
"fe",
"*",
"fieldError",
")",
"StructField",
"(",
")",
"string",
"{",
"return",
"fe",
".",
"structNs",
"[",
"len",
"(",
"fe",
".",
"structNs",
")",
"-",
"int",
"(",
"fe",
".",
"structfieldLen",
")",
":",
"]",
"\n",
"}"
] |
// returns the fields actual name from the struct, when able to determine.
|
[
"returns",
"the",
"fields",
"actual",
"name",
"from",
"the",
"struct",
"when",
"able",
"to",
"determine",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L222-L225
|
train
|
go-playground/validator
|
errors.go
|
Error
|
func (fe *fieldError) Error() string {
return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag)
}
|
go
|
func (fe *fieldError) Error() string {
return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag)
}
|
[
"func",
"(",
"fe",
"*",
"fieldError",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"fieldErrMsg",
",",
"fe",
".",
"ns",
",",
"fe",
".",
"Field",
"(",
")",
",",
"fe",
".",
"tag",
")",
"\n",
"}"
] |
// Error returns the fieldError's error message
|
[
"Error",
"returns",
"the",
"fieldError",
"s",
"error",
"message"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L250-L252
|
train
|
go-playground/validator
|
non-standard/validators/notblank.go
|
NotBlank
|
func NotBlank(fl validator.FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
return len(strings.TrimSpace(field.String())) > 0
case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array:
return field.Len() > 0
case reflect.Ptr, reflect.Interface, reflect.Func:
return !field.IsNil()
default:
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
}
|
go
|
func NotBlank(fl validator.FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
return len(strings.TrimSpace(field.String())) > 0
case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array:
return field.Len() > 0
case reflect.Ptr, reflect.Interface, reflect.Func:
return !field.IsNil()
default:
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
}
|
[
"func",
"NotBlank",
"(",
"fl",
"validator",
".",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"return",
"len",
"(",
"strings",
".",
"TrimSpace",
"(",
"field",
".",
"String",
"(",
")",
")",
")",
">",
"0",
"\n",
"case",
"reflect",
".",
"Chan",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Array",
":",
"return",
"field",
".",
"Len",
"(",
")",
">",
"0",
"\n",
"case",
"reflect",
".",
"Ptr",
",",
"reflect",
".",
"Interface",
",",
"reflect",
".",
"Func",
":",
"return",
"!",
"field",
".",
"IsNil",
"(",
")",
"\n",
"default",
":",
"return",
"field",
".",
"IsValid",
"(",
")",
"&&",
"field",
".",
"Interface",
"(",
")",
"!=",
"reflect",
".",
"Zero",
"(",
"field",
".",
"Type",
"(",
")",
")",
".",
"Interface",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// NotBlank is the validation function for validating if the current field
// has a value or length greater than zero, or is not a space only string.
|
[
"NotBlank",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"has",
"a",
"value",
"or",
"length",
"greater",
"than",
"zero",
"or",
"is",
"not",
"a",
"space",
"only",
"string",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/non-standard/validators/notblank.go#L12-L25
|
train
|
go-playground/validator
|
baked_in.go
|
wrapFunc
|
func wrapFunc(fn Func) FuncCtx {
if fn == nil {
return nil // be sure not to wrap a bad function.
}
return func(ctx context.Context, fl FieldLevel) bool {
return fn(fl)
}
}
|
go
|
func wrapFunc(fn Func) FuncCtx {
if fn == nil {
return nil // be sure not to wrap a bad function.
}
return func(ctx context.Context, fl FieldLevel) bool {
return fn(fl)
}
}
|
[
"func",
"wrapFunc",
"(",
"fn",
"Func",
")",
"FuncCtx",
"{",
"if",
"fn",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"fl",
"FieldLevel",
")",
"bool",
"{",
"return",
"fn",
"(",
"fl",
")",
"\n",
"}",
"\n",
"}"
] |
// wrapFunc wraps noramal Func makes it compatible with FuncCtx
|
[
"wrapFunc",
"wraps",
"noramal",
"Func",
"makes",
"it",
"compatible",
"with",
"FuncCtx"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L30-L37
|
train
|
go-playground/validator
|
baked_in.go
|
isUnique
|
func isUnique(fl FieldLevel) bool {
field := fl.Field()
v := reflect.ValueOf(struct{}{})
switch field.Kind() {
case reflect.Slice, reflect.Array:
m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
for i := 0; i < field.Len(); i++ {
m.SetMapIndex(field.Index(i), v)
}
return field.Len() == m.Len()
case reflect.Map:
m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
for _, k := range field.MapKeys() {
m.SetMapIndex(field.MapIndex(k), v)
}
return field.Len() == m.Len()
default:
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
}
|
go
|
func isUnique(fl FieldLevel) bool {
field := fl.Field()
v := reflect.ValueOf(struct{}{})
switch field.Kind() {
case reflect.Slice, reflect.Array:
m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
for i := 0; i < field.Len(); i++ {
m.SetMapIndex(field.Index(i), v)
}
return field.Len() == m.Len()
case reflect.Map:
m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
for _, k := range field.MapKeys() {
m.SetMapIndex(field.MapIndex(k), v)
}
return field.Len() == m.Len()
default:
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
}
|
[
"func",
"isUnique",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"struct",
"{",
"}",
"{",
"}",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Array",
":",
"m",
":=",
"reflect",
".",
"MakeMap",
"(",
"reflect",
".",
"MapOf",
"(",
"field",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
",",
"v",
".",
"Type",
"(",
")",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"field",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"m",
".",
"SetMapIndex",
"(",
"field",
".",
"Index",
"(",
"i",
")",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"field",
".",
"Len",
"(",
")",
"==",
"m",
".",
"Len",
"(",
")",
"\n",
"case",
"reflect",
".",
"Map",
":",
"m",
":=",
"reflect",
".",
"MakeMap",
"(",
"reflect",
".",
"MapOf",
"(",
"field",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
",",
"v",
".",
"Type",
"(",
")",
")",
")",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"field",
".",
"MapKeys",
"(",
")",
"{",
"m",
".",
"SetMapIndex",
"(",
"field",
".",
"MapIndex",
"(",
"k",
")",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"field",
".",
"Len",
"(",
")",
"==",
"m",
".",
"Len",
"(",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// isUnique is the validation function for validating if each array|slice|map value is unique
|
[
"isUnique",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"each",
"array|slice|map",
"value",
"is",
"unique"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L220-L243
|
train
|
go-playground/validator
|
baked_in.go
|
isMAC
|
func isMAC(fl FieldLevel) bool {
_, err := net.ParseMAC(fl.Field().String())
return err == nil
}
|
go
|
func isMAC(fl FieldLevel) bool {
_, err := net.ParseMAC(fl.Field().String())
return err == nil
}
|
[
"func",
"isMAC",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"net",
".",
"ParseMAC",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsMAC is the validation function for validating if the field's value is a valid MAC address.
|
[
"IsMAC",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"MAC",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L246-L251
|
train
|
go-playground/validator
|
baked_in.go
|
isCIDRv4
|
func isCIDRv4(fl FieldLevel) bool {
ip, _, err := net.ParseCIDR(fl.Field().String())
return err == nil && ip.To4() != nil
}
|
go
|
func isCIDRv4(fl FieldLevel) bool {
ip, _, err := net.ParseCIDR(fl.Field().String())
return err == nil && ip.To4() != nil
}
|
[
"func",
"isCIDRv4",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"ip",
",",
"_",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"&&",
"ip",
".",
"To4",
"(",
")",
"!=",
"nil",
"\n",
"}"
] |
// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.
|
[
"IsCIDRv4",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"v4",
"CIDR",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L254-L259
|
train
|
go-playground/validator
|
baked_in.go
|
isCIDR
|
func isCIDR(fl FieldLevel) bool {
_, _, err := net.ParseCIDR(fl.Field().String())
return err == nil
}
|
go
|
func isCIDR(fl FieldLevel) bool {
_, _, err := net.ParseCIDR(fl.Field().String())
return err == nil
}
|
[
"func",
"isCIDR",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"_",
",",
"_",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address.
|
[
"IsCIDR",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"v4",
"or",
"v6",
"CIDR",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L270-L275
|
train
|
go-playground/validator
|
baked_in.go
|
isIPv6
|
func isIPv6(fl FieldLevel) bool {
ip := net.ParseIP(fl.Field().String())
return ip != nil && ip.To4() == nil
}
|
go
|
func isIPv6(fl FieldLevel) bool {
ip := net.ParseIP(fl.Field().String())
return ip != nil && ip.To4() == nil
}
|
[
"func",
"isIPv6",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"ip",
"!=",
"nil",
"&&",
"ip",
".",
"To4",
"(",
")",
"==",
"nil",
"\n",
"}"
] |
// IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address.
|
[
"IsIPv6",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"v6",
"IP",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L286-L291
|
train
|
go-playground/validator
|
baked_in.go
|
isIP
|
func isIP(fl FieldLevel) bool {
ip := net.ParseIP(fl.Field().String())
return ip != nil
}
|
go
|
func isIP(fl FieldLevel) bool {
ip := net.ParseIP(fl.Field().String())
return ip != nil
}
|
[
"func",
"isIP",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"ip",
"!=",
"nil",
"\n",
"}"
] |
// IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address.
|
[
"IsIP",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"v4",
"or",
"v6",
"IP",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L294-L299
|
train
|
go-playground/validator
|
baked_in.go
|
isSSN
|
func isSSN(fl FieldLevel) bool {
field := fl.Field()
if field.Len() != 11 {
return false
}
return sSNRegex.MatchString(field.String())
}
|
go
|
func isSSN(fl FieldLevel) bool {
field := fl.Field()
if field.Len() != 11 {
return false
}
return sSNRegex.MatchString(field.String())
}
|
[
"func",
"isSSN",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"if",
"field",
".",
"Len",
"(",
")",
"!=",
"11",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"sSNRegex",
".",
"MatchString",
"(",
"field",
".",
"String",
"(",
")",
")",
"\n",
"}"
] |
// IsSSN is the validation function for validating if the field's value is a valid SSN.
|
[
"IsSSN",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"SSN",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L302-L311
|
train
|
go-playground/validator
|
baked_in.go
|
isLongitude
|
func isLongitude(fl FieldLevel) bool {
field := fl.Field()
var v string
switch field.Kind() {
case reflect.String:
v = field.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v = strconv.FormatInt(field.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v = strconv.FormatUint(field.Uint(), 10)
case reflect.Float32:
v = strconv.FormatFloat(field.Float(), 'f', -1, 32)
case reflect.Float64:
v = strconv.FormatFloat(field.Float(), 'f', -1, 64)
default:
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
return longitudeRegex.MatchString(v)
}
|
go
|
func isLongitude(fl FieldLevel) bool {
field := fl.Field()
var v string
switch field.Kind() {
case reflect.String:
v = field.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v = strconv.FormatInt(field.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v = strconv.FormatUint(field.Uint(), 10)
case reflect.Float32:
v = strconv.FormatFloat(field.Float(), 'f', -1, 32)
case reflect.Float64:
v = strconv.FormatFloat(field.Float(), 'f', -1, 64)
default:
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
return longitudeRegex.MatchString(v)
}
|
[
"func",
"isLongitude",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"var",
"v",
"string",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"v",
"=",
"field",
".",
"String",
"(",
")",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"v",
"=",
"strconv",
".",
"FormatInt",
"(",
"field",
".",
"Int",
"(",
")",
",",
"10",
")",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"v",
"=",
"strconv",
".",
"FormatUint",
"(",
"field",
".",
"Uint",
"(",
")",
",",
"10",
")",
"\n",
"case",
"reflect",
".",
"Float32",
":",
"v",
"=",
"strconv",
".",
"FormatFloat",
"(",
"field",
".",
"Float",
"(",
")",
",",
"'f'",
",",
"-",
"1",
",",
"32",
")",
"\n",
"case",
"reflect",
".",
"Float64",
":",
"v",
"=",
"strconv",
".",
"FormatFloat",
"(",
"field",
".",
"Float",
"(",
")",
",",
"'f'",
",",
"-",
"1",
",",
"64",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"longitudeRegex",
".",
"MatchString",
"(",
"v",
")",
"\n",
"}"
] |
// IsLongitude is the validation function for validating if the field's value is a valid longitude coordinate.
|
[
"IsLongitude",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"longitude",
"coordinate",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L314-L334
|
train
|
go-playground/validator
|
baked_in.go
|
isDataURI
|
func isDataURI(fl FieldLevel) bool {
uri := strings.SplitN(fl.Field().String(), ",", 2)
if len(uri) != 2 {
return false
}
if !dataURIRegex.MatchString(uri[0]) {
return false
}
return base64Regex.MatchString(uri[1])
}
|
go
|
func isDataURI(fl FieldLevel) bool {
uri := strings.SplitN(fl.Field().String(), ",", 2)
if len(uri) != 2 {
return false
}
if !dataURIRegex.MatchString(uri[0]) {
return false
}
return base64Regex.MatchString(uri[1])
}
|
[
"func",
"isDataURI",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"uri",
":=",
"strings",
".",
"SplitN",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"\",\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"uri",
")",
"!=",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"dataURIRegex",
".",
"MatchString",
"(",
"uri",
"[",
"0",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"base64Regex",
".",
"MatchString",
"(",
"uri",
"[",
"1",
"]",
")",
"\n",
"}"
] |
// IsDataURI is the validation function for validating if the field's value is a valid data URI.
|
[
"IsDataURI",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"data",
"URI",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L360-L373
|
train
|
go-playground/validator
|
baked_in.go
|
hasMultiByteCharacter
|
func hasMultiByteCharacter(fl FieldLevel) bool {
field := fl.Field()
if field.Len() == 0 {
return true
}
return multibyteRegex.MatchString(field.String())
}
|
go
|
func hasMultiByteCharacter(fl FieldLevel) bool {
field := fl.Field()
if field.Len() == 0 {
return true
}
return multibyteRegex.MatchString(field.String())
}
|
[
"func",
"hasMultiByteCharacter",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"if",
"field",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"multibyteRegex",
".",
"MatchString",
"(",
"field",
".",
"String",
"(",
")",
")",
"\n",
"}"
] |
// HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character.
|
[
"HasMultiByteCharacter",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"has",
"a",
"multi",
"byte",
"character",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L376-L385
|
train
|
go-playground/validator
|
baked_in.go
|
isISBN13
|
func isISBN13(fl FieldLevel) bool {
s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4)
if !iSBN13Regex.MatchString(s) {
return false
}
var checksum int32
var i int32
factor := []int32{1, 3}
for i = 0; i < 12; i++ {
checksum += factor[i%2] * int32(s[i]-'0')
}
return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0
}
|
go
|
func isISBN13(fl FieldLevel) bool {
s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4)
if !iSBN13Regex.MatchString(s) {
return false
}
var checksum int32
var i int32
factor := []int32{1, 3}
for i = 0; i < 12; i++ {
checksum += factor[i%2] * int32(s[i]-'0')
}
return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0
}
|
[
"func",
"isISBN13",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"s",
":=",
"strings",
".",
"Replace",
"(",
"strings",
".",
"Replace",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"\"-\"",
",",
"\"\"",
",",
"4",
")",
",",
"\" \"",
",",
"\"\"",
",",
"4",
")",
"\n",
"if",
"!",
"iSBN13Regex",
".",
"MatchString",
"(",
"s",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"var",
"checksum",
"int32",
"\n",
"var",
"i",
"int32",
"\n",
"factor",
":=",
"[",
"]",
"int32",
"{",
"1",
",",
"3",
"}",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"12",
";",
"i",
"++",
"{",
"checksum",
"+=",
"factor",
"[",
"i",
"%",
"2",
"]",
"*",
"int32",
"(",
"s",
"[",
"i",
"]",
"-",
"'0'",
")",
"\n",
"}",
"\n",
"return",
"(",
"int32",
"(",
"s",
"[",
"12",
"]",
"-",
"'0'",
")",
")",
"-",
"(",
"(",
"10",
"-",
"(",
"checksum",
"%",
"10",
")",
")",
"%",
"10",
")",
"==",
"0",
"\n",
"}"
] |
// IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN.
|
[
"IsISBN13",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"v13",
"ISBN",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L443-L461
|
train
|
go-playground/validator
|
baked_in.go
|
isISBN10
|
func isISBN10(fl FieldLevel) bool {
s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3)
if !iSBN10Regex.MatchString(s) {
return false
}
var checksum int32
var i int32
for i = 0; i < 9; i++ {
checksum += (i + 1) * int32(s[i]-'0')
}
if s[9] == 'X' {
checksum += 10 * 10
} else {
checksum += 10 * int32(s[9]-'0')
}
return checksum%11 == 0
}
|
go
|
func isISBN10(fl FieldLevel) bool {
s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3)
if !iSBN10Regex.MatchString(s) {
return false
}
var checksum int32
var i int32
for i = 0; i < 9; i++ {
checksum += (i + 1) * int32(s[i]-'0')
}
if s[9] == 'X' {
checksum += 10 * 10
} else {
checksum += 10 * int32(s[9]-'0')
}
return checksum%11 == 0
}
|
[
"func",
"isISBN10",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"s",
":=",
"strings",
".",
"Replace",
"(",
"strings",
".",
"Replace",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"\"-\"",
",",
"\"\"",
",",
"3",
")",
",",
"\" \"",
",",
"\"\"",
",",
"3",
")",
"\n",
"if",
"!",
"iSBN10Regex",
".",
"MatchString",
"(",
"s",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"var",
"checksum",
"int32",
"\n",
"var",
"i",
"int32",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"9",
";",
"i",
"++",
"{",
"checksum",
"+=",
"(",
"i",
"+",
"1",
")",
"*",
"int32",
"(",
"s",
"[",
"i",
"]",
"-",
"'0'",
")",
"\n",
"}",
"\n",
"if",
"s",
"[",
"9",
"]",
"==",
"'X'",
"{",
"checksum",
"+=",
"10",
"*",
"10",
"\n",
"}",
"else",
"{",
"checksum",
"+=",
"10",
"*",
"int32",
"(",
"s",
"[",
"9",
"]",
"-",
"'0'",
")",
"\n",
"}",
"\n",
"return",
"checksum",
"%",
"11",
"==",
"0",
"\n",
"}"
] |
// IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN.
|
[
"IsISBN10",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"v10",
"ISBN",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L464-L486
|
train
|
go-playground/validator
|
baked_in.go
|
isEthereumAddress
|
func isEthereumAddress(fl FieldLevel) bool {
address := fl.Field().String()
if !ethAddressRegex.MatchString(address) {
return false
}
if ethaddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) {
return true
}
// checksum validation is blocked by https://github.com/golang/crypto/pull/28
return true
}
|
go
|
func isEthereumAddress(fl FieldLevel) bool {
address := fl.Field().String()
if !ethAddressRegex.MatchString(address) {
return false
}
if ethaddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) {
return true
}
// checksum validation is blocked by https://github.com/golang/crypto/pull/28
return true
}
|
[
"func",
"isEthereumAddress",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"address",
":=",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
"\n",
"if",
"!",
"ethAddressRegex",
".",
"MatchString",
"(",
"address",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"ethaddressRegexUpper",
".",
"MatchString",
"(",
"address",
")",
"||",
"ethAddressRegexLower",
".",
"MatchString",
"(",
"address",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// IsEthereumAddress is the validation function for validating if the field's value is a valid ethereum address based currently only on the format
|
[
"IsEthereumAddress",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"ethereum",
"address",
"based",
"currently",
"only",
"on",
"the",
"format"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L489-L503
|
train
|
go-playground/validator
|
baked_in.go
|
isBitcoinAddress
|
func isBitcoinAddress(fl FieldLevel) bool {
address := fl.Field().String()
if !btcAddressRegex.MatchString(address) {
return false
}
alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
decode := [25]byte{}
for _, n := range []byte(address) {
d := bytes.IndexByte(alphabet, n)
for i := 24; i >= 0; i-- {
d += 58 * int(decode[i])
decode[i] = byte(d % 256)
d /= 256
}
}
h := sha256.New()
_, _ = h.Write(decode[:21])
d := h.Sum([]byte{})
h = sha256.New()
_, _ = h.Write(d)
validchecksum := [4]byte{}
computedchecksum := [4]byte{}
copy(computedchecksum[:], h.Sum(d[:0]))
copy(validchecksum[:], decode[21:])
return validchecksum == computedchecksum
}
|
go
|
func isBitcoinAddress(fl FieldLevel) bool {
address := fl.Field().String()
if !btcAddressRegex.MatchString(address) {
return false
}
alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
decode := [25]byte{}
for _, n := range []byte(address) {
d := bytes.IndexByte(alphabet, n)
for i := 24; i >= 0; i-- {
d += 58 * int(decode[i])
decode[i] = byte(d % 256)
d /= 256
}
}
h := sha256.New()
_, _ = h.Write(decode[:21])
d := h.Sum([]byte{})
h = sha256.New()
_, _ = h.Write(d)
validchecksum := [4]byte{}
computedchecksum := [4]byte{}
copy(computedchecksum[:], h.Sum(d[:0]))
copy(validchecksum[:], decode[21:])
return validchecksum == computedchecksum
}
|
[
"func",
"isBitcoinAddress",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"address",
":=",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
"\n",
"if",
"!",
"btcAddressRegex",
".",
"MatchString",
"(",
"address",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"alphabet",
":=",
"[",
"]",
"byte",
"(",
"\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"",
")",
"\n",
"decode",
":=",
"[",
"25",
"]",
"byte",
"{",
"}",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"[",
"]",
"byte",
"(",
"address",
")",
"{",
"d",
":=",
"bytes",
".",
"IndexByte",
"(",
"alphabet",
",",
"n",
")",
"\n",
"for",
"i",
":=",
"24",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"d",
"+=",
"58",
"*",
"int",
"(",
"decode",
"[",
"i",
"]",
")",
"\n",
"decode",
"[",
"i",
"]",
"=",
"byte",
"(",
"d",
"%",
"256",
")",
"\n",
"d",
"/=",
"256",
"\n",
"}",
"\n",
"}",
"\n",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"decode",
"[",
":",
"21",
"]",
")",
"\n",
"d",
":=",
"h",
".",
"Sum",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"h",
"=",
"sha256",
".",
"New",
"(",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"d",
")",
"\n",
"validchecksum",
":=",
"[",
"4",
"]",
"byte",
"{",
"}",
"\n",
"computedchecksum",
":=",
"[",
"4",
"]",
"byte",
"{",
"}",
"\n",
"copy",
"(",
"computedchecksum",
"[",
":",
"]",
",",
"h",
".",
"Sum",
"(",
"d",
"[",
":",
"0",
"]",
")",
")",
"\n",
"copy",
"(",
"validchecksum",
"[",
":",
"]",
",",
"decode",
"[",
"21",
":",
"]",
")",
"\n",
"return",
"validchecksum",
"==",
"computedchecksum",
"\n",
"}"
] |
// IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address
|
[
"IsBitcoinAddress",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"btc",
"address"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L506-L540
|
train
|
go-playground/validator
|
baked_in.go
|
isBitcoinBech32Address
|
func isBitcoinBech32Address(fl FieldLevel) bool {
address := fl.Field().String()
if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) {
return false
}
am := len(address) % 8
if am == 0 || am == 3 || am == 5 {
return false
}
address = strings.ToLower(address)
alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc
addr := address[3:]
dp := make([]int, 0, len(addr))
for _, c := range addr {
dp = append(dp, strings.IndexRune(alphabet, c))
}
ver := dp[0]
if ver < 0 || ver > 16 {
return false
}
if ver == 0 {
if len(address) != 42 && len(address) != 62 {
return false
}
}
values := append(hr, dp...)
GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3}
p := 1
for _, v := range values {
b := p >> 25
p = (p&0x1ffffff)<<5 ^ v
for i := 0; i < 5; i++ {
if (b>>uint(i))&1 == 1 {
p ^= GEN[i]
}
}
}
if p != 1 {
return false
}
b := uint(0)
acc := 0
mv := (1 << 5) - 1
var sw []int
for _, v := range dp[1 : len(dp)-6] {
acc = (acc << 5) | v
b += 5
for b >= 8 {
b -= 8
sw = append(sw, (acc>>b)&mv)
}
}
if len(sw) < 2 || len(sw) > 40 {
return false
}
return true
}
|
go
|
func isBitcoinBech32Address(fl FieldLevel) bool {
address := fl.Field().String()
if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) {
return false
}
am := len(address) % 8
if am == 0 || am == 3 || am == 5 {
return false
}
address = strings.ToLower(address)
alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc
addr := address[3:]
dp := make([]int, 0, len(addr))
for _, c := range addr {
dp = append(dp, strings.IndexRune(alphabet, c))
}
ver := dp[0]
if ver < 0 || ver > 16 {
return false
}
if ver == 0 {
if len(address) != 42 && len(address) != 62 {
return false
}
}
values := append(hr, dp...)
GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3}
p := 1
for _, v := range values {
b := p >> 25
p = (p&0x1ffffff)<<5 ^ v
for i := 0; i < 5; i++ {
if (b>>uint(i))&1 == 1 {
p ^= GEN[i]
}
}
}
if p != 1 {
return false
}
b := uint(0)
acc := 0
mv := (1 << 5) - 1
var sw []int
for _, v := range dp[1 : len(dp)-6] {
acc = (acc << 5) | v
b += 5
for b >= 8 {
b -= 8
sw = append(sw, (acc>>b)&mv)
}
}
if len(sw) < 2 || len(sw) > 40 {
return false
}
return true
}
|
[
"func",
"isBitcoinBech32Address",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"address",
":=",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
"\n",
"if",
"!",
"btcLowerAddressRegexBech32",
".",
"MatchString",
"(",
"address",
")",
"&&",
"!",
"btcUpperAddressRegexBech32",
".",
"MatchString",
"(",
"address",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"am",
":=",
"len",
"(",
"address",
")",
"%",
"8",
"\n",
"if",
"am",
"==",
"0",
"||",
"am",
"==",
"3",
"||",
"am",
"==",
"5",
"{",
"return",
"false",
"\n",
"}",
"\n",
"address",
"=",
"strings",
".",
"ToLower",
"(",
"address",
")",
"\n",
"alphabet",
":=",
"\"qpzry9x8gf2tvdw0s3jn54khce6mua7l\"",
"\n",
"hr",
":=",
"[",
"]",
"int",
"{",
"3",
",",
"3",
",",
"0",
",",
"2",
",",
"3",
"}",
"\n",
"addr",
":=",
"address",
"[",
"3",
":",
"]",
"\n",
"dp",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"len",
"(",
"addr",
")",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"addr",
"{",
"dp",
"=",
"append",
"(",
"dp",
",",
"strings",
".",
"IndexRune",
"(",
"alphabet",
",",
"c",
")",
")",
"\n",
"}",
"\n",
"ver",
":=",
"dp",
"[",
"0",
"]",
"\n",
"if",
"ver",
"<",
"0",
"||",
"ver",
">",
"16",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"ver",
"==",
"0",
"{",
"if",
"len",
"(",
"address",
")",
"!=",
"42",
"&&",
"len",
"(",
"address",
")",
"!=",
"62",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"values",
":=",
"append",
"(",
"hr",
",",
"dp",
"...",
")",
"\n",
"GEN",
":=",
"[",
"]",
"int",
"{",
"0x3b6a57b2",
",",
"0x26508e6d",
",",
"0x1ea119fa",
",",
"0x3d4233dd",
",",
"0x2a1462b3",
"}",
"\n",
"p",
":=",
"1",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"values",
"{",
"b",
":=",
"p",
">>",
"25",
"\n",
"p",
"=",
"(",
"p",
"&",
"0x1ffffff",
")",
"<<",
"5",
"^",
"v",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"5",
";",
"i",
"++",
"{",
"if",
"(",
"b",
">>",
"uint",
"(",
"i",
")",
")",
"&",
"1",
"==",
"1",
"{",
"p",
"^=",
"GEN",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"p",
"!=",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n",
"b",
":=",
"uint",
"(",
"0",
")",
"\n",
"acc",
":=",
"0",
"\n",
"mv",
":=",
"(",
"1",
"<<",
"5",
")",
"-",
"1",
"\n",
"var",
"sw",
"[",
"]",
"int",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"dp",
"[",
"1",
":",
"len",
"(",
"dp",
")",
"-",
"6",
"]",
"{",
"acc",
"=",
"(",
"acc",
"<<",
"5",
")",
"|",
"v",
"\n",
"b",
"+=",
"5",
"\n",
"for",
"b",
">=",
"8",
"{",
"b",
"-=",
"8",
"\n",
"sw",
"=",
"append",
"(",
"sw",
",",
"(",
"acc",
">>",
"b",
")",
"&",
"mv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"sw",
")",
"<",
"2",
"||",
"len",
"(",
"sw",
")",
">",
"40",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address
|
[
"IsBitcoinBech32Address",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"valid",
"bech32",
"btc",
"address"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L543-L620
|
train
|
go-playground/validator
|
baked_in.go
|
containsRune
|
func containsRune(fl FieldLevel) bool {
r, _ := utf8.DecodeRuneInString(fl.Param())
return strings.ContainsRune(fl.Field().String(), r)
}
|
go
|
func containsRune(fl FieldLevel) bool {
r, _ := utf8.DecodeRuneInString(fl.Param())
return strings.ContainsRune(fl.Field().String(), r)
}
|
[
"func",
"containsRune",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"r",
",",
"_",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"fl",
".",
"Param",
"(",
")",
")",
"\n",
"return",
"strings",
".",
"ContainsRune",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"r",
")",
"\n",
"}"
] |
// ContainsRune is the validation function for validating that the field's value contains the rune specified within the param.
|
[
"ContainsRune",
"is",
"the",
"validation",
"function",
"for",
"validating",
"that",
"the",
"field",
"s",
"value",
"contains",
"the",
"rune",
"specified",
"within",
"the",
"param",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L638-L643
|
train
|
go-playground/validator
|
baked_in.go
|
containsAny
|
func containsAny(fl FieldLevel) bool {
return strings.ContainsAny(fl.Field().String(), fl.Param())
}
|
go
|
func containsAny(fl FieldLevel) bool {
return strings.ContainsAny(fl.Field().String(), fl.Param())
}
|
[
"func",
"containsAny",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"return",
"strings",
".",
"ContainsAny",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"fl",
".",
"Param",
"(",
")",
")",
"\n",
"}"
] |
// ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param.
|
[
"ContainsAny",
"is",
"the",
"validation",
"function",
"for",
"validating",
"that",
"the",
"field",
"s",
"value",
"contains",
"any",
"of",
"the",
"characters",
"specified",
"within",
"the",
"param",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L646-L648
|
train
|
go-playground/validator
|
baked_in.go
|
contains
|
func contains(fl FieldLevel) bool {
return strings.Contains(fl.Field().String(), fl.Param())
}
|
go
|
func contains(fl FieldLevel) bool {
return strings.Contains(fl.Field().String(), fl.Param())
}
|
[
"func",
"contains",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"return",
"strings",
".",
"Contains",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"fl",
".",
"Param",
"(",
")",
")",
"\n",
"}"
] |
// Contains is the validation function for validating that the field's value contains the text specified within the param.
|
[
"Contains",
"is",
"the",
"validation",
"function",
"for",
"validating",
"that",
"the",
"field",
"s",
"value",
"contains",
"the",
"text",
"specified",
"within",
"the",
"param",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L651-L653
|
train
|
go-playground/validator
|
baked_in.go
|
startsWith
|
func startsWith(fl FieldLevel) bool {
return strings.HasPrefix(fl.Field().String(), fl.Param())
}
|
go
|
func startsWith(fl FieldLevel) bool {
return strings.HasPrefix(fl.Field().String(), fl.Param())
}
|
[
"func",
"startsWith",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"fl",
".",
"Param",
"(",
")",
")",
"\n",
"}"
] |
// StartsWith is the validation function for validating that the field's value starts with the text specified within the param.
|
[
"StartsWith",
"is",
"the",
"validation",
"function",
"for",
"validating",
"that",
"the",
"field",
"s",
"value",
"starts",
"with",
"the",
"text",
"specified",
"within",
"the",
"param",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L656-L658
|
train
|
go-playground/validator
|
baked_in.go
|
endsWith
|
func endsWith(fl FieldLevel) bool {
return strings.HasSuffix(fl.Field().String(), fl.Param())
}
|
go
|
func endsWith(fl FieldLevel) bool {
return strings.HasSuffix(fl.Field().String(), fl.Param())
}
|
[
"func",
"endsWith",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"return",
"strings",
".",
"HasSuffix",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
",",
"fl",
".",
"Param",
"(",
")",
")",
"\n",
"}"
] |
// EndsWith is the validation function for validating that the field's value ends with the text specified within the param.
|
[
"EndsWith",
"is",
"the",
"validation",
"function",
"for",
"validating",
"that",
"the",
"field",
"s",
"value",
"ends",
"with",
"the",
"text",
"specified",
"within",
"the",
"param",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L661-L663
|
train
|
go-playground/validator
|
baked_in.go
|
fieldContains
|
func fieldContains(fl FieldLevel) bool {
field := fl.Field()
currentField, _, ok := fl.GetStructFieldOK()
if !ok {
return false
}
return strings.Contains(field.String(), currentField.String())
}
|
go
|
func fieldContains(fl FieldLevel) bool {
field := fl.Field()
currentField, _, ok := fl.GetStructFieldOK()
if !ok {
return false
}
return strings.Contains(field.String(), currentField.String())
}
|
[
"func",
"fieldContains",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"currentField",
",",
"_",
",",
"ok",
":=",
"fl",
".",
"GetStructFieldOK",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Contains",
"(",
"field",
".",
"String",
"(",
")",
",",
"currentField",
".",
"String",
"(",
")",
")",
"\n",
"}"
] |
// FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value.
|
[
"FieldContains",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"contains",
"the",
"field",
"specified",
"by",
"the",
"param",
"s",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L666-L676
|
train
|
go-playground/validator
|
baked_in.go
|
fieldExcludes
|
func fieldExcludes(fl FieldLevel) bool {
field := fl.Field()
currentField, _, ok := fl.GetStructFieldOK()
if !ok {
return true
}
return !strings.Contains(field.String(), currentField.String())
}
|
go
|
func fieldExcludes(fl FieldLevel) bool {
field := fl.Field()
currentField, _, ok := fl.GetStructFieldOK()
if !ok {
return true
}
return !strings.Contains(field.String(), currentField.String())
}
|
[
"func",
"fieldExcludes",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"currentField",
",",
"_",
",",
"ok",
":=",
"fl",
".",
"GetStructFieldOK",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"!",
"strings",
".",
"Contains",
"(",
"field",
".",
"String",
"(",
")",
",",
"currentField",
".",
"String",
"(",
")",
")",
"\n",
"}"
] |
// FieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value.
|
[
"FieldExcludes",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"excludes",
"the",
"field",
"specified",
"by",
"the",
"param",
"s",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L679-L688
|
train
|
go-playground/validator
|
baked_in.go
|
isEqCrossStructField
|
func isEqCrossStructField(fl FieldLevel) bool {
field := fl.Field()
kind := field.Kind()
topField, topKind, ok := fl.GetStructFieldOK()
if !ok || topKind != kind {
return false
}
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return topField.Int() == field.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return topField.Uint() == field.Uint()
case reflect.Float32, reflect.Float64:
return topField.Float() == field.Float()
case reflect.Slice, reflect.Map, reflect.Array:
return int64(topField.Len()) == int64(field.Len())
case reflect.Struct:
fieldType := field.Type()
// Not Same underlying type i.e. struct and time
if fieldType != topField.Type() {
return false
}
if fieldType == timeType {
t := field.Interface().(time.Time)
fieldTime := topField.Interface().(time.Time)
return fieldTime.Equal(t)
}
}
// default reflect.String:
return topField.String() == field.String()
}
|
go
|
func isEqCrossStructField(fl FieldLevel) bool {
field := fl.Field()
kind := field.Kind()
topField, topKind, ok := fl.GetStructFieldOK()
if !ok || topKind != kind {
return false
}
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return topField.Int() == field.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return topField.Uint() == field.Uint()
case reflect.Float32, reflect.Float64:
return topField.Float() == field.Float()
case reflect.Slice, reflect.Map, reflect.Array:
return int64(topField.Len()) == int64(field.Len())
case reflect.Struct:
fieldType := field.Type()
// Not Same underlying type i.e. struct and time
if fieldType != topField.Type() {
return false
}
if fieldType == timeType {
t := field.Interface().(time.Time)
fieldTime := topField.Interface().(time.Time)
return fieldTime.Equal(t)
}
}
// default reflect.String:
return topField.String() == field.String()
}
|
[
"func",
"isEqCrossStructField",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"kind",
":=",
"field",
".",
"Kind",
"(",
")",
"\n",
"topField",
",",
"topKind",
",",
"ok",
":=",
"fl",
".",
"GetStructFieldOK",
"(",
")",
"\n",
"if",
"!",
"ok",
"||",
"topKind",
"!=",
"kind",
"{",
"return",
"false",
"\n",
"}",
"\n",
"switch",
"kind",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"return",
"topField",
".",
"Int",
"(",
")",
"==",
"field",
".",
"Int",
"(",
")",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
":",
"return",
"topField",
".",
"Uint",
"(",
")",
"==",
"field",
".",
"Uint",
"(",
")",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"return",
"topField",
".",
"Float",
"(",
")",
"==",
"field",
".",
"Float",
"(",
")",
"\n",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Array",
":",
"return",
"int64",
"(",
"topField",
".",
"Len",
"(",
")",
")",
"==",
"int64",
"(",
"field",
".",
"Len",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"fieldType",
":=",
"field",
".",
"Type",
"(",
")",
"\n",
"if",
"fieldType",
"!=",
"topField",
".",
"Type",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"fieldType",
"==",
"timeType",
"{",
"t",
":=",
"field",
".",
"Interface",
"(",
")",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"fieldTime",
":=",
"topField",
".",
"Interface",
"(",
")",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"return",
"fieldTime",
".",
"Equal",
"(",
"t",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"topField",
".",
"String",
"(",
")",
"==",
"field",
".",
"String",
"(",
")",
"\n",
"}"
] |
// IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value.
|
[
"IsEqCrossStructField",
"is",
"the",
"validation",
"function",
"for",
"validating",
"that",
"the",
"current",
"field",
"s",
"value",
"is",
"equal",
"to",
"the",
"field",
"within",
"a",
"separate",
"struct",
"specified",
"by",
"the",
"param",
"s",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L981-L1025
|
train
|
go-playground/validator
|
baked_in.go
|
isEq
|
func isEq(fl FieldLevel) bool {
field := fl.Field()
param := fl.Param()
switch field.Kind() {
case reflect.String:
return field.String() == param
case reflect.Slice, reflect.Map, reflect.Array:
p := asInt(param)
return int64(field.Len()) == p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p := asInt(param)
return field.Int() == p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p := asUint(param)
return field.Uint() == p
case reflect.Float32, reflect.Float64:
p := asFloat(param)
return field.Float() == p
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
go
|
func isEq(fl FieldLevel) bool {
field := fl.Field()
param := fl.Param()
switch field.Kind() {
case reflect.String:
return field.String() == param
case reflect.Slice, reflect.Map, reflect.Array:
p := asInt(param)
return int64(field.Len()) == p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p := asInt(param)
return field.Int() == p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p := asUint(param)
return field.Uint() == p
case reflect.Float32, reflect.Float64:
p := asFloat(param)
return field.Float() == p
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
[
"func",
"isEq",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"param",
":=",
"fl",
".",
"Param",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"return",
"field",
".",
"String",
"(",
")",
"==",
"param",
"\n",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Array",
":",
"p",
":=",
"asInt",
"(",
"param",
")",
"\n",
"return",
"int64",
"(",
"field",
".",
"Len",
"(",
")",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"p",
":=",
"asInt",
"(",
"param",
")",
"\n",
"return",
"field",
".",
"Int",
"(",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
":",
"p",
":=",
"asUint",
"(",
"param",
")",
"\n",
"return",
"field",
".",
"Uint",
"(",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"p",
":=",
"asFloat",
"(",
"param",
")",
"\n",
"return",
"field",
".",
"Float",
"(",
")",
"==",
"p",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}"
] |
// IsEq is the validation function for validating if the current field's value is equal to the param's value.
|
[
"IsEq",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"equal",
"to",
"the",
"param",
"s",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1076-L1108
|
train
|
go-playground/validator
|
baked_in.go
|
isURI
|
func isURI(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
s := field.String()
// checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195
// emulate browser and strip the '#' suffix prior to validation. see issue-#237
if i := strings.Index(s, "#"); i > -1 {
s = s[:i]
}
if len(s) == 0 {
return false
}
_, err := url.ParseRequestURI(s)
return err == nil
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
go
|
func isURI(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
s := field.String()
// checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195
// emulate browser and strip the '#' suffix prior to validation. see issue-#237
if i := strings.Index(s, "#"); i > -1 {
s = s[:i]
}
if len(s) == 0 {
return false
}
_, err := url.ParseRequestURI(s)
return err == nil
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
[
"func",
"isURI",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"s",
":=",
"field",
".",
"String",
"(",
")",
"\n",
"if",
"i",
":=",
"strings",
".",
"Index",
"(",
"s",
",",
"\"#\"",
")",
";",
"i",
">",
"-",
"1",
"{",
"s",
"=",
"s",
"[",
":",
"i",
"]",
"\n",
"}",
"\n",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"url",
".",
"ParseRequestURI",
"(",
"s",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}"
] |
// IsURI is the validation function for validating if the current field's value is a valid URI.
|
[
"IsURI",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"a",
"valid",
"URI",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1121-L1147
|
train
|
go-playground/validator
|
baked_in.go
|
isUrnRFC2141
|
func isUrnRFC2141(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
str := field.String()
_, match := urn.Parse([]byte(str))
return match
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
go
|
func isUrnRFC2141(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
str := field.String()
_, match := urn.Parse([]byte(str))
return match
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
[
"func",
"isUrnRFC2141",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"str",
":=",
"field",
".",
"String",
"(",
")",
"\n",
"_",
",",
"match",
":=",
"urn",
".",
"Parse",
"(",
"[",
"]",
"byte",
"(",
"str",
")",
")",
"\n",
"return",
"match",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}"
] |
// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141.
|
[
"isUrnRFC2141",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"a",
"valid",
"URN",
"as",
"per",
"RFC",
"2141",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1184-L1199
|
train
|
go-playground/validator
|
baked_in.go
|
isFile
|
func isFile(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
fileInfo, err := os.Stat(field.String())
if err != nil {
return false
}
return !fileInfo.IsDir()
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
go
|
func isFile(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
fileInfo, err := os.Stat(field.String())
if err != nil {
return false
}
return !fileInfo.IsDir()
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
[
"func",
"isFile",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"fileInfo",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"field",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"!",
"fileInfo",
".",
"IsDir",
"(",
")",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}"
] |
// IsFile is the validation function for validating if the current field's value is a valid file path.
|
[
"IsFile",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"a",
"valid",
"file",
"path",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1202-L1216
|
train
|
go-playground/validator
|
baked_in.go
|
isNumber
|
func isNumber(fl FieldLevel) bool {
switch fl.Field().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:
return true
default:
return numberRegex.MatchString(fl.Field().String())
}
}
|
go
|
func isNumber(fl FieldLevel) bool {
switch fl.Field().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:
return true
default:
return numberRegex.MatchString(fl.Field().String())
}
}
|
[
"func",
"isNumber",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"switch",
"fl",
".",
"Field",
"(",
")",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
",",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
",",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"numberRegex",
".",
"MatchString",
"(",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// IsNumber is the validation function for validating if the current field's value is a valid number.
|
[
"IsNumber",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"a",
"valid",
"number",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1254-L1261
|
train
|
go-playground/validator
|
baked_in.go
|
hasValue
|
func hasValue(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:
return !field.IsNil()
default:
if fl.(*validate).fldIsPointer && field.Interface() != nil {
return true
}
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
}
|
go
|
func hasValue(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:
return !field.IsNil()
default:
if fl.(*validate).fldIsPointer && field.Interface() != nil {
return true
}
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
}
|
[
"func",
"hasValue",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Ptr",
",",
"reflect",
".",
"Interface",
",",
"reflect",
".",
"Chan",
",",
"reflect",
".",
"Func",
":",
"return",
"!",
"field",
".",
"IsNil",
"(",
")",
"\n",
"default",
":",
"if",
"fl",
".",
"(",
"*",
"validate",
")",
".",
"fldIsPointer",
"&&",
"field",
".",
"Interface",
"(",
")",
"!=",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"field",
".",
"IsValid",
"(",
")",
"&&",
"field",
".",
"Interface",
"(",
")",
"!=",
"reflect",
".",
"Zero",
"(",
"field",
".",
"Type",
"(",
")",
")",
".",
"Interface",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// HasValue is the validation function for validating if the current field's value is not the default static value.
|
[
"HasValue",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"not",
"the",
"default",
"static",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1299-L1314
|
train
|
go-playground/validator
|
baked_in.go
|
isLte
|
func isLte(fl FieldLevel) bool {
field := fl.Field()
param := fl.Param()
switch field.Kind() {
case reflect.String:
p := asInt(param)
return int64(utf8.RuneCountInString(field.String())) <= p
case reflect.Slice, reflect.Map, reflect.Array:
p := asInt(param)
return int64(field.Len()) <= p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p := asInt(param)
return field.Int() <= p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p := asUint(param)
return field.Uint() <= p
case reflect.Float32, reflect.Float64:
p := asFloat(param)
return field.Float() <= p
case reflect.Struct:
if field.Type() == timeType {
now := time.Now().UTC()
t := field.Interface().(time.Time)
return t.Before(now) || t.Equal(now)
}
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
go
|
func isLte(fl FieldLevel) bool {
field := fl.Field()
param := fl.Param()
switch field.Kind() {
case reflect.String:
p := asInt(param)
return int64(utf8.RuneCountInString(field.String())) <= p
case reflect.Slice, reflect.Map, reflect.Array:
p := asInt(param)
return int64(field.Len()) <= p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p := asInt(param)
return field.Int() <= p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p := asUint(param)
return field.Uint() <= p
case reflect.Float32, reflect.Float64:
p := asFloat(param)
return field.Float() <= p
case reflect.Struct:
if field.Type() == timeType {
now := time.Now().UTC()
t := field.Interface().(time.Time)
return t.Before(now) || t.Equal(now)
}
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
|
[
"func",
"isLte",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"field",
":=",
"fl",
".",
"Field",
"(",
")",
"\n",
"param",
":=",
"fl",
".",
"Param",
"(",
")",
"\n",
"switch",
"field",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"p",
":=",
"asInt",
"(",
"param",
")",
"\n",
"return",
"int64",
"(",
"utf8",
".",
"RuneCountInString",
"(",
"field",
".",
"String",
"(",
")",
")",
")",
"<=",
"p",
"\n",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Array",
":",
"p",
":=",
"asInt",
"(",
"param",
")",
"\n",
"return",
"int64",
"(",
"field",
".",
"Len",
"(",
")",
")",
"<=",
"p",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"p",
":=",
"asInt",
"(",
"param",
")",
"\n",
"return",
"field",
".",
"Int",
"(",
")",
"<=",
"p",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
":",
"p",
":=",
"asUint",
"(",
"param",
")",
"\n",
"return",
"field",
".",
"Uint",
"(",
")",
"<=",
"p",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"p",
":=",
"asFloat",
"(",
"param",
")",
"\n",
"return",
"field",
".",
"Float",
"(",
")",
"<=",
"p",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"if",
"field",
".",
"Type",
"(",
")",
"==",
"timeType",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"t",
":=",
"field",
".",
"Interface",
"(",
")",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"return",
"t",
".",
"Before",
"(",
"now",
")",
"||",
"t",
".",
"Equal",
"(",
"now",
")",
"\n",
"}",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Bad field type %T\"",
",",
"field",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}"
] |
// IsLte is the validation function for validating if the current field's value is less than or equal to the param's value.
|
[
"IsLte",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"current",
"field",
"s",
"value",
"is",
"less",
"than",
"or",
"equal",
"to",
"the",
"param",
"s",
"value",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1637-L1681
|
train
|
go-playground/validator
|
baked_in.go
|
isTCP4AddrResolvable
|
func isTCP4AddrResolvable(fl FieldLevel) bool {
if !isIP4Addr(fl) {
return false
}
_, err := net.ResolveTCPAddr("tcp4", fl.Field().String())
return err == nil
}
|
go
|
func isTCP4AddrResolvable(fl FieldLevel) bool {
if !isIP4Addr(fl) {
return false
}
_, err := net.ResolveTCPAddr("tcp4", fl.Field().String())
return err == nil
}
|
[
"func",
"isTCP4AddrResolvable",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"if",
"!",
"isIP4Addr",
"(",
"fl",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"net",
".",
"ResolveTCPAddr",
"(",
"\"tcp4\"",
",",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address.
|
[
"IsTCP4AddrResolvable",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"resolvable",
"tcp4",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1733-L1741
|
train
|
go-playground/validator
|
baked_in.go
|
isUDPAddrResolvable
|
func isUDPAddrResolvable(fl FieldLevel) bool {
if !isIP4Addr(fl) && !isIP6Addr(fl) {
return false
}
_, err := net.ResolveUDPAddr("udp", fl.Field().String())
return err == nil
}
|
go
|
func isUDPAddrResolvable(fl FieldLevel) bool {
if !isIP4Addr(fl) && !isIP6Addr(fl) {
return false
}
_, err := net.ResolveUDPAddr("udp", fl.Field().String())
return err == nil
}
|
[
"func",
"isUDPAddrResolvable",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"if",
"!",
"isIP4Addr",
"(",
"fl",
")",
"&&",
"!",
"isIP6Addr",
"(",
"fl",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"\"udp\"",
",",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address.
|
[
"IsUDPAddrResolvable",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"resolvable",
"udp",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1792-L1801
|
train
|
go-playground/validator
|
baked_in.go
|
isIP4AddrResolvable
|
func isIP4AddrResolvable(fl FieldLevel) bool {
if !isIPv4(fl) {
return false
}
_, err := net.ResolveIPAddr("ip4", fl.Field().String())
return err == nil
}
|
go
|
func isIP4AddrResolvable(fl FieldLevel) bool {
if !isIPv4(fl) {
return false
}
_, err := net.ResolveIPAddr("ip4", fl.Field().String())
return err == nil
}
|
[
"func",
"isIP4AddrResolvable",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"if",
"!",
"isIPv4",
"(",
"fl",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"net",
".",
"ResolveIPAddr",
"(",
"\"ip4\"",
",",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address.
|
[
"IsIP4AddrResolvable",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"resolvable",
"ip4",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1804-L1813
|
train
|
go-playground/validator
|
baked_in.go
|
isIP6AddrResolvable
|
func isIP6AddrResolvable(fl FieldLevel) bool {
if !isIPv6(fl) {
return false
}
_, err := net.ResolveIPAddr("ip6", fl.Field().String())
return err == nil
}
|
go
|
func isIP6AddrResolvable(fl FieldLevel) bool {
if !isIPv6(fl) {
return false
}
_, err := net.ResolveIPAddr("ip6", fl.Field().String())
return err == nil
}
|
[
"func",
"isIP6AddrResolvable",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"if",
"!",
"isIPv6",
"(",
"fl",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"net",
".",
"ResolveIPAddr",
"(",
"\"ip6\"",
",",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address.
|
[
"IsIP6AddrResolvable",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"resolvable",
"ip6",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1816-L1825
|
train
|
go-playground/validator
|
baked_in.go
|
isIPAddrResolvable
|
func isIPAddrResolvable(fl FieldLevel) bool {
if !isIP(fl) {
return false
}
_, err := net.ResolveIPAddr("ip", fl.Field().String())
return err == nil
}
|
go
|
func isIPAddrResolvable(fl FieldLevel) bool {
if !isIP(fl) {
return false
}
_, err := net.ResolveIPAddr("ip", fl.Field().String())
return err == nil
}
|
[
"func",
"isIPAddrResolvable",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"if",
"!",
"isIP",
"(",
"fl",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"net",
".",
"ResolveIPAddr",
"(",
"\"ip\"",
",",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address.
|
[
"IsIPAddrResolvable",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"resolvable",
"ip",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1828-L1837
|
train
|
go-playground/validator
|
baked_in.go
|
isUnixAddrResolvable
|
func isUnixAddrResolvable(fl FieldLevel) bool {
_, err := net.ResolveUnixAddr("unix", fl.Field().String())
return err == nil
}
|
go
|
func isUnixAddrResolvable(fl FieldLevel) bool {
_, err := net.ResolveUnixAddr("unix", fl.Field().String())
return err == nil
}
|
[
"func",
"isUnixAddrResolvable",
"(",
"fl",
"FieldLevel",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"net",
".",
"ResolveUnixAddr",
"(",
"\"unix\"",
",",
"fl",
".",
"Field",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address.
|
[
"IsUnixAddrResolvable",
"is",
"the",
"validation",
"function",
"for",
"validating",
"if",
"the",
"field",
"s",
"value",
"is",
"a",
"resolvable",
"unix",
"address",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1840-L1845
|
train
|
go-playground/validator
|
util.go
|
extractTypeInternal
|
func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) {
BEGIN:
switch current.Kind() {
case reflect.Ptr:
nullable = true
if current.IsNil() {
return current, reflect.Ptr, nullable
}
current = current.Elem()
goto BEGIN
case reflect.Interface:
nullable = true
if current.IsNil() {
return current, reflect.Interface, nullable
}
current = current.Elem()
goto BEGIN
case reflect.Invalid:
return current, reflect.Invalid, nullable
default:
if v.v.hasCustomFuncs {
if fn, ok := v.v.customFuncs[current.Type()]; ok {
current = reflect.ValueOf(fn(current))
goto BEGIN
}
}
return current, current.Kind(), nullable
}
}
|
go
|
func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) {
BEGIN:
switch current.Kind() {
case reflect.Ptr:
nullable = true
if current.IsNil() {
return current, reflect.Ptr, nullable
}
current = current.Elem()
goto BEGIN
case reflect.Interface:
nullable = true
if current.IsNil() {
return current, reflect.Interface, nullable
}
current = current.Elem()
goto BEGIN
case reflect.Invalid:
return current, reflect.Invalid, nullable
default:
if v.v.hasCustomFuncs {
if fn, ok := v.v.customFuncs[current.Type()]; ok {
current = reflect.ValueOf(fn(current))
goto BEGIN
}
}
return current, current.Kind(), nullable
}
}
|
[
"func",
"(",
"v",
"*",
"validate",
")",
"extractTypeInternal",
"(",
"current",
"reflect",
".",
"Value",
",",
"nullable",
"bool",
")",
"(",
"reflect",
".",
"Value",
",",
"reflect",
".",
"Kind",
",",
"bool",
")",
"{",
"BEGIN",
":",
"switch",
"current",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Ptr",
":",
"nullable",
"=",
"true",
"\n",
"if",
"current",
".",
"IsNil",
"(",
")",
"{",
"return",
"current",
",",
"reflect",
".",
"Ptr",
",",
"nullable",
"\n",
"}",
"\n",
"current",
"=",
"current",
".",
"Elem",
"(",
")",
"\n",
"goto",
"BEGIN",
"\n",
"case",
"reflect",
".",
"Interface",
":",
"nullable",
"=",
"true",
"\n",
"if",
"current",
".",
"IsNil",
"(",
")",
"{",
"return",
"current",
",",
"reflect",
".",
"Interface",
",",
"nullable",
"\n",
"}",
"\n",
"current",
"=",
"current",
".",
"Elem",
"(",
")",
"\n",
"goto",
"BEGIN",
"\n",
"case",
"reflect",
".",
"Invalid",
":",
"return",
"current",
",",
"reflect",
".",
"Invalid",
",",
"nullable",
"\n",
"default",
":",
"if",
"v",
".",
"v",
".",
"hasCustomFuncs",
"{",
"if",
"fn",
",",
"ok",
":=",
"v",
".",
"v",
".",
"customFuncs",
"[",
"current",
".",
"Type",
"(",
")",
"]",
";",
"ok",
"{",
"current",
"=",
"reflect",
".",
"ValueOf",
"(",
"fn",
"(",
"current",
")",
")",
"\n",
"goto",
"BEGIN",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"current",
",",
"current",
".",
"Kind",
"(",
")",
",",
"nullable",
"\n",
"}",
"\n",
"}"
] |
// extractTypeInternal gets the actual underlying type of field value.
// It will dive into pointers, customTypes and return you the
// underlying value and it's kind.
|
[
"extractTypeInternal",
"gets",
"the",
"actual",
"underlying",
"type",
"of",
"field",
"value",
".",
"It",
"will",
"dive",
"into",
"pointers",
"customTypes",
"and",
"return",
"you",
"the",
"underlying",
"value",
"and",
"it",
"s",
"kind",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L12-L53
|
train
|
go-playground/validator
|
util.go
|
asInt
|
func asInt(param string) int64 {
i, err := strconv.ParseInt(param, 0, 64)
panicIf(err)
return i
}
|
go
|
func asInt(param string) int64 {
i, err := strconv.ParseInt(param, 0, 64)
panicIf(err)
return i
}
|
[
"func",
"asInt",
"(",
"param",
"string",
")",
"int64",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"param",
",",
"0",
",",
"64",
")",
"\n",
"panicIf",
"(",
"err",
")",
"\n",
"return",
"i",
"\n",
"}"
] |
// asInt returns the parameter as a int64
// or panics if it can't convert
|
[
"asInt",
"returns",
"the",
"parameter",
"as",
"a",
"int64",
"or",
"panics",
"if",
"it",
"can",
"t",
"convert"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L225-L231
|
train
|
go-playground/validator
|
util.go
|
asUint
|
func asUint(param string) uint64 {
i, err := strconv.ParseUint(param, 0, 64)
panicIf(err)
return i
}
|
go
|
func asUint(param string) uint64 {
i, err := strconv.ParseUint(param, 0, 64)
panicIf(err)
return i
}
|
[
"func",
"asUint",
"(",
"param",
"string",
")",
"uint64",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"param",
",",
"0",
",",
"64",
")",
"\n",
"panicIf",
"(",
"err",
")",
"\n",
"return",
"i",
"\n",
"}"
] |
// asUint returns the parameter as a uint64
// or panics if it can't convert
|
[
"asUint",
"returns",
"the",
"parameter",
"as",
"a",
"uint64",
"or",
"panics",
"if",
"it",
"can",
"t",
"convert"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L235-L241
|
train
|
go-playground/validator
|
util.go
|
asFloat
|
func asFloat(param string) float64 {
i, err := strconv.ParseFloat(param, 64)
panicIf(err)
return i
}
|
go
|
func asFloat(param string) float64 {
i, err := strconv.ParseFloat(param, 64)
panicIf(err)
return i
}
|
[
"func",
"asFloat",
"(",
"param",
"string",
")",
"float64",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"param",
",",
"64",
")",
"\n",
"panicIf",
"(",
"err",
")",
"\n",
"return",
"i",
"\n",
"}"
] |
// asFloat returns the parameter as a float64
// or panics if it can't convert
|
[
"asFloat",
"returns",
"the",
"parameter",
"as",
"a",
"float64",
"or",
"panics",
"if",
"it",
"can",
"t",
"convert"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L245-L251
|
train
|
go-playground/validator
|
validator_instance.go
|
New
|
func New() *Validate {
tc := new(tagCache)
tc.m.Store(make(map[string]*cTag))
sc := new(structCache)
sc.m.Store(make(map[reflect.Type]*cStruct))
v := &Validate{
tagName: defaultTagName,
aliases: make(map[string]string, len(bakedInAliases)),
validations: make(map[string]FuncCtx, len(bakedInValidators)),
tagCache: tc,
structCache: sc,
}
// must copy alias validators for separate validations to be used in each validator instance
for k, val := range bakedInAliases {
v.RegisterAlias(k, val)
}
// must copy validators for separate validations to be used in each instance
for k, val := range bakedInValidators {
// no need to error check here, baked in will always be valid
_ = v.registerValidation(k, wrapFunc(val), true)
}
v.pool = &sync.Pool{
New: func() interface{} {
return &validate{
v: v,
ns: make([]byte, 0, 64),
actualNs: make([]byte, 0, 64),
misc: make([]byte, 32),
}
},
}
return v
}
|
go
|
func New() *Validate {
tc := new(tagCache)
tc.m.Store(make(map[string]*cTag))
sc := new(structCache)
sc.m.Store(make(map[reflect.Type]*cStruct))
v := &Validate{
tagName: defaultTagName,
aliases: make(map[string]string, len(bakedInAliases)),
validations: make(map[string]FuncCtx, len(bakedInValidators)),
tagCache: tc,
structCache: sc,
}
// must copy alias validators for separate validations to be used in each validator instance
for k, val := range bakedInAliases {
v.RegisterAlias(k, val)
}
// must copy validators for separate validations to be used in each instance
for k, val := range bakedInValidators {
// no need to error check here, baked in will always be valid
_ = v.registerValidation(k, wrapFunc(val), true)
}
v.pool = &sync.Pool{
New: func() interface{} {
return &validate{
v: v,
ns: make([]byte, 0, 64),
actualNs: make([]byte, 0, 64),
misc: make([]byte, 32),
}
},
}
return v
}
|
[
"func",
"New",
"(",
")",
"*",
"Validate",
"{",
"tc",
":=",
"new",
"(",
"tagCache",
")",
"\n",
"tc",
".",
"m",
".",
"Store",
"(",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"cTag",
")",
")",
"\n",
"sc",
":=",
"new",
"(",
"structCache",
")",
"\n",
"sc",
".",
"m",
".",
"Store",
"(",
"make",
"(",
"map",
"[",
"reflect",
".",
"Type",
"]",
"*",
"cStruct",
")",
")",
"\n",
"v",
":=",
"&",
"Validate",
"{",
"tagName",
":",
"defaultTagName",
",",
"aliases",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"bakedInAliases",
")",
")",
",",
"validations",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"FuncCtx",
",",
"len",
"(",
"bakedInValidators",
")",
")",
",",
"tagCache",
":",
"tc",
",",
"structCache",
":",
"sc",
",",
"}",
"\n",
"for",
"k",
",",
"val",
":=",
"range",
"bakedInAliases",
"{",
"v",
".",
"RegisterAlias",
"(",
"k",
",",
"val",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"val",
":=",
"range",
"bakedInValidators",
"{",
"_",
"=",
"v",
".",
"registerValidation",
"(",
"k",
",",
"wrapFunc",
"(",
"val",
")",
",",
"true",
")",
"\n",
"}",
"\n",
"v",
".",
"pool",
"=",
"&",
"sync",
".",
"Pool",
"{",
"New",
":",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"return",
"&",
"validate",
"{",
"v",
":",
"v",
",",
"ns",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"64",
")",
",",
"actualNs",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"64",
")",
",",
"misc",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
",",
"}",
"\n",
"}",
",",
"}",
"\n",
"return",
"v",
"\n",
"}"
] |
// New returns a new instance of 'validate' with sane defaults.
|
[
"New",
"returns",
"a",
"new",
"instance",
"of",
"validate",
"with",
"sane",
"defaults",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L75-L115
|
train
|
go-playground/validator
|
validator_instance.go
|
RegisterValidationCtx
|
func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx) error {
return v.registerValidation(tag, fn, false)
}
|
go
|
func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx) error {
return v.registerValidation(tag, fn, false)
}
|
[
"func",
"(",
"v",
"*",
"Validate",
")",
"RegisterValidationCtx",
"(",
"tag",
"string",
",",
"fn",
"FuncCtx",
")",
"error",
"{",
"return",
"v",
".",
"registerValidation",
"(",
"tag",
",",
"fn",
",",
"false",
")",
"\n",
"}"
] |
// RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation
// allowing context.Context validation support.
|
[
"RegisterValidationCtx",
"does",
"the",
"same",
"as",
"RegisterValidation",
"on",
"accepts",
"a",
"FuncCtx",
"validation",
"allowing",
"context",
".",
"Context",
"validation",
"support",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L149-L151
|
train
|
go-playground/validator
|
validator_instance.go
|
RegisterTranslation
|
func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) {
if v.transTagFunc == nil {
v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc)
}
if err = registerFn(trans); err != nil {
return
}
m, ok := v.transTagFunc[trans]
if !ok {
m = make(map[string]TranslationFunc)
v.transTagFunc[trans] = m
}
m[tag] = translationFn
return
}
|
go
|
func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) {
if v.transTagFunc == nil {
v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc)
}
if err = registerFn(trans); err != nil {
return
}
m, ok := v.transTagFunc[trans]
if !ok {
m = make(map[string]TranslationFunc)
v.transTagFunc[trans] = m
}
m[tag] = translationFn
return
}
|
[
"func",
"(",
"v",
"*",
"Validate",
")",
"RegisterTranslation",
"(",
"tag",
"string",
",",
"trans",
"ut",
".",
"Translator",
",",
"registerFn",
"RegisterTranslationsFunc",
",",
"translationFn",
"TranslationFunc",
")",
"(",
"err",
"error",
")",
"{",
"if",
"v",
".",
"transTagFunc",
"==",
"nil",
"{",
"v",
".",
"transTagFunc",
"=",
"make",
"(",
"map",
"[",
"ut",
".",
"Translator",
"]",
"map",
"[",
"string",
"]",
"TranslationFunc",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"registerFn",
"(",
"trans",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"m",
",",
"ok",
":=",
"v",
".",
"transTagFunc",
"[",
"trans",
"]",
"\n",
"if",
"!",
"ok",
"{",
"m",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"TranslationFunc",
")",
"\n",
"v",
".",
"transTagFunc",
"[",
"trans",
"]",
"=",
"m",
"\n",
"}",
"\n",
"m",
"[",
"tag",
"]",
"=",
"translationFn",
"\n",
"return",
"\n",
"}"
] |
// RegisterTranslation registers translations against the provided tag.
|
[
"RegisterTranslation",
"registers",
"translations",
"against",
"the",
"provided",
"tag",
"."
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L236-L255
|
train
|
go-playground/validator
|
validator.go
|
validateStruct
|
func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) {
cs, ok := v.v.structCache.Get(typ)
if !ok {
cs = v.v.extractStructCache(current, typ.Name())
}
if len(ns) == 0 && len(cs.name) != 0 {
ns = append(ns, cs.name...)
ns = append(ns, '.')
structNs = append(structNs, cs.name...)
structNs = append(structNs, '.')
}
// ct is nil on top level struct, and structs as fields that have no tag info
// so if nil or if not nil and the structonly tag isn't present
if ct == nil || ct.typeof != typeStructOnly {
var f *cField
for i := 0; i < len(cs.fields); i++ {
f = cs.fields[i]
if v.isPartial {
if v.ffn != nil {
// used with StructFiltered
if v.ffn(append(structNs, f.name...)) {
continue
}
} else {
// used with StructPartial & StructExcept
_, ok = v.includeExclude[string(append(structNs, f.name...))]
if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) {
continue
}
}
}
v.traverseField(ctx, parent, current.Field(f.idx), ns, structNs, f, f.cTags)
}
}
// check if any struct level validations, after all field validations already checked.
// first iteration will have no info about nostructlevel tag, and is checked prior to
// calling the next iteration of validateStruct called from traverseField.
if cs.fn != nil {
v.slflParent = parent
v.slCurrent = current
v.ns = ns
v.actualNs = structNs
cs.fn(ctx, v)
}
}
|
go
|
func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) {
cs, ok := v.v.structCache.Get(typ)
if !ok {
cs = v.v.extractStructCache(current, typ.Name())
}
if len(ns) == 0 && len(cs.name) != 0 {
ns = append(ns, cs.name...)
ns = append(ns, '.')
structNs = append(structNs, cs.name...)
structNs = append(structNs, '.')
}
// ct is nil on top level struct, and structs as fields that have no tag info
// so if nil or if not nil and the structonly tag isn't present
if ct == nil || ct.typeof != typeStructOnly {
var f *cField
for i := 0; i < len(cs.fields); i++ {
f = cs.fields[i]
if v.isPartial {
if v.ffn != nil {
// used with StructFiltered
if v.ffn(append(structNs, f.name...)) {
continue
}
} else {
// used with StructPartial & StructExcept
_, ok = v.includeExclude[string(append(structNs, f.name...))]
if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) {
continue
}
}
}
v.traverseField(ctx, parent, current.Field(f.idx), ns, structNs, f, f.cTags)
}
}
// check if any struct level validations, after all field validations already checked.
// first iteration will have no info about nostructlevel tag, and is checked prior to
// calling the next iteration of validateStruct called from traverseField.
if cs.fn != nil {
v.slflParent = parent
v.slCurrent = current
v.ns = ns
v.actualNs = structNs
cs.fn(ctx, v)
}
}
|
[
"func",
"(",
"v",
"*",
"validate",
")",
"validateStruct",
"(",
"ctx",
"context",
".",
"Context",
",",
"parent",
"reflect",
".",
"Value",
",",
"current",
"reflect",
".",
"Value",
",",
"typ",
"reflect",
".",
"Type",
",",
"ns",
"[",
"]",
"byte",
",",
"structNs",
"[",
"]",
"byte",
",",
"ct",
"*",
"cTag",
")",
"{",
"cs",
",",
"ok",
":=",
"v",
".",
"v",
".",
"structCache",
".",
"Get",
"(",
"typ",
")",
"\n",
"if",
"!",
"ok",
"{",
"cs",
"=",
"v",
".",
"v",
".",
"extractStructCache",
"(",
"current",
",",
"typ",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ns",
")",
"==",
"0",
"&&",
"len",
"(",
"cs",
".",
"name",
")",
"!=",
"0",
"{",
"ns",
"=",
"append",
"(",
"ns",
",",
"cs",
".",
"name",
"...",
")",
"\n",
"ns",
"=",
"append",
"(",
"ns",
",",
"'.'",
")",
"\n",
"structNs",
"=",
"append",
"(",
"structNs",
",",
"cs",
".",
"name",
"...",
")",
"\n",
"structNs",
"=",
"append",
"(",
"structNs",
",",
"'.'",
")",
"\n",
"}",
"\n",
"if",
"ct",
"==",
"nil",
"||",
"ct",
".",
"typeof",
"!=",
"typeStructOnly",
"{",
"var",
"f",
"*",
"cField",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"cs",
".",
"fields",
")",
";",
"i",
"++",
"{",
"f",
"=",
"cs",
".",
"fields",
"[",
"i",
"]",
"\n",
"if",
"v",
".",
"isPartial",
"{",
"if",
"v",
".",
"ffn",
"!=",
"nil",
"{",
"if",
"v",
".",
"ffn",
"(",
"append",
"(",
"structNs",
",",
"f",
".",
"name",
"...",
")",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"else",
"{",
"_",
",",
"ok",
"=",
"v",
".",
"includeExclude",
"[",
"string",
"(",
"append",
"(",
"structNs",
",",
"f",
".",
"name",
"...",
")",
")",
"]",
"\n",
"if",
"(",
"ok",
"&&",
"v",
".",
"hasExcludes",
")",
"||",
"(",
"!",
"ok",
"&&",
"!",
"v",
".",
"hasExcludes",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"v",
".",
"traverseField",
"(",
"ctx",
",",
"parent",
",",
"current",
".",
"Field",
"(",
"f",
".",
"idx",
")",
",",
"ns",
",",
"structNs",
",",
"f",
",",
"f",
".",
"cTags",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cs",
".",
"fn",
"!=",
"nil",
"{",
"v",
".",
"slflParent",
"=",
"parent",
"\n",
"v",
".",
"slCurrent",
"=",
"current",
"\n",
"v",
".",
"ns",
"=",
"ns",
"\n",
"v",
".",
"actualNs",
"=",
"structNs",
"\n",
"cs",
".",
"fn",
"(",
"ctx",
",",
"v",
")",
"\n",
"}",
"\n",
"}"
] |
// parent and current will be the same the first run of validateStruct
|
[
"parent",
"and",
"current",
"will",
"be",
"the",
"same",
"the",
"first",
"run",
"of",
"validateStruct"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator.go#L33-L93
|
train
|
go-playground/validator
|
field_level.go
|
GetStructFieldOK
|
func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) {
return v.getStructFieldOKInternal(v.slflParent, v.ct.param)
}
|
go
|
func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) {
return v.getStructFieldOKInternal(v.slflParent, v.ct.param)
}
|
[
"func",
"(",
"v",
"*",
"validate",
")",
"GetStructFieldOK",
"(",
")",
"(",
"reflect",
".",
"Value",
",",
"reflect",
".",
"Kind",
",",
"bool",
")",
"{",
"return",
"v",
".",
"getStructFieldOKInternal",
"(",
"v",
".",
"slflParent",
",",
"v",
".",
"ct",
".",
"param",
")",
"\n",
"}"
] |
// GetStructFieldOK returns Param returns param for validation against current field
|
[
"GetStructFieldOK",
"returns",
"Param",
"returns",
"param",
"for",
"validation",
"against",
"current",
"field"
] |
e25e66164b537d7b3161dfede38466880534e783
|
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/field_level.go#L67-L69
|
train
|
muesli/beehive
|
api/resources/actions/actions.go
|
Register
|
func (r *ActionResource) Register(container *restful.Container, config smolder.APIConfig, context smolder.APIContextFactory) {
r.Name = "ActionResource"
r.TypeName = "action"
r.Endpoint = "actions"
r.Doc = "Manage actions"
r.Config = config
r.Context = context
r.Init(container, r)
}
|
go
|
func (r *ActionResource) Register(container *restful.Container, config smolder.APIConfig, context smolder.APIContextFactory) {
r.Name = "ActionResource"
r.TypeName = "action"
r.Endpoint = "actions"
r.Doc = "Manage actions"
r.Config = config
r.Context = context
r.Init(container, r)
}
|
[
"func",
"(",
"r",
"*",
"ActionResource",
")",
"Register",
"(",
"container",
"*",
"restful",
".",
"Container",
",",
"config",
"smolder",
".",
"APIConfig",
",",
"context",
"smolder",
".",
"APIContextFactory",
")",
"{",
"r",
".",
"Name",
"=",
"\"ActionResource\"",
"\n",
"r",
".",
"TypeName",
"=",
"\"action\"",
"\n",
"r",
".",
"Endpoint",
"=",
"\"actions\"",
"\n",
"r",
".",
"Doc",
"=",
"\"Manage actions\"",
"\n",
"r",
".",
"Config",
"=",
"config",
"\n",
"r",
".",
"Context",
"=",
"context",
"\n",
"r",
".",
"Init",
"(",
"container",
",",
"r",
")",
"\n",
"}"
] |
// Register this resource with the container to setup all the routes
|
[
"Register",
"this",
"resource",
"with",
"the",
"container",
"to",
"setup",
"all",
"the",
"routes"
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/actions/actions.go#L40-L50
|
train
|
muesli/beehive
|
api/resources/bees/bees.go
|
Validate
|
func (r *BeeResource) Validate(context smolder.APIContext, data interface{}, request *restful.Request) error {
// ps := data.(*BeePostStruct)
// FIXME
return nil
}
|
go
|
func (r *BeeResource) Validate(context smolder.APIContext, data interface{}, request *restful.Request) error {
// ps := data.(*BeePostStruct)
// FIXME
return nil
}
|
[
"func",
"(",
"r",
"*",
"BeeResource",
")",
"Validate",
"(",
"context",
"smolder",
".",
"APIContext",
",",
"data",
"interface",
"{",
"}",
",",
"request",
"*",
"restful",
".",
"Request",
")",
"error",
"{",
"return",
"nil",
"\n",
"}"
] |
// Validate checks an incoming request for data errors
|
[
"Validate",
"checks",
"an",
"incoming",
"request",
"for",
"data",
"errors"
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/bees/bees.go#L65-L69
|
train
|
muesli/beehive
|
bees/bees.go
|
RegisterBee
|
func RegisterBee(bee BeeInterface) {
log.Println("Worker bee ready:", bee.Name(), "-", bee.Description())
bees[bee.Name()] = &bee
}
|
go
|
func RegisterBee(bee BeeInterface) {
log.Println("Worker bee ready:", bee.Name(), "-", bee.Description())
bees[bee.Name()] = &bee
}
|
[
"func",
"RegisterBee",
"(",
"bee",
"BeeInterface",
")",
"{",
"log",
".",
"Println",
"(",
"\"Worker bee ready:\"",
",",
"bee",
".",
"Name",
"(",
")",
",",
"\"-\"",
",",
"bee",
".",
"Description",
"(",
")",
")",
"\n",
"bees",
"[",
"bee",
".",
"Name",
"(",
")",
"]",
"=",
"&",
"bee",
"\n",
"}"
] |
// RegisterBee gets called by Bees to register themselves.
|
[
"RegisterBee",
"gets",
"called",
"by",
"Bees",
"to",
"register",
"themselves",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L99-L103
|
train
|
muesli/beehive
|
bees/bees.go
|
GetBee
|
func GetBee(identifier string) *BeeInterface {
bee, ok := bees[identifier]
if ok {
return bee
}
return nil
}
|
go
|
func GetBee(identifier string) *BeeInterface {
bee, ok := bees[identifier]
if ok {
return bee
}
return nil
}
|
[
"func",
"GetBee",
"(",
"identifier",
"string",
")",
"*",
"BeeInterface",
"{",
"bee",
",",
"ok",
":=",
"bees",
"[",
"identifier",
"]",
"\n",
"if",
"ok",
"{",
"return",
"bee",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// GetBee returns a bee with a specific name.
|
[
"GetBee",
"returns",
"a",
"bee",
"with",
"a",
"specific",
"name",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L106-L113
|
train
|
muesli/beehive
|
bees/bees.go
|
GetBees
|
func GetBees() []*BeeInterface {
r := []*BeeInterface{}
for _, bee := range bees {
r = append(r, bee)
}
return r
}
|
go
|
func GetBees() []*BeeInterface {
r := []*BeeInterface{}
for _, bee := range bees {
r = append(r, bee)
}
return r
}
|
[
"func",
"GetBees",
"(",
")",
"[",
"]",
"*",
"BeeInterface",
"{",
"r",
":=",
"[",
"]",
"*",
"BeeInterface",
"{",
"}",
"\n",
"for",
"_",
",",
"bee",
":=",
"range",
"bees",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"bee",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// GetBees returns all known bees.
|
[
"GetBees",
"returns",
"all",
"known",
"bees",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L116-L123
|
train
|
muesli/beehive
|
bees/bees.go
|
startBee
|
func startBee(bee *BeeInterface, fatals int) {
if fatals >= 3 {
log.Println("Terminating evil bee", (*bee).Name(), "after", fatals, "failed tries!")
(*bee).Stop()
return
}
(*bee).WaitGroup().Add(1)
defer (*bee).WaitGroup().Done()
defer func(bee *BeeInterface) {
if e := recover(); e != nil {
log.Println("Fatal bee event:", e, fatals)
go startBee(bee, fatals+1)
}
}(bee)
(*bee).Run(eventsIn)
}
|
go
|
func startBee(bee *BeeInterface, fatals int) {
if fatals >= 3 {
log.Println("Terminating evil bee", (*bee).Name(), "after", fatals, "failed tries!")
(*bee).Stop()
return
}
(*bee).WaitGroup().Add(1)
defer (*bee).WaitGroup().Done()
defer func(bee *BeeInterface) {
if e := recover(); e != nil {
log.Println("Fatal bee event:", e, fatals)
go startBee(bee, fatals+1)
}
}(bee)
(*bee).Run(eventsIn)
}
|
[
"func",
"startBee",
"(",
"bee",
"*",
"BeeInterface",
",",
"fatals",
"int",
")",
"{",
"if",
"fatals",
">=",
"3",
"{",
"log",
".",
"Println",
"(",
"\"Terminating evil bee\"",
",",
"(",
"*",
"bee",
")",
".",
"Name",
"(",
")",
",",
"\"after\"",
",",
"fatals",
",",
"\"failed tries!\"",
")",
"\n",
"(",
"*",
"bee",
")",
".",
"Stop",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"(",
"*",
"bee",
")",
".",
"WaitGroup",
"(",
")",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"(",
"*",
"bee",
")",
".",
"WaitGroup",
"(",
")",
".",
"Done",
"(",
")",
"\n",
"defer",
"func",
"(",
"bee",
"*",
"BeeInterface",
")",
"{",
"if",
"e",
":=",
"recover",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"Fatal bee event:\"",
",",
"e",
",",
"fatals",
")",
"\n",
"go",
"startBee",
"(",
"bee",
",",
"fatals",
"+",
"1",
")",
"\n",
"}",
"\n",
"}",
"(",
"bee",
")",
"\n",
"(",
"*",
"bee",
")",
".",
"Run",
"(",
"eventsIn",
")",
"\n",
"}"
] |
// startBee starts a bee and recovers from panics.
|
[
"startBee",
"starts",
"a",
"bee",
"and",
"recovers",
"from",
"panics",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L126-L144
|
train
|
muesli/beehive
|
bees/bees.go
|
NewBeeInstance
|
func NewBeeInstance(bee BeeConfig) *BeeInterface {
factory := GetFactory(bee.Class)
if factory == nil {
panic("Unknown bee-class in config file: " + bee.Class)
}
mod := (*factory).New(bee.Name, bee.Description, bee.Options)
RegisterBee(mod)
return &mod
}
|
go
|
func NewBeeInstance(bee BeeConfig) *BeeInterface {
factory := GetFactory(bee.Class)
if factory == nil {
panic("Unknown bee-class in config file: " + bee.Class)
}
mod := (*factory).New(bee.Name, bee.Description, bee.Options)
RegisterBee(mod)
return &mod
}
|
[
"func",
"NewBeeInstance",
"(",
"bee",
"BeeConfig",
")",
"*",
"BeeInterface",
"{",
"factory",
":=",
"GetFactory",
"(",
"bee",
".",
"Class",
")",
"\n",
"if",
"factory",
"==",
"nil",
"{",
"panic",
"(",
"\"Unknown bee-class in config file: \"",
"+",
"bee",
".",
"Class",
")",
"\n",
"}",
"\n",
"mod",
":=",
"(",
"*",
"factory",
")",
".",
"New",
"(",
"bee",
".",
"Name",
",",
"bee",
".",
"Description",
",",
"bee",
".",
"Options",
")",
"\n",
"RegisterBee",
"(",
"mod",
")",
"\n",
"return",
"&",
"mod",
"\n",
"}"
] |
// NewBeeInstance sets up a new Bee with supplied config.
|
[
"NewBeeInstance",
"sets",
"up",
"a",
"new",
"Bee",
"with",
"supplied",
"config",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L147-L156
|
train
|
muesli/beehive
|
bees/bees.go
|
StartBee
|
func StartBee(bee BeeConfig) *BeeInterface {
b := NewBeeInstance(bee)
(*b).Start()
go func(mod *BeeInterface) {
startBee(mod, 0)
}(b)
return b
}
|
go
|
func StartBee(bee BeeConfig) *BeeInterface {
b := NewBeeInstance(bee)
(*b).Start()
go func(mod *BeeInterface) {
startBee(mod, 0)
}(b)
return b
}
|
[
"func",
"StartBee",
"(",
"bee",
"BeeConfig",
")",
"*",
"BeeInterface",
"{",
"b",
":=",
"NewBeeInstance",
"(",
"bee",
")",
"\n",
"(",
"*",
"b",
")",
".",
"Start",
"(",
")",
"\n",
"go",
"func",
"(",
"mod",
"*",
"BeeInterface",
")",
"{",
"startBee",
"(",
"mod",
",",
"0",
")",
"\n",
"}",
"(",
"b",
")",
"\n",
"return",
"b",
"\n",
"}"
] |
// StartBee starts a bee.
|
[
"StartBee",
"starts",
"a",
"bee",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L166-L175
|
train
|
muesli/beehive
|
bees/bees.go
|
StartBees
|
func StartBees(beeList []BeeConfig) {
eventsIn = make(chan Event)
go handleEvents()
for _, bee := range beeList {
StartBee(bee)
}
}
|
go
|
func StartBees(beeList []BeeConfig) {
eventsIn = make(chan Event)
go handleEvents()
for _, bee := range beeList {
StartBee(bee)
}
}
|
[
"func",
"StartBees",
"(",
"beeList",
"[",
"]",
"BeeConfig",
")",
"{",
"eventsIn",
"=",
"make",
"(",
"chan",
"Event",
")",
"\n",
"go",
"handleEvents",
"(",
")",
"\n",
"for",
"_",
",",
"bee",
":=",
"range",
"beeList",
"{",
"StartBee",
"(",
"bee",
")",
"\n",
"}",
"\n",
"}"
] |
// StartBees starts all registered bees.
|
[
"StartBees",
"starts",
"all",
"registered",
"bees",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L178-L185
|
train
|
muesli/beehive
|
bees/bees.go
|
StopBees
|
func StopBees() {
for _, bee := range bees {
log.Println("Stopping bee:", (*bee).Name())
(*bee).Stop()
}
close(eventsIn)
bees = make(map[string]*BeeInterface)
}
|
go
|
func StopBees() {
for _, bee := range bees {
log.Println("Stopping bee:", (*bee).Name())
(*bee).Stop()
}
close(eventsIn)
bees = make(map[string]*BeeInterface)
}
|
[
"func",
"StopBees",
"(",
")",
"{",
"for",
"_",
",",
"bee",
":=",
"range",
"bees",
"{",
"log",
".",
"Println",
"(",
"\"Stopping bee:\"",
",",
"(",
"*",
"bee",
")",
".",
"Name",
"(",
")",
")",
"\n",
"(",
"*",
"bee",
")",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"close",
"(",
"eventsIn",
")",
"\n",
"bees",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"BeeInterface",
")",
"\n",
"}"
] |
// StopBees stops all bees gracefully.
|
[
"StopBees",
"stops",
"all",
"bees",
"gracefully",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L188-L196
|
train
|
muesli/beehive
|
bees/bees.go
|
RestartBee
|
func RestartBee(bee *BeeInterface) {
(*bee).Stop()
(*bee).SetSigChan(make(chan bool))
(*bee).Start()
go func(mod *BeeInterface) {
startBee(mod, 0)
}(bee)
}
|
go
|
func RestartBee(bee *BeeInterface) {
(*bee).Stop()
(*bee).SetSigChan(make(chan bool))
(*bee).Start()
go func(mod *BeeInterface) {
startBee(mod, 0)
}(bee)
}
|
[
"func",
"RestartBee",
"(",
"bee",
"*",
"BeeInterface",
")",
"{",
"(",
"*",
"bee",
")",
".",
"Stop",
"(",
")",
"\n",
"(",
"*",
"bee",
")",
".",
"SetSigChan",
"(",
"make",
"(",
"chan",
"bool",
")",
")",
"\n",
"(",
"*",
"bee",
")",
".",
"Start",
"(",
")",
"\n",
"go",
"func",
"(",
"mod",
"*",
"BeeInterface",
")",
"{",
"startBee",
"(",
"mod",
",",
"0",
")",
"\n",
"}",
"(",
"bee",
")",
"\n",
"}"
] |
// RestartBee restarts a Bee.
|
[
"RestartBee",
"restarts",
"a",
"Bee",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L199-L207
|
train
|
muesli/beehive
|
bees/bees.go
|
NewBee
|
func NewBee(name, factoryName, description string, options []BeeOption) Bee {
c := BeeConfig{
Name: name,
Class: factoryName,
Description: description,
Options: options,
}
b := Bee{
config: c,
SigChan: make(chan bool),
waitGroup: &sync.WaitGroup{},
}
return b
}
|
go
|
func NewBee(name, factoryName, description string, options []BeeOption) Bee {
c := BeeConfig{
Name: name,
Class: factoryName,
Description: description,
Options: options,
}
b := Bee{
config: c,
SigChan: make(chan bool),
waitGroup: &sync.WaitGroup{},
}
return b
}
|
[
"func",
"NewBee",
"(",
"name",
",",
"factoryName",
",",
"description",
"string",
",",
"options",
"[",
"]",
"BeeOption",
")",
"Bee",
"{",
"c",
":=",
"BeeConfig",
"{",
"Name",
":",
"name",
",",
"Class",
":",
"factoryName",
",",
"Description",
":",
"description",
",",
"Options",
":",
"options",
",",
"}",
"\n",
"b",
":=",
"Bee",
"{",
"config",
":",
"c",
",",
"SigChan",
":",
"make",
"(",
"chan",
"bool",
")",
",",
"waitGroup",
":",
"&",
"sync",
".",
"WaitGroup",
"{",
"}",
",",
"}",
"\n",
"return",
"b",
"\n",
"}"
] |
// NewBee returns a new bee and sets up sig-channel & waitGroup.
|
[
"NewBee",
"returns",
"a",
"new",
"bee",
"and",
"sets",
"up",
"sig",
"-",
"channel",
"&",
"waitGroup",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L216-L230
|
train
|
muesli/beehive
|
bees/bees.go
|
Stop
|
func (bee *Bee) Stop() {
if !bee.IsRunning() {
return
}
log.Println(bee.Name(), "stopping gracefully!")
close(bee.SigChan)
bee.waitGroup.Wait()
bee.Running = false
log.Println(bee.Name(), "stopped gracefully!")
}
|
go
|
func (bee *Bee) Stop() {
if !bee.IsRunning() {
return
}
log.Println(bee.Name(), "stopping gracefully!")
close(bee.SigChan)
bee.waitGroup.Wait()
bee.Running = false
log.Println(bee.Name(), "stopped gracefully!")
}
|
[
"func",
"(",
"bee",
"*",
"Bee",
")",
"Stop",
"(",
")",
"{",
"if",
"!",
"bee",
".",
"IsRunning",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"bee",
".",
"Name",
"(",
")",
",",
"\"stopping gracefully!\"",
")",
"\n",
"close",
"(",
"bee",
".",
"SigChan",
")",
"\n",
"bee",
".",
"waitGroup",
".",
"Wait",
"(",
")",
"\n",
"bee",
".",
"Running",
"=",
"false",
"\n",
"log",
".",
"Println",
"(",
"bee",
".",
"Name",
"(",
")",
",",
"\"stopped gracefully!\"",
")",
"\n",
"}"
] |
// Stop gracefully stops a Bee.
|
[
"Stop",
"gracefully",
"stops",
"a",
"Bee",
"."
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L301-L311
|
train
|
muesli/beehive
|
bees/bees.go
|
Logln
|
func (bee *Bee) Logln(args ...interface{}) {
a := []interface{}{"[" + bee.Name() + "]:"}
for _, v := range args {
a = append(a, v)
}
log.Println(a...)
Log(bee.Name(), fmt.Sprintln(args...), 0)
}
|
go
|
func (bee *Bee) Logln(args ...interface{}) {
a := []interface{}{"[" + bee.Name() + "]:"}
for _, v := range args {
a = append(a, v)
}
log.Println(a...)
Log(bee.Name(), fmt.Sprintln(args...), 0)
}
|
[
"func",
"(",
"bee",
"*",
"Bee",
")",
"Logln",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"a",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"\"[\"",
"+",
"bee",
".",
"Name",
"(",
")",
"+",
"\"]:\"",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"args",
"{",
"a",
"=",
"append",
"(",
"a",
",",
"v",
")",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"a",
"...",
")",
"\n",
"Log",
"(",
"bee",
".",
"Name",
"(",
")",
",",
"fmt",
".",
"Sprintln",
"(",
"args",
"...",
")",
",",
"0",
")",
"\n",
"}"
] |
// Logln logs args
|
[
"Logln",
"logs",
"args"
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L334-L342
|
train
|
muesli/beehive
|
bees/bees.go
|
Logf
|
func (bee *Bee) Logf(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
log.Printf("[%s]: %s", bee.Name(), s)
Log(bee.Name(), s, 0)
}
|
go
|
func (bee *Bee) Logf(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
log.Printf("[%s]: %s", bee.Name(), s)
Log(bee.Name(), s, 0)
}
|
[
"func",
"(",
"bee",
"*",
"Bee",
")",
"Logf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"s",
":=",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"[%s]: %s\"",
",",
"bee",
".",
"Name",
"(",
")",
",",
"s",
")",
"\n",
"Log",
"(",
"bee",
".",
"Name",
"(",
")",
",",
"s",
",",
"0",
")",
"\n",
"}"
] |
// Logf logs a formatted string
|
[
"Logf",
"logs",
"a",
"formatted",
"string"
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L345-L349
|
train
|
muesli/beehive
|
bees/bees.go
|
LogErrorf
|
func (bee *Bee) LogErrorf(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
log.Errorf("[%s]: %s", bee.Name(), s)
Log(bee.Name(), s, 1)
}
|
go
|
func (bee *Bee) LogErrorf(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
log.Errorf("[%s]: %s", bee.Name(), s)
Log(bee.Name(), s, 1)
}
|
[
"func",
"(",
"bee",
"*",
"Bee",
")",
"LogErrorf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"s",
":=",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
"\n",
"log",
".",
"Errorf",
"(",
"\"[%s]: %s\"",
",",
"bee",
".",
"Name",
"(",
")",
",",
"s",
")",
"\n",
"Log",
"(",
"bee",
".",
"Name",
"(",
")",
",",
"s",
",",
"1",
")",
"\n",
"}"
] |
// LogErrorf logs a formatted error string
|
[
"LogErrorf",
"logs",
"a",
"formatted",
"error",
"string"
] |
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
|
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L352-L356
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.