repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
minio/mc | cmd/config-old.go | newConfigV6 | func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = "6"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV6)
return conf
} | go | func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = "6"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV6)
return conf
} | [
"func",
"newConfigV6",
"(",
")",
"*",
"configV6",
"{",
"conf",
":=",
"new",
"(",
"configV6",
")",
"\n",
"conf",
".",
"Version",
"=",
"\"6\"",
"\n",
"conf",
".",
"Aliases",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"conf",
".... | // newConfigV6 - new config version '6'. | [
"newConfigV6",
"-",
"new",
"config",
"version",
"6",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-old.go#L155-L161 | train |
minio/mc | cmd/config-old.go | newConfigV7 | func newConfigV7() *configV7 {
cfg := new(configV7)
cfg.Version = "7"
cfg.Hosts = make(map[string]hostConfigV7)
return cfg
} | go | func newConfigV7() *configV7 {
cfg := new(configV7)
cfg.Version = "7"
cfg.Hosts = make(map[string]hostConfigV7)
return cfg
} | [
"func",
"newConfigV7",
"(",
")",
"*",
"configV7",
"{",
"cfg",
":=",
"new",
"(",
"configV7",
")",
"\n",
"cfg",
".",
"Version",
"=",
"\"7\"",
"\n",
"cfg",
".",
"Hosts",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"hostConfigV7",
")",
"\n",
"return",
... | // newConfigV7 - new config version '7'. | [
"newConfigV7",
"-",
"new",
"config",
"version",
"7",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-old.go#L179-L184 | train |
minio/mc | cmd/config-old.go | newConfigV8 | func newConfigV8() *configV8 {
cfg := new(configV8)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV8)
return cfg
} | go | func newConfigV8() *configV8 {
cfg := new(configV8)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV8)
return cfg
} | [
"func",
"newConfigV8",
"(",
")",
"*",
"configV8",
"{",
"cfg",
":=",
"new",
"(",
"configV8",
")",
"\n",
"cfg",
".",
"Version",
"=",
"globalMCConfigVersion",
"\n",
"cfg",
".",
"Hosts",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"hostConfigV8",
")",
"\n... | // newConfigV8 - new config version. | [
"newConfigV8",
"-",
"new",
"config",
"version",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-old.go#L258-L263 | train |
minio/mc | cmd/config-host-remove.go | checkConfigHostRemoveSyntax | func checkConfigHostRemoveSyntax(ctx *cli.Context) {
args := ctx.Args()
if len(ctx.Args()) != 1 {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments for remove host command.")
}
if !isValidAlias(args.Get(0)) {
fatalIf(errDummy().Trace(args.Get(0)),
"Invalid alias `"+args.Get(0)+"`.")
}
} | go | func checkConfigHostRemoveSyntax(ctx *cli.Context) {
args := ctx.Args()
if len(ctx.Args()) != 1 {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments for remove host command.")
}
if !isValidAlias(args.Get(0)) {
fatalIf(errDummy().Trace(args.Get(0)),
"Invalid alias `"+args.Get(0)+"`.")
}
} | [
"func",
"checkConfigHostRemoveSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"1",
"{",
"fatalIf",
"(",
"errInvalidArgument",
"(",... | // checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'. | [
"checkConfigHostRemoveSyntax",
"-",
"verifies",
"input",
"arguments",
"to",
"config",
"host",
"remove",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-remove.go#L50-L62 | train |
minio/mc | cmd/config-host-remove.go | mainConfigHostRemove | func mainConfigHostRemove(ctx *cli.Context) error {
checkConfigHostRemoveSyntax(ctx)
console.SetColor("HostMessage", color.New(color.FgGreen))
args := ctx.Args()
alias := args.Get(0)
removeHost(alias) // Remove a host.
return nil
} | go | func mainConfigHostRemove(ctx *cli.Context) error {
checkConfigHostRemoveSyntax(ctx)
console.SetColor("HostMessage", color.New(color.FgGreen))
args := ctx.Args()
alias := args.Get(0)
removeHost(alias) // Remove a host.
return nil
} | [
"func",
"mainConfigHostRemove",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkConfigHostRemoveSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"HostMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
... | // mainConfigHost is the handle for "mc config host rm" command. | [
"mainConfigHost",
"is",
"the",
"handle",
"for",
"mc",
"config",
"host",
"rm",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-remove.go#L65-L74 | train |
minio/mc | cmd/config-host-remove.go | removeHost | func removeHost(alias string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// Remove host.
delete(conf.Hosts, alias)
err = saveMcConfig(conf)
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version `"+globalMCConfigVersion+"`.")
printMsg(hostMessage{op: "remove", Alias: alias})
} | go | func removeHost(alias string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// Remove host.
delete(conf.Hosts, alias)
err = saveMcConfig(conf)
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version `"+globalMCConfigVersion+"`.")
printMsg(hostMessage{op: "remove", Alias: alias})
} | [
"func",
"removeHost",
"(",
"alias",
"string",
")",
"{",
"conf",
",",
"err",
":=",
"loadMcConfig",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
"globalMCConfigVersion",
")",
",",
"\"Unable to load config version `\"",
"+",
"globalMCConfigVersion",
"+... | // removeHost - removes a host. | [
"removeHost",
"-",
"removes",
"a",
"host",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-remove.go#L77-L88 | train |
minio/mc | cmd/config-host.go | mainConfigHost | func mainConfigHost(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "remove", "list" have their own main.
} | go | func mainConfigHost(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "remove", "list" have their own main.
} | [
"func",
"mainConfigHost",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"cli",
".",
"ShowCommandHelp",
"(",
"ctx",
",",
"ctx",
".",
"Args",
"(",
")",
".",
"First",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // mainConfigHost is the handle for "mc config host" command. | [
"mainConfigHost",
"is",
"the",
"handle",
"for",
"mc",
"config",
"host",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host.go#L41-L45 | train |
minio/mc | cmd/config-host.go | String | func (h hostMessage) String() string {
switch h.op {
case "list":
// Create a new pretty table with cols configuration
t := newPrettyRecord(2,
Row{"Alias", "Alias"},
Row{"URL", "URL"},
Row{"AccessKey", "AccessKey"},
Row{"SecretKey", "SecretKey"},
Row{"API", "API"},
Row{"Lookup", "Lookup"},
)
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, h.Lookup)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
return console.Colorize("HostMessage", "Added `"+h.Alias+"` successfully.")
default:
return ""
}
} | go | func (h hostMessage) String() string {
switch h.op {
case "list":
// Create a new pretty table with cols configuration
t := newPrettyRecord(2,
Row{"Alias", "Alias"},
Row{"URL", "URL"},
Row{"AccessKey", "AccessKey"},
Row{"SecretKey", "SecretKey"},
Row{"API", "API"},
Row{"Lookup", "Lookup"},
)
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, h.Lookup)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
return console.Colorize("HostMessage", "Added `"+h.Alias+"` successfully.")
default:
return ""
}
} | [
"func",
"(",
"h",
"hostMessage",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"h",
".",
"op",
"{",
"case",
"\"list\"",
":",
"t",
":=",
"newPrettyRecord",
"(",
"2",
",",
"Row",
"{",
"\"Alias\"",
",",
"\"Alias\"",
"}",
",",
"Row",
"{",
"\"URL\"",
... | // Print the config information of one alias, when prettyPrint flag
// is activated, fields contents are cut and '...' will be added to
// show a pretty table of all aliases configurations | [
"Print",
"the",
"config",
"information",
"of",
"one",
"alias",
"when",
"prettyPrint",
"flag",
"is",
"activated",
"fields",
"contents",
"are",
"cut",
"and",
"...",
"will",
"be",
"added",
"to",
"show",
"a",
"pretty",
"table",
"of",
"all",
"aliases",
"configura... | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host.go#L63-L83 | train |
minio/mc | cmd/config-host.go | JSON | func (h hostMessage) JSON() string {
h.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(h, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
} | go | func (h hostMessage) JSON() string {
h.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(h, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
} | [
"func",
"(",
"h",
"hostMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"h",
".",
"Status",
"=",
"\"success\"",
"\n",
"jsonMessageBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"h",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"pr... | // JSON jsonified host message | [
"JSON",
"jsonified",
"host",
"message"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host.go#L86-L92 | train |
minio/mc | cmd/find.go | regexMatch | func regexMatch(pattern, path string) bool {
matched, e := regexp.MatchString(pattern, path)
errorIf(probe.NewError(e).Trace(pattern), "Unable to regex match with input pattern.")
return matched
} | go | func regexMatch(pattern, path string) bool {
matched, e := regexp.MatchString(pattern, path)
errorIf(probe.NewError(e).Trace(pattern), "Unable to regex match with input pattern.")
return matched
} | [
"func",
"regexMatch",
"(",
"pattern",
",",
"path",
"string",
")",
"bool",
"{",
"matched",
",",
"e",
":=",
"regexp",
".",
"MatchString",
"(",
"pattern",
",",
"path",
")",
"\n",
"errorIf",
"(",
"probe",
".",
"NewError",
"(",
"e",
")",
".",
"Trace",
"("... | // regexMatch reports whether path matches the regex pattern. | [
"regexMatch",
"reports",
"whether",
"path",
"matches",
"the",
"regex",
"pattern",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/find.go#L95-L99 | train |
minio/mc | cmd/find.go | execFind | func execFind(command string) {
commandArgs := strings.Split(command, " ")
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
console.Print(console.Colorize("FindExecErr", stderr.String()))
// Return exit status of the command run
os.Exit(getExitStatus(err))
}
console.PrintC(out.String())
} | go | func execFind(command string) {
commandArgs := strings.Split(command, " ")
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
console.Print(console.Colorize("FindExecErr", stderr.String()))
// Return exit status of the command run
os.Exit(getExitStatus(err))
}
console.PrintC(out.String())
} | [
"func",
"execFind",
"(",
"command",
"string",
")",
"{",
"commandArgs",
":=",
"strings",
".",
"Split",
"(",
"command",
",",
"\" \"",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"commandArgs",
"[",
"0",
"]",
",",
"commandArgs",
"[",
"1",
":",
... | // execFind executes the input command line, additionally formats input
// for the command line in accordance with subsititution arguments. | [
"execFind",
"executes",
"the",
"input",
"command",
"line",
"additionally",
"formats",
"input",
"for",
"the",
"command",
"line",
"in",
"accordance",
"with",
"subsititution",
"arguments",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/find.go#L115-L129 | train |
minio/mc | cmd/find.go | doFind | func doFind(ctx *findContext) error {
// If watch is enabled we will wait on the prefix perpetually
// for all I/O events until canceled by user, if watch is not enabled
// following defer is a no-op.
defer watchFind(ctx)
var prevKeyName string
// iterate over all content which is within the given directory
for content := range ctx.clnt.List(true, false, DirNone) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case BrokenSymlink:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list broken link.")
continue
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case PathNotFound:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
case PathInsufficientPermission:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
case ObjectOnGlacier:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "")
continue
}
fatalIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
}
fileKeyName := getAliasedPath(ctx, content.URL.String())
fileContent := contentMessage{
Key: fileKeyName,
Time: content.Time.Local(),
Size: content.Size,
}
// Match the incoming content, didn't match return.
if !matchFind(ctx, fileContent) || prevKeyName == fileKeyName {
continue
} // For all matching content
prevKeyName = fileKeyName
// proceed to either exec, format the output string.
if ctx.execCmd != "" {
execFind(stringsReplace(ctx.execCmd, fileContent))
continue
}
if ctx.printFmt != "" {
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
}
printMsg(findMessage{fileContent})
}
// Success, notice watch will execute in defer only if enabled and this call
// will return after watch is canceled.
return nil
} | go | func doFind(ctx *findContext) error {
// If watch is enabled we will wait on the prefix perpetually
// for all I/O events until canceled by user, if watch is not enabled
// following defer is a no-op.
defer watchFind(ctx)
var prevKeyName string
// iterate over all content which is within the given directory
for content := range ctx.clnt.List(true, false, DirNone) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case BrokenSymlink:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list broken link.")
continue
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case PathNotFound:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
case PathInsufficientPermission:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
case ObjectOnGlacier:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "")
continue
}
fatalIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
}
fileKeyName := getAliasedPath(ctx, content.URL.String())
fileContent := contentMessage{
Key: fileKeyName,
Time: content.Time.Local(),
Size: content.Size,
}
// Match the incoming content, didn't match return.
if !matchFind(ctx, fileContent) || prevKeyName == fileKeyName {
continue
} // For all matching content
prevKeyName = fileKeyName
// proceed to either exec, format the output string.
if ctx.execCmd != "" {
execFind(stringsReplace(ctx.execCmd, fileContent))
continue
}
if ctx.printFmt != "" {
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
}
printMsg(findMessage{fileContent})
}
// Success, notice watch will execute in defer only if enabled and this call
// will return after watch is canceled.
return nil
} | [
"func",
"doFind",
"(",
"ctx",
"*",
"findContext",
")",
"error",
"{",
"defer",
"watchFind",
"(",
"ctx",
")",
"\n",
"var",
"prevKeyName",
"string",
"\n",
"for",
"content",
":=",
"range",
"ctx",
".",
"clnt",
".",
"List",
"(",
"true",
",",
"false",
",",
... | // doFind - find is main function body which interprets and executes
// all the input parameters. | [
"doFind",
"-",
"find",
"is",
"main",
"function",
"body",
"which",
"interprets",
"and",
"executes",
"all",
"the",
"input",
"parameters",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/find.go#L244-L306 | train |
minio/mc | cmd/find.go | matchFind | func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
match = true
prefixPath := ctx.targetURL
// Add separator only if targetURL doesn't already have separator.
if !strings.HasPrefix(prefixPath, string(ctx.clnt.GetURL().Separator)) {
prefixPath = ctx.targetURL + string(ctx.clnt.GetURL().Separator)
}
// Trim the prefix such that we will apply file path matching techniques
// on path excluding the starting prefix.
path := strings.TrimPrefix(fileContent.Key, prefixPath)
if match && ctx.ignorePattern != "" {
match = !pathMatch(ctx.ignorePattern, path)
}
if match && ctx.namePattern != "" {
match = nameMatch(ctx.namePattern, path)
}
if match && ctx.pathPattern != "" {
match = pathMatch(ctx.pathPattern, path)
}
if match && ctx.regexPattern != "" {
match = regexMatch(ctx.regexPattern, path)
}
if match && ctx.olderThan != "" {
match = !isOlder(fileContent.Time, ctx.olderThan)
}
if match && ctx.newerThan != "" {
match = !isNewer(fileContent.Time, ctx.newerThan)
}
if match && ctx.largerSize > 0 {
match = int64(ctx.largerSize) < fileContent.Size
}
if match && ctx.smallerSize > 0 {
match = int64(ctx.smallerSize) > fileContent.Size
}
return match
} | go | func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
match = true
prefixPath := ctx.targetURL
// Add separator only if targetURL doesn't already have separator.
if !strings.HasPrefix(prefixPath, string(ctx.clnt.GetURL().Separator)) {
prefixPath = ctx.targetURL + string(ctx.clnt.GetURL().Separator)
}
// Trim the prefix such that we will apply file path matching techniques
// on path excluding the starting prefix.
path := strings.TrimPrefix(fileContent.Key, prefixPath)
if match && ctx.ignorePattern != "" {
match = !pathMatch(ctx.ignorePattern, path)
}
if match && ctx.namePattern != "" {
match = nameMatch(ctx.namePattern, path)
}
if match && ctx.pathPattern != "" {
match = pathMatch(ctx.pathPattern, path)
}
if match && ctx.regexPattern != "" {
match = regexMatch(ctx.regexPattern, path)
}
if match && ctx.olderThan != "" {
match = !isOlder(fileContent.Time, ctx.olderThan)
}
if match && ctx.newerThan != "" {
match = !isNewer(fileContent.Time, ctx.newerThan)
}
if match && ctx.largerSize > 0 {
match = int64(ctx.largerSize) < fileContent.Size
}
if match && ctx.smallerSize > 0 {
match = int64(ctx.smallerSize) > fileContent.Size
}
return match
} | [
"func",
"matchFind",
"(",
"ctx",
"*",
"findContext",
",",
"fileContent",
"contentMessage",
")",
"(",
"match",
"bool",
")",
"{",
"match",
"=",
"true",
"\n",
"prefixPath",
":=",
"ctx",
".",
"targetURL",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"p... | // matchFind matches whether fileContent matches appropriately with standard
// "pattern matching" flags requested by the user, such as "name", "path", "regex" ..etc. | [
"matchFind",
"matches",
"whether",
"fileContent",
"matches",
"appropriately",
"with",
"standard",
"pattern",
"matching",
"flags",
"requested",
"by",
"the",
"user",
"such",
"as",
"name",
"path",
"regex",
"..",
"etc",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/find.go#L377-L412 | train |
minio/mc | pkg/hookreader/hookreader.go | Read | func (hr *hookReader) Read(b []byte) (n int, err error) {
n, err = hr.source.Read(b)
if err != nil && err != io.EOF {
return n, err
}
// Progress the hook with the total read bytes from the source.
if _, herr := hr.hook.Read(b[:n]); herr != nil {
if herr != io.EOF {
return n, herr
}
}
return n, err
} | go | func (hr *hookReader) Read(b []byte) (n int, err error) {
n, err = hr.source.Read(b)
if err != nil && err != io.EOF {
return n, err
}
// Progress the hook with the total read bytes from the source.
if _, herr := hr.hook.Read(b[:n]); herr != nil {
if herr != io.EOF {
return n, herr
}
}
return n, err
} | [
"func",
"(",
"hr",
"*",
"hookReader",
")",
"Read",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"n",
",",
"err",
"=",
"hr",
".",
"source",
".",
"Read",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",... | // Read implements io.Reader. Always reads from the source, the return
// value 'n' number of bytes are reported through the hook. Returns
// error for all non io.EOF conditions. | [
"Read",
"implements",
"io",
".",
"Reader",
".",
"Always",
"reads",
"from",
"the",
"source",
"the",
"return",
"value",
"n",
"number",
"of",
"bytes",
"are",
"reported",
"through",
"the",
"hook",
".",
"Returns",
"error",
"for",
"all",
"non",
"io",
".",
"EOF... | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/hookreader/hookreader.go#L53-L65 | train |
minio/mc | pkg/hookreader/hookreader.go | NewHook | func NewHook(source, hook io.Reader) io.Reader {
if hook == nil {
return source
}
return &hookReader{source, hook}
} | go | func NewHook(source, hook io.Reader) io.Reader {
if hook == nil {
return source
}
return &hookReader{source, hook}
} | [
"func",
"NewHook",
"(",
"source",
",",
"hook",
"io",
".",
"Reader",
")",
"io",
".",
"Reader",
"{",
"if",
"hook",
"==",
"nil",
"{",
"return",
"source",
"\n",
"}",
"\n",
"return",
"&",
"hookReader",
"{",
"source",
",",
"hook",
"}",
"\n",
"}"
] | // NewHook returns a io.Reader which implements hookReader that
// reports the data read from the source to the hook. | [
"NewHook",
"returns",
"a",
"io",
".",
"Reader",
"which",
"implements",
"hookReader",
"that",
"reports",
"the",
"data",
"read",
"from",
"the",
"source",
"to",
"the",
"hook",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/hookreader/hookreader.go#L69-L74 | train |
minio/mc | cmd/admin-heal.go | JSON | func (s stopHealMessage) JSON() string {
stopHealJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(stopHealJSONBytes)
} | go | func (s stopHealMessage) JSON() string {
stopHealJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(stopHealJSONBytes)
} | [
"func",
"(",
"s",
"stopHealMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"stopHealJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"s",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"probe",
".",
"NewError",
"(",
"e",
")",
","... | // JSON jsonified stop heal message. | [
"JSON",
"jsonified",
"stop",
"heal",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-heal.go#L129-L134 | train |
minio/mc | cmd/admin-heal.go | mainAdminHeal | func mainAdminHeal(ctx *cli.Context) error {
// Check for command syntax
checkAdminHealSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
console.SetColor("HealStopped", color.New(color.FgGreen, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
splits := splitStr(aliasedURL, "/", 3)
bucket, prefix := splits[1], splits[2]
opts := madmin.HealOpts{
ScanMode: transformScanArg(ctx.String("scan")),
Remove: ctx.Bool("remove"),
Recursive: ctx.Bool("recursive"),
DryRun: ctx.Bool("dry-run"),
}
forceStart := ctx.Bool("force-start")
forceStop := ctx.Bool("force-stop")
if forceStop {
_, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, forceStop)
errorIf(probe.NewError(herr), "Failed to stop heal sequence.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, false)
errorIf(probe.NewError(herr), "Failed to start heal sequence.")
ui := uiData{
Bucket: bucket,
Prefix: prefix,
Client: client,
ClientToken: healStart.ClientToken,
ForceStart: forceStart,
HealOpts: &opts,
ObjectsByOnlineDrives: make(map[int]int64),
HealthCols: make(map[col]int64),
CurChan: cursorAnimate(),
}
res, e := ui.DisplayAndFollowHealStatus(aliasedURL)
if e != nil {
if res.FailureDetail != "" {
data, _ := json.MarshalIndent(res, "", " ")
traceStr := string(data)
errorIf(probe.NewError(e).Trace(aliasedURL, traceStr), "Unable to display heal status.")
} else {
errorIf(probe.NewError(e).Trace(aliasedURL), "Unable to display heal status.")
}
}
return nil
} | go | func mainAdminHeal(ctx *cli.Context) error {
// Check for command syntax
checkAdminHealSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
console.SetColor("HealStopped", color.New(color.FgGreen, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
splits := splitStr(aliasedURL, "/", 3)
bucket, prefix := splits[1], splits[2]
opts := madmin.HealOpts{
ScanMode: transformScanArg(ctx.String("scan")),
Remove: ctx.Bool("remove"),
Recursive: ctx.Bool("recursive"),
DryRun: ctx.Bool("dry-run"),
}
forceStart := ctx.Bool("force-start")
forceStop := ctx.Bool("force-stop")
if forceStop {
_, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, forceStop)
errorIf(probe.NewError(herr), "Failed to stop heal sequence.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, false)
errorIf(probe.NewError(herr), "Failed to start heal sequence.")
ui := uiData{
Bucket: bucket,
Prefix: prefix,
Client: client,
ClientToken: healStart.ClientToken,
ForceStart: forceStart,
HealOpts: &opts,
ObjectsByOnlineDrives: make(map[int]int64),
HealthCols: make(map[col]int64),
CurChan: cursorAnimate(),
}
res, e := ui.DisplayAndFollowHealStatus(aliasedURL)
if e != nil {
if res.FailureDetail != "" {
data, _ := json.MarshalIndent(res, "", " ")
traceStr := string(data)
errorIf(probe.NewError(e).Trace(aliasedURL, traceStr), "Unable to display heal status.")
} else {
errorIf(probe.NewError(e).Trace(aliasedURL), "Unable to display heal status.")
}
}
return nil
} | [
"func",
"mainAdminHeal",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminHealSyntax",
"(",
"ctx",
")",
"\n",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"aliasedURL",
":=",
"args",
".",
"Get",
"(",
"0",
")",
"\n",
"console... | // mainAdminHeal - the entry function of heal command | [
"mainAdminHeal",
"-",
"the",
"entry",
"function",
"of",
"heal",
"command"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-heal.go#L145-L212 | train |
minio/mc | cmd/diff-main.go | String | func (d diffMessage) String() string {
msg := ""
switch d.Diff {
case differInFirst:
msg = console.Colorize("DiffOnlyInFirst", "< "+d.FirstURL)
case differInSecond:
msg = console.Colorize("DiffOnlyInSecond", "> "+d.SecondURL)
case differInType:
msg = console.Colorize("DiffType", "! "+d.SecondURL)
case differInSize:
msg = console.Colorize("DiffSize", "! "+d.SecondURL)
case differInTime:
msg = console.Colorize("DiffTime", "! "+d.SecondURL)
default:
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
"Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.")
}
return msg
} | go | func (d diffMessage) String() string {
msg := ""
switch d.Diff {
case differInFirst:
msg = console.Colorize("DiffOnlyInFirst", "< "+d.FirstURL)
case differInSecond:
msg = console.Colorize("DiffOnlyInSecond", "> "+d.SecondURL)
case differInType:
msg = console.Colorize("DiffType", "! "+d.SecondURL)
case differInSize:
msg = console.Colorize("DiffSize", "! "+d.SecondURL)
case differInTime:
msg = console.Colorize("DiffTime", "! "+d.SecondURL)
default:
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
"Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.")
}
return msg
} | [
"func",
"(",
"d",
"diffMessage",
")",
"String",
"(",
")",
"string",
"{",
"msg",
":=",
"\"\"",
"\n",
"switch",
"d",
".",
"Diff",
"{",
"case",
"differInFirst",
":",
"msg",
"=",
"console",
".",
"Colorize",
"(",
"\"DiffOnlyInFirst\"",
",",
"\"< \"",
"+",
"... | // String colorized diff message | [
"String",
"colorized",
"diff",
"message"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/diff-main.go#L81-L100 | train |
minio/mc | cmd/diff-main.go | JSON | func (d diffMessage) JSON() string {
d.Status = "success"
diffJSONBytes, e := json.MarshalIndent(d, "", " ")
fatalIf(probe.NewError(e),
"Unable to marshal diff message `"+d.FirstURL+"`, `"+d.SecondURL+"` and `"+string(d.Diff)+"`.")
return string(diffJSONBytes)
} | go | func (d diffMessage) JSON() string {
d.Status = "success"
diffJSONBytes, e := json.MarshalIndent(d, "", " ")
fatalIf(probe.NewError(e),
"Unable to marshal diff message `"+d.FirstURL+"`, `"+d.SecondURL+"` and `"+string(d.Diff)+"`.")
return string(diffJSONBytes)
} | [
"func",
"(",
"d",
"diffMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"d",
".",
"Status",
"=",
"\"success\"",
"\n",
"diffJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"d",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"probe... | // JSON jsonified diff message | [
"JSON",
"jsonified",
"diff",
"message"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/diff-main.go#L103-L109 | train |
minio/mc | cmd/diff-main.go | doDiffMain | func doDiffMain(firstURL, secondURL string) error {
// Source and targets are always directories
sourceSeparator := string(newClientURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
}
targetSeparator := string(newClientURL(secondURL).Separator)
if !strings.HasSuffix(secondURL, targetSeparator) {
secondURL = secondURL + targetSeparator
}
// Expand aliased urls.
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
firstClient, err := newClientFromAlias(firstAlias, firstURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
secondClient, err := newClientFromAlias(secondAlias, secondURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
// Diff first and second urls.
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) {
if diffMsg.Error != nil {
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
// Ignore error and proceed to next object.
continue
}
printMsg(diffMsg)
}
return nil
} | go | func doDiffMain(firstURL, secondURL string) error {
// Source and targets are always directories
sourceSeparator := string(newClientURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
}
targetSeparator := string(newClientURL(secondURL).Separator)
if !strings.HasSuffix(secondURL, targetSeparator) {
secondURL = secondURL + targetSeparator
}
// Expand aliased urls.
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
firstClient, err := newClientFromAlias(firstAlias, firstURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
secondClient, err := newClientFromAlias(secondAlias, secondURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
// Diff first and second urls.
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) {
if diffMsg.Error != nil {
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
// Ignore error and proceed to next object.
continue
}
printMsg(diffMsg)
}
return nil
} | [
"func",
"doDiffMain",
"(",
"firstURL",
",",
"secondURL",
"string",
")",
"error",
"{",
"sourceSeparator",
":=",
"string",
"(",
"newClientURL",
"(",
"firstURL",
")",
".",
"Separator",
")",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"firstURL",
",",
"... | // doDiffMain runs the diff. | [
"doDiffMain",
"runs",
"the",
"diff",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/diff-main.go#L150-L188 | train |
minio/mc | cmd/diff-main.go | mainDiff | func mainDiff(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'diff' cli arguments.
checkDiffSyntax(ctx, encKeyDB)
// Additional command specific theme customization.
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed))
console.SetColor("DiffOnlyInSecond", color.New(color.FgGreen))
console.SetColor("DiffType", color.New(color.FgMagenta))
console.SetColor("DiffSize", color.New(color.FgYellow, color.Bold))
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
URLs := ctx.Args()
firstURL := URLs.Get(0)
secondURL := URLs.Get(1)
return doDiffMain(firstURL, secondURL)
} | go | func mainDiff(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'diff' cli arguments.
checkDiffSyntax(ctx, encKeyDB)
// Additional command specific theme customization.
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed))
console.SetColor("DiffOnlyInSecond", color.New(color.FgGreen))
console.SetColor("DiffType", color.New(color.FgMagenta))
console.SetColor("DiffSize", color.New(color.FgYellow, color.Bold))
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
URLs := ctx.Args()
firstURL := URLs.Get(0)
secondURL := URLs.Get(1)
return doDiffMain(firstURL, secondURL)
} | [
"func",
"mainDiff",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"checkDiffSyntax",
"(",
"ctx",
... | // mainDiff main for 'diff'. | [
"mainDiff",
"main",
"for",
"diff",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/diff-main.go#L191-L212 | train |
minio/mc | pkg/colorjson/decode.go | isValidNumber | func isValidNumber(s string) bool {
// This function implements the JSON numbers grammar.
// See https://tools.ietf.org/html/rfc7159#section-6
// and https://json.org/number.gif
if s == "" {
return false
}
// Optional -
if s[0] == '-' {
s = s[1:]
if s == "" {
return false
}
}
// Digits
switch {
default:
return false
case s[0] == '0':
s = s[1:]
case '1' <= s[0] && s[0] <= '9':
s = s[1:]
for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
s = s[1:]
}
}
// . followed by 1 or more digits.
if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' {
s = s[2:]
for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
s = s[1:]
}
}
// e or E followed by an optional - or + and
// 1 or more digits.
if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') {
s = s[1:]
if s[0] == '+' || s[0] == '-' {
s = s[1:]
if s == "" {
return false
}
}
for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
s = s[1:]
}
}
// Make sure we are at the end.
return s == ""
} | go | func isValidNumber(s string) bool {
// This function implements the JSON numbers grammar.
// See https://tools.ietf.org/html/rfc7159#section-6
// and https://json.org/number.gif
if s == "" {
return false
}
// Optional -
if s[0] == '-' {
s = s[1:]
if s == "" {
return false
}
}
// Digits
switch {
default:
return false
case s[0] == '0':
s = s[1:]
case '1' <= s[0] && s[0] <= '9':
s = s[1:]
for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
s = s[1:]
}
}
// . followed by 1 or more digits.
if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' {
s = s[2:]
for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
s = s[1:]
}
}
// e or E followed by an optional - or + and
// 1 or more digits.
if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') {
s = s[1:]
if s[0] == '+' || s[0] == '-' {
s = s[1:]
if s == "" {
return false
}
}
for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
s = s[1:]
}
}
// Make sure we are at the end.
return s == ""
} | [
"func",
"isValidNumber",
"(",
"s",
"string",
")",
"bool",
"{",
"if",
"s",
"==",
"\"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"s",
"[",
"0",
"]",
"==",
"'-'",
"{",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"\n",
"if",
"s",
"==",
"\"\"",
"... | // isValidNumber reports whether s is a valid JSON number literal. | [
"isValidNumber",
"reports",
"whether",
"s",
"is",
"a",
"valid",
"JSON",
"number",
"literal",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/decode.go#L216-L273 | train |
minio/mc | pkg/colorjson/decode.go | addErrorContext | func (d *decodeState) addErrorContext(err error) error {
if d.errorContext.Struct != "" || d.errorContext.Field != "" {
switch err := err.(type) {
case *UnmarshalTypeError:
err.Struct = d.errorContext.Struct
err.Field = d.errorContext.Field
return err
}
}
return err
} | go | func (d *decodeState) addErrorContext(err error) error {
if d.errorContext.Struct != "" || d.errorContext.Field != "" {
switch err := err.(type) {
case *UnmarshalTypeError:
err.Struct = d.errorContext.Struct
err.Field = d.errorContext.Field
return err
}
}
return err
} | [
"func",
"(",
"d",
"*",
"decodeState",
")",
"addErrorContext",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"d",
".",
"errorContext",
".",
"Struct",
"!=",
"\"\"",
"||",
"d",
".",
"errorContext",
".",
"Field",
"!=",
"\"\"",
"{",
"switch",
"err",
":=",
... | // addErrorContext returns a new error enhanced with information from d.errorContext | [
"addErrorContext",
"returns",
"a",
"new",
"error",
"enhanced",
"with",
"information",
"from",
"d",
".",
"errorContext"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/decode.go#L318-L328 | train |
minio/mc | pkg/colorjson/decode.go | skip | func (d *decodeState) skip() {
s, data, i := &d.scan, d.data, d.off
depth := len(s.parseState)
for {
op := s.step(s, data[i])
i++
if len(s.parseState) < depth {
d.off = i
d.opcode = op
return
}
}
} | go | func (d *decodeState) skip() {
s, data, i := &d.scan, d.data, d.off
depth := len(s.parseState)
for {
op := s.step(s, data[i])
i++
if len(s.parseState) < depth {
d.off = i
d.opcode = op
return
}
}
} | [
"func",
"(",
"d",
"*",
"decodeState",
")",
"skip",
"(",
")",
"{",
"s",
",",
"data",
",",
"i",
":=",
"&",
"d",
".",
"scan",
",",
"d",
".",
"data",
",",
"d",
".",
"off",
"\n",
"depth",
":=",
"len",
"(",
"s",
".",
"parseState",
")",
"\n",
"for... | // skip scans to the end of what was started. | [
"skip",
"scans",
"to",
"the",
"end",
"of",
"what",
"was",
"started",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/decode.go#L331-L343 | train |
minio/mc | cmd/pipe-main.go | checkPipeSyntax | func checkPipeSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "pipe", 1) // last argument is exit code.
}
} | go | func checkPipeSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "pipe", 1) // last argument is exit code.
}
} | [
"func",
"checkPipeSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"1",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"pipe\"",
",",
"1",
")",
"\n",
"}",
"\n",
"}... | // check pipe input arguments. | [
"check",
"pipe",
"input",
"arguments",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pipe-main.go#L95-L99 | train |
minio/mc | cmd/pipe-main.go | mainPipe | func mainPipe(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// validate pipe input arguments.
checkPipeSyntax(ctx)
if len(ctx.Args()) == 0 {
err = pipe("", nil)
fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.")
} else {
// extract URLs.
URLs := ctx.Args()
err = pipe(URLs[0], encKeyDB)
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
}
// Done.
return nil
} | go | func mainPipe(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// validate pipe input arguments.
checkPipeSyntax(ctx)
if len(ctx.Args()) == 0 {
err = pipe("", nil)
fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.")
} else {
// extract URLs.
URLs := ctx.Args()
err = pipe(URLs[0], encKeyDB)
fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.")
}
// Done.
return nil
} | [
"func",
"mainPipe",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"checkPipeSyntax",
"(",
"ctx",
... | // mainPipe is the main entry point for pipe command. | [
"mainPipe",
"is",
"the",
"main",
"entry",
"point",
"for",
"pipe",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pipe-main.go#L102-L122 | train |
minio/mc | cmd/certs.go | getCertsDir | func getCertsDir() (string, *probe.Error) {
p, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(p, globalMCCertsDir), nil
} | go | func getCertsDir() (string, *probe.Error) {
p, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(p, globalMCCertsDir), nil
} | [
"func",
"getCertsDir",
"(",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"p",
",",
"err",
":=",
"getMcConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
".",
"Trace",
"(",
")",
"\n",
"}",
... | // getCertsDir - return the full path of certs dir | [
"getCertsDir",
"-",
"return",
"the",
"full",
"path",
"of",
"certs",
"dir"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L29-L35 | train |
minio/mc | cmd/certs.go | isCertsDirExists | func isCertsDirExists() bool {
certsDir, err := getCertsDir()
fatalIf(err.Trace(), "Unable to determine certs folder.")
if _, e := os.Stat(certsDir); e != nil {
return false
}
return true
} | go | func isCertsDirExists() bool {
certsDir, err := getCertsDir()
fatalIf(err.Trace(), "Unable to determine certs folder.")
if _, e := os.Stat(certsDir); e != nil {
return false
}
return true
} | [
"func",
"isCertsDirExists",
"(",
")",
"bool",
"{",
"certsDir",
",",
"err",
":=",
"getCertsDir",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
")",
",",
"\"Unable to determine certs folder.\"",
")",
"\n",
"if",
"_",
",",
"e",
":=",
"os",
".",
... | // isCertsDirExists - verify if certs directory exists. | [
"isCertsDirExists",
"-",
"verify",
"if",
"certs",
"directory",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L38-L45 | train |
minio/mc | cmd/certs.go | createCertsDir | func createCertsDir() *probe.Error {
p, err := getCertsDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | go | func createCertsDir() *probe.Error {
p, err := getCertsDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"createCertsDir",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"p",
",",
"err",
":=",
"getCertsDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
".",
"Trace",
"(",
")",
"\n",
"}",
"\n",
"if",
"e",
":=",
"os",
".",
"Mkd... | // createCertsDir - create MinIO Client certs folder | [
"createCertsDir",
"-",
"create",
"MinIO",
"Client",
"certs",
"folder"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L48-L57 | train |
minio/mc | cmd/certs.go | getCAsDir | func getCAsDir() (string, *probe.Error) {
p, err := getCertsDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(p, globalMCCAsDir), nil
} | go | func getCAsDir() (string, *probe.Error) {
p, err := getCertsDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(p, globalMCCAsDir), nil
} | [
"func",
"getCAsDir",
"(",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"p",
",",
"err",
":=",
"getCertsDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
".",
"Trace",
"(",
")",
"\n",
"}",
"\n",... | // getCAsDir - return the full path of CAs dir | [
"getCAsDir",
"-",
"return",
"the",
"full",
"path",
"of",
"CAs",
"dir"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L60-L66 | train |
minio/mc | cmd/certs.go | isCAsDirExists | func isCAsDirExists() bool {
CAsDir, err := getCAsDir()
fatalIf(err.Trace(), "Unable to determine CAs folder.")
if _, e := os.Stat(CAsDir); e != nil {
return false
}
return true
} | go | func isCAsDirExists() bool {
CAsDir, err := getCAsDir()
fatalIf(err.Trace(), "Unable to determine CAs folder.")
if _, e := os.Stat(CAsDir); e != nil {
return false
}
return true
} | [
"func",
"isCAsDirExists",
"(",
")",
"bool",
"{",
"CAsDir",
",",
"err",
":=",
"getCAsDir",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
")",
",",
"\"Unable to determine CAs folder.\"",
")",
"\n",
"if",
"_",
",",
"e",
":=",
"os",
".",
"Stat"... | // isCAsDirExists - verify if CAs directory exists. | [
"isCAsDirExists",
"-",
"verify",
"if",
"CAs",
"directory",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L78-L85 | train |
minio/mc | cmd/certs.go | createCAsDir | func createCAsDir() *probe.Error {
p, err := getCAsDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | go | func createCAsDir() *probe.Error {
p, err := getCAsDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"createCAsDir",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"p",
",",
"err",
":=",
"getCAsDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
".",
"Trace",
"(",
")",
"\n",
"}",
"\n",
"if",
"e",
":=",
"os",
".",
"MkdirAl... | // createCAsDir - create MinIO Client CAs folder | [
"createCAsDir",
"-",
"create",
"MinIO",
"Client",
"CAs",
"folder"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L88-L97 | train |
minio/mc | cmd/certs.go | mustGetCAFiles | func mustGetCAFiles() (caCerts []string) {
CAsDir := mustGetCAsDir()
caFiles, _ := ioutil.ReadDir(CAsDir)
for _, cert := range caFiles {
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
}
return
} | go | func mustGetCAFiles() (caCerts []string) {
CAsDir := mustGetCAsDir()
caFiles, _ := ioutil.ReadDir(CAsDir)
for _, cert := range caFiles {
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
}
return
} | [
"func",
"mustGetCAFiles",
"(",
")",
"(",
"caCerts",
"[",
"]",
"string",
")",
"{",
"CAsDir",
":=",
"mustGetCAsDir",
"(",
")",
"\n",
"caFiles",
",",
"_",
":=",
"ioutil",
".",
"ReadDir",
"(",
"CAsDir",
")",
"\n",
"for",
"_",
",",
"cert",
":=",
"range",
... | // mustGetCAFiles - get the list of the CA certificates stored in MinIO config dir | [
"mustGetCAFiles",
"-",
"get",
"the",
"list",
"of",
"the",
"CA",
"certificates",
"stored",
"in",
"MinIO",
"config",
"dir"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L100-L107 | train |
minio/mc | cmd/certs.go | loadRootCAs | func loadRootCAs() {
caFiles := mustGetCAFiles()
if len(caFiles) == 0 {
return
}
// Get system cert pool, and empty cert pool under Windows because it is not supported
globalRootCAs = mustGetSystemCertPool()
// Load custom root CAs for client requests
for _, caFile := range caFiles {
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
fatalIf(probe.NewError(err), "Unable to load a CA file.")
}
globalRootCAs.AppendCertsFromPEM(caCert)
}
} | go | func loadRootCAs() {
caFiles := mustGetCAFiles()
if len(caFiles) == 0 {
return
}
// Get system cert pool, and empty cert pool under Windows because it is not supported
globalRootCAs = mustGetSystemCertPool()
// Load custom root CAs for client requests
for _, caFile := range caFiles {
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
fatalIf(probe.NewError(err), "Unable to load a CA file.")
}
globalRootCAs.AppendCertsFromPEM(caCert)
}
} | [
"func",
"loadRootCAs",
"(",
")",
"{",
"caFiles",
":=",
"mustGetCAFiles",
"(",
")",
"\n",
"if",
"len",
"(",
"caFiles",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"globalRootCAs",
"=",
"mustGetSystemCertPool",
"(",
")",
"\n",
"for",
"_",
",",
"caFil... | // loadRootCAs fetches CA files provided in MinIO config and adds them to globalRootCAs
// Currently under Windows, there is no way to load system + user CAs at the same time | [
"loadRootCAs",
"fetches",
"CA",
"files",
"provided",
"in",
"MinIO",
"config",
"and",
"adds",
"them",
"to",
"globalRootCAs",
"Currently",
"under",
"Windows",
"there",
"is",
"no",
"way",
"to",
"load",
"system",
"+",
"user",
"CAs",
"at",
"the",
"same",
"time"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L120-L135 | train |
minio/mc | pkg/httptracer/httptracer.go | CancelRequest | func (t RoundTripTrace) CancelRequest(req *http.Request) {
transport, ok := t.Transport.(*http.Transport)
if ok {
transport.CancelRequest(req)
}
} | go | func (t RoundTripTrace) CancelRequest(req *http.Request) {
transport, ok := t.Transport.(*http.Transport)
if ok {
transport.CancelRequest(req)
}
} | [
"func",
"(",
"t",
"RoundTripTrace",
")",
"CancelRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"transport",
",",
"ok",
":=",
"t",
".",
"Transport",
".",
"(",
"*",
"http",
".",
"Transport",
")",
"\n",
"if",
"ok",
"{",
"transport",
".",
... | // CancelRequest implements functinality to cancel an underlying request. | [
"CancelRequest",
"implements",
"functinality",
"to",
"cancel",
"an",
"underlying",
"request",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/httptracer/httptracer.go#L40-L45 | train |
minio/mc | pkg/httptracer/httptracer.go | RoundTrip | func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) {
timeStamp := time.Now()
if t.Transport == nil {
return nil, errors.New("Invalid Argument")
}
res, err = t.Transport.RoundTrip(req)
if err != nil {
return res, err
}
if t.Trace != nil {
err = t.Trace.Request(req)
if err != nil {
return nil, err
}
err = t.Trace.Response(res)
if err != nil {
return nil, err
}
console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n")
}
return res, err
} | go | func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) {
timeStamp := time.Now()
if t.Transport == nil {
return nil, errors.New("Invalid Argument")
}
res, err = t.Transport.RoundTrip(req)
if err != nil {
return res, err
}
if t.Trace != nil {
err = t.Trace.Request(req)
if err != nil {
return nil, err
}
err = t.Trace.Response(res)
if err != nil {
return nil, err
}
console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n")
}
return res, err
} | [
"func",
"(",
"t",
"RoundTripTrace",
")",
"RoundTrip",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"res",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"timeStamp",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"t",
".",
"T... | // RoundTrip executes user provided request and response hooks for each HTTP call. | [
"RoundTrip",
"executes",
"user",
"provided",
"request",
"and",
"response",
"hooks",
"for",
"each",
"HTTP",
"call",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/httptracer/httptracer.go#L48-L73 | train |
minio/mc | cmd/admin-user-add-policy.go | checkAdminUserPolicySyntax | func checkAdminUserPolicySyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code
}
} | go | func checkAdminUserPolicySyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code
}
} | [
"func",
"checkAdminUserPolicySyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"3",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"policy\"",
",",
"1",
")",
"\n",
"}"... | // checkAdminUserPolicySyntax - validate all the passed arguments | [
"checkAdminUserPolicySyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-add-policy.go#L51-L55 | train |
minio/mc | cmd/admin-user-add-policy.go | mainAdminUserPolicy | func mainAdminUserPolicy(ctx *cli.Context) error {
checkAdminUserPolicySyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(2))).Trace(args...), "Cannot set user policy for user")
printMsg(userMessage{
op: "policy",
AccessKey: args.Get(1),
PolicyName: args.Get(2),
UserStatus: "enabled",
})
return nil
} | go | func mainAdminUserPolicy(ctx *cli.Context) error {
checkAdminUserPolicySyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(2))).Trace(args...), "Cannot set user policy for user")
printMsg(userMessage{
op: "policy",
AccessKey: args.Get(1),
PolicyName: args.Get(2),
UserStatus: "enabled",
})
return nil
} | [
"func",
"mainAdminUserPolicy",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminUserPolicySyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"UserMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
... | // mainAdminUserPolicy is the handle for "mc admin user policy" command. | [
"mainAdminUserPolicy",
"is",
"the",
"handle",
"for",
"mc",
"admin",
"user",
"policy",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-add-policy.go#L58-L81 | train |
minio/mc | cmd/admin-service-status.go | checkAdminServiceStatusSyntax | func checkAdminServiceStatusSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
} | go | func checkAdminServiceStatusSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
} | [
"func",
"checkAdminServiceStatusSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"2",
"{",
"cli",
".",
"ShowComman... | // checkAdminServiceStatusSyntax - validate all the passed arguments | [
"checkAdminServiceStatusSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-service-status.go#L93-L97 | train |
minio/mc | cmd/session-v8.go | String | func (s sessionV8) String() string {
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
return message
} | go | func (s sessionV8) String() string {
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
return message
} | [
"func",
"(",
"s",
"sessionV8",
")",
"String",
"(",
")",
"string",
"{",
"message",
":=",
"console",
".",
"Colorize",
"(",
"\"SessionID\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s -> \"",
",",
"s",
".",
"SessionID",
")",
")",
"\n",
"message",
"=",
"messag... | // String colorized session message. | [
"String",
"colorized",
"session",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L86-L91 | train |
minio/mc | cmd/session-v8.go | JSON | func (s sessionV8) JSON() string {
sessionMsg := sessionMessage{
SessionID: s.SessionID,
Time: s.Header.When.Local(),
CommandType: s.Header.CommandType,
CommandArgs: s.Header.CommandArgs,
}
sessionMsg.Status = "success"
sessionBytes, e := json.MarshalIndent(sessionMsg, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(sessionBytes)
} | go | func (s sessionV8) JSON() string {
sessionMsg := sessionMessage{
SessionID: s.SessionID,
Time: s.Header.When.Local(),
CommandType: s.Header.CommandType,
CommandArgs: s.Header.CommandArgs,
}
sessionMsg.Status = "success"
sessionBytes, e := json.MarshalIndent(sessionMsg, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(sessionBytes)
} | [
"func",
"(",
"s",
"sessionV8",
")",
"JSON",
"(",
")",
"string",
"{",
"sessionMsg",
":=",
"sessionMessage",
"{",
"SessionID",
":",
"s",
".",
"SessionID",
",",
"Time",
":",
"s",
".",
"Header",
".",
"When",
".",
"Local",
"(",
")",
",",
"CommandType",
":... | // JSON jsonified session message. | [
"JSON",
"jsonified",
"session",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L94-L106 | train |
minio/mc | cmd/session-v8.go | loadSessionV8 | func loadSessionV8(sid string) (*sessionV8, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, err.Trace(sid)
}
if _, e := os.Stat(sessionFile); e != nil {
return nil, probe.NewError(e)
}
// Initialize new session.
s := &sessionV8{
Header: &sessionV8Header{
Version: globalSessionConfigVersion,
},
SessionID: sid,
}
// Initialize session config loader.
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
}
if e = qs.Load(sessionFile); e != nil {
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
}
// Validate if the version matches with expected current version.
sV8Header := qs.Data().(*sessionV8Header)
if sV8Header.Version != globalSessionConfigVersion {
msg := fmt.Sprintf("Session header version %s does not match mc session version %s.\n",
sV8Header.Version, globalSessionConfigVersion)
return nil, probe.NewError(errors.New(msg)).Trace(sid, sV8Header.Version)
}
s.mutex = new(sync.Mutex)
s.Header = sV8Header
sessionDataFile, err := getSessionDataFile(s.SessionID)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
}
dataFile, e := os.Open(sessionDataFile)
if e != nil {
return nil, probe.NewError(e)
}
s.DataFP = &sessionDataFP{false, dataFile}
return s, nil
} | go | func loadSessionV8(sid string) (*sessionV8, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, err.Trace(sid)
}
if _, e := os.Stat(sessionFile); e != nil {
return nil, probe.NewError(e)
}
// Initialize new session.
s := &sessionV8{
Header: &sessionV8Header{
Version: globalSessionConfigVersion,
},
SessionID: sid,
}
// Initialize session config loader.
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
}
if e = qs.Load(sessionFile); e != nil {
return nil, probe.NewError(e).Trace(sid, s.Header.Version)
}
// Validate if the version matches with expected current version.
sV8Header := qs.Data().(*sessionV8Header)
if sV8Header.Version != globalSessionConfigVersion {
msg := fmt.Sprintf("Session header version %s does not match mc session version %s.\n",
sV8Header.Version, globalSessionConfigVersion)
return nil, probe.NewError(errors.New(msg)).Trace(sid, sV8Header.Version)
}
s.mutex = new(sync.Mutex)
s.Header = sV8Header
sessionDataFile, err := getSessionDataFile(s.SessionID)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
}
dataFile, e := os.Open(sessionDataFile)
if e != nil {
return nil, probe.NewError(e)
}
s.DataFP = &sessionDataFP{false, dataFile}
return s, nil
} | [
"func",
"loadSessionV8",
"(",
"sid",
"string",
")",
"(",
"*",
"sessionV8",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"!",
"isSessionDirExists",
"(",
")",
"{",
"return",
"nil",
",",
"errInvalidArgument",
"(",
")",
".",
"Trace",
"(",
")",
"\n",
... | // loadSessionV8 - reads session file if exists and re-initiates internal variables | [
"loadSessionV8",
"-",
"reads",
"session",
"file",
"if",
"exists",
"and",
"re",
"-",
"initiates",
"internal",
"variables"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L109-L163 | train |
minio/mc | cmd/session-v8.go | newSessionV8 | func newSessionV8() *sessionV8 {
s := &sessionV8{}
s.Header = &sessionV8Header{}
s.Header.Version = globalSessionConfigVersion
// map of command and files copied.
s.Header.GlobalBoolFlags = make(map[string]bool)
s.Header.GlobalIntFlags = make(map[string]int)
s.Header.GlobalStringFlags = make(map[string]string)
s.Header.CommandArgs = nil
s.Header.CommandBoolFlags = make(map[string]bool)
s.Header.CommandIntFlags = make(map[string]int)
s.Header.CommandStringFlags = make(map[string]string)
s.Header.UserMetaData = make(map[string]string)
s.Header.When = UTCNow()
s.mutex = new(sync.Mutex)
s.SessionID = newRandomID(8)
sessionDataFile, err := getSessionDataFile(s.SessionID)
fatalIf(err.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
dataFile, e := os.Create(sessionDataFile)
fatalIf(probe.NewError(e), "Unable to create session data file \""+sessionDataFile+"\".")
s.DataFP = &sessionDataFP{false, dataFile}
// Capture state of global flags.
s.setGlobals()
return s
} | go | func newSessionV8() *sessionV8 {
s := &sessionV8{}
s.Header = &sessionV8Header{}
s.Header.Version = globalSessionConfigVersion
// map of command and files copied.
s.Header.GlobalBoolFlags = make(map[string]bool)
s.Header.GlobalIntFlags = make(map[string]int)
s.Header.GlobalStringFlags = make(map[string]string)
s.Header.CommandArgs = nil
s.Header.CommandBoolFlags = make(map[string]bool)
s.Header.CommandIntFlags = make(map[string]int)
s.Header.CommandStringFlags = make(map[string]string)
s.Header.UserMetaData = make(map[string]string)
s.Header.When = UTCNow()
s.mutex = new(sync.Mutex)
s.SessionID = newRandomID(8)
sessionDataFile, err := getSessionDataFile(s.SessionID)
fatalIf(err.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
dataFile, e := os.Create(sessionDataFile)
fatalIf(probe.NewError(e), "Unable to create session data file \""+sessionDataFile+"\".")
s.DataFP = &sessionDataFP{false, dataFile}
// Capture state of global flags.
s.setGlobals()
return s
} | [
"func",
"newSessionV8",
"(",
")",
"*",
"sessionV8",
"{",
"s",
":=",
"&",
"sessionV8",
"{",
"}",
"\n",
"s",
".",
"Header",
"=",
"&",
"sessionV8Header",
"{",
"}",
"\n",
"s",
".",
"Header",
".",
"Version",
"=",
"globalSessionConfigVersion",
"\n",
"s",
"."... | // newSessionV8 provides a new session. | [
"newSessionV8",
"provides",
"a",
"new",
"session",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L166-L195 | train |
minio/mc | cmd/session-v8.go | HasData | func (s sessionV8) HasData() bool {
return s.Header.LastCopied != "" || s.Header.LastRemoved != ""
} | go | func (s sessionV8) HasData() bool {
return s.Header.LastCopied != "" || s.Header.LastRemoved != ""
} | [
"func",
"(",
"s",
"sessionV8",
")",
"HasData",
"(",
")",
"bool",
"{",
"return",
"s",
".",
"Header",
".",
"LastCopied",
"!=",
"\"\"",
"||",
"s",
".",
"Header",
".",
"LastRemoved",
"!=",
"\"\"",
"\n",
"}"
] | // HasData provides true if this is a session resume, false otherwise. | [
"HasData",
"provides",
"true",
"if",
"this",
"is",
"a",
"session",
"resume",
"false",
"otherwise",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L198-L200 | train |
minio/mc | cmd/session-v8.go | NewDataReader | func (s *sessionV8) NewDataReader() io.Reader {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Reader(s.DataFP)
} | go | func (s *sessionV8) NewDataReader() io.Reader {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Reader(s.DataFP)
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"NewDataReader",
"(",
")",
"io",
".",
"Reader",
"{",
"s",
".",
"DataFP",
".",
"Seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"\n",
"return",
"io",
".",
"Reader",
"(",
"s",
".",
"DataFP",
")",
"\n",
"... | // NewDataReader provides reader interface to session data file. | [
"NewDataReader",
"provides",
"reader",
"interface",
"to",
"session",
"data",
"file",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L203-L207 | train |
minio/mc | cmd/session-v8.go | NewDataWriter | func (s *sessionV8) NewDataWriter() io.Writer {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
// when moving to file position 0 we want to truncate the file as well,
// otherwise we'll partly overwrite existing data
s.DataFP.Truncate(0)
return io.Writer(s.DataFP)
} | go | func (s *sessionV8) NewDataWriter() io.Writer {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
// when moving to file position 0 we want to truncate the file as well,
// otherwise we'll partly overwrite existing data
s.DataFP.Truncate(0)
return io.Writer(s.DataFP)
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"NewDataWriter",
"(",
")",
"io",
".",
"Writer",
"{",
"s",
".",
"DataFP",
".",
"Seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"\n",
"s",
".",
"DataFP",
".",
"Truncate",
"(",
"0",
")",
"\n",
"return",
... | // NewDataReader provides writer interface to session data file. | [
"NewDataReader",
"provides",
"writer",
"interface",
"to",
"session",
"data",
"file",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L210-L217 | train |
minio/mc | cmd/session-v8.go | Save | func (s *sessionV8) Save() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.DataFP.dirty {
if err := s.DataFP.Sync(); err != nil {
return probe.NewError(err)
}
s.DataFP.dirty = false
}
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return probe.NewError(e).Trace(s.SessionID)
}
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
e = qs.Save(sessionFile)
if e != nil {
return probe.NewError(e).Trace(sessionFile)
}
return nil
} | go | func (s *sessionV8) Save() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.DataFP.dirty {
if err := s.DataFP.Sync(); err != nil {
return probe.NewError(err)
}
s.DataFP.dirty = false
}
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return probe.NewError(e).Trace(s.SessionID)
}
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
e = qs.Save(sessionFile)
if e != nil {
return probe.NewError(e).Trace(sessionFile)
}
return nil
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"Save",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"DataFP",
".",
"dirty",
"{"... | // Save this session. | [
"Save",
"this",
"session",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L220-L245 | train |
minio/mc | cmd/session-v8.go | setGlobals | func (s *sessionV8) setGlobals() {
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
s.Header.GlobalBoolFlags["debug"] = globalDebug
s.Header.GlobalBoolFlags["json"] = globalJSON
s.Header.GlobalBoolFlags["noColor"] = globalNoColor
s.Header.GlobalBoolFlags["insecure"] = globalInsecure
} | go | func (s *sessionV8) setGlobals() {
s.Header.GlobalBoolFlags["quiet"] = globalQuiet
s.Header.GlobalBoolFlags["debug"] = globalDebug
s.Header.GlobalBoolFlags["json"] = globalJSON
s.Header.GlobalBoolFlags["noColor"] = globalNoColor
s.Header.GlobalBoolFlags["insecure"] = globalInsecure
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"setGlobals",
"(",
")",
"{",
"s",
".",
"Header",
".",
"GlobalBoolFlags",
"[",
"\"quiet\"",
"]",
"=",
"globalQuiet",
"\n",
"s",
".",
"Header",
".",
"GlobalBoolFlags",
"[",
"\"debug\"",
"]",
"=",
"globalDebug",
"\n"... | // setGlobals captures the state of global variables into session header.
// Used by newSession. | [
"setGlobals",
"captures",
"the",
"state",
"of",
"global",
"variables",
"into",
"session",
"header",
".",
"Used",
"by",
"newSession",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L249-L255 | train |
minio/mc | cmd/session-v8.go | restoreGlobals | func (s sessionV8) restoreGlobals() {
quiet := s.Header.GlobalBoolFlags["quiet"]
debug := s.Header.GlobalBoolFlags["debug"]
json := s.Header.GlobalBoolFlags["json"]
noColor := s.Header.GlobalBoolFlags["noColor"]
insecure := s.Header.GlobalBoolFlags["insecure"]
setGlobals(quiet, debug, json, noColor, insecure)
} | go | func (s sessionV8) restoreGlobals() {
quiet := s.Header.GlobalBoolFlags["quiet"]
debug := s.Header.GlobalBoolFlags["debug"]
json := s.Header.GlobalBoolFlags["json"]
noColor := s.Header.GlobalBoolFlags["noColor"]
insecure := s.Header.GlobalBoolFlags["insecure"]
setGlobals(quiet, debug, json, noColor, insecure)
} | [
"func",
"(",
"s",
"sessionV8",
")",
"restoreGlobals",
"(",
")",
"{",
"quiet",
":=",
"s",
".",
"Header",
".",
"GlobalBoolFlags",
"[",
"\"quiet\"",
"]",
"\n",
"debug",
":=",
"s",
".",
"Header",
".",
"GlobalBoolFlags",
"[",
"\"debug\"",
"]",
"\n",
"json",
... | // RestoreGlobals restores the state of global variables.
// Used by resumeSession. | [
"RestoreGlobals",
"restores",
"the",
"state",
"of",
"global",
"variables",
".",
"Used",
"by",
"resumeSession",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L259-L266 | train |
minio/mc | cmd/session-v8.go | isModified | func (s *sessionV8) isModified(sessionFile string) (bool, *probe.Error) {
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return false, probe.NewError(e).Trace(s.SessionID)
}
var currentHeader = &sessionV8Header{}
currentQS, e := quick.LoadConfig(sessionFile, nil, currentHeader)
if e != nil {
// If session does not exist for the first, return modified to
// be true.
if os.IsNotExist(e) {
return true, nil
}
// For all other errors return.
return false, probe.NewError(e).Trace(s.SessionID)
}
changedFields, e := qs.DeepDiff(currentQS)
if e != nil {
return false, probe.NewError(e).Trace(s.SessionID)
}
// Returns true if there are changed entries.
return len(changedFields) > 0, nil
} | go | func (s *sessionV8) isModified(sessionFile string) (bool, *probe.Error) {
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return false, probe.NewError(e).Trace(s.SessionID)
}
var currentHeader = &sessionV8Header{}
currentQS, e := quick.LoadConfig(sessionFile, nil, currentHeader)
if e != nil {
// If session does not exist for the first, return modified to
// be true.
if os.IsNotExist(e) {
return true, nil
}
// For all other errors return.
return false, probe.NewError(e).Trace(s.SessionID)
}
changedFields, e := qs.DeepDiff(currentQS)
if e != nil {
return false, probe.NewError(e).Trace(s.SessionID)
}
// Returns true if there are changed entries.
return len(changedFields) > 0, nil
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"isModified",
"(",
"sessionFile",
"string",
")",
"(",
"bool",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"qs",
",",
"e",
":=",
"quick",
".",
"NewConfig",
"(",
"s",
".",
"Header",
",",
"nil",
")",
"\n",
"if... | // IsModified - returns if in memory session header has changed from
// its on disk value. | [
"IsModified",
"-",
"returns",
"if",
"in",
"memory",
"session",
"header",
"has",
"changed",
"from",
"its",
"on",
"disk",
"value",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L270-L295 | train |
minio/mc | cmd/session-v8.go | save | func (s *sessionV8) save() *probe.Error {
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
// Verify if sessionFile is modified.
modified, err := s.isModified(sessionFile)
if err != nil {
return err.Trace(s.SessionID)
}
// Header is modified, we save it.
if modified {
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return probe.NewError(e).Trace(s.SessionID)
}
// Save an return.
e = qs.Save(sessionFile)
if e != nil {
return probe.NewError(e).Trace(sessionFile)
}
}
return nil
} | go | func (s *sessionV8) save() *probe.Error {
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
// Verify if sessionFile is modified.
modified, err := s.isModified(sessionFile)
if err != nil {
return err.Trace(s.SessionID)
}
// Header is modified, we save it.
if modified {
qs, e := quick.NewConfig(s.Header, nil)
if e != nil {
return probe.NewError(e).Trace(s.SessionID)
}
// Save an return.
e = qs.Save(sessionFile)
if e != nil {
return probe.NewError(e).Trace(sessionFile)
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"save",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"sessionFile",
",",
"err",
":=",
"getSessionFile",
"(",
"s",
".",
"SessionID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
".",
"Trace",
"(",... | // save - wrapper for quick.Save and saves only if sessionHeader is
// modified. | [
"save",
"-",
"wrapper",
"for",
"quick",
".",
"Save",
"and",
"saves",
"only",
"if",
"sessionHeader",
"is",
"modified",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L299-L323 | train |
minio/mc | cmd/session-v8.go | Close | func (s *sessionV8) Close() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
if err := s.DataFP.Close(); err != nil {
return probe.NewError(err)
}
// Attempt to save the header if modified.
return s.save()
} | go | func (s *sessionV8) Close() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
if err := s.DataFP.Close(); err != nil {
return probe.NewError(err)
}
// Attempt to save the header if modified.
return s.save()
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"Close",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"DataFP",
"."... | // Close ends this session and removes all associated session files. | [
"Close",
"ends",
"this",
"session",
"and",
"removes",
"all",
"associated",
"session",
"files",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L326-L336 | train |
minio/mc | cmd/session-v8.go | Delete | func (s *sessionV8) Delete() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.DataFP != nil {
name := s.DataFP.Name()
// close file pro-actively before deleting
// ignore any error, it could be possibly that
// the file is closed already
s.DataFP.Close()
// Remove the data file.
if e := os.Remove(name); e != nil {
return probe.NewError(e)
}
}
// Fetch the session file.
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
// Remove session file
if e := os.Remove(sessionFile); e != nil {
return probe.NewError(e)
}
// Remove session backup file if any, ignore any error.
os.Remove(sessionFile + ".old")
return nil
} | go | func (s *sessionV8) Delete() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.DataFP != nil {
name := s.DataFP.Name()
// close file pro-actively before deleting
// ignore any error, it could be possibly that
// the file is closed already
s.DataFP.Close()
// Remove the data file.
if e := os.Remove(name); e != nil {
return probe.NewError(e)
}
}
// Fetch the session file.
sessionFile, err := getSessionFile(s.SessionID)
if err != nil {
return err.Trace(s.SessionID)
}
// Remove session file
if e := os.Remove(sessionFile); e != nil {
return probe.NewError(e)
}
// Remove session backup file if any, ignore any error.
os.Remove(sessionFile + ".old")
return nil
} | [
"func",
"(",
"s",
"*",
"sessionV8",
")",
"Delete",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"DataFP",
"!=",
"nil",
"{... | // Delete removes all the session files. | [
"Delete",
"removes",
"all",
"the",
"session",
"files",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L339-L371 | train |
minio/mc | cmd/session-v8.go | isLastFactory | func isLastFactory(lastURL string) func(string) bool {
last := true // closure
return func(sourceURL string) bool {
if sourceURL == "" {
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
}
if lastURL == "" {
return false
}
if last {
if lastURL == sourceURL {
last = false // from next call onwards we say false.
}
return true
}
return false
}
} | go | func isLastFactory(lastURL string) func(string) bool {
last := true // closure
return func(sourceURL string) bool {
if sourceURL == "" {
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
}
if lastURL == "" {
return false
}
if last {
if lastURL == sourceURL {
last = false // from next call onwards we say false.
}
return true
}
return false
}
} | [
"func",
"isLastFactory",
"(",
"lastURL",
"string",
")",
"func",
"(",
"string",
")",
"bool",
"{",
"last",
":=",
"true",
"\n",
"return",
"func",
"(",
"sourceURL",
"string",
")",
"bool",
"{",
"if",
"sourceURL",
"==",
"\"\"",
"{",
"fatalIf",
"(",
"errInvalid... | // Create a factory function to simplify checking if
// object was last operated on. | [
"Create",
"a",
"factory",
"function",
"to",
"simplify",
"checking",
"if",
"object",
"was",
"last",
"operated",
"on",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L381-L399 | train |
minio/mc | cmd/client-s3.go | AddNotificationConfig | func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, suffix string) *probe.Error {
bucket, _ := c.url2BucketAndObject()
// Validate total fields in ARN.
fields := strings.Split(arn, ":")
if len(fields) != 6 {
return errInvalidArgument()
}
// Get any enabled notification.
mb, e := c.api.GetBucketNotification(bucket)
if e != nil {
return probe.NewError(e)
}
accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
nc := minio.NewNotificationConfig(accountArn)
// Configure events
for _, event := range events {
switch event {
case "put":
nc.AddEvents(minio.ObjectCreatedAll)
case "delete":
nc.AddEvents(minio.ObjectRemovedAll)
case "get":
nc.AddEvents(minio.ObjectAccessedAll)
default:
return errInvalidArgument().Trace(events...)
}
}
if prefix != "" {
nc.AddFilterPrefix(prefix)
}
if suffix != "" {
nc.AddFilterSuffix(suffix)
}
switch fields[2] {
case "sns":
if !mb.AddTopic(nc) {
return errInvalidArgument().Trace("Overlapping Topic configs")
}
case "sqs":
if !mb.AddQueue(nc) {
return errInvalidArgument().Trace("Overlapping Queue configs")
}
case "lambda":
if !mb.AddLambda(nc) {
return errInvalidArgument().Trace("Overlapping lambda configs")
}
default:
return errInvalidArgument().Trace(fields[2])
}
// Set the new bucket configuration
if err := c.api.SetBucketNotification(bucket, mb); err != nil {
return probe.NewError(err)
}
return nil
} | go | func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, suffix string) *probe.Error {
bucket, _ := c.url2BucketAndObject()
// Validate total fields in ARN.
fields := strings.Split(arn, ":")
if len(fields) != 6 {
return errInvalidArgument()
}
// Get any enabled notification.
mb, e := c.api.GetBucketNotification(bucket)
if e != nil {
return probe.NewError(e)
}
accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
nc := minio.NewNotificationConfig(accountArn)
// Configure events
for _, event := range events {
switch event {
case "put":
nc.AddEvents(minio.ObjectCreatedAll)
case "delete":
nc.AddEvents(minio.ObjectRemovedAll)
case "get":
nc.AddEvents(minio.ObjectAccessedAll)
default:
return errInvalidArgument().Trace(events...)
}
}
if prefix != "" {
nc.AddFilterPrefix(prefix)
}
if suffix != "" {
nc.AddFilterSuffix(suffix)
}
switch fields[2] {
case "sns":
if !mb.AddTopic(nc) {
return errInvalidArgument().Trace("Overlapping Topic configs")
}
case "sqs":
if !mb.AddQueue(nc) {
return errInvalidArgument().Trace("Overlapping Queue configs")
}
case "lambda":
if !mb.AddLambda(nc) {
return errInvalidArgument().Trace("Overlapping lambda configs")
}
default:
return errInvalidArgument().Trace(fields[2])
}
// Set the new bucket configuration
if err := c.api.SetBucketNotification(bucket, mb); err != nil {
return probe.NewError(err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"AddNotificationConfig",
"(",
"arn",
"string",
",",
"events",
"[",
"]",
"string",
",",
"prefix",
",",
"suffix",
"string",
")",
"*",
"probe",
".",
"Error",
"{",
"bucket",
",",
"_",
":=",
"c",
".",
"url2BucketAndOb... | // Add bucket notification | [
"Add",
"bucket",
"notification"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L243-L302 | train |
minio/mc | cmd/client-s3.go | RemoveNotificationConfig | func (c *s3Client) RemoveNotificationConfig(arn string) *probe.Error {
bucket, _ := c.url2BucketAndObject()
// Remove all notification configs if arn is empty
if arn == "" {
if err := c.api.RemoveAllBucketNotification(bucket); err != nil {
return probe.NewError(err)
}
return nil
}
mb, e := c.api.GetBucketNotification(bucket)
if e != nil {
return probe.NewError(e)
}
fields := strings.Split(arn, ":")
if len(fields) != 6 {
return errInvalidArgument().Trace(fields...)
}
accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
switch fields[2] {
case "sns":
mb.RemoveTopicByArn(accountArn)
case "sqs":
mb.RemoveQueueByArn(accountArn)
case "lambda":
mb.RemoveLambdaByArn(accountArn)
default:
return errInvalidArgument().Trace(fields[2])
}
// Set the new bucket configuration
if e := c.api.SetBucketNotification(bucket, mb); e != nil {
return probe.NewError(e)
}
return nil
} | go | func (c *s3Client) RemoveNotificationConfig(arn string) *probe.Error {
bucket, _ := c.url2BucketAndObject()
// Remove all notification configs if arn is empty
if arn == "" {
if err := c.api.RemoveAllBucketNotification(bucket); err != nil {
return probe.NewError(err)
}
return nil
}
mb, e := c.api.GetBucketNotification(bucket)
if e != nil {
return probe.NewError(e)
}
fields := strings.Split(arn, ":")
if len(fields) != 6 {
return errInvalidArgument().Trace(fields...)
}
accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5])
switch fields[2] {
case "sns":
mb.RemoveTopicByArn(accountArn)
case "sqs":
mb.RemoveQueueByArn(accountArn)
case "lambda":
mb.RemoveLambdaByArn(accountArn)
default:
return errInvalidArgument().Trace(fields[2])
}
// Set the new bucket configuration
if e := c.api.SetBucketNotification(bucket, mb); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"RemoveNotificationConfig",
"(",
"arn",
"string",
")",
"*",
"probe",
".",
"Error",
"{",
"bucket",
",",
"_",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"if",
"arn",
"==",
"\"\"",
"{",
"if",
"err",
":... | // Remove bucket notification | [
"Remove",
"bucket",
"notification"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L305-L342 | train |
minio/mc | cmd/client-s3.go | ListNotificationConfigs | func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *probe.Error) {
var configs []notificationConfig
bucket, _ := c.url2BucketAndObject()
mb, e := c.api.GetBucketNotification(bucket)
if e != nil {
return nil, probe.NewError(e)
}
// Generate pretty event names from event types
prettyEventNames := func(eventsTypes []minio.NotificationEventType) []string {
var result []string
for _, eventType := range eventsTypes {
result = append(result, string(eventType))
}
return result
}
getFilters := func(config minio.NotificationConfig) (prefix, suffix string) {
if config.Filter == nil {
return
}
for _, filter := range config.Filter.S3Key.FilterRules {
if strings.ToLower(filter.Name) == "prefix" {
prefix = filter.Value
}
if strings.ToLower(filter.Name) == "suffix" {
suffix = filter.Value
}
}
return prefix, suffix
}
for _, config := range mb.TopicConfigs {
if arn != "" && config.Topic != arn {
continue
}
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, notificationConfig{ID: config.ID,
Arn: config.Topic,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix})
}
for _, config := range mb.QueueConfigs {
if arn != "" && config.Queue != arn {
continue
}
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, notificationConfig{ID: config.ID,
Arn: config.Queue,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix})
}
for _, config := range mb.LambdaConfigs {
if arn != "" && config.Lambda != arn {
continue
}
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, notificationConfig{ID: config.ID,
Arn: config.Lambda,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix})
}
return configs, nil
} | go | func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *probe.Error) {
var configs []notificationConfig
bucket, _ := c.url2BucketAndObject()
mb, e := c.api.GetBucketNotification(bucket)
if e != nil {
return nil, probe.NewError(e)
}
// Generate pretty event names from event types
prettyEventNames := func(eventsTypes []minio.NotificationEventType) []string {
var result []string
for _, eventType := range eventsTypes {
result = append(result, string(eventType))
}
return result
}
getFilters := func(config minio.NotificationConfig) (prefix, suffix string) {
if config.Filter == nil {
return
}
for _, filter := range config.Filter.S3Key.FilterRules {
if strings.ToLower(filter.Name) == "prefix" {
prefix = filter.Value
}
if strings.ToLower(filter.Name) == "suffix" {
suffix = filter.Value
}
}
return prefix, suffix
}
for _, config := range mb.TopicConfigs {
if arn != "" && config.Topic != arn {
continue
}
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, notificationConfig{ID: config.ID,
Arn: config.Topic,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix})
}
for _, config := range mb.QueueConfigs {
if arn != "" && config.Queue != arn {
continue
}
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, notificationConfig{ID: config.ID,
Arn: config.Queue,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix})
}
for _, config := range mb.LambdaConfigs {
if arn != "" && config.Lambda != arn {
continue
}
prefix, suffix := getFilters(config.NotificationConfig)
configs = append(configs, notificationConfig{ID: config.ID,
Arn: config.Lambda,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix})
}
return configs, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"ListNotificationConfigs",
"(",
"arn",
"string",
")",
"(",
"[",
"]",
"notificationConfig",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"var",
"configs",
"[",
"]",
"notificationConfig",
"\n",
"bucket",
",",
"_",
":="... | // List notification configs | [
"List",
"notification",
"configs"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L353-L423 | train |
minio/mc | cmd/client-s3.go | selectObjectOutputOpts | func selectObjectOutputOpts(selOpts SelectObjectOpts, i minio.SelectObjectInputSerialization) minio.SelectObjectOutputSerialization {
var isOK bool
var recDelim, fldDelim, quoteChar, quoteEscChar, qf string
o := minio.SelectObjectOutputSerialization{}
if _, ok := selOpts.OutputSerOpts["json"]; ok {
recDelim, isOK = selOpts.OutputSerOpts["json"][recordDelimiterType]
if !isOK {
recDelim = "\n"
}
o.JSON = &minio.JSONOutputOptions{RecordDelimiter: recDelim}
}
if _, ok := selOpts.OutputSerOpts["csv"]; ok {
o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter}
if recDelim, isOK = selOpts.OutputSerOpts["csv"][recordDelimiterType]; isOK {
o.CSV.RecordDelimiter = recDelim
}
if fldDelim, isOK = selOpts.OutputSerOpts["csv"][fieldDelimiterType]; isOK {
o.CSV.FieldDelimiter = fldDelim
}
if quoteChar, isOK = selOpts.OutputSerOpts["csv"][quoteCharacterType]; isOK {
o.CSV.QuoteCharacter = quoteChar
}
if quoteEscChar, isOK = selOpts.OutputSerOpts["csv"][quoteEscapeCharacterType]; isOK {
o.CSV.QuoteEscapeCharacter = quoteEscChar
}
if qf, isOK = selOpts.OutputSerOpts["csv"][quoteFieldType]; isOK {
o.CSV.QuoteFields = minio.CSVQuoteFields(qf)
}
}
// default to CSV output if options left unspecified
if o.CSV == nil && o.JSON == nil {
if i.JSON != nil {
o.JSON = &minio.JSONOutputOptions{RecordDelimiter: "\n"}
} else {
o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter}
}
}
return o
} | go | func selectObjectOutputOpts(selOpts SelectObjectOpts, i minio.SelectObjectInputSerialization) minio.SelectObjectOutputSerialization {
var isOK bool
var recDelim, fldDelim, quoteChar, quoteEscChar, qf string
o := minio.SelectObjectOutputSerialization{}
if _, ok := selOpts.OutputSerOpts["json"]; ok {
recDelim, isOK = selOpts.OutputSerOpts["json"][recordDelimiterType]
if !isOK {
recDelim = "\n"
}
o.JSON = &minio.JSONOutputOptions{RecordDelimiter: recDelim}
}
if _, ok := selOpts.OutputSerOpts["csv"]; ok {
o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter}
if recDelim, isOK = selOpts.OutputSerOpts["csv"][recordDelimiterType]; isOK {
o.CSV.RecordDelimiter = recDelim
}
if fldDelim, isOK = selOpts.OutputSerOpts["csv"][fieldDelimiterType]; isOK {
o.CSV.FieldDelimiter = fldDelim
}
if quoteChar, isOK = selOpts.OutputSerOpts["csv"][quoteCharacterType]; isOK {
o.CSV.QuoteCharacter = quoteChar
}
if quoteEscChar, isOK = selOpts.OutputSerOpts["csv"][quoteEscapeCharacterType]; isOK {
o.CSV.QuoteEscapeCharacter = quoteEscChar
}
if qf, isOK = selOpts.OutputSerOpts["csv"][quoteFieldType]; isOK {
o.CSV.QuoteFields = minio.CSVQuoteFields(qf)
}
}
// default to CSV output if options left unspecified
if o.CSV == nil && o.JSON == nil {
if i.JSON != nil {
o.JSON = &minio.JSONOutputOptions{RecordDelimiter: "\n"}
} else {
o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter}
}
}
return o
} | [
"func",
"selectObjectOutputOpts",
"(",
"selOpts",
"SelectObjectOpts",
",",
"i",
"minio",
".",
"SelectObjectInputSerialization",
")",
"minio",
".",
"SelectObjectOutputSerialization",
"{",
"var",
"isOK",
"bool",
"\n",
"var",
"recDelim",
",",
"fldDelim",
",",
"quoteChar"... | // set the SelectObjectOutputSerialization struct using options passed in by client. If unspecified,
// default S3 API specified defaults | [
"set",
"the",
"SelectObjectOutputSerialization",
"struct",
"using",
"options",
"passed",
"in",
"by",
"client",
".",
"If",
"unspecified",
"default",
"S3",
"API",
"specified",
"defaults"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L435-L476 | train |
minio/mc | cmd/client-s3.go | selectObjectInputOpts | func selectObjectInputOpts(selOpts SelectObjectOpts, object string) minio.SelectObjectInputSerialization {
var isOK bool
var recDelim, fldDelim, quoteChar, quoteEscChar, fileHeader, commentChar, typ string
i := minio.SelectObjectInputSerialization{}
if _, ok := selOpts.InputSerOpts["parquet"]; ok {
i.Parquet = &minio.ParquetInputOptions{}
}
if _, ok := selOpts.InputSerOpts["json"]; ok {
i.JSON = &minio.JSONInputOptions{}
if typ, _ = selOpts.InputSerOpts["json"][typeJSONType]; typ != "" {
i.JSON.Type = minio.JSONType(typ)
}
}
if _, ok := selOpts.InputSerOpts["csv"]; ok {
i.CSV = &minio.CSVInputOptions{RecordDelimiter: defaultRecordDelimiter}
if recDelim, isOK = selOpts.InputSerOpts["csv"][recordDelimiterType]; isOK {
i.CSV.RecordDelimiter = recDelim
}
if fldDelim, isOK = selOpts.InputSerOpts["csv"][fieldDelimiterType]; isOK {
i.CSV.FieldDelimiter = fldDelim
}
if quoteChar, isOK = selOpts.InputSerOpts["csv"][quoteCharacterType]; isOK {
i.CSV.QuoteCharacter = quoteChar
}
if quoteEscChar, isOK = selOpts.InputSerOpts["csv"][quoteEscapeCharacterType]; isOK {
i.CSV.QuoteEscapeCharacter = quoteEscChar
}
fileHeader, _ = selOpts.InputSerOpts["csv"][fileHeaderType]
i.CSV.FileHeaderInfo = minio.CSVFileHeaderInfo(fileHeader)
if commentChar, isOK = selOpts.InputSerOpts["csv"][commentCharType]; isOK {
i.CSV.Comments = commentChar
}
// needs to be added to minio-go
// if qrd, isOK = selOpts.InputSerOpts["csv"][quotedRecordDelimiterType];isOK {
// i.CSV.QuotedRecordDelimiter = qrd
// }
}
if i.CSV == nil && i.JSON == nil && i.Parquet == nil {
ext := filepath.Ext(trimCompressionFileExts(object))
if strings.Contains(ext, "csv") {
i.CSV = &minio.CSVInputOptions{
RecordDelimiter: defaultRecordDelimiter,
FieldDelimiter: defaultFieldDelimiter,
FileHeaderInfo: minio.CSVFileHeaderInfoUse,
}
}
if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") {
i.Parquet = &minio.ParquetInputOptions{}
}
if strings.Contains(ext, "json") {
i.JSON = &minio.JSONInputOptions{Type: minio.JSONLinesType}
}
}
i.CompressionType = selectCompressionType(selOpts, object)
return i
} | go | func selectObjectInputOpts(selOpts SelectObjectOpts, object string) minio.SelectObjectInputSerialization {
var isOK bool
var recDelim, fldDelim, quoteChar, quoteEscChar, fileHeader, commentChar, typ string
i := minio.SelectObjectInputSerialization{}
if _, ok := selOpts.InputSerOpts["parquet"]; ok {
i.Parquet = &minio.ParquetInputOptions{}
}
if _, ok := selOpts.InputSerOpts["json"]; ok {
i.JSON = &minio.JSONInputOptions{}
if typ, _ = selOpts.InputSerOpts["json"][typeJSONType]; typ != "" {
i.JSON.Type = minio.JSONType(typ)
}
}
if _, ok := selOpts.InputSerOpts["csv"]; ok {
i.CSV = &minio.CSVInputOptions{RecordDelimiter: defaultRecordDelimiter}
if recDelim, isOK = selOpts.InputSerOpts["csv"][recordDelimiterType]; isOK {
i.CSV.RecordDelimiter = recDelim
}
if fldDelim, isOK = selOpts.InputSerOpts["csv"][fieldDelimiterType]; isOK {
i.CSV.FieldDelimiter = fldDelim
}
if quoteChar, isOK = selOpts.InputSerOpts["csv"][quoteCharacterType]; isOK {
i.CSV.QuoteCharacter = quoteChar
}
if quoteEscChar, isOK = selOpts.InputSerOpts["csv"][quoteEscapeCharacterType]; isOK {
i.CSV.QuoteEscapeCharacter = quoteEscChar
}
fileHeader, _ = selOpts.InputSerOpts["csv"][fileHeaderType]
i.CSV.FileHeaderInfo = minio.CSVFileHeaderInfo(fileHeader)
if commentChar, isOK = selOpts.InputSerOpts["csv"][commentCharType]; isOK {
i.CSV.Comments = commentChar
}
// needs to be added to minio-go
// if qrd, isOK = selOpts.InputSerOpts["csv"][quotedRecordDelimiterType];isOK {
// i.CSV.QuotedRecordDelimiter = qrd
// }
}
if i.CSV == nil && i.JSON == nil && i.Parquet == nil {
ext := filepath.Ext(trimCompressionFileExts(object))
if strings.Contains(ext, "csv") {
i.CSV = &minio.CSVInputOptions{
RecordDelimiter: defaultRecordDelimiter,
FieldDelimiter: defaultFieldDelimiter,
FileHeaderInfo: minio.CSVFileHeaderInfoUse,
}
}
if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") {
i.Parquet = &minio.ParquetInputOptions{}
}
if strings.Contains(ext, "json") {
i.JSON = &minio.JSONInputOptions{Type: minio.JSONLinesType}
}
}
i.CompressionType = selectCompressionType(selOpts, object)
return i
} | [
"func",
"selectObjectInputOpts",
"(",
"selOpts",
"SelectObjectOpts",
",",
"object",
"string",
")",
"minio",
".",
"SelectObjectInputSerialization",
"{",
"var",
"isOK",
"bool",
"\n",
"var",
"recDelim",
",",
"fldDelim",
",",
"quoteChar",
",",
"quoteEscChar",
",",
"fi... | // set the SelectObjectInputSerialization struct using options passed in by client. If unspecified,
// default S3 API specified defaults | [
"set",
"the",
"SelectObjectInputSerialization",
"struct",
"using",
"options",
"passed",
"in",
"by",
"client",
".",
"If",
"unspecified",
"default",
"S3",
"API",
"specified",
"defaults"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L484-L541 | train |
minio/mc | cmd/client-s3.go | selectCompressionType | func selectCompressionType(selOpts SelectObjectOpts, object string) minio.SelectCompressionType {
ext := filepath.Ext(object)
contentType := mimedb.TypeByExtension(ext)
if selOpts.CompressionType != "" {
return selOpts.CompressionType
}
if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") {
return minio.SelectCompressionNONE
}
if contentType != "" {
if strings.Contains(contentType, "gzip") {
return minio.SelectCompressionGZIP
} else if strings.Contains(contentType, "bzip") {
return minio.SelectCompressionBZIP
}
}
return minio.SelectCompressionNONE
} | go | func selectCompressionType(selOpts SelectObjectOpts, object string) minio.SelectCompressionType {
ext := filepath.Ext(object)
contentType := mimedb.TypeByExtension(ext)
if selOpts.CompressionType != "" {
return selOpts.CompressionType
}
if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") {
return minio.SelectCompressionNONE
}
if contentType != "" {
if strings.Contains(contentType, "gzip") {
return minio.SelectCompressionGZIP
} else if strings.Contains(contentType, "bzip") {
return minio.SelectCompressionBZIP
}
}
return minio.SelectCompressionNONE
} | [
"func",
"selectCompressionType",
"(",
"selOpts",
"SelectObjectOpts",
",",
"object",
"string",
")",
"minio",
".",
"SelectCompressionType",
"{",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"object",
")",
"\n",
"contentType",
":=",
"mimedb",
".",
"TypeByExtension",
"... | // get client specified compression type or default compression type from file extension | [
"get",
"client",
"specified",
"compression",
"type",
"or",
"default",
"compression",
"type",
"from",
"file",
"extension"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L544-L562 | train |
minio/mc | cmd/client-s3.go | Get | func (c *s3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
bucket, object := c.url2BucketAndObject()
opts := minio.GetObjectOptions{}
opts.ServerSideEncryption = sse
reader, e := c.api.GetObject(bucket, object, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "NoSuchBucket" {
return nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return nil, probe.NewError(ObjectMissing{})
}
return nil, probe.NewError(e)
}
return reader, nil
} | go | func (c *s3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
bucket, object := c.url2BucketAndObject()
opts := minio.GetObjectOptions{}
opts.ServerSideEncryption = sse
reader, e := c.api.GetObject(bucket, object, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "NoSuchBucket" {
return nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return nil, probe.NewError(ObjectMissing{})
}
return nil, probe.NewError(e)
}
return reader, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"Get",
"(",
"sse",
"encrypt",
".",
"ServerSide",
")",
"(",
"io",
".",
"ReadCloser",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"bucket",
",",
"object",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"... | // Get - get object with metadata. | [
"Get",
"-",
"get",
"object",
"with",
"metadata",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L707-L730 | train |
minio/mc | cmd/client-s3.go | Copy | func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
dstBucket, dstObject := c.url2BucketAndObject()
if dstBucket == "" {
return probe.NewError(BucketNameEmpty{})
}
tokens := splitStr(source, string(c.targetURL.Separator), 3)
// Source object
src := minio.NewSourceInfo(tokens[1], tokens[2], srcSSE)
// Destination object
dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtSSE, metadata)
if e != nil {
return probe.NewError(e)
}
if e = c.api.ComposeObjectWithProgress(dst, []minio.SourceInfo{src}, progress); e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
return probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "NoSuchBucket" {
return probe.NewError(BucketDoesNotExist{
Bucket: dstBucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return probe.NewError(BucketInvalid{
Bucket: dstBucket,
})
}
if errResponse.Code == "NoSuchKey" {
return probe.NewError(ObjectMissing{})
}
return probe.NewError(e)
}
return nil
} | go | func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
dstBucket, dstObject := c.url2BucketAndObject()
if dstBucket == "" {
return probe.NewError(BucketNameEmpty{})
}
tokens := splitStr(source, string(c.targetURL.Separator), 3)
// Source object
src := minio.NewSourceInfo(tokens[1], tokens[2], srcSSE)
// Destination object
dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtSSE, metadata)
if e != nil {
return probe.NewError(e)
}
if e = c.api.ComposeObjectWithProgress(dst, []minio.SourceInfo{src}, progress); e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
return probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "NoSuchBucket" {
return probe.NewError(BucketDoesNotExist{
Bucket: dstBucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return probe.NewError(BucketInvalid{
Bucket: dstBucket,
})
}
if errResponse.Code == "NoSuchKey" {
return probe.NewError(ObjectMissing{})
}
return probe.NewError(e)
}
return nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"Copy",
"(",
"source",
"string",
",",
"size",
"int64",
",",
"progress",
"io",
".",
"Reader",
",",
"srcSSE",
",",
"tgtSSE",
"encrypt",
".",
"ServerSide",
",",
"metadata",
"map",
"[",
"string",
"]",
"string",
")",
... | // Copy - copy object, uses server side copy API. Also uses an abstracted API
// such that large file sizes will be copied in multipart manner on server
// side. | [
"Copy",
"-",
"copy",
"object",
"uses",
"server",
"side",
"copy",
"API",
".",
"Also",
"uses",
"an",
"abstracted",
"API",
"such",
"that",
"large",
"file",
"sizes",
"will",
"be",
"copied",
"in",
"multipart",
"manner",
"on",
"server",
"side",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L735-L775 | train |
minio/mc | cmd/client-s3.go | Put | func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
bucket, object := c.url2BucketAndObject()
contentType, ok := metadata["Content-Type"]
if ok {
delete(metadata, "Content-Type")
} else {
// Set content-type if not specified.
contentType = "application/octet-stream"
}
cacheControl, ok := metadata["Cache-Control"]
if ok {
delete(metadata, "Cache-Control")
}
contentEncoding, ok := metadata["Content-Encoding"]
if ok {
delete(metadata, "Content-Encoding")
}
contentDisposition, ok := metadata["Content-Disposition"]
if ok {
delete(metadata, "Content-Disposition")
}
contentLanguage, ok := metadata["Content-Language"]
if ok {
delete(metadata, "Content-Language")
}
storageClass, ok := metadata["X-Amz-Storage-Class"]
if ok {
delete(metadata, "X-Amz-Storage-Class")
}
if bucket == "" {
return 0, probe.NewError(BucketNameEmpty{})
}
opts := minio.PutObjectOptions{
UserMetadata: metadata,
Progress: progress,
NumThreads: defaultMultipartThreadsNum,
ContentType: contentType,
CacheControl: cacheControl,
ContentDisposition: contentDisposition,
ContentEncoding: contentEncoding,
ContentLanguage: contentLanguage,
StorageClass: strings.ToUpper(storageClass),
ServerSideEncryption: sse,
}
n, e := c.api.PutObjectWithContext(ctx, bucket, object, reader, size, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
return n, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
if errResponse.Code == "AccessDenied" {
return n, probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return n, probe.NewError(ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "XMinioObjectExistsAsDirectory" {
return n, probe.NewError(ObjectAlreadyExistsAsDirectory{
Object: object,
})
}
if errResponse.Code == "NoSuchBucket" {
return n, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return n, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return n, probe.NewError(ObjectMissing{})
}
return n, probe.NewError(e)
}
return n, nil
} | go | func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
bucket, object := c.url2BucketAndObject()
contentType, ok := metadata["Content-Type"]
if ok {
delete(metadata, "Content-Type")
} else {
// Set content-type if not specified.
contentType = "application/octet-stream"
}
cacheControl, ok := metadata["Cache-Control"]
if ok {
delete(metadata, "Cache-Control")
}
contentEncoding, ok := metadata["Content-Encoding"]
if ok {
delete(metadata, "Content-Encoding")
}
contentDisposition, ok := metadata["Content-Disposition"]
if ok {
delete(metadata, "Content-Disposition")
}
contentLanguage, ok := metadata["Content-Language"]
if ok {
delete(metadata, "Content-Language")
}
storageClass, ok := metadata["X-Amz-Storage-Class"]
if ok {
delete(metadata, "X-Amz-Storage-Class")
}
if bucket == "" {
return 0, probe.NewError(BucketNameEmpty{})
}
opts := minio.PutObjectOptions{
UserMetadata: metadata,
Progress: progress,
NumThreads: defaultMultipartThreadsNum,
ContentType: contentType,
CacheControl: cacheControl,
ContentDisposition: contentDisposition,
ContentEncoding: contentEncoding,
ContentLanguage: contentLanguage,
StorageClass: strings.ToUpper(storageClass),
ServerSideEncryption: sse,
}
n, e := c.api.PutObjectWithContext(ctx, bucket, object, reader, size, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
return n, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
if errResponse.Code == "AccessDenied" {
return n, probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return n, probe.NewError(ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "XMinioObjectExistsAsDirectory" {
return n, probe.NewError(ObjectAlreadyExistsAsDirectory{
Object: object,
})
}
if errResponse.Code == "NoSuchBucket" {
return n, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return n, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return n, probe.NewError(ObjectMissing{})
}
return n, probe.NewError(e)
}
return n, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"reader",
"io",
".",
"Reader",
",",
"size",
"int64",
",",
"metadata",
"map",
"[",
"string",
"]",
"string",
",",
"progress",
"io",
".",
"Reader",
",",
"sse",
... | // Put - upload an object with custom metadata. | [
"Put",
"-",
"upload",
"an",
"object",
"with",
"custom",
"metadata",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L778-L867 | train |
minio/mc | cmd/client-s3.go | removeIncompleteObjects | func (c *s3Client) removeIncompleteObjects(bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError {
removeObjectErrorCh := make(chan minio.RemoveObjectError)
// Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any.
go func() {
defer close(removeObjectErrorCh)
for object := range objectsCh {
if err := c.api.RemoveIncompleteUpload(bucket, object); err != nil {
removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err}
}
}
}()
return removeObjectErrorCh
} | go | func (c *s3Client) removeIncompleteObjects(bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError {
removeObjectErrorCh := make(chan minio.RemoveObjectError)
// Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any.
go func() {
defer close(removeObjectErrorCh)
for object := range objectsCh {
if err := c.api.RemoveIncompleteUpload(bucket, object); err != nil {
removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err}
}
}
}()
return removeObjectErrorCh
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"removeIncompleteObjects",
"(",
"bucket",
"string",
",",
"objectsCh",
"<-",
"chan",
"string",
")",
"<-",
"chan",
"minio",
".",
"RemoveObjectError",
"{",
"removeObjectErrorCh",
":=",
"make",
"(",
"chan",
"minio",
".",
"... | // Remove incomplete uploads. | [
"Remove",
"incomplete",
"uploads",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L870-L885 | train |
minio/mc | cmd/client-s3.go | MakeBucket | func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
if object != "" {
if strings.HasSuffix(object, "/") {
retry:
if _, e := c.api.PutObject(bucket, object, bytes.NewReader([]byte("")), 0, minio.PutObjectOptions{}); e != nil {
switch minio.ToErrorResponse(e).Code {
case "NoSuchBucket":
e = c.api.MakeBucket(bucket, region)
if e != nil {
return probe.NewError(e)
}
goto retry
}
return probe.NewError(e)
}
return nil
}
return probe.NewError(BucketNameTopLevel{})
}
e := c.api.MakeBucket(bucket, region)
if e != nil {
// Ignore bucket already existing error when ignoreExisting flag is enabled
if ignoreExisting {
switch minio.ToErrorResponse(e).Code {
case "BucketAlreadyOwnedByYou":
fallthrough
case "BucketAlreadyExists":
return nil
}
}
return probe.NewError(e)
}
return nil
} | go | func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
if object != "" {
if strings.HasSuffix(object, "/") {
retry:
if _, e := c.api.PutObject(bucket, object, bytes.NewReader([]byte("")), 0, minio.PutObjectOptions{}); e != nil {
switch minio.ToErrorResponse(e).Code {
case "NoSuchBucket":
e = c.api.MakeBucket(bucket, region)
if e != nil {
return probe.NewError(e)
}
goto retry
}
return probe.NewError(e)
}
return nil
}
return probe.NewError(BucketNameTopLevel{})
}
e := c.api.MakeBucket(bucket, region)
if e != nil {
// Ignore bucket already existing error when ignoreExisting flag is enabled
if ignoreExisting {
switch minio.ToErrorResponse(e).Code {
case "BucketAlreadyOwnedByYou":
fallthrough
case "BucketAlreadyExists":
return nil
}
}
return probe.NewError(e)
}
return nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"MakeBucket",
"(",
"region",
"string",
",",
"ignoreExisting",
"bool",
")",
"*",
"probe",
".",
"Error",
"{",
"bucket",
",",
"object",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"if",
"bucket",
"==",
"\... | // MakeBucket - make a new bucket. | [
"MakeBucket",
"-",
"make",
"a",
"new",
"bucket",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L984-L1022 | train |
minio/mc | cmd/client-s3.go | GetAccessRules | func (c *s3Client) GetAccessRules() (map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return map[string]string{}, probe.NewError(BucketNameEmpty{})
}
policies := map[string]string{}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return nil, probe.NewError(e)
}
if policyStr == "" {
return policies, nil
}
var p policy.BucketAccessPolicy
if e = json.Unmarshal([]byte(policyStr), &p); e != nil {
return nil, probe.NewError(e)
}
policyRules := policy.GetPolicies(p.Statements, bucket, object)
// Hide policy data structure at this level
for k, v := range policyRules {
policies[k] = string(v)
}
return policies, nil
} | go | func (c *s3Client) GetAccessRules() (map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return map[string]string{}, probe.NewError(BucketNameEmpty{})
}
policies := map[string]string{}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return nil, probe.NewError(e)
}
if policyStr == "" {
return policies, nil
}
var p policy.BucketAccessPolicy
if e = json.Unmarshal([]byte(policyStr), &p); e != nil {
return nil, probe.NewError(e)
}
policyRules := policy.GetPolicies(p.Statements, bucket, object)
// Hide policy data structure at this level
for k, v := range policyRules {
policies[k] = string(v)
}
return policies, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"GetAccessRules",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"bucket",
",",
"object",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"if",
"bucket",
... | // GetAccessRules - get configured policies from the server | [
"GetAccessRules",
"-",
"get",
"configured",
"policies",
"from",
"the",
"server"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1025-L1048 | train |
minio/mc | cmd/client-s3.go | GetAccess | func (c *s3Client) GetAccess() (string, string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return "", "", probe.NewError(BucketNameEmpty{})
}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return "", "", probe.NewError(e)
}
if policyStr == "" {
return string(policy.BucketPolicyNone), policyStr, nil
}
var p policy.BucketAccessPolicy
if e = json.Unmarshal([]byte(policyStr), &p); e != nil {
return "", "", probe.NewError(e)
}
pType := string(policy.GetPolicy(p.Statements, bucket, object))
if pType == string(policy.BucketPolicyNone) && policyStr != "" {
pType = "custom"
}
return pType, policyStr, nil
} | go | func (c *s3Client) GetAccess() (string, string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return "", "", probe.NewError(BucketNameEmpty{})
}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return "", "", probe.NewError(e)
}
if policyStr == "" {
return string(policy.BucketPolicyNone), policyStr, nil
}
var p policy.BucketAccessPolicy
if e = json.Unmarshal([]byte(policyStr), &p); e != nil {
return "", "", probe.NewError(e)
}
pType := string(policy.GetPolicy(p.Statements, bucket, object))
if pType == string(policy.BucketPolicyNone) && policyStr != "" {
pType = "custom"
}
return pType, policyStr, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"GetAccess",
"(",
")",
"(",
"string",
",",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"bucket",
",",
"object",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"if",
"bucket",
"==",
"\"\"",
"{... | // GetAccess get access policy permissions. | [
"GetAccess",
"get",
"access",
"policy",
"permissions",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1051-L1072 | train |
minio/mc | cmd/client-s3.go | SetAccess | func (c *s3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
if isJSON {
if e := c.api.SetBucketPolicy(bucket, bucketPolicy); e != nil {
return probe.NewError(e)
}
return nil
}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return probe.NewError(e)
}
var p = policy.BucketAccessPolicy{Version: "2012-10-17"}
if policyStr != "" {
if e = json.Unmarshal([]byte(policyStr), &p); e != nil {
return probe.NewError(e)
}
}
p.Statements = policy.SetPolicy(p.Statements, policy.BucketPolicy(bucketPolicy), bucket, object)
if len(p.Statements) == 0 {
if e = c.api.SetBucketPolicy(bucket, ""); e != nil {
return probe.NewError(e)
}
return nil
}
policyB, e := json.Marshal(p)
if e != nil {
return probe.NewError(e)
}
if e = c.api.SetBucketPolicy(bucket, string(policyB)); e != nil {
return probe.NewError(e)
}
return nil
} | go | func (c *s3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
if isJSON {
if e := c.api.SetBucketPolicy(bucket, bucketPolicy); e != nil {
return probe.NewError(e)
}
return nil
}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return probe.NewError(e)
}
var p = policy.BucketAccessPolicy{Version: "2012-10-17"}
if policyStr != "" {
if e = json.Unmarshal([]byte(policyStr), &p); e != nil {
return probe.NewError(e)
}
}
p.Statements = policy.SetPolicy(p.Statements, policy.BucketPolicy(bucketPolicy), bucket, object)
if len(p.Statements) == 0 {
if e = c.api.SetBucketPolicy(bucket, ""); e != nil {
return probe.NewError(e)
}
return nil
}
policyB, e := json.Marshal(p)
if e != nil {
return probe.NewError(e)
}
if e = c.api.SetBucketPolicy(bucket, string(policyB)); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"SetAccess",
"(",
"bucketPolicy",
"string",
",",
"isJSON",
"bool",
")",
"*",
"probe",
".",
"Error",
"{",
"bucket",
",",
"object",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"if",
"bucket",
"==",
"\"\"... | // SetAccess set access policy permissions. | [
"SetAccess",
"set",
"access",
"policy",
"permissions",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1075-L1111 | train |
minio/mc | cmd/client-s3.go | listObjectWrapper | func (c *s3Client) listObjectWrapper(bucket, object string, isRecursive bool, doneCh chan struct{}) <-chan minio.ObjectInfo {
if isAmazon(c.targetURL.Host) || isAmazonAccelerated(c.targetURL.Host) {
return c.api.ListObjectsV2(bucket, object, isRecursive, doneCh)
}
return c.api.ListObjects(bucket, object, isRecursive, doneCh)
} | go | func (c *s3Client) listObjectWrapper(bucket, object string, isRecursive bool, doneCh chan struct{}) <-chan minio.ObjectInfo {
if isAmazon(c.targetURL.Host) || isAmazonAccelerated(c.targetURL.Host) {
return c.api.ListObjectsV2(bucket, object, isRecursive, doneCh)
}
return c.api.ListObjects(bucket, object, isRecursive, doneCh)
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"listObjectWrapper",
"(",
"bucket",
",",
"object",
"string",
",",
"isRecursive",
"bool",
",",
"doneCh",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"minio",
".",
"ObjectInfo",
"{",
"if",
"isAmazon",
"(",
"c",
... | // listObjectWrapper - select ObjectList version depending on the target hostname | [
"listObjectWrapper",
"-",
"select",
"ObjectList",
"version",
"depending",
"on",
"the",
"target",
"hostname"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1114-L1119 | train |
minio/mc | cmd/client-s3.go | getObjectStat | func (c *s3Client) getObjectStat(bucket, object string, opts minio.StatObjectOptions) (*clientContent, *probe.Error) {
objectMetadata := &clientContent{}
objectStat, e := c.api.StatObject(bucket, object, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()})
}
if errResponse.Code == "NoSuchBucket" {
return nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return nil, probe.NewError(ObjectMissing{})
}
return nil, probe.NewError(e)
}
objectMetadata.URL = *c.targetURL
objectMetadata.Time = objectStat.LastModified
objectMetadata.Size = objectStat.Size
objectMetadata.ETag = objectStat.ETag
objectMetadata.Expires = objectStat.Expires
objectMetadata.Type = os.FileMode(0664)
objectMetadata.Metadata = map[string]string{}
objectMetadata.EncryptionHeaders = map[string]string{}
objectMetadata.Metadata["Content-Type"] = objectStat.ContentType
for k, v := range objectStat.Metadata {
isCSEHeader := false
for _, header := range cseHeaders {
if (strings.Compare(strings.ToLower(header), strings.ToLower(k)) == 0) ||
strings.HasPrefix(strings.ToLower(serverEncryptionKeyPrefix), strings.ToLower(k)) {
if len(v) > 0 {
objectMetadata.EncryptionHeaders[k] = v[0]
}
isCSEHeader = true
break
}
}
if !isCSEHeader {
if len(v) > 0 {
objectMetadata.Metadata[k] = v[0]
}
}
}
objectMetadata.ETag = objectStat.ETag
return objectMetadata, nil
} | go | func (c *s3Client) getObjectStat(bucket, object string, opts minio.StatObjectOptions) (*clientContent, *probe.Error) {
objectMetadata := &clientContent{}
objectStat, e := c.api.StatObject(bucket, object, opts)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()})
}
if errResponse.Code == "NoSuchBucket" {
return nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return nil, probe.NewError(ObjectMissing{})
}
return nil, probe.NewError(e)
}
objectMetadata.URL = *c.targetURL
objectMetadata.Time = objectStat.LastModified
objectMetadata.Size = objectStat.Size
objectMetadata.ETag = objectStat.ETag
objectMetadata.Expires = objectStat.Expires
objectMetadata.Type = os.FileMode(0664)
objectMetadata.Metadata = map[string]string{}
objectMetadata.EncryptionHeaders = map[string]string{}
objectMetadata.Metadata["Content-Type"] = objectStat.ContentType
for k, v := range objectStat.Metadata {
isCSEHeader := false
for _, header := range cseHeaders {
if (strings.Compare(strings.ToLower(header), strings.ToLower(k)) == 0) ||
strings.HasPrefix(strings.ToLower(serverEncryptionKeyPrefix), strings.ToLower(k)) {
if len(v) > 0 {
objectMetadata.EncryptionHeaders[k] = v[0]
}
isCSEHeader = true
break
}
}
if !isCSEHeader {
if len(v) > 0 {
objectMetadata.Metadata[k] = v[0]
}
}
}
objectMetadata.ETag = objectStat.ETag
return objectMetadata, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"getObjectStat",
"(",
"bucket",
",",
"object",
"string",
",",
"opts",
"minio",
".",
"StatObjectOptions",
")",
"(",
"*",
"clientContent",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"objectMetadata",
":=",
"&",
"clie... | // getObjectStat returns the metadata of an object from a HEAD call. | [
"getObjectStat",
"returns",
"the",
"metadata",
"of",
"an",
"object",
"from",
"a",
"HEAD",
"call",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1229-L1281 | train |
minio/mc | cmd/client-s3.go | url2BucketAndObject | func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
path := c.targetURL.Path
// Convert any virtual host styled requests.
//
// For the time being this check is introduced for S3,
// If you have custom virtual styled hosts please.
// List them below.
if c.virtualStyle {
var bucket string
hostIndex := strings.Index(c.targetURL.Host, "s3")
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate")
}
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
}
if hostIndex > 0 {
bucket = c.targetURL.Host[:hostIndex-1]
path = string(c.targetURL.Separator) + bucket + c.targetURL.Path
}
}
tokens := splitStr(path, string(c.targetURL.Separator), 3)
return tokens[1], tokens[2]
} | go | func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
path := c.targetURL.Path
// Convert any virtual host styled requests.
//
// For the time being this check is introduced for S3,
// If you have custom virtual styled hosts please.
// List them below.
if c.virtualStyle {
var bucket string
hostIndex := strings.Index(c.targetURL.Host, "s3")
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate")
}
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
}
if hostIndex > 0 {
bucket = c.targetURL.Host[:hostIndex-1]
path = string(c.targetURL.Separator) + bucket + c.targetURL.Path
}
}
tokens := splitStr(path, string(c.targetURL.Separator), 3)
return tokens[1], tokens[2]
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"url2BucketAndObject",
"(",
")",
"(",
"bucketName",
",",
"objectName",
"string",
")",
"{",
"path",
":=",
"c",
".",
"targetURL",
".",
"Path",
"\n",
"if",
"c",
".",
"virtualStyle",
"{",
"var",
"bucket",
"string",
"... | // url2BucketAndObject gives bucketName and objectName from URL path. | [
"url2BucketAndObject",
"gives",
"bucketName",
"and",
"objectName",
"from",
"URL",
"path",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1317-L1340 | train |
minio/mc | cmd/client-s3.go | splitPath | func (c *s3Client) splitPath(path string) (bucketName, objectName string) {
path = strings.TrimPrefix(path, string(c.targetURL.Separator))
// Handle path if its virtual style.
if c.virtualStyle {
hostIndex := strings.Index(c.targetURL.Host, "s3")
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate")
}
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
}
if hostIndex > 0 {
bucketName = c.targetURL.Host[:hostIndex-1]
objectName = path
return bucketName, objectName
}
}
tokens := splitStr(path, string(c.targetURL.Separator), 2)
return tokens[0], tokens[1]
} | go | func (c *s3Client) splitPath(path string) (bucketName, objectName string) {
path = strings.TrimPrefix(path, string(c.targetURL.Separator))
// Handle path if its virtual style.
if c.virtualStyle {
hostIndex := strings.Index(c.targetURL.Host, "s3")
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate")
}
if hostIndex == -1 {
hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis")
}
if hostIndex > 0 {
bucketName = c.targetURL.Host[:hostIndex-1]
objectName = path
return bucketName, objectName
}
}
tokens := splitStr(path, string(c.targetURL.Separator), 2)
return tokens[0], tokens[1]
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"splitPath",
"(",
"path",
"string",
")",
"(",
"bucketName",
",",
"objectName",
"string",
")",
"{",
"path",
"=",
"strings",
".",
"TrimPrefix",
"(",
"path",
",",
"string",
"(",
"c",
".",
"targetURL",
".",
"Separato... | // splitPath split path into bucket and object. | [
"splitPath",
"split",
"path",
"into",
"bucket",
"and",
"object",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1343-L1364 | train |
minio/mc | cmd/client-s3.go | objectMultipartInfo2ClientContent | func (c *s3Client) objectMultipartInfo2ClientContent(bucket string, entry minio.ObjectMultipartInfo) clientContent {
content := clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = c.joinPath(bucket, entry.Key)
content.URL = url
content.Size = entry.Size
content.Time = entry.Initiated
if strings.HasSuffix(entry.Key, "/") {
content.Type = os.ModeDir
} else {
content.Type = os.ModeTemporary
}
return content
} | go | func (c *s3Client) objectMultipartInfo2ClientContent(bucket string, entry minio.ObjectMultipartInfo) clientContent {
content := clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = c.joinPath(bucket, entry.Key)
content.URL = url
content.Size = entry.Size
content.Time = entry.Initiated
if strings.HasSuffix(entry.Key, "/") {
content.Type = os.ModeDir
} else {
content.Type = os.ModeTemporary
}
return content
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"objectMultipartInfo2ClientContent",
"(",
"bucket",
"string",
",",
"entry",
"minio",
".",
"ObjectMultipartInfo",
")",
"clientContent",
"{",
"content",
":=",
"clientContent",
"{",
"}",
"\n",
"url",
":=",
"*",
"c",
".",
... | // Convert objectMultipartInfo to clientContent | [
"Convert",
"objectMultipartInfo",
"to",
"clientContent"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1525-L1542 | train |
minio/mc | cmd/client-s3.go | joinPath | func (c *s3Client) joinPath(bucket string, objects ...string) string {
p := string(c.targetURL.Separator) + bucket
for _, o := range objects {
p += string(c.targetURL.Separator) + o
}
return p
} | go | func (c *s3Client) joinPath(bucket string, objects ...string) string {
p := string(c.targetURL.Separator) + bucket
for _, o := range objects {
p += string(c.targetURL.Separator) + o
}
return p
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"joinPath",
"(",
"bucket",
"string",
",",
"objects",
"...",
"string",
")",
"string",
"{",
"p",
":=",
"string",
"(",
"c",
".",
"targetURL",
".",
"Separator",
")",
"+",
"bucket",
"\n",
"for",
"_",
",",
"o",
":=... | // Returns new path by joining path segments with URL path separator. | [
"Returns",
"new",
"path",
"by",
"joining",
"path",
"segments",
"with",
"URL",
"path",
"separator",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1643-L1649 | train |
minio/mc | cmd/client-s3.go | objectInfo2ClientContent | func (c *s3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInfo) clientContent {
content := clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = c.joinPath(bucket, entry.Key)
content.URL = url
content.Size = entry.Size
content.ETag = entry.ETag
content.Time = entry.LastModified
if strings.HasSuffix(entry.Key, "/") && entry.Size == 0 && entry.LastModified.IsZero() {
content.Type = os.ModeDir
} else {
content.Type = os.FileMode(0664)
}
return content
} | go | func (c *s3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInfo) clientContent {
content := clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = c.joinPath(bucket, entry.Key)
content.URL = url
content.Size = entry.Size
content.ETag = entry.ETag
content.Time = entry.LastModified
if strings.HasSuffix(entry.Key, "/") && entry.Size == 0 && entry.LastModified.IsZero() {
content.Type = os.ModeDir
} else {
content.Type = os.FileMode(0664)
}
return content
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"objectInfo2ClientContent",
"(",
"bucket",
"string",
",",
"entry",
"minio",
".",
"ObjectInfo",
")",
"clientContent",
"{",
"content",
":=",
"clientContent",
"{",
"}",
"\n",
"url",
":=",
"*",
"c",
".",
"targetURL",
"\n... | // Convert objectInfo to clientContent | [
"Convert",
"objectInfo",
"to",
"clientContent"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1652-L1670 | train |
minio/mc | cmd/client-s3.go | bucketStat | func (c *s3Client) bucketStat(bucket string) (*clientContent, *probe.Error) {
exists, e := c.api.BucketExists(bucket)
if e != nil {
return nil, probe.NewError(e)
}
if !exists {
return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket})
}
return &clientContent{URL: *c.targetURL, Time: time.Unix(0, 0), Type: os.ModeDir}, nil
} | go | func (c *s3Client) bucketStat(bucket string) (*clientContent, *probe.Error) {
exists, e := c.api.BucketExists(bucket)
if e != nil {
return nil, probe.NewError(e)
}
if !exists {
return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket})
}
return &clientContent{URL: *c.targetURL, Time: time.Unix(0, 0), Type: os.ModeDir}, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"bucketStat",
"(",
"bucket",
"string",
")",
"(",
"*",
"clientContent",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"exists",
",",
"e",
":=",
"c",
".",
"api",
".",
"BucketExists",
"(",
"bucket",
")",
"\n",
"if"... | // Returns bucket stat info of current bucket. | [
"Returns",
"bucket",
"stat",
"info",
"of",
"current",
"bucket",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1673-L1682 | train |
minio/mc | cmd/client-s3.go | ShareDownload | func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
// No additional request parameters are set for the time being.
reqParams := make(url.Values)
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires, reqParams)
if e != nil {
return "", probe.NewError(e)
}
return presignedURL.String(), nil
} | go | func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
// No additional request parameters are set for the time being.
reqParams := make(url.Values)
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires, reqParams)
if e != nil {
return "", probe.NewError(e)
}
return presignedURL.String(), nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"ShareDownload",
"(",
"expires",
"time",
".",
"Duration",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"bucket",
",",
"object",
":=",
"c",
".",
"url2BucketAndObject",
"(",
")",
"\n",
"reqParams"... | // ShareDownload - get a usable presigned object url to share. | [
"ShareDownload",
"-",
"get",
"a",
"usable",
"presigned",
"object",
"url",
"to",
"share",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1926-L1935 | train |
minio/mc | cmd/client-s3.go | ShareUpload | func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
if e := p.SetExpires(UTCNow().Add(expires)); e != nil {
return "", nil, probe.NewError(e)
}
if strings.TrimSpace(contentType) != "" || contentType != "" {
// No need to verify for error here, since we have stripped out spaces.
p.SetContentType(contentType)
}
if e := p.SetBucket(bucket); e != nil {
return "", nil, probe.NewError(e)
}
if isRecursive {
if e := p.SetKeyStartsWith(object); e != nil {
return "", nil, probe.NewError(e)
}
} else {
if e := p.SetKey(object); e != nil {
return "", nil, probe.NewError(e)
}
}
u, m, e := c.api.PresignedPostPolicy(p)
if e != nil {
return "", nil, probe.NewError(e)
}
return u.String(), m, nil
} | go | func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
if e := p.SetExpires(UTCNow().Add(expires)); e != nil {
return "", nil, probe.NewError(e)
}
if strings.TrimSpace(contentType) != "" || contentType != "" {
// No need to verify for error here, since we have stripped out spaces.
p.SetContentType(contentType)
}
if e := p.SetBucket(bucket); e != nil {
return "", nil, probe.NewError(e)
}
if isRecursive {
if e := p.SetKeyStartsWith(object); e != nil {
return "", nil, probe.NewError(e)
}
} else {
if e := p.SetKey(object); e != nil {
return "", nil, probe.NewError(e)
}
}
u, m, e := c.api.PresignedPostPolicy(p)
if e != nil {
return "", nil, probe.NewError(e)
}
return u.String(), m, nil
} | [
"func",
"(",
"c",
"*",
"s3Client",
")",
"ShareUpload",
"(",
"isRecursive",
"bool",
",",
"expires",
"time",
".",
"Duration",
",",
"contentType",
"string",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")"... | // ShareUpload - get data for presigned post http form upload. | [
"ShareUpload",
"-",
"get",
"data",
"for",
"presigned",
"post",
"http",
"form",
"upload",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1938-L1965 | train |
minio/mc | cmd/admin-top-locks.go | String | func (u lockMessage) String() string {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
return console.Colorize(lockState, newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
} | go | func (u lockMessage) String() string {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
return console.Colorize(lockState, newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
} | [
"func",
"(",
"u",
"lockMessage",
")",
"String",
"(",
")",
"string",
"{",
"timeFieldMaxLen",
":=",
"20",
"\n",
"resourceFieldMaxLen",
":=",
"-",
"1",
"\n",
"typeFieldMaxLen",
":=",
"6",
"\n",
"ownerFieldMaxLen",
":=",
"20",
"\n",
"lockState",
",",
"timeDiff",... | // String colorized oldest locks message. | [
"String",
"colorized",
"oldest",
"locks",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-top-locks.go#L75-L88 | train |
minio/mc | cmd/admin-top-locks.go | checkAdminTopLocksSyntax | func checkAdminTopLocksSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "locks", 1) // last argument is exit code
}
} | go | func checkAdminTopLocksSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "locks", 1) // last argument is exit code
}
} | [
"func",
"checkAdminTopLocksSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"1",
"{",
"cli",
".",
"ShowCommandHelp... | // checkAdminTopLocksSyntax - validate all the passed arguments | [
"checkAdminTopLocksSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-top-locks.go#L99-L103 | train |
minio/mc | cmd/admin-top-locks.go | printLocks | func printLocks(locks madmin.LockEntries) {
if !globalJSON {
printHeaders()
}
for _, entry := range locks {
printMsg(lockMessage{Lock: entry})
}
} | go | func printLocks(locks madmin.LockEntries) {
if !globalJSON {
printHeaders()
}
for _, entry := range locks {
printMsg(lockMessage{Lock: entry})
}
} | [
"func",
"printLocks",
"(",
"locks",
"madmin",
".",
"LockEntries",
")",
"{",
"if",
"!",
"globalJSON",
"{",
"printHeaders",
"(",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"locks",
"{",
"printMsg",
"(",
"lockMessage",
"{",
"Lock",
":"... | // Prints oldest locks. | [
"Prints",
"oldest",
"locks",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-top-locks.go#L144-L151 | train |
minio/mc | cmd/watch.go | NewWatcher | func NewWatcher(sessionStartTime time.Time) *Watcher {
return &Watcher{
sessionStartTime: sessionStartTime,
errorChan: make(chan *probe.Error),
eventInfoChan: make(chan EventInfo),
o: []*watchObject{},
}
} | go | func NewWatcher(sessionStartTime time.Time) *Watcher {
return &Watcher{
sessionStartTime: sessionStartTime,
errorChan: make(chan *probe.Error),
eventInfoChan: make(chan EventInfo),
o: []*watchObject{},
}
} | [
"func",
"NewWatcher",
"(",
"sessionStartTime",
"time",
".",
"Time",
")",
"*",
"Watcher",
"{",
"return",
"&",
"Watcher",
"{",
"sessionStartTime",
":",
"sessionStartTime",
",",
"errorChan",
":",
"make",
"(",
"chan",
"*",
"probe",
".",
"Error",
")",
",",
"eve... | // NewWatcher creates a new watcher | [
"NewWatcher",
"creates",
"a",
"new",
"watcher"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/watch.go#L102-L109 | train |
minio/mc | cmd/watch.go | Join | func (w *Watcher) Join(client Client, recursive bool) *probe.Error {
wo, err := client.Watch(watchParams{
recursive: recursive,
events: []string{"put", "delete"},
})
if err != nil {
return err
}
w.o = append(w.o, wo)
// join monitoring waitgroup
w.wg.Add(1)
// wait for events and errors of individual client watchers
// and sent then to eventsChan and errorsChan
go func() {
defer w.wg.Done()
for {
select {
case event, ok := <-wo.Events():
if !ok {
return
}
w.eventInfoChan <- event
case err, ok := <-wo.Errors():
if !ok {
return
}
w.errorChan <- err
}
}
}()
return nil
} | go | func (w *Watcher) Join(client Client, recursive bool) *probe.Error {
wo, err := client.Watch(watchParams{
recursive: recursive,
events: []string{"put", "delete"},
})
if err != nil {
return err
}
w.o = append(w.o, wo)
// join monitoring waitgroup
w.wg.Add(1)
// wait for events and errors of individual client watchers
// and sent then to eventsChan and errorsChan
go func() {
defer w.wg.Done()
for {
select {
case event, ok := <-wo.Events():
if !ok {
return
}
w.eventInfoChan <- event
case err, ok := <-wo.Errors():
if !ok {
return
}
w.errorChan <- err
}
}
}()
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Join",
"(",
"client",
"Client",
",",
"recursive",
"bool",
")",
"*",
"probe",
".",
"Error",
"{",
"wo",
",",
"err",
":=",
"client",
".",
"Watch",
"(",
"watchParams",
"{",
"recursive",
":",
"recursive",
",",
"even... | // Join the watcher with client | [
"Join",
"the",
"watcher",
"with",
"client"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/watch.go#L145-L183 | train |
boombuler/barcode | code39/encoder.go | Encode | func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.BarcodeIntCS, error) {
if fullASCIIMode {
var err error
content, err = prepare(content)
if err != nil {
return nil, err
}
} else if strings.ContainsRune(content, '*') {
return nil, errors.New("invalid data! try full ascii mode")
}
data := "*" + content
if includeChecksum {
data += getChecksum(content)
}
data += "*"
result := new(utils.BitList)
for i, r := range data {
if i != 0 {
result.AddBit(false)
}
info, ok := encodeTable[r]
if !ok {
return nil, errors.New("invalid data! try full ascii mode")
}
result.AddBit(info.data...)
}
checkSum, err := strconv.ParseInt(getChecksum(content), 10, 64)
if err != nil {
checkSum = 0
}
return utils.New1DCodeIntCheckSum(barcode.TypeCode39, content, result, int(checkSum)), nil
} | go | func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.BarcodeIntCS, error) {
if fullASCIIMode {
var err error
content, err = prepare(content)
if err != nil {
return nil, err
}
} else if strings.ContainsRune(content, '*') {
return nil, errors.New("invalid data! try full ascii mode")
}
data := "*" + content
if includeChecksum {
data += getChecksum(content)
}
data += "*"
result := new(utils.BitList)
for i, r := range data {
if i != 0 {
result.AddBit(false)
}
info, ok := encodeTable[r]
if !ok {
return nil, errors.New("invalid data! try full ascii mode")
}
result.AddBit(info.data...)
}
checkSum, err := strconv.ParseInt(getChecksum(content), 10, 64)
if err != nil {
checkSum = 0
}
return utils.New1DCodeIntCheckSum(barcode.TypeCode39, content, result, int(checkSum)), nil
} | [
"func",
"Encode",
"(",
"content",
"string",
",",
"includeChecksum",
"bool",
",",
"fullASCIIMode",
"bool",
")",
"(",
"barcode",
".",
"BarcodeIntCS",
",",
"error",
")",
"{",
"if",
"fullASCIIMode",
"{",
"var",
"err",
"error",
"\n",
"content",
",",
"err",
"=",... | // Encode returns a code39 barcode for the given content
// if includeChecksum is set to true, a checksum character is calculated and added to the content | [
"Encode",
"returns",
"a",
"code39",
"barcode",
"for",
"the",
"given",
"content",
"if",
"includeChecksum",
"is",
"set",
"to",
"true",
"a",
"checksum",
"character",
"is",
"calculated",
"and",
"added",
"to",
"the",
"content"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/code39/encoder.go#L116-L152 | train |
boombuler/barcode | utils/galoisfield.go | NewGaloisField | func NewGaloisField(pp, fieldSize, b int) *GaloisField {
result := new(GaloisField)
result.Size = fieldSize
result.Base = b
result.ALogTbl = make([]int, fieldSize)
result.LogTbl = make([]int, fieldSize)
x := 1
for i := 0; i < fieldSize; i++ {
result.ALogTbl[i] = x
x = x * 2
if x >= fieldSize {
x = (x ^ pp) & (fieldSize - 1)
}
}
for i := 0; i < fieldSize; i++ {
result.LogTbl[result.ALogTbl[i]] = int(i)
}
return result
} | go | func NewGaloisField(pp, fieldSize, b int) *GaloisField {
result := new(GaloisField)
result.Size = fieldSize
result.Base = b
result.ALogTbl = make([]int, fieldSize)
result.LogTbl = make([]int, fieldSize)
x := 1
for i := 0; i < fieldSize; i++ {
result.ALogTbl[i] = x
x = x * 2
if x >= fieldSize {
x = (x ^ pp) & (fieldSize - 1)
}
}
for i := 0; i < fieldSize; i++ {
result.LogTbl[result.ALogTbl[i]] = int(i)
}
return result
} | [
"func",
"NewGaloisField",
"(",
"pp",
",",
"fieldSize",
",",
"b",
"int",
")",
"*",
"GaloisField",
"{",
"result",
":=",
"new",
"(",
"GaloisField",
")",
"\n",
"result",
".",
"Size",
"=",
"fieldSize",
"\n",
"result",
".",
"Base",
"=",
"b",
"\n",
"result",
... | // NewGaloisField creates a new galois field | [
"NewGaloisField",
"creates",
"a",
"new",
"galois",
"field"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/galoisfield.go#L12-L34 | train |
boombuler/barcode | utils/galoisfield.go | Multiply | func (gf *GaloisField) Multiply(a, b int) int {
if a == 0 || b == 0 {
return 0
}
return gf.ALogTbl[(gf.LogTbl[a]+gf.LogTbl[b])%(gf.Size-1)]
} | go | func (gf *GaloisField) Multiply(a, b int) int {
if a == 0 || b == 0 {
return 0
}
return gf.ALogTbl[(gf.LogTbl[a]+gf.LogTbl[b])%(gf.Size-1)]
} | [
"func",
"(",
"gf",
"*",
"GaloisField",
")",
"Multiply",
"(",
"a",
",",
"b",
"int",
")",
"int",
"{",
"if",
"a",
"==",
"0",
"||",
"b",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"gf",
".",
"ALogTbl",
"[",
"(",
"gf",
".",
"LogTbl"... | // Multiply multiplys two numbers | [
"Multiply",
"multiplys",
"two",
"numbers"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/galoisfield.go#L46-L51 | train |
boombuler/barcode | utils/galoisfield.go | Divide | func (gf *GaloisField) Divide(a, b int) int {
if b == 0 {
panic("divide by zero")
} else if a == 0 {
return 0
}
return gf.ALogTbl[(gf.LogTbl[a]-gf.LogTbl[b])%(gf.Size-1)]
} | go | func (gf *GaloisField) Divide(a, b int) int {
if b == 0 {
panic("divide by zero")
} else if a == 0 {
return 0
}
return gf.ALogTbl[(gf.LogTbl[a]-gf.LogTbl[b])%(gf.Size-1)]
} | [
"func",
"(",
"gf",
"*",
"GaloisField",
")",
"Divide",
"(",
"a",
",",
"b",
"int",
")",
"int",
"{",
"if",
"b",
"==",
"0",
"{",
"panic",
"(",
"\"divide by zero\"",
")",
"\n",
"}",
"else",
"if",
"a",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
... | // Divide divides two numbers | [
"Divide",
"divides",
"two",
"numbers"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/galoisfield.go#L54-L61 | train |
boombuler/barcode | utils/gfpoly.go | GetCoefficient | func (gp *GFPoly) GetCoefficient(degree int) int {
return gp.Coefficients[gp.Degree()-degree]
} | go | func (gp *GFPoly) GetCoefficient(degree int) int {
return gp.Coefficients[gp.Degree()-degree]
} | [
"func",
"(",
"gp",
"*",
"GFPoly",
")",
"GetCoefficient",
"(",
"degree",
"int",
")",
"int",
"{",
"return",
"gp",
".",
"Coefficients",
"[",
"gp",
".",
"Degree",
"(",
")",
"-",
"degree",
"]",
"\n",
"}"
] | // GetCoefficient returns the coefficient of x ^ degree | [
"GetCoefficient",
"returns",
"the",
"coefficient",
"of",
"x",
"^",
"degree"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/gfpoly.go#L17-L19 | train |
boombuler/barcode | utils/base1dcode.go | New1DCodeIntCheckSum | func New1DCodeIntCheckSum(codeKind, content string, bars *BitList, checksum int) barcode.BarcodeIntCS {
return &base1DCodeIntCS{base1DCode{bars, codeKind, content}, checksum}
} | go | func New1DCodeIntCheckSum(codeKind, content string, bars *BitList, checksum int) barcode.BarcodeIntCS {
return &base1DCodeIntCS{base1DCode{bars, codeKind, content}, checksum}
} | [
"func",
"New1DCodeIntCheckSum",
"(",
"codeKind",
",",
"content",
"string",
",",
"bars",
"*",
"BitList",
",",
"checksum",
"int",
")",
"barcode",
".",
"BarcodeIntCS",
"{",
"return",
"&",
"base1DCodeIntCS",
"{",
"base1DCode",
"{",
"bars",
",",
"codeKind",
",",
... | // New1DCodeIntCheckSum creates a new 1D barcode where the bars are represented by the bits in the bars BitList | [
"New1DCodeIntCheckSum",
"creates",
"a",
"new",
"1D",
"barcode",
"where",
"the",
"bars",
"are",
"represented",
"by",
"the",
"bits",
"in",
"the",
"bars",
"BitList"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/base1dcode.go#L50-L52 | train |
boombuler/barcode | utils/base1dcode.go | New1DCode | func New1DCode(codeKind, content string, bars *BitList) barcode.Barcode {
return &base1DCode{bars, codeKind, content}
} | go | func New1DCode(codeKind, content string, bars *BitList) barcode.Barcode {
return &base1DCode{bars, codeKind, content}
} | [
"func",
"New1DCode",
"(",
"codeKind",
",",
"content",
"string",
",",
"bars",
"*",
"BitList",
")",
"barcode",
".",
"Barcode",
"{",
"return",
"&",
"base1DCode",
"{",
"bars",
",",
"codeKind",
",",
"content",
"}",
"\n",
"}"
] | // New1DCode creates a new 1D barcode where the bars are represented by the bits in the bars BitList | [
"New1DCode",
"creates",
"a",
"new",
"1D",
"barcode",
"where",
"the",
"bars",
"are",
"represented",
"by",
"the",
"bits",
"in",
"the",
"bars",
"BitList"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/base1dcode.go#L55-L57 | train |
boombuler/barcode | code128/encode.go | Encode | func Encode(content string) (barcode.BarcodeIntCS, error) {
contentRunes := strToRunes(content)
if len(contentRunes) <= 0 || len(contentRunes) > 80 {
return nil, fmt.Errorf("content length should be between 1 and 80 runes but got %d", len(contentRunes))
}
idxList := getCodeIndexList(contentRunes)
if idxList == nil {
return nil, fmt.Errorf("\"%s\" could not be encoded", content)
}
result := new(utils.BitList)
sum := 0
for i, idx := range idxList.GetBytes() {
if i == 0 {
sum = int(idx)
} else {
sum += i * int(idx)
}
result.AddBit(encodingTable[idx]...)
}
sum = sum % 103
result.AddBit(encodingTable[sum]...)
result.AddBit(encodingTable[stopSymbol]...)
return utils.New1DCodeIntCheckSum(barcode.TypeCode128, content, result, sum), nil
} | go | func Encode(content string) (barcode.BarcodeIntCS, error) {
contentRunes := strToRunes(content)
if len(contentRunes) <= 0 || len(contentRunes) > 80 {
return nil, fmt.Errorf("content length should be between 1 and 80 runes but got %d", len(contentRunes))
}
idxList := getCodeIndexList(contentRunes)
if idxList == nil {
return nil, fmt.Errorf("\"%s\" could not be encoded", content)
}
result := new(utils.BitList)
sum := 0
for i, idx := range idxList.GetBytes() {
if i == 0 {
sum = int(idx)
} else {
sum += i * int(idx)
}
result.AddBit(encodingTable[idx]...)
}
sum = sum % 103
result.AddBit(encodingTable[sum]...)
result.AddBit(encodingTable[stopSymbol]...)
return utils.New1DCodeIntCheckSum(barcode.TypeCode128, content, result, sum), nil
} | [
"func",
"Encode",
"(",
"content",
"string",
")",
"(",
"barcode",
".",
"BarcodeIntCS",
",",
"error",
")",
"{",
"contentRunes",
":=",
"strToRunes",
"(",
"content",
")",
"\n",
"if",
"len",
"(",
"contentRunes",
")",
"<=",
"0",
"||",
"len",
"(",
"contentRunes... | // Encode creates a Code 128 barcode for the given content | [
"Encode",
"creates",
"a",
"Code",
"128",
"barcode",
"for",
"the",
"given",
"content"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/code128/encode.go#L159-L184 | train |
boombuler/barcode | utils/bitlist.go | NewBitList | func NewBitList(capacity int) *BitList {
bl := new(BitList)
bl.count = capacity
x := 0
if capacity%32 != 0 {
x = 1
}
bl.data = make([]int32, capacity/32+x)
return bl
} | go | func NewBitList(capacity int) *BitList {
bl := new(BitList)
bl.count = capacity
x := 0
if capacity%32 != 0 {
x = 1
}
bl.data = make([]int32, capacity/32+x)
return bl
} | [
"func",
"NewBitList",
"(",
"capacity",
"int",
")",
"*",
"BitList",
"{",
"bl",
":=",
"new",
"(",
"BitList",
")",
"\n",
"bl",
".",
"count",
"=",
"capacity",
"\n",
"x",
":=",
"0",
"\n",
"if",
"capacity",
"%",
"32",
"!=",
"0",
"{",
"x",
"=",
"1",
"... | // NewBitList returns a new BitList with the given length
// all bits are initialize with false | [
"NewBitList",
"returns",
"a",
"new",
"BitList",
"with",
"the",
"given",
"length",
"all",
"bits",
"are",
"initialize",
"with",
"false"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L11-L20 | train |
boombuler/barcode | utils/bitlist.go | AddBit | func (bl *BitList) AddBit(bits ...bool) {
for _, bit := range bits {
itmIndex := bl.count / 32
for itmIndex >= len(bl.data) {
bl.grow()
}
bl.SetBit(bl.count, bit)
bl.count++
}
} | go | func (bl *BitList) AddBit(bits ...bool) {
for _, bit := range bits {
itmIndex := bl.count / 32
for itmIndex >= len(bl.data) {
bl.grow()
}
bl.SetBit(bl.count, bit)
bl.count++
}
} | [
"func",
"(",
"bl",
"*",
"BitList",
")",
"AddBit",
"(",
"bits",
"...",
"bool",
")",
"{",
"for",
"_",
",",
"bit",
":=",
"range",
"bits",
"{",
"itmIndex",
":=",
"bl",
".",
"count",
"/",
"32",
"\n",
"for",
"itmIndex",
">=",
"len",
"(",
"bl",
".",
"... | // AddBit appends the given bits to the end of the list | [
"AddBit",
"appends",
"the",
"given",
"bits",
"to",
"the",
"end",
"of",
"the",
"list"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L41-L50 | train |
boombuler/barcode | utils/bitlist.go | SetBit | func (bl *BitList) SetBit(index int, value bool) {
itmIndex := index / 32
itmBitShift := 31 - (index % 32)
if value {
bl.data[itmIndex] = bl.data[itmIndex] | 1<<uint(itmBitShift)
} else {
bl.data[itmIndex] = bl.data[itmIndex] & ^(1 << uint(itmBitShift))
}
} | go | func (bl *BitList) SetBit(index int, value bool) {
itmIndex := index / 32
itmBitShift := 31 - (index % 32)
if value {
bl.data[itmIndex] = bl.data[itmIndex] | 1<<uint(itmBitShift)
} else {
bl.data[itmIndex] = bl.data[itmIndex] & ^(1 << uint(itmBitShift))
}
} | [
"func",
"(",
"bl",
"*",
"BitList",
")",
"SetBit",
"(",
"index",
"int",
",",
"value",
"bool",
")",
"{",
"itmIndex",
":=",
"index",
"/",
"32",
"\n",
"itmBitShift",
":=",
"31",
"-",
"(",
"index",
"%",
"32",
")",
"\n",
"if",
"value",
"{",
"bl",
".",
... | // SetBit sets the bit at the given index to the given value | [
"SetBit",
"sets",
"the",
"bit",
"at",
"the",
"given",
"index",
"to",
"the",
"given",
"value"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L53-L61 | train |
boombuler/barcode | utils/bitlist.go | GetBit | func (bl *BitList) GetBit(index int) bool {
itmIndex := index / 32
itmBitShift := 31 - (index % 32)
return ((bl.data[itmIndex] >> uint(itmBitShift)) & 1) == 1
} | go | func (bl *BitList) GetBit(index int) bool {
itmIndex := index / 32
itmBitShift := 31 - (index % 32)
return ((bl.data[itmIndex] >> uint(itmBitShift)) & 1) == 1
} | [
"func",
"(",
"bl",
"*",
"BitList",
")",
"GetBit",
"(",
"index",
"int",
")",
"bool",
"{",
"itmIndex",
":=",
"index",
"/",
"32",
"\n",
"itmBitShift",
":=",
"31",
"-",
"(",
"index",
"%",
"32",
")",
"\n",
"return",
"(",
"(",
"bl",
".",
"data",
"[",
... | // GetBit returns the bit at the given index | [
"GetBit",
"returns",
"the",
"bit",
"at",
"the",
"given",
"index"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L64-L68 | train |
boombuler/barcode | utils/bitlist.go | AddByte | func (bl *BitList) AddByte(b byte) {
for i := 7; i >= 0; i-- {
bl.AddBit(((b >> uint(i)) & 1) == 1)
}
} | go | func (bl *BitList) AddByte(b byte) {
for i := 7; i >= 0; i-- {
bl.AddBit(((b >> uint(i)) & 1) == 1)
}
} | [
"func",
"(",
"bl",
"*",
"BitList",
")",
"AddByte",
"(",
"b",
"byte",
")",
"{",
"for",
"i",
":=",
"7",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"bl",
".",
"AddBit",
"(",
"(",
"(",
"b",
">>",
"uint",
"(",
"i",
")",
")",
"&",
"1",
")",
"=... | // AddByte appends all 8 bits of the given byte to the end of the list | [
"AddByte",
"appends",
"all",
"8",
"bits",
"of",
"the",
"given",
"byte",
"to",
"the",
"end",
"of",
"the",
"list"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L71-L75 | train |
boombuler/barcode | utils/bitlist.go | IterateBytes | func (bl *BitList) IterateBytes() <-chan byte {
res := make(chan byte)
go func() {
c := bl.count
shift := 24
i := 0
for c > 0 {
res <- byte((bl.data[i] >> uint(shift)) & 0xFF)
shift -= 8
if shift < 0 {
shift = 24
i++
}
c -= 8
}
close(res)
}()
return res
} | go | func (bl *BitList) IterateBytes() <-chan byte {
res := make(chan byte)
go func() {
c := bl.count
shift := 24
i := 0
for c > 0 {
res <- byte((bl.data[i] >> uint(shift)) & 0xFF)
shift -= 8
if shift < 0 {
shift = 24
i++
}
c -= 8
}
close(res)
}()
return res
} | [
"func",
"(",
"bl",
"*",
"BitList",
")",
"IterateBytes",
"(",
")",
"<-",
"chan",
"byte",
"{",
"res",
":=",
"make",
"(",
"chan",
"byte",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"c",
":=",
"bl",
".",
"count",
"\n",
"shift",
":=",
"24",
"\n",
"i",
... | // IterateBytes iterates through all bytes contained in the BitList | [
"IterateBytes",
"iterates",
"through",
"all",
"bytes",
"contained",
"in",
"the",
"BitList"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L99-L119 | train |
boombuler/barcode | qr/encoder.go | Encode | func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) {
bits, vi, err := mode.getEncoder()(content, level)
if err != nil {
return nil, err
}
blocks := splitToBlocks(bits.IterateBytes(), vi)
data := blocks.interleave(vi)
result := render(data, vi)
result.content = content
return result, nil
} | go | func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) {
bits, vi, err := mode.getEncoder()(content, level)
if err != nil {
return nil, err
}
blocks := splitToBlocks(bits.IterateBytes(), vi)
data := blocks.interleave(vi)
result := render(data, vi)
result.content = content
return result, nil
} | [
"func",
"Encode",
"(",
"content",
"string",
",",
"level",
"ErrorCorrectionLevel",
",",
"mode",
"Encoding",
")",
"(",
"barcode",
".",
"Barcode",
",",
"error",
")",
"{",
"bits",
",",
"vi",
",",
"err",
":=",
"mode",
".",
"getEncoder",
"(",
")",
"(",
"cont... | // Encode returns a QR barcode with the given content, error correction level and uses the given encoding | [
"Encode",
"returns",
"a",
"QR",
"barcode",
"with",
"the",
"given",
"content",
"error",
"correction",
"level",
"and",
"uses",
"the",
"given",
"encoding"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/qr/encoder.go#L58-L69 | train |
boombuler/barcode | code93/encoder.go | Encode | func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.Barcode, error) {
if fullASCIIMode {
var err error
content, err = prepare(content)
if err != nil {
return nil, err
}
} else if strings.ContainsRune(content, '*') {
return nil, errors.New("invalid data! content may not contain '*'")
}
data := content + string(getChecksum(content, 20))
data += string(getChecksum(data, 15))
data = "*" + data + "*"
result := new(utils.BitList)
for _, r := range data {
info, ok := encodeTable[r]
if !ok {
return nil, errors.New("invalid data!")
}
result.AddBits(info.data, 9)
}
result.AddBit(true)
return utils.New1DCode(barcode.TypeCode93, content, result), nil
} | go | func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.Barcode, error) {
if fullASCIIMode {
var err error
content, err = prepare(content)
if err != nil {
return nil, err
}
} else if strings.ContainsRune(content, '*') {
return nil, errors.New("invalid data! content may not contain '*'")
}
data := content + string(getChecksum(content, 20))
data += string(getChecksum(data, 15))
data = "*" + data + "*"
result := new(utils.BitList)
for _, r := range data {
info, ok := encodeTable[r]
if !ok {
return nil, errors.New("invalid data!")
}
result.AddBits(info.data, 9)
}
result.AddBit(true)
return utils.New1DCode(barcode.TypeCode93, content, result), nil
} | [
"func",
"Encode",
"(",
"content",
"string",
",",
"includeChecksum",
"bool",
",",
"fullASCIIMode",
"bool",
")",
"(",
"barcode",
".",
"Barcode",
",",
"error",
")",
"{",
"if",
"fullASCIIMode",
"{",
"var",
"err",
"error",
"\n",
"content",
",",
"err",
"=",
"p... | // Encode returns a code93 barcode for the given content
// if includeChecksum is set to true, two checksum characters are calculated and added to the content | [
"Encode",
"returns",
"a",
"code93",
"barcode",
"for",
"the",
"given",
"content",
"if",
"includeChecksum",
"is",
"set",
"to",
"true",
"two",
"checksum",
"characters",
"are",
"calculated",
"and",
"added",
"to",
"the",
"content"
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/code93/encoder.go#L79-L106 | train |
boombuler/barcode | aztec/highlevel.go | updateStateForChar | func updateStateForChar(s *state, data []byte, index int) stateSlice {
var result stateSlice = nil
ch := data[index]
charInCurrentTable := charMap[s.mode][ch] > 0
var stateNoBinary *state = nil
for mode := mode_upper; mode <= mode_punct; mode++ {
charInMode := charMap[mode][ch]
if charInMode > 0 {
if stateNoBinary == nil {
// Only create stateNoBinary the first time it's required.
stateNoBinary = s.endBinaryShift(index)
}
// Try generating the character by latching to its mode
if !charInCurrentTable || mode == s.mode || mode == mode_digit {
// If the character is in the current table, we don't want to latch to
// any other mode except possibly digit (which uses only 4 bits). Any
// other latch would be equally successful *after* this character, and
// so wouldn't save any bits.
res := stateNoBinary.latchAndAppend(mode, charInMode)
result = append(result, res)
}
// Try generating the character by switching to its mode.
if _, ok := shiftTable[s.mode][mode]; !charInCurrentTable && ok {
// It never makes sense to temporarily shift to another mode if the
// character exists in the current mode. That can never save bits.
res := stateNoBinary.shiftAndAppend(mode, charInMode)
result = append(result, res)
}
}
}
if s.bShiftByteCount > 0 || charMap[s.mode][ch] == 0 {
// It's never worthwhile to go into binary shift mode if you're not already
// in binary shift mode, and the character exists in your current mode.
// That can never save bits over just outputting the char in the current mode.
res := s.addBinaryShiftChar(index)
result = append(result, res)
}
return result
} | go | func updateStateForChar(s *state, data []byte, index int) stateSlice {
var result stateSlice = nil
ch := data[index]
charInCurrentTable := charMap[s.mode][ch] > 0
var stateNoBinary *state = nil
for mode := mode_upper; mode <= mode_punct; mode++ {
charInMode := charMap[mode][ch]
if charInMode > 0 {
if stateNoBinary == nil {
// Only create stateNoBinary the first time it's required.
stateNoBinary = s.endBinaryShift(index)
}
// Try generating the character by latching to its mode
if !charInCurrentTable || mode == s.mode || mode == mode_digit {
// If the character is in the current table, we don't want to latch to
// any other mode except possibly digit (which uses only 4 bits). Any
// other latch would be equally successful *after* this character, and
// so wouldn't save any bits.
res := stateNoBinary.latchAndAppend(mode, charInMode)
result = append(result, res)
}
// Try generating the character by switching to its mode.
if _, ok := shiftTable[s.mode][mode]; !charInCurrentTable && ok {
// It never makes sense to temporarily shift to another mode if the
// character exists in the current mode. That can never save bits.
res := stateNoBinary.shiftAndAppend(mode, charInMode)
result = append(result, res)
}
}
}
if s.bShiftByteCount > 0 || charMap[s.mode][ch] == 0 {
// It's never worthwhile to go into binary shift mode if you're not already
// in binary shift mode, and the character exists in your current mode.
// That can never save bits over just outputting the char in the current mode.
res := s.addBinaryShiftChar(index)
result = append(result, res)
}
return result
} | [
"func",
"updateStateForChar",
"(",
"s",
"*",
"state",
",",
"data",
"[",
"]",
"byte",
",",
"index",
"int",
")",
"stateSlice",
"{",
"var",
"result",
"stateSlice",
"=",
"nil",
"\n",
"ch",
":=",
"data",
"[",
"index",
"]",
"\n",
"charInCurrentTable",
":=",
... | // Return a set of states that represent the possible ways of updating this
// state for the next character. The resulting set of states are added to
// the "result" list. | [
"Return",
"a",
"set",
"of",
"states",
"that",
"represent",
"the",
"possible",
"ways",
"of",
"updating",
"this",
"state",
"for",
"the",
"next",
"character",
".",
"The",
"resulting",
"set",
"of",
"states",
"are",
"added",
"to",
"the",
"result",
"list",
"."
] | 6c824513baccd76c674ce72112c29ef550187b08 | https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/aztec/highlevel.go#L94-L133 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.