repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
goreleaser/goreleaser
internal/artifact/artifact.go
ByType
func ByType(t Type) Filter { return func(a Artifact) bool { return a.Type == t } }
go
func ByType(t Type) Filter { return func(a Artifact) bool { return a.Type == t } }
[ "func", "ByType", "(", "t", "Type", ")", "Filter", "{", "return", "func", "(", "a", "Artifact", ")", "bool", "{", "return", "a", ".", "Type", "==", "t", "\n", "}", "\n", "}" ]
// ByType is a predefined filter that filters by the given type
[ "ByType", "is", "a", "predefined", "filter", "that", "filters", "by", "the", "given", "type" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L190-L194
train
goreleaser/goreleaser
internal/artifact/artifact.go
ByIDs
func ByIDs(ids ...string) Filter { var filters = make([]Filter, 0, len(ids)) for _, id := range ids { id := id filters = append(filters, func(a Artifact) bool { return a.ExtraOr("ID", "") == id }) } return Or(filters...) }
go
func ByIDs(ids ...string) Filter { var filters = make([]Filter, 0, len(ids)) for _, id := range ids { id := id filters = append(filters, func(a Artifact) bool { return a.ExtraOr("ID", "") == id }) } return Or(filters...) }
[ "func", "ByIDs", "(", "ids", "...", "string", ")", "Filter", "{", "var", "filters", "=", "make", "(", "[", "]", "Filter", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "id", ":=", "id", "\n", "filters", "=", "append", "(", "filters", ",", "func", "(", "a", "Artifact", ")", "bool", "{", "return", "a", ".", "ExtraOr", "(", "\"ID\"", ",", "\"\"", ")", "==", "id", "\n", "}", ")", "\n", "}", "\n", "return", "Or", "(", "filters", "...", ")", "\n", "}" ]
// ByIDs filter artifacts by an `ID` extra field.
[ "ByIDs", "filter", "artifacts", "by", "an", "ID", "extra", "field", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L197-L206
train
goreleaser/goreleaser
internal/artifact/artifact.go
Or
func Or(filters ...Filter) Filter { return func(a Artifact) bool { for _, f := range filters { if f(a) { return true } } return false } }
go
func Or(filters ...Filter) Filter { return func(a Artifact) bool { for _, f := range filters { if f(a) { return true } } return false } }
[ "func", "Or", "(", "filters", "...", "Filter", ")", "Filter", "{", "return", "func", "(", "a", "Artifact", ")", "bool", "{", "for", "_", ",", "f", ":=", "range", "filters", "{", "if", "f", "(", "a", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "}" ]
// Or performs an OR between all given filters
[ "Or", "performs", "an", "OR", "between", "all", "given", "filters" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L209-L218
train
goreleaser/goreleaser
internal/artifact/artifact.go
Filter
func (artifacts *Artifacts) Filter(filter Filter) Artifacts { var result = New() for _, a := range artifacts.items { if filter(a) { result.items = append(result.items, a) } } return result }
go
func (artifacts *Artifacts) Filter(filter Filter) Artifacts { var result = New() for _, a := range artifacts.items { if filter(a) { result.items = append(result.items, a) } } return result }
[ "func", "(", "artifacts", "*", "Artifacts", ")", "Filter", "(", "filter", "Filter", ")", "Artifacts", "{", "var", "result", "=", "New", "(", ")", "\n", "for", "_", ",", "a", ":=", "range", "artifacts", ".", "items", "{", "if", "filter", "(", "a", ")", "{", "result", ".", "items", "=", "append", "(", "result", ".", "items", ",", "a", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Filter filters the artifact list, returning a new instance. // There are some pre-defined filters but anything of the Type Filter // is accepted. // You can compose filters by using the And and Or filters.
[ "Filter", "filters", "the", "artifact", "list", "returning", "a", "new", "instance", ".", "There", "are", "some", "pre", "-", "defined", "filters", "but", "anything", "of", "the", "Type", "Filter", "is", "accepted", ".", "You", "can", "compose", "filters", "by", "using", "the", "And", "and", "Or", "filters", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L236-L244
train
goreleaser/goreleaser
internal/pipe/sign/sign.go
Default
func (Pipe) Default(ctx *context.Context) error { cfg := &ctx.Config.Sign if cfg.Cmd == "" { cfg.Cmd = "gpg" } if cfg.Signature == "" { cfg.Signature = "${artifact}.sig" } if len(cfg.Args) == 0 { cfg.Args = []string{"--output", "$signature", "--detach-sig", "$artifact"} } if cfg.Artifacts == "" { cfg.Artifacts = "none" } return nil }
go
func (Pipe) Default(ctx *context.Context) error { cfg := &ctx.Config.Sign if cfg.Cmd == "" { cfg.Cmd = "gpg" } if cfg.Signature == "" { cfg.Signature = "${artifact}.sig" } if len(cfg.Args) == 0 { cfg.Args = []string{"--output", "$signature", "--detach-sig", "$artifact"} } if cfg.Artifacts == "" { cfg.Artifacts = "none" } return nil }
[ "func", "(", "Pipe", ")", "Default", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "cfg", ":=", "&", "ctx", ".", "Config", ".", "Sign", "\n", "if", "cfg", ".", "Cmd", "==", "\"\"", "{", "cfg", ".", "Cmd", "=", "\"gpg\"", "\n", "}", "\n", "if", "cfg", ".", "Signature", "==", "\"\"", "{", "cfg", ".", "Signature", "=", "\"${artifact}.sig\"", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "Args", ")", "==", "0", "{", "cfg", ".", "Args", "=", "[", "]", "string", "{", "\"--output\"", ",", "\"$signature\"", ",", "\"--detach-sig\"", ",", "\"$artifact\"", "}", "\n", "}", "\n", "if", "cfg", ".", "Artifacts", "==", "\"\"", "{", "cfg", ".", "Artifacts", "=", "\"none\"", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Default sets the Pipes defaults.
[ "Default", "sets", "the", "Pipes", "defaults", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/sign/sign.go#L23-L38
train
goreleaser/goreleaser
internal/pipe/sign/sign.go
Run
func (Pipe) Run(ctx *context.Context) error { if ctx.SkipSign { return pipe.ErrSkipSignEnabled } switch ctx.Config.Sign.Artifacts { case "checksum": return sign(ctx, ctx.Artifacts.Filter(artifact.ByType(artifact.Checksum)).List()) case "all": return sign(ctx, ctx.Artifacts.Filter( artifact.Or( artifact.ByType(artifact.UploadableArchive), artifact.ByType(artifact.UploadableBinary), artifact.ByType(artifact.Checksum), artifact.ByType(artifact.LinuxPackage), )).List()) case "none": return pipe.ErrSkipSignEnabled default: return fmt.Errorf("invalid list of artifacts to sign: %s", ctx.Config.Sign.Artifacts) } }
go
func (Pipe) Run(ctx *context.Context) error { if ctx.SkipSign { return pipe.ErrSkipSignEnabled } switch ctx.Config.Sign.Artifacts { case "checksum": return sign(ctx, ctx.Artifacts.Filter(artifact.ByType(artifact.Checksum)).List()) case "all": return sign(ctx, ctx.Artifacts.Filter( artifact.Or( artifact.ByType(artifact.UploadableArchive), artifact.ByType(artifact.UploadableBinary), artifact.ByType(artifact.Checksum), artifact.ByType(artifact.LinuxPackage), )).List()) case "none": return pipe.ErrSkipSignEnabled default: return fmt.Errorf("invalid list of artifacts to sign: %s", ctx.Config.Sign.Artifacts) } }
[ "func", "(", "Pipe", ")", "Run", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "if", "ctx", ".", "SkipSign", "{", "return", "pipe", ".", "ErrSkipSignEnabled", "\n", "}", "\n", "switch", "ctx", ".", "Config", ".", "Sign", ".", "Artifacts", "{", "case", "\"checksum\"", ":", "return", "sign", "(", "ctx", ",", "ctx", ".", "Artifacts", ".", "Filter", "(", "artifact", ".", "ByType", "(", "artifact", ".", "Checksum", ")", ")", ".", "List", "(", ")", ")", "\n", "case", "\"all\"", ":", "return", "sign", "(", "ctx", ",", "ctx", ".", "Artifacts", ".", "Filter", "(", "artifact", ".", "Or", "(", "artifact", ".", "ByType", "(", "artifact", ".", "UploadableArchive", ")", ",", "artifact", ".", "ByType", "(", "artifact", ".", "UploadableBinary", ")", ",", "artifact", ".", "ByType", "(", "artifact", ".", "Checksum", ")", ",", "artifact", ".", "ByType", "(", "artifact", ".", "LinuxPackage", ")", ",", ")", ")", ".", "List", "(", ")", ")", "\n", "case", "\"none\"", ":", "return", "pipe", ".", "ErrSkipSignEnabled", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"invalid list of artifacts to sign: %s\"", ",", "ctx", ".", "Config", ".", "Sign", ".", "Artifacts", ")", "\n", "}", "\n", "}" ]
// Run executes the Pipe.
[ "Run", "executes", "the", "Pipe", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/sign/sign.go#L41-L62
train
goreleaser/goreleaser
pkg/build/build.go
Register
func Register(lang string, builder Builder) { lock.Lock() builders[lang] = builder lock.Unlock() }
go
func Register(lang string, builder Builder) { lock.Lock() builders[lang] = builder lock.Unlock() }
[ "func", "Register", "(", "lang", "string", ",", "builder", "Builder", ")", "{", "lock", ".", "Lock", "(", ")", "\n", "builders", "[", "lang", "]", "=", "builder", "\n", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// Register registers a builder to a given lang
[ "Register", "registers", "a", "builder", "to", "a", "given", "lang" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/build/build.go#L18-L22
train
goreleaser/goreleaser
internal/builders/golang/build.go
WithDefaults
func (*Builder) WithDefaults(build config.Build) config.Build { if build.Main == "" { build.Main = "." } if len(build.Goos) == 0 { build.Goos = []string{"linux", "darwin"} } if len(build.Goarch) == 0 { build.Goarch = []string{"amd64", "386"} } if len(build.Goarm) == 0 { build.Goarm = []string{"6"} } if len(build.Ldflags) == 0 { build.Ldflags = []string{"-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}"} } if len(build.Targets) == 0 { build.Targets = matrix(build) } return build }
go
func (*Builder) WithDefaults(build config.Build) config.Build { if build.Main == "" { build.Main = "." } if len(build.Goos) == 0 { build.Goos = []string{"linux", "darwin"} } if len(build.Goarch) == 0 { build.Goarch = []string{"amd64", "386"} } if len(build.Goarm) == 0 { build.Goarm = []string{"6"} } if len(build.Ldflags) == 0 { build.Ldflags = []string{"-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}"} } if len(build.Targets) == 0 { build.Targets = matrix(build) } return build }
[ "func", "(", "*", "Builder", ")", "WithDefaults", "(", "build", "config", ".", "Build", ")", "config", ".", "Build", "{", "if", "build", ".", "Main", "==", "\"\"", "{", "build", ".", "Main", "=", "\".\"", "\n", "}", "\n", "if", "len", "(", "build", ".", "Goos", ")", "==", "0", "{", "build", ".", "Goos", "=", "[", "]", "string", "{", "\"linux\"", ",", "\"darwin\"", "}", "\n", "}", "\n", "if", "len", "(", "build", ".", "Goarch", ")", "==", "0", "{", "build", ".", "Goarch", "=", "[", "]", "string", "{", "\"amd64\"", ",", "\"386\"", "}", "\n", "}", "\n", "if", "len", "(", "build", ".", "Goarm", ")", "==", "0", "{", "build", ".", "Goarm", "=", "[", "]", "string", "{", "\"6\"", "}", "\n", "}", "\n", "if", "len", "(", "build", ".", "Ldflags", ")", "==", "0", "{", "build", ".", "Ldflags", "=", "[", "]", "string", "{", "\"-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}\"", "}", "\n", "}", "\n", "if", "len", "(", "build", ".", "Targets", ")", "==", "0", "{", "build", ".", "Targets", "=", "matrix", "(", "build", ")", "\n", "}", "\n", "return", "build", "\n", "}" ]
// WithDefaults sets the defaults for a golang build and returns it
[ "WithDefaults", "sets", "the", "defaults", "for", "a", "golang", "build", "and", "returns", "it" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/builders/golang/build.go#L34-L54
train
goreleaser/goreleaser
internal/builders/golang/build.go
Build
func (*Builder) Build(ctx *context.Context, build config.Build, options api.Options) error { if err := checkMain(build); err != nil { return err } target, err := newBuildTarget(options.Target) if err != nil { return err } var cmd = []string{"go", "build"} var env = append(ctx.Env.Strings(), build.Env...) env = append(env, target.Env()...) flags, err := processFlags(ctx, env, build.Flags, "") if err != nil { return err } cmd = append(cmd, flags...) asmflags, err := processFlags(ctx, env, build.Asmflags, "-asmflags=") if err != nil { return err } cmd = append(cmd, asmflags...) gcflags, err := processFlags(ctx, env, build.Gcflags, "-gcflags=") if err != nil { return err } cmd = append(cmd, gcflags...) ldflags, err := processFlags(ctx, env, build.Ldflags, "-ldflags=") if err != nil { return err } cmd = append(cmd, ldflags...) cmd = append(cmd, "-o", options.Path, build.Main) if err := run(ctx, cmd, env); err != nil { return errors.Wrapf(err, "failed to build for %s", options.Target) } ctx.Artifacts.Add(artifact.Artifact{ Type: artifact.Binary, Path: options.Path, Name: options.Name, Goos: target.os, Goarch: target.arch, Goarm: target.arm, Extra: map[string]interface{}{ "Binary": build.Binary, "Ext": options.Ext, "ID": build.ID, }, }) return nil }
go
func (*Builder) Build(ctx *context.Context, build config.Build, options api.Options) error { if err := checkMain(build); err != nil { return err } target, err := newBuildTarget(options.Target) if err != nil { return err } var cmd = []string{"go", "build"} var env = append(ctx.Env.Strings(), build.Env...) env = append(env, target.Env()...) flags, err := processFlags(ctx, env, build.Flags, "") if err != nil { return err } cmd = append(cmd, flags...) asmflags, err := processFlags(ctx, env, build.Asmflags, "-asmflags=") if err != nil { return err } cmd = append(cmd, asmflags...) gcflags, err := processFlags(ctx, env, build.Gcflags, "-gcflags=") if err != nil { return err } cmd = append(cmd, gcflags...) ldflags, err := processFlags(ctx, env, build.Ldflags, "-ldflags=") if err != nil { return err } cmd = append(cmd, ldflags...) cmd = append(cmd, "-o", options.Path, build.Main) if err := run(ctx, cmd, env); err != nil { return errors.Wrapf(err, "failed to build for %s", options.Target) } ctx.Artifacts.Add(artifact.Artifact{ Type: artifact.Binary, Path: options.Path, Name: options.Name, Goos: target.os, Goarch: target.arch, Goarm: target.arm, Extra: map[string]interface{}{ "Binary": build.Binary, "Ext": options.Ext, "ID": build.ID, }, }) return nil }
[ "func", "(", "*", "Builder", ")", "Build", "(", "ctx", "*", "context", ".", "Context", ",", "build", "config", ".", "Build", ",", "options", "api", ".", "Options", ")", "error", "{", "if", "err", ":=", "checkMain", "(", "build", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "target", ",", "err", ":=", "newBuildTarget", "(", "options", ".", "Target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "cmd", "=", "[", "]", "string", "{", "\"go\"", ",", "\"build\"", "}", "\n", "var", "env", "=", "append", "(", "ctx", ".", "Env", ".", "Strings", "(", ")", ",", "build", ".", "Env", "...", ")", "\n", "env", "=", "append", "(", "env", ",", "target", ".", "Env", "(", ")", "...", ")", "\n", "flags", ",", "err", ":=", "processFlags", "(", "ctx", ",", "env", ",", "build", ".", "Flags", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cmd", "=", "append", "(", "cmd", ",", "flags", "...", ")", "\n", "asmflags", ",", "err", ":=", "processFlags", "(", "ctx", ",", "env", ",", "build", ".", "Asmflags", ",", "\"-asmflags=\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cmd", "=", "append", "(", "cmd", ",", "asmflags", "...", ")", "\n", "gcflags", ",", "err", ":=", "processFlags", "(", "ctx", ",", "env", ",", "build", ".", "Gcflags", ",", "\"-gcflags=\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cmd", "=", "append", "(", "cmd", ",", "gcflags", "...", ")", "\n", "ldflags", ",", "err", ":=", "processFlags", "(", "ctx", ",", "env", ",", "build", ".", "Ldflags", ",", "\"-ldflags=\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cmd", "=", "append", "(", "cmd", ",", "ldflags", "...", ")", "\n", "cmd", "=", "append", "(", "cmd", ",", "\"-o\"", ",", "options", ".", "Path", ",", "build", ".", "Main", ")", "\n", "if", "err", ":=", "run", "(", "ctx", ",", "cmd", ",", "env", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"failed to build for %s\"", ",", "options", ".", "Target", ")", "\n", "}", "\n", "ctx", ".", "Artifacts", ".", "Add", "(", "artifact", ".", "Artifact", "{", "Type", ":", "artifact", ".", "Binary", ",", "Path", ":", "options", ".", "Path", ",", "Name", ":", "options", ".", "Name", ",", "Goos", ":", "target", ".", "os", ",", "Goarch", ":", "target", ".", "arch", ",", "Goarm", ":", "target", ".", "arm", ",", "Extra", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "\"Binary\"", ":", "build", ".", "Binary", ",", "\"Ext\"", ":", "options", ".", "Ext", ",", "\"ID\"", ":", "build", ".", "ID", ",", "}", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Build builds a golang build
[ "Build", "builds", "a", "golang", "build" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/builders/golang/build.go#L57-L113
train
goreleaser/goreleaser
internal/pipe/docker/docker.go
Publish
func (Pipe) Publish(ctx *context.Context) error { var images = ctx.Artifacts.Filter(artifact.ByType(artifact.PublishableDockerImage)).List() for _, image := range images { if err := dockerPush(ctx, image); err != nil { return err } } return nil }
go
func (Pipe) Publish(ctx *context.Context) error { var images = ctx.Artifacts.Filter(artifact.ByType(artifact.PublishableDockerImage)).List() for _, image := range images { if err := dockerPush(ctx, image); err != nil { return err } } return nil }
[ "func", "(", "Pipe", ")", "Publish", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "var", "images", "=", "ctx", ".", "Artifacts", ".", "Filter", "(", "artifact", ".", "ByType", "(", "artifact", ".", "PublishableDockerImage", ")", ")", ".", "List", "(", ")", "\n", "for", "_", ",", "image", ":=", "range", "images", "{", "if", "err", ":=", "dockerPush", "(", "ctx", ",", "image", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Publish the docker images
[ "Publish", "the", "docker", "images" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/docker/docker.go#L94-L102
train
goreleaser/goreleaser
internal/pipe/docker/docker.go
link
func link(src, dest string) error { return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } // We have the following: // - src = "a/b" // - dest = "dist/linuxamd64/b" // - path = "a/b/c.txt" // So we join "a/b" with "c.txt" and use it as the destination. var dst = filepath.Join(dest, strings.Replace(path, src, "", 1)) log.WithFields(log.Fields{ "src": path, "dst": dst, }).Debug("extra file") if info.IsDir() { return os.MkdirAll(dst, info.Mode()) } return os.Link(path, dst) }) }
go
func link(src, dest string) error { return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } // We have the following: // - src = "a/b" // - dest = "dist/linuxamd64/b" // - path = "a/b/c.txt" // So we join "a/b" with "c.txt" and use it as the destination. var dst = filepath.Join(dest, strings.Replace(path, src, "", 1)) log.WithFields(log.Fields{ "src": path, "dst": dst, }).Debug("extra file") if info.IsDir() { return os.MkdirAll(dst, info.Mode()) } return os.Link(path, dst) }) }
[ "func", "link", "(", "src", ",", "dest", "string", ")", "error", "{", "return", "filepath", ".", "Walk", "(", "src", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "dst", "=", "filepath", ".", "Join", "(", "dest", ",", "strings", ".", "Replace", "(", "path", ",", "src", ",", "\"\"", ",", "1", ")", ")", "\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"src\"", ":", "path", ",", "\"dst\"", ":", "dst", ",", "}", ")", ".", "Debug", "(", "\"extra file\"", ")", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "os", ".", "MkdirAll", "(", "dst", ",", "info", ".", "Mode", "(", ")", ")", "\n", "}", "\n", "return", "os", ".", "Link", "(", "path", ",", "dst", ")", "\n", "}", ")", "\n", "}" ]
// walks the src, recreating dirs and hard-linking files
[ "walks", "the", "src", "recreating", "dirs", "and", "hard", "-", "linking", "files" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/docker/docker.go#L246-L266
train
goreleaser/goreleaser
internal/middleware/logging.go
Logging
func Logging(title string, next Action, padding Padding) Action { return func(ctx *context.Context) error { defer func() { cli.Default.Padding = int(DefaultInitialPadding) }() cli.Default.Padding = int(padding) log.Infof(color.New(color.Bold).Sprint(strings.ToUpper(title))) cli.Default.Padding = int(padding + DefaultInitialPadding) return next(ctx) } }
go
func Logging(title string, next Action, padding Padding) Action { return func(ctx *context.Context) error { defer func() { cli.Default.Padding = int(DefaultInitialPadding) }() cli.Default.Padding = int(padding) log.Infof(color.New(color.Bold).Sprint(strings.ToUpper(title))) cli.Default.Padding = int(padding + DefaultInitialPadding) return next(ctx) } }
[ "func", "Logging", "(", "title", "string", ",", "next", "Action", ",", "padding", "Padding", ")", "Action", "{", "return", "func", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "defer", "func", "(", ")", "{", "cli", ".", "Default", ".", "Padding", "=", "int", "(", "DefaultInitialPadding", ")", "\n", "}", "(", ")", "\n", "cli", ".", "Default", ".", "Padding", "=", "int", "(", "padding", ")", "\n", "log", ".", "Infof", "(", "color", ".", "New", "(", "color", ".", "Bold", ")", ".", "Sprint", "(", "strings", ".", "ToUpper", "(", "title", ")", ")", ")", "\n", "cli", ".", "Default", ".", "Padding", "=", "int", "(", "padding", "+", "DefaultInitialPadding", ")", "\n", "return", "next", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// Logging pretty prints the given action and its title. // You can have different padding levels by providing different initial // paddings. The middleware will print the title in the given padding and the // action logs in padding+default padding. // The default padding in the log library is 3. // The middleware always resets to the default padding.
[ "Logging", "pretty", "prints", "the", "given", "action", "and", "its", "title", ".", "You", "can", "have", "different", "padding", "levels", "by", "providing", "different", "initial", "paddings", ".", "The", "middleware", "will", "print", "the", "title", "in", "the", "given", "padding", "and", "the", "action", "logs", "in", "padding", "+", "default", "padding", ".", "The", "default", "padding", "in", "the", "log", "library", "is", "3", ".", "The", "middleware", "always", "resets", "to", "the", "default", "padding", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/middleware/logging.go#L27-L37
train
goreleaser/goreleaser
pkg/config/config.go
Load
func Load(file string) (config Project, err error) { f, err := os.Open(file) // #nosec if err != nil { return } log.WithField("file", file).Info("loading config file") return LoadReader(f) }
go
func Load(file string) (config Project, err error) { f, err := os.Open(file) // #nosec if err != nil { return } log.WithField("file", file).Info("loading config file") return LoadReader(f) }
[ "func", "Load", "(", "file", "string", ")", "(", "config", "Project", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "log", ".", "WithField", "(", "\"file\"", ",", "file", ")", ".", "Info", "(", "\"loading config file\"", ")", "\n", "return", "LoadReader", "(", "f", ")", "\n", "}" ]
// Load config file
[ "Load", "config", "file" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/config/config.go#L342-L349
train
goreleaser/goreleaser
pkg/config/config.go
LoadReader
func LoadReader(fd io.Reader) (config Project, err error) { data, err := ioutil.ReadAll(fd) if err != nil { return config, err } err = yaml.UnmarshalStrict(data, &config) log.WithField("config", config).Debug("loaded config file") return config, err }
go
func LoadReader(fd io.Reader) (config Project, err error) { data, err := ioutil.ReadAll(fd) if err != nil { return config, err } err = yaml.UnmarshalStrict(data, &config) log.WithField("config", config).Debug("loaded config file") return config, err }
[ "func", "LoadReader", "(", "fd", "io", ".", "Reader", ")", "(", "config", "Project", ",", "err", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "fd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "config", ",", "err", "\n", "}", "\n", "err", "=", "yaml", ".", "UnmarshalStrict", "(", "data", ",", "&", "config", ")", "\n", "log", ".", "WithField", "(", "\"config\"", ",", "config", ")", ".", "Debug", "(", "\"loaded config file\"", ")", "\n", "return", "config", ",", "err", "\n", "}" ]
// LoadReader config via io.Reader
[ "LoadReader", "config", "via", "io", ".", "Reader" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/config/config.go#L352-L360
train
goreleaser/goreleaser
pkg/archive/archive.go
New
func New(file *os.File) Archive { if strings.HasSuffix(file.Name(), ".tar.gz") { return targz.New(file) } if strings.HasSuffix(file.Name(), ".gz") { return gzip.New(file) } if strings.HasSuffix(file.Name(), ".zip") { return zip.New(file) } return targz.New(file) }
go
func New(file *os.File) Archive { if strings.HasSuffix(file.Name(), ".tar.gz") { return targz.New(file) } if strings.HasSuffix(file.Name(), ".gz") { return gzip.New(file) } if strings.HasSuffix(file.Name(), ".zip") { return zip.New(file) } return targz.New(file) }
[ "func", "New", "(", "file", "*", "os", ".", "File", ")", "Archive", "{", "if", "strings", ".", "HasSuffix", "(", "file", ".", "Name", "(", ")", ",", "\".tar.gz\"", ")", "{", "return", "targz", ".", "New", "(", "file", ")", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "file", ".", "Name", "(", ")", ",", "\".gz\"", ")", "{", "return", "gzip", ".", "New", "(", "file", ")", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "file", ".", "Name", "(", ")", ",", "\".zip\"", ")", "{", "return", "zip", ".", "New", "(", "file", ")", "\n", "}", "\n", "return", "targz", ".", "New", "(", "file", ")", "\n", "}" ]
// New archive.
[ "New", "archive", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/archive/archive.go#L20-L31
train
goreleaser/goreleaser
main.go
initProject
func initProject(filename string) error { if _, err := os.Stat(filename); !os.IsNotExist(err) { if err != nil { return err } return fmt.Errorf("%s already exists", filename) } log.Infof(color.New(color.Bold).Sprintf("Generating %s file", filename)) return ioutil.WriteFile(filename, []byte(static.ExampleConfig), 0644) }
go
func initProject(filename string) error { if _, err := os.Stat(filename); !os.IsNotExist(err) { if err != nil { return err } return fmt.Errorf("%s already exists", filename) } log.Infof(color.New(color.Bold).Sprintf("Generating %s file", filename)) return ioutil.WriteFile(filename, []byte(static.ExampleConfig), 0644) }
[ "func", "initProject", "(", "filename", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filename", ")", ";", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"%s already exists\"", ",", "filename", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "color", ".", "New", "(", "color", ".", "Bold", ")", ".", "Sprintf", "(", "\"Generating %s file\"", ",", "filename", ")", ")", "\n", "return", "ioutil", ".", "WriteFile", "(", "filename", ",", "[", "]", "byte", "(", "static", ".", "ExampleConfig", ")", ",", "0644", ")", "\n", "}" ]
// InitProject creates an example goreleaser.yml in the current directory
[ "InitProject", "creates", "an", "example", "goreleaser", ".", "yml", "in", "the", "current", "directory" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/main.go#L135-L144
train
goreleaser/goreleaser
pkg/archive/gzip/gzip.go
New
func New(target io.Writer) Archive { gw := gzip.NewWriter(target) return Archive{ gw: gw, } }
go
func New(target io.Writer) Archive { gw := gzip.NewWriter(target) return Archive{ gw: gw, } }
[ "func", "New", "(", "target", "io", ".", "Writer", ")", "Archive", "{", "gw", ":=", "gzip", ".", "NewWriter", "(", "target", ")", "\n", "return", "Archive", "{", "gw", ":", "gw", ",", "}", "\n", "}" ]
// New gz archive
[ "New", "gz", "archive" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/archive/gzip/gzip.go#L23-L28
train
goreleaser/goreleaser
pkg/context/context.go
Strings
func (e Env) Strings() []string { var result = make([]string, 0, len(e)) for k, v := range e { result = append(result, k+"="+v) } return result }
go
func (e Env) Strings() []string { var result = make([]string, 0, len(e)) for k, v := range e { result = append(result, k+"="+v) } return result }
[ "func", "(", "e", "Env", ")", "Strings", "(", ")", "[", "]", "string", "{", "var", "result", "=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "e", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "e", "{", "result", "=", "append", "(", "result", ",", "k", "+", "\"=\"", "+", "v", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Strings returns the current environment as a list of strings, suitable for // os executions.
[ "Strings", "returns", "the", "current", "environment", "as", "a", "list", "of", "strings", "suitable", "for", "os", "executions", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/context/context.go#L33-L39
train
goreleaser/goreleaser
pkg/context/context.go
NewWithTimeout
func NewWithTimeout(config config.Project, timeout time.Duration) (*Context, ctx.CancelFunc) { ctx, cancel := ctx.WithTimeout(ctx.Background(), timeout) return Wrap(ctx, config), cancel }
go
func NewWithTimeout(config config.Project, timeout time.Duration) (*Context, ctx.CancelFunc) { ctx, cancel := ctx.WithTimeout(ctx.Background(), timeout) return Wrap(ctx, config), cancel }
[ "func", "NewWithTimeout", "(", "config", "config", ".", "Project", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "Context", ",", "ctx", ".", "CancelFunc", ")", "{", "ctx", ",", "cancel", ":=", "ctx", ".", "WithTimeout", "(", "ctx", ".", "Background", "(", ")", ",", "timeout", ")", "\n", "return", "Wrap", "(", "ctx", ",", "config", ")", ",", "cancel", "\n", "}" ]
// NewWithTimeout new context with the given timeout
[ "NewWithTimeout", "new", "context", "with", "the", "given", "timeout" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/context/context.go#L75-L78
train
goreleaser/goreleaser
pkg/context/context.go
Wrap
func Wrap(ctx ctx.Context, config config.Project) *Context { return &Context{ Context: ctx, Config: config, Env: splitEnv(append(os.Environ(), config.Env...)), Parallelism: 4, Artifacts: artifact.New(), } }
go
func Wrap(ctx ctx.Context, config config.Project) *Context { return &Context{ Context: ctx, Config: config, Env: splitEnv(append(os.Environ(), config.Env...)), Parallelism: 4, Artifacts: artifact.New(), } }
[ "func", "Wrap", "(", "ctx", "ctx", ".", "Context", ",", "config", "config", ".", "Project", ")", "*", "Context", "{", "return", "&", "Context", "{", "Context", ":", "ctx", ",", "Config", ":", "config", ",", "Env", ":", "splitEnv", "(", "append", "(", "os", ".", "Environ", "(", ")", ",", "config", ".", "Env", "...", ")", ")", ",", "Parallelism", ":", "4", ",", "Artifacts", ":", "artifact", ".", "New", "(", ")", ",", "}", "\n", "}" ]
// Wrap wraps an existing context
[ "Wrap", "wraps", "an", "existing", "context" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/context/context.go#L81-L89
train
goreleaser/goreleaser
internal/git/git.go
IsRepo
func IsRepo() bool { out, err := Run("rev-parse", "--is-inside-work-tree") return err == nil && strings.TrimSpace(out) == "true" }
go
func IsRepo() bool { out, err := Run("rev-parse", "--is-inside-work-tree") return err == nil && strings.TrimSpace(out) == "true" }
[ "func", "IsRepo", "(", ")", "bool", "{", "out", ",", "err", ":=", "Run", "(", "\"rev-parse\"", ",", "\"--is-inside-work-tree\"", ")", "\n", "return", "err", "==", "nil", "&&", "strings", ".", "TrimSpace", "(", "out", ")", "==", "\"true\"", "\n", "}" ]
// IsRepo returns true if current folder is a git repository
[ "IsRepo", "returns", "true", "if", "current", "folder", "is", "a", "git", "repository" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/git/git.go#L13-L16
train
goreleaser/goreleaser
internal/git/git.go
Run
func Run(args ...string) (string, error) { // TODO: use exex.CommandContext here and refactor. var extraArgs = []string{ "-c", "log.showSignature=false", } args = append(extraArgs, args...) /* #nosec */ var cmd = exec.Command("git", args...) log.WithField("args", args).Debug("running git") bts, err := cmd.CombinedOutput() log.WithField("output", string(bts)). Debug("git result") if err != nil { return "", errors.New(string(bts)) } return string(bts), nil }
go
func Run(args ...string) (string, error) { // TODO: use exex.CommandContext here and refactor. var extraArgs = []string{ "-c", "log.showSignature=false", } args = append(extraArgs, args...) /* #nosec */ var cmd = exec.Command("git", args...) log.WithField("args", args).Debug("running git") bts, err := cmd.CombinedOutput() log.WithField("output", string(bts)). Debug("git result") if err != nil { return "", errors.New(string(bts)) } return string(bts), nil }
[ "func", "Run", "(", "args", "...", "string", ")", "(", "string", ",", "error", ")", "{", "var", "extraArgs", "=", "[", "]", "string", "{", "\"-c\"", ",", "\"log.showSignature=false\"", ",", "}", "\n", "args", "=", "append", "(", "extraArgs", ",", "args", "...", ")", "\n", "var", "cmd", "=", "exec", ".", "Command", "(", "\"git\"", ",", "args", "...", ")", "\n", "log", ".", "WithField", "(", "\"args\"", ",", "args", ")", ".", "Debug", "(", "\"running git\"", ")", "\n", "bts", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "log", ".", "WithField", "(", "\"output\"", ",", "string", "(", "bts", ")", ")", ".", "Debug", "(", "\"git result\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "string", "(", "bts", ")", ")", "\n", "}", "\n", "return", "string", "(", "bts", ")", ",", "nil", "\n", "}" ]
// Run runs a git command and returns its output or errors
[ "Run", "runs", "a", "git", "command", "and", "returns", "its", "output", "or", "errors" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/git/git.go#L19-L35
train
goreleaser/goreleaser
internal/git/git.go
Clean
func Clean(output string, err error) (string, error) { output = strings.Replace(strings.Split(output, "\n")[0], "'", "", -1) if err != nil { err = errors.New(strings.TrimSuffix(err.Error(), "\n")) } return output, err }
go
func Clean(output string, err error) (string, error) { output = strings.Replace(strings.Split(output, "\n")[0], "'", "", -1) if err != nil { err = errors.New(strings.TrimSuffix(err.Error(), "\n")) } return output, err }
[ "func", "Clean", "(", "output", "string", ",", "err", "error", ")", "(", "string", ",", "error", ")", "{", "output", "=", "strings", ".", "Replace", "(", "strings", ".", "Split", "(", "output", ",", "\"\\n\"", ")", "[", "\\n", "]", ",", "0", ",", "\"'\"", ",", "\"\"", ")", "\n", "-", "1", "\n", "if", "err", "!=", "nil", "{", "err", "=", "errors", ".", "New", "(", "strings", ".", "TrimSuffix", "(", "err", ".", "Error", "(", ")", ",", "\"\\n\"", ")", ")", "\n", "}", "\n", "}" ]
// Clean the output
[ "Clean", "the", "output" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/git/git.go#L38-L44
train
goreleaser/goreleaser
internal/pipe/brew/brew.go
Publish
func (Pipe) Publish(ctx *context.Context) error { client, err := client.NewGitHub(ctx) if err != nil { return err } return doRun(ctx, client) }
go
func (Pipe) Publish(ctx *context.Context) error { client, err := client.NewGitHub(ctx) if err != nil { return err } return doRun(ctx, client) }
[ "func", "(", "Pipe", ")", "Publish", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "client", ",", "err", ":=", "client", ".", "NewGitHub", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "doRun", "(", "ctx", ",", "client", ")", "\n", "}" ]
// Publish brew formula
[ "Publish", "brew", "formula" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/brew/brew.go#L36-L42
train
goreleaser/goreleaser
internal/client/github.go
NewGitHub
func NewGitHub(ctx *context.Context) (Client, error) { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: ctx.Token}, ) httpClient := oauth2.NewClient(ctx, ts) base := httpClient.Transport.(*oauth2.Transport).Base // nolint: govet if &base != nil { base = http.DefaultTransport } // nolint: gosec base.(*http.Transport).TLSClientConfig = &tls.Config{ InsecureSkipVerify: ctx.Config.GitHubURLs.SkipTLSVerify, } httpClient.Transport.(*oauth2.Transport).Base = base client := github.NewClient(httpClient) if ctx.Config.GitHubURLs.API != "" { api, err := url.Parse(ctx.Config.GitHubURLs.API) if err != nil { return &githubClient{}, err } upload, err := url.Parse(ctx.Config.GitHubURLs.Upload) if err != nil { return &githubClient{}, err } client.BaseURL = api client.UploadURL = upload } return &githubClient{client: client}, nil }
go
func NewGitHub(ctx *context.Context) (Client, error) { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: ctx.Token}, ) httpClient := oauth2.NewClient(ctx, ts) base := httpClient.Transport.(*oauth2.Transport).Base // nolint: govet if &base != nil { base = http.DefaultTransport } // nolint: gosec base.(*http.Transport).TLSClientConfig = &tls.Config{ InsecureSkipVerify: ctx.Config.GitHubURLs.SkipTLSVerify, } httpClient.Transport.(*oauth2.Transport).Base = base client := github.NewClient(httpClient) if ctx.Config.GitHubURLs.API != "" { api, err := url.Parse(ctx.Config.GitHubURLs.API) if err != nil { return &githubClient{}, err } upload, err := url.Parse(ctx.Config.GitHubURLs.Upload) if err != nil { return &githubClient{}, err } client.BaseURL = api client.UploadURL = upload } return &githubClient{client: client}, nil }
[ "func", "NewGitHub", "(", "ctx", "*", "context", ".", "Context", ")", "(", "Client", ",", "error", ")", "{", "ts", ":=", "oauth2", ".", "StaticTokenSource", "(", "&", "oauth2", ".", "Token", "{", "AccessToken", ":", "ctx", ".", "Token", "}", ",", ")", "\n", "httpClient", ":=", "oauth2", ".", "NewClient", "(", "ctx", ",", "ts", ")", "\n", "base", ":=", "httpClient", ".", "Transport", ".", "(", "*", "oauth2", ".", "Transport", ")", ".", "Base", "\n", "if", "&", "base", "!=", "nil", "{", "base", "=", "http", ".", "DefaultTransport", "\n", "}", "\n", "base", ".", "(", "*", "http", ".", "Transport", ")", ".", "TLSClientConfig", "=", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "ctx", ".", "Config", ".", "GitHubURLs", ".", "SkipTLSVerify", ",", "}", "\n", "httpClient", ".", "Transport", ".", "(", "*", "oauth2", ".", "Transport", ")", ".", "Base", "=", "base", "\n", "client", ":=", "github", ".", "NewClient", "(", "httpClient", ")", "\n", "if", "ctx", ".", "Config", ".", "GitHubURLs", ".", "API", "!=", "\"\"", "{", "api", ",", "err", ":=", "url", ".", "Parse", "(", "ctx", ".", "Config", ".", "GitHubURLs", ".", "API", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "githubClient", "{", "}", ",", "err", "\n", "}", "\n", "upload", ",", "err", ":=", "url", ".", "Parse", "(", "ctx", ".", "Config", ".", "GitHubURLs", ".", "Upload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "githubClient", "{", "}", ",", "err", "\n", "}", "\n", "client", ".", "BaseURL", "=", "api", "\n", "client", ".", "UploadURL", "=", "upload", "\n", "}", "\n", "return", "&", "githubClient", "{", "client", ":", "client", "}", ",", "nil", "\n", "}" ]
// NewGitHub returns a github client implementation
[ "NewGitHub", "returns", "a", "github", "client", "implementation" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/client/github.go#L23-L53
train
goreleaser/goreleaser
internal/pipe/s3/s3.go
Publish
func (Pipe) Publish(ctx *context.Context) error { if len(ctx.Config.S3) == 0 { return pipe.Skip("s3 section is not configured") } var g = semerrgroup.New(ctx.Parallelism) for _, conf := range ctx.Config.S3 { conf := conf g.Go(func() error { return upload(ctx, conf) }) } return g.Wait() }
go
func (Pipe) Publish(ctx *context.Context) error { if len(ctx.Config.S3) == 0 { return pipe.Skip("s3 section is not configured") } var g = semerrgroup.New(ctx.Parallelism) for _, conf := range ctx.Config.S3 { conf := conf g.Go(func() error { return upload(ctx, conf) }) } return g.Wait() }
[ "func", "(", "Pipe", ")", "Publish", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "if", "len", "(", "ctx", ".", "Config", ".", "S3", ")", "==", "0", "{", "return", "pipe", ".", "Skip", "(", "\"s3 section is not configured\"", ")", "\n", "}", "\n", "var", "g", "=", "semerrgroup", ".", "New", "(", "ctx", ".", "Parallelism", ")", "\n", "for", "_", ",", "conf", ":=", "range", "ctx", ".", "Config", ".", "S3", "{", "conf", ":=", "conf", "\n", "g", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "upload", "(", "ctx", ",", "conf", ")", "\n", "}", ")", "\n", "}", "\n", "return", "g", ".", "Wait", "(", ")", "\n", "}" ]
// Publish to S3
[ "Publish", "to", "S3" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/s3/s3.go#L48-L60
train
goreleaser/goreleaser
internal/http/http.go
Defaults
func Defaults(puts []config.Put) error { for i := range puts { defaults(&puts[i]) } return nil }
go
func Defaults(puts []config.Put) error { for i := range puts { defaults(&puts[i]) } return nil }
[ "func", "Defaults", "(", "puts", "[", "]", "config", ".", "Put", ")", "error", "{", "for", "i", ":=", "range", "puts", "{", "defaults", "(", "&", "puts", "[", "i", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Defaults sets default configuration options on Put structs
[ "Defaults", "sets", "default", "configuration", "options", "on", "Put", "structs" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L72-L77
train
goreleaser/goreleaser
internal/http/http.go
CheckConfig
func CheckConfig(ctx *context.Context, put *config.Put, kind string) error { if put.Target == "" { return misconfigured(kind, put, "missing target") } if put.Name == "" { return misconfigured(kind, put, "missing name") } if put.Mode != ModeArchive && put.Mode != ModeBinary { return misconfigured(kind, put, "mode must be 'binary' or 'archive'") } envName := fmt.Sprintf("%s_%s_SECRET", strings.ToUpper(kind), strings.ToUpper(put.Name)) if _, ok := ctx.Env[envName]; !ok { return misconfigured(kind, put, fmt.Sprintf("missing %s environment variable", envName)) } if put.TrustedCerts != "" && !x509.NewCertPool().AppendCertsFromPEM([]byte(put.TrustedCerts)) { return misconfigured(kind, put, "no certificate could be added from the specified trusted_certificates configuration") } return nil }
go
func CheckConfig(ctx *context.Context, put *config.Put, kind string) error { if put.Target == "" { return misconfigured(kind, put, "missing target") } if put.Name == "" { return misconfigured(kind, put, "missing name") } if put.Mode != ModeArchive && put.Mode != ModeBinary { return misconfigured(kind, put, "mode must be 'binary' or 'archive'") } envName := fmt.Sprintf("%s_%s_SECRET", strings.ToUpper(kind), strings.ToUpper(put.Name)) if _, ok := ctx.Env[envName]; !ok { return misconfigured(kind, put, fmt.Sprintf("missing %s environment variable", envName)) } if put.TrustedCerts != "" && !x509.NewCertPool().AppendCertsFromPEM([]byte(put.TrustedCerts)) { return misconfigured(kind, put, "no certificate could be added from the specified trusted_certificates configuration") } return nil }
[ "func", "CheckConfig", "(", "ctx", "*", "context", ".", "Context", ",", "put", "*", "config", ".", "Put", ",", "kind", "string", ")", "error", "{", "if", "put", ".", "Target", "==", "\"\"", "{", "return", "misconfigured", "(", "kind", ",", "put", ",", "\"missing target\"", ")", "\n", "}", "\n", "if", "put", ".", "Name", "==", "\"\"", "{", "return", "misconfigured", "(", "kind", ",", "put", ",", "\"missing name\"", ")", "\n", "}", "\n", "if", "put", ".", "Mode", "!=", "ModeArchive", "&&", "put", ".", "Mode", "!=", "ModeBinary", "{", "return", "misconfigured", "(", "kind", ",", "put", ",", "\"mode must be 'binary' or 'archive'\"", ")", "\n", "}", "\n", "envName", ":=", "fmt", ".", "Sprintf", "(", "\"%s_%s_SECRET\"", ",", "strings", ".", "ToUpper", "(", "kind", ")", ",", "strings", ".", "ToUpper", "(", "put", ".", "Name", ")", ")", "\n", "if", "_", ",", "ok", ":=", "ctx", ".", "Env", "[", "envName", "]", ";", "!", "ok", "{", "return", "misconfigured", "(", "kind", ",", "put", ",", "fmt", ".", "Sprintf", "(", "\"missing %s environment variable\"", ",", "envName", ")", ")", "\n", "}", "\n", "if", "put", ".", "TrustedCerts", "!=", "\"\"", "&&", "!", "x509", ".", "NewCertPool", "(", ")", ".", "AppendCertsFromPEM", "(", "[", "]", "byte", "(", "put", ".", "TrustedCerts", ")", ")", "{", "return", "misconfigured", "(", "kind", ",", "put", ",", "\"no certificate could be added from the specified trusted_certificates configuration\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckConfig validates a Put configuration returning a descriptive error when appropriate
[ "CheckConfig", "validates", "a", "Put", "configuration", "returning", "a", "descriptive", "error", "when", "appropriate" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L86-L111
train
goreleaser/goreleaser
internal/http/http.go
Upload
func Upload(ctx *context.Context, puts []config.Put, kind string, check ResponseChecker) error { if ctx.SkipPublish { return pipe.ErrSkipPublishEnabled } // Handle every configured put for _, put := range puts { put := put filters := []artifact.Filter{} if put.Checksum { filters = append(filters, artifact.ByType(artifact.Checksum)) } if put.Signature { filters = append(filters, artifact.ByType(artifact.Signature)) } // We support two different modes // - "archive": Upload all artifacts // - "binary": Upload only the raw binaries switch v := strings.ToLower(put.Mode); v { case ModeArchive: filters = append(filters, artifact.ByType(artifact.UploadableArchive), artifact.ByType(artifact.LinuxPackage), ) case ModeBinary: filters = append(filters, artifact.ByType(artifact.UploadableBinary)) default: err := fmt.Errorf("%s: mode \"%s\" not supported", kind, v) log.WithFields(log.Fields{ kind: put.Name, "mode": v, }).Error(err.Error()) return err } if err := uploadWithFilter(ctx, &put, artifact.Or(filters...), kind, check); err != nil { return err } } return nil }
go
func Upload(ctx *context.Context, puts []config.Put, kind string, check ResponseChecker) error { if ctx.SkipPublish { return pipe.ErrSkipPublishEnabled } // Handle every configured put for _, put := range puts { put := put filters := []artifact.Filter{} if put.Checksum { filters = append(filters, artifact.ByType(artifact.Checksum)) } if put.Signature { filters = append(filters, artifact.ByType(artifact.Signature)) } // We support two different modes // - "archive": Upload all artifacts // - "binary": Upload only the raw binaries switch v := strings.ToLower(put.Mode); v { case ModeArchive: filters = append(filters, artifact.ByType(artifact.UploadableArchive), artifact.ByType(artifact.LinuxPackage), ) case ModeBinary: filters = append(filters, artifact.ByType(artifact.UploadableBinary)) default: err := fmt.Errorf("%s: mode \"%s\" not supported", kind, v) log.WithFields(log.Fields{ kind: put.Name, "mode": v, }).Error(err.Error()) return err } if err := uploadWithFilter(ctx, &put, artifact.Or(filters...), kind, check); err != nil { return err } } return nil }
[ "func", "Upload", "(", "ctx", "*", "context", ".", "Context", ",", "puts", "[", "]", "config", ".", "Put", ",", "kind", "string", ",", "check", "ResponseChecker", ")", "error", "{", "if", "ctx", ".", "SkipPublish", "{", "return", "pipe", ".", "ErrSkipPublishEnabled", "\n", "}", "\n", "for", "_", ",", "put", ":=", "range", "puts", "{", "put", ":=", "put", "\n", "filters", ":=", "[", "]", "artifact", ".", "Filter", "{", "}", "\n", "if", "put", ".", "Checksum", "{", "filters", "=", "append", "(", "filters", ",", "artifact", ".", "ByType", "(", "artifact", ".", "Checksum", ")", ")", "\n", "}", "\n", "if", "put", ".", "Signature", "{", "filters", "=", "append", "(", "filters", ",", "artifact", ".", "ByType", "(", "artifact", ".", "Signature", ")", ")", "\n", "}", "\n", "switch", "v", ":=", "strings", ".", "ToLower", "(", "put", ".", "Mode", ")", ";", "v", "{", "case", "ModeArchive", ":", "filters", "=", "append", "(", "filters", ",", "artifact", ".", "ByType", "(", "artifact", ".", "UploadableArchive", ")", ",", "artifact", ".", "ByType", "(", "artifact", ".", "LinuxPackage", ")", ",", ")", "\n", "case", "ModeBinary", ":", "filters", "=", "append", "(", "filters", ",", "artifact", ".", "ByType", "(", "artifact", ".", "UploadableBinary", ")", ")", "\n", "default", ":", "err", ":=", "fmt", ".", "Errorf", "(", "\"%s: mode \\\"%s\\\" not supported\"", ",", "\\\"", ",", "\\\"", ")", "\n", "kind", "\n", "v", "\n", "}", "\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "kind", ":", "put", ".", "Name", ",", "\"mode\"", ":", "v", ",", "}", ")", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Upload does the actual uploading work
[ "Upload", "does", "the", "actual", "uploading", "work" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L122-L162
train
goreleaser/goreleaser
internal/http/http.go
uploadAsset
func uploadAsset(ctx *context.Context, put *config.Put, artifact artifact.Artifact, kind string, check ResponseChecker) error { envBase := fmt.Sprintf("%s_%s_", strings.ToUpper(kind), strings.ToUpper(put.Name)) username := put.Username if username == "" { // username not configured: using env username = ctx.Env[envBase+"USERNAME"] } secret := ctx.Env[envBase+"SECRET"] // Generate the target url targetURL, err := resolveTargetTemplate(ctx, put, artifact) if err != nil { msg := fmt.Sprintf("%s: error while building the target url", kind) log.WithField("instance", put.Name).WithError(err).Error(msg) return errors.Wrap(err, msg) } // Handle the artifact asset, err := assetOpen(kind, &artifact) if err != nil { return err } defer asset.ReadCloser.Close() // nolint: errcheck // The target url needs to contain the artifact name if !strings.HasSuffix(targetURL, "/") { targetURL += "/" } targetURL += artifact.Name var headers = map[string]string{} if put.ChecksumHeader != "" { sum, err := artifact.Checksum("sha256") if err != nil { return err } headers[put.ChecksumHeader] = sum } _, err = uploadAssetToServer(ctx, put, targetURL, username, secret, headers, asset, check) if err != nil { msg := fmt.Sprintf("%s: upload failed", kind) log.WithError(err).WithFields(log.Fields{ "instance": put.Name, "username": username, }).Error(msg) return errors.Wrap(err, msg) } log.WithFields(log.Fields{ "instance": put.Name, "mode": put.Mode, }).Info("uploaded successful") return nil }
go
func uploadAsset(ctx *context.Context, put *config.Put, artifact artifact.Artifact, kind string, check ResponseChecker) error { envBase := fmt.Sprintf("%s_%s_", strings.ToUpper(kind), strings.ToUpper(put.Name)) username := put.Username if username == "" { // username not configured: using env username = ctx.Env[envBase+"USERNAME"] } secret := ctx.Env[envBase+"SECRET"] // Generate the target url targetURL, err := resolveTargetTemplate(ctx, put, artifact) if err != nil { msg := fmt.Sprintf("%s: error while building the target url", kind) log.WithField("instance", put.Name).WithError(err).Error(msg) return errors.Wrap(err, msg) } // Handle the artifact asset, err := assetOpen(kind, &artifact) if err != nil { return err } defer asset.ReadCloser.Close() // nolint: errcheck // The target url needs to contain the artifact name if !strings.HasSuffix(targetURL, "/") { targetURL += "/" } targetURL += artifact.Name var headers = map[string]string{} if put.ChecksumHeader != "" { sum, err := artifact.Checksum("sha256") if err != nil { return err } headers[put.ChecksumHeader] = sum } _, err = uploadAssetToServer(ctx, put, targetURL, username, secret, headers, asset, check) if err != nil { msg := fmt.Sprintf("%s: upload failed", kind) log.WithError(err).WithFields(log.Fields{ "instance": put.Name, "username": username, }).Error(msg) return errors.Wrap(err, msg) } log.WithFields(log.Fields{ "instance": put.Name, "mode": put.Mode, }).Info("uploaded successful") return nil }
[ "func", "uploadAsset", "(", "ctx", "*", "context", ".", "Context", ",", "put", "*", "config", ".", "Put", ",", "artifact", "artifact", ".", "Artifact", ",", "kind", "string", ",", "check", "ResponseChecker", ")", "error", "{", "envBase", ":=", "fmt", ".", "Sprintf", "(", "\"%s_%s_\"", ",", "strings", ".", "ToUpper", "(", "kind", ")", ",", "strings", ".", "ToUpper", "(", "put", ".", "Name", ")", ")", "\n", "username", ":=", "put", ".", "Username", "\n", "if", "username", "==", "\"\"", "{", "username", "=", "ctx", ".", "Env", "[", "envBase", "+", "\"USERNAME\"", "]", "\n", "}", "\n", "secret", ":=", "ctx", ".", "Env", "[", "envBase", "+", "\"SECRET\"", "]", "\n", "targetURL", ",", "err", ":=", "resolveTargetTemplate", "(", "ctx", ",", "put", ",", "artifact", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"%s: error while building the target url\"", ",", "kind", ")", "\n", "log", ".", "WithField", "(", "\"instance\"", ",", "put", ".", "Name", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "msg", ")", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "msg", ")", "\n", "}", "\n", "asset", ",", "err", ":=", "assetOpen", "(", "kind", ",", "&", "artifact", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "asset", ".", "ReadCloser", ".", "Close", "(", ")", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "targetURL", ",", "\"/\"", ")", "{", "targetURL", "+=", "\"/\"", "\n", "}", "\n", "targetURL", "+=", "artifact", ".", "Name", "\n", "var", "headers", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "if", "put", ".", "ChecksumHeader", "!=", "\"\"", "{", "sum", ",", "err", ":=", "artifact", ".", "Checksum", "(", "\"sha256\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "headers", "[", "put", ".", "ChecksumHeader", "]", "=", "sum", "\n", "}", "\n", "_", ",", "err", "=", "uploadAssetToServer", "(", "ctx", ",", "put", ",", "targetURL", ",", "username", ",", "secret", ",", "headers", ",", "asset", ",", "check", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"%s: upload failed\"", ",", "kind", ")", "\n", "log", ".", "WithError", "(", "err", ")", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"instance\"", ":", "put", ".", "Name", ",", "\"username\"", ":", "username", ",", "}", ")", ".", "Error", "(", "msg", ")", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "msg", ")", "\n", "}", "\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"instance\"", ":", "put", ".", "Name", ",", "\"mode\"", ":", "put", ".", "Mode", ",", "}", ")", ".", "Info", "(", "\"uploaded successful\"", ")", "\n", "return", "nil", "\n", "}" ]
// uploadAsset uploads file to target and logs all actions
[ "uploadAsset", "uploads", "file", "to", "target", "and", "logs", "all", "actions" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L178-L233
train
goreleaser/goreleaser
internal/http/http.go
uploadAssetToServer
func uploadAssetToServer(ctx *context.Context, put *config.Put, target, username, secret string, headers map[string]string, a *asset, check ResponseChecker) (*h.Response, error) { req, err := newUploadRequest(target, username, secret, headers, a) if err != nil { return nil, err } return executeHTTPRequest(ctx, put, req, check) }
go
func uploadAssetToServer(ctx *context.Context, put *config.Put, target, username, secret string, headers map[string]string, a *asset, check ResponseChecker) (*h.Response, error) { req, err := newUploadRequest(target, username, secret, headers, a) if err != nil { return nil, err } return executeHTTPRequest(ctx, put, req, check) }
[ "func", "uploadAssetToServer", "(", "ctx", "*", "context", ".", "Context", ",", "put", "*", "config", ".", "Put", ",", "target", ",", "username", ",", "secret", "string", ",", "headers", "map", "[", "string", "]", "string", ",", "a", "*", "asset", ",", "check", "ResponseChecker", ")", "(", "*", "h", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "newUploadRequest", "(", "target", ",", "username", ",", "secret", ",", "headers", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "executeHTTPRequest", "(", "ctx", ",", "put", ",", "req", ",", "check", ")", "\n", "}" ]
// uploadAssetToServer uploads the asset file to target
[ "uploadAssetToServer", "uploads", "the", "asset", "file", "to", "target" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L236-L243
train
goreleaser/goreleaser
internal/http/http.go
newUploadRequest
func newUploadRequest(target, username, secret string, headers map[string]string, a *asset) (*h.Request, error) { req, err := h.NewRequest(h.MethodPut, target, a.ReadCloser) if err != nil { return nil, err } req.ContentLength = a.Size req.SetBasicAuth(username, secret) for k, v := range headers { req.Header.Add(k, v) } return req, err }
go
func newUploadRequest(target, username, secret string, headers map[string]string, a *asset) (*h.Request, error) { req, err := h.NewRequest(h.MethodPut, target, a.ReadCloser) if err != nil { return nil, err } req.ContentLength = a.Size req.SetBasicAuth(username, secret) for k, v := range headers { req.Header.Add(k, v) } return req, err }
[ "func", "newUploadRequest", "(", "target", ",", "username", ",", "secret", "string", ",", "headers", "map", "[", "string", "]", "string", ",", "a", "*", "asset", ")", "(", "*", "h", ".", "Request", ",", "error", ")", "{", "req", ",", "err", ":=", "h", ".", "NewRequest", "(", "h", ".", "MethodPut", ",", "target", ",", "a", ".", "ReadCloser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "ContentLength", "=", "a", ".", "Size", "\n", "req", ".", "SetBasicAuth", "(", "username", ",", "secret", ")", "\n", "for", "k", ",", "v", ":=", "range", "headers", "{", "req", ".", "Header", ".", "Add", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "req", ",", "err", "\n", "}" ]
// newUploadRequest creates a new h.Request for uploading
[ "newUploadRequest", "creates", "a", "new", "h", ".", "Request", "for", "uploading" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L246-L259
train
goreleaser/goreleaser
internal/http/http.go
executeHTTPRequest
func executeHTTPRequest(ctx *context.Context, put *config.Put, req *h.Request, check ResponseChecker) (*h.Response, error) { client, err := getHTTPClient(put) if err != nil { return nil, err } log.Debugf("executing request: %s %s (headers: %v)", req.Method, req.URL, req.Header) resp, err := client.Do(req) if err != nil { // If we got an error, and the context has been canceled, // the context's error is probably more useful. select { case <-ctx.Done(): return nil, ctx.Err() default: } return nil, err } defer resp.Body.Close() // nolint: errcheck err = check(resp) if err != nil { // even though there was an error, we still return the response // in case the caller wants to inspect it further return resp, err } return resp, err }
go
func executeHTTPRequest(ctx *context.Context, put *config.Put, req *h.Request, check ResponseChecker) (*h.Response, error) { client, err := getHTTPClient(put) if err != nil { return nil, err } log.Debugf("executing request: %s %s (headers: %v)", req.Method, req.URL, req.Header) resp, err := client.Do(req) if err != nil { // If we got an error, and the context has been canceled, // the context's error is probably more useful. select { case <-ctx.Done(): return nil, ctx.Err() default: } return nil, err } defer resp.Body.Close() // nolint: errcheck err = check(resp) if err != nil { // even though there was an error, we still return the response // in case the caller wants to inspect it further return resp, err } return resp, err }
[ "func", "executeHTTPRequest", "(", "ctx", "*", "context", ".", "Context", ",", "put", "*", "config", ".", "Put", ",", "req", "*", "h", ".", "Request", ",", "check", "ResponseChecker", ")", "(", "*", "h", ".", "Response", ",", "error", ")", "{", "client", ",", "err", ":=", "getHTTPClient", "(", "put", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"executing request: %s %s (headers: %v)\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ",", "req", ".", "Header", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "default", ":", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "err", "=", "check", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resp", ",", "err", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// executeHTTPRequest processes the http call with respect of context ctx
[ "executeHTTPRequest", "processes", "the", "http", "call", "with", "respect", "of", "context", "ctx" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L285-L313
train
goreleaser/goreleaser
internal/http/http.go
resolveTargetTemplate
func resolveTargetTemplate(ctx *context.Context, put *config.Put, artifact artifact.Artifact) (string, error) { data := targetData{ Version: ctx.Version, Tag: ctx.Git.CurrentTag, ProjectName: ctx.Config.ProjectName, } if put.Mode == ModeBinary { data.Os = replace(ctx.Config.Archive.Replacements, artifact.Goos) data.Arch = replace(ctx.Config.Archive.Replacements, artifact.Goarch) data.Arm = replace(ctx.Config.Archive.Replacements, artifact.Goarm) } var out bytes.Buffer t, err := template.New(ctx.Config.ProjectName).Parse(put.Target) if err != nil { return "", err } err = t.Execute(&out, data) return out.String(), err }
go
func resolveTargetTemplate(ctx *context.Context, put *config.Put, artifact artifact.Artifact) (string, error) { data := targetData{ Version: ctx.Version, Tag: ctx.Git.CurrentTag, ProjectName: ctx.Config.ProjectName, } if put.Mode == ModeBinary { data.Os = replace(ctx.Config.Archive.Replacements, artifact.Goos) data.Arch = replace(ctx.Config.Archive.Replacements, artifact.Goarch) data.Arm = replace(ctx.Config.Archive.Replacements, artifact.Goarm) } var out bytes.Buffer t, err := template.New(ctx.Config.ProjectName).Parse(put.Target) if err != nil { return "", err } err = t.Execute(&out, data) return out.String(), err }
[ "func", "resolveTargetTemplate", "(", "ctx", "*", "context", ".", "Context", ",", "put", "*", "config", ".", "Put", ",", "artifact", "artifact", ".", "Artifact", ")", "(", "string", ",", "error", ")", "{", "data", ":=", "targetData", "{", "Version", ":", "ctx", ".", "Version", ",", "Tag", ":", "ctx", ".", "Git", ".", "CurrentTag", ",", "ProjectName", ":", "ctx", ".", "Config", ".", "ProjectName", ",", "}", "\n", "if", "put", ".", "Mode", "==", "ModeBinary", "{", "data", ".", "Os", "=", "replace", "(", "ctx", ".", "Config", ".", "Archive", ".", "Replacements", ",", "artifact", ".", "Goos", ")", "\n", "data", ".", "Arch", "=", "replace", "(", "ctx", ".", "Config", ".", "Archive", ".", "Replacements", ",", "artifact", ".", "Goarch", ")", "\n", "data", ".", "Arm", "=", "replace", "(", "ctx", ".", "Config", ".", "Archive", ".", "Replacements", ",", "artifact", ".", "Goarm", ")", "\n", "}", "\n", "var", "out", "bytes", ".", "Buffer", "\n", "t", ",", "err", ":=", "template", ".", "New", "(", "ctx", ".", "Config", ".", "ProjectName", ")", ".", "Parse", "(", "put", ".", "Target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "err", "=", "t", ".", "Execute", "(", "&", "out", ",", "data", ")", "\n", "return", "out", ".", "String", "(", ")", ",", "err", "\n", "}" ]
// resolveTargetTemplate returns the resolved target template with replaced variables // Those variables can be replaced by the given context, goos, goarch, goarm and more
[ "resolveTargetTemplate", "returns", "the", "resolved", "target", "template", "with", "replaced", "variables", "Those", "variables", "can", "be", "replaced", "by", "the", "given", "context", "goos", "goarch", "goarm", "and", "more" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/http/http.go#L330-L350
train
goreleaser/goreleaser
internal/pipe/archive/archive.go
NewEnhancedArchive
func NewEnhancedArchive(a archive.Archive, wrap string) archive.Archive { return EnhancedArchive{ a: a, wrap: wrap, files: map[string]string{}, } }
go
func NewEnhancedArchive(a archive.Archive, wrap string) archive.Archive { return EnhancedArchive{ a: a, wrap: wrap, files: map[string]string{}, } }
[ "func", "NewEnhancedArchive", "(", "a", "archive", ".", "Archive", ",", "wrap", "string", ")", "archive", ".", "Archive", "{", "return", "EnhancedArchive", "{", "a", ":", "a", ",", "wrap", ":", "wrap", ",", "files", ":", "map", "[", "string", "]", "string", "{", "}", ",", "}", "\n", "}" ]
// NewEnhancedArchive enhances a pre-existing archive.Archive instance // with this pipe specifics.
[ "NewEnhancedArchive", "enhances", "a", "pre", "-", "existing", "archive", ".", "Archive", "instance", "with", "this", "pipe", "specifics", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/archive/archive.go#L245-L251
train
goreleaser/goreleaser
internal/pipe/archive/archive.go
Add
func (d EnhancedArchive) Add(name, path string) error { name = strings.Replace(filepath.Join(d.wrap, name), "\\", "/", -1) log.Debugf("adding file: %s as %s", path, name) if _, ok := d.files[name]; ok { return fmt.Errorf("file %s already exists in the archive", name) } d.files[name] = path return d.a.Add(name, path) }
go
func (d EnhancedArchive) Add(name, path string) error { name = strings.Replace(filepath.Join(d.wrap, name), "\\", "/", -1) log.Debugf("adding file: %s as %s", path, name) if _, ok := d.files[name]; ok { return fmt.Errorf("file %s already exists in the archive", name) } d.files[name] = path return d.a.Add(name, path) }
[ "func", "(", "d", "EnhancedArchive", ")", "Add", "(", "name", ",", "path", "string", ")", "error", "{", "name", "=", "strings", ".", "Replace", "(", "filepath", ".", "Join", "(", "d", ".", "wrap", ",", "name", ")", ",", "\"\\\\\"", ",", "\\\\", ",", "\"/\"", ")", "\n", "-", "1", "\n", "log", ".", "Debugf", "(", "\"adding file: %s as %s\"", ",", "path", ",", "name", ")", "\n", "if", "_", ",", "ok", ":=", "d", ".", "files", "[", "name", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"file %s already exists in the archive\"", ",", "name", ")", "\n", "}", "\n", "d", ".", "files", "[", "name", "]", "=", "path", "\n", "}" ]
// Add adds a file
[ "Add", "adds", "a", "file" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/archive/archive.go#L263-L271
train
goreleaser/goreleaser
internal/deprecate/deprecate.go
Notice
func Notice(property string) { cli.Default.Padding += 3 defer func() { cli.Default.Padding -= 3 }() // replaces . and _ with - url := baseURL + strings.NewReplacer( ".", "-", "_", "-", ).Replace(property) log.Warn(color.New(color.Bold, color.FgHiYellow).Sprintf( "DEPRECATED: `%s` should not be used anymore, check %s for more info.", property, url, )) }
go
func Notice(property string) { cli.Default.Padding += 3 defer func() { cli.Default.Padding -= 3 }() // replaces . and _ with - url := baseURL + strings.NewReplacer( ".", "-", "_", "-", ).Replace(property) log.Warn(color.New(color.Bold, color.FgHiYellow).Sprintf( "DEPRECATED: `%s` should not be used anymore, check %s for more info.", property, url, )) }
[ "func", "Notice", "(", "property", "string", ")", "{", "cli", ".", "Default", ".", "Padding", "+=", "3", "\n", "defer", "func", "(", ")", "{", "cli", ".", "Default", ".", "Padding", "-=", "3", "\n", "}", "(", ")", "\n", "url", ":=", "baseURL", "+", "strings", ".", "NewReplacer", "(", "\".\"", ",", "\"-\"", ",", "\"_\"", ",", "\"-\"", ",", ")", ".", "Replace", "(", "property", ")", "\n", "log", ".", "Warn", "(", "color", ".", "New", "(", "color", ".", "Bold", ",", "color", ".", "FgHiYellow", ")", ".", "Sprintf", "(", "\"DEPRECATED: `%s` should not be used anymore, check %s for more info.\"", ",", "property", ",", "url", ",", ")", ")", "\n", "}" ]
// Notice warns the user about the deprecation of the given property
[ "Notice", "warns", "the", "user", "about", "the", "deprecation", "of", "the", "given", "property" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/deprecate/deprecate.go#L16-L31
train
goreleaser/goreleaser
pkg/archive/zip/zip.go
New
func New(target io.Writer) Archive { return Archive{ z: zip.NewWriter(target), } }
go
func New(target io.Writer) Archive { return Archive{ z: zip.NewWriter(target), } }
[ "func", "New", "(", "target", "io", ".", "Writer", ")", "Archive", "{", "return", "Archive", "{", "z", ":", "zip", ".", "NewWriter", "(", "target", ")", ",", "}", "\n", "}" ]
// New zip archive
[ "New", "zip", "archive" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/archive/zip/zip.go#L22-L26
train
goreleaser/goreleaser
pkg/archive/zip/zip.go
Add
func (a Archive) Add(name, path string) (err error) { file, err := os.Open(path) // #nosec if err != nil { return } defer file.Close() // nolint: errcheck info, err := file.Stat() if err != nil { return } if info.IsDir() { return } header, err := zip.FileInfoHeader(info) if err != nil { return err } header.Name = name header.Method = zip.Deflate w, err := a.z.CreateHeader(header) if err != nil { return err } _, err = io.Copy(w, file) return err }
go
func (a Archive) Add(name, path string) (err error) { file, err := os.Open(path) // #nosec if err != nil { return } defer file.Close() // nolint: errcheck info, err := file.Stat() if err != nil { return } if info.IsDir() { return } header, err := zip.FileInfoHeader(info) if err != nil { return err } header.Name = name header.Method = zip.Deflate w, err := a.z.CreateHeader(header) if err != nil { return err } _, err = io.Copy(w, file) return err }
[ "func", "(", "a", "Archive", ")", "Add", "(", "name", ",", "path", "string", ")", "(", "err", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "info", ",", "err", ":=", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "\n", "}", "\n", "header", ",", "err", ":=", "zip", ".", "FileInfoHeader", "(", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "header", ".", "Name", "=", "name", "\n", "header", ".", "Method", "=", "zip", ".", "Deflate", "\n", "w", ",", "err", ":=", "a", ".", "z", ".", "CreateHeader", "(", "header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "w", ",", "file", ")", "\n", "return", "err", "\n", "}" ]
// Add a file to the zip archive
[ "Add", "a", "file", "to", "the", "zip", "archive" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/archive/zip/zip.go#L29-L54
train
goreleaser/goreleaser
internal/pipe/project/project.go
Default
func (Pipe) Default(ctx *context.Context) error { if ctx.Config.ProjectName == "" { ctx.Config.ProjectName = ctx.Config.Release.GitHub.Name } return nil }
go
func (Pipe) Default(ctx *context.Context) error { if ctx.Config.ProjectName == "" { ctx.Config.ProjectName = ctx.Config.Release.GitHub.Name } return nil }
[ "func", "(", "Pipe", ")", "Default", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "if", "ctx", ".", "Config", ".", "ProjectName", "==", "\"\"", "{", "ctx", ".", "Config", ".", "ProjectName", "=", "ctx", ".", "Config", ".", "Release", ".", "GitHub", ".", "Name", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Default set project defaults
[ "Default", "set", "project", "defaults" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/project/project.go#L14-L19
train
goreleaser/goreleaser
internal/tmpl/tmpl.go
WithEnvS
func (t *Template) WithEnvS(envs []string) *Template { var result = map[string]string{} for _, env := range envs { var parts = strings.SplitN(env, "=", 2) result[parts[0]] = parts[1] } return t.WithEnv(result) }
go
func (t *Template) WithEnvS(envs []string) *Template { var result = map[string]string{} for _, env := range envs { var parts = strings.SplitN(env, "=", 2) result[parts[0]] = parts[1] } return t.WithEnv(result) }
[ "func", "(", "t", "*", "Template", ")", "WithEnvS", "(", "envs", "[", "]", "string", ")", "*", "Template", "{", "var", "result", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "_", ",", "env", ":=", "range", "envs", "{", "var", "parts", "=", "strings", ".", "SplitN", "(", "env", ",", "\"=\"", ",", "2", ")", "\n", "result", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "\n", "}", "\n", "return", "t", ".", "WithEnv", "(", "result", ")", "\n", "}" ]
// WithEnvS overrides template's env field with the given KEY=VALUE list of // environment variables
[ "WithEnvS", "overrides", "template", "s", "env", "field", "with", "the", "given", "KEY", "=", "VALUE", "list", "of", "environment", "variables" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/tmpl/tmpl.go#L69-L76
train
goreleaser/goreleaser
internal/tmpl/tmpl.go
WithEnv
func (t *Template) WithEnv(e map[string]string) *Template { t.fields[env] = e return t }
go
func (t *Template) WithEnv(e map[string]string) *Template { t.fields[env] = e return t }
[ "func", "(", "t", "*", "Template", ")", "WithEnv", "(", "e", "map", "[", "string", "]", "string", ")", "*", "Template", "{", "t", ".", "fields", "[", "env", "]", "=", "e", "\n", "return", "t", "\n", "}" ]
// WithEnv overrides template's env field with the given environment map
[ "WithEnv", "overrides", "template", "s", "env", "field", "with", "the", "given", "environment", "map" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/tmpl/tmpl.go#L79-L82
train
goreleaser/goreleaser
internal/tmpl/tmpl.go
WithArtifact
func (t *Template) WithArtifact(a artifact.Artifact, replacements map[string]string) *Template { var bin = a.Extra[binary] if bin == nil { bin = t.fields[projectName] } t.fields[os] = replace(replacements, a.Goos) t.fields[arch] = replace(replacements, a.Goarch) t.fields[arm] = replace(replacements, a.Goarm) t.fields[binary] = bin.(string) t.fields[artifactName] = a.Name return t }
go
func (t *Template) WithArtifact(a artifact.Artifact, replacements map[string]string) *Template { var bin = a.Extra[binary] if bin == nil { bin = t.fields[projectName] } t.fields[os] = replace(replacements, a.Goos) t.fields[arch] = replace(replacements, a.Goarch) t.fields[arm] = replace(replacements, a.Goarm) t.fields[binary] = bin.(string) t.fields[artifactName] = a.Name return t }
[ "func", "(", "t", "*", "Template", ")", "WithArtifact", "(", "a", "artifact", ".", "Artifact", ",", "replacements", "map", "[", "string", "]", "string", ")", "*", "Template", "{", "var", "bin", "=", "a", ".", "Extra", "[", "binary", "]", "\n", "if", "bin", "==", "nil", "{", "bin", "=", "t", ".", "fields", "[", "projectName", "]", "\n", "}", "\n", "t", ".", "fields", "[", "os", "]", "=", "replace", "(", "replacements", ",", "a", ".", "Goos", ")", "\n", "t", ".", "fields", "[", "arch", "]", "=", "replace", "(", "replacements", ",", "a", ".", "Goarch", ")", "\n", "t", ".", "fields", "[", "arm", "]", "=", "replace", "(", "replacements", ",", "a", ".", "Goarm", ")", "\n", "t", ".", "fields", "[", "binary", "]", "=", "bin", ".", "(", "string", ")", "\n", "t", ".", "fields", "[", "artifactName", "]", "=", "a", ".", "Name", "\n", "return", "t", "\n", "}" ]
// WithArtifact populates fields from the artifact and replacements
[ "WithArtifact", "populates", "fields", "from", "the", "artifact", "and", "replacements" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/tmpl/tmpl.go#L85-L96
train
goreleaser/goreleaser
internal/tmpl/tmpl.go
Apply
func (t *Template) Apply(s string) (string, error) { var out bytes.Buffer tmpl, err := template.New("tmpl"). Option("missingkey=error"). Funcs(template.FuncMap{ "time": func(s string) string { return time.Now().UTC().Format(s) }, }). Parse(s) if err != nil { return "", err } err = tmpl.Execute(&out, t.fields) return out.String(), err }
go
func (t *Template) Apply(s string) (string, error) { var out bytes.Buffer tmpl, err := template.New("tmpl"). Option("missingkey=error"). Funcs(template.FuncMap{ "time": func(s string) string { return time.Now().UTC().Format(s) }, }). Parse(s) if err != nil { return "", err } err = tmpl.Execute(&out, t.fields) return out.String(), err }
[ "func", "(", "t", "*", "Template", ")", "Apply", "(", "s", "string", ")", "(", "string", ",", "error", ")", "{", "var", "out", "bytes", ".", "Buffer", "\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "\"tmpl\"", ")", ".", "Option", "(", "\"missingkey=error\"", ")", ".", "Funcs", "(", "template", ".", "FuncMap", "{", "\"time\"", ":", "func", "(", "s", "string", ")", "string", "{", "return", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Format", "(", "s", ")", "\n", "}", ",", "}", ")", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "err", "=", "tmpl", ".", "Execute", "(", "&", "out", ",", "t", ".", "fields", ")", "\n", "return", "out", ".", "String", "(", ")", ",", "err", "\n", "}" ]
// Apply applies the given string against the fields stored in the template.
[ "Apply", "applies", "the", "given", "string", "against", "the", "fields", "stored", "in", "the", "template", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/tmpl/tmpl.go#L99-L115
train
goreleaser/goreleaser
internal/pipe/release/release.go
Publish
func (Pipe) Publish(ctx *context.Context) error { c, err := client.NewGitHub(ctx) if err != nil { return err } return doPublish(ctx, c) }
go
func (Pipe) Publish(ctx *context.Context) error { c, err := client.NewGitHub(ctx) if err != nil { return err } return doPublish(ctx, c) }
[ "func", "(", "Pipe", ")", "Publish", "(", "ctx", "*", "context", ".", "Context", ")", "error", "{", "c", ",", "err", ":=", "client", ".", "NewGitHub", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "doPublish", "(", "ctx", ",", "c", ")", "\n", "}" ]
// Publish github release
[ "Publish", "github", "release" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/release/release.go#L55-L61
train
goreleaser/goreleaser
internal/semerrgroup/sem.go
New
func New(size int) *Group { return &Group{ ch: make(chan bool, size), g: errgroup.Group{}, } }
go
func New(size int) *Group { return &Group{ ch: make(chan bool, size), g: errgroup.Group{}, } }
[ "func", "New", "(", "size", "int", ")", "*", "Group", "{", "return", "&", "Group", "{", "ch", ":", "make", "(", "chan", "bool", ",", "size", ")", ",", "g", ":", "errgroup", ".", "Group", "{", "}", ",", "}", "\n", "}" ]
// New returns a new Group of a given size.
[ "New", "returns", "a", "new", "Group", "of", "a", "given", "size", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/semerrgroup/sem.go#L14-L19
train
goreleaser/goreleaser
internal/semerrgroup/sem.go
Go
func (s *Group) Go(fn func() error) { s.g.Go(func() error { s.ch <- true defer func() { <-s.ch }() return fn() }) }
go
func (s *Group) Go(fn func() error) { s.g.Go(func() error { s.ch <- true defer func() { <-s.ch }() return fn() }) }
[ "func", "(", "s", "*", "Group", ")", "Go", "(", "fn", "func", "(", ")", "error", ")", "{", "s", ".", "g", ".", "Go", "(", "func", "(", ")", "error", "{", "s", ".", "ch", "<-", "true", "\n", "defer", "func", "(", ")", "{", "<-", "s", ".", "ch", "\n", "}", "(", ")", "\n", "return", "fn", "(", ")", "\n", "}", ")", "\n", "}" ]
// Go execs one function respecting the group and semaphore.
[ "Go", "execs", "one", "function", "respecting", "the", "group", "and", "semaphore", "." ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/semerrgroup/sem.go#L22-L30
train
goreleaser/goreleaser
pkg/archive/targz/targz.go
Close
func (a Archive) Close() error { if err := a.tw.Close(); err != nil { return err } return a.gw.Close() }
go
func (a Archive) Close() error { if err := a.tw.Close(); err != nil { return err } return a.gw.Close() }
[ "func", "(", "a", "Archive", ")", "Close", "(", ")", "error", "{", "if", "err", ":=", "a", ".", "tw", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "a", ".", "gw", ".", "Close", "(", ")", "\n", "}" ]
// Close all closeables
[ "Close", "all", "closeables" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/archive/targz/targz.go#L19-L24
train
goreleaser/goreleaser
pkg/archive/targz/targz.go
New
func New(target io.Writer) Archive { gw := gzip.NewWriter(target) tw := tar.NewWriter(gw) return Archive{ gw: gw, tw: tw, } }
go
func New(target io.Writer) Archive { gw := gzip.NewWriter(target) tw := tar.NewWriter(gw) return Archive{ gw: gw, tw: tw, } }
[ "func", "New", "(", "target", "io", ".", "Writer", ")", "Archive", "{", "gw", ":=", "gzip", ".", "NewWriter", "(", "target", ")", "\n", "tw", ":=", "tar", ".", "NewWriter", "(", "gw", ")", "\n", "return", "Archive", "{", "gw", ":", "gw", ",", "tw", ":", "tw", ",", "}", "\n", "}" ]
// New tar.gz archive
[ "New", "tar", ".", "gz", "archive" ]
76fa5909a2dbf261ec188188db66a294786188c8
https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/pkg/archive/targz/targz.go#L27-L34
train
qor/qor
resource/meta.go
GetSetter
func (meta Meta) GetSetter() func(resource interface{}, metaValue *MetaValue, context *qor.Context) { return meta.Setter }
go
func (meta Meta) GetSetter() func(resource interface{}, metaValue *MetaValue, context *qor.Context) { return meta.Setter }
[ "func", "(", "meta", "Meta", ")", "GetSetter", "(", ")", "func", "(", "resource", "interface", "{", "}", ",", "metaValue", "*", "MetaValue", ",", "context", "*", "qor", ".", "Context", ")", "{", "return", "meta", ".", "Setter", "\n", "}" ]
// GetSetter get setter from meta
[ "GetSetter", "get", "setter", "from", "meta" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta.go#L89-L91
train
qor/qor
resource/meta.go
SetSetter
func (meta *Meta) SetSetter(fc func(resource interface{}, metaValue *MetaValue, context *qor.Context)) { meta.Setter = fc }
go
func (meta *Meta) SetSetter(fc func(resource interface{}, metaValue *MetaValue, context *qor.Context)) { meta.Setter = fc }
[ "func", "(", "meta", "*", "Meta", ")", "SetSetter", "(", "fc", "func", "(", "resource", "interface", "{", "}", ",", "metaValue", "*", "MetaValue", ",", "context", "*", "qor", ".", "Context", ")", ")", "{", "meta", ".", "Setter", "=", "fc", "\n", "}" ]
// SetSetter set setter to meta
[ "SetSetter", "set", "setter", "to", "meta" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta.go#L94-L96
train
qor/qor
resource/meta.go
GetFormattedValuer
func (meta *Meta) GetFormattedValuer() func(interface{}, *qor.Context) interface{} { if meta.FormattedValuer != nil { return meta.FormattedValuer } return meta.Valuer }
go
func (meta *Meta) GetFormattedValuer() func(interface{}, *qor.Context) interface{} { if meta.FormattedValuer != nil { return meta.FormattedValuer } return meta.Valuer }
[ "func", "(", "meta", "*", "Meta", ")", "GetFormattedValuer", "(", ")", "func", "(", "interface", "{", "}", ",", "*", "qor", ".", "Context", ")", "interface", "{", "}", "{", "if", "meta", ".", "FormattedValuer", "!=", "nil", "{", "return", "meta", ".", "FormattedValuer", "\n", "}", "\n", "return", "meta", ".", "Valuer", "\n", "}" ]
// GetFormattedValuer get formatted valuer from meta
[ "GetFormattedValuer", "get", "formatted", "valuer", "from", "meta" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta.go#L109-L114
train
qor/qor
resource/meta.go
HasPermission
func (meta Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool { if meta.Permission == nil { return true } var roles = []interface{}{} for _, role := range context.Roles { roles = append(roles, role) } return meta.Permission.HasPermission(mode, roles...) }
go
func (meta Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool { if meta.Permission == nil { return true } var roles = []interface{}{} for _, role := range context.Roles { roles = append(roles, role) } return meta.Permission.HasPermission(mode, roles...) }
[ "func", "(", "meta", "Meta", ")", "HasPermission", "(", "mode", "roles", ".", "PermissionMode", ",", "context", "*", "qor", ".", "Context", ")", "bool", "{", "if", "meta", ".", "Permission", "==", "nil", "{", "return", "true", "\n", "}", "\n", "var", "roles", "=", "[", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "role", ":=", "range", "context", ".", "Roles", "{", "roles", "=", "append", "(", "roles", ",", "role", ")", "\n", "}", "\n", "return", "meta", ".", "Permission", ".", "HasPermission", "(", "mode", ",", "roles", "...", ")", "\n", "}" ]
// HasPermission check has permission or not
[ "HasPermission", "check", "has", "permission", "or", "not" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta.go#L122-L131
train
qor/qor
resource/meta.go
PreInitialize
func (meta *Meta) PreInitialize() error { if meta.Name == "" { utils.ExitWithMsg("Meta should have name: %v", reflect.TypeOf(meta)) } else if meta.FieldName == "" { meta.FieldName = meta.Name } // parseNestedField used to handle case like Profile.Name var parseNestedField = func(value reflect.Value, name string) (reflect.Value, string) { fields := strings.Split(name, ".") value = reflect.Indirect(value) for _, field := range fields[:len(fields)-1] { value = value.FieldByName(field) } return value, fields[len(fields)-1] } var getField = func(fields []*gorm.StructField, name string) *gorm.StructField { for _, field := range fields { if field.Name == name || field.DBName == name { return field } } return nil } var nestedField = strings.Contains(meta.FieldName, ".") var scope = &gorm.Scope{Value: meta.BaseResource.GetResource().Value} if nestedField { subModel, name := parseNestedField(reflect.ValueOf(meta.BaseResource.GetResource().Value), meta.FieldName) meta.FieldStruct = getField(scope.New(subModel.Interface()).GetStructFields(), name) } else { meta.FieldStruct = getField(scope.GetStructFields(), meta.FieldName) } return nil }
go
func (meta *Meta) PreInitialize() error { if meta.Name == "" { utils.ExitWithMsg("Meta should have name: %v", reflect.TypeOf(meta)) } else if meta.FieldName == "" { meta.FieldName = meta.Name } // parseNestedField used to handle case like Profile.Name var parseNestedField = func(value reflect.Value, name string) (reflect.Value, string) { fields := strings.Split(name, ".") value = reflect.Indirect(value) for _, field := range fields[:len(fields)-1] { value = value.FieldByName(field) } return value, fields[len(fields)-1] } var getField = func(fields []*gorm.StructField, name string) *gorm.StructField { for _, field := range fields { if field.Name == name || field.DBName == name { return field } } return nil } var nestedField = strings.Contains(meta.FieldName, ".") var scope = &gorm.Scope{Value: meta.BaseResource.GetResource().Value} if nestedField { subModel, name := parseNestedField(reflect.ValueOf(meta.BaseResource.GetResource().Value), meta.FieldName) meta.FieldStruct = getField(scope.New(subModel.Interface()).GetStructFields(), name) } else { meta.FieldStruct = getField(scope.GetStructFields(), meta.FieldName) } return nil }
[ "func", "(", "meta", "*", "Meta", ")", "PreInitialize", "(", ")", "error", "{", "if", "meta", ".", "Name", "==", "\"\"", "{", "utils", ".", "ExitWithMsg", "(", "\"Meta should have name: %v\"", ",", "reflect", ".", "TypeOf", "(", "meta", ")", ")", "\n", "}", "else", "if", "meta", ".", "FieldName", "==", "\"\"", "{", "meta", ".", "FieldName", "=", "meta", ".", "Name", "\n", "}", "\n", "var", "parseNestedField", "=", "func", "(", "value", "reflect", ".", "Value", ",", "name", "string", ")", "(", "reflect", ".", "Value", ",", "string", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "name", ",", "\".\"", ")", "\n", "value", "=", "reflect", ".", "Indirect", "(", "value", ")", "\n", "for", "_", ",", "field", ":=", "range", "fields", "[", ":", "len", "(", "fields", ")", "-", "1", "]", "{", "value", "=", "value", ".", "FieldByName", "(", "field", ")", "\n", "}", "\n", "return", "value", ",", "fields", "[", "len", "(", "fields", ")", "-", "1", "]", "\n", "}", "\n", "var", "getField", "=", "func", "(", "fields", "[", "]", "*", "gorm", ".", "StructField", ",", "name", "string", ")", "*", "gorm", ".", "StructField", "{", "for", "_", ",", "field", ":=", "range", "fields", "{", "if", "field", ".", "Name", "==", "name", "||", "field", ".", "DBName", "==", "name", "{", "return", "field", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "var", "nestedField", "=", "strings", ".", "Contains", "(", "meta", ".", "FieldName", ",", "\".\"", ")", "\n", "var", "scope", "=", "&", "gorm", ".", "Scope", "{", "Value", ":", "meta", ".", "BaseResource", ".", "GetResource", "(", ")", ".", "Value", "}", "\n", "if", "nestedField", "{", "subModel", ",", "name", ":=", "parseNestedField", "(", "reflect", ".", "ValueOf", "(", "meta", ".", "BaseResource", ".", "GetResource", "(", ")", ".", "Value", ")", ",", "meta", ".", "FieldName", ")", "\n", "meta", ".", "FieldStruct", "=", "getField", "(", "scope", ".", "New", "(", "subModel", ".", "Interface", "(", ")", ")", ".", "GetStructFields", "(", ")", ",", "name", ")", "\n", "}", "else", "{", "meta", ".", "FieldStruct", "=", "getField", "(", "scope", ".", "GetStructFields", "(", ")", ",", "meta", ".", "FieldName", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// PreInitialize when will be run before initialize, used to fill some basic necessary information
[ "PreInitialize", "when", "will", "be", "run", "before", "initialize", "used", "to", "fill", "some", "basic", "necessary", "information" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta.go#L139-L175
train
qor/qor
resource/meta.go
Initialize
func (meta *Meta) Initialize() error { // Set Valuer for Meta if meta.Valuer == nil { setupValuer(meta, meta.FieldName, meta.GetBaseResource().NewStruct()) } if meta.Valuer == nil { utils.ExitWithMsg("Meta %v is not supported for resource %v, no `Valuer` configured for it", meta.FieldName, reflect.TypeOf(meta.BaseResource.GetResource().Value)) } // Set Setter for Meta if meta.Setter == nil { setupSetter(meta, meta.FieldName, meta.GetBaseResource().NewStruct()) } return nil }
go
func (meta *Meta) Initialize() error { // Set Valuer for Meta if meta.Valuer == nil { setupValuer(meta, meta.FieldName, meta.GetBaseResource().NewStruct()) } if meta.Valuer == nil { utils.ExitWithMsg("Meta %v is not supported for resource %v, no `Valuer` configured for it", meta.FieldName, reflect.TypeOf(meta.BaseResource.GetResource().Value)) } // Set Setter for Meta if meta.Setter == nil { setupSetter(meta, meta.FieldName, meta.GetBaseResource().NewStruct()) } return nil }
[ "func", "(", "meta", "*", "Meta", ")", "Initialize", "(", ")", "error", "{", "if", "meta", ".", "Valuer", "==", "nil", "{", "setupValuer", "(", "meta", ",", "meta", ".", "FieldName", ",", "meta", ".", "GetBaseResource", "(", ")", ".", "NewStruct", "(", ")", ")", "\n", "}", "\n", "if", "meta", ".", "Valuer", "==", "nil", "{", "utils", ".", "ExitWithMsg", "(", "\"Meta %v is not supported for resource %v, no `Valuer` configured for it\"", ",", "meta", ".", "FieldName", ",", "reflect", ".", "TypeOf", "(", "meta", ".", "BaseResource", ".", "GetResource", "(", ")", ".", "Value", ")", ")", "\n", "}", "\n", "if", "meta", ".", "Setter", "==", "nil", "{", "setupSetter", "(", "meta", ",", "meta", ".", "FieldName", ",", "meta", ".", "GetBaseResource", "(", ")", ".", "NewStruct", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Initialize initialize meta, will set valuer, setter if haven't configure it
[ "Initialize", "initialize", "meta", "will", "set", "valuer", "setter", "if", "haven", "t", "configure", "it" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta.go#L178-L193
train
qor/qor
resource/crud.go
CallFindOne
func (res *Resource) CallFindOne(result interface{}, metaValues *MetaValues, context *qor.Context) error { return res.FindOneHandler(result, metaValues, context) }
go
func (res *Resource) CallFindOne(result interface{}, metaValues *MetaValues, context *qor.Context) error { return res.FindOneHandler(result, metaValues, context) }
[ "func", "(", "res", "*", "Resource", ")", "CallFindOne", "(", "result", "interface", "{", "}", ",", "metaValues", "*", "MetaValues", ",", "context", "*", "qor", ".", "Context", ")", "error", "{", "return", "res", ".", "FindOneHandler", "(", "result", ",", "metaValues", ",", "context", ")", "\n", "}" ]
// CallFindOne call find one method
[ "CallFindOne", "call", "find", "one", "method" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/crud.go#L15-L17
train
qor/qor
resource/crud.go
CallFindMany
func (res *Resource) CallFindMany(result interface{}, context *qor.Context) error { return res.FindManyHandler(result, context) }
go
func (res *Resource) CallFindMany(result interface{}, context *qor.Context) error { return res.FindManyHandler(result, context) }
[ "func", "(", "res", "*", "Resource", ")", "CallFindMany", "(", "result", "interface", "{", "}", ",", "context", "*", "qor", ".", "Context", ")", "error", "{", "return", "res", ".", "FindManyHandler", "(", "result", ",", "context", ")", "\n", "}" ]
// CallFindMany call find many method
[ "CallFindMany", "call", "find", "many", "method" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/crud.go#L20-L22
train
qor/qor
resource/crud.go
CallSave
func (res *Resource) CallSave(result interface{}, context *qor.Context) error { return res.SaveHandler(result, context) }
go
func (res *Resource) CallSave(result interface{}, context *qor.Context) error { return res.SaveHandler(result, context) }
[ "func", "(", "res", "*", "Resource", ")", "CallSave", "(", "result", "interface", "{", "}", ",", "context", "*", "qor", ".", "Context", ")", "error", "{", "return", "res", ".", "SaveHandler", "(", "result", ",", "context", ")", "\n", "}" ]
// CallSave call save method
[ "CallSave", "call", "save", "method" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/crud.go#L25-L27
train
qor/qor
resource/crud.go
CallDelete
func (res *Resource) CallDelete(result interface{}, context *qor.Context) error { return res.DeleteHandler(result, context) }
go
func (res *Resource) CallDelete(result interface{}, context *qor.Context) error { return res.DeleteHandler(result, context) }
[ "func", "(", "res", "*", "Resource", ")", "CallDelete", "(", "result", "interface", "{", "}", ",", "context", "*", "qor", ".", "Context", ")", "error", "{", "return", "res", ".", "DeleteHandler", "(", "result", ",", "context", ")", "\n", "}" ]
// CallDelete call delete method
[ "CallDelete", "call", "delete", "method" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/crud.go#L30-L32
train
qor/qor
resource/crud.go
ToPrimaryQueryParams
func (res *Resource) ToPrimaryQueryParams(primaryValue string, context *qor.Context) (string, []interface{}) { if primaryValue != "" { scope := context.GetDB().NewScope(res.Value) // multiple primary fields if len(res.PrimaryFields) > 1 { if primaryValueStrs := strings.Split(primaryValue, ","); len(primaryValueStrs) == len(res.PrimaryFields) { sqls := []string{} primaryValues := []interface{}{} for idx, field := range res.PrimaryFields { sqls = append(sqls, fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(field.DBName))) primaryValues = append(primaryValues, primaryValueStrs[idx]) } return strings.Join(sqls, " AND "), primaryValues } } // fallback to first configured primary field if len(res.PrimaryFields) > 0 { return fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(res.PrimaryFields[0].DBName)), []interface{}{primaryValue} } // if no configured primary fields found if primaryField := scope.PrimaryField(); primaryField != nil { return fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(primaryField.DBName)), []interface{}{primaryValue} } } return "", []interface{}{} }
go
func (res *Resource) ToPrimaryQueryParams(primaryValue string, context *qor.Context) (string, []interface{}) { if primaryValue != "" { scope := context.GetDB().NewScope(res.Value) // multiple primary fields if len(res.PrimaryFields) > 1 { if primaryValueStrs := strings.Split(primaryValue, ","); len(primaryValueStrs) == len(res.PrimaryFields) { sqls := []string{} primaryValues := []interface{}{} for idx, field := range res.PrimaryFields { sqls = append(sqls, fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(field.DBName))) primaryValues = append(primaryValues, primaryValueStrs[idx]) } return strings.Join(sqls, " AND "), primaryValues } } // fallback to first configured primary field if len(res.PrimaryFields) > 0 { return fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(res.PrimaryFields[0].DBName)), []interface{}{primaryValue} } // if no configured primary fields found if primaryField := scope.PrimaryField(); primaryField != nil { return fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(primaryField.DBName)), []interface{}{primaryValue} } } return "", []interface{}{} }
[ "func", "(", "res", "*", "Resource", ")", "ToPrimaryQueryParams", "(", "primaryValue", "string", ",", "context", "*", "qor", ".", "Context", ")", "(", "string", ",", "[", "]", "interface", "{", "}", ")", "{", "if", "primaryValue", "!=", "\"\"", "{", "scope", ":=", "context", ".", "GetDB", "(", ")", ".", "NewScope", "(", "res", ".", "Value", ")", "\n", "if", "len", "(", "res", ".", "PrimaryFields", ")", ">", "1", "{", "if", "primaryValueStrs", ":=", "strings", ".", "Split", "(", "primaryValue", ",", "\",\"", ")", ";", "len", "(", "primaryValueStrs", ")", "==", "len", "(", "res", ".", "PrimaryFields", ")", "{", "sqls", ":=", "[", "]", "string", "{", "}", "\n", "primaryValues", ":=", "[", "]", "interface", "{", "}", "{", "}", "\n", "for", "idx", ",", "field", ":=", "range", "res", ".", "PrimaryFields", "{", "sqls", "=", "append", "(", "sqls", ",", "fmt", ".", "Sprintf", "(", "\"%v.%v = ?\"", ",", "scope", ".", "QuotedTableName", "(", ")", ",", "scope", ".", "Quote", "(", "field", ".", "DBName", ")", ")", ")", "\n", "primaryValues", "=", "append", "(", "primaryValues", ",", "primaryValueStrs", "[", "idx", "]", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "sqls", ",", "\" AND \"", ")", ",", "primaryValues", "\n", "}", "\n", "}", "\n", "if", "len", "(", "res", ".", "PrimaryFields", ")", ">", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"%v.%v = ?\"", ",", "scope", ".", "QuotedTableName", "(", ")", ",", "scope", ".", "Quote", "(", "res", ".", "PrimaryFields", "[", "0", "]", ".", "DBName", ")", ")", ",", "[", "]", "interface", "{", "}", "{", "primaryValue", "}", "\n", "}", "\n", "if", "primaryField", ":=", "scope", ".", "PrimaryField", "(", ")", ";", "primaryField", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"%v.%v = ?\"", ",", "scope", ".", "QuotedTableName", "(", ")", ",", "scope", ".", "Quote", "(", "primaryField", ".", "DBName", ")", ")", ",", "[", "]", "interface", "{", "}", "{", "primaryValue", "}", "\n", "}", "\n", "}", "\n", "return", "\"\"", ",", "[", "]", "interface", "{", "}", "{", "}", "\n", "}" ]
// ToPrimaryQueryParams generate query params based on primary key, multiple primary value are linked with a comma
[ "ToPrimaryQueryParams", "generate", "query", "params", "based", "on", "primary", "key", "multiple", "primary", "value", "are", "linked", "with", "a", "comma" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/crud.go#L35-L65
train
qor/qor
resource/crud.go
ToPrimaryQueryParamsFromMetaValue
func (res *Resource) ToPrimaryQueryParamsFromMetaValue(metaValues *MetaValues, context *qor.Context) (string, []interface{}) { var ( sqls []string primaryValues []interface{} scope = context.GetDB().NewScope(res.Value) ) if metaValues != nil { for _, field := range res.PrimaryFields { if metaField := metaValues.Get(field.Name); metaField != nil { sqls = append(sqls, fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(field.DBName))) primaryValues = append(primaryValues, utils.ToString(metaField.Value)) } } } return strings.Join(sqls, " AND "), primaryValues }
go
func (res *Resource) ToPrimaryQueryParamsFromMetaValue(metaValues *MetaValues, context *qor.Context) (string, []interface{}) { var ( sqls []string primaryValues []interface{} scope = context.GetDB().NewScope(res.Value) ) if metaValues != nil { for _, field := range res.PrimaryFields { if metaField := metaValues.Get(field.Name); metaField != nil { sqls = append(sqls, fmt.Sprintf("%v.%v = ?", scope.QuotedTableName(), scope.Quote(field.DBName))) primaryValues = append(primaryValues, utils.ToString(metaField.Value)) } } } return strings.Join(sqls, " AND "), primaryValues }
[ "func", "(", "res", "*", "Resource", ")", "ToPrimaryQueryParamsFromMetaValue", "(", "metaValues", "*", "MetaValues", ",", "context", "*", "qor", ".", "Context", ")", "(", "string", ",", "[", "]", "interface", "{", "}", ")", "{", "var", "(", "sqls", "[", "]", "string", "\n", "primaryValues", "[", "]", "interface", "{", "}", "\n", "scope", "=", "context", ".", "GetDB", "(", ")", ".", "NewScope", "(", "res", ".", "Value", ")", "\n", ")", "\n", "if", "metaValues", "!=", "nil", "{", "for", "_", ",", "field", ":=", "range", "res", ".", "PrimaryFields", "{", "if", "metaField", ":=", "metaValues", ".", "Get", "(", "field", ".", "Name", ")", ";", "metaField", "!=", "nil", "{", "sqls", "=", "append", "(", "sqls", ",", "fmt", ".", "Sprintf", "(", "\"%v.%v = ?\"", ",", "scope", ".", "QuotedTableName", "(", ")", ",", "scope", ".", "Quote", "(", "field", ".", "DBName", ")", ")", ")", "\n", "primaryValues", "=", "append", "(", "primaryValues", ",", "utils", ".", "ToString", "(", "metaField", ".", "Value", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "sqls", ",", "\" AND \"", ")", ",", "primaryValues", "\n", "}" ]
// ToPrimaryQueryParamsFromMetaValue generate query params based on MetaValues
[ "ToPrimaryQueryParamsFromMetaValue", "generate", "query", "params", "based", "on", "MetaValues" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/crud.go#L68-L85
train
qor/qor
resource/schema.go
ConvertJSONToMetaValues
func ConvertJSONToMetaValues(reader io.Reader, metaors []Metaor) (*MetaValues, error) { var ( err error values = map[string]interface{}{} decoder = json.NewDecoder(reader) ) if err = decoder.Decode(&values); err == nil { return convertMapToMetaValues(values, metaors) } return nil, err }
go
func ConvertJSONToMetaValues(reader io.Reader, metaors []Metaor) (*MetaValues, error) { var ( err error values = map[string]interface{}{} decoder = json.NewDecoder(reader) ) if err = decoder.Decode(&values); err == nil { return convertMapToMetaValues(values, metaors) } return nil, err }
[ "func", "ConvertJSONToMetaValues", "(", "reader", "io", ".", "Reader", ",", "metaors", "[", "]", "Metaor", ")", "(", "*", "MetaValues", ",", "error", ")", "{", "var", "(", "err", "error", "\n", "values", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "decoder", "=", "json", ".", "NewDecoder", "(", "reader", ")", "\n", ")", "\n", "if", "err", "=", "decoder", ".", "Decode", "(", "&", "values", ")", ";", "err", "==", "nil", "{", "return", "convertMapToMetaValues", "(", "values", ",", "metaors", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// ConvertJSONToMetaValues convert json to meta values
[ "ConvertJSONToMetaValues", "convert", "json", "to", "meta", "values" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/schema.go#L59-L70
train
qor/qor
resource/schema.go
Decode
func Decode(context *qor.Context, result interface{}, res Resourcer) error { var errors qor.Errors var err error var metaValues *MetaValues metaors := res.GetMetas([]string{}) if strings.Contains(context.Request.Header.Get("Content-Type"), "json") { metaValues, err = ConvertJSONToMetaValues(context.Request.Body, metaors) context.Request.Body.Close() } else { metaValues, err = ConvertFormToMetaValues(context.Request, metaors, "QorResource.") } errors.AddError(err) errors.AddError(DecodeToResource(res, result, metaValues, context).Start()) return errors }
go
func Decode(context *qor.Context, result interface{}, res Resourcer) error { var errors qor.Errors var err error var metaValues *MetaValues metaors := res.GetMetas([]string{}) if strings.Contains(context.Request.Header.Get("Content-Type"), "json") { metaValues, err = ConvertJSONToMetaValues(context.Request.Body, metaors) context.Request.Body.Close() } else { metaValues, err = ConvertFormToMetaValues(context.Request, metaors, "QorResource.") } errors.AddError(err) errors.AddError(DecodeToResource(res, result, metaValues, context).Start()) return errors }
[ "func", "Decode", "(", "context", "*", "qor", ".", "Context", ",", "result", "interface", "{", "}", ",", "res", "Resourcer", ")", "error", "{", "var", "errors", "qor", ".", "Errors", "\n", "var", "err", "error", "\n", "var", "metaValues", "*", "MetaValues", "\n", "metaors", ":=", "res", ".", "GetMetas", "(", "[", "]", "string", "{", "}", ")", "\n", "if", "strings", ".", "Contains", "(", "context", ".", "Request", ".", "Header", ".", "Get", "(", "\"Content-Type\"", ")", ",", "\"json\"", ")", "{", "metaValues", ",", "err", "=", "ConvertJSONToMetaValues", "(", "context", ".", "Request", ".", "Body", ",", "metaors", ")", "\n", "context", ".", "Request", ".", "Body", ".", "Close", "(", ")", "\n", "}", "else", "{", "metaValues", ",", "err", "=", "ConvertFormToMetaValues", "(", "context", ".", "Request", ",", "metaors", ",", "\"QorResource.\"", ")", "\n", "}", "\n", "errors", ".", "AddError", "(", "err", ")", "\n", "errors", ".", "AddError", "(", "DecodeToResource", "(", "res", ",", "result", ",", "metaValues", ",", "context", ")", ".", "Start", "(", ")", ")", "\n", "return", "errors", "\n", "}" ]
// Decode decode context to result according to resource definition
[ "Decode", "decode", "context", "to", "result", "according", "to", "resource", "definition" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/schema.go#L162-L178
train
qor/qor
resource/processor.go
DecodeToResource
func DecodeToResource(res Resourcer, result interface{}, metaValues *MetaValues, context *qor.Context) *processor { return &processor{Resource: res, Result: result, Context: context, MetaValues: metaValues} }
go
func DecodeToResource(res Resourcer, result interface{}, metaValues *MetaValues, context *qor.Context) *processor { return &processor{Resource: res, Result: result, Context: context, MetaValues: metaValues} }
[ "func", "DecodeToResource", "(", "res", "Resourcer", ",", "result", "interface", "{", "}", ",", "metaValues", "*", "MetaValues", ",", "context", "*", "qor", ".", "Context", ")", "*", "processor", "{", "return", "&", "processor", "{", "Resource", ":", "res", ",", "Result", ":", "result", ",", "Context", ":", "context", ",", "MetaValues", ":", "metaValues", "}", "\n", "}" ]
// DecodeToResource decode meta values to resource result
[ "DecodeToResource", "decode", "meta", "values", "to", "resource", "result" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/processor.go#L26-L28
train
qor/qor
resource/processor.go
Initialize
func (processor *processor) Initialize() error { err := processor.Resource.CallFindOne(processor.Result, processor.MetaValues, processor.Context) processor.checkSkipLeft(err) return err }
go
func (processor *processor) Initialize() error { err := processor.Resource.CallFindOne(processor.Result, processor.MetaValues, processor.Context) processor.checkSkipLeft(err) return err }
[ "func", "(", "processor", "*", "processor", ")", "Initialize", "(", ")", "error", "{", "err", ":=", "processor", ".", "Resource", ".", "CallFindOne", "(", "processor", ".", "Result", ",", "processor", ".", "MetaValues", ",", "processor", ".", "Context", ")", "\n", "processor", ".", "checkSkipLeft", "(", "err", ")", "\n", "return", "err", "\n", "}" ]
// Initialize initialize a processor
[ "Initialize", "initialize", "a", "processor" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/processor.go#L45-L49
train
qor/qor
resource/processor.go
Validate
func (processor *processor) Validate() error { var errs qor.Errors if processor.checkSkipLeft() { return nil } for _, v := range processor.Resource.GetResource().Validators { if errs.AddError(v.Handler(processor.Result, processor.MetaValues, processor.Context)); !errs.HasError() { if processor.checkSkipLeft(errs.GetErrors()...) { break } } } return errs }
go
func (processor *processor) Validate() error { var errs qor.Errors if processor.checkSkipLeft() { return nil } for _, v := range processor.Resource.GetResource().Validators { if errs.AddError(v.Handler(processor.Result, processor.MetaValues, processor.Context)); !errs.HasError() { if processor.checkSkipLeft(errs.GetErrors()...) { break } } } return errs }
[ "func", "(", "processor", "*", "processor", ")", "Validate", "(", ")", "error", "{", "var", "errs", "qor", ".", "Errors", "\n", "if", "processor", ".", "checkSkipLeft", "(", ")", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "processor", ".", "Resource", ".", "GetResource", "(", ")", ".", "Validators", "{", "if", "errs", ".", "AddError", "(", "v", ".", "Handler", "(", "processor", ".", "Result", ",", "processor", ".", "MetaValues", ",", "processor", ".", "Context", ")", ")", ";", "!", "errs", ".", "HasError", "(", ")", "{", "if", "processor", ".", "checkSkipLeft", "(", "errs", ".", "GetErrors", "(", ")", "...", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "errs", "\n", "}" ]
// Validate run validators
[ "Validate", "run", "validators" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/processor.go#L52-L66
train
qor/qor
resource/processor.go
Start
func (processor *processor) Start() error { var errs qor.Errors processor.Initialize() if errs.AddError(processor.Validate()); !errs.HasError() { errs.AddError(processor.Commit()) } if errs.HasError() { return errs } return nil }
go
func (processor *processor) Start() error { var errs qor.Errors processor.Initialize() if errs.AddError(processor.Validate()); !errs.HasError() { errs.AddError(processor.Commit()) } if errs.HasError() { return errs } return nil }
[ "func", "(", "processor", "*", "processor", ")", "Start", "(", ")", "error", "{", "var", "errs", "qor", ".", "Errors", "\n", "processor", ".", "Initialize", "(", ")", "\n", "if", "errs", ".", "AddError", "(", "processor", ".", "Validate", "(", ")", ")", ";", "!", "errs", ".", "HasError", "(", ")", "{", "errs", ".", "AddError", "(", "processor", ".", "Commit", "(", ")", ")", "\n", "}", "\n", "if", "errs", ".", "HasError", "(", ")", "{", "return", "errs", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Start start processor
[ "Start", "start", "processor" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/processor.go#L126-L136
train
qor/qor
resource/processor.go
Commit
func (processor *processor) Commit() error { var errs qor.Errors errs.AddError(processor.decode()...) if processor.checkSkipLeft(errs.GetErrors()...) { return nil } for _, p := range processor.Resource.GetResource().Processors { if err := p.Handler(processor.Result, processor.MetaValues, processor.Context); err != nil { if processor.checkSkipLeft(err) { break } errs.AddError(err) } } return errs }
go
func (processor *processor) Commit() error { var errs qor.Errors errs.AddError(processor.decode()...) if processor.checkSkipLeft(errs.GetErrors()...) { return nil } for _, p := range processor.Resource.GetResource().Processors { if err := p.Handler(processor.Result, processor.MetaValues, processor.Context); err != nil { if processor.checkSkipLeft(err) { break } errs.AddError(err) } } return errs }
[ "func", "(", "processor", "*", "processor", ")", "Commit", "(", ")", "error", "{", "var", "errs", "qor", ".", "Errors", "\n", "errs", ".", "AddError", "(", "processor", ".", "decode", "(", ")", "...", ")", "\n", "if", "processor", ".", "checkSkipLeft", "(", "errs", ".", "GetErrors", "(", ")", "...", ")", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "p", ":=", "range", "processor", ".", "Resource", ".", "GetResource", "(", ")", ".", "Processors", "{", "if", "err", ":=", "p", ".", "Handler", "(", "processor", ".", "Result", ",", "processor", ".", "MetaValues", ",", "processor", ".", "Context", ")", ";", "err", "!=", "nil", "{", "if", "processor", ".", "checkSkipLeft", "(", "err", ")", "{", "break", "\n", "}", "\n", "errs", ".", "AddError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "errs", "\n", "}" ]
// Commit commit data into result
[ "Commit", "commit", "data", "into", "result" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/processor.go#L139-L155
train
qor/qor
utils/params.go
ParamsMatch
func ParamsMatch(source string, pth string) (url.Values, string, bool) { var ( i, j int p = make(url.Values) ext = path.Ext(pth) ) pth = strings.TrimSuffix(pth, ext) if ext != "" { p.Add(":format", strings.TrimPrefix(ext, ".")) } for i < len(pth) { switch { case j >= len(source): if source != "/" && len(source) > 0 && source[len(source)-1] == '/' { return p, pth[:i], true } if source == "" && pth == "/" { return p, pth, true } return p, pth[:i], false case source[j] == ':': var name, val string var nextc byte name, nextc, j = match(source, isAlnum, j+1) val, _, i = match(pth, matchPart(nextc), i) if (j < len(source)) && source[j] == '[' { var index int if idx := strings.Index(source[j:], "]/"); idx > 0 { index = idx } else if source[len(source)-1] == ']' { index = len(source) - j - 1 } if index > 0 { match := strings.TrimSuffix(strings.TrimPrefix(source[j:j+index+1], "["), "]") if reg, err := regexp.Compile("^" + match + "$"); err == nil && reg.MatchString(val) { j = j + index + 1 } else { return nil, "", false } } } p.Add(":"+name, val) case pth[i] == source[j]: i++ j++ default: return nil, "", false } } if j != len(source) { if (len(source) == j+1) && source[j] == '/' { return p, pth, true } return nil, "", false } return p, pth, true }
go
func ParamsMatch(source string, pth string) (url.Values, string, bool) { var ( i, j int p = make(url.Values) ext = path.Ext(pth) ) pth = strings.TrimSuffix(pth, ext) if ext != "" { p.Add(":format", strings.TrimPrefix(ext, ".")) } for i < len(pth) { switch { case j >= len(source): if source != "/" && len(source) > 0 && source[len(source)-1] == '/' { return p, pth[:i], true } if source == "" && pth == "/" { return p, pth, true } return p, pth[:i], false case source[j] == ':': var name, val string var nextc byte name, nextc, j = match(source, isAlnum, j+1) val, _, i = match(pth, matchPart(nextc), i) if (j < len(source)) && source[j] == '[' { var index int if idx := strings.Index(source[j:], "]/"); idx > 0 { index = idx } else if source[len(source)-1] == ']' { index = len(source) - j - 1 } if index > 0 { match := strings.TrimSuffix(strings.TrimPrefix(source[j:j+index+1], "["), "]") if reg, err := regexp.Compile("^" + match + "$"); err == nil && reg.MatchString(val) { j = j + index + 1 } else { return nil, "", false } } } p.Add(":"+name, val) case pth[i] == source[j]: i++ j++ default: return nil, "", false } } if j != len(source) { if (len(source) == j+1) && source[j] == '/' { return p, pth, true } return nil, "", false } return p, pth, true }
[ "func", "ParamsMatch", "(", "source", "string", ",", "pth", "string", ")", "(", "url", ".", "Values", ",", "string", ",", "bool", ")", "{", "var", "(", "i", ",", "j", "int", "\n", "p", "=", "make", "(", "url", ".", "Values", ")", "\n", "ext", "=", "path", ".", "Ext", "(", "pth", ")", "\n", ")", "\n", "pth", "=", "strings", ".", "TrimSuffix", "(", "pth", ",", "ext", ")", "\n", "if", "ext", "!=", "\"\"", "{", "p", ".", "Add", "(", "\":format\"", ",", "strings", ".", "TrimPrefix", "(", "ext", ",", "\".\"", ")", ")", "\n", "}", "\n", "for", "i", "<", "len", "(", "pth", ")", "{", "switch", "{", "case", "j", ">=", "len", "(", "source", ")", ":", "if", "source", "!=", "\"/\"", "&&", "len", "(", "source", ")", ">", "0", "&&", "source", "[", "len", "(", "source", ")", "-", "1", "]", "==", "'/'", "{", "return", "p", ",", "pth", "[", ":", "i", "]", ",", "true", "\n", "}", "\n", "if", "source", "==", "\"\"", "&&", "pth", "==", "\"/\"", "{", "return", "p", ",", "pth", ",", "true", "\n", "}", "\n", "return", "p", ",", "pth", "[", ":", "i", "]", ",", "false", "\n", "case", "source", "[", "j", "]", "==", "':'", ":", "var", "name", ",", "val", "string", "\n", "var", "nextc", "byte", "\n", "name", ",", "nextc", ",", "j", "=", "match", "(", "source", ",", "isAlnum", ",", "j", "+", "1", ")", "\n", "val", ",", "_", ",", "i", "=", "match", "(", "pth", ",", "matchPart", "(", "nextc", ")", ",", "i", ")", "\n", "if", "(", "j", "<", "len", "(", "source", ")", ")", "&&", "source", "[", "j", "]", "==", "'['", "{", "var", "index", "int", "\n", "if", "idx", ":=", "strings", ".", "Index", "(", "source", "[", "j", ":", "]", ",", "\"]/\"", ")", ";", "idx", ">", "0", "{", "index", "=", "idx", "\n", "}", "else", "if", "source", "[", "len", "(", "source", ")", "-", "1", "]", "==", "']'", "{", "index", "=", "len", "(", "source", ")", "-", "j", "-", "1", "\n", "}", "\n", "if", "index", ">", "0", "{", "match", ":=", "strings", ".", "TrimSuffix", "(", "strings", ".", "TrimPrefix", "(", "source", "[", "j", ":", "j", "+", "index", "+", "1", "]", ",", "\"[\"", ")", ",", "\"]\"", ")", "\n", "if", "reg", ",", "err", ":=", "regexp", ".", "Compile", "(", "\"^\"", "+", "match", "+", "\"$\"", ")", ";", "err", "==", "nil", "&&", "reg", ".", "MatchString", "(", "val", ")", "{", "j", "=", "j", "+", "index", "+", "1", "\n", "}", "else", "{", "return", "nil", ",", "\"\"", ",", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "p", ".", "Add", "(", "\":\"", "+", "name", ",", "val", ")", "\n", "case", "pth", "[", "i", "]", "==", "source", "[", "j", "]", ":", "i", "++", "\n", "j", "++", "\n", "default", ":", "return", "nil", ",", "\"\"", ",", "false", "\n", "}", "\n", "}", "\n", "if", "j", "!=", "len", "(", "source", ")", "{", "if", "(", "len", "(", "source", ")", "==", "j", "+", "1", ")", "&&", "source", "[", "j", "]", "==", "'/'", "{", "return", "p", ",", "pth", ",", "true", "\n", "}", "\n", "return", "nil", ",", "\"\"", ",", "false", "\n", "}", "\n", "return", "p", ",", "pth", ",", "true", "\n", "}" ]
// ParamsMatch match string by param
[ "ParamsMatch", "match", "string", "by", "param" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/params.go#L40-L107
train
qor/qor
errors.go
AddError
func (errs *Errors) AddError(errors ...error) { for _, err := range errors { if err != nil { if e, ok := err.(errorsInterface); ok { errs.errors = append(errs.errors, e.GetErrors()...) } else { errs.errors = append(errs.errors, err) } } } }
go
func (errs *Errors) AddError(errors ...error) { for _, err := range errors { if err != nil { if e, ok := err.(errorsInterface); ok { errs.errors = append(errs.errors, e.GetErrors()...) } else { errs.errors = append(errs.errors, err) } } } }
[ "func", "(", "errs", "*", "Errors", ")", "AddError", "(", "errors", "...", "error", ")", "{", "for", "_", ",", "err", ":=", "range", "errors", "{", "if", "err", "!=", "nil", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "errorsInterface", ")", ";", "ok", "{", "errs", ".", "errors", "=", "append", "(", "errs", ".", "errors", ",", "e", ".", "GetErrors", "(", ")", "...", ")", "\n", "}", "else", "{", "errs", ".", "errors", "=", "append", "(", "errs", ".", "errors", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// AddError add error to Errors struct
[ "AddError", "add", "error", "to", "Errors", "struct" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/errors.go#L22-L32
train
qor/qor
resource/resource.go
New
func New(value interface{}) *Resource { var ( name = utils.HumanizeString(utils.ModelType(value).Name()) res = &Resource{Value: value, Name: name} ) res.FindOneHandler = res.findOneHandler res.FindManyHandler = res.findManyHandler res.SaveHandler = res.saveHandler res.DeleteHandler = res.deleteHandler res.SetPrimaryFields() return res }
go
func New(value interface{}) *Resource { var ( name = utils.HumanizeString(utils.ModelType(value).Name()) res = &Resource{Value: value, Name: name} ) res.FindOneHandler = res.findOneHandler res.FindManyHandler = res.findManyHandler res.SaveHandler = res.saveHandler res.DeleteHandler = res.deleteHandler res.SetPrimaryFields() return res }
[ "func", "New", "(", "value", "interface", "{", "}", ")", "*", "Resource", "{", "var", "(", "name", "=", "utils", ".", "HumanizeString", "(", "utils", ".", "ModelType", "(", "value", ")", ".", "Name", "(", ")", ")", "\n", "res", "=", "&", "Resource", "{", "Value", ":", "value", ",", "Name", ":", "name", "}", "\n", ")", "\n", "res", ".", "FindOneHandler", "=", "res", ".", "findOneHandler", "\n", "res", ".", "FindManyHandler", "=", "res", ".", "findManyHandler", "\n", "res", ".", "SaveHandler", "=", "res", ".", "saveHandler", "\n", "res", ".", "DeleteHandler", "=", "res", ".", "deleteHandler", "\n", "res", ".", "SetPrimaryFields", "(", ")", "\n", "return", "res", "\n", "}" ]
// New initialize qor resource
[ "New", "initialize", "qor", "resource" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L51-L63
train
qor/qor
resource/resource.go
SetPrimaryFields
func (res *Resource) SetPrimaryFields(fields ...string) error { scope := gorm.Scope{Value: res.Value} res.PrimaryFields = nil if len(fields) > 0 { for _, fieldName := range fields { if field, ok := scope.FieldByName(fieldName); ok { res.PrimaryFields = append(res.PrimaryFields, field.StructField) } else { return fmt.Errorf("%v is not a valid field for resource %v", fieldName, res.Name) } } return nil } if primaryField := scope.PrimaryField(); primaryField != nil { res.PrimaryFields = []*gorm.StructField{primaryField.StructField} return nil } return fmt.Errorf("no valid primary field for resource %v", res.Name) }
go
func (res *Resource) SetPrimaryFields(fields ...string) error { scope := gorm.Scope{Value: res.Value} res.PrimaryFields = nil if len(fields) > 0 { for _, fieldName := range fields { if field, ok := scope.FieldByName(fieldName); ok { res.PrimaryFields = append(res.PrimaryFields, field.StructField) } else { return fmt.Errorf("%v is not a valid field for resource %v", fieldName, res.Name) } } return nil } if primaryField := scope.PrimaryField(); primaryField != nil { res.PrimaryFields = []*gorm.StructField{primaryField.StructField} return nil } return fmt.Errorf("no valid primary field for resource %v", res.Name) }
[ "func", "(", "res", "*", "Resource", ")", "SetPrimaryFields", "(", "fields", "...", "string", ")", "error", "{", "scope", ":=", "gorm", ".", "Scope", "{", "Value", ":", "res", ".", "Value", "}", "\n", "res", ".", "PrimaryFields", "=", "nil", "\n", "if", "len", "(", "fields", ")", ">", "0", "{", "for", "_", ",", "fieldName", ":=", "range", "fields", "{", "if", "field", ",", "ok", ":=", "scope", ".", "FieldByName", "(", "fieldName", ")", ";", "ok", "{", "res", ".", "PrimaryFields", "=", "append", "(", "res", ".", "PrimaryFields", ",", "field", ".", "StructField", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"%v is not a valid field for resource %v\"", ",", "fieldName", ",", "res", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "primaryField", ":=", "scope", ".", "PrimaryField", "(", ")", ";", "primaryField", "!=", "nil", "{", "res", ".", "PrimaryFields", "=", "[", "]", "*", "gorm", ".", "StructField", "{", "primaryField", ".", "StructField", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"no valid primary field for resource %v\"", ",", "res", ".", "Name", ")", "\n", "}" ]
// SetPrimaryFields set primary fields
[ "SetPrimaryFields", "set", "primary", "fields" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L71-L92
train
qor/qor
resource/resource.go
AddValidator
func (res *Resource) AddValidator(validator *Validator) { for idx, v := range res.Validators { if v.Name == validator.Name { res.Validators[idx] = validator return } } res.Validators = append(res.Validators, validator) }
go
func (res *Resource) AddValidator(validator *Validator) { for idx, v := range res.Validators { if v.Name == validator.Name { res.Validators[idx] = validator return } } res.Validators = append(res.Validators, validator) }
[ "func", "(", "res", "*", "Resource", ")", "AddValidator", "(", "validator", "*", "Validator", ")", "{", "for", "idx", ",", "v", ":=", "range", "res", ".", "Validators", "{", "if", "v", ".", "Name", "==", "validator", ".", "Name", "{", "res", ".", "Validators", "[", "idx", "]", "=", "validator", "\n", "return", "\n", "}", "\n", "}", "\n", "res", ".", "Validators", "=", "append", "(", "res", ".", "Validators", ",", "validator", ")", "\n", "}" ]
// AddValidator add validator to resource, it will invoked when creating, updating, and will rollback the change if validator return any error
[ "AddValidator", "add", "validator", "to", "resource", "it", "will", "invoked", "when", "creating", "updating", "and", "will", "rollback", "the", "change", "if", "validator", "return", "any", "error" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L101-L110
train
qor/qor
resource/resource.go
AddProcessor
func (res *Resource) AddProcessor(processor *Processor) { for idx, p := range res.Processors { if p.Name == processor.Name { res.Processors[idx] = processor return } } res.Processors = append(res.Processors, processor) }
go
func (res *Resource) AddProcessor(processor *Processor) { for idx, p := range res.Processors { if p.Name == processor.Name { res.Processors[idx] = processor return } } res.Processors = append(res.Processors, processor) }
[ "func", "(", "res", "*", "Resource", ")", "AddProcessor", "(", "processor", "*", "Processor", ")", "{", "for", "idx", ",", "p", ":=", "range", "res", ".", "Processors", "{", "if", "p", ".", "Name", "==", "processor", ".", "Name", "{", "res", ".", "Processors", "[", "idx", "]", "=", "processor", "\n", "return", "\n", "}", "\n", "}", "\n", "res", ".", "Processors", "=", "append", "(", "res", ".", "Processors", ",", "processor", ")", "\n", "}" ]
// AddProcessor add processor to resource, it is used to process data before creating, updating, will rollback the change if it return any error
[ "AddProcessor", "add", "processor", "to", "resource", "it", "is", "used", "to", "process", "data", "before", "creating", "updating", "will", "rollback", "the", "change", "if", "it", "return", "any", "error" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L119-L127
train
qor/qor
resource/resource.go
NewStruct
func (res *Resource) NewStruct() interface{} { if res.Value == nil { return nil } return reflect.New(utils.Indirect(reflect.ValueOf(res.Value)).Type()).Interface() }
go
func (res *Resource) NewStruct() interface{} { if res.Value == nil { return nil } return reflect.New(utils.Indirect(reflect.ValueOf(res.Value)).Type()).Interface() }
[ "func", "(", "res", "*", "Resource", ")", "NewStruct", "(", ")", "interface", "{", "}", "{", "if", "res", ".", "Value", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "reflect", ".", "New", "(", "utils", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "res", ".", "Value", ")", ")", ".", "Type", "(", ")", ")", ".", "Interface", "(", ")", "\n", "}" ]
// NewStruct initialize a struct for the Resource
[ "NewStruct", "initialize", "a", "struct", "for", "the", "Resource" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L130-L135
train
qor/qor
resource/resource.go
NewSlice
func (res *Resource) NewSlice() interface{} { if res.Value == nil { return nil } sliceType := reflect.SliceOf(reflect.TypeOf(res.Value)) slice := reflect.MakeSlice(sliceType, 0, 0) slicePtr := reflect.New(sliceType) slicePtr.Elem().Set(slice) return slicePtr.Interface() }
go
func (res *Resource) NewSlice() interface{} { if res.Value == nil { return nil } sliceType := reflect.SliceOf(reflect.TypeOf(res.Value)) slice := reflect.MakeSlice(sliceType, 0, 0) slicePtr := reflect.New(sliceType) slicePtr.Elem().Set(slice) return slicePtr.Interface() }
[ "func", "(", "res", "*", "Resource", ")", "NewSlice", "(", ")", "interface", "{", "}", "{", "if", "res", ".", "Value", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "sliceType", ":=", "reflect", ".", "SliceOf", "(", "reflect", ".", "TypeOf", "(", "res", ".", "Value", ")", ")", "\n", "slice", ":=", "reflect", ".", "MakeSlice", "(", "sliceType", ",", "0", ",", "0", ")", "\n", "slicePtr", ":=", "reflect", ".", "New", "(", "sliceType", ")", "\n", "slicePtr", ".", "Elem", "(", ")", ".", "Set", "(", "slice", ")", "\n", "return", "slicePtr", ".", "Interface", "(", ")", "\n", "}" ]
// NewSlice initialize a slice of struct for the Resource
[ "NewSlice", "initialize", "a", "slice", "of", "struct", "for", "the", "Resource" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L138-L147
train
qor/qor
resource/resource.go
HasPermission
func (res *Resource) HasPermission(mode roles.PermissionMode, context *qor.Context) bool { if res == nil || res.Permission == nil { return true } var roles = []interface{}{} for _, role := range context.Roles { roles = append(roles, role) } return res.Permission.HasPermission(mode, roles...) }
go
func (res *Resource) HasPermission(mode roles.PermissionMode, context *qor.Context) bool { if res == nil || res.Permission == nil { return true } var roles = []interface{}{} for _, role := range context.Roles { roles = append(roles, role) } return res.Permission.HasPermission(mode, roles...) }
[ "func", "(", "res", "*", "Resource", ")", "HasPermission", "(", "mode", "roles", ".", "PermissionMode", ",", "context", "*", "qor", ".", "Context", ")", "bool", "{", "if", "res", "==", "nil", "||", "res", ".", "Permission", "==", "nil", "{", "return", "true", "\n", "}", "\n", "var", "roles", "=", "[", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "role", ":=", "range", "context", ".", "Roles", "{", "roles", "=", "append", "(", "roles", ",", "role", ")", "\n", "}", "\n", "return", "res", ".", "Permission", ".", "HasPermission", "(", "mode", ",", "roles", "...", ")", "\n", "}" ]
// HasPermission check permission of resource
[ "HasPermission", "check", "permission", "of", "resource" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/resource.go#L155-L165
train
qor/qor
resource/meta_value.go
Get
func (mvs MetaValues) Get(name string) *MetaValue { for _, mv := range mvs.Values { if mv.Name == name { return mv } } return nil }
go
func (mvs MetaValues) Get(name string) *MetaValue { for _, mv := range mvs.Values { if mv.Name == name { return mv } } return nil }
[ "func", "(", "mvs", "MetaValues", ")", "Get", "(", "name", "string", ")", "*", "MetaValue", "{", "for", "_", ",", "mv", ":=", "range", "mvs", ".", "Values", "{", "if", "mv", ".", "Name", "==", "name", "{", "return", "mv", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Get get meta value from MetaValues with name
[ "Get", "get", "meta", "value", "from", "MetaValues", "with", "name" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/resource/meta_value.go#L15-L23
train
qor/qor
utils/utils.go
GOPATH
func GOPATH() []string { paths := strings.Split(os.Getenv("GOPATH"), string(os.PathListSeparator)) if len(paths) == 0 { fmt.Println("GOPATH doesn't exist") } return paths }
go
func GOPATH() []string { paths := strings.Split(os.Getenv("GOPATH"), string(os.PathListSeparator)) if len(paths) == 0 { fmt.Println("GOPATH doesn't exist") } return paths }
[ "func", "GOPATH", "(", ")", "[", "]", "string", "{", "paths", ":=", "strings", ".", "Split", "(", "os", ".", "Getenv", "(", "\"GOPATH\"", ")", ",", "string", "(", "os", ".", "PathListSeparator", ")", ")", "\n", "if", "len", "(", "paths", ")", "==", "0", "{", "fmt", ".", "Println", "(", "\"GOPATH doesn't exist\"", ")", "\n", "}", "\n", "return", "paths", "\n", "}" ]
// GOPATH return GOPATH from env
[ "GOPATH", "return", "GOPATH", "from", "env" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L48-L54
train
qor/qor
utils/utils.go
SetCookie
func SetCookie(cookie http.Cookie, context *qor.Context) { cookie.HttpOnly = true // set https cookie if context.Request != nil && context.Request.URL.Scheme == "https" { cookie.Secure = true } // set default path if cookie.Path == "" { cookie.Path = "/" } http.SetCookie(context.Writer, &cookie) }
go
func SetCookie(cookie http.Cookie, context *qor.Context) { cookie.HttpOnly = true // set https cookie if context.Request != nil && context.Request.URL.Scheme == "https" { cookie.Secure = true } // set default path if cookie.Path == "" { cookie.Path = "/" } http.SetCookie(context.Writer, &cookie) }
[ "func", "SetCookie", "(", "cookie", "http", ".", "Cookie", ",", "context", "*", "qor", ".", "Context", ")", "{", "cookie", ".", "HttpOnly", "=", "true", "\n", "if", "context", ".", "Request", "!=", "nil", "&&", "context", ".", "Request", ".", "URL", ".", "Scheme", "==", "\"https\"", "{", "cookie", ".", "Secure", "=", "true", "\n", "}", "\n", "if", "cookie", ".", "Path", "==", "\"\"", "{", "cookie", ".", "Path", "=", "\"/\"", "\n", "}", "\n", "http", ".", "SetCookie", "(", "context", ".", "Writer", ",", "&", "cookie", ")", "\n", "}" ]
// SetCookie set cookie for context
[ "SetCookie", "set", "cookie", "for", "context" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L148-L162
train
qor/qor
utils/utils.go
Stringify
func Stringify(object interface{}) string { if obj, ok := object.(interface { Stringify() string }); ok { return obj.Stringify() } scope := gorm.Scope{Value: object} for _, column := range []string{"Name", "Title", "Code"} { if field, ok := scope.FieldByName(column); ok { if field.Field.IsValid() { result := field.Field.Interface() if valuer, ok := result.(driver.Valuer); ok { if result, err := valuer.Value(); err == nil { return fmt.Sprint(result) } } return fmt.Sprint(result) } } } if scope.PrimaryField() != nil { if scope.PrimaryKeyZero() { return "" } return fmt.Sprintf("%v#%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue()) } return fmt.Sprint(reflect.Indirect(reflect.ValueOf(object)).Interface()) }
go
func Stringify(object interface{}) string { if obj, ok := object.(interface { Stringify() string }); ok { return obj.Stringify() } scope := gorm.Scope{Value: object} for _, column := range []string{"Name", "Title", "Code"} { if field, ok := scope.FieldByName(column); ok { if field.Field.IsValid() { result := field.Field.Interface() if valuer, ok := result.(driver.Valuer); ok { if result, err := valuer.Value(); err == nil { return fmt.Sprint(result) } } return fmt.Sprint(result) } } } if scope.PrimaryField() != nil { if scope.PrimaryKeyZero() { return "" } return fmt.Sprintf("%v#%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue()) } return fmt.Sprint(reflect.Indirect(reflect.ValueOf(object)).Interface()) }
[ "func", "Stringify", "(", "object", "interface", "{", "}", ")", "string", "{", "if", "obj", ",", "ok", ":=", "object", ".", "(", "interface", "{", "Stringify", "(", ")", "string", "\n", "}", ")", ";", "ok", "{", "return", "obj", ".", "Stringify", "(", ")", "\n", "}", "\n", "scope", ":=", "gorm", ".", "Scope", "{", "Value", ":", "object", "}", "\n", "for", "_", ",", "column", ":=", "range", "[", "]", "string", "{", "\"Name\"", ",", "\"Title\"", ",", "\"Code\"", "}", "{", "if", "field", ",", "ok", ":=", "scope", ".", "FieldByName", "(", "column", ")", ";", "ok", "{", "if", "field", ".", "Field", ".", "IsValid", "(", ")", "{", "result", ":=", "field", ".", "Field", ".", "Interface", "(", ")", "\n", "if", "valuer", ",", "ok", ":=", "result", ".", "(", "driver", ".", "Valuer", ")", ";", "ok", "{", "if", "result", ",", "err", ":=", "valuer", ".", "Value", "(", ")", ";", "err", "==", "nil", "{", "return", "fmt", ".", "Sprint", "(", "result", ")", "\n", "}", "\n", "}", "\n", "return", "fmt", ".", "Sprint", "(", "result", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "scope", ".", "PrimaryField", "(", ")", "!=", "nil", "{", "if", "scope", ".", "PrimaryKeyZero", "(", ")", "{", "return", "\"\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v#%v\"", ",", "scope", ".", "GetModelStruct", "(", ")", ".", "ModelType", ".", "Name", "(", ")", ",", "scope", ".", "PrimaryKeyValue", "(", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprint", "(", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "object", ")", ")", ".", "Interface", "(", ")", ")", "\n", "}" ]
// Stringify stringify any data, if it is a struct, will try to use its Name, Title, Code field, else will use its primary key
[ "Stringify", "stringify", "any", "data", "if", "it", "is", "a", "struct", "will", "try", "to", "use", "its", "Name", "Title", "Code", "field", "else", "will", "use", "its", "primary", "key" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L165-L195
train
qor/qor
utils/utils.go
ExitWithMsg
func ExitWithMsg(msg interface{}, value ...interface{}) { fmt.Printf("\n"+filenameWithLineNum()+"\n"+fmt.Sprint(msg)+"\n", value...) debug.PrintStack() }
go
func ExitWithMsg(msg interface{}, value ...interface{}) { fmt.Printf("\n"+filenameWithLineNum()+"\n"+fmt.Sprint(msg)+"\n", value...) debug.PrintStack() }
[ "func", "ExitWithMsg", "(", "msg", "interface", "{", "}", ",", "value", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"\\n\"", "+", "\\n", "+", "filenameWithLineNum", "(", ")", "+", "\"\\n\"", "+", "\\n", ",", "fmt", ".", "Sprint", "(", "msg", ")", ")", "\n", "\"\\n\"", "\n", "}" ]
// ExitWithMsg debug error messages and print stack
[ "ExitWithMsg", "debug", "error", "messages", "and", "print", "stack" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L225-L228
train
qor/qor
utils/utils.go
FileServer
func FileServer(dir http.Dir) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := path.Join(string(dir), r.URL.Path) if f, err := os.Stat(p); err == nil && !f.IsDir() { http.ServeFile(w, r, p) return } http.NotFound(w, r) }) }
go
func FileServer(dir http.Dir) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := path.Join(string(dir), r.URL.Path) if f, err := os.Stat(p); err == nil && !f.IsDir() { http.ServeFile(w, r, p) return } http.NotFound(w, r) }) }
[ "func", "FileServer", "(", "dir", "http", ".", "Dir", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "p", ":=", "path", ".", "Join", "(", "string", "(", "dir", ")", ",", "r", ".", "URL", ".", "Path", ")", "\n", "if", "f", ",", "err", ":=", "os", ".", "Stat", "(", "p", ")", ";", "err", "==", "nil", "&&", "!", "f", ".", "IsDir", "(", ")", "{", "http", ".", "ServeFile", "(", "w", ",", "r", ",", "p", ")", "\n", "return", "\n", "}", "\n", "http", ".", "NotFound", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// FileServer file server that disabled file listing
[ "FileServer", "file", "server", "that", "disabled", "file", "listing" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L231-L241
train
qor/qor
utils/utils.go
SortFormKeys
func SortFormKeys(strs []string) { sort.Slice(strs, func(i, j int) bool { // true for first str1 := strs[i] str2 := strs[j] matched1 := replaceIdxRegexp.FindAllStringIndex(str1, -1) matched2 := replaceIdxRegexp.FindAllStringIndex(str2, -1) for x := 0; x < len(matched1); x++ { prefix1 := str1[:matched1[x][0]] prefix2 := str2 if len(matched2) >= x+1 { prefix2 = str2[:matched2[x][0]] } if prefix1 != prefix2 { return strings.Compare(prefix1, prefix2) < 0 } if len(matched2) < x+1 { return false } number1 := str1[matched1[x][0]:matched1[x][1]] number2 := str2[matched2[x][0]:matched2[x][1]] if number1 != number2 { if len(number1) != len(number2) { return len(number1) < len(number2) } return strings.Compare(number1, number2) < 0 } } return strings.Compare(str1, str2) < 0 }) }
go
func SortFormKeys(strs []string) { sort.Slice(strs, func(i, j int) bool { // true for first str1 := strs[i] str2 := strs[j] matched1 := replaceIdxRegexp.FindAllStringIndex(str1, -1) matched2 := replaceIdxRegexp.FindAllStringIndex(str2, -1) for x := 0; x < len(matched1); x++ { prefix1 := str1[:matched1[x][0]] prefix2 := str2 if len(matched2) >= x+1 { prefix2 = str2[:matched2[x][0]] } if prefix1 != prefix2 { return strings.Compare(prefix1, prefix2) < 0 } if len(matched2) < x+1 { return false } number1 := str1[matched1[x][0]:matched1[x][1]] number2 := str2[matched2[x][0]:matched2[x][1]] if number1 != number2 { if len(number1) != len(number2) { return len(number1) < len(number2) } return strings.Compare(number1, number2) < 0 } } return strings.Compare(str1, str2) < 0 }) }
[ "func", "SortFormKeys", "(", "strs", "[", "]", "string", ")", "{", "sort", ".", "Slice", "(", "strs", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "str1", ":=", "strs", "[", "i", "]", "\n", "str2", ":=", "strs", "[", "j", "]", "\n", "matched1", ":=", "replaceIdxRegexp", ".", "FindAllStringIndex", "(", "str1", ",", "-", "1", ")", "\n", "matched2", ":=", "replaceIdxRegexp", ".", "FindAllStringIndex", "(", "str2", ",", "-", "1", ")", "\n", "for", "x", ":=", "0", ";", "x", "<", "len", "(", "matched1", ")", ";", "x", "++", "{", "prefix1", ":=", "str1", "[", ":", "matched1", "[", "x", "]", "[", "0", "]", "]", "\n", "prefix2", ":=", "str2", "\n", "if", "len", "(", "matched2", ")", ">=", "x", "+", "1", "{", "prefix2", "=", "str2", "[", ":", "matched2", "[", "x", "]", "[", "0", "]", "]", "\n", "}", "\n", "if", "prefix1", "!=", "prefix2", "{", "return", "strings", ".", "Compare", "(", "prefix1", ",", "prefix2", ")", "<", "0", "\n", "}", "\n", "if", "len", "(", "matched2", ")", "<", "x", "+", "1", "{", "return", "false", "\n", "}", "\n", "number1", ":=", "str1", "[", "matched1", "[", "x", "]", "[", "0", "]", ":", "matched1", "[", "x", "]", "[", "1", "]", "]", "\n", "number2", ":=", "str2", "[", "matched2", "[", "x", "]", "[", "0", "]", ":", "matched2", "[", "x", "]", "[", "1", "]", "]", "\n", "if", "number1", "!=", "number2", "{", "if", "len", "(", "number1", ")", "!=", "len", "(", "number2", ")", "{", "return", "len", "(", "number1", ")", "<", "len", "(", "number2", ")", "\n", "}", "\n", "return", "strings", ".", "Compare", "(", "number1", ",", "number2", ")", "<", "0", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Compare", "(", "str1", ",", "str2", ")", "<", "0", "\n", "}", ")", "\n", "}" ]
// SortFormKeys sort form keys
[ "SortFormKeys", "sort", "form", "keys" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L308-L344
train
qor/qor
utils/utils.go
Indirect
func Indirect(v reflect.Value) reflect.Value { for v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } return v }
go
func Indirect(v reflect.Value) reflect.Value { for v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } return v }
[ "func", "Indirect", "(", "v", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "for", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "reflect", ".", "Indirect", "(", "v", ")", "\n", "}", "\n", "return", "v", "\n", "}" ]
// Indirect returns last value that v points to
[ "Indirect", "returns", "last", "value", "that", "v", "points", "to" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L364-L369
train
qor/qor
utils/utils.go
SliceUniq
func SliceUniq(s []string) []string { for i := 0; i < len(s); i++ { for i2 := i + 1; i2 < len(s); i2++ { if s[i] == s[i2] { // delete s = append(s[:i2], s[i2+1:]...) i2-- } } } return s }
go
func SliceUniq(s []string) []string { for i := 0; i < len(s); i++ { for i2 := i + 1; i2 < len(s); i2++ { if s[i] == s[i2] { // delete s = append(s[:i2], s[i2+1:]...) i2-- } } } return s }
[ "func", "SliceUniq", "(", "s", "[", "]", "string", ")", "[", "]", "string", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "for", "i2", ":=", "i", "+", "1", ";", "i2", "<", "len", "(", "s", ")", ";", "i2", "++", "{", "if", "s", "[", "i", "]", "==", "s", "[", "i2", "]", "{", "s", "=", "append", "(", "s", "[", ":", "i2", "]", ",", "s", "[", "i2", "+", "1", ":", "]", "...", ")", "\n", "i2", "--", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "s", "\n", "}" ]
// SliceUniq removes duplicate values in given slice
[ "SliceUniq", "removes", "duplicate", "values", "in", "given", "slice" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/utils.go#L372-L383
train
qor/qor
utils/meta.go
NewValue
func NewValue(t reflect.Type) (v reflect.Value) { v = reflect.New(t) ov := v for t.Kind() == reflect.Ptr { v = v.Elem() t = t.Elem() e := reflect.New(t) v.Set(e) } if e := v.Elem(); e.Kind() == reflect.Map && e.IsNil() { v.Elem().Set(reflect.MakeMap(v.Elem().Type())) } return ov }
go
func NewValue(t reflect.Type) (v reflect.Value) { v = reflect.New(t) ov := v for t.Kind() == reflect.Ptr { v = v.Elem() t = t.Elem() e := reflect.New(t) v.Set(e) } if e := v.Elem(); e.Kind() == reflect.Map && e.IsNil() { v.Elem().Set(reflect.MakeMap(v.Elem().Type())) } return ov }
[ "func", "NewValue", "(", "t", "reflect", ".", "Type", ")", "(", "v", "reflect", ".", "Value", ")", "{", "v", "=", "reflect", ".", "New", "(", "t", ")", "\n", "ov", ":=", "v", "\n", "for", "t", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "t", "=", "t", ".", "Elem", "(", ")", "\n", "e", ":=", "reflect", ".", "New", "(", "t", ")", "\n", "v", ".", "Set", "(", "e", ")", "\n", "}", "\n", "if", "e", ":=", "v", ".", "Elem", "(", ")", ";", "e", ".", "Kind", "(", ")", "==", "reflect", ".", "Map", "&&", "e", ".", "IsNil", "(", ")", "{", "v", ".", "Elem", "(", ")", ".", "Set", "(", "reflect", ".", "MakeMap", "(", "v", ".", "Elem", "(", ")", ".", "Type", "(", ")", ")", ")", "\n", "}", "\n", "return", "ov", "\n", "}" ]
// NewValue new struct value with reflect type
[ "NewValue", "new", "struct", "value", "with", "reflect", "type" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/meta.go#L10-L24
train
qor/qor
utils/meta.go
ToArray
func ToArray(value interface{}) (values []string) { switch value := value.(type) { case []string: values = []string{} for _, v := range value { if v != "" { values = append(values, v) } } case []interface{}: for _, v := range value { values = append(values, fmt.Sprint(v)) } default: if value := fmt.Sprint(value); value != "" { values = []string{value} } } return }
go
func ToArray(value interface{}) (values []string) { switch value := value.(type) { case []string: values = []string{} for _, v := range value { if v != "" { values = append(values, v) } } case []interface{}: for _, v := range value { values = append(values, fmt.Sprint(v)) } default: if value := fmt.Sprint(value); value != "" { values = []string{value} } } return }
[ "func", "ToArray", "(", "value", "interface", "{", "}", ")", "(", "values", "[", "]", "string", ")", "{", "switch", "value", ":=", "value", ".", "(", "type", ")", "{", "case", "[", "]", "string", ":", "values", "=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "v", ":=", "range", "value", "{", "if", "v", "!=", "\"\"", "{", "values", "=", "append", "(", "values", ",", "v", ")", "\n", "}", "\n", "}", "\n", "case", "[", "]", "interface", "{", "}", ":", "for", "_", ",", "v", ":=", "range", "value", "{", "values", "=", "append", "(", "values", ",", "fmt", ".", "Sprint", "(", "v", ")", ")", "\n", "}", "\n", "default", ":", "if", "value", ":=", "fmt", ".", "Sprint", "(", "value", ")", ";", "value", "!=", "\"\"", "{", "values", "=", "[", "]", "string", "{", "value", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ToArray get array from value, will ignore blank string to convert it to array
[ "ToArray", "get", "array", "from", "value", "will", "ignore", "blank", "string", "to", "convert", "it", "to", "array" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/meta.go#L27-L46
train
qor/qor
utils/meta.go
ToString
func ToString(value interface{}) string { if v, ok := value.([]string); ok { for _, s := range v { if s != "" { return s } } return "" } else if v, ok := value.(string); ok { return v } else if v, ok := value.([]interface{}); ok { for _, s := range v { if fmt.Sprint(s) != "" { return fmt.Sprint(s) } } return "" } return fmt.Sprintf("%v", value) }
go
func ToString(value interface{}) string { if v, ok := value.([]string); ok { for _, s := range v { if s != "" { return s } } return "" } else if v, ok := value.(string); ok { return v } else if v, ok := value.([]interface{}); ok { for _, s := range v { if fmt.Sprint(s) != "" { return fmt.Sprint(s) } } return "" } return fmt.Sprintf("%v", value) }
[ "func", "ToString", "(", "value", "interface", "{", "}", ")", "string", "{", "if", "v", ",", "ok", ":=", "value", ".", "(", "[", "]", "string", ")", ";", "ok", "{", "for", "_", ",", "s", ":=", "range", "v", "{", "if", "s", "!=", "\"\"", "{", "return", "s", "\n", "}", "\n", "}", "\n", "return", "\"\"", "\n", "}", "else", "if", "v", ",", "ok", ":=", "value", ".", "(", "string", ")", ";", "ok", "{", "return", "v", "\n", "}", "else", "if", "v", ",", "ok", ":=", "value", ".", "(", "[", "]", "interface", "{", "}", ")", ";", "ok", "{", "for", "_", ",", "s", ":=", "range", "v", "{", "if", "fmt", ".", "Sprint", "(", "s", ")", "!=", "\"\"", "{", "return", "fmt", ".", "Sprint", "(", "s", ")", "\n", "}", "\n", "}", "\n", "return", "\"\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "value", ")", "\n", "}" ]
// ToString get string from value, if passed value is a slice, will use the first element
[ "ToString", "get", "string", "from", "value", "if", "passed", "value", "is", "a", "slice", "will", "use", "the", "first", "element" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/meta.go#L49-L68
train
qor/qor
utils/meta.go
ToInt
func ToInt(value interface{}) int64 { if result := ToString(value); result == "" { return 0 } else if i, err := strconv.ParseInt(result, 10, 64); err == nil { return i } else { panic("failed to parse int: " + result) } }
go
func ToInt(value interface{}) int64 { if result := ToString(value); result == "" { return 0 } else if i, err := strconv.ParseInt(result, 10, 64); err == nil { return i } else { panic("failed to parse int: " + result) } }
[ "func", "ToInt", "(", "value", "interface", "{", "}", ")", "int64", "{", "if", "result", ":=", "ToString", "(", "value", ")", ";", "result", "==", "\"\"", "{", "return", "0", "\n", "}", "else", "if", "i", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "result", ",", "10", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "i", "\n", "}", "else", "{", "panic", "(", "\"failed to parse int: \"", "+", "result", ")", "\n", "}", "\n", "}" ]
// ToInt get int from value, if passed value is empty string, result will be 0
[ "ToInt", "get", "int", "from", "value", "if", "passed", "value", "is", "empty", "string", "result", "will", "be", "0" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/meta.go#L71-L79
train
qor/qor
utils/meta.go
ToUint
func ToUint(value interface{}) uint64 { if result := ToString(value); result == "" { return 0 } else if i, err := strconv.ParseUint(result, 10, 64); err == nil { return i } else { panic("failed to parse uint: " + result) } }
go
func ToUint(value interface{}) uint64 { if result := ToString(value); result == "" { return 0 } else if i, err := strconv.ParseUint(result, 10, 64); err == nil { return i } else { panic("failed to parse uint: " + result) } }
[ "func", "ToUint", "(", "value", "interface", "{", "}", ")", "uint64", "{", "if", "result", ":=", "ToString", "(", "value", ")", ";", "result", "==", "\"\"", "{", "return", "0", "\n", "}", "else", "if", "i", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "result", ",", "10", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "i", "\n", "}", "else", "{", "panic", "(", "\"failed to parse uint: \"", "+", "result", ")", "\n", "}", "\n", "}" ]
// ToUint get uint from value, if passed value is empty string, result will be 0
[ "ToUint", "get", "uint", "from", "value", "if", "passed", "value", "is", "empty", "string", "result", "will", "be", "0" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/meta.go#L82-L90
train
qor/qor
utils/meta.go
ToFloat
func ToFloat(value interface{}) float64 { if result := ToString(value); result == "" { return 0 } else if i, err := strconv.ParseFloat(result, 64); err == nil { return i } else { panic("failed to parse float: " + result) } }
go
func ToFloat(value interface{}) float64 { if result := ToString(value); result == "" { return 0 } else if i, err := strconv.ParseFloat(result, 64); err == nil { return i } else { panic("failed to parse float: " + result) } }
[ "func", "ToFloat", "(", "value", "interface", "{", "}", ")", "float64", "{", "if", "result", ":=", "ToString", "(", "value", ")", ";", "result", "==", "\"\"", "{", "return", "0", "\n", "}", "else", "if", "i", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "result", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "i", "\n", "}", "else", "{", "panic", "(", "\"failed to parse float: \"", "+", "result", ")", "\n", "}", "\n", "}" ]
// ToFloat get float from value, if passed value is empty string, result will be 0
[ "ToFloat", "get", "float", "from", "value", "if", "passed", "value", "is", "empty", "string", "result", "will", "be", "0" ]
186b0237364b23ebbe564d0764c5b8523c953575
https://github.com/qor/qor/blob/186b0237364b23ebbe564d0764c5b8523c953575/utils/meta.go#L93-L101
train
hashicorp/golang-lru
arc.go
NewARC
func NewARC(size int) (*ARCCache, error) { // Create the sub LRUs b1, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } b2, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } t1, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } t2, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } // Initialize the ARC c := &ARCCache{ size: size, p: 0, t1: t1, b1: b1, t2: t2, b2: b2, } return c, nil }
go
func NewARC(size int) (*ARCCache, error) { // Create the sub LRUs b1, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } b2, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } t1, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } t2, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } // Initialize the ARC c := &ARCCache{ size: size, p: 0, t1: t1, b1: b1, t2: t2, b2: b2, } return c, nil }
[ "func", "NewARC", "(", "size", "int", ")", "(", "*", "ARCCache", ",", "error", ")", "{", "b1", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b2", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "t1", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "t2", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ":=", "&", "ARCCache", "{", "size", ":", "size", ",", "p", ":", "0", ",", "t1", ":", "t1", ",", "b1", ":", "b1", ",", "t2", ":", "t2", ",", "b2", ":", "b2", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewARC creates an ARC of the given size
[ "NewARC", "creates", "an", "ARC", "of", "the", "given", "size" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/arc.go#L31-L60
train
hashicorp/golang-lru
arc.go
replace
func (c *ARCCache) replace(b2ContainsKey bool) { t1Len := c.t1.Len() if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) { k, _, ok := c.t1.RemoveOldest() if ok { c.b1.Add(k, nil) } } else { k, _, ok := c.t2.RemoveOldest() if ok { c.b2.Add(k, nil) } } }
go
func (c *ARCCache) replace(b2ContainsKey bool) { t1Len := c.t1.Len() if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) { k, _, ok := c.t1.RemoveOldest() if ok { c.b1.Add(k, nil) } } else { k, _, ok := c.t2.RemoveOldest() if ok { c.b2.Add(k, nil) } } }
[ "func", "(", "c", "*", "ARCCache", ")", "replace", "(", "b2ContainsKey", "bool", ")", "{", "t1Len", ":=", "c", ".", "t1", ".", "Len", "(", ")", "\n", "if", "t1Len", ">", "0", "&&", "(", "t1Len", ">", "c", ".", "p", "||", "(", "t1Len", "==", "c", ".", "p", "&&", "b2ContainsKey", ")", ")", "{", "k", ",", "_", ",", "ok", ":=", "c", ".", "t1", ".", "RemoveOldest", "(", ")", "\n", "if", "ok", "{", "c", ".", "b1", ".", "Add", "(", "k", ",", "nil", ")", "\n", "}", "\n", "}", "else", "{", "k", ",", "_", ",", "ok", ":=", "c", ".", "t2", ".", "RemoveOldest", "(", ")", "\n", "if", "ok", "{", "c", ".", "b2", ".", "Add", "(", "k", ",", "nil", ")", "\n", "}", "\n", "}", "\n", "}" ]
// replace is used to adaptively evict from either T1 or T2 // based on the current learned value of P
[ "replace", "is", "used", "to", "adaptively", "evict", "from", "either", "T1", "or", "T2", "based", "on", "the", "current", "learned", "value", "of", "P" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/arc.go#L181-L194
train
hashicorp/golang-lru
arc.go
Len
func (c *ARCCache) Len() int { c.lock.RLock() defer c.lock.RUnlock() return c.t1.Len() + c.t2.Len() }
go
func (c *ARCCache) Len() int { c.lock.RLock() defer c.lock.RUnlock() return c.t1.Len() + c.t2.Len() }
[ "func", "(", "c", "*", "ARCCache", ")", "Len", "(", ")", "int", "{", "c", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "t1", ".", "Len", "(", ")", "+", "c", ".", "t2", ".", "Len", "(", ")", "\n", "}" ]
// Len returns the number of cached entries
[ "Len", "returns", "the", "number", "of", "cached", "entries" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/arc.go#L197-L201
train
hashicorp/golang-lru
arc.go
Keys
func (c *ARCCache) Keys() []interface{} { c.lock.RLock() defer c.lock.RUnlock() k1 := c.t1.Keys() k2 := c.t2.Keys() return append(k1, k2...) }
go
func (c *ARCCache) Keys() []interface{} { c.lock.RLock() defer c.lock.RUnlock() k1 := c.t1.Keys() k2 := c.t2.Keys() return append(k1, k2...) }
[ "func", "(", "c", "*", "ARCCache", ")", "Keys", "(", ")", "[", "]", "interface", "{", "}", "{", "c", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "RUnlock", "(", ")", "\n", "k1", ":=", "c", ".", "t1", ".", "Keys", "(", ")", "\n", "k2", ":=", "c", ".", "t2", ".", "Keys", "(", ")", "\n", "return", "append", "(", "k1", ",", "k2", "...", ")", "\n", "}" ]
// Keys returns all the cached keys
[ "Keys", "returns", "all", "the", "cached", "keys" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/arc.go#L204-L210
train
hashicorp/golang-lru
arc.go
Remove
func (c *ARCCache) Remove(key interface{}) { c.lock.Lock() defer c.lock.Unlock() if c.t1.Remove(key) { return } if c.t2.Remove(key) { return } if c.b1.Remove(key) { return } if c.b2.Remove(key) { return } }
go
func (c *ARCCache) Remove(key interface{}) { c.lock.Lock() defer c.lock.Unlock() if c.t1.Remove(key) { return } if c.t2.Remove(key) { return } if c.b1.Remove(key) { return } if c.b2.Remove(key) { return } }
[ "func", "(", "c", "*", "ARCCache", ")", "Remove", "(", "key", "interface", "{", "}", ")", "{", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "c", ".", "t1", ".", "Remove", "(", "key", ")", "{", "return", "\n", "}", "\n", "if", "c", ".", "t2", ".", "Remove", "(", "key", ")", "{", "return", "\n", "}", "\n", "if", "c", ".", "b1", ".", "Remove", "(", "key", ")", "{", "return", "\n", "}", "\n", "if", "c", ".", "b2", ".", "Remove", "(", "key", ")", "{", "return", "\n", "}", "\n", "}" ]
// Remove is used to purge a key from the cache
[ "Remove", "is", "used", "to", "purge", "a", "key", "from", "the", "cache" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/arc.go#L213-L228
train
hashicorp/golang-lru
2q.go
New2QParams
func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) { if size <= 0 { return nil, fmt.Errorf("invalid size") } if recentRatio < 0.0 || recentRatio > 1.0 { return nil, fmt.Errorf("invalid recent ratio") } if ghostRatio < 0.0 || ghostRatio > 1.0 { return nil, fmt.Errorf("invalid ghost ratio") } // Determine the sub-sizes recentSize := int(float64(size) * recentRatio) evictSize := int(float64(size) * ghostRatio) // Allocate the LRUs recent, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } frequent, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } recentEvict, err := simplelru.NewLRU(evictSize, nil) if err != nil { return nil, err } // Initialize the cache c := &TwoQueueCache{ size: size, recentSize: recentSize, recent: recent, frequent: frequent, recentEvict: recentEvict, } return c, nil }
go
func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) { if size <= 0 { return nil, fmt.Errorf("invalid size") } if recentRatio < 0.0 || recentRatio > 1.0 { return nil, fmt.Errorf("invalid recent ratio") } if ghostRatio < 0.0 || ghostRatio > 1.0 { return nil, fmt.Errorf("invalid ghost ratio") } // Determine the sub-sizes recentSize := int(float64(size) * recentRatio) evictSize := int(float64(size) * ghostRatio) // Allocate the LRUs recent, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } frequent, err := simplelru.NewLRU(size, nil) if err != nil { return nil, err } recentEvict, err := simplelru.NewLRU(evictSize, nil) if err != nil { return nil, err } // Initialize the cache c := &TwoQueueCache{ size: size, recentSize: recentSize, recent: recent, frequent: frequent, recentEvict: recentEvict, } return c, nil }
[ "func", "New2QParams", "(", "size", "int", ",", "recentRatio", "float64", ",", "ghostRatio", "float64", ")", "(", "*", "TwoQueueCache", ",", "error", ")", "{", "if", "size", "<=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid size\"", ")", "\n", "}", "\n", "if", "recentRatio", "<", "0.0", "||", "recentRatio", ">", "1.0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid recent ratio\"", ")", "\n", "}", "\n", "if", "ghostRatio", "<", "0.0", "||", "ghostRatio", ">", "1.0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid ghost ratio\"", ")", "\n", "}", "\n", "recentSize", ":=", "int", "(", "float64", "(", "size", ")", "*", "recentRatio", ")", "\n", "evictSize", ":=", "int", "(", "float64", "(", "size", ")", "*", "ghostRatio", ")", "\n", "recent", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "frequent", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "recentEvict", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "evictSize", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ":=", "&", "TwoQueueCache", "{", "size", ":", "size", ",", "recentSize", ":", "recentSize", ",", "recent", ":", "recent", ",", "frequent", ":", "frequent", ",", "recentEvict", ":", "recentEvict", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// New2QParams creates a new TwoQueueCache using the provided // parameter values.
[ "New2QParams", "creates", "a", "new", "TwoQueueCache", "using", "the", "provided", "parameter", "values", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/2q.go#L47-L85
train
hashicorp/golang-lru
2q.go
ensureSpace
func (c *TwoQueueCache) ensureSpace(recentEvict bool) { // If we have space, nothing to do recentLen := c.recent.Len() freqLen := c.frequent.Len() if recentLen+freqLen < c.size { return } // If the recent buffer is larger than // the target, evict from there if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) { k, _, _ := c.recent.RemoveOldest() c.recentEvict.Add(k, nil) return } // Remove from the frequent list otherwise c.frequent.RemoveOldest() }
go
func (c *TwoQueueCache) ensureSpace(recentEvict bool) { // If we have space, nothing to do recentLen := c.recent.Len() freqLen := c.frequent.Len() if recentLen+freqLen < c.size { return } // If the recent buffer is larger than // the target, evict from there if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) { k, _, _ := c.recent.RemoveOldest() c.recentEvict.Add(k, nil) return } // Remove from the frequent list otherwise c.frequent.RemoveOldest() }
[ "func", "(", "c", "*", "TwoQueueCache", ")", "ensureSpace", "(", "recentEvict", "bool", ")", "{", "recentLen", ":=", "c", ".", "recent", ".", "Len", "(", ")", "\n", "freqLen", ":=", "c", ".", "frequent", ".", "Len", "(", ")", "\n", "if", "recentLen", "+", "freqLen", "<", "c", ".", "size", "{", "return", "\n", "}", "\n", "if", "recentLen", ">", "0", "&&", "(", "recentLen", ">", "c", ".", "recentSize", "||", "(", "recentLen", "==", "c", ".", "recentSize", "&&", "!", "recentEvict", ")", ")", "{", "k", ",", "_", ",", "_", ":=", "c", ".", "recent", ".", "RemoveOldest", "(", ")", "\n", "c", ".", "recentEvict", ".", "Add", "(", "k", ",", "nil", ")", "\n", "return", "\n", "}", "\n", "c", ".", "frequent", ".", "RemoveOldest", "(", ")", "\n", "}" ]
// ensureSpace is used to ensure we have space in the cache
[ "ensureSpace", "is", "used", "to", "ensure", "we", "have", "space", "in", "the", "cache" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/2q.go#L145-L163
train
hashicorp/golang-lru
2q.go
Keys
func (c *TwoQueueCache) Keys() []interface{} { c.lock.RLock() defer c.lock.RUnlock() k1 := c.frequent.Keys() k2 := c.recent.Keys() return append(k1, k2...) }
go
func (c *TwoQueueCache) Keys() []interface{} { c.lock.RLock() defer c.lock.RUnlock() k1 := c.frequent.Keys() k2 := c.recent.Keys() return append(k1, k2...) }
[ "func", "(", "c", "*", "TwoQueueCache", ")", "Keys", "(", ")", "[", "]", "interface", "{", "}", "{", "c", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "RUnlock", "(", ")", "\n", "k1", ":=", "c", ".", "frequent", ".", "Keys", "(", ")", "\n", "k2", ":=", "c", ".", "recent", ".", "Keys", "(", ")", "\n", "return", "append", "(", "k1", ",", "k2", "...", ")", "\n", "}" ]
// Keys returns a slice of the keys in the cache. // The frequently used keys are first in the returned slice.
[ "Keys", "returns", "a", "slice", "of", "the", "keys", "in", "the", "cache", ".", "The", "frequently", "used", "keys", "are", "first", "in", "the", "returned", "slice", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/2q.go#L174-L180
train