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/cat-main.go | catURL | func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
var reader io.ReadCloser
size := int64(-1)
switch sourceURL {
case "-":
reader = os.Stdin
default:
var err *probe.Error
// Try to stat the object, the purpose is to extract the
// size of S3 object so we can check if the size of the
// downloaded object is equal to the original one. FS files
// are ignored since some of them have zero size though they
// have contents like files under /proc.
client, content, err := url2Stat(sourceURL, false, encKeyDB)
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
}
if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
defer reader.Close()
}
return catOut(reader, size).Trace(sourceURL)
} | go | func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
var reader io.ReadCloser
size := int64(-1)
switch sourceURL {
case "-":
reader = os.Stdin
default:
var err *probe.Error
// Try to stat the object, the purpose is to extract the
// size of S3 object so we can check if the size of the
// downloaded object is equal to the original one. FS files
// are ignored since some of them have zero size though they
// have contents like files under /proc.
client, content, err := url2Stat(sourceURL, false, encKeyDB)
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
}
if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
defer reader.Close()
}
return catOut(reader, size).Trace(sourceURL)
} | [
"func",
"catURL",
"(",
"sourceURL",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"*",
"probe",
".",
"Error",
"{",
"var",
"reader",
"io",
".",
"ReadCloser",
"\n",
"size",
":=",
"int64",
"(",
"-",
"1",
")",
"\n"... | // catURL displays contents of a URL to stdout. | [
"catURL",
"displays",
"contents",
"of",
"a",
"URL",
"to",
"stdout",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cat-main.go#L140-L163 | train |
minio/mc | cmd/cat-main.go | mainCat | func mainCat(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'cat' cli arguments.
checkCatSyntax(ctx)
// Set command flags from context.
stdinMode := false
if !ctx.Args().Present() {
stdinMode = true
}
// handle std input data.
if stdinMode {
fatalIf(catOut(os.Stdin, -1).Trace(), "Unable to read from standard input.")
return nil
}
// if Args contain `-`, we need to preserve its order specially.
args := []string(ctx.Args())
if ctx.Args().First() == "-" {
for i, arg := range os.Args {
if arg == "cat" {
// Overwrite ctx.Args with os.Args.
args = os.Args[i+1:]
break
}
}
}
// Convert arguments to URLs: expand alias, fix format.
for _, url := range args {
fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
} | go | func mainCat(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'cat' cli arguments.
checkCatSyntax(ctx)
// Set command flags from context.
stdinMode := false
if !ctx.Args().Present() {
stdinMode = true
}
// handle std input data.
if stdinMode {
fatalIf(catOut(os.Stdin, -1).Trace(), "Unable to read from standard input.")
return nil
}
// if Args contain `-`, we need to preserve its order specially.
args := []string(ctx.Args())
if ctx.Args().First() == "-" {
for i, arg := range os.Args {
if arg == "cat" {
// Overwrite ctx.Args with os.Args.
args = os.Args[i+1:]
break
}
}
}
// Convert arguments to URLs: expand alias, fix format.
for _, url := range args {
fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
} | [
"func",
"mainCat",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"checkCatSyntax",
"(",
"ctx",
")... | // mainCat is the main entry point for cat command. | [
"mainCat",
"is",
"the",
"main",
"entry",
"point",
"for",
"cat",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cat-main.go#L211-L249 | train |
minio/mc | cmd/mb-main.go | mainMakeBucket | func mainMakeBucket(ctx *cli.Context) error {
// check 'mb' cli arguments.
checkMakeBucketSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
// Save region.
region := ctx.String("region")
ignoreExisting := ctx.Bool("p")
var cErr error
for _, targetURL := range ctx.Args() {
// Instantiate client for URL.
clnt, err := newClient(targetURL)
if err != nil {
errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
continue
}
// Make bucket.
err = clnt.MakeBucket(region, ignoreExisting)
if err != nil {
switch err.ToGoError().(type) {
case BucketNameEmpty:
errorIf(err.Trace(targetURL), "Unable to make bucket, please use `mc mb %s/<your-bucket-name>`.", targetURL)
case BucketNameTopLevel:
errorIf(err.Trace(targetURL), "Unable to make prefix, please use `mc mb %s/`.", targetURL)
default:
errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.")
}
cErr = exitStatus(globalErrorExitStatus)
continue
}
// Successfully created a bucket.
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
}
return cErr
} | go | func mainMakeBucket(ctx *cli.Context) error {
// check 'mb' cli arguments.
checkMakeBucketSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
// Save region.
region := ctx.String("region")
ignoreExisting := ctx.Bool("p")
var cErr error
for _, targetURL := range ctx.Args() {
// Instantiate client for URL.
clnt, err := newClient(targetURL)
if err != nil {
errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
continue
}
// Make bucket.
err = clnt.MakeBucket(region, ignoreExisting)
if err != nil {
switch err.ToGoError().(type) {
case BucketNameEmpty:
errorIf(err.Trace(targetURL), "Unable to make bucket, please use `mc mb %s/<your-bucket-name>`.", targetURL)
case BucketNameTopLevel:
errorIf(err.Trace(targetURL), "Unable to make prefix, please use `mc mb %s/`.", targetURL)
default:
errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.")
}
cErr = exitStatus(globalErrorExitStatus)
continue
}
// Successfully created a bucket.
printMsg(makeBucketMessage{Status: "success", Bucket: targetURL})
}
return cErr
} | [
"func",
"mainMakeBucket",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkMakeBucketSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"MakeBucket\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
",",
"color",
... | // mainMakeBucket is entry point for mb command. | [
"mainMakeBucket",
"is",
"entry",
"point",
"for",
"mb",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mb-main.go#L104-L145 | train |
minio/mc | cmd/humanized-duration.go | timeDurationToHumanizedDuration | func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration {
r := humanizedDuration{}
if duration.Seconds() < 60.0 {
r.Seconds = int64(duration.Seconds())
return r
}
if duration.Minutes() < 60.0 {
remainingSeconds := math.Mod(duration.Seconds(), 60)
r.Seconds = int64(remainingSeconds)
r.Minutes = int64(duration.Minutes())
return r
}
if duration.Hours() < 24.0 {
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
r.Seconds = int64(remainingSeconds)
r.Minutes = int64(remainingMinutes)
r.Hours = int64(duration.Hours())
return r
}
remainingHours := math.Mod(duration.Hours(), 24)
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
r.Hours = int64(remainingHours)
r.Minutes = int64(remainingMinutes)
r.Seconds = int64(remainingSeconds)
r.Days = int64(duration.Hours() / 24)
return r
} | go | func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration {
r := humanizedDuration{}
if duration.Seconds() < 60.0 {
r.Seconds = int64(duration.Seconds())
return r
}
if duration.Minutes() < 60.0 {
remainingSeconds := math.Mod(duration.Seconds(), 60)
r.Seconds = int64(remainingSeconds)
r.Minutes = int64(duration.Minutes())
return r
}
if duration.Hours() < 24.0 {
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
r.Seconds = int64(remainingSeconds)
r.Minutes = int64(remainingMinutes)
r.Hours = int64(duration.Hours())
return r
}
remainingHours := math.Mod(duration.Hours(), 24)
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
r.Hours = int64(remainingHours)
r.Minutes = int64(remainingMinutes)
r.Seconds = int64(remainingSeconds)
r.Days = int64(duration.Hours() / 24)
return r
} | [
"func",
"timeDurationToHumanizedDuration",
"(",
"duration",
"time",
".",
"Duration",
")",
"humanizedDuration",
"{",
"r",
":=",
"humanizedDuration",
"{",
"}",
"\n",
"if",
"duration",
".",
"Seconds",
"(",
")",
"<",
"60.0",
"{",
"r",
".",
"Seconds",
"=",
"int64... | // timeDurationToHumanizedDuration convert golang time.Duration to a custom more readable humanizedDuration. | [
"timeDurationToHumanizedDuration",
"convert",
"golang",
"time",
".",
"Duration",
"to",
"a",
"custom",
"more",
"readable",
"humanizedDuration",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/humanized-duration.go#L60-L88 | train |
minio/mc | cmd/admin-heal-result-item.go | getObjectHCCChange | func (h hri) getObjectHCCChange() (b, a col, err error) {
parityShards := h.ParityBlocks
dataShards := h.DataBlocks
onlineBefore, onlineAfter := h.GetOnlineCounts()
surplusShardsBeforeHeal := onlineBefore - dataShards
surplusShardsAfterHeal := onlineAfter - dataShards
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
if err != nil {
return
}
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
return
} | go | func (h hri) getObjectHCCChange() (b, a col, err error) {
parityShards := h.ParityBlocks
dataShards := h.DataBlocks
onlineBefore, onlineAfter := h.GetOnlineCounts()
surplusShardsBeforeHeal := onlineBefore - dataShards
surplusShardsAfterHeal := onlineAfter - dataShards
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
if err != nil {
return
}
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
return
} | [
"func",
"(",
"h",
"hri",
")",
"getObjectHCCChange",
"(",
")",
"(",
"b",
",",
"a",
"col",
",",
"err",
"error",
")",
"{",
"parityShards",
":=",
"h",
".",
"ParityBlocks",
"\n",
"dataShards",
":=",
"h",
".",
"DataBlocks",
"\n",
"onlineBefore",
",",
"online... | // getObjectHCCChange - returns before and after color change for
// objects | [
"getObjectHCCChange",
"-",
"returns",
"before",
"and",
"after",
"color",
"change",
"for",
"objects"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-heal-result-item.go#L35-L50 | train |
minio/mc | cmd/admin-heal-result-item.go | getReplicatedFileHCCChange | func (h hri) getReplicatedFileHCCChange() (b, a col, err error) {
getColCode := func(numAvail int) (c col, err error) {
// calculate color code for replicated object similar
// to erasure coded objects
quorum := h.DiskCount/h.SetCount/2 + 1
surplus := numAvail/h.SetCount - quorum
parity := h.DiskCount/h.SetCount - quorum
c, err = getHColCode(surplus, parity)
return
}
onlineBefore, onlineAfter := h.GetOnlineCounts()
b, err = getColCode(onlineBefore)
if err != nil {
return
}
a, err = getColCode(onlineAfter)
return
} | go | func (h hri) getReplicatedFileHCCChange() (b, a col, err error) {
getColCode := func(numAvail int) (c col, err error) {
// calculate color code for replicated object similar
// to erasure coded objects
quorum := h.DiskCount/h.SetCount/2 + 1
surplus := numAvail/h.SetCount - quorum
parity := h.DiskCount/h.SetCount - quorum
c, err = getHColCode(surplus, parity)
return
}
onlineBefore, onlineAfter := h.GetOnlineCounts()
b, err = getColCode(onlineBefore)
if err != nil {
return
}
a, err = getColCode(onlineAfter)
return
} | [
"func",
"(",
"h",
"hri",
")",
"getReplicatedFileHCCChange",
"(",
")",
"(",
"b",
",",
"a",
"col",
",",
"err",
"error",
")",
"{",
"getColCode",
":=",
"func",
"(",
"numAvail",
"int",
")",
"(",
"c",
"col",
",",
"err",
"error",
")",
"{",
"quorum",
":=",... | // getReplicatedFileHCCChange - fetches health color code for metadata
// files that are replicated. | [
"getReplicatedFileHCCChange",
"-",
"fetches",
"health",
"color",
"code",
"for",
"metadata",
"files",
"that",
"are",
"replicated",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-heal-result-item.go#L54-L72 | train |
minio/mc | cmd/event-list.go | checkEventListSyntax | func checkEventListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 && len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
} | go | func checkEventListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 && len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
} | [
"func",
"checkEventListSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"2",
"&&",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"1",
"{",
"cli",
".",
"ShowCommandHelpAnd... | // checkEventListSyntax - validate all the passed arguments | [
"checkEventListSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/event-list.go#L59-L63 | train |
minio/mc | cmd/config-host-add.go | checkConfigHostAddSyntax | func checkConfigHostAddSyntax(ctx *cli.Context) {
args := ctx.Args()
argsNr := len(args)
if argsNr < 4 || argsNr > 5 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
alias := args.Get(0)
url := args.Get(1)
accessKey := args.Get(2)
secretKey := args.Get(3)
api := ctx.String("api")
bucketLookup := ctx.String("lookup")
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
if !isValidHostURL(url) {
fatalIf(errInvalidURL(url), "Invalid URL.")
}
if !isValidAccessKey(accessKey) {
fatalIf(errInvalidArgument().Trace(accessKey),
"Invalid access key `"+accessKey+"`.")
}
if !isValidSecretKey(secretKey) {
fatalIf(errInvalidArgument().Trace(secretKey),
"Invalid secret key `"+secretKey+"`.")
}
if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4".
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized API signature. Valid options are `[S3v4, S3v2]`.")
}
if !isValidLookup(bucketLookup) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
}
} | go | func checkConfigHostAddSyntax(ctx *cli.Context) {
args := ctx.Args()
argsNr := len(args)
if argsNr < 4 || argsNr > 5 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
alias := args.Get(0)
url := args.Get(1)
accessKey := args.Get(2)
secretKey := args.Get(3)
api := ctx.String("api")
bucketLookup := ctx.String("lookup")
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
if !isValidHostURL(url) {
fatalIf(errInvalidURL(url), "Invalid URL.")
}
if !isValidAccessKey(accessKey) {
fatalIf(errInvalidArgument().Trace(accessKey),
"Invalid access key `"+accessKey+"`.")
}
if !isValidSecretKey(secretKey) {
fatalIf(errInvalidArgument().Trace(secretKey),
"Invalid secret key `"+secretKey+"`.")
}
if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4".
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized API signature. Valid options are `[S3v4, S3v2]`.")
}
if !isValidLookup(bucketLookup) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
}
} | [
"func",
"checkConfigHostAddSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"argsNr",
":=",
"len",
"(",
"args",
")",
"\n",
"if",
"argsNr",
"<",
"4",
"||",
"argsNr",
">",
"5",
"{",
"fatalIf... | // checkConfigHostAddSyntax - verifies input arguments to 'config host add'. | [
"checkConfigHostAddSyntax",
"-",
"verifies",
"input",
"arguments",
"to",
"config",
"host",
"add",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-add.go#L87-L128 | train |
minio/mc | cmd/config-host-add.go | addHost | func addHost(alias string, hostCfgV9 hostConfigV9) {
mcCfgV9, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.")
// Add new host.
mcCfgV9.Hosts[alias] = hostCfgV9
err = saveMcConfig(mcCfgV9)
fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.")
printMsg(hostMessage{
op: "add",
Alias: alias,
URL: hostCfgV9.URL,
AccessKey: hostCfgV9.AccessKey,
SecretKey: hostCfgV9.SecretKey,
API: hostCfgV9.API,
Lookup: hostCfgV9.Lookup,
})
} | go | func addHost(alias string, hostCfgV9 hostConfigV9) {
mcCfgV9, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.")
// Add new host.
mcCfgV9.Hosts[alias] = hostCfgV9
err = saveMcConfig(mcCfgV9)
fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.")
printMsg(hostMessage{
op: "add",
Alias: alias,
URL: hostCfgV9.URL,
AccessKey: hostCfgV9.AccessKey,
SecretKey: hostCfgV9.SecretKey,
API: hostCfgV9.API,
Lookup: hostCfgV9.Lookup,
})
} | [
"func",
"addHost",
"(",
"alias",
"string",
",",
"hostCfgV9",
"hostConfigV9",
")",
"{",
"mcCfgV9",
",",
"err",
":=",
"loadMcConfig",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
"globalMCConfigVersion",
")",
",",
"\"Unable to load config `\"",
"+",... | // addHost - add a host config. | [
"addHost",
"-",
"add",
"a",
"host",
"config",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-add.go#L131-L150 | train |
minio/mc | cmd/config-host-add.go | buildS3Config | func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
s3Config := newS3Config(url, &hostConfigV9{
AccessKey: accessKey,
SecretKey: secretKey,
URL: url,
Lookup: lookup,
})
// If api is provided we do not auto probe signature, this is
// required in situations when signature type is provided by the user.
if api != "" {
s3Config.Signature = api
return s3Config, nil
}
// Probe S3 signature version
api, err := probeS3Signature(accessKey, secretKey, url)
if err != nil {
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
}
s3Config.Signature = api
// Success.
return s3Config, nil
} | go | func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
s3Config := newS3Config(url, &hostConfigV9{
AccessKey: accessKey,
SecretKey: secretKey,
URL: url,
Lookup: lookup,
})
// If api is provided we do not auto probe signature, this is
// required in situations when signature type is provided by the user.
if api != "" {
s3Config.Signature = api
return s3Config, nil
}
// Probe S3 signature version
api, err := probeS3Signature(accessKey, secretKey, url)
if err != nil {
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
}
s3Config.Signature = api
// Success.
return s3Config, nil
} | [
"func",
"buildS3Config",
"(",
"url",
",",
"accessKey",
",",
"secretKey",
",",
"api",
",",
"lookup",
"string",
")",
"(",
"*",
"Config",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"s3Config",
":=",
"newS3Config",
"(",
"url",
",",
"&",
"hostConfigV9",
"{"... | // buildS3Config constructs an S3 Config and does
// signature auto-probe when needed. | [
"buildS3Config",
"constructs",
"an",
"S3",
"Config",
"and",
"does",
"signature",
"auto",
"-",
"probe",
"when",
"needed",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-add.go#L198-L222 | train |
minio/mc | pkg/colorjson/scanner.go | eof | func (s *scanner) eof() int {
if s.err != nil {
return scanError
}
if s.endTop {
return scanEnd
}
s.step(s, ' ')
if s.endTop {
return scanEnd
}
if s.err == nil {
s.err = &SyntaxError{"unexpected end of JSON input", s.bytes}
}
return scanError
} | go | func (s *scanner) eof() int {
if s.err != nil {
return scanError
}
if s.endTop {
return scanEnd
}
s.step(s, ' ')
if s.endTop {
return scanEnd
}
if s.err == nil {
s.err = &SyntaxError{"unexpected end of JSON input", s.bytes}
}
return scanError
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"eof",
"(",
")",
"int",
"{",
"if",
"s",
".",
"err",
"!=",
"nil",
"{",
"return",
"scanError",
"\n",
"}",
"\n",
"if",
"s",
".",
"endTop",
"{",
"return",
"scanEnd",
"\n",
"}",
"\n",
"s",
".",
"step",
"(",
"... | // eof tells the scanner that the end of input has been reached.
// It returns a scan status just as s.step does. | [
"eof",
"tells",
"the",
"scanner",
"that",
"the",
"end",
"of",
"input",
"has",
"been",
"reached",
".",
"It",
"returns",
"a",
"scan",
"status",
"just",
"as",
"s",
".",
"step",
"does",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L137-L152 | train |
minio/mc | pkg/colorjson/scanner.go | stateBeginColorESC | func stateBeginColorESC(s *scanner, c byte) int {
switch c {
case '[':
s.step = stateBeginColorRest
return scanContinue
}
return s.error(c, "in string color escape code")
} | go | func stateBeginColorESC(s *scanner, c byte) int {
switch c {
case '[':
s.step = stateBeginColorRest
return scanContinue
}
return s.error(c, "in string color escape code")
} | [
"func",
"stateBeginColorESC",
"(",
"s",
"*",
"scanner",
",",
"c",
"byte",
")",
"int",
"{",
"switch",
"c",
"{",
"case",
"'['",
":",
"s",
".",
"step",
"=",
"stateBeginColorRest",
"\n",
"return",
"scanContinue",
"\n",
"}",
"\n",
"return",
"s",
".",
"error... | // stateInStringColorFirst is the state after reading the beginning of a color representation
// which is \x1b | [
"stateInStringColorFirst",
"is",
"the",
"state",
"after",
"reading",
"the",
"beginning",
"of",
"a",
"color",
"representation",
"which",
"is",
"\\",
"x1b"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L358-L365 | train |
minio/mc | pkg/colorjson/scanner.go | stateBeginColorRest | func stateBeginColorRest(s *scanner, c byte) int {
if c <= ' ' && isSpace(c) {
return scanSkipSpace
}
if '0' <= c && c <= '9' {
s.step = stateBeginColorRest
return scanContinue
}
switch c {
case ';':
s.step = stateBeginColorRest
return scanContinue
case 'm':
s.step = stateBeginValue
return scanContinue
}
return s.error(c, "in string color escape code")
} | go | func stateBeginColorRest(s *scanner, c byte) int {
if c <= ' ' && isSpace(c) {
return scanSkipSpace
}
if '0' <= c && c <= '9' {
s.step = stateBeginColorRest
return scanContinue
}
switch c {
case ';':
s.step = stateBeginColorRest
return scanContinue
case 'm':
s.step = stateBeginValue
return scanContinue
}
return s.error(c, "in string color escape code")
} | [
"func",
"stateBeginColorRest",
"(",
"s",
"*",
"scanner",
",",
"c",
"byte",
")",
"int",
"{",
"if",
"c",
"<=",
"' '",
"&&",
"isSpace",
"(",
"c",
")",
"{",
"return",
"scanSkipSpace",
"\n",
"}",
"\n",
"if",
"'0'",
"<=",
"c",
"&&",
"c",
"<=",
"'9'",
"... | // stateInStringColorSecond is the state after reading the second character of a color representation
// which is \x1b[ | [
"stateInStringColorSecond",
"is",
"the",
"state",
"after",
"reading",
"the",
"second",
"character",
"of",
"a",
"color",
"representation",
"which",
"is",
"\\",
"x1b",
"["
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L369-L386 | train |
minio/mc | pkg/colorjson/scanner.go | stateInStringEscU | func stateInStringEscU(s *scanner, c byte) int {
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
s.step = stateInStringEscU1
return scanContinue
}
// numbers
return s.error(c, "in \\u hexadecimal character escape")
} | go | func stateInStringEscU(s *scanner, c byte) int {
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
s.step = stateInStringEscU1
return scanContinue
}
// numbers
return s.error(c, "in \\u hexadecimal character escape")
} | [
"func",
"stateInStringEscU",
"(",
"s",
"*",
"scanner",
",",
"c",
"byte",
")",
"int",
"{",
"if",
"'0'",
"<=",
"c",
"&&",
"c",
"<=",
"'9'",
"||",
"'a'",
"<=",
"c",
"&&",
"c",
"<=",
"'f'",
"||",
"'A'",
"<=",
"c",
"&&",
"c",
"<=",
"'F'",
"{",
"s"... | // stateInStringEscU is the state after reading `"\u` during a quoted string. | [
"stateInStringEscU",
"is",
"the",
"state",
"after",
"reading",
"\\",
"u",
"during",
"a",
"quoted",
"string",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L407-L414 | train |
minio/mc | cmd/admin-info.go | checkAdminInfoSyntax | func checkAdminInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
} | go | func checkAdminInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
} | [
"func",
"checkAdminInfoSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"2",
"{",
"cli",
".",
"ShowCommandHelpAndE... | // checkAdminInfoSyntax - validate all the passed arguments | [
"checkAdminInfoSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-info.go#L204-L208 | train |
minio/mc | cmd/session-clear.go | String | func (c clearSessionMessage) String() string {
msg := "Session `" + c.SessionID + "`"
var colorizedMsg string
switch c.Status {
case "success":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared successfully.")
case "forced":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.")
}
return colorizedMsg
} | go | func (c clearSessionMessage) String() string {
msg := "Session `" + c.SessionID + "`"
var colorizedMsg string
switch c.Status {
case "success":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared successfully.")
case "forced":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.")
}
return colorizedMsg
} | [
"func",
"(",
"c",
"clearSessionMessage",
")",
"String",
"(",
")",
"string",
"{",
"msg",
":=",
"\"Session `\"",
"+",
"c",
".",
"SessionID",
"+",
"\"`\"",
"\n",
"var",
"colorizedMsg",
"string",
"\n",
"switch",
"c",
".",
"Status",
"{",
"case",
"\"success\"",
... | // String colorized clear session message. | [
"String",
"colorized",
"clear",
"session",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L70-L80 | train |
minio/mc | cmd/session-clear.go | JSON | func (c clearSessionMessage) JSON() string {
clearSessionJSONBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(clearSessionJSONBytes)
} | go | func (c clearSessionMessage) JSON() string {
clearSessionJSONBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(clearSessionJSONBytes)
} | [
"func",
"(",
"c",
"clearSessionMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"clearSessionJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"c",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"probe",
".",
"NewError",
"(",
"e",
")... | // JSON jsonified clear session message. | [
"JSON",
"jsonified",
"clear",
"session",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L83-L88 | train |
minio/mc | cmd/session-clear.go | clearSession | func clearSession(sid string, isForce bool) {
var toRemove []string
if sid == "all" {
toRemove = getSessionIDs()
} else {
toRemove = append(toRemove, sid)
}
for _, sid := range toRemove {
session, err := loadSessionV8(sid)
if !isForce {
fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`. Use --force flag to remove obsolete session files.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`. Use --force flag to remove obsolete session files.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
continue
}
// Forced removal of a session.
forceClear(sid, session)
}
return
} | go | func clearSession(sid string, isForce bool) {
var toRemove []string
if sid == "all" {
toRemove = getSessionIDs()
} else {
toRemove = append(toRemove, sid)
}
for _, sid := range toRemove {
session, err := loadSessionV8(sid)
if !isForce {
fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`. Use --force flag to remove obsolete session files.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`. Use --force flag to remove obsolete session files.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
continue
}
// Forced removal of a session.
forceClear(sid, session)
}
return
} | [
"func",
"clearSession",
"(",
"sid",
"string",
",",
"isForce",
"bool",
")",
"{",
"var",
"toRemove",
"[",
"]",
"string",
"\n",
"if",
"sid",
"==",
"\"all\"",
"{",
"toRemove",
"=",
"getSessionIDs",
"(",
")",
"\n",
"}",
"else",
"{",
"toRemove",
"=",
"append... | // clearSession clear sessions. | [
"clearSession",
"clear",
"sessions",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L107-L128 | train |
minio/mc | cmd/session-clear.go | checkSessionClearSyntax | func checkSessionClearSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code
}
} | go | func checkSessionClearSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code
}
} | [
"func",
"checkSessionClearSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"2",
"{",
"cli",
".",
"ShowCommandHelpA... | // checkSessionClearSyntax - Check syntax of 'session clear sid'. | [
"checkSessionClearSyntax",
"-",
"Check",
"syntax",
"of",
"session",
"clear",
"sid",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L131-L135 | train |
minio/mc | cmd/session-clear.go | mainSessionClear | func mainSessionClear(ctx *cli.Context) error {
// Check command arguments
checkSessionClearSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
console.SetColor("SessionTime", color.New(color.FgGreen))
console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold))
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
}
// Set command flags.
isForce := ctx.Bool("force")
// Retrieve requested session id.
sessionID := ctx.Args().Get(0)
// Purge requested session id or all pending sessions.
clearSession(sessionID, isForce)
return nil
} | go | func mainSessionClear(ctx *cli.Context) error {
// Check command arguments
checkSessionClearSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
console.SetColor("SessionTime", color.New(color.FgGreen))
console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold))
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
}
// Set command flags.
isForce := ctx.Bool("force")
// Retrieve requested session id.
sessionID := ctx.Args().Get(0)
// Purge requested session id or all pending sessions.
clearSession(sessionID, isForce)
return nil
} | [
"func",
"mainSessionClear",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkSessionClearSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"Command\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgWhite",
",",
"color",
... | // mainSessionClear - Main session clear. | [
"mainSessionClear",
"-",
"Main",
"session",
"clear",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L138-L160 | train |
minio/mc | cmd/admin-monitor.go | checkAdminMonitorSyntax | func checkAdminMonitorSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
exit := globalErrorExitStatus
cli.ShowCommandHelpAndExit(ctx, "monitor", exit)
}
} | go | func checkAdminMonitorSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
exit := globalErrorExitStatus
cli.ShowCommandHelpAndExit(ctx, "monitor", exit)
}
} | [
"func",
"checkAdminMonitorSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"1",
"{",
"exit",
":=",
"globalErrorExi... | // checkAdminMonitorSyntax - validate all the passed arguments | [
"checkAdminMonitorSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-monitor.go#L246-L252 | train |
minio/mc | cmd/client-admin.go | newAdminFactory | func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
clientCache := make(map[uint32]*madmin.AdminClient)
mutex := &sync.Mutex{}
// Return New function.
return func(config *Config) (*madmin.AdminClient, *probe.Error) {
// Creates a parsed URL.
targetURL, e := url.Parse(config.HostURL)
if e != nil {
return nil, probe.NewError(e)
}
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
confSum := confHash.Sum32()
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api *madmin.AdminClient
var found bool
if api, found = clientCache[confSum]; !found {
// Not found. Instantiate a new MinIO
var e error
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
if e != nil {
return nil, probe.NewError(e)
}
// Keep TLS config.
tlsConfig := &tls.Config{RootCAs: globalRootCAs}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
var transport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: tlsConfig,
}
if config.Debug {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
}
// Set custom transport.
api.SetCustomTransport(transport)
// Set app info.
api.SetAppInfo(config.AppName, config.AppVersion)
// Cache the new MinIO Client with hash of config as key.
clientCache[confSum] = api
}
// Store the new api object.
return api, nil
}
} | go | func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
clientCache := make(map[uint32]*madmin.AdminClient)
mutex := &sync.Mutex{}
// Return New function.
return func(config *Config) (*madmin.AdminClient, *probe.Error) {
// Creates a parsed URL.
targetURL, e := url.Parse(config.HostURL)
if e != nil {
return nil, probe.NewError(e)
}
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
confSum := confHash.Sum32()
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api *madmin.AdminClient
var found bool
if api, found = clientCache[confSum]; !found {
// Not found. Instantiate a new MinIO
var e error
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
if e != nil {
return nil, probe.NewError(e)
}
// Keep TLS config.
tlsConfig := &tls.Config{RootCAs: globalRootCAs}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
var transport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: tlsConfig,
}
if config.Debug {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
}
// Set custom transport.
api.SetCustomTransport(transport)
// Set app info.
api.SetAppInfo(config.AppName, config.AppVersion)
// Cache the new MinIO Client with hash of config as key.
clientCache[confSum] = api
}
// Store the new api object.
return api, nil
}
} | [
"func",
"newAdminFactory",
"(",
")",
"func",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"madmin",
".",
"AdminClient",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"clientCache",
":=",
"make",
"(",
"map",
"[",
"uint32",
"]",
"*",
"madmin",
".",
"Admin... | // newAdminFactory encloses New function with client cache. | [
"newAdminFactory",
"encloses",
"New",
"function",
"with",
"client",
"cache",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-admin.go#L35-L109 | train |
minio/mc | cmd/client-admin.go | newAdminClient | func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
}
// Verify if the aliasedURL is a real URL, fail in those cases
// indicating the user to add alias.
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
}
if hostCfg == nil {
return nil, probe.NewError(fmt.Errorf("The specified alias: %s not found", urlStrFull))
}
s3Config := newS3Config(urlStrFull, hostCfg)
s3Client, err := s3AdminNew(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStrFull)
}
return s3Client, nil
} | go | func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
}
// Verify if the aliasedURL is a real URL, fail in those cases
// indicating the user to add alias.
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
}
if hostCfg == nil {
return nil, probe.NewError(fmt.Errorf("The specified alias: %s not found", urlStrFull))
}
s3Config := newS3Config(urlStrFull, hostCfg)
s3Client, err := s3AdminNew(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStrFull)
}
return s3Client, nil
} | [
"func",
"newAdminClient",
"(",
"aliasedURL",
"string",
")",
"(",
"*",
"madmin",
".",
"AdminClient",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"alias",
",",
"urlStrFull",
",",
"hostCfg",
",",
"err",
":=",
"expandAlias",
"(",
"aliasedURL",
")",
"\n",
"if"... | // newAdminClient gives a new client interface | [
"newAdminClient",
"gives",
"a",
"new",
"client",
"interface"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-admin.go#L112-L134 | train |
minio/mc | cmd/ls.go | JSON | func (c contentMessage) JSON() string {
c.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
} | go | func (c contentMessage) JSON() string {
c.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
} | [
"func",
"(",
"c",
"contentMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"c",
".",
"Status",
"=",
"\"success\"",
"\n",
"jsonMessageBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"c",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
... | // JSON jsonified content message. | [
"JSON",
"jsonified",
"content",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/ls.go#L61-L67 | train |
minio/mc | cmd/ls.go | parseContent | func parseContent(c *clientContent) contentMessage {
content := contentMessage{}
content.Time = c.Time.Local()
// guess file type.
content.Filetype = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
md5sum := strings.TrimPrefix(c.ETag, "\"")
md5sum = strings.TrimSuffix(md5sum, "\"")
content.ETag = md5sum
// Convert OS Type to match console file printing style.
content.Key = getKey(c)
return content
} | go | func parseContent(c *clientContent) contentMessage {
content := contentMessage{}
content.Time = c.Time.Local()
// guess file type.
content.Filetype = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
md5sum := strings.TrimPrefix(c.ETag, "\"")
md5sum = strings.TrimSuffix(md5sum, "\"")
content.ETag = md5sum
// Convert OS Type to match console file printing style.
content.Key = getKey(c)
return content
} | [
"func",
"parseContent",
"(",
"c",
"*",
"clientContent",
")",
"contentMessage",
"{",
"content",
":=",
"contentMessage",
"{",
"}",
"\n",
"content",
".",
"Time",
"=",
"c",
".",
"Time",
".",
"Local",
"(",
")",
"\n",
"content",
".",
"Filetype",
"=",
"func",
... | // parseContent parse client Content container into printer struct. | [
"parseContent",
"parse",
"client",
"Content",
"container",
"into",
"printer",
"struct",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/ls.go#L70-L89 | train |
minio/mc | cmd/ls.go | getKey | func getKey(c *clientContent) string {
sep := "/"
// for windows make sure to print in 'windows' specific style.
if runtime.GOOS == "windows" {
c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1)
sep = "\\"
}
if c.Type.IsDir() && !strings.HasSuffix(c.URL.Path, sep) {
return fmt.Sprintf("%s%s", c.URL.Path, sep)
}
return c.URL.Path
} | go | func getKey(c *clientContent) string {
sep := "/"
// for windows make sure to print in 'windows' specific style.
if runtime.GOOS == "windows" {
c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1)
sep = "\\"
}
if c.Type.IsDir() && !strings.HasSuffix(c.URL.Path, sep) {
return fmt.Sprintf("%s%s", c.URL.Path, sep)
}
return c.URL.Path
} | [
"func",
"getKey",
"(",
"c",
"*",
"clientContent",
")",
"string",
"{",
"sep",
":=",
"\"/\"",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"{",
"c",
".",
"URL",
".",
"Path",
"=",
"strings",
".",
"Replace",
"(",
"c",
".",
"URL",
".",
"Path... | // get content key | [
"get",
"content",
"key"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/ls.go#L92-L105 | train |
minio/mc | cmd/ls.go | doList | func doList(clnt Client, isRecursive, isIncomplete bool) error {
prefixPath := clnt.GetURL().Path
separator := string(clnt.GetURL().Separator)
if !strings.HasSuffix(prefixPath, separator) {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
}
var cErr error
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case BrokenSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
continue
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case PathNotFound:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
case PathInsufficientPermission:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
case ObjectOnGlacier:
errorIf(content.Err.Trace(clnt.GetURL().String()), "")
continue
}
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
continue
}
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(content.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
// Trim prefix of current working dir
prefixPath = strings.TrimPrefix(prefixPath, "."+separator)
// Trim prefix path from the content path.
contentURL = strings.TrimPrefix(contentURL, prefixPath)
content.URL.Path = contentURL
parsedContent := parseContent(content)
// Print colorized or jsonized content info.
printMsg(parsedContent)
}
return cErr
} | go | func doList(clnt Client, isRecursive, isIncomplete bool) error {
prefixPath := clnt.GetURL().Path
separator := string(clnt.GetURL().Separator)
if !strings.HasSuffix(prefixPath, separator) {
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
}
var cErr error
for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case BrokenSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
continue
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case PathNotFound:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
case PathInsufficientPermission:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
case ObjectOnGlacier:
errorIf(content.Err.Trace(clnt.GetURL().String()), "")
continue
}
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
continue
}
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(content.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
// Trim prefix of current working dir
prefixPath = strings.TrimPrefix(prefixPath, "."+separator)
// Trim prefix path from the content path.
contentURL = strings.TrimPrefix(contentURL, prefixPath)
content.URL.Path = contentURL
parsedContent := parseContent(content)
// Print colorized or jsonized content info.
printMsg(parsedContent)
}
return cErr
} | [
"func",
"doList",
"(",
"clnt",
"Client",
",",
"isRecursive",
",",
"isIncomplete",
"bool",
")",
"error",
"{",
"prefixPath",
":=",
"clnt",
".",
"GetURL",
"(",
")",
".",
"Path",
"\n",
"separator",
":=",
"string",
"(",
"clnt",
".",
"GetURL",
"(",
")",
".",... | // doList - list all entities inside a folder. | [
"doList",
"-",
"list",
"all",
"entities",
"inside",
"a",
"folder",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/ls.go#L108-L153 | train |
minio/mc | cmd/head-main.go | headURL | func headURL(sourceURL string, encKeyDB map[string][]prefixSSEPair, nlines int64) *probe.Error {
var reader io.ReadCloser
switch sourceURL {
case "-":
reader = os.Stdin
default:
var err *probe.Error
var metadata map[string]string
if reader, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
ctype := metadata["Content-Type"]
if strings.Contains(ctype, "gzip") {
var e error
reader, e = gzip.NewReader(reader)
if e != nil {
return probe.NewError(e)
}
defer reader.Close()
} else if strings.Contains(ctype, "bzip") {
defer reader.Close()
reader = ioutil.NopCloser(bzip2.NewReader(reader))
} else {
defer reader.Close()
}
}
return headOut(reader, nlines).Trace(sourceURL)
} | go | func headURL(sourceURL string, encKeyDB map[string][]prefixSSEPair, nlines int64) *probe.Error {
var reader io.ReadCloser
switch sourceURL {
case "-":
reader = os.Stdin
default:
var err *probe.Error
var metadata map[string]string
if reader, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
ctype := metadata["Content-Type"]
if strings.Contains(ctype, "gzip") {
var e error
reader, e = gzip.NewReader(reader)
if e != nil {
return probe.NewError(e)
}
defer reader.Close()
} else if strings.Contains(ctype, "bzip") {
defer reader.Close()
reader = ioutil.NopCloser(bzip2.NewReader(reader))
} else {
defer reader.Close()
}
}
return headOut(reader, nlines).Trace(sourceURL)
} | [
"func",
"headURL",
"(",
"sourceURL",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
",",
"nlines",
"int64",
")",
"*",
"probe",
".",
"Error",
"{",
"var",
"reader",
"io",
".",
"ReadCloser",
"\n",
"switch",
"sourceURL",
"{"... | // headURL displays contents of a URL to stdout. | [
"headURL",
"displays",
"contents",
"of",
"a",
"URL",
"to",
"stdout",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/head-main.go#L77-L104 | train |
minio/mc | cmd/head-main.go | mainHead | func mainHead(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// Set command flags from context.
stdinMode := false
if !ctx.Args().Present() {
stdinMode = true
}
// handle std input data.
if stdinMode {
fatalIf(headOut(os.Stdin, ctx.Int64("lines")).Trace(), "Unable to read from standard input.")
return nil
}
// Convert arguments to URLs: expand alias, fix format.
for _, url := range ctx.Args() {
fatalIf(headURL(url, encKeyDB, ctx.Int64("lines")).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
} | go | func mainHead(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// Set command flags from context.
stdinMode := false
if !ctx.Args().Present() {
stdinMode = true
}
// handle std input data.
if stdinMode {
fatalIf(headOut(os.Stdin, ctx.Int64("lines")).Trace(), "Unable to read from standard input.")
return nil
}
// Convert arguments to URLs: expand alias, fix format.
for _, url := range ctx.Args() {
fatalIf(headURL(url, encKeyDB, ctx.Int64("lines")).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
} | [
"func",
"mainHead",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"stdinMode",
":=",
"false",
"\n... | // mainHead is the main entry point for head command. | [
"mainHead",
"is",
"the",
"main",
"entry",
"point",
"for",
"head",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/head-main.go#L151-L174 | train |
minio/mc | cmd/parallel-manager.go | addWorker | func (p *ParallelManager) addWorker() {
if atomic.LoadUint32(&p.workersNum) >= maxParallelWorkers {
// Number of maximum workers is reached, no need to
// to create a new one.
return
}
// Update number of threads
atomic.AddUint32(&p.workersNum, 1)
// Start a new worker
p.wg.Add(1)
go func() {
for {
// Wait for jobs
fn, ok := <-p.queueCh
if !ok {
// No more tasks, quit
p.wg.Done()
return
}
// Execute the task and send the result
// to result channel.
p.resultCh <- fn()
}
}()
} | go | func (p *ParallelManager) addWorker() {
if atomic.LoadUint32(&p.workersNum) >= maxParallelWorkers {
// Number of maximum workers is reached, no need to
// to create a new one.
return
}
// Update number of threads
atomic.AddUint32(&p.workersNum, 1)
// Start a new worker
p.wg.Add(1)
go func() {
for {
// Wait for jobs
fn, ok := <-p.queueCh
if !ok {
// No more tasks, quit
p.wg.Done()
return
}
// Execute the task and send the result
// to result channel.
p.resultCh <- fn()
}
}()
} | [
"func",
"(",
"p",
"*",
"ParallelManager",
")",
"addWorker",
"(",
")",
"{",
"if",
"atomic",
".",
"LoadUint32",
"(",
"&",
"p",
".",
"workersNum",
")",
">=",
"maxParallelWorkers",
"{",
"return",
"\n",
"}",
"\n",
"atomic",
".",
"AddUint32",
"(",
"&",
"p",
... | // addWorker creates a new worker to process tasks | [
"addWorker",
"creates",
"a",
"new",
"worker",
"to",
"process",
"tasks"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/parallel-manager.go#L57-L83 | train |
minio/mc | cmd/parallel-manager.go | monitorProgress | func (p *ParallelManager) monitorProgress() {
go func() {
ticker := time.NewTicker(monitorPeriod)
defer ticker.Stop()
var prevSentBytes, maxBandwidth int64
var retry int
for {
select {
case <-p.stopMonitorCh:
// Ordered to quit immediately
return
case <-ticker.C:
// Compute new bandwidth from counted sent bytes
sentBytes := atomic.LoadInt64(&p.sentBytes)
bandwidth := sentBytes - prevSentBytes
prevSentBytes = sentBytes
if bandwidth <= maxBandwidth {
retry++
// We still want to add more workers
// until we are sure that it is not
// useful to add more of them.
if retry > 2 {
return
}
} else {
retry = 0
maxBandwidth = bandwidth
}
for i := 0; i < defaultWorkerFactor; i++ {
p.addWorker()
}
}
}
}()
} | go | func (p *ParallelManager) monitorProgress() {
go func() {
ticker := time.NewTicker(monitorPeriod)
defer ticker.Stop()
var prevSentBytes, maxBandwidth int64
var retry int
for {
select {
case <-p.stopMonitorCh:
// Ordered to quit immediately
return
case <-ticker.C:
// Compute new bandwidth from counted sent bytes
sentBytes := atomic.LoadInt64(&p.sentBytes)
bandwidth := sentBytes - prevSentBytes
prevSentBytes = sentBytes
if bandwidth <= maxBandwidth {
retry++
// We still want to add more workers
// until we are sure that it is not
// useful to add more of them.
if retry > 2 {
return
}
} else {
retry = 0
maxBandwidth = bandwidth
}
for i := 0; i < defaultWorkerFactor; i++ {
p.addWorker()
}
}
}
}()
} | [
"func",
"(",
"p",
"*",
"ParallelManager",
")",
"monitorProgress",
"(",
")",
"{",
"go",
"func",
"(",
")",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"monitorPeriod",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"var",
"prevSentByt... | // monitorProgress monitors realtime transfer speed of data
// and increases threads until it reaches a maximum number of
// threads or notice there is no apparent enhancement of
// transfer speed. | [
"monitorProgress",
"monitors",
"realtime",
"transfer",
"speed",
"of",
"data",
"and",
"increases",
"threads",
"until",
"it",
"reaches",
"a",
"maximum",
"number",
"of",
"threads",
"or",
"notice",
"there",
"is",
"no",
"apparent",
"enhancement",
"of",
"transfer",
"s... | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/parallel-manager.go#L94-L132 | train |
minio/mc | cmd/parallel-manager.go | newParallelManager | func newParallelManager(resultCh chan URLs) (*ParallelManager, chan func() URLs) {
p := &ParallelManager{
wg: &sync.WaitGroup{},
workersNum: 0,
stopMonitorCh: make(chan struct{}),
queueCh: make(chan func() URLs),
resultCh: resultCh,
}
// Start with runtime.NumCPU().
for i := 0; i < runtime.NumCPU(); i++ {
p.addWorker()
}
// Start monitoring tasks progress
p.monitorProgress()
return p, p.queueCh
} | go | func newParallelManager(resultCh chan URLs) (*ParallelManager, chan func() URLs) {
p := &ParallelManager{
wg: &sync.WaitGroup{},
workersNum: 0,
stopMonitorCh: make(chan struct{}),
queueCh: make(chan func() URLs),
resultCh: resultCh,
}
// Start with runtime.NumCPU().
for i := 0; i < runtime.NumCPU(); i++ {
p.addWorker()
}
// Start monitoring tasks progress
p.monitorProgress()
return p, p.queueCh
} | [
"func",
"newParallelManager",
"(",
"resultCh",
"chan",
"URLs",
")",
"(",
"*",
"ParallelManager",
",",
"chan",
"func",
"(",
")",
"URLs",
")",
"{",
"p",
":=",
"&",
"ParallelManager",
"{",
"wg",
":",
"&",
"sync",
".",
"WaitGroup",
"{",
"}",
",",
"workersN... | // newParallelManager starts new workers waiting for executing tasks | [
"newParallelManager",
"starts",
"new",
"workers",
"waiting",
"for",
"executing",
"tasks"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/parallel-manager.go#L141-L159 | train |
minio/mc | cmd/config-v9.go | newConfigV9 | func newConfigV9() *configV9 {
cfg := new(configV9)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV9)
return cfg
} | go | func newConfigV9() *configV9 {
cfg := new(configV9)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV9)
return cfg
} | [
"func",
"newConfigV9",
"(",
")",
"*",
"configV9",
"{",
"cfg",
":=",
"new",
"(",
"configV9",
")",
"\n",
"cfg",
".",
"Version",
"=",
"globalMCConfigVersion",
"\n",
"cfg",
".",
"Hosts",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"hostConfigV9",
")",
"\n... | // newConfigV9 - new config version. | [
"newConfigV9",
"-",
"new",
"config",
"version",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-v9.go#L54-L59 | train |
minio/mc | cmd/config-v9.go | loadConfigV9 | func loadConfigV9() (*configV9, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// If already cached, return the cached value.
if cacheCfgV9 != nil {
return cacheCfgV9, nil
}
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
// Initialize a new config loader.
qc, e := quick.NewConfig(newConfigV9(), nil)
if e != nil {
return nil, probe.NewError(e)
}
// Load config at configPath, fails if config is not
// accessible, malformed or version missing.
if e = qc.Load(mustGetMcConfigPath()); e != nil {
return nil, probe.NewError(e)
}
cfgV9 := qc.Data().(*configV9)
// Cache config.
cacheCfgV9 = cfgV9
// Success.
return cfgV9, nil
} | go | func loadConfigV9() (*configV9, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// If already cached, return the cached value.
if cacheCfgV9 != nil {
return cacheCfgV9, nil
}
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
// Initialize a new config loader.
qc, e := quick.NewConfig(newConfigV9(), nil)
if e != nil {
return nil, probe.NewError(e)
}
// Load config at configPath, fails if config is not
// accessible, malformed or version missing.
if e = qc.Load(mustGetMcConfigPath()); e != nil {
return nil, probe.NewError(e)
}
cfgV9 := qc.Data().(*configV9)
// Cache config.
cacheCfgV9 = cfgV9
// Success.
return cfgV9, nil
} | [
"func",
"loadConfigV9",
"(",
")",
"(",
"*",
"configV9",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"cfgMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cfgMutex",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"cacheCfgV9",
"!=",
"nil",
"{",
"return",
"cacheCf... | // loadConfigV9 - loads a new config. | [
"loadConfigV9",
"-",
"loads",
"a",
"new",
"config",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-v9.go#L108-L140 | train |
minio/mc | cmd/config-v9.go | saveConfigV9 | func saveConfigV9(cfgV9 *configV9) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, e := quick.NewConfig(cfgV9, nil)
if e != nil {
return probe.NewError(e)
}
// update the cache.
cacheCfgV9 = cfgV9
e = qs.Save(mustGetMcConfigPath())
if e != nil {
return probe.NewError(e).Trace(mustGetMcConfigPath())
}
return nil
} | go | func saveConfigV9(cfgV9 *configV9) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, e := quick.NewConfig(cfgV9, nil)
if e != nil {
return probe.NewError(e)
}
// update the cache.
cacheCfgV9 = cfgV9
e = qs.Save(mustGetMcConfigPath())
if e != nil {
return probe.NewError(e).Trace(mustGetMcConfigPath())
}
return nil
} | [
"func",
"saveConfigV9",
"(",
"cfgV9",
"*",
"configV9",
")",
"*",
"probe",
".",
"Error",
"{",
"cfgMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cfgMutex",
".",
"Unlock",
"(",
")",
"\n",
"qs",
",",
"e",
":=",
"quick",
".",
"NewConfig",
"(",
"cfgV9",
... | // saveConfigV8 - saves an updated config. | [
"saveConfigV8",
"-",
"saves",
"an",
"updated",
"config",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-v9.go#L143-L160 | train |
minio/mc | cmd/access-perms.go | isValidAccessPERM | func (b accessPerms) isValidAccessPERM() bool {
switch b {
case accessNone, accessDownload, accessUpload, accessPublic:
return true
}
return false
} | go | func (b accessPerms) isValidAccessPERM() bool {
switch b {
case accessNone, accessDownload, accessUpload, accessPublic:
return true
}
return false
} | [
"func",
"(",
"b",
"accessPerms",
")",
"isValidAccessPERM",
"(",
")",
"bool",
"{",
"switch",
"b",
"{",
"case",
"accessNone",
",",
"accessDownload",
",",
"accessUpload",
",",
"accessPublic",
":",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}... | // isValidAccessPERM - is provided access perm string supported. | [
"isValidAccessPERM",
"-",
"is",
"provided",
"access",
"perm",
"string",
"supported",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/access-perms.go#L22-L28 | train |
minio/mc | cmd/ls-main.go | checkListSyntax | func checkListSyntax(ctx *cli.Context) {
args := ctx.Args()
if !ctx.Args().Present() {
args = []string{"."}
}
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// extract URLs.
URLs := ctx.Args()
isIncomplete := ctx.Bool("incomplete")
for _, url := range URLs {
_, _, err := url2Stat(url, false, nil)
if err != nil && !isURLPrefixExists(url, isIncomplete) {
// Bucket name empty is a valid error for 'ls myminio',
// treat it as such.
if _, ok := err.ToGoError().(BucketNameEmpty); ok {
continue
}
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
} | go | func checkListSyntax(ctx *cli.Context) {
args := ctx.Args()
if !ctx.Args().Present() {
args = []string{"."}
}
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// extract URLs.
URLs := ctx.Args()
isIncomplete := ctx.Bool("incomplete")
for _, url := range URLs {
_, _, err := url2Stat(url, false, nil)
if err != nil && !isURLPrefixExists(url, isIncomplete) {
// Bucket name empty is a valid error for 'ls myminio',
// treat it as such.
if _, ok := err.ToGoError().(BucketNameEmpty); ok {
continue
}
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
} | [
"func",
"checkListSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"if",
"!",
"ctx",
".",
"Args",
"(",
")",
".",
"Present",
"(",
")",
"{",
"args",
"=",
"[",
"]",
"string",
"{",
"\".\""... | // checkListSyntax - validate all the passed arguments | [
"checkListSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/ls-main.go#L80-L105 | train |
minio/mc | cmd/ls-main.go | mainList | func mainList(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("File", color.New(color.Bold))
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
console.SetColor("Size", color.New(color.FgYellow))
console.SetColor("Time", color.New(color.FgGreen))
// check 'ls' cli arguments.
checkListSyntax(ctx)
// Set command flags from context.
isRecursive := ctx.Bool("recursive")
isIncomplete := ctx.Bool("incomplete")
args := ctx.Args()
// mimic operating system tool behavior.
if !ctx.Args().Present() {
args = []string{"."}
}
var cErr error
for _, targetURL := range args {
clnt, err := newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) {
var st *clientContent
st, err = clnt.Stat(isIncomplete, false, nil)
if err == nil && st.Type.IsDir() {
targetURL = targetURL + string(clnt.GetURL().Separator)
clnt, err = newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
}
}
if e := doList(clnt, isRecursive, isIncomplete); e != nil {
cErr = e
}
}
return cErr
} | go | func mainList(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("File", color.New(color.Bold))
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
console.SetColor("Size", color.New(color.FgYellow))
console.SetColor("Time", color.New(color.FgGreen))
// check 'ls' cli arguments.
checkListSyntax(ctx)
// Set command flags from context.
isRecursive := ctx.Bool("recursive")
isIncomplete := ctx.Bool("incomplete")
args := ctx.Args()
// mimic operating system tool behavior.
if !ctx.Args().Present() {
args = []string{"."}
}
var cErr error
for _, targetURL := range args {
clnt, err := newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) {
var st *clientContent
st, err = clnt.Stat(isIncomplete, false, nil)
if err == nil && st.Type.IsDir() {
targetURL = targetURL + string(clnt.GetURL().Separator)
clnt, err = newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
}
}
if e := doList(clnt, isRecursive, isIncomplete); e != nil {
cErr = e
}
}
return cErr
} | [
"func",
"mainList",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"console",
".",
"SetColor",
"(",
"\"File\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"Bold",
")",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"Dir\"",
",",
"color",... | // mainList - is a handler for mc ls command | [
"mainList",
"-",
"is",
"a",
"handler",
"for",
"mc",
"ls",
"command"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/ls-main.go#L108-L148 | train |
minio/mc | cmd/complete.go | mainComplete | func mainComplete() error {
// Recursively register all commands and subcommands
// along with global and local flags
var complCmds = make(complete.Commands)
for _, cmd := range appCmds {
complCmds[cmd.Name] = cmdToCompleteCmd(cmd, "")
}
complFlags := flagsToCompleteFlags(globalFlags)
mcComplete := complete.Command{
Sub: complCmds,
GlobalFlags: complFlags,
}
// Answer to bash completion call
complete.New("mc", mcComplete).Run()
return nil
} | go | func mainComplete() error {
// Recursively register all commands and subcommands
// along with global and local flags
var complCmds = make(complete.Commands)
for _, cmd := range appCmds {
complCmds[cmd.Name] = cmdToCompleteCmd(cmd, "")
}
complFlags := flagsToCompleteFlags(globalFlags)
mcComplete := complete.Command{
Sub: complCmds,
GlobalFlags: complFlags,
}
// Answer to bash completion call
complete.New("mc", mcComplete).Run()
return nil
} | [
"func",
"mainComplete",
"(",
")",
"error",
"{",
"var",
"complCmds",
"=",
"make",
"(",
"complete",
".",
"Commands",
")",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"appCmds",
"{",
"complCmds",
"[",
"cmd",
".",
"Name",
"]",
"=",
"cmdToCompleteCmd",
"("... | // Main function to answer to bash completion calls | [
"Main",
"function",
"to",
"answer",
"to",
"bash",
"completion",
"calls"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/complete.go#L242-L257 | train |
minio/mc | cmd/client-s3-trace_v2.go | Response | func (t traceV2) Response(resp *http.Response) (err error) {
var respTrace []byte
// For errors we make sure to dump response body as well.
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
} else {
respTrace, err = httputil.DumpResponse(resp, false)
}
if err == nil {
console.Debug(string(respTrace))
}
if globalInsecure && resp.TLS != nil {
dumpTLSCertificates(resp.TLS)
}
return err
} | go | func (t traceV2) Response(resp *http.Response) (err error) {
var respTrace []byte
// For errors we make sure to dump response body as well.
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
} else {
respTrace, err = httputil.DumpResponse(resp, false)
}
if err == nil {
console.Debug(string(respTrace))
}
if globalInsecure && resp.TLS != nil {
dumpTLSCertificates(resp.TLS)
}
return err
} | [
"func",
"(",
"t",
"traceV2",
")",
"Response",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"err",
"error",
")",
"{",
"var",
"respTrace",
"[",
"]",
"byte",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"&&",
"resp",
"... | // Response - Trace HTTP Response | [
"Response",
"-",
"Trace",
"HTTP",
"Response"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3-trace_v2.go#L60-L79 | train |
minio/mc | cmd/client-fs.go | fsNew | func fsNew(path string) (Client, *probe.Error) {
if strings.TrimSpace(path) == "" {
return nil, probe.NewError(EmptyPath{})
}
return &fsClient{
PathURL: newClientURL(normalizePath(path)),
}, nil
} | go | func fsNew(path string) (Client, *probe.Error) {
if strings.TrimSpace(path) == "" {
return nil, probe.NewError(EmptyPath{})
}
return &fsClient{
PathURL: newClientURL(normalizePath(path)),
}, nil
} | [
"func",
"fsNew",
"(",
"path",
"string",
")",
"(",
"Client",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"path",
")",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"probe",
".",
"NewError",
"(",
"EmptyPath",
"{",
"}... | // fsNew - instantiate a new fs | [
"fsNew",
"-",
"instantiate",
"a",
"new",
"fs"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L58-L65 | train |
minio/mc | cmd/client-fs.go | isIgnoredFile | func isIgnoredFile(filename string) bool {
matchFile := path.Base(filename)
// OS specific ignore list.
for _, ignoredFile := range ignoreFiles[runtime.GOOS] {
matched, err := filepath.Match(ignoredFile, matchFile)
if err != nil {
panic(err)
}
if matched {
return true
}
}
// Default ignore list for all OSes.
for _, ignoredFile := range ignoreFiles["default"] {
matched, err := filepath.Match(ignoredFile, matchFile)
if err != nil {
panic(err)
}
if matched {
return true
}
}
return false
} | go | func isIgnoredFile(filename string) bool {
matchFile := path.Base(filename)
// OS specific ignore list.
for _, ignoredFile := range ignoreFiles[runtime.GOOS] {
matched, err := filepath.Match(ignoredFile, matchFile)
if err != nil {
panic(err)
}
if matched {
return true
}
}
// Default ignore list for all OSes.
for _, ignoredFile := range ignoreFiles["default"] {
matched, err := filepath.Match(ignoredFile, matchFile)
if err != nil {
panic(err)
}
if matched {
return true
}
}
return false
} | [
"func",
"isIgnoredFile",
"(",
"filename",
"string",
")",
"bool",
"{",
"matchFile",
":=",
"path",
".",
"Base",
"(",
"filename",
")",
"\n",
"for",
"_",
",",
"ignoredFile",
":=",
"range",
"ignoreFiles",
"[",
"runtime",
".",
"GOOS",
"]",
"{",
"matched",
",",... | // isIgnoredFile returns true if 'filename' is on the exclude list. | [
"isIgnoredFile",
"returns",
"true",
"if",
"filename",
"is",
"on",
"the",
"exclude",
"list",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L81-L107 | train |
minio/mc | cmd/client-fs.go | Select | func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
return nil, probe.NewError(APINotImplemented{})
} | go | func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
return nil, probe.NewError(APINotImplemented{})
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Select",
"(",
"expression",
"string",
",",
"sse",
"encrypt",
".",
"ServerSide",
",",
"opts",
"SelectObjectOpts",
")",
"(",
"io",
".",
"ReadCloser",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"return",
"nil",
","... | // Select replies a stream of query results. | [
"Select",
"replies",
"a",
"stream",
"of",
"query",
"results",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L115-L117 | train |
minio/mc | cmd/client-fs.go | Watch | func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
in, out := PipeChan(1000)
var fsEvents []notify.Event
for _, event := range params.events {
switch event {
case "put":
fsEvents = append(fsEvents, EventTypePut...)
case "delete":
fsEvents = append(fsEvents, EventTypeDelete...)
case "get":
fsEvents = append(fsEvents, EventTypeGet...)
default:
return nil, errInvalidArgument().Trace(event)
}
}
// Set up a watchpoint listening for events within a directory tree rooted
// at current working directory. Dispatch remove events to c.
recursivePath := f.PathURL.Path
if params.recursive {
recursivePath = f.PathURL.Path + "..."
}
if e := notify.Watch(recursivePath, in, fsEvents...); e != nil {
return nil, probe.NewError(e)
}
// wait for doneChan to close the watcher, eventChan and errorChan
go func() {
<-doneChan
close(eventChan)
close(errorChan)
notify.Stop(in)
}()
timeFormatFS := "2006-01-02T15:04:05.000Z"
// Get fsnotify notifications for events and errors, and sent them
// using eventChan and errorChan
go func() {
for event := range out {
if isIgnoredFile(event.Path()) {
continue
}
var i os.FileInfo
if IsPutEvent(event.Event()) {
// Look for any writes, send a response to indicate a full copy.
var e error
i, e = os.Stat(event.Path())
if e != nil {
if os.IsNotExist(e) {
continue
}
errorChan <- probe.NewError(e)
continue
}
if i.IsDir() {
// we want files
continue
}
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Type: EventCreate,
}
} else if IsDeleteEvent(event.Event()) {
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventRemove,
}
} else if IsGetEvent(event.Event()) {
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventAccessed,
}
}
}
}()
return &watchObject{
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
}, nil
} | go | func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
in, out := PipeChan(1000)
var fsEvents []notify.Event
for _, event := range params.events {
switch event {
case "put":
fsEvents = append(fsEvents, EventTypePut...)
case "delete":
fsEvents = append(fsEvents, EventTypeDelete...)
case "get":
fsEvents = append(fsEvents, EventTypeGet...)
default:
return nil, errInvalidArgument().Trace(event)
}
}
// Set up a watchpoint listening for events within a directory tree rooted
// at current working directory. Dispatch remove events to c.
recursivePath := f.PathURL.Path
if params.recursive {
recursivePath = f.PathURL.Path + "..."
}
if e := notify.Watch(recursivePath, in, fsEvents...); e != nil {
return nil, probe.NewError(e)
}
// wait for doneChan to close the watcher, eventChan and errorChan
go func() {
<-doneChan
close(eventChan)
close(errorChan)
notify.Stop(in)
}()
timeFormatFS := "2006-01-02T15:04:05.000Z"
// Get fsnotify notifications for events and errors, and sent them
// using eventChan and errorChan
go func() {
for event := range out {
if isIgnoredFile(event.Path()) {
continue
}
var i os.FileInfo
if IsPutEvent(event.Event()) {
// Look for any writes, send a response to indicate a full copy.
var e error
i, e = os.Stat(event.Path())
if e != nil {
if os.IsNotExist(e) {
continue
}
errorChan <- probe.NewError(e)
continue
}
if i.IsDir() {
// we want files
continue
}
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Type: EventCreate,
}
} else if IsDeleteEvent(event.Event()) {
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventRemove,
}
} else if IsGetEvent(event.Event()) {
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventAccessed,
}
}
}
}()
return &watchObject{
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
}, nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Watch",
"(",
"params",
"watchParams",
")",
"(",
"*",
"watchObject",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"eventChan",
":=",
"make",
"(",
"chan",
"EventInfo",
")",
"\n",
"errorChan",
":=",
"make",
"(",
"c... | // Watches for all fs events on an input path. | [
"Watches",
"for",
"all",
"fs",
"events",
"on",
"an",
"input",
"path",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L120-L213 | train |
minio/mc | cmd/client-fs.go | Put | func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
return f.put(reader, size, nil, progress)
} | go | func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
return f.put(reader, size, nil, progress)
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"reader",
"io",
".",
"Reader",
",",
"size",
"int64",
",",
"metadata",
"map",
"[",
"string",
"]",
"string",
",",
"progress",
"io",
".",
"Reader",
",",
"sse",
... | // Put - create a new file with metadata. | [
"Put",
"-",
"create",
"a",
"new",
"file",
"with",
"metadata",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L345-L347 | train |
minio/mc | cmd/client-fs.go | ShareDownload | func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(APINotImplemented{
API: "ShareDownload",
APIType: "filesystem",
})
} | go | func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(APINotImplemented{
API: "ShareDownload",
APIType: "filesystem",
})
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"ShareDownload",
"(",
"expires",
"time",
".",
"Duration",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"return",
"\"\"",
",",
"probe",
".",
"NewError",
"(",
"APINotImplemented",
"{",
"API",
":",... | // ShareDownload - share download not implemented for filesystem. | [
"ShareDownload",
"-",
"share",
"download",
"not",
"implemented",
"for",
"filesystem",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L350-L355 | train |
minio/mc | cmd/client-fs.go | ShareUpload | func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
return "", nil, probe.NewError(APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
})
} | go | func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
return "", nil, probe.NewError(APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
})
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"ShareUpload",
"(",
"startsWith",
"bool",
",",
"expires",
"time",
".",
"Duration",
",",
"contentType",
"string",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",... | // ShareUpload - share upload not implemented for filesystem. | [
"ShareUpload",
"-",
"share",
"upload",
"not",
"implemented",
"for",
"filesystem",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L358-L363 | train |
minio/mc | cmd/client-fs.go | readFile | func readFile(fpath string) (io.ReadCloser, error) {
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, "/") {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
return nil, e
}
fileData, e := os.Open(fpath)
if e != nil {
return nil, e
}
return fileData, nil
} | go | func readFile(fpath string) (io.ReadCloser, error) {
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, "/") {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
return nil, e
}
fileData, e := os.Open(fpath)
if e != nil {
return nil, e
}
return fileData, nil
} | [
"func",
"readFile",
"(",
"fpath",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"fpath",
",",
"\"/\"",
")",
"{",
"fpath",
"=",
"fpath",
"+",
"\".\"",
"\n",
"}",
"\n",
"fpath",
",",
"e",... | // readFile reads and returns the data inside the file located
// at the provided filepath. | [
"readFile",
"reads",
"and",
"returns",
"the",
"data",
"inside",
"the",
"file",
"located",
"at",
"the",
"provided",
"filepath",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L367-L382 | train |
minio/mc | cmd/client-fs.go | Copy | func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
destination := f.PathURL.Path
rc, e := readFile(source)
if e != nil {
err := f.toClientError(e, destination)
return err.Trace(destination)
}
defer rc.Close()
_, err := f.put(rc, size, map[string][]string{}, progress)
if err != nil {
return err.Trace(destination, source)
}
return nil
} | go | func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
destination := f.PathURL.Path
rc, e := readFile(source)
if e != nil {
err := f.toClientError(e, destination)
return err.Trace(destination)
}
defer rc.Close()
_, err := f.put(rc, size, map[string][]string{}, progress)
if err != nil {
return err.Trace(destination, source)
}
return nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Copy",
"(",
"source",
"string",
",",
"size",
"int64",
",",
"progress",
"io",
".",
"Reader",
",",
"srcSSE",
",",
"tgtSSE",
"encrypt",
".",
"ServerSide",
",",
"metadata",
"map",
"[",
"string",
"]",
"string",
")",
... | // Copy - copy data from source to destination | [
"Copy",
"-",
"copy",
"data",
"from",
"source",
"to",
"destination"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L385-L399 | train |
minio/mc | cmd/client-fs.go | get | func (f *fsClient) get() (io.ReadCloser, *probe.Error) {
tmppath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(tmppath, string(f.PathURL.Separator)) {
tmppath = tmppath + "."
}
// Resolve symlinks.
_, e := filepath.EvalSymlinks(tmppath)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(f.PathURL.Path)
}
fileData, e := os.Open(f.PathURL.Path)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(f.PathURL.Path)
}
return fileData, nil
} | go | func (f *fsClient) get() (io.ReadCloser, *probe.Error) {
tmppath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(tmppath, string(f.PathURL.Separator)) {
tmppath = tmppath + "."
}
// Resolve symlinks.
_, e := filepath.EvalSymlinks(tmppath)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(f.PathURL.Path)
}
fileData, e := os.Open(f.PathURL.Path)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(f.PathURL.Path)
}
return fileData, nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"get",
"(",
")",
"(",
"io",
".",
"ReadCloser",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"tmppath",
":=",
"f",
".",
"PathURL",
".",
"Path",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"tmppath",
",",
"st... | // get - get wrapper returning object reader. | [
"get",
"-",
"get",
"wrapper",
"returning",
"object",
"reader",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L402-L422 | train |
minio/mc | cmd/client-fs.go | Get | func (f *fsClient) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
return f.get()
} | go | func (f *fsClient) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
return f.get()
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Get",
"(",
"sse",
"encrypt",
".",
"ServerSide",
")",
"(",
"io",
".",
"ReadCloser",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"return",
"f",
".",
"get",
"(",
")",
"\n",
"}"
] | // Get returns reader and any additional metadata. | [
"Get",
"returns",
"reader",
"and",
"any",
"additional",
"metadata",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L425-L427 | train |
minio/mc | cmd/client-fs.go | Remove | func (f *fsClient) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) <-chan *probe.Error {
errorCh := make(chan *probe.Error)
// Goroutine reads from contentCh and removes the entry in content.
go func() {
defer close(errorCh)
for content := range contentCh {
name := content.URL.Path
// Add partSuffix for incomplete uploads.
if isIncomplete {
name += partSuffix
}
if err := os.Remove(name); err != nil {
if os.IsPermission(err) {
// Ignore permission error.
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
} else {
errorCh <- probe.NewError(err)
return
}
}
}
}()
return errorCh
} | go | func (f *fsClient) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) <-chan *probe.Error {
errorCh := make(chan *probe.Error)
// Goroutine reads from contentCh and removes the entry in content.
go func() {
defer close(errorCh)
for content := range contentCh {
name := content.URL.Path
// Add partSuffix for incomplete uploads.
if isIncomplete {
name += partSuffix
}
if err := os.Remove(name); err != nil {
if os.IsPermission(err) {
// Ignore permission error.
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
} else {
errorCh <- probe.NewError(err)
return
}
}
}
}()
return errorCh
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Remove",
"(",
"isIncomplete",
",",
"isRemoveBucket",
"bool",
",",
"contentCh",
"<-",
"chan",
"*",
"clientContent",
")",
"<-",
"chan",
"*",
"probe",
".",
"Error",
"{",
"errorCh",
":=",
"make",
"(",
"chan",
"*",
"... | // Remove - remove entry read from clientContent channel. | [
"Remove",
"-",
"remove",
"entry",
"read",
"from",
"clientContent",
"channel",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L430-L456 | train |
minio/mc | cmd/client-fs.go | List | func (f *fsClient) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent {
contentCh := make(chan *clientContent)
filteredCh := make(chan *clientContent)
if isRecursive {
if showDir == DirNone {
go f.listRecursiveInRoutine(contentCh)
} else {
go f.listDirOpt(contentCh, isIncomplete, showDir)
}
} else {
go f.listInRoutine(contentCh)
}
// This function filters entries from any listing go routine
// created previously. If isIncomplete is activated, we will
// only show partly uploaded files,
go func() {
for c := range contentCh {
if isIncomplete {
if !strings.HasSuffix(c.URL.Path, partSuffix) {
continue
}
// Strip part suffix
c.URL.Path = strings.Split(c.URL.Path, partSuffix)[0]
} else {
if strings.HasSuffix(c.URL.Path, partSuffix) {
continue
}
}
// Send to filtered channel
filteredCh <- c
}
defer close(filteredCh)
}()
return filteredCh
} | go | func (f *fsClient) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent {
contentCh := make(chan *clientContent)
filteredCh := make(chan *clientContent)
if isRecursive {
if showDir == DirNone {
go f.listRecursiveInRoutine(contentCh)
} else {
go f.listDirOpt(contentCh, isIncomplete, showDir)
}
} else {
go f.listInRoutine(contentCh)
}
// This function filters entries from any listing go routine
// created previously. If isIncomplete is activated, we will
// only show partly uploaded files,
go func() {
for c := range contentCh {
if isIncomplete {
if !strings.HasSuffix(c.URL.Path, partSuffix) {
continue
}
// Strip part suffix
c.URL.Path = strings.Split(c.URL.Path, partSuffix)[0]
} else {
if strings.HasSuffix(c.URL.Path, partSuffix) {
continue
}
}
// Send to filtered channel
filteredCh <- c
}
defer close(filteredCh)
}()
return filteredCh
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"List",
"(",
"isRecursive",
",",
"isIncomplete",
"bool",
",",
"showDir",
"DirOpt",
")",
"<-",
"chan",
"*",
"clientContent",
"{",
"contentCh",
":=",
"make",
"(",
"chan",
"*",
"clientContent",
")",
"\n",
"filteredCh",
... | // List - list files and folders. | [
"List",
"-",
"list",
"files",
"and",
"folders",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L459-L496 | train |
minio/mc | cmd/client-fs.go | readDir | func readDir(dirname string) ([]os.FileInfo, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
sort.Sort(byDirName(list))
return list, nil
} | go | func readDir(dirname string) ([]os.FileInfo, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
sort.Sort(byDirName(list))
return list, nil
} | [
"func",
"readDir",
"(",
"dirname",
"string",
")",
"(",
"[",
"]",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"f",
",",
"e",
":=",
"os",
".",
"Open",
"(",
"dirname",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"nil",
",",
"e",
"\n",
"... | // readDir reads the directory named by dirname and returns
// a list of sorted directory entries. | [
"readDir",
"reads",
"the",
"directory",
"named",
"by",
"dirname",
"and",
"returns",
"a",
"list",
"of",
"sorted",
"directory",
"entries",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L519-L533 | train |
minio/mc | cmd/client-fs.go | listPrefixes | func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent) {
dirName := filepath.Dir(prefix)
files, e := readDir(dirName)
if e != nil {
err := f.toClientError(e, dirName)
contentCh <- &clientContent{
Err: err.Trace(dirName),
}
return
}
pathURL := *f.PathURL
for _, fi := range files {
// Skip ignored files.
if isIgnoredFile(fi.Name()) {
continue
}
file := filepath.Join(dirName, fi.Name())
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
st, e := os.Stat(file)
if e != nil {
if os.IsPermission(e) {
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
}
if os.IsNotExist(e) {
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
if e != nil {
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
}
}
if strings.HasPrefix(file, prefix) {
contentCh <- &clientContent{
URL: *newClientURL(file),
Time: st.ModTime(),
Size: st.Size(),
Type: st.Mode(),
Err: nil,
}
continue
}
}
if strings.HasPrefix(file, prefix) {
contentCh <- &clientContent{
URL: *newClientURL(file),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
Err: nil,
}
}
}
return
} | go | func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent) {
dirName := filepath.Dir(prefix)
files, e := readDir(dirName)
if e != nil {
err := f.toClientError(e, dirName)
contentCh <- &clientContent{
Err: err.Trace(dirName),
}
return
}
pathURL := *f.PathURL
for _, fi := range files {
// Skip ignored files.
if isIgnoredFile(fi.Name()) {
continue
}
file := filepath.Join(dirName, fi.Name())
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
st, e := os.Stat(file)
if e != nil {
if os.IsPermission(e) {
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
}
if os.IsNotExist(e) {
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
if e != nil {
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
}
}
if strings.HasPrefix(file, prefix) {
contentCh <- &clientContent{
URL: *newClientURL(file),
Time: st.ModTime(),
Size: st.Size(),
Type: st.Mode(),
Err: nil,
}
continue
}
}
if strings.HasPrefix(file, prefix) {
contentCh <- &clientContent{
URL: *newClientURL(file),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
Err: nil,
}
}
}
return
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"listPrefixes",
"(",
"prefix",
"string",
",",
"contentCh",
"chan",
"<-",
"*",
"clientContent",
")",
"{",
"dirName",
":=",
"filepath",
".",
"Dir",
"(",
"prefix",
")",
"\n",
"files",
",",
"e",
":=",
"readDir",
"(",... | // listPrefixes - list all files for any given prefix. | [
"listPrefixes",
"-",
"list",
"all",
"files",
"for",
"any",
"given",
"prefix",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L536-L602 | train |
minio/mc | cmd/client-fs.go | listDirOpt | func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool, dirOpt DirOpt) {
defer close(contentCh)
// Trim trailing / or \.
currentPath := f.PathURL.Path
currentPath = strings.TrimSuffix(currentPath, "/")
if runtime.GOOS == "windows" {
currentPath = strings.TrimSuffix(currentPath, `\`)
}
// Closure function reads currentPath and sends to contentCh. If a directory is found, it lists the directory content recursively.
var listDir func(currentPath string) bool
listDir = func(currentPath string) (isStop bool) {
files, err := readDir(currentPath)
if err != nil {
if os.IsPermission(err) {
contentCh <- &clientContent{Err: probe.NewError(PathInsufficientPermission{Path: currentPath})}
return false
}
contentCh <- &clientContent{Err: probe.NewError(err)}
return true
}
for _, file := range files {
name := filepath.Join(currentPath, file.Name())
content := clientContent{
URL: *newClientURL(name),
Time: file.ModTime(),
Size: file.Size(),
Type: file.Mode(),
Err: nil,
}
if file.Mode().IsDir() {
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &content
}
if listDir(filepath.Join(name)) {
return true
}
if dirOpt == DirLast && !isIncomplete {
contentCh <- &content
}
continue
}
contentCh <- &content
}
return false
}
// listDir() does not send currentPath to contentCh. We send it here depending on dirOpt.
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
listDir(currentPath)
if dirOpt == DirLast && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
} | go | func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool, dirOpt DirOpt) {
defer close(contentCh)
// Trim trailing / or \.
currentPath := f.PathURL.Path
currentPath = strings.TrimSuffix(currentPath, "/")
if runtime.GOOS == "windows" {
currentPath = strings.TrimSuffix(currentPath, `\`)
}
// Closure function reads currentPath and sends to contentCh. If a directory is found, it lists the directory content recursively.
var listDir func(currentPath string) bool
listDir = func(currentPath string) (isStop bool) {
files, err := readDir(currentPath)
if err != nil {
if os.IsPermission(err) {
contentCh <- &clientContent{Err: probe.NewError(PathInsufficientPermission{Path: currentPath})}
return false
}
contentCh <- &clientContent{Err: probe.NewError(err)}
return true
}
for _, file := range files {
name := filepath.Join(currentPath, file.Name())
content := clientContent{
URL: *newClientURL(name),
Time: file.ModTime(),
Size: file.Size(),
Type: file.Mode(),
Err: nil,
}
if file.Mode().IsDir() {
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &content
}
if listDir(filepath.Join(name)) {
return true
}
if dirOpt == DirLast && !isIncomplete {
contentCh <- &content
}
continue
}
contentCh <- &content
}
return false
}
// listDir() does not send currentPath to contentCh. We send it here depending on dirOpt.
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
listDir(currentPath)
if dirOpt == DirLast && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"listDirOpt",
"(",
"contentCh",
"chan",
"*",
"clientContent",
",",
"isIncomplete",
"bool",
",",
"dirOpt",
"DirOpt",
")",
"{",
"defer",
"close",
"(",
"contentCh",
")",
"\n",
"currentPath",
":=",
"f",
".",
"PathURL",
... | // List files recursively using non-recursive mode. | [
"List",
"files",
"recursively",
"using",
"non",
"-",
"recursive",
"mode",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L698-L762 | train |
minio/mc | cmd/client-fs.go | MakeBucket | func (f *fsClient) MakeBucket(region string, ignoreExisting bool) *probe.Error {
// TODO: ignoreExisting has no effect currently. In the future, we want
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
// otherwise.
e := os.MkdirAll(f.PathURL.Path, 0777)
if e != nil {
return probe.NewError(e)
}
return nil
} | go | func (f *fsClient) MakeBucket(region string, ignoreExisting bool) *probe.Error {
// TODO: ignoreExisting has no effect currently. In the future, we want
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
// otherwise.
e := os.MkdirAll(f.PathURL.Path, 0777)
if e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"MakeBucket",
"(",
"region",
"string",
",",
"ignoreExisting",
"bool",
")",
"*",
"probe",
".",
"Error",
"{",
"e",
":=",
"os",
".",
"MkdirAll",
"(",
"f",
".",
"PathURL",
".",
"Path",
",",
"0777",
")",
"\n",
"if... | // MakeBucket - create a new bucket. | [
"MakeBucket",
"-",
"create",
"a",
"new",
"bucket",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L891-L900 | train |
minio/mc | cmd/client-fs.go | GetAccessRules | func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
return map[string]string{}, probe.NewError(APINotImplemented{
API: "ListBucketPolicies",
APIType: "filesystem",
})
} | go | func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
return map[string]string{}, probe.NewError(APINotImplemented{
API: "ListBucketPolicies",
APIType: "filesystem",
})
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"GetAccessRules",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"return",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"probe",
".",
"NewError",
"(",
... | // GetAccessRules - unsupported API | [
"GetAccessRules",
"-",
"unsupported",
"API"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L903-L908 | train |
minio/mc | cmd/client-fs.go | GetAccess | func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) {
// For windows this feature is not implemented.
if runtime.GOOS == "windows" {
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
st, err := f.fsStat(false)
if err != nil {
return "", "", err.Trace(f.PathURL.String())
}
if !st.Mode().IsDir() {
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
// Mask with os.ModePerm to get only inode permissions
switch st.Mode() & os.ModePerm {
case os.FileMode(0777):
return "readwrite", "", nil
case os.FileMode(0555):
return "readonly", "", nil
case os.FileMode(0333):
return "writeonly", "", nil
}
return "none", "", nil
} | go | func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) {
// For windows this feature is not implemented.
if runtime.GOOS == "windows" {
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
st, err := f.fsStat(false)
if err != nil {
return "", "", err.Trace(f.PathURL.String())
}
if !st.Mode().IsDir() {
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
}
// Mask with os.ModePerm to get only inode permissions
switch st.Mode() & os.ModePerm {
case os.FileMode(0777):
return "readwrite", "", nil
case os.FileMode(0555):
return "readonly", "", nil
case os.FileMode(0333):
return "writeonly", "", nil
}
return "none", "", nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"GetAccess",
"(",
")",
"(",
"access",
"string",
",",
"policyJSON",
"string",
",",
"err",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"{",
"return",
"\"\"",
",",
"\"\... | // GetAccess - get access policy permissions. | [
"GetAccess",
"-",
"get",
"access",
"policy",
"permissions",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L911-L933 | train |
minio/mc | cmd/client-fs.go | SetAccess | func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
// For windows this feature is not implemented.
// JSON policy for fs is not yet implemented.
if runtime.GOOS == "windows" || isJSON {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
st, err := f.fsStat(false)
if err != nil {
return err.Trace(f.PathURL.String())
}
if !st.Mode().IsDir() {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
var mode os.FileMode
switch access {
case "readonly":
mode = os.FileMode(0555)
case "writeonly":
mode = os.FileMode(0333)
case "readwrite":
mode = os.FileMode(0777)
case "none":
mode = os.FileMode(0755)
}
e := os.Chmod(f.PathURL.Path, mode)
if e != nil {
return probe.NewError(e)
}
return nil
} | go | func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
// For windows this feature is not implemented.
// JSON policy for fs is not yet implemented.
if runtime.GOOS == "windows" || isJSON {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
st, err := f.fsStat(false)
if err != nil {
return err.Trace(f.PathURL.String())
}
if !st.Mode().IsDir() {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
var mode os.FileMode
switch access {
case "readonly":
mode = os.FileMode(0555)
case "writeonly":
mode = os.FileMode(0333)
case "readwrite":
mode = os.FileMode(0777)
case "none":
mode = os.FileMode(0755)
}
e := os.Chmod(f.PathURL.Path, mode)
if e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"SetAccess",
"(",
"access",
"string",
",",
"isJSON",
"bool",
")",
"*",
"probe",
".",
"Error",
"{",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"||",
"isJSON",
"{",
"return",
"probe",
".",
"NewError",
"(",
... | // SetAccess - set access policy permissions. | [
"SetAccess",
"-",
"set",
"access",
"policy",
"permissions",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L936-L965 | train |
minio/mc | cmd/client-fs.go | Stat | func (f *fsClient) Stat(isIncomplete, isFetchMeta bool, sse encrypt.ServerSide) (content *clientContent, err *probe.Error) {
st, err := f.fsStat(isIncomplete)
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
content = &clientContent{}
content.URL = *f.PathURL
content.Size = st.Size()
content.Time = st.ModTime()
content.Type = st.Mode()
content.Metadata = map[string]string{
"Content-Type": guessURLContentType(f.PathURL.Path),
}
// isFetchMeta is true only in the case of mc stat command which lists any extended attributes
// present for this object.
if isFetchMeta {
path := f.PathURL.String()
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
}
return content, nil
} | go | func (f *fsClient) Stat(isIncomplete, isFetchMeta bool, sse encrypt.ServerSide) (content *clientContent, err *probe.Error) {
st, err := f.fsStat(isIncomplete)
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
content = &clientContent{}
content.URL = *f.PathURL
content.Size = st.Size()
content.Time = st.ModTime()
content.Type = st.Mode()
content.Metadata = map[string]string{
"Content-Type": guessURLContentType(f.PathURL.Path),
}
// isFetchMeta is true only in the case of mc stat command which lists any extended attributes
// present for this object.
if isFetchMeta {
path := f.PathURL.String()
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
}
return content, nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"Stat",
"(",
"isIncomplete",
",",
"isFetchMeta",
"bool",
",",
"sse",
"encrypt",
".",
"ServerSide",
")",
"(",
"content",
"*",
"clientContent",
",",
"err",
"*",
"probe",
".",
"Error",
")",
"{",
"st",
",",
"err",
... | // Stat - get metadata from path. | [
"Stat",
"-",
"get",
"metadata",
"from",
"path",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L968-L997 | train |
minio/mc | cmd/client-fs.go | toClientError | func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
if os.IsPermission(e) {
return probe.NewError(PathInsufficientPermission{Path: fpath})
}
if os.IsNotExist(e) {
return probe.NewError(PathNotFound{Path: fpath})
}
return probe.NewError(e)
} | go | func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
if os.IsPermission(e) {
return probe.NewError(PathInsufficientPermission{Path: fpath})
}
if os.IsNotExist(e) {
return probe.NewError(PathNotFound{Path: fpath})
}
return probe.NewError(e)
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"toClientError",
"(",
"e",
"error",
",",
"fpath",
"string",
")",
"*",
"probe",
".",
"Error",
"{",
"if",
"os",
".",
"IsPermission",
"(",
"e",
")",
"{",
"return",
"probe",
".",
"NewError",
"(",
"PathInsufficientPer... | // toClientError error constructs a typed client error for known filesystem errors. | [
"toClientError",
"error",
"constructs",
"a",
"typed",
"client",
"error",
"for",
"known",
"filesystem",
"errors",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L1000-L1008 | train |
minio/mc | cmd/client-fs.go | fsStat | func (f *fsClient) fsStat(isIncomplete bool) (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
// Check if the path corresponds to a directory and returns
// the successful result whether isIncomplete is specified or not.
st, e := os.Stat(fpath)
if e == nil && st.IsDir() {
return st, nil
}
if isIncomplete {
fpath += partSuffix
}
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e = filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e = os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
}
return st, nil
} | go | func (f *fsClient) fsStat(isIncomplete bool) (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
// Check if the path corresponds to a directory and returns
// the successful result whether isIncomplete is specified or not.
st, e := os.Stat(fpath)
if e == nil && st.IsDir() {
return st, nil
}
if isIncomplete {
fpath += partSuffix
}
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e = filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e = os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
}
return st, nil
} | [
"func",
"(",
"f",
"*",
"fsClient",
")",
"fsStat",
"(",
"isIncomplete",
"bool",
")",
"(",
"os",
".",
"FileInfo",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"fpath",
":=",
"f",
".",
"PathURL",
".",
"Path",
"\n",
"st",
",",
"e",
":=",
"os",
".",
"... | // fsStat - wrapper function to get file stat. | [
"fsStat",
"-",
"wrapper",
"function",
"to",
"get",
"file",
"stat",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs.go#L1011-L1050 | train |
minio/mc | cmd/sql-main.go | getSQLFlags | func getSQLFlags() []cli.Flag {
flags := append(sqlFlags, ioFlags...)
for _, f := range globalFlags {
if f.GetName() != "json" {
flags = append(flags, f)
}
}
return flags
} | go | func getSQLFlags() []cli.Flag {
flags := append(sqlFlags, ioFlags...)
for _, f := range globalFlags {
if f.GetName() != "json" {
flags = append(flags, f)
}
}
return flags
} | [
"func",
"getSQLFlags",
"(",
")",
"[",
"]",
"cli",
".",
"Flag",
"{",
"flags",
":=",
"append",
"(",
"sqlFlags",
",",
"ioFlags",
"...",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"globalFlags",
"{",
"if",
"f",
".",
"GetName",
"(",
")",
"!=",
"\... | // filter json from allowed flags for sql command | [
"filter",
"json",
"from",
"allowed",
"flags",
"for",
"sql",
"command"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L127-L135 | train |
minio/mc | cmd/sql-main.go | parseKVArgs | func parseKVArgs(is string) (map[string]string, *probe.Error) {
kvmap := make(map[string]string)
var key, value string
var s, e int // tracking start and end of value
var index int // current index in string
if is != "" {
for index < len(is) {
i := strings.Index(is[index:], "=")
if i == -1 {
return nil, probe.NewError(errors.New("Arguments should be of the form key=value,... "))
}
key = is[index : index+i]
s = i + index + 1
e = strings.Index(is[s:], ",")
delimFound := false
for !delimFound {
if e == -1 || e+s >= len(is) {
delimFound = true
break
}
if string(is[s+e]) != "," {
delimFound = true
if string(is[s+e-1]) == "," {
e--
}
} else {
e++
}
}
var vEnd = len(is)
if e != -1 {
vEnd = s + e
}
value = is[s:vEnd]
index = vEnd + 1
if _, ok := kvmap[strings.ToLower(key)]; ok {
return nil, probe.NewError(fmt.Errorf("More than one key=value found for %s", strings.TrimSpace(key)))
}
kvmap[strings.ToLower(key)] = strings.NewReplacer(`\n`, "\n", `\t`, "\t", `\r`, "\r").Replace(value)
}
}
return kvmap, nil
} | go | func parseKVArgs(is string) (map[string]string, *probe.Error) {
kvmap := make(map[string]string)
var key, value string
var s, e int // tracking start and end of value
var index int // current index in string
if is != "" {
for index < len(is) {
i := strings.Index(is[index:], "=")
if i == -1 {
return nil, probe.NewError(errors.New("Arguments should be of the form key=value,... "))
}
key = is[index : index+i]
s = i + index + 1
e = strings.Index(is[s:], ",")
delimFound := false
for !delimFound {
if e == -1 || e+s >= len(is) {
delimFound = true
break
}
if string(is[s+e]) != "," {
delimFound = true
if string(is[s+e-1]) == "," {
e--
}
} else {
e++
}
}
var vEnd = len(is)
if e != -1 {
vEnd = s + e
}
value = is[s:vEnd]
index = vEnd + 1
if _, ok := kvmap[strings.ToLower(key)]; ok {
return nil, probe.NewError(fmt.Errorf("More than one key=value found for %s", strings.TrimSpace(key)))
}
kvmap[strings.ToLower(key)] = strings.NewReplacer(`\n`, "\n", `\t`, "\t", `\r`, "\r").Replace(value)
}
}
return kvmap, nil
} | [
"func",
"parseKVArgs",
"(",
"is",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"kvmap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"var",
"key",
",",
"value",
"string",
... | // parseKVArgs parses string of the form k=v delimited by ","
// into a map of k-v pairs | [
"parseKVArgs",
"parses",
"string",
"of",
"the",
"form",
"k",
"=",
"v",
"delimited",
"by",
"into",
"a",
"map",
"of",
"k",
"-",
"v",
"pairs"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L154-L197 | train |
minio/mc | cmd/sql-main.go | parseSerializationOpts | func parseSerializationOpts(inp string, validKeys []string, validAbbrKeys map[string]string) (map[string]string, *probe.Error) {
if validAbbrKeys == nil {
validAbbrKeys = make(map[string]string)
}
validKeyFn := func(key string, validKeys []string) bool {
for _, name := range validKeys {
if strings.ToLower(name) == strings.ToLower(key) {
return true
}
}
return false
}
kv, err := parseKVArgs(inp)
if err != nil {
return nil, err
}
ikv := make(map[string]string)
for k, v := range kv {
fldName, ok := validAbbrKeys[strings.ToLower(k)]
if ok {
ikv[strings.ToLower(fldName)] = v
} else {
ikv[strings.ToLower(k)] = v
}
}
for k := range ikv {
if !validKeyFn(k, validKeys) {
return nil, probe.NewError(errors.New("Options should be key-value pairs in the form key=value,... where valid key(s) are " + fmtString(validAbbrKeys, validKeys)))
}
}
return ikv, nil
} | go | func parseSerializationOpts(inp string, validKeys []string, validAbbrKeys map[string]string) (map[string]string, *probe.Error) {
if validAbbrKeys == nil {
validAbbrKeys = make(map[string]string)
}
validKeyFn := func(key string, validKeys []string) bool {
for _, name := range validKeys {
if strings.ToLower(name) == strings.ToLower(key) {
return true
}
}
return false
}
kv, err := parseKVArgs(inp)
if err != nil {
return nil, err
}
ikv := make(map[string]string)
for k, v := range kv {
fldName, ok := validAbbrKeys[strings.ToLower(k)]
if ok {
ikv[strings.ToLower(fldName)] = v
} else {
ikv[strings.ToLower(k)] = v
}
}
for k := range ikv {
if !validKeyFn(k, validKeys) {
return nil, probe.NewError(errors.New("Options should be key-value pairs in the form key=value,... where valid key(s) are " + fmtString(validAbbrKeys, validKeys)))
}
}
return ikv, nil
} | [
"func",
"parseSerializationOpts",
"(",
"inp",
"string",
",",
"validKeys",
"[",
"]",
"string",
",",
"validAbbrKeys",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"va... | // parses the input string and constructs a k-v map, replacing any abbreviated keys with actual keys | [
"parses",
"the",
"input",
"string",
"and",
"constructs",
"a",
"k",
"-",
"v",
"map",
"replacing",
"any",
"abbreviated",
"keys",
"with",
"actual",
"keys"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L219-L250 | train |
minio/mc | cmd/sql-main.go | getInputSerializationOpts | func getInputSerializationOpts(ctx *cli.Context) map[string]map[string]string {
icsv := ctx.String("csv-input")
ijson := ctx.String("json-input")
m := make(map[string]map[string]string)
csvType := ctx.IsSet("csv-input")
jsonType := ctx.IsSet("json-input")
if csvType && jsonType {
fatalIf(errInvalidArgument(), "Only one of --csv-input or --json-input can be specified as input serialization option")
}
if icsv != "" {
kv, err := parseSerializationOpts(icsv, append(validCSVCommonKeys, validCSVInputKeys...), validCSVInputAbbrKeys)
fatalIf(err, "Invalid serialization option(s) specified for --csv-input flag")
m["csv"] = kv
}
if ijson != "" {
kv, err := parseSerializationOpts(ijson, validJSONInputKeys, nil)
fatalIf(err, "Invalid serialization option(s) specified for --json-input flag")
m["json"] = kv
}
return m
} | go | func getInputSerializationOpts(ctx *cli.Context) map[string]map[string]string {
icsv := ctx.String("csv-input")
ijson := ctx.String("json-input")
m := make(map[string]map[string]string)
csvType := ctx.IsSet("csv-input")
jsonType := ctx.IsSet("json-input")
if csvType && jsonType {
fatalIf(errInvalidArgument(), "Only one of --csv-input or --json-input can be specified as input serialization option")
}
if icsv != "" {
kv, err := parseSerializationOpts(icsv, append(validCSVCommonKeys, validCSVInputKeys...), validCSVInputAbbrKeys)
fatalIf(err, "Invalid serialization option(s) specified for --csv-input flag")
m["csv"] = kv
}
if ijson != "" {
kv, err := parseSerializationOpts(ijson, validJSONInputKeys, nil)
fatalIf(err, "Invalid serialization option(s) specified for --json-input flag")
m["json"] = kv
}
return m
} | [
"func",
"getInputSerializationOpts",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"{",
"icsv",
":=",
"ctx",
".",
"String",
"(",
"\"csv-input\"",
")",
"\n",
"ijson",
":=",
"ctx",
".",
"Stri... | // gets the input serialization opts from cli context and constructs a map of csv, json or parquet options | [
"gets",
"the",
"input",
"serialization",
"opts",
"from",
"cli",
"context",
"and",
"constructs",
"a",
"map",
"of",
"csv",
"json",
"or",
"parquet",
"options"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L253-L278 | train |
minio/mc | cmd/sql-main.go | getOutputSerializationOpts | func getOutputSerializationOpts(ctx *cli.Context, csvHdrs []string) (opts map[string]map[string]string) {
m := make(map[string]map[string]string)
ocsv := ctx.String("csv-output")
ojson := ctx.String("json-output")
csvType := ctx.IsSet("csv-output")
jsonType := ctx.IsSet("json-output")
if csvType && jsonType {
fatalIf(errInvalidArgument(), "Only one of --csv-output, or --json-output can be specified as output serialization option")
}
if jsonType && len(csvHdrs) > 0 {
fatalIf(errInvalidArgument(), "--csv-output-header incompatible with --json-output option")
}
if csvType {
validKeys := append(validCSVCommonKeys, validJSONCSVCommonOutputKeys...)
kv, err := parseSerializationOpts(ocsv, append(validKeys, validCSVOutputKeys...), validCSVOutputAbbrKeys)
fatalIf(err, "Invalid value(s) specified for --csv-output flag")
m["csv"] = kv
}
if jsonType {
kv, err := parseSerializationOpts(ojson, validJSONCSVCommonOutputKeys, validJSONOutputAbbrKeys)
fatalIf(err, "Invalid value(s) specified for --json-output flag")
m["json"] = kv
}
return m
} | go | func getOutputSerializationOpts(ctx *cli.Context, csvHdrs []string) (opts map[string]map[string]string) {
m := make(map[string]map[string]string)
ocsv := ctx.String("csv-output")
ojson := ctx.String("json-output")
csvType := ctx.IsSet("csv-output")
jsonType := ctx.IsSet("json-output")
if csvType && jsonType {
fatalIf(errInvalidArgument(), "Only one of --csv-output, or --json-output can be specified as output serialization option")
}
if jsonType && len(csvHdrs) > 0 {
fatalIf(errInvalidArgument(), "--csv-output-header incompatible with --json-output option")
}
if csvType {
validKeys := append(validCSVCommonKeys, validJSONCSVCommonOutputKeys...)
kv, err := parseSerializationOpts(ocsv, append(validKeys, validCSVOutputKeys...), validCSVOutputAbbrKeys)
fatalIf(err, "Invalid value(s) specified for --csv-output flag")
m["csv"] = kv
}
if jsonType {
kv, err := parseSerializationOpts(ojson, validJSONCSVCommonOutputKeys, validJSONOutputAbbrKeys)
fatalIf(err, "Invalid value(s) specified for --json-output flag")
m["json"] = kv
}
return m
} | [
"func",
"getOutputSerializationOpts",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"csvHdrs",
"[",
"]",
"string",
")",
"(",
"opts",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string"... | // gets the output serialization opts from cli context and constructs a map of csv or json options | [
"gets",
"the",
"output",
"serialization",
"opts",
"from",
"cli",
"context",
"and",
"constructs",
"a",
"map",
"of",
"csv",
"or",
"json",
"options"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L281-L310 | train |
minio/mc | cmd/sql-main.go | getCSVHeader | func getCSVHeader(sourceURL string, encKeyDB map[string][]prefixSSEPair) ([]string, *probe.Error) {
var r io.ReadCloser
switch sourceURL {
case "-":
r = os.Stdin
default:
var err *probe.Error
var metadata map[string]string
if r, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil {
return nil, err.Trace(sourceURL)
}
ctype := metadata["Content-Type"]
if strings.Contains(ctype, "gzip") {
var e error
r, e = gzip.NewReader(r)
if e != nil {
return nil, probe.NewError(e)
}
defer r.Close()
} else if strings.Contains(ctype, "bzip") {
defer r.Close()
r = ioutil.NopCloser(bzip2.NewReader(r))
} else {
defer r.Close()
}
}
br := bufio.NewReader(r)
line, _, err := br.ReadLine()
if err != nil {
return nil, probe.NewError(err)
}
return strings.Split(string(line), ","), nil
} | go | func getCSVHeader(sourceURL string, encKeyDB map[string][]prefixSSEPair) ([]string, *probe.Error) {
var r io.ReadCloser
switch sourceURL {
case "-":
r = os.Stdin
default:
var err *probe.Error
var metadata map[string]string
if r, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil {
return nil, err.Trace(sourceURL)
}
ctype := metadata["Content-Type"]
if strings.Contains(ctype, "gzip") {
var e error
r, e = gzip.NewReader(r)
if e != nil {
return nil, probe.NewError(e)
}
defer r.Close()
} else if strings.Contains(ctype, "bzip") {
defer r.Close()
r = ioutil.NopCloser(bzip2.NewReader(r))
} else {
defer r.Close()
}
}
br := bufio.NewReader(r)
line, _, err := br.ReadLine()
if err != nil {
return nil, probe.NewError(err)
}
return strings.Split(string(line), ","), nil
} | [
"func",
"getCSVHeader",
"(",
"sourceURL",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"(",
"[",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"var",
"r",
"io",
".",
"ReadCloser",
"\n",
"switch",
"... | // getCSVHeader fetches the first line of csv query object | [
"getCSVHeader",
"fetches",
"the",
"first",
"line",
"of",
"csv",
"query",
"object"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L313-L345 | train |
minio/mc | cmd/sql-main.go | isSelectAll | func isSelectAll(query string) bool {
match, _ := regexp.MatchString("^\\s*?select\\s+?\\*\\s+?.*?$", query)
return match
} | go | func isSelectAll(query string) bool {
match, _ := regexp.MatchString("^\\s*?select\\s+?\\*\\s+?.*?$", query)
return match
} | [
"func",
"isSelectAll",
"(",
"query",
"string",
")",
"bool",
"{",
"match",
",",
"_",
":=",
"regexp",
".",
"MatchString",
"(",
"\"^\\\\s*?select\\\\s+?\\\\*\\\\s+?.*?$\"",
",",
"\\\\",
")",
"\n",
"\\\\",
"\n",
"}"
] | // returns true if query is selectign all columns of the csv object | [
"returns",
"true",
"if",
"query",
"is",
"selectign",
"all",
"columns",
"of",
"the",
"csv",
"object"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L348-L351 | train |
minio/mc | cmd/sql-main.go | getCSVOutputHeaders | func getCSVOutputHeaders(ctx *cli.Context, url string, encKeyDB map[string][]prefixSSEPair, query string) (hdrs []string) {
if !ctx.IsSet("csv-output-header") {
return
}
hdrStr := ctx.String("csv-output-header")
if hdrStr == "" && isSelectAll(query) {
// attempt to get the first line of csv as header
if hdrs, err := getCSVHeader(url, encKeyDB); err == nil {
return hdrs
}
}
hdrs = strings.Split(hdrStr, ",")
return
} | go | func getCSVOutputHeaders(ctx *cli.Context, url string, encKeyDB map[string][]prefixSSEPair, query string) (hdrs []string) {
if !ctx.IsSet("csv-output-header") {
return
}
hdrStr := ctx.String("csv-output-header")
if hdrStr == "" && isSelectAll(query) {
// attempt to get the first line of csv as header
if hdrs, err := getCSVHeader(url, encKeyDB); err == nil {
return hdrs
}
}
hdrs = strings.Split(hdrStr, ",")
return
} | [
"func",
"getCSVOutputHeaders",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"url",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
",",
"query",
"string",
")",
"(",
"hdrs",
"[",
"]",
"string",
")",
"{",
"if",
"!",
"ct... | // if csv-output-header is set to a comma delimited string use it, othjerwise attempt to get the header from
// query object | [
"if",
"csv",
"-",
"output",
"-",
"header",
"is",
"set",
"to",
"a",
"comma",
"delimited",
"string",
"use",
"it",
"othjerwise",
"attempt",
"to",
"get",
"the",
"header",
"from",
"query",
"object"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L355-L369 | train |
minio/mc | cmd/sql-main.go | getSQLOpts | func getSQLOpts(ctx *cli.Context, csvHdrs []string) (s SelectObjectOpts) {
is := getInputSerializationOpts(ctx)
os := getOutputSerializationOpts(ctx, csvHdrs)
return SelectObjectOpts{
InputSerOpts: is,
OutputSerOpts: os,
}
} | go | func getSQLOpts(ctx *cli.Context, csvHdrs []string) (s SelectObjectOpts) {
is := getInputSerializationOpts(ctx)
os := getOutputSerializationOpts(ctx, csvHdrs)
return SelectObjectOpts{
InputSerOpts: is,
OutputSerOpts: os,
}
} | [
"func",
"getSQLOpts",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"csvHdrs",
"[",
"]",
"string",
")",
"(",
"s",
"SelectObjectOpts",
")",
"{",
"is",
":=",
"getInputSerializationOpts",
"(",
"ctx",
")",
"\n",
"os",
":=",
"getOutputSerializationOpts",
"(",
"c... | // get the Select options for sql select API | [
"get",
"the",
"Select",
"options",
"for",
"sql",
"select",
"API"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L372-L380 | train |
minio/mc | cmd/sql-main.go | getAndValidateArgs | func getAndValidateArgs(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, url string) (query string, csvHdrs []string, selOpts SelectObjectOpts) {
query = ctx.String("query")
csvHdrs = getCSVOutputHeaders(ctx, url, encKeyDB, query)
selOpts = getSQLOpts(ctx, csvHdrs)
validateOpts(selOpts, url)
return
} | go | func getAndValidateArgs(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, url string) (query string, csvHdrs []string, selOpts SelectObjectOpts) {
query = ctx.String("query")
csvHdrs = getCSVOutputHeaders(ctx, url, encKeyDB, query)
selOpts = getSQLOpts(ctx, csvHdrs)
validateOpts(selOpts, url)
return
} | [
"func",
"getAndValidateArgs",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
",",
"url",
"string",
")",
"(",
"query",
"string",
",",
"csvHdrs",
"[",
"]",
"string",
",",
"selOpts",
"SelectObj... | // validate args and optionally fetch the csv header of query object | [
"validate",
"args",
"and",
"optionally",
"fetch",
"the",
"csv",
"header",
"of",
"query",
"object"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L426-L432 | train |
minio/mc | cmd/sql-main.go | checkSQLSyntax | func checkSQLSyntax(ctx *cli.Context) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "sql", 1) // last argument is exit code.
}
} | go | func checkSQLSyntax(ctx *cli.Context) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "sql", 1) // last argument is exit code.
}
} | [
"func",
"checkSQLSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"!",
"ctx",
".",
"Args",
"(",
")",
".",
"Present",
"(",
")",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"sql\"",
",",
"1",
")",
"\n",
"}",
"\n",
... | // check sql input arguments. | [
"check",
"sql",
"input",
"arguments",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L435-L439 | train |
minio/mc | cmd/sql-main.go | mainSQL | func mainSQL(ctx *cli.Context) error {
var (
csvHdrs []string
selOpts SelectObjectOpts
query string
)
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// validate sql input arguments.
checkSQLSyntax(ctx)
// extract URLs.
URLs := ctx.Args()
writeHdr := true
for _, url := range URLs {
if !isAliasURLDir(url, encKeyDB) {
if writeHdr {
query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, url)
}
errorIf(sqlSelect(url, query, encKeyDB, selOpts, csvHdrs, writeHdr).Trace(url), "Unable to run sql")
writeHdr = false
continue
}
targetAlias, targetURL, _ := mustExpandAlias(url)
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
errorIf(err.Trace(url), "Unable to initialize target `"+url+"`.")
continue
}
for content := range clnt.List(ctx.Bool("recursive"), false, DirNone) {
if content.Err != nil {
errorIf(content.Err.Trace(url), "Unable to list on target `"+url+"`.")
continue
}
if writeHdr {
query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, targetAlias+content.URL.Path)
}
contentType := mimedb.TypeByExtension(filepath.Ext(content.URL.Path))
for _, cTypeSuffix := range supportedContentTypes {
if strings.Contains(contentType, cTypeSuffix) {
errorIf(sqlSelect(targetAlias+content.URL.Path, query,
encKeyDB, selOpts, csvHdrs, writeHdr).Trace(content.URL.String()), "Unable to run sql")
}
writeHdr = false
}
}
}
// Done.
return nil
} | go | func mainSQL(ctx *cli.Context) error {
var (
csvHdrs []string
selOpts SelectObjectOpts
query string
)
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// validate sql input arguments.
checkSQLSyntax(ctx)
// extract URLs.
URLs := ctx.Args()
writeHdr := true
for _, url := range URLs {
if !isAliasURLDir(url, encKeyDB) {
if writeHdr {
query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, url)
}
errorIf(sqlSelect(url, query, encKeyDB, selOpts, csvHdrs, writeHdr).Trace(url), "Unable to run sql")
writeHdr = false
continue
}
targetAlias, targetURL, _ := mustExpandAlias(url)
clnt, err := newClientFromAlias(targetAlias, targetURL)
if err != nil {
errorIf(err.Trace(url), "Unable to initialize target `"+url+"`.")
continue
}
for content := range clnt.List(ctx.Bool("recursive"), false, DirNone) {
if content.Err != nil {
errorIf(content.Err.Trace(url), "Unable to list on target `"+url+"`.")
continue
}
if writeHdr {
query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, targetAlias+content.URL.Path)
}
contentType := mimedb.TypeByExtension(filepath.Ext(content.URL.Path))
for _, cTypeSuffix := range supportedContentTypes {
if strings.Contains(contentType, cTypeSuffix) {
errorIf(sqlSelect(targetAlias+content.URL.Path, query,
encKeyDB, selOpts, csvHdrs, writeHdr).Trace(content.URL.String()), "Unable to run sql")
}
writeHdr = false
}
}
}
// Done.
return nil
} | [
"func",
"mainSQL",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"var",
"(",
"csvHdrs",
"[",
"]",
"string",
"\n",
"selOpts",
"SelectObjectOpts",
"\n",
"query",
"string",
"\n",
")",
"\n",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ct... | // mainSQL is the main entry point for sql command. | [
"mainSQL",
"is",
"the",
"main",
"entry",
"point",
"for",
"sql",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/sql-main.go#L442-L494 | train |
minio/mc | cmd/flags.go | registerCmd | func registerCmd(cmd cli.Command) {
commands = append(commands, cmd)
commandsTree.Insert(cmd.Name)
} | go | func registerCmd(cmd cli.Command) {
commands = append(commands, cmd)
commandsTree.Insert(cmd.Name)
} | [
"func",
"registerCmd",
"(",
"cmd",
"cli",
".",
"Command",
")",
"{",
"commands",
"=",
"append",
"(",
"commands",
",",
"cmd",
")",
"\n",
"commandsTree",
".",
"Insert",
"(",
"cmd",
".",
"Name",
")",
"\n",
"}"
] | // registerCmd registers a cli command | [
"registerCmd",
"registers",
"a",
"cli",
"command"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/flags.go#L68-L71 | train |
minio/mc | cmd/update-main.go | GetCurrentReleaseTime | func GetCurrentReleaseTime() (releaseTime time.Time, err *probe.Error) {
if releaseTime, err = mcVersionToReleaseTime(Version); err == nil {
return releaseTime, nil
}
// Looks like version is mc non-standard, we use mc
// binary's ModTime as release time:
path, e := os.Executable()
if e != nil {
return releaseTime, probe.NewError(e)
}
return getModTime(path)
} | go | func GetCurrentReleaseTime() (releaseTime time.Time, err *probe.Error) {
if releaseTime, err = mcVersionToReleaseTime(Version); err == nil {
return releaseTime, nil
}
// Looks like version is mc non-standard, we use mc
// binary's ModTime as release time:
path, e := os.Executable()
if e != nil {
return releaseTime, probe.NewError(e)
}
return getModTime(path)
} | [
"func",
"GetCurrentReleaseTime",
"(",
")",
"(",
"releaseTime",
"time",
".",
"Time",
",",
"err",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"releaseTime",
",",
"err",
"=",
"mcVersionToReleaseTime",
"(",
"Version",
")",
";",
"err",
"==",
"nil",
"{",
"retu... | // GetCurrentReleaseTime - returns this process's release time. If it
// is official mc version, parsed version is returned else mc
// binary's mod time is returned. | [
"GetCurrentReleaseTime",
"-",
"returns",
"this",
"process",
"s",
"release",
"time",
".",
"If",
"it",
"is",
"official",
"mc",
"version",
"parsed",
"version",
"is",
"returned",
"else",
"mc",
"binary",
"s",
"mod",
"time",
"is",
"returned",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/update-main.go#L150-L162 | train |
minio/mc | cmd/update-main.go | DownloadReleaseData | func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) {
releaseURLs := mcReleaseInfoURLs
if runtime.GOOS == "windows" {
releaseURLs = mcReleaseWindowsInfoURLs
}
return func() (data string, err *probe.Error) {
for _, url := range releaseURLs {
data, err = downloadReleaseURL(url, timeout)
if err == nil {
return data, nil
}
}
return data, err.Trace(releaseURLs...)
}()
} | go | func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) {
releaseURLs := mcReleaseInfoURLs
if runtime.GOOS == "windows" {
releaseURLs = mcReleaseWindowsInfoURLs
}
return func() (data string, err *probe.Error) {
for _, url := range releaseURLs {
data, err = downloadReleaseURL(url, timeout)
if err == nil {
return data, nil
}
}
return data, err.Trace(releaseURLs...)
}()
} | [
"func",
"DownloadReleaseData",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"data",
"string",
",",
"err",
"*",
"probe",
".",
"Error",
")",
"{",
"releaseURLs",
":=",
"mcReleaseInfoURLs",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"{",
"r... | // DownloadReleaseData - downloads release data from mc official server. | [
"DownloadReleaseData",
"-",
"downloads",
"release",
"data",
"from",
"mc",
"official",
"server",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/update-main.go#L277-L291 | train |
minio/mc | cmd/progress-bar.go | newProgressBar | func newProgressBar(total int64) *progressBar {
// Progress bar speific theme customization.
console.SetColor("Bar", color.New(color.FgGreen, color.Bold))
pgbar := progressBar{}
// get the new original progress bar.
bar := pb.New64(total)
// Set new human friendly print units.
bar.SetUnits(pb.U_BYTES)
// Refresh rate for progress bar is set to 125 milliseconds.
bar.SetRefreshRate(time.Millisecond * 125)
// Do not print a newline by default handled, it is handled manually.
bar.NotPrint = true
// Show current speed is true.
bar.ShowSpeed = true
// Custom callback with colorized bar.
bar.Callback = func(s string) {
console.Print(console.Colorize("Bar", "\r"+s))
}
// Use different unicodes for Linux, OS X and Windows.
switch runtime.GOOS {
case "linux":
// Need to add '\x00' as delimiter for unicode characters.
bar.Format("┃\x00▓\x00█\x00░\x00┃")
case "darwin":
// Need to add '\x00' as delimiter for unicode characters.
bar.Format(" \x00▓\x00 \x00░\x00 ")
default:
// Default to non unicode characters.
bar.Format("[=> ]")
}
// Start the progress bar.
if bar.Total > 0 {
bar.Start()
}
// Copy for future
pgbar.ProgressBar = bar
// Return new progress bar here.
return &pgbar
} | go | func newProgressBar(total int64) *progressBar {
// Progress bar speific theme customization.
console.SetColor("Bar", color.New(color.FgGreen, color.Bold))
pgbar := progressBar{}
// get the new original progress bar.
bar := pb.New64(total)
// Set new human friendly print units.
bar.SetUnits(pb.U_BYTES)
// Refresh rate for progress bar is set to 125 milliseconds.
bar.SetRefreshRate(time.Millisecond * 125)
// Do not print a newline by default handled, it is handled manually.
bar.NotPrint = true
// Show current speed is true.
bar.ShowSpeed = true
// Custom callback with colorized bar.
bar.Callback = func(s string) {
console.Print(console.Colorize("Bar", "\r"+s))
}
// Use different unicodes for Linux, OS X and Windows.
switch runtime.GOOS {
case "linux":
// Need to add '\x00' as delimiter for unicode characters.
bar.Format("┃\x00▓\x00█\x00░\x00┃")
case "darwin":
// Need to add '\x00' as delimiter for unicode characters.
bar.Format(" \x00▓\x00 \x00░\x00 ")
default:
// Default to non unicode characters.
bar.Format("[=> ]")
}
// Start the progress bar.
if bar.Total > 0 {
bar.Start()
}
// Copy for future
pgbar.ProgressBar = bar
// Return new progress bar here.
return &pgbar
} | [
"func",
"newProgressBar",
"(",
"total",
"int64",
")",
"*",
"progressBar",
"{",
"console",
".",
"SetColor",
"(",
"\"Bar\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
",",
"color",
".",
"Bold",
")",
")",
"\n",
"pgbar",
":=",
"progressBar",
... | // newProgressBar - instantiate a progress bar. | [
"newProgressBar",
"-",
"instantiate",
"a",
"progress",
"bar",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/progress-bar.go#L36-L85 | train |
minio/mc | cmd/progress-bar.go | SetCaption | func (p *progressBar) SetCaption(caption string) *progressBar {
caption = fixateBarCaption(caption, getFixedWidth(p.ProgressBar.GetWidth(), 18))
p.ProgressBar.Prefix(caption)
return p
} | go | func (p *progressBar) SetCaption(caption string) *progressBar {
caption = fixateBarCaption(caption, getFixedWidth(p.ProgressBar.GetWidth(), 18))
p.ProgressBar.Prefix(caption)
return p
} | [
"func",
"(",
"p",
"*",
"progressBar",
")",
"SetCaption",
"(",
"caption",
"string",
")",
"*",
"progressBar",
"{",
"caption",
"=",
"fixateBarCaption",
"(",
"caption",
",",
"getFixedWidth",
"(",
"p",
".",
"ProgressBar",
".",
"GetWidth",
"(",
")",
",",
"18",
... | // Set caption. | [
"Set",
"caption",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/progress-bar.go#L88-L92 | train |
minio/mc | cmd/progress-bar.go | cursorAnimate | func cursorAnimate() <-chan string {
cursorCh := make(chan string)
var cursors string
switch runtime.GOOS {
case "linux":
// cursors = "➩➪➫➬➭➮➯➱"
// cursors = "▁▃▄▅▆▇█▇▆▅▄▃"
cursors = "◐◓◑◒"
// cursors = "←↖↑↗→↘↓↙"
// cursors = "◴◷◶◵"
// cursors = "◰◳◲◱"
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
case "darwin":
cursors = "◐◓◑◒"
default:
cursors = "|/-\\"
}
go func() {
for {
for _, cursor := range cursors {
cursorCh <- string(cursor)
}
}
}()
return cursorCh
} | go | func cursorAnimate() <-chan string {
cursorCh := make(chan string)
var cursors string
switch runtime.GOOS {
case "linux":
// cursors = "➩➪➫➬➭➮➯➱"
// cursors = "▁▃▄▅▆▇█▇▆▅▄▃"
cursors = "◐◓◑◒"
// cursors = "←↖↑↗→↘↓↙"
// cursors = "◴◷◶◵"
// cursors = "◰◳◲◱"
//cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
case "darwin":
cursors = "◐◓◑◒"
default:
cursors = "|/-\\"
}
go func() {
for {
for _, cursor := range cursors {
cursorCh <- string(cursor)
}
}
}()
return cursorCh
} | [
"func",
"cursorAnimate",
"(",
")",
"<-",
"chan",
"string",
"{",
"cursorCh",
":=",
"make",
"(",
"chan",
"string",
")",
"\n",
"var",
"cursors",
"string",
"\n",
"switch",
"runtime",
".",
"GOOS",
"{",
"case",
"\"linux\"",
":",
"cursors",
"=",
"\"◐◓◑◒\"",
"\n... | // cursorAnimate - returns a animated rune through read channel for every read. | [
"cursorAnimate",
"-",
"returns",
"a",
"animated",
"rune",
"through",
"read",
"channel",
"for",
"every",
"read",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/progress-bar.go#L118-L144 | train |
minio/mc | cmd/progress-bar.go | fixateBarCaption | func fixateBarCaption(caption string, width int) string {
switch {
case len(caption) > width:
// Trim caption to fit within the screen
trimSize := len(caption) - width + 3
if trimSize < len(caption) {
caption = "..." + caption[trimSize:]
}
case len(caption) < width:
caption += strings.Repeat(" ", width-len(caption))
}
return caption
} | go | func fixateBarCaption(caption string, width int) string {
switch {
case len(caption) > width:
// Trim caption to fit within the screen
trimSize := len(caption) - width + 3
if trimSize < len(caption) {
caption = "..." + caption[trimSize:]
}
case len(caption) < width:
caption += strings.Repeat(" ", width-len(caption))
}
return caption
} | [
"func",
"fixateBarCaption",
"(",
"caption",
"string",
",",
"width",
"int",
")",
"string",
"{",
"switch",
"{",
"case",
"len",
"(",
"caption",
")",
">",
"width",
":",
"trimSize",
":=",
"len",
"(",
"caption",
")",
"-",
"width",
"+",
"3",
"\n",
"if",
"tr... | // fixateBarCaption - fancify bar caption based on the terminal width. | [
"fixateBarCaption",
"-",
"fancify",
"bar",
"caption",
"based",
"on",
"the",
"terminal",
"width",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/progress-bar.go#L147-L159 | train |
minio/mc | cmd/cp-url.go | guessCopyURLType | func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(sourceURL, false, keys)
if err != nil {
return copyURLsTypeInvalid, err
}
// If recursion is ON, it is type C.
// If source is a folder, it is Type C.
if sourceContent.Type.IsDir() || isRecursive {
return copyURLsTypeC, nil
}
// If target is a folder, it is Type B.
if isAliasURLDir(targetURL, keys) {
return copyURLsTypeB, nil
}
// else Type A.
return copyURLsTypeA, nil
}
// Multiple source args and target is a folder. It is Type D.
if isAliasURLDir(targetURL, keys) {
return copyURLsTypeD, nil
}
return copyURLsTypeInvalid, errInvalidArgument().Trace()
} | go | func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(sourceURL, false, keys)
if err != nil {
return copyURLsTypeInvalid, err
}
// If recursion is ON, it is type C.
// If source is a folder, it is Type C.
if sourceContent.Type.IsDir() || isRecursive {
return copyURLsTypeC, nil
}
// If target is a folder, it is Type B.
if isAliasURLDir(targetURL, keys) {
return copyURLsTypeB, nil
}
// else Type A.
return copyURLsTypeA, nil
}
// Multiple source args and target is a folder. It is Type D.
if isAliasURLDir(targetURL, keys) {
return copyURLsTypeD, nil
}
return copyURLsTypeInvalid, errInvalidArgument().Trace()
} | [
"func",
"guessCopyURLType",
"(",
"sourceURLs",
"[",
"]",
"string",
",",
"targetURL",
"string",
",",
"isRecursive",
"bool",
",",
"keys",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"(",
"copyURLsType",
",",
"*",
"probe",
".",
"Error",
")",
... | // guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
// functions to accurately report failure causes. | [
"guessCopyURLType",
"guesses",
"the",
"type",
"of",
"clientURL",
".",
"This",
"approach",
"all",
"allows",
"prepareURL",
"functions",
"to",
"accurately",
"report",
"failure",
"causes",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url.go#L53-L81 | train |
minio/mc | cmd/cp-url.go | makeCopyContentTypeA | func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
targetContent := clientContent{URL: *newClientURL(targetURL)}
return URLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: &targetContent,
}
} | go | func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
targetContent := clientContent{URL: *newClientURL(targetURL)}
return URLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: &targetContent,
}
} | [
"func",
"makeCopyContentTypeA",
"(",
"sourceAlias",
"string",
",",
"sourceContent",
"*",
"clientContent",
",",
"targetAlias",
"string",
",",
"targetURL",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"URLs",
"{",
"targetCo... | // prepareCopyContentTypeA - makes CopyURLs content for copying. | [
"prepareCopyContentTypeA",
"-",
"makes",
"CopyURLs",
"content",
"for",
"copying",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url.go#L106-L114 | train |
minio/mc | cmd/cp-url.go | makeCopyContentTypeB | func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
targetURLParse := newClientURL(targetURL)
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String(), encKeyDB)
} | go | func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
targetURLParse := newClientURL(targetURL)
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String(), encKeyDB)
} | [
"func",
"makeCopyContentTypeB",
"(",
"sourceAlias",
"string",
",",
"sourceContent",
"*",
"clientContent",
",",
"targetAlias",
"string",
",",
"targetURL",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"URLs",
"{",
"targetUR... | // makeCopyContentTypeB - CopyURLs content for copying. | [
"makeCopyContentTypeB",
"-",
"CopyURLs",
"content",
"for",
"copying",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url.go#L143-L148 | train |
minio/mc | cmd/cp-url.go | makeCopyContentTypeC | func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
if pathSeparatorIndex > 1 {
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL, encKeyDB)
} | go | func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
if pathSeparatorIndex > 1 {
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL, encKeyDB)
} | [
"func",
"makeCopyContentTypeC",
"(",
"sourceAlias",
"string",
",",
"sourceURL",
"clientURL",
",",
"sourceContent",
"*",
"clientContent",
",",
"targetAlias",
"string",
",",
"targetURL",
"string",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair"... | // makeCopyContentTypeC - CopyURLs content for copying. | [
"makeCopyContentTypeC",
"-",
"CopyURLs",
"content",
"for",
"copying",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url.go#L188-L198 | train |
minio/mc | cmd/cp-url.go | prepareCopyURLs | func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
defer close(copyURLsCh)
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive, encKeyDB)
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
switch cpType {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB)
case copyURLsTypeB:
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB)
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cURLs
}
case copyURLsTypeD:
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cURLs
}
default:
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
}
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
return copyURLsCh
} | go | func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
defer close(copyURLsCh)
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive, encKeyDB)
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
switch cpType {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB)
case copyURLsTypeB:
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB)
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cURLs
}
case copyURLsTypeD:
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cURLs
}
default:
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
}
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
return copyURLsCh
} | [
"func",
"prepareCopyURLs",
"(",
"sourceURLs",
"[",
"]",
"string",
",",
"targetURL",
"string",
",",
"isRecursive",
"bool",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"<-",
"chan",
"URLs",
"{",
"copyURLsCh",
":=",
"make",
"("... | // prepareCopyURLs - prepares target and source clientURLs for copying. | [
"prepareCopyURLs",
"-",
"prepares",
"target",
"and",
"source",
"clientURLs",
"for",
"copying",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url.go#L216-L242 | train |
minio/mc | cmd/client-url.go | getHost | func getHost(authority string) (host string) {
i := strings.LastIndex(authority, "@")
if i >= 0 {
// TODO support, username@password style userinfo, useful for ftp support.
return
}
return authority
} | go | func getHost(authority string) (host string) {
i := strings.LastIndex(authority, "@")
if i >= 0 {
// TODO support, username@password style userinfo, useful for ftp support.
return
}
return authority
} | [
"func",
"getHost",
"(",
"authority",
"string",
")",
"(",
"host",
"string",
")",
"{",
"i",
":=",
"strings",
".",
"LastIndex",
"(",
"authority",
",",
"\"@\"",
")",
"\n",
"if",
"i",
">=",
"0",
"{",
"return",
"\n",
"}",
"\n",
"return",
"authority",
"\n",... | // getHost - extract host from authority string, we do not support ftp style username@ yet. | [
"getHost",
"-",
"extract",
"host",
"from",
"authority",
"string",
"we",
"do",
"not",
"support",
"ftp",
"style",
"username"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L84-L91 | train |
minio/mc | cmd/client-url.go | newClientURL | func newClientURL(urlStr string) *clientURL {
scheme, rest := getScheme(urlStr)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
var authority string
authority, rest = splitSpecial(rest[2:], "/", false)
if rest == "" {
rest = "/"
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &clientURL{
Scheme: scheme,
Type: objectStorage,
Host: host,
Path: rest,
SchemeSeparator: "://",
Separator: '/',
}
}
}
return &clientURL{
Type: fileSystem,
Path: rest,
Separator: filepath.Separator,
}
} | go | func newClientURL(urlStr string) *clientURL {
scheme, rest := getScheme(urlStr)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
var authority string
authority, rest = splitSpecial(rest[2:], "/", false)
if rest == "" {
rest = "/"
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &clientURL{
Scheme: scheme,
Type: objectStorage,
Host: host,
Path: rest,
SchemeSeparator: "://",
Separator: '/',
}
}
}
return &clientURL{
Type: fileSystem,
Path: rest,
Separator: filepath.Separator,
}
} | [
"func",
"newClientURL",
"(",
"urlStr",
"string",
")",
"*",
"clientURL",
"{",
"scheme",
",",
"rest",
":=",
"getScheme",
"(",
"urlStr",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"rest",
",",
"\"//\"",
")",
"{",
"var",
"authority",
"string",
"\n",
... | // newClientURL returns an abstracted URL for filesystems and object storage. | [
"newClientURL",
"returns",
"an",
"abstracted",
"URL",
"for",
"filesystems",
"and",
"object",
"storage",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L94-L120 | train |
minio/mc | cmd/client-url.go | joinURLs | func joinURLs(url1, url2 *clientURL) *clientURL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
return url1
} | go | func joinURLs(url1, url2 *clientURL) *clientURL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
return url1
} | [
"func",
"joinURLs",
"(",
"url1",
",",
"url2",
"*",
"clientURL",
")",
"*",
"clientURL",
"{",
"var",
"url1Path",
",",
"url2Path",
"string",
"\n",
"url1Path",
"=",
"filepath",
".",
"ToSlash",
"(",
"url1",
".",
"Path",
")",
"\n",
"url2Path",
"=",
"filepath",... | // joinURLs join two input urls and returns a url | [
"joinURLs",
"join",
"two",
"input",
"urls",
"and",
"returns",
"a",
"url"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L123-L133 | train |
minio/mc | cmd/client-url.go | String | func (u clientURL) String() string {
var buf bytes.Buffer
// if fileSystem no translation needed, return as is.
if u.Type == fileSystem {
return u.Path
}
// if objectStorage convert from any non standard paths to a supported URL path style.
if u.Type == objectStorage {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
buf.WriteString("//")
if h := u.Host; h != "" {
buf.WriteString(h)
}
switch runtime.GOOS {
case "windows":
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
buf.WriteByte('/')
}
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
default:
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
buf.WriteByte('/')
}
buf.WriteString(u.Path)
}
}
return buf.String()
} | go | func (u clientURL) String() string {
var buf bytes.Buffer
// if fileSystem no translation needed, return as is.
if u.Type == fileSystem {
return u.Path
}
// if objectStorage convert from any non standard paths to a supported URL path style.
if u.Type == objectStorage {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
buf.WriteString("//")
if h := u.Host; h != "" {
buf.WriteString(h)
}
switch runtime.GOOS {
case "windows":
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
buf.WriteByte('/')
}
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
default:
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
buf.WriteByte('/')
}
buf.WriteString(u.Path)
}
}
return buf.String()
} | [
"func",
"(",
"u",
"clientURL",
")",
"String",
"(",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"u",
".",
"Type",
"==",
"fileSystem",
"{",
"return",
"u",
".",
"Path",
"\n",
"}",
"\n",
"if",
"u",
".",
"Type",
"==",
"object... | // String convert URL into its canonical form. | [
"String",
"convert",
"URL",
"into",
"its",
"canonical",
"form",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L136-L164 | train |
minio/mc | cmd/client-url.go | urlJoinPath | func urlJoinPath(url1, url2 string) string {
u1 := newClientURL(url1)
u2 := newClientURL(url2)
return joinURLs(u1, u2).String()
} | go | func urlJoinPath(url1, url2 string) string {
u1 := newClientURL(url1)
u2 := newClientURL(url2)
return joinURLs(u1, u2).String()
} | [
"func",
"urlJoinPath",
"(",
"url1",
",",
"url2",
"string",
")",
"string",
"{",
"u1",
":=",
"newClientURL",
"(",
"url1",
")",
"\n",
"u2",
":=",
"newClientURL",
"(",
"url2",
")",
"\n",
"return",
"joinURLs",
"(",
"u1",
",",
"u2",
")",
".",
"String",
"("... | // urlJoinPath Join a path to existing URL. | [
"urlJoinPath",
"Join",
"a",
"path",
"to",
"existing",
"URL",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L167-L171 | train |
minio/mc | cmd/client-url.go | url2Stat | func url2Stat(urlStr string, isFetchMeta bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *clientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(false, isFetchMeta, sse)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
} | go | func url2Stat(urlStr string, isFetchMeta bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *clientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(false, isFetchMeta, sse)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
} | [
"func",
"url2Stat",
"(",
"urlStr",
"string",
",",
"isFetchMeta",
"bool",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"(",
"client",
"Client",
",",
"content",
"*",
"clientContent",
",",
"err",
"*",
"probe",
".",
"Error",
")... | // url2Stat returns stat info for URL. | [
"url2Stat",
"returns",
"stat",
"info",
"for",
"URL",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L174-L187 | train |
minio/mc | cmd/client-url.go | isURLPrefixExists | func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
clnt, err := newClient(urlPrefix)
if err != nil {
return false
}
isRecursive := false
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
return entry.Err == nil
}
return false
} | go | func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
clnt, err := newClient(urlPrefix)
if err != nil {
return false
}
isRecursive := false
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
return entry.Err == nil
}
return false
} | [
"func",
"isURLPrefixExists",
"(",
"urlPrefix",
"string",
",",
"incomplete",
"bool",
")",
"bool",
"{",
"clnt",
",",
"err",
":=",
"newClient",
"(",
"urlPrefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"isRecursive",
":... | // isURLPrefixExists - check if object key prefix exists. | [
"isURLPrefixExists",
"-",
"check",
"if",
"object",
"key",
"prefix",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-url.go#L214-L225 | train |
minio/mc | cmd/admin-user-disable.go | checkAdminUserDisableSyntax | func checkAdminUserDisableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "disable", 1) // last argument is exit code
}
} | go | func checkAdminUserDisableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "disable", 1) // last argument is exit code
}
} | [
"func",
"checkAdminUserDisableSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"2",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"disable\"",
",",
"1",
")",
"\n",
"... | // checkAdminUserDisableSyntax - validate all the passed arguments | [
"checkAdminUserDisableSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-disable.go#L49-L53 | train |
minio/mc | cmd/admin-user-disable.go | mainAdminUserDisable | func mainAdminUserDisable(ctx *cli.Context) error {
checkAdminUserDisableSyntax(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.")
e := client.SetUserStatus(args.Get(1), madmin.AccountDisabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
printMsg(userMessage{
op: "disable",
AccessKey: args.Get(1),
})
return nil
} | go | func mainAdminUserDisable(ctx *cli.Context) error {
checkAdminUserDisableSyntax(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.")
e := client.SetUserStatus(args.Get(1), madmin.AccountDisabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
printMsg(userMessage{
op: "disable",
AccessKey: args.Get(1),
})
return nil
} | [
"func",
"mainAdminUserDisable",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminUserDisableSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"UserMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
... | // mainAdminUserDisable is the handle for "mc admin user disable" command. | [
"mainAdminUserDisable",
"is",
"the",
"handle",
"for",
"mc",
"admin",
"user",
"disable",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-disable.go#L56-L78 | train |
minio/mc | cmd/table-ui.go | getPrintCol | func getPrintCol(c col) *color.Color {
switch c {
case colGrey:
return color.New(color.FgWhite, color.Bold)
case colRed:
return color.New(color.FgRed, color.Bold)
case colYellow:
return color.New(color.FgYellow, color.Bold)
case colGreen:
return color.New(color.FgGreen, color.Bold)
}
return nil
} | go | func getPrintCol(c col) *color.Color {
switch c {
case colGrey:
return color.New(color.FgWhite, color.Bold)
case colRed:
return color.New(color.FgRed, color.Bold)
case colYellow:
return color.New(color.FgYellow, color.Bold)
case colGreen:
return color.New(color.FgGreen, color.Bold)
}
return nil
} | [
"func",
"getPrintCol",
"(",
"c",
"col",
")",
"*",
"color",
".",
"Color",
"{",
"switch",
"c",
"{",
"case",
"colGrey",
":",
"return",
"color",
".",
"New",
"(",
"color",
".",
"FgWhite",
",",
"color",
".",
"Bold",
")",
"\n",
"case",
"colRed",
":",
"ret... | // getPrintCol - map color code to color for printing | [
"getPrintCol",
"-",
"map",
"color",
"code",
"to",
"color",
"for",
"printing"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/table-ui.go#L32-L44 | train |
minio/mc | cmd/share-main.go | migrateShare | func migrateShare() {
if !isShareDirExists() {
return
}
// Shared URLs are now managed by sub-commands. So delete any old URLs file if found.
oldShareFile := filepath.Join(mustGetShareDir(), "urls.json")
if _, e := os.Stat(oldShareFile); e == nil {
// Old file exits.
e := os.Remove(oldShareFile)
fatalIf(probe.NewError(e), "Unable to delete old `"+oldShareFile+"`.")
console.Infof("Removed older version of share `%s` file.\n", oldShareFile)
}
} | go | func migrateShare() {
if !isShareDirExists() {
return
}
// Shared URLs are now managed by sub-commands. So delete any old URLs file if found.
oldShareFile := filepath.Join(mustGetShareDir(), "urls.json")
if _, e := os.Stat(oldShareFile); e == nil {
// Old file exits.
e := os.Remove(oldShareFile)
fatalIf(probe.NewError(e), "Unable to delete old `"+oldShareFile+"`.")
console.Infof("Removed older version of share `%s` file.\n", oldShareFile)
}
} | [
"func",
"migrateShare",
"(",
")",
"{",
"if",
"!",
"isShareDirExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"oldShareFile",
":=",
"filepath",
".",
"Join",
"(",
"mustGetShareDir",
"(",
")",
",",
"\"urls.json\"",
")",
"\n",
"if",
"_",
",",
"e",
":=",... | // migrateShare migrate to newest version sequentially. | [
"migrateShare",
"migrate",
"to",
"newest",
"version",
"sequentially",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-main.go#L48-L61 | train |
minio/mc | cmd/rb-main.go | String | func (s removeBucketMessage) String() string {
return console.Colorize("RemoveBucket", fmt.Sprintf("Removed `%s` successfully.", s.Bucket))
} | go | func (s removeBucketMessage) String() string {
return console.Colorize("RemoveBucket", fmt.Sprintf("Removed `%s` successfully.", s.Bucket))
} | [
"func",
"(",
"s",
"removeBucketMessage",
")",
"String",
"(",
")",
"string",
"{",
"return",
"console",
".",
"Colorize",
"(",
"\"RemoveBucket\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"Removed `%s` successfully.\"",
",",
"s",
".",
"Bucket",
")",
")",
"\n",
"}"
] | // String colorized delete bucket message. | [
"String",
"colorized",
"delete",
"bucket",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/rb-main.go#L82-L84 | train |
minio/mc | cmd/rb-main.go | JSON | func (s removeBucketMessage) JSON() string {
removeBucketJSONBytes, e := json.Marshal(s)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(removeBucketJSONBytes)
} | go | func (s removeBucketMessage) JSON() string {
removeBucketJSONBytes, e := json.Marshal(s)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(removeBucketJSONBytes)
} | [
"func",
"(",
"s",
"removeBucketMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"removeBucketJSONBytes",
",",
"e",
":=",
"json",
".",
"Marshal",
"(",
"s",
")",
"\n",
"fatalIf",
"(",
"probe",
".",
"NewError",
"(",
"e",
")",
",",
"\"Unable to marshal into JSO... | // JSON jsonified remove bucket message. | [
"JSON",
"jsonified",
"remove",
"bucket",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/rb-main.go#L87-L92 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.